Repository navigation
Expand file tree
/
Copy pathsetup_wizard.py
More file actions
2405 lines (2096 loc) · 95.5 KB
/
Copy pathsetup_wizard.py
File metadata and controls
2405 lines (2096 loc) · 95.5 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,
InkboxPluginConfig,
VoiceStack,
inkbox_base_url_kwargs,
inkbox_client_kwargs,
public_call_ws_url,
resolve_voice_stack,
)
except ImportError: # pragma: no cover - direct local import/test fallback
from config import (
INKBOX_BASE_URL_DEFAULT,
InkboxPluginConfig,
VoiceStack,
inkbox_base_url_kwargs,
inkbox_client_kwargs,
public_call_ws_url,
resolve_voice_stack,
)
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.7.11"
INKBOX_REQUIREMENTS = (
f"inkbox>={INKBOX_MIN_VERSION},<1.0.0", "aiohttp>=3.9", "segno>=1.5",
"audioop-lts>=0.2.1; python_version >= '3.13'",
)
_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"
VOICE_STACK_CHOICES = [
(
VoiceStack.INKBOX_VOICE_AI,
"Inkbox Voice AI — Inkbox handles calls on behalf of your agent; "
"Hermes is notified when the call ends.",
),
(
VoiceStack.OPENAI_REALTIME,
"OpenAI Realtime API — Bring your own API key; the realtime agent can "
"consult Hermes for complex tasks.",
),
(
VoiceStack.INKBOX_TTS_STT,
"Inkbox TTS/STT — Hermes talks through the Inkbox voice stack with "
"increased latency.",
),
]
# A restart drains in-flight agent runs before coming back up, so give it more
# room than the CLI's own 90s service-restart timeout.
GATEWAY_COMMAND_TIMEOUT = 180
# A gateway only becomes visible to the CLI once it has taken its runtime lock
# and written its PID record, which happens partway through its own startup.
GATEWAY_START_CONFIRM_TIMEOUT = 15.0
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_enter_to_continue(message: str) -> None:
if not _is_interactive_stdin():
return
try:
input(color(f"{message}... ", Colors.YELLOW))
except (KeyboardInterrupt, EOFError):
print()
raise SystemExit(1)
def prompt_choice(
question: str,
choices: list[str],
default: int = 0,
*,
description: str | None = None,
) -> int:
try:
from hermes_cli.curses_ui import curses_radiolist
except Exception:
curses_radiolist = None
if curses_radiolist is not None:
selected = curses_radiolist(
question,
choices,
selected=default,
cancel_returns=default,
description=description,
)
print()
return selected
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:
if sys.platform == "win32":
return "; ".join(
"& " + " ".join("'" + arg.replace("'", "''") + "'" for arg in command)
for command in _install_commands()[0]
)
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 _voice_stack_default_index(detected_realtime_key: str) -> int:
stack, _ = resolve_voice_stack(
_env("INKBOX_VOICE_STACK"),
realtime_enabled=_env("INKBOX_REALTIME_ENABLED") or None,
realtime_api_key=detected_realtime_key,
)
return next(
(index for index, (candidate, _) in enumerate(VOICE_STACK_CHOICES) if candidate is stack),
2,
)
def _setup_call_ws_url(identity: Any) -> str:
cfg = InkboxPluginConfig(
identity=str(getattr(identity, "agent_handle", "") or "").strip(),
public_url=_env("INKBOX_PUBLIC_URL").strip(),
tunnel_name=_env("INKBOX_TUNNEL_NAME").strip(),
)
return public_call_ws_url(cfg, identity)
def _incoming_call_values(config: Any) -> dict[str, Any]:
return {
"incoming_call_action": _enum_value(getattr(config, "incoming_call_action", "")),
"client_websocket_url": getattr(config, "client_websocket_url", None),
"incoming_call_webhook_url": getattr(config, "incoming_call_webhook_url", None),
}
def _set_local_incoming_call_action(identity: Any) -> None:
setter = getattr(identity, "set_incoming_call_action", None)
if not callable(setter):
raise RuntimeError("The installed Inkbox SDK cannot configure identity-scoped incoming calls.")
ws_url = _setup_call_ws_url(identity)
if not ws_url:
raise RuntimeError("Could not resolve the public call WebSocket URL.")
setter(
incoming_call_action="auto_accept",
client_websocket_url=ws_url,
incoming_call_webhook_url=None,
)
def _load_admin_identity(
identity: Any,
*,
base_url: str,
Inkbox: Any,
InkboxAPIError: Any,
WhoamiApiKeyResponse: Any,
ADMIN_SCOPED: Any,
) -> Any | None:
admin_key = prompt(
" Paste an admin-scoped Inkbox API key for this authority change",
password=True,
).strip()
if not admin_key:
print_warning(" No admin-scoped key entered. Returning to the voice-stack choices.")
return None
try:
client = Inkbox(**inkbox_client_kwargs(admin_key, base_url))
info = client.whoami()
if WhoamiApiKeyResponse is not None and not isinstance(info, WhoamiApiKeyResponse):
print_error(" This authority change requires an admin-scoped API key.")
return None
if _enum_value(getattr(info, "auth_subtype", "")) != _enum_value(ADMIN_SCOPED):
print_error(" This authority change requires an admin-scoped API key.")
return None
return client.get_identity(identity.agent_handle)
except InkboxAPIError as exc:
print_error(f" Admin key validation failed: HTTP {_error_status(exc)} {_error_detail(exc)}")
except Exception as exc:
print_error(f" Admin key validation failed: {exc}")
return None
def _restore_voice_ai_config(
identity: Any,
*,
incoming_before: Any,
hosted_before: Any,
authority_before: str,
authority_identity: Any | None,
incoming_changed: bool,
authority_changed: bool,
hosted_changed: bool,
) -> None:
failures: list[str] = []
if incoming_changed:
try:
identity.set_incoming_call_action(**_incoming_call_values(incoming_before))
except Exception as exc:
failures.append(f"incoming-call action ({exc})")
if authority_changed and authority_identity is not None:
try:
authority_identity.set_hosted_agent_authority_mode(authority_before)
except Exception as exc:
failures.append(f"authority mode ({exc})")
if hosted_changed:
try:
identity.set_hosted_agent_config(
voice=getattr(hosted_before, "voice", None),
model=getattr(hosted_before, "model", None),
instructions=getattr(hosted_before, "instructions", None),
)
except Exception as exc:
failures.append(f"Voice AI config ({exc})")
if failures:
print_warning(" Could not fully restore the prior call configuration:")
for failure in failures:
print_warning(f" {failure}")
def _configure_voice_ai(
identity: Any,
*,
base_url: str,
Inkbox: Any,
InkboxAPIError: Any,
WhoamiApiKeyResponse: Any,
ADMIN_SCOPED: Any,
authority_identity: Any | None,
) -> tuple[bool, Any | None, str]:
required_methods = (
"get_hosted_agent_config",
"set_hosted_agent_config",
"get_incoming_call_action",
"set_incoming_call_action",
)
if any(not callable(getattr(identity, method, None)) for method in required_methods):
print_error(" Inkbox Voice AI setup requires a newer Inkbox SDK.")
print_info(" Upgrade the plugin environment, then rerun setup.")
return False, authority_identity, ""
try:
hosted_before = identity.get_hosted_agent_config()
incoming_before = identity.get_incoming_call_action()
except Exception as exc:
print_error(f" Could not read the current phone-call configuration: {exc}")
return False, authority_identity, ""
authority_before = _enum_value(
getattr(hosted_before, "authority_mode", "contact_scoped")
) or "contact_scoped"
authority_default = 1 if authority_before == "yolo" else 0
authority_index = prompt_choice(
" How much authority should Inkbox Voice AI have?",
[
"Contact-scoped — tools are limited to the current caller and conversation.",
"YOLO mode — tools can use the identity's wider authorized capabilities.",
],
authority_default,
)
authority_mode = "yolo" if authority_index == 1 else "contact_scoped"
selected_authority_identity = authority_identity
if authority_mode != authority_before:
if selected_authority_identity is None:
selected_authority_identity = _load_admin_identity(
identity,
base_url=base_url,
Inkbox=Inkbox,
InkboxAPIError=InkboxAPIError,
WhoamiApiKeyResponse=WhoamiApiKeyResponse,
ADMIN_SCOPED=ADMIN_SCOPED,
)
if selected_authority_identity is None:
return False, authority_identity, ""
if not callable(
getattr(selected_authority_identity, "set_hosted_agent_authority_mode", None)
):
print_error(" The installed Inkbox SDK cannot update Voice AI authority.")
return False, authority_identity, ""
hosted_changed = False
authority_changed = False
incoming_changed = False
try:
hosted_changed = True
identity.set_hosted_agent_config(voice=None, model=None, instructions=None)
if authority_mode != authority_before:
authority_changed = True
selected_authority_identity.set_hosted_agent_authority_mode(authority_mode)
incoming_changed = True
identity.set_incoming_call_action(
incoming_call_action="hosted_agent",
client_websocket_url=None,
incoming_call_webhook_url=None,
)
except Exception as exc:
print_error(f" Inkbox Voice AI configuration failed: {exc}")
_restore_voice_ai_config(
identity,
incoming_before=incoming_before,
hosted_before=hosted_before,
authority_before=authority_before,
authority_identity=selected_authority_identity,
incoming_changed=incoming_changed,
authority_changed=authority_changed,
hosted_changed=hosted_changed,
)
print_info(" The previous local voice-stack selection remains active.")
return False, selected_authority_identity, ""
return True, selected_authority_identity, authority_mode
def _save_voice_stack(
stack: VoiceStack,
*,
realtime_api_key: str = "",
authority_mode: str = "",
) -> None:
if stack is VoiceStack.OPENAI_REALTIME:
_save("INKBOX_REALTIME_API_KEY", realtime_api_key)
_save("INKBOX_REALTIME_MODEL", OPENAI_REALTIME_TEST_MODEL)
_save("INKBOX_REALTIME_ENABLED", "true")
else:
if authority_mode:
_save("INKBOX_VOICE_AI_AUTHORITY_MODE", authority_mode)
_save("INKBOX_REALTIME_ENABLED", "false")
_save("INKBOX_VOICE_STACK", stack.value)
def _configure_phone_call_voice_stack(
identity: Any,
*,
base_url: str,
Inkbox: Any,
InkboxAPIError: Any,
WhoamiApiKeyResponse: Any,
ADMIN_SCOPED: Any,
imessage_enabled: bool = False,
authority_identity: Any | None = None,
) -> None:
phone = getattr(identity, "phone_number", None)
if phone is None and not imessage_enabled:
return
prompt_enter_to_continue(" Press Enter to continue and set up phone call handling")
print()
print(color(" --- Phone call voice stack ---", Colors.CYAN))
detected = _detect_openai_realtime_key()
detected_key = detected[1] if detected is not None else ""
default_index = _voice_stack_default_index(detected_key)
prompt_for_realtime_key = False
while True:
selected_index = prompt_choice(
" Choose how this agent should handle phone calls:",
[description for _, description in VOICE_STACK_CHOICES],
default_index,
)
stack = VOICE_STACK_CHOICES[selected_index][0]
default_index = selected_index
if stack is VoiceStack.INKBOX_VOICE_AI:
ok, authority_identity, authority_mode = _configure_voice_ai(
identity,
base_url=base_url,
Inkbox=Inkbox,
InkboxAPIError=InkboxAPIError,
WhoamiApiKeyResponse=WhoamiApiKeyResponse,
ADMIN_SCOPED=ADMIN_SCOPED,
authority_identity=authority_identity,
)
if not ok:
continue
_save_voice_stack(stack, authority_mode=authority_mode)
print_success(" Inkbox Voice AI is configured for phone calls.")
print_info(" Hermes will be notified when each call ends.")
return
if stack is VoiceStack.OPENAI_REALTIME:
if prompt_for_realtime_key or not detected_key:
realtime_api_key = prompt(
" Paste your OpenAI API key for Realtime calls",
password=True,
).strip()
else:
realtime_api_key = detected_key
if detected is not None:
print_success(
f" Found existing OpenAI API key in {_redact_key_source(detected[0])}."
)
if not realtime_api_key:
print_warning(" No OpenAI API key entered. Returning to the voice-stack choices.")
prompt_for_realtime_key = True
continue
print_info(f" Testing OpenAI Realtime access with {OPENAI_REALTIME_TEST_MODEL}...")
ok, detail = _test_openai_realtime_api_key(
realtime_api_key,
OPENAI_REALTIME_TEST_MODEL,
)
if not ok:
print_error(" OpenAI Realtime validation failed.")
print_info(f" {detail}")
print_info(" Choose a voice stack again. Realtime was not enabled.")
detected_key = ""
prompt_for_realtime_key = True
continue
try:
_set_local_incoming_call_action(identity)
except Exception as exc:
print_error(f" Could not configure incoming Realtime calls: {exc}")
print_info(" Choose a voice stack again. Realtime was not enabled.")
detected_key = realtime_api_key
prompt_for_realtime_key = False
continue
_save_voice_stack(stack, realtime_api_key=realtime_api_key)
print_success(" OpenAI Realtime validation succeeded.")
print_info(" OpenAI Realtime API is configured for phone calls.")
return
try:
_set_local_incoming_call_action(identity)
except Exception as exc:
print_error(f" Could not configure incoming Inkbox TTS/STT calls: {exc}")
print_info(" Choose a voice stack again. The previous selection remains active.")
continue
_save_voice_stack(stack)
print_success(" Inkbox TTS/STT is configured for phone calls.")
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)