forked from inkbox-ai/hermes-agent-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_wizard.py
More file actions
1542 lines (1317 loc) · 59.3 KB
/
Copy pathsetup_wizard.py
File metadata and controls
1542 lines (1317 loc) · 59.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Interactive setup wizard for the Inkbox Hermes plugin."""
from __future__ import annotations
import asyncio
import getpass
import importlib
import importlib.metadata
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
from urllib.parse import quote, urlencode
try:
from .config import INKBOX_BASE_URL_DEFAULT, inkbox_base_url_kwargs, inkbox_client_kwargs
except ImportError: # pragma: no cover - direct local import/test fallback
from config import INKBOX_BASE_URL_DEFAULT, inkbox_base_url_kwargs, inkbox_client_kwargs
try:
from hermes_cli.colors import Colors, color
except Exception: # pragma: no cover - local tests without Hermes
class Colors:
CYAN = ""
DIM = ""
GREEN = ""
RED = ""
YELLOW = ""
BOLD = ""
def color(text: str, *_args: Any) -> str:
return text
try:
from hermes_cli.cli_output import print_error, print_info, print_success, print_warning
except Exception: # pragma: no cover - local tests without Hermes
def print_error(message: str) -> None:
print(message)
def print_info(message: str) -> None:
print(message)
def print_success(message: str) -> None:
print(message)
def print_warning(message: str) -> None:
print(message)
try:
from hermes_cli.secret_prompt import masked_secret_prompt
except Exception: # pragma: no cover - local tests without Hermes
masked_secret_prompt = None
INKBOX_MIN_VERSION = "0.4.15"
INKBOX_REQUIREMENTS = (f"inkbox>={INKBOX_MIN_VERSION},<1.0.0", "aiohttp>=3.9", "segno>=1.5")
_BRACKETED_PASTE_PATTERN = re.compile(r"\x1b\[\s*200~|\x1b\[\s*201~")
_AVATAR_PATH = Path(__file__).resolve().parent / "assets" / "hermes_with_iphone.png"
_RAW_AVATAR_BASE_URL_DEFAULT = "https://inkbox.ai"
OPENAI_REALTIME_TEST_MODEL = "gpt-realtime-2"
OPENAI_REALTIME_TEST_URL = "wss://api.openai.com/v1/realtime"
def print_header(title: str) -> None:
print()
print(color(f"* {title}", Colors.CYAN, Colors.BOLD))
def _show_qr(data: str) -> bool:
stdout = getattr(sys, "stdout", None)
if stdout is not None and hasattr(stdout, "isatty") and not stdout.isatty():
return False
try:
import segno
except ImportError:
return False
try:
segno.make(data).terminal(compact=True)
return True
except Exception:
return False
def _sanitize_pasted_input(value: str) -> str:
if not isinstance(value, str) or not value:
return value
return _BRACKETED_PASTE_PATTERN.sub("", value)
def _is_interactive_stdin() -> bool:
stdin = getattr(sys, "stdin", None)
if stdin is None:
return False
try:
return bool(stdin.isatty())
except Exception:
return False
def prompt(question: str, default: str | None = None, *, password: bool = False) -> str:
display = f"{question} [{default}]: " if default else f"{question}: "
try:
if password:
if masked_secret_prompt is not None:
value = masked_secret_prompt(color(display, Colors.YELLOW))
else:
value = getpass.getpass(display)
else:
value = input(color(display, Colors.YELLOW))
except (KeyboardInterrupt, EOFError):
print()
raise SystemExit(1)
cleaned = _sanitize_pasted_input(value)
return cleaned.strip() or default or ""
def prompt_yes_no(question: str, default: bool = True) -> bool:
default_word = "yes" if default else "no"
while True:
try:
value = input(color(f"{question} [y/n] (default: {default_word}): ", Colors.YELLOW)).strip().lower()
except (KeyboardInterrupt, EOFError):
print()
raise SystemExit(1)
if not value:
return default
if value in {"y", "yes"}:
return True
if value in {"n", "no"}:
return False
print_error("Please enter 'y' or 'n'.")
def prompt_choice(
question: str,
choices: list[str],
default: int = 0,
*,
description: str | None = None,
) -> int:
print(color(question, Colors.YELLOW))
if description:
for line in description.splitlines():
print_info(f" {line}")
for idx, choice in enumerate(choices, start=1):
marker = "*" if idx - 1 == default else " "
print(f" {marker} {idx}. {choice}")
while True:
try:
value = input(color(f" Select [1-{len(choices)}] ({default + 1}): ", Colors.DIM)).strip()
except (KeyboardInterrupt, EOFError):
print()
raise SystemExit(1)
if not value:
return default
try:
selected = int(value) - 1
except ValueError:
print_error("Please enter a number.")
continue
if 0 <= selected < len(choices):
return selected
print_error(f"Please enter a number between 1 and {len(choices)}.")
def _save(name: str, value: str) -> None:
if value == "":
return
from hermes_cli.config import save_env_value
save_env_value(name, value)
def _env(name: str) -> str:
try:
from hermes_cli.config import get_env_value
return os.getenv(name) or get_env_value(name) or ""
except Exception:
return os.getenv(name, "")
def _config_realtime_api_key() -> str:
try:
from hermes_cli.config import load_config
cfg = load_config() or {}
except Exception:
return ""
platforms = cfg.get("platforms") if isinstance(cfg, dict) else {}
inkbox = platforms.get("inkbox") if isinstance(platforms, dict) else {}
realtime = inkbox.get("realtime") if isinstance(inkbox, dict) else {}
api_key = realtime.get("api_key") if isinstance(realtime, dict) else ""
return str(api_key or "").strip()
def _hermes_openai_api_key() -> tuple[str, str] | None:
try:
from hermes_cli.auth import has_usable_secret, resolve_api_key_provider_credentials
creds = resolve_api_key_provider_credentials("openai-api")
except Exception:
return None
api_key = str(creds.get("api_key") or "").strip()
if not api_key or not has_usable_secret(api_key):
return None
source = str(creds.get("source") or "openai-api").strip() or "openai-api"
return source, api_key
def _detect_openai_realtime_key() -> tuple[str, str] | None:
config_key = _config_realtime_api_key()
if config_key:
return "platforms.inkbox.realtime.api_key", config_key
realtime_key = _env("INKBOX_REALTIME_API_KEY").strip()
if realtime_key:
return "INKBOX_REALTIME_API_KEY", realtime_key
hermes_key = _hermes_openai_api_key()
if hermes_key is not None:
return hermes_key
openai_key = _env("OPENAI_API_KEY").strip()
if openai_key:
return "OPENAI_API_KEY", openai_key
return None
def _install_commands() -> list[list[list[str]]]:
plans: list[list[list[str]]] = []
uv = shutil.which("uv")
if uv:
plans.append([[uv, "pip", "install", "--python", sys.executable, *INKBOX_REQUIREMENTS]])
plans.append([[sys.executable, "-m", "pip", "install", *INKBOX_REQUIREMENTS]])
plans.append(
[
[sys.executable, "-m", "ensurepip", "--upgrade"],
[sys.executable, "-m", "pip", "install", *INKBOX_REQUIREMENTS],
]
)
return plans
def _install_command_text() -> str:
return " && ".join(shlex.join(command) for command in _install_commands()[0])
def _run_install_plan() -> bool:
last_exc: Exception | None = None
for plan in _install_commands():
try:
for command in plan:
subprocess.check_call(command)
return True
except Exception as exc:
last_exc = exc
if last_exc is not None:
print_error(f"Install failed: {last_exc}")
return False
def _purge_inkbox_modules() -> None:
for name in list(sys.modules):
if name == "inkbox" or name.startswith("inkbox."):
sys.modules.pop(name, None)
def _load_inkbox_symbols() -> dict[str, Any]:
from inkbox import Inkbox
from inkbox.exceptions import InkboxAPIError
from inkbox.identities.types import IdentityPhoneNumberCreateOptions
from inkbox.whoami.types import (
AUTH_SUBTYPE_API_KEY_ADMIN_SCOPED,
AUTH_SUBTYPE_API_KEY_AGENT_SCOPED_CLAIMED,
AUTH_SUBTYPE_API_KEY_AGENT_SCOPED_UNCLAIMED,
WhoamiApiKeyResponse,
)
return {
"Inkbox": Inkbox,
"InkboxAPIError": InkboxAPIError,
"IdentityPhoneNumberCreateOptions": IdentityPhoneNumberCreateOptions,
"WhoamiApiKeyResponse": WhoamiApiKeyResponse,
"ADMIN_SCOPED": AUTH_SUBTYPE_API_KEY_ADMIN_SCOPED,
"AGENT_CLAIMED": AUTH_SUBTYPE_API_KEY_AGENT_SCOPED_CLAIMED,
"AGENT_UNCLAIMED": AUTH_SUBTYPE_API_KEY_AGENT_SCOPED_UNCLAIMED,
}
def _parse_version(value: str) -> tuple[int, ...]:
# Best-effort numeric parse of "X.Y.Z" so we can compare without packaging.
parts: list[int] = []
for chunk in value.split("."):
digits = ""
for char in chunk:
if char.isdigit():
digits += char
else:
break
if digits == "":
break
parts.append(int(digits))
return tuple(parts)
def _inkbox_version_ok() -> bool:
try:
installed = importlib.metadata.version("inkbox")
except Exception:
return False
try:
from packaging.version import Version
return Version(installed) >= Version(INKBOX_MIN_VERSION)
except Exception:
# Fall back to a simple parsed-tuple comparison when packaging is unavailable.
return _parse_version(installed) >= _parse_version(INKBOX_MIN_VERSION)
def _ensure_inkbox_sdk() -> dict[str, Any] | None:
try:
symbols = _load_inkbox_symbols()
if _inkbox_version_ok():
return symbols
first_error = (
f"inkbox SDK is older than {INKBOX_MIN_VERSION}; an upgrade is required."
)
except Exception as exc:
first_error = exc
print_warning("The Python Inkbox SDK is not available in the Hermes environment.")
print_info("The setup command is running under:")
print_info(f" {sys.executable}")
print_info("Install or upgrade the SDK in that exact environment with:")
print_info(f" {_install_command_text()}")
print_info(f"Import error: {first_error}")
if not _is_interactive_stdin():
return None
if not prompt_yes_no("Install/upgrade Inkbox SDK in this Hermes environment now?", True):
return None
if not _run_install_plan():
print_info("Run this command manually, then rerun setup:")
print_info(f" {_install_command_text()}")
return None
importlib.invalidate_caches()
_purge_inkbox_modules()
try:
return _load_inkbox_symbols()
except Exception as retry_exc:
print_error(f"Inkbox SDK still cannot be imported: {retry_exc}")
print_info("Run this command manually, then rerun setup:")
print_info(f" {_install_command_text()}")
return None
def _error_status(exc: Exception) -> Any:
return getattr(exc, "status_code", "?")
def _error_detail(exc: Exception) -> str:
return str(getattr(exc, "detail", "") or exc)
def _enum_value(value: Any) -> str:
raw = getattr(value, "value", value)
return str(raw or "")
def _seed_identity_state(identity: Any) -> None:
try:
from hermes_cli.config import get_hermes_home
mailbox = getattr(identity, "mailbox", None)
phone = getattr(identity, "phone_number", None)
tunnel = getattr(identity, "tunnel", None)
state = {
"handle": getattr(identity, "agent_handle", None),
"email_address": (
getattr(identity, "email_address", None)
or (getattr(mailbox, "email_address", None) if mailbox else None)
),
"phone_number": getattr(phone, "number", None) if phone else None,
"phone_number_id": str(getattr(phone, "id", "")) if phone else None,
"imessage_enabled": bool(getattr(identity, "imessage_enabled", False)),
"tunnel_public_host": getattr(tunnel, "public_host", None) if tunnel else None,
}
path = Path(get_hermes_home()) / "inkbox_identity_state.json"
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(state, indent=2) + "\n")
os.replace(tmp, path)
except Exception as exc:
print_warning(f" Could not seed inkbox_identity_state.json: {exc}")
print_info(" Start the gateway and it will populate the file on connect.")
def _redact_key_source(name: str) -> str:
if name == "platforms.inkbox.realtime.api_key":
return "platforms.inkbox.realtime.api_key"
if name == "INKBOX_REALTIME_API_KEY":
return "INKBOX_REALTIME_API_KEY"
if name == "OPENAI_API_KEY":
return "OPENAI_API_KEY"
if name == "credential_pool:openai-api":
return "Hermes credential pool (openai-api)"
if name == "openai-api":
return "Hermes OpenAI API credentials"
return "the configured OpenAI API key"
async def _test_openai_realtime_api_key_async(api_key: str, model: str) -> tuple[bool, str]:
try:
import aiohttp
except Exception as exc:
return False, f"aiohttp is not available in this Hermes environment: {exc}"
url = f"{OPENAI_REALTIME_TEST_URL}?{urlencode({'model': model})}"
headers = {"Authorization": f"Bearer {api_key}"}
timeout = aiohttp.ClientTimeout(total=12)
session_update = {
"type": "session.update",
"session": {
"type": "realtime",
"model": model,
"instructions": "Validation probe. Do not speak unless audio is provided.",
"output_modalities": ["audio"],
"audio": {
"input": {
"format": {"type": "audio/pcmu"},
"noise_reduction": None,
"transcription": {"model": "gpt-4o-mini-transcribe"},
"turn_detection": {
"type": "server_vad",
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500,
"create_response": True,
"interrupt_response": True,
},
},
"output": {
"format": {"type": "audio/pcmu"},
"voice": "cedar",
},
},
},
}
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.ws_connect(url, headers=headers, heartbeat=10) as ws:
await ws.send_str(json.dumps(session_update))
loop = asyncio.get_running_loop()
deadline = loop.time() + 8.0
saw_session_created = False
while True:
remaining = deadline - loop.time()
if remaining <= 0:
if saw_session_created:
return True, "OpenAI Realtime websocket accepted the key."
return False, "Timed out waiting for an OpenAI Realtime session response."
msg = await asyncio.wait_for(ws.receive(), timeout=remaining)
if msg.type == aiohttp.WSMsgType.TEXT:
try:
event = json.loads(msg.data)
except Exception:
continue
event_type = str(event.get("type") or "")
if event_type == "session.updated":
return True, "OpenAI Realtime session update succeeded."
if event_type == "session.created":
saw_session_created = True
continue
if event_type == "error":
error = event.get("error") if isinstance(event.get("error"), dict) else event
message = str(error.get("message") or event).strip()
code = str(error.get("code") or "").strip()
prefix = f"{code}: " if code else ""
return False, f"{prefix}{message}"
if msg.type in {aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR}:
detail = str(getattr(ws, "exception", lambda: None)() or "websocket closed")
return False, detail
except aiohttp.WSServerHandshakeError as exc:
if exc.status in {401, 403}:
return False, f"OpenAI rejected the key or Realtime permission: HTTP {exc.status}"
return False, f"OpenAI Realtime websocket handshake failed: HTTP {exc.status} {exc.message}"
except asyncio.TimeoutError:
return False, "Timed out connecting to OpenAI Realtime."
except Exception as exc:
return False, str(exc)
def _test_openai_realtime_api_key(api_key: str, model: str = OPENAI_REALTIME_TEST_MODEL) -> tuple[bool, str]:
try:
return asyncio.run(_test_openai_realtime_api_key_async(api_key, model))
except RuntimeError as exc:
return False, f"Could not run Realtime validation from this setup process: {exc}"
def _configure_realtime_calls(identity: Any, *, imessage_enabled: bool = False) -> None:
# Calls can arrive over the dedicated number OR the shared iMessage line,
# so offer realtime whenever either exists.
phone = getattr(identity, "phone_number", None)
if phone is None and not imessage_enabled:
return
print()
print(color(" --- OpenAI Realtime calls ---", Colors.CYAN))
print_info(" Realtime calls send raw phone audio to OpenAI Realtime.")
print_info(" This requires an OpenAI API key with /v1/realtime permission.")
detected = _detect_openai_realtime_key()
detected_key = ""
default_opt_in = False
prompt_for_key = False
if detected is not None:
key_source, detected_key = detected
default_opt_in = True
print_success(f" Found existing OpenAI API key in {_redact_key_source(key_source)}.")
else:
print_warning(" No OpenAI API key was detected for Realtime.")
print_info(" If you opt in, paste an OpenAI API key in the next step.")
print_info(" The wizard will test the key before enabling Realtime calls.")
while True:
if not prompt_yes_no(" Use OpenAI Realtime API for phone calls?", default_opt_in):
_save("INKBOX_REALTIME_ENABLED", "false")
print_info(" Realtime disabled. Calls will use Inkbox STT/TTS.")
return
if prompt_for_key or not detected_key:
api_key = prompt(" Paste your OpenAI API key for Realtime calls", password=True).strip()
else:
api_key = detected_key
if not api_key:
_save("INKBOX_REALTIME_ENABLED", "false")
print_warning(" No OpenAI API key entered. Realtime disabled; calls will use Inkbox STT/TTS.")
return
print_info(f" Testing OpenAI Realtime access with {OPENAI_REALTIME_TEST_MODEL}...")
ok, detail = _test_openai_realtime_api_key(api_key, OPENAI_REALTIME_TEST_MODEL)
if not ok:
_save("INKBOX_REALTIME_ENABLED", "false")
print_error(" OpenAI Realtime validation failed.")
print_info(f" {detail}")
print_info(" Realtime remains disabled. Try another key, or answer no to use Inkbox STT/TTS.")
default_opt_in = True
prompt_for_key = True
continue
_save("INKBOX_REALTIME_ENABLED", "true")
_save("INKBOX_REALTIME_MODEL", OPENAI_REALTIME_TEST_MODEL)
# Persist the exact validated key under the plugin-specific env var so the
# gateway does not depend on the operator's shell exporting OPENAI_API_KEY.
_save("INKBOX_REALTIME_API_KEY", api_key)
print_success(" OpenAI Realtime validation succeeded.")
print_info(" Realtime calls are enabled for this Hermes Inkbox gateway.")
return
def _setup_signing_key(api_key: str, base_url: str, Inkbox: Any) -> None:
print()
print(color(" --- Webhook signing key ---", Colors.CYAN))
print_info(" Inkbox signs outbound webhooks with an HMAC over the body.")
print_info(" Without the matching key, the gateway cannot verify inbound Inkbox traffic.")
print_info(" A signing key is required to continue.")
has_key = prompt_yes_no(" Do you already have an Inkbox signing key?", False)
if has_key:
key = prompt(" Paste your Inkbox signing key", password=True).strip()
if key:
_save("INKBOX_SIGNING_KEY", key)
_save("INKBOX_REQUIRE_SIGNATURE", "true")
print_success(" Saved signing key. Signature verification enabled.")
return
# An empty paste can't satisfy the requirement — fall through to mint one.
print_warning(" No key entered; a signing key is required, so we'll mint one now.")
print_info(" Minting a new key here rotates any existing key for your org.")
print_info(" Any other gateway using the old key will fail verification until updated.")
if not prompt_yes_no(" Generate a new signing key now?", True):
print_error(" A signing key is required; cannot complete setup without one.")
print_info(" Re-run setup and paste an existing key, or allow key generation.")
raise SystemExit(1)
try:
new_key = Inkbox(**inkbox_client_kwargs(api_key, base_url)).create_signing_key()
except Exception as exc:
print_error(f" Failed to create signing key: {exc}")
print_error(" A signing key is required; aborting setup. Retry, or paste an existing key.")
raise SystemExit(1)
signing_key = str(getattr(new_key, "signing_key", "") or "")
if not signing_key:
print_error(" Signing-key response did not include signing_key.")
print_error(" A signing key is required; aborting setup.")
raise SystemExit(1)
_save("INKBOX_SIGNING_KEY", signing_key)
_save("INKBOX_REQUIRE_SIGNATURE", "true")
created_at = getattr(new_key, "created_at", None)
if created_at is not None and hasattr(created_at, "isoformat"):
print_success(f" Generated and saved signing key (created at {created_at.isoformat()}).")
else:
print_success(" Generated and saved signing key.")
print_info(" Signature verification enabled.")
def _wait_for_sms_opt_in(api_key: str, base_url: str, phone: Any, Inkbox: Any) -> None:
if phone is None or getattr(phone, "type", None) != "local":
return
phone_id = getattr(phone, "id", None)
if phone_id is None:
return
def find_start(texts: Any) -> Any | None:
for text in texts:
direction = (getattr(text, "direction", "") or "").lower()
body = (getattr(text, "text", "") or "").strip().upper()
if direction == "inbound" and body == "START":
return text
return None
try:
client = Inkbox(**inkbox_client_kwargs(api_key, base_url))
except Exception:
return
print()
print(color(" --- Waiting for your START text ---", Colors.YELLOW))
print_info(f" Polling every 3s for an inbound START to {phone.number}.")
print_info(" Without it, the agent cannot send outbound SMS to that phone later.")
print_info(" Press Ctrl+C to skip; you can text START anytime.")
spinner = "|/-\\"
idx = 0
next_poll_at = time.monotonic()
clear_line = "\r" + " " * 72 + "\r"
try:
while True:
now = time.monotonic()
if now >= next_poll_at:
try:
texts = client.texts.list(phone_id, limit=20)
except Exception:
texts = []
match = find_start(texts)
if match is not None:
remote = getattr(match, "remote_phone_number", "")
sys.stdout.write(clear_line)
sys.stdout.flush()
print_success(f" Got it. SMS opt-in confirmed from {remote}")
return
next_poll_at = now + 3.0
sys.stdout.write(f"\r {spinner[idx]} Listening for START... ")
sys.stdout.flush()
idx = (idx + 1) % len(spinner)
time.sleep(0.25)
except KeyboardInterrupt:
sys.stdout.write(clear_line)
sys.stdout.flush()
print()
print_warning(f" Skipped. Text START to {phone.number} anytime to enable outbound SMS.")
def _avatar_base_url(base_url: str) -> str:
return (base_url or _RAW_AVATAR_BASE_URL_DEFAULT).rstrip("/")
async def _identity_has_avatar_async(base_url: str, api_key: str, handle: str) -> bool | None:
"""Check whether an identity already has a contact-card avatar."""
import aiohttp
url = f"{_avatar_base_url(base_url)}/api/v1/identities/{handle}/avatar"
timeout = aiohttp.ClientTimeout(total=10)
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url, headers={"X-API-Key": api_key}) as resp:
if resp.status == 200:
return True
if resp.status == 404:
return False
return None
except Exception:
return None
async def _upload_avatar_async(
base_url: str, api_key: str, handle: str, image: bytes
) -> tuple[bool, str]:
"""PUT the Hermes avatar image to the identity's avatar endpoint."""
import aiohttp
url = f"{_avatar_base_url(base_url)}/api/v1/identities/{handle}/avatar"
timeout = aiohttp.ClientTimeout(total=30)
form = aiohttp.FormData()
form.add_field("file", image, filename="hermes_with_iphone.png", content_type="image/png")
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.put(url, headers={"X-API-Key": api_key}, data=form) as resp:
if resp.status in (200, 201):
return True, "ok"
return False, f"HTTP {resp.status} {(await resp.text())[:200]}"
except Exception as exc:
return False, str(exc)
def _identity_has_avatar(base_url: str, api_key: str, handle: str) -> bool | None:
try:
return asyncio.run(_identity_has_avatar_async(base_url, api_key, handle))
except RuntimeError:
return None
def _upload_avatar(base_url: str, api_key: str, handle: str, image: bytes) -> tuple[bool, str]:
try:
return asyncio.run(_upload_avatar_async(base_url, api_key, handle, image))
except RuntimeError as exc:
return False, f"could not run avatar upload from this setup process: {exc}"
def _configure_avatar(base_url: str, api_key: str, identity: Any, *, is_signup: bool) -> None:
"""Attach the bundled Hermes avatar to the agent's Inkbox contact card."""
handle = getattr(identity, "agent_handle", "") or ""
if not handle or not _AVATAR_PATH.exists():
return
if not is_signup:
if _identity_has_avatar(base_url, api_key, handle) is True:
return
print()
print(color(" --- Agent avatar ---", Colors.CYAN))
print_info(" This agent has no avatar on its Inkbox contact card.")
if not prompt_yes_no(" Add the Hermes avatar?", True):
print_info(" Skipped. You can set an avatar later in the Inkbox console.")
return
try:
image = _AVATAR_PATH.read_bytes()
except Exception as exc:
print_warning(f" Could not read the bundled avatar: {exc}")
return
ok, detail = _upload_avatar(base_url, api_key, handle, image)
if ok:
print_success(" Attached the Hermes avatar to this agent.")
else:
print_warning(f" Could not attach the avatar: {detail}")
print_info(" You can set one later in the Inkbox console.")
def _configure_imessage(api_key: str, base_url: str, handle: str, Inkbox: Any) -> bool:
"""Offer to enable iMessage for the agent and walk through connecting.
Args:
api_key (str): The agent-scoped Inkbox API key the wizard saved.
base_url (str): Inkbox API base URL.
handle (str): Agent identity handle being configured.
Inkbox (Any): The Inkbox SDK client class.
Returns:
bool: True when iMessage ended up enabled (newly or already), so the
caller can gate iMessage-dependent steps like realtime calling.
"""
print()
print(color(" --- iMessage ---", Colors.CYAN))
print_info(" Inkbox can make this agent reachable over iMessage from your iPhone.")
print_info(" No number to provision — you connect through the Inkbox iMessage router.")
print_info(" Once connected, the agent can also make and take voice calls with you")
print_info(" over that same shared iMessage line.")
try:
client = Inkbox(**inkbox_client_kwargs(api_key, base_url))
identity = client.get_identity(handle)
except Exception as exc:
print_warning(f" Could not load the identity for iMessage setup: {exc}")
return False
# Old SDKs predate iMessage entirely — detect by surface, not version.
if not hasattr(client, "imessages") or not hasattr(identity, "imessage_enabled"):
print_warning(" The installed Inkbox SDK does not support iMessage yet.")
print_info(" Upgrade it and rerun setup:")
print_info(f" {_install_command_text()}")
return False
if identity.imessage_enabled:
print_success(" iMessage is already enabled for this agent.")
else:
if not prompt_yes_no(" Enable iMessage for this agent?", True):
print_info(" Skipped. Rerun `hermes inkbox setup` anytime to enable iMessage.")
return False
try:
identity.update(imessage_enabled=True)
except Exception as exc:
print_error(f" Could not enable iMessage: {exc}")
print_info(" You can enable it later from the Inkbox console and rerun setup.")
return False
print_success(" iMessage enabled for this agent.")
try:
# Re-fetch so the local object reflects the new flag (the SDK
# gates its iMessage helpers on it).
identity = client.get_identity(handle)
except Exception as exc:
print_warning(f" Could not refresh the identity after enabling: {exc}")
return True
# Surface phones already connected through the router so reruns don't
# read like a first-time setup, and default the walkthrough off when a
# connection already exists (connecting another phone is the rare case).
connected = []
list_assignments = getattr(identity, "list_imessage_assignments", None)
if callable(list_assignments):
try:
connected = list(list_assignments(limit=5))
except Exception:
connected = []
if connected:
numbers = ", ".join(
str(getattr(a, "remote_number", "") or "") for a in connected
)
print_success(f" Already connected: {numbers}")
question = (
" Connect another iPhone to this agent now?"
if connected
else " Connect your iPhone to this agent now?"
)
if not prompt_yes_no(question, not connected):
print_info(" You can connect anytime — rerun `hermes inkbox setup` for the walkthrough.")
return True
_wait_for_imessage_first_message(client, identity, handle)
return True
def _wait_for_imessage_first_message(client: Any, identity: Any, handle: str) -> None:
"""Walk the user through the iMessage connect flow and greet them back.
Args:
client (Any): Authenticated Inkbox SDK client (agent-scoped key).
identity (Any): The iMessage-enabled agent identity object.
handle (str): Agent identity handle, used in the welcome message.
Returns:
None: Polls until the first inbound iMessage arrives (Ctrl+C skips),
then sends the channel-introduction reply into that conversation.
"""
from datetime import datetime, timezone
try:
triage = client.imessages.get_triage_number()
except Exception as exc:
print_warning(f" Could not fetch the iMessage router number: {exc}")
print_info(" Rerun `hermes inkbox setup` later to finish connecting.")
return
connect_command = str(getattr(triage, "connect_command", "") or "").strip()
if not connect_command or "your-handle" in connect_command:
connect_command = f"connect @{handle}"
print()
print_info(" From your iPhone, in the Messages app:")
print(color(f" 1. Text \"{connect_command}\" to {triage.number}", Colors.BOLD))
print_info(" 2. Inkbox texts you back from the number now assigned to this agent.")
print_info(" 3. Send any first message (e.g. \"hi\") in that NEW thread.")
print_info(" The agent can only message you after you message it first.")
sms_link = str(getattr(triage, "sms_link", "") or "").strip()
if not sms_link or "your-handle" in sms_link:
sms_link = f"sms:{triage.number}?&body={quote(connect_command)}"
qr_payload = f"SMSTO:{triage.number}:{connect_command}"
print()
print_info(" Or just scan this with your iPhone camera to do step 1 in one tap:")
print()
if not _show_qr(qr_payload):
print_info(f" (install 'segno' to show a scannable QR here: {sms_link})")
print()
print(color(" --- Waiting for your first iMessage ---", Colors.YELLOW))
print_info(" Polling every 3s for an inbound iMessage to this agent.")
print_info(" Press Ctrl+C to skip; you can connect anytime.")
started_at = datetime.now(timezone.utc)
def find_first_inbound(messages: Any) -> Any | None:
for message in messages:
direction = (_enum_value(getattr(message, "direction", "")) or "").lower()
if direction != "inbound":
continue
created_at = getattr(message, "created_at", None)
# Ignore traffic from a connection that predates this run.
# Naive timestamps can't be compared to the aware cutoff —
# accept those rather than crash the poll loop.
if (
created_at is not None
and created_at.tzinfo is not None
and created_at < started_at
):
continue
return message
return None
spinner = "|/-\\"
idx = 0
next_poll_at = time.monotonic()
clear_line = "\r" + " " * 72 + "\r"
match = None
try:
while match is None:
now = time.monotonic()
if now >= next_poll_at:
try:
messages = identity.list_imessages(limit=10)
except Exception:
messages = []
match = find_first_inbound(messages)
next_poll_at = now + 3.0
if match is None:
sys.stdout.write(f"\r {spinner[idx]} Listening for your first iMessage... ")
sys.stdout.flush()
idx = (idx + 1) % len(spinner)
time.sleep(0.25)
except KeyboardInterrupt:
sys.stdout.write(clear_line)
sys.stdout.flush()
print()
print_warning(" Skipped. The agent replies over iMessage once you connect and message it.")
return
sys.stdout.write(clear_line)
sys.stdout.flush()
remote = getattr(match, "remote_number", "") or "your phone"
print_success(f" Got it. First iMessage received from {remote}.")
conversation_id = getattr(match, "conversation_id", None)
welcome = (
f"You're connected! This is your iMessage channel to your Hermes agent "
f"@{handle}. Anything you send here goes straight to the agent, and its "
f"replies will show up right in this thread."
)
try:
identity.send_imessage(conversation_id=conversation_id, text=welcome)
print_success(" Sent a welcome message back on that thread.")
except Exception as exc:
print_warning(f" Could not send the welcome message: {exc}")
try:
# Clear the unread flag the walkthrough message left behind.
identity.mark_imessage_conversation_read(conversation_id)
except Exception:
pass
print_info(" Start the gateway (`hermes gateway run`) and keep chatting there.")
print_info(" If the gateway is already running, restart it (`hermes gateway restart`)")
print_info(" so it picks up this new iMessage connection.")
def _self_signup_flow(base_url: str, Inkbox: Any, InkboxAPIError: Any) -> tuple[Any | None, str, bool]:
print()
print_info("No problem. We will create a fresh agent identity for you.")
print_info("You will get an Inkbox-hosted mailbox plus an API key.")
print_info("A short verification email goes to you to claim full capabilities.")
print()
note = "Setting up a Hermes agent on Inkbox."
human_email = ""
handle = ""
while True:
if not human_email:
human_email = prompt(" Your email address (for the verification step)").strip()
if not human_email or "@" not in human_email:
print_error(" A valid email address is required for signup.")
return None, "", False
if not handle:
handle = prompt(
" Desired agent handle (e.g. on-call-agent, recruiting-agent) - "
"globally unique, also becomes the mailbox local part"
).strip()
if not handle:
print_error(" Agent handle is required.")
return None, "", False
print()
print_info("Calling agent-signup...")
try:
resp = Inkbox.signup(
human_email=human_email,
note_to_human=note,
agent_handle=handle,