-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.py
More file actions
1736 lines (1429 loc) · 65.2 KB
/
cli.py
File metadata and controls
1736 lines (1429 loc) · 65.2 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
#!/usr/bin/env python3
"""
Haldir CLI — command-line interface for the Haldir agent governance API.
Manage sessions, secrets, payments, audit, and proxy from the terminal.
Usage:
python3 cli.py <command> <subcommand> [options]
haldir <command> <subcommand> [options] # if installed via pip
Examples:
haldir login
haldir session create --agent my-bot --scopes read,browse --budget 50
haldir secret store STRIPE_KEY sk_live_xxx
haldir audit trail --agent my-bot --limit 20
"""
from __future__ import annotations
import argparse
import getpass
import json
import os
import sys
import time
from pathlib import Path
from typing import Any
import httpx
# ── Config ──
CONFIG_DIR = Path.home() / ".haldir"
CONFIG_FILE = CONFIG_DIR / "config.json"
DEFAULT_BASE_URL = "https://haldir.xyz"
def load_config() -> dict:
"""Load config from ~/.haldir/config.json, return empty dict if missing."""
if CONFIG_FILE.exists():
try:
return json.loads(CONFIG_FILE.read_text())
except (json.JSONDecodeError, OSError):
return {}
return {}
def save_config(config: dict) -> None:
"""Write config to ~/.haldir/config.json, creating the directory if needed."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_FILE.write_text(json.dumps(config, indent=2) + "\n")
# Restrict permissions — config contains the API key
CONFIG_FILE.chmod(0o600)
def get_api_key() -> str:
"""Resolve API key from env var, then config file."""
key = os.environ.get("HALDIR_API_KEY", "")
if key:
return key
config = load_config()
return config.get("api_key", "")
def get_base_url() -> str:
"""Resolve base URL from env var, then config file, then default."""
url = os.environ.get("HALDIR_BASE_URL", "")
if url:
return url.rstrip("/")
config = load_config()
return config.get("base_url", DEFAULT_BASE_URL).rstrip("/")
# ── Terminal colors ──
class Color:
"""ANSI color codes. Disabled when stdout is not a TTY."""
_enabled = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
RESET = "\033[0m" if _enabled else ""
BOLD = "\033[1m" if _enabled else ""
DIM = "\033[2m" if _enabled else ""
GREEN = "\033[32m" if _enabled else ""
RED = "\033[31m" if _enabled else ""
YELLOW = "\033[33m" if _enabled else ""
CYAN = "\033[36m" if _enabled else ""
MAGENTA = "\033[35m" if _enabled else ""
WHITE = "\033[97m" if _enabled else ""
def success(msg: str) -> None:
print(f"{Color.GREEN}{Color.BOLD}[+]{Color.RESET} {msg}")
def error(msg: str) -> None:
print(f"{Color.RED}{Color.BOLD}[-]{Color.RESET} {msg}", file=sys.stderr)
def warn(msg: str) -> None:
print(f"{Color.YELLOW}{Color.BOLD}[!]{Color.RESET} {msg}")
def info(msg: str) -> None:
print(f"{Color.CYAN}[*]{Color.RESET} {msg}")
def mono(value: str) -> str:
"""Wrap a value in bold white for monospace emphasis."""
return f"{Color.WHITE}{Color.BOLD}{value}{Color.RESET}"
def label(key: str, value: Any) -> None:
"""Print a key-value pair with dim key and bold value."""
print(f" {Color.DIM}{key}:{Color.RESET} {Color.WHITE}{value}{Color.RESET}")
def print_json_table(data: dict, indent: int = 2) -> None:
"""Print a dict as a clean labeled table."""
prefix = " " * indent
for k, v in data.items():
if isinstance(v, dict):
print(f"{prefix}{Color.DIM}{k}:{Color.RESET}")
print_json_table(v, indent + 2)
elif isinstance(v, list):
print(f"{prefix}{Color.DIM}{k}:{Color.RESET} {Color.WHITE}{', '.join(str(i) for i in v) if v else '(none)'}{Color.RESET}")
elif isinstance(v, bool):
color = Color.GREEN if v else Color.RED
print(f"{prefix}{Color.DIM}{k}:{Color.RESET} {color}{v}{Color.RESET}")
elif isinstance(v, float):
print(f"{prefix}{Color.DIM}{k}:{Color.RESET} {Color.WHITE}{v:.2f}{Color.RESET}")
else:
print(f"{prefix}{Color.DIM}{k}:{Color.RESET} {Color.WHITE}{v}{Color.RESET}")
# ── HTTP client ──
class APIClient:
"""Thin wrapper around httpx for Haldir API calls."""
def __init__(self, api_key: str = "", base_url: str = ""):
self.api_key = api_key or get_api_key()
self.base_url = base_url or get_base_url()
def _headers(self) -> dict:
h = {"Content-Type": "application/json"}
if self.api_key:
h["Authorization"] = f"Bearer {self.api_key}"
return h
def request(self, method: str, path: str, **kwargs: Any) -> dict:
"""Make a request, return parsed JSON. Exits on error."""
url = f"{self.base_url}{path}"
try:
resp = httpx.request(
method, url,
headers=self._headers(),
timeout=30.0,
**kwargs,
)
except httpx.ConnectError:
error(f"Cannot connect to {self.base_url}")
error("Is the Haldir server running? Check your base_url config.")
sys.exit(1)
except httpx.TimeoutException:
error(f"Request timed out: {method} {path}")
sys.exit(1)
try:
body = resp.json()
except Exception:
body = {"raw": resp.text}
if resp.status_code >= 400:
msg = body.get("error") or body.get("reason") or resp.text
if resp.status_code == 401:
error(f"Authentication failed: {msg}")
warn("Run 'haldir login' to set your API key.")
elif resp.status_code == 403:
error(f"Permission denied: {msg}")
elif resp.status_code == 404:
error(f"Not found: {msg}")
elif resp.status_code == 429:
error(f"Rate limited: {msg}")
retry = body.get("retry_after")
if retry:
warn(f"Retry after {retry}s")
else:
error(f"API error ({resp.status_code}): {msg}")
sys.exit(1)
return body
def get(self, path: str, **kwargs: Any) -> dict:
return self.request("GET", path, **kwargs)
def post(self, path: str, **kwargs: Any) -> dict:
return self.request("POST", path, **kwargs)
def delete(self, path: str, **kwargs: Any) -> dict:
return self.request("DELETE", path, **kwargs)
# ── Commands ──
def cmd_login(args: argparse.Namespace) -> None:
"""Prompt for API key and save to config."""
config = load_config()
print(f"{Color.BOLD}Haldir Login{Color.RESET}")
print()
if args.key:
api_key = args.key
else:
api_key = getpass.getpass("API key (hld_...): ").strip()
if not api_key:
error("No API key provided.")
sys.exit(1)
if not api_key.startswith("hld_"):
warn("Key does not start with 'hld_' — are you sure this is correct?")
# Optionally set base URL
base_url = args.url or config.get("base_url", DEFAULT_BASE_URL)
# Verify the key works
info(f"Verifying key against {base_url}...")
client = APIClient(api_key=api_key, base_url=base_url)
try:
result = client.get("/v1/usage")
tier = result.get("tier", "unknown")
success(f"Authenticated! Tier: {mono(tier)}")
except SystemExit:
error("Key verification failed. Saving anyway in case the server is down.")
config["api_key"] = api_key
config["base_url"] = base_url
save_config(config)
success(f"Config saved to {mono(str(CONFIG_FILE))}")
def cmd_keys_list(args: argparse.Namespace) -> None:
"""List API keys registered against the authed tenant."""
client = APIClient()
r = client.get("/v1/keys")
keys = r.get("keys", [])
if getattr(args, "json", False):
print(json.dumps(keys, indent=2))
return
if not keys:
info("no keys registered")
return
print()
print(f" {Color.DIM}{'prefix':<14} {'name':<22} {'tier':<7} {'scopes':<28} {'last used':<19} state{Color.RESET}")
for k in keys:
last = (
time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(k["last_used"])))
if k.get("last_used") else "never"
)
state = (
f"{Color.RED}revoked{Color.RESET}" if k["revoked"]
else f"{Color.GREEN}active{Color.RESET}"
)
scopes = ",".join(k.get("scopes", ["*"]))[:28]
print(f" {Color.WHITE}{k['prefix']:<14}{Color.RESET} "
f"{k['name']:<22} {k['tier']:<7} "
f"{Color.DIM}{scopes:<28}{Color.RESET} "
f"{last:<19} {state}")
print()
def cmd_keys_revoke(args: argparse.Namespace) -> None:
"""Revoke a key by its 12-char prefix."""
client = APIClient()
url = f"{client.base_url}/v1/keys/{args.prefix}"
if not args.yes:
# Confirm interactively unless --yes — leaked-key panic still
# benefits from a 2-second pause.
sys.stderr.write(
f"About to revoke key prefix {args.prefix!r}. Continue? [y/N] "
)
sys.stderr.flush()
if input().strip().lower() not in ("y", "yes"):
warn("aborted")
sys.exit(1)
r = httpx.delete(url, headers=client._headers(), timeout=10.0)
if r.status_code == 200:
success(f"revoked {args.prefix}")
elif r.status_code == 404:
error("no active key with that prefix in this tenant")
sys.exit(1)
else:
error(f"revoke failed: HTTP {r.status_code} — {r.text}")
sys.exit(1)
def cmd_keys_create(args: argparse.Namespace) -> None:
"""Create a new API key with optional per-key scopes."""
client = APIClient()
payload: dict[str, Any] = {"name": args.name}
if args.tier:
payload["tier"] = args.tier
if args.scopes:
# Comma-separated for ergonomics; the API accepts both list
# and string form (haldir_scopes.parse() normalizes either).
payload["scopes"] = [s.strip() for s in args.scopes.split(",") if s.strip()]
result = client.post("/v1/keys", json=payload)
success("API key created")
print()
label("Key", result["key"])
label("Prefix", result.get("prefix", ""))
label("Name", result.get("name", ""))
label("Tier", result.get("tier", ""))
if result.get("scopes"):
label("Scopes", ", ".join(result["scopes"]))
print()
warn("Save this key now — it will not be shown again.")
# ── Session commands ──
def cmd_session_create(args: argparse.Namespace) -> None:
"""Create an agent session."""
client = APIClient()
payload: dict[str, Any] = {"agent_id": args.agent}
if args.scopes:
payload["scopes"] = [s.strip() for s in args.scopes.split(",")]
if args.ttl:
payload["ttl"] = args.ttl
if args.budget is not None:
payload["spend_limit"] = args.budget
result = client.post("/v1/sessions", json=payload)
success("Session created")
print()
label("Session ID", result["session_id"])
label("Agent", result["agent_id"])
label("Scopes", ", ".join(result.get("scopes", [])))
label("Spend Limit", result.get("spend_limit") or "unlimited")
label("TTL", f"{result.get('ttl', 3600)}s")
expires = result.get("expires_at")
if expires:
label("Expires", time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(expires)))
def cmd_session_get(args: argparse.Namespace) -> None:
"""Get session details."""
client = APIClient()
result = client.get(f"/v1/sessions/{args.session_id}")
valid = result.get("is_valid", False)
status_color = Color.GREEN if valid else Color.RED
status_text = "ACTIVE" if valid else "EXPIRED/REVOKED"
print(f"{Color.BOLD}Session{Color.RESET} {mono(result['session_id'])}")
print(f" {Color.DIM}Status:{Color.RESET} {status_color}{Color.BOLD}{status_text}{Color.RESET}")
label("Agent", result["agent_id"])
label("Scopes", ", ".join(result.get("scopes", [])))
label("Spend Limit", result.get("spend_limit") or "unlimited")
label("Spent", f"${result.get('spent', 0):.2f}")
remaining = result.get("remaining_budget")
if remaining is not None:
label("Remaining", f"${remaining:.2f}")
expires = result.get("expires_at")
if expires:
label("Expires", time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(expires)))
def cmd_session_revoke(args: argparse.Namespace) -> None:
"""Revoke a session."""
client = APIClient()
client.delete(f"/v1/sessions/{args.session_id}")
success(f"Session {mono(args.session_id)} revoked")
def cmd_session_check(args: argparse.Namespace) -> None:
"""Check if a session has a specific permission."""
client = APIClient()
result = client.post(
f"/v1/sessions/{args.session_id}/check",
json={"scope": args.scope},
)
allowed = result.get("allowed", False)
if allowed:
success(f"Session has {mono(args.scope)} permission")
else:
error(f"Session does NOT have {mono(args.scope)} permission")
# ── Secret commands ──
def cmd_secret_store(args: argparse.Namespace) -> None:
"""Store a secret in the vault."""
client = APIClient()
payload: dict[str, Any] = {"name": args.name, "value": args.value}
if args.scope:
payload["scope_required"] = args.scope
client.post("/v1/secrets", json=payload)
success(f"Secret {mono(args.name)} stored")
def cmd_secret_get(args: argparse.Namespace) -> None:
"""Retrieve a secret from the vault."""
client = APIClient()
headers = {}
if args.session:
headers["X-Session-ID"] = args.session
result = client.request("GET", f"/v1/secrets/{args.name}", headers=headers)
print(f"{Color.BOLD}Secret{Color.RESET} {mono(result['name'])}")
label("Value", result["value"])
def cmd_secret_list(args: argparse.Namespace) -> None:
"""List all secrets in the vault."""
client = APIClient()
result = client.get("/v1/secrets")
secrets_list = result.get("secrets", [])
count = result.get("count", len(secrets_list))
info(f"{count} secret(s) in vault")
if secrets_list:
print()
for name in secrets_list:
print(f" {Color.MAGENTA}*{Color.RESET} {mono(name)}")
def cmd_secret_delete(args: argparse.Namespace) -> None:
"""Delete a secret from the vault."""
client = APIClient()
client.delete(f"/v1/secrets/{args.name}")
success(f"Secret {mono(args.name)} deleted")
# ── Payment commands ──
def cmd_pay_authorize(args: argparse.Namespace) -> None:
"""Authorize a payment against a session's budget."""
client = APIClient()
payload: dict[str, Any] = {
"session_id": args.session_id,
"amount": args.amount,
}
if args.currency:
payload["currency"] = args.currency
if args.description:
payload["description"] = args.description
result = client.post("/v1/payments/authorize", json=payload)
authorized = result.get("authorized", False)
if authorized:
success(f"Payment of ${args.amount:.2f} authorized")
remaining = result.get("remaining_budget")
if remaining is not None:
label("Remaining Budget", f"${remaining:.2f}")
else:
error(f"Payment of ${args.amount:.2f} denied")
reason = result.get("reason", "")
if reason:
label("Reason", reason)
# ── Audit commands ──
def cmd_audit_log(args: argparse.Namespace) -> None:
"""Log an auditable action."""
client = APIClient()
payload: dict[str, Any] = {
"session_id": args.session_id,
"action": args.action,
}
if args.tool:
payload["tool"] = args.tool
if args.cost is not None:
payload["cost_usd"] = args.cost
if args.details:
try:
payload["details"] = json.loads(args.details)
except json.JSONDecodeError:
error("--details must be valid JSON")
sys.exit(1)
result = client.post("/v1/audit", json=payload)
success(f"Action logged: {mono(result.get('entry_id', 'ok'))}")
if result.get("flagged"):
warn(f"FLAGGED: {result.get('flag_reason', 'anomaly detected')}")
def cmd_audit_trail(args: argparse.Namespace) -> None:
"""Query the audit trail."""
client = APIClient()
params: dict[str, Any] = {}
if args.session:
params["session_id"] = args.session
if args.agent:
params["agent_id"] = args.agent
if args.tool:
params["tool"] = args.tool
if args.flagged:
params["flagged"] = "true"
if args.limit:
params["limit"] = args.limit
result = client.get("/v1/audit", params=params)
entries = result.get("entries", [])
count = result.get("count", len(entries))
info(f"{count} audit entries")
print()
if not entries:
print(f" {Color.DIM}(no entries){Color.RESET}")
return
for entry in entries:
ts = entry.get("timestamp", 0)
ts_str = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ts)) if ts else "?"
flagged = entry.get("flagged", False)
flag_marker = f" {Color.RED}FLAGGED{Color.RESET}" if flagged else ""
tool_str = entry.get("tool", "")
action_str = entry.get("action", "")
cost = entry.get("cost_usd", 0)
print(f" {Color.DIM}{ts_str}{Color.RESET} "
f"{mono(entry.get('entry_id', '')[:12])} "
f"{Color.CYAN}{entry.get('agent_id', '')}{Color.RESET} "
f"{tool_str}:{action_str}"
f"{f' ${cost:.2f}' if cost else ''}"
f"{flag_marker}")
def cmd_audit_spend(args: argparse.Namespace) -> None:
"""Get spend summary."""
client = APIClient()
params: dict[str, Any] = {}
if args.session:
params["session_id"] = args.session
if args.agent:
params["agent_id"] = args.agent
result = client.get("/v1/audit/spend", params=params)
total = result.get("total_usd", 0)
print(f"{Color.BOLD}Spend Summary{Color.RESET}")
print()
label("Total", f"${total:.2f}")
by_tool = result.get("by_tool", {})
if by_tool:
print()
print(f" {Color.DIM}By tool:{Color.RESET}")
for tool, amount in by_tool.items():
print(f" {Color.MAGENTA}{tool}{Color.RESET}: ${amount:.2f}")
# ── Proxy commands ──
def cmd_proxy_register(args: argparse.Namespace) -> None:
"""Register an upstream MCP server."""
client = APIClient()
result = client.post("/v1/proxy/upstreams", json={
"name": args.name,
"url": args.url,
})
healthy = result.get("healthy", False)
tools_count = result.get("tools_discovered", 0)
if healthy:
success(f"Upstream {mono(args.name)} registered ({tools_count} tools discovered)")
else:
warn(f"Upstream {mono(args.name)} registered but is NOT healthy")
err = result.get("error")
if err:
error(f" {err}")
tool_names = result.get("tool_names", [])
if tool_names:
print()
info("Discovered tools:")
for name in tool_names:
print(f" {Color.MAGENTA}*{Color.RESET} {mono(name)}")
def cmd_proxy_tools(args: argparse.Namespace) -> None:
"""List all tools available through the proxy."""
client = APIClient()
result = client.get("/v1/proxy/tools")
tools = result.get("tools", [])
count = result.get("count", len(tools))
info(f"{count} tool(s) available")
print()
if not tools:
print(f" {Color.DIM}(no tools — register an upstream first){Color.RESET}")
return
for tool in tools:
upstream = tool.get("upstream", "")
desc = tool.get("description", "")
print(f" {Color.MAGENTA}*{Color.RESET} {mono(tool['name'])}"
f"{Color.DIM} ({upstream}){Color.RESET}"
f"{f' — {desc[:60]}' if desc else ''}")
def cmd_proxy_call(args: argparse.Namespace) -> None:
"""Call a tool through the Haldir proxy."""
client = APIClient()
arguments = {}
if args.args:
try:
arguments = json.loads(args.args)
except json.JSONDecodeError:
error("--args must be valid JSON")
sys.exit(1)
result = client.post("/v1/proxy/call", json={
"tool": args.tool,
"arguments": arguments,
"session_id": args.session,
})
is_error = result.get("isError", False)
content = result.get("content", [])
if is_error:
error("Tool call blocked or failed")
for item in content:
text = item.get("text", "")
try:
parsed = json.loads(text)
if "error" in parsed:
error(f" {parsed['error']}")
else:
print(json.dumps(parsed, indent=2))
except json.JSONDecodeError:
print(f" {text}")
else:
success("Tool call succeeded")
for item in content:
text = item.get("text", "")
try:
parsed = json.loads(text)
print(json.dumps(parsed, indent=2))
except json.JSONDecodeError:
print(text)
def cmd_proxy_policy_add(args: argparse.Namespace) -> None:
"""Add a governance policy to the proxy."""
client = APIClient()
payload: dict[str, Any] = {"type": args.type}
if args.tool:
payload["tool"] = args.tool
if args.tools:
payload["tools"] = [t.strip() for t in args.tools.split(",")]
if args.max is not None:
payload["max"] = args.max
if args.max_per_minute is not None:
payload["max_per_minute"] = args.max_per_minute
if args.start_hour is not None:
payload["start_hour"] = args.start_hour
if args.end_hour is not None:
payload["end_hour"] = args.end_hour
client.post("/v1/proxy/policies", json=payload)
success(f"Policy {mono(args.type)} added")
# ── Metrics ──
def cmd_metrics(args: argparse.Namespace) -> None:
"""Show platform metrics."""
client = APIClient()
result = client.get("/v1/metrics")
print(f"{Color.BOLD}Haldir Metrics{Color.RESET}")
print()
print_json_table(result)
# ── Overview / status / ready (the screenshot moments) ──────────────
def _state_pill(state: str) -> str:
"""Render an inline status pill: ● with color matching the state."""
color = {
"ok": Color.GREEN,
"ready": Color.GREEN,
"alive": Color.GREEN,
"degraded": Color.YELLOW,
"down": Color.RED,
}.get(state, Color.DIM)
return f"{color}●{Color.RESET} {state}"
def _bar(pct: float, width: int = 20) -> str:
"""Inline progress bar — 20 cells, color shifts as you approach 1.0."""
pct = max(0.0, min(1.0, pct))
filled = int(round(pct * width))
color = (
Color.GREEN if pct < 0.7 else
Color.YELLOW if pct < 0.9 else
Color.RED
)
return f"{color}{'█' * filled}{Color.DIM}{'░' * (width - filled)}{Color.RESET}"
def _render_overview(o: dict) -> None:
"""Pretty-print the /v1/admin/overview payload. The screenshot
moment for the README + tweets — every value is laid out in the
visual hierarchy a reader would scan top-down."""
print()
print(f" {Color.BOLD}Haldir tenant overview{Color.RESET}")
print(f" {Color.DIM}{o.get('tenant_id', '?')} · tier "
f"{Color.WHITE}{o.get('tier', '?')}{Color.RESET}{Color.DIM} · "
f"{o.get('generated_at', '')}{Color.RESET}")
h = o.get("health", {})
print()
print(f" {Color.DIM}Status{Color.RESET} {_state_pill(h.get('status', 'ok'))}")
u = o.get("usage", {})
pct = float(u.get("actions_pct_used", 0.0))
print(f" {Color.DIM}Actions{Color.RESET} {Color.WHITE}{u.get('actions_this_month', 0):>7,}{Color.RESET}"
f" {Color.DIM}/{Color.RESET} {u.get('actions_limit', 0):,}"
f" {_bar(pct)} {Color.DIM}{pct * 100:5.1f}%{Color.RESET}")
print(f" {Color.DIM}Spend{Color.RESET} {Color.WHITE}${u.get('spend_usd_this_month', 0.0):>6.2f}{Color.RESET}"
f" {Color.DIM}this month{Color.RESET}")
s = o.get("sessions", {})
print(f" {Color.DIM}Sessions{Color.RESET} {Color.WHITE}{s.get('active_count', 0):>7}{Color.RESET}"
f" {Color.DIM}active · {s.get('agents_active', 0)}/"
f"{s.get('agents_limit', 0)} agents{Color.RESET}")
v = o.get("vault", {})
print(f" {Color.DIM}Vault{Color.RESET} {Color.WHITE}{v.get('secrets_count', 0):>7}{Color.RESET}"
f" {Color.DIM}secrets · {v.get('secret_access_count', 0)} accesses this month{Color.RESET}")
a = o.get("audit", {})
chain = "✓" if a.get("chain_verified") else "✗"
chain_color = Color.GREEN if a.get("chain_verified") else Color.RED
print(f" {Color.DIM}Audit{Color.RESET} {Color.WHITE}{a.get('total_entries', 0):>7,}{Color.RESET}"
f" {Color.DIM}entries · {a.get('flagged_7d', 0)} flagged (7d) · "
f"chain {chain_color}{chain}{Color.RESET}")
w = o.get("webhooks", {})
rate = float(w.get("delivery_success_rate_24h", 1.0))
rate_color = Color.GREEN if rate >= 0.99 else (Color.YELLOW if rate >= 0.95 else Color.RED)
print(f" {Color.DIM}Webhooks{Color.RESET} {Color.WHITE}{w.get('registered_count', 0):>7}{Color.RESET}"
f" {Color.DIM}registered · {w.get('deliveries_24h', 0)} deliveries (24h) · "
f"{rate_color}{rate * 100:.2f}%{Color.RESET}{Color.DIM} success{Color.RESET}")
ap = o.get("approvals", {})
pending = ap.get("pending_count", 0)
pending_color = Color.YELLOW if pending else Color.DIM
print(f" {Color.DIM}Approvals{Color.RESET} {pending_color}{pending:>7}{Color.RESET}"
f" {Color.DIM}pending{Color.RESET}")
c = o.get("compliance", {})
next_due = c.get("next_due_at") or "—"
sched_color = Color.GREEN if c.get("active_count") else Color.DIM
print(f" {Color.DIM}Compliance{Color.RESET} {sched_color}{c.get('active_count', 0):>7}{Color.RESET}"
f" {Color.DIM}schedules · next pack {next_due}{Color.RESET}")
print()
def cmd_overview(args: argparse.Namespace) -> None:
"""Single-call tenant dashboard (calls /v1/admin/overview)."""
client = APIClient()
def _once() -> None:
o = client.get("/v1/admin/overview")
if getattr(args, "json", False):
print(json.dumps(o, indent=2))
else:
_render_overview(o)
if not getattr(args, "watch", False):
_once()
return
# Live-refresh mode: redraw every interval seconds, top-style.
interval = max(1.0, float(args.interval or 5.0))
try:
while True:
sys.stdout.write("\033[2J\033[H") # clear + home
_once()
sys.stdout.write(f" {Color.DIM}refreshing every {interval:.0f}s — Ctrl+C to exit{Color.RESET}\n")
sys.stdout.flush()
time.sleep(interval)
except KeyboardInterrupt:
print()
def cmd_status(args: argparse.Namespace) -> None:
"""System health (calls /v1/status)."""
client = APIClient()
s = client.get("/v1/status")
if getattr(args, "json", False):
print(json.dumps(s, indent=2))
return
print()
print(f" {Color.BOLD}Haldir status{Color.RESET} {_state_pill(s.get('status', 'ok'))}")
print()
for c in s.get("components", []):
print(f" {Color.DIM}{c['name']:10}{Color.RESET} {_state_pill(c['state'])}")
print(f" {Color.DIM}{c.get('message', '')}{Color.RESET}")
print()
m = s.get("metrics", {})
sr = m.get("success_rate", {})
lat = m.get("latency_seconds", {})
print(f" {Color.DIM}Success rate{Color.RESET} "
f"{Color.WHITE}{sr.get('ratio', 1.0) * 100:.3f}%{Color.RESET} "
f"{Color.DIM}({sr.get('total', 0)} requests){Color.RESET}")
if lat.get("p95"):
print(f" {Color.DIM}Latency p95{Color.RESET} "
f"{Color.WHITE}{lat['p95'] * 1000:.0f} ms{Color.RESET}"
f" {Color.DIM}p99 {lat.get('p99', 0) * 1000:.0f} ms{Color.RESET}")
print()
def cmd_ready(args: argparse.Namespace) -> None:
"""One-shot readiness check. Exits 0 if ready, 1 if not — useful
for CI / pre-deploy gates."""
client = APIClient()
try:
r = httpx.get(
f"{client.base_url}/readyz",
headers=client._headers(), timeout=5.0,
)
body = r.json()
except Exception as e:
error(f"Could not reach /readyz: {e}")
sys.exit(2)
if getattr(args, "json", False):
print(json.dumps(body, indent=2))
sys.exit(0 if body.get("ready") else 1)
if body.get("ready"):
success("ready")
else:
error("not ready")
for c in body.get("checks", []):
mark = f"{Color.GREEN}✓{Color.RESET}" if c["ok"] else f"{Color.RED}✗{Color.RESET}"
print(f" {mark} {c['name']:16} {Color.DIM}{c['message']} ({c['duration_ms']} ms){Color.RESET}")
sys.exit(0 if body.get("ready") else 1)
# ── Audit export + verify ────────────────────────────────────────────
def cmd_audit_export(args: argparse.Namespace) -> None:
"""Stream the audit trail to stdout (or --out FILE)."""
client = APIClient()
fmt = (args.format or "jsonl").lower()
if fmt not in ("csv", "jsonl"):
error(f"format must be csv or jsonl, got {fmt!r}")
sys.exit(2)
params: dict[str, str] = {"format": fmt}
if args.since:
params["since"] = args.since
if args.until:
params["until"] = args.until
if args.session:
params["session_id"] = args.session
if args.agent:
params["agent_id"] = args.agent
if args.tool:
params["tool"] = args.tool
url = f"{client.base_url}/v1/audit/export"
out = open(args.out, "w") if args.out else sys.stdout
try:
with httpx.stream("GET", url, params=params,
headers=client._headers(),
timeout=120.0) as r:
if r.status_code != 200:
error(f"export failed: HTTP {r.status_code}")
sys.exit(1)
for chunk in r.iter_text():
out.write(chunk)
if args.out:
success(f"wrote {args.out}")
finally:
if args.out:
out.close()
def cmd_audit_verify(args: argparse.Namespace) -> None:
"""Verify the hash chain integrity of the audit trail."""
client = APIClient()
r = client.get("/v1/audit/verify")
if getattr(args, "json", False):
print(json.dumps(r, indent=2))
return
verified = r.get("verified", False)
if verified:
success(f"chain verified — {r.get('entries_checked', 0)} entries")
else:
error(f"chain BROKEN at entry {r.get('first_break', '?')}")
sys.exit(1)
# ── Audit tree (RFC 6962 Merkle tamper-evidence) ────────────────────
def cmd_audit_tree_head(args: argparse.Namespace) -> None:
"""Fetch the current Signed Tree Head for the caller's audit log."""
client = APIClient()
sth = client.get("/v1/audit/tree-head")
if getattr(args, "json", False):
print(json.dumps(sth, indent=2))
return
success(f"STH tree_size={sth['tree_size']} algorithm={sth['algorithm']}")
print()
label("Root hash", sth["root_hash"] or "(empty tree)")
label("Signed at", sth.get("signed_at", ""))
label("Signature", sth.get("signature", "")[:48] + ("…" if sth.get("signature") else ""))
label("Key source", sth.get("signing_key_source", ""))
def cmd_audit_prove(args: argparse.Namespace) -> None:
"""Request an RFC 6962 inclusion proof for a specific audit entry.
Writes the full proof (with embedded STH) to stdout or --out as JSON
so it can be archived alongside a single audit row and verified
offline later."""
client = APIClient()
proof = client.get(f"/v1/audit/inclusion-proof/{args.entry_id}")
if args.out:
from pathlib import Path
Path(args.out).write_text(json.dumps(proof, indent=2))
success(f"inclusion proof for {args.entry_id} → {args.out}")
return
if getattr(args, "json", False):
print(json.dumps(proof, indent=2))
return
success(
f"entry {args.entry_id} is leaf #{proof['leaf_index']} "
f"of a {proof['tree_size']}-leaf tree"
)
print()
label("Leaf hash", proof["leaf_hash"])
label("Root hash", proof["root_hash"])
label("Path hops", len(proof["audit_path"]))
def cmd_audit_verify_proof(args: argparse.Namespace) -> None:
"""Verify an archived inclusion proof locally — no network calls.
Reads a proof JSON (as written by `haldir audit prove --out`) and
re-hashes up to the root. Exits 0 on success, 1 on mismatch. If
HALDIR_TREE_SIGNING_KEY (or HALDIR_ENCRYPTION_KEY) is set locally
AND matches the server's key, the STH signature is verified too."""
from pathlib import Path
import haldir_merkle as merkle
proof = json.loads(Path(args.proof).read_text())
ok_inc = merkle.verify_inclusion_hex(proof)
if not ok_inc:
error("inclusion proof does NOT verify against the embedded root")
sys.exit(1)
success("inclusion proof verifies — leaf hashes up to the signed root")
sth = proof.get("sth") or {}
key, source = merkle.load_signing_key_from_env()
sig_ok = merkle.verify_sth(sth, key) if sth.get("signature") else False
if sig_ok:
success(f"STH signature verifies (local key source: {source})")
else:
warn("STH signature NOT verified locally — either no key set "
"or key differs from server (proof body still valid).")
def cmd_audit_consistency(args: argparse.Namespace) -> None:
"""Fetch a consistency proof between two audit-tree sizes and verify
it locally (no trust in the server beyond the key you already hold)."""
import haldir_merkle as merkle
client = APIClient()
proof = client.get(
f"/v1/audit/consistency-proof?first={args.first}&second={args.second}"
)
if getattr(args, "json", False):
print(json.dumps(proof, indent=2))