-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1615 lines (1453 loc) · 64.1 KB
/
Copy pathcli.py
File metadata and controls
1615 lines (1453 loc) · 64.1 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
"""Console entry point for the pip-installable VIBAP proxy package."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shlex
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Sequence
import jwt
from . import __version__
from .ardur_profile import PROFILE_TEMPLATES, ArdurProfile, load_ardur_profile, write_profile_template
from .ardur_personal_native_host import (
build_native_host_manifest,
handle_native_host_message,
run_native_host,
)
from .passport import DEFAULT_HOME, MissionPassport, generate_keypair, issue_passport, load_mission_file, verify_passport
from .personal_hub import (
DEFAULT_HUB_HOST,
DEFAULT_HUB_PORT,
DEFAULT_HUB_URL,
desktop_observe,
doctor_personal,
hub_request,
run_under_hub,
serve_hub,
setup_personal,
status_response_with_next_steps,
uninstall_personal,
)
from .claude_code_report import build_claude_code_report
from .claude_code_hook import main as claude_code_hook_main
from .gemini_cli_hook import (
build_local_fixture as build_gemini_local_fixture,
build_shareable_context as build_gemini_shareable_context,
build_shareable_report as build_gemini_shareable_report,
main as gemini_cli_hook_main,
)
from .codex_app_server_fixture import (
build_local_fixture as build_codex_local_fixture,
build_shareable_context as build_codex_shareable_context,
build_shareable_report as build_codex_shareable_report,
handle_host_event as handle_codex_host_event,
)
from .posture_index import build_posture_index, format_posture_report
from .claude_code_daemon import install_native_pre_tool_use_command, resolve_native_pre_tool_use_command_path
from .proxy import GovernanceProxy, serve_proxy
def _print_json(payload: dict) -> None:
print(json.dumps(payload, indent=2))
def _print_report_next_steps(report: dict) -> None:
next_steps = report.get("next_steps") or []
if not next_steps:
return
print("Next steps:")
for index, step in enumerate(next_steps, start=1):
command = step.get("command", "")
detail = step.get("detail", "")
print(f"{index}. {command}")
if detail:
print(f" {detail}")
def cmd_start(args: argparse.Namespace) -> int:
private_key, public_key = generate_keypair(keys_dir=args.keys_dir)
proxy = GovernanceProxy(
log_path=args.log_path,
state_dir=args.state_dir,
keys_dir=args.keys_dir,
public_key=public_key,
)
initial_session_id = None
if args.mission:
mission, ttl_s, _ = load_mission_file(args.mission)
token = issue_passport(mission, private_key, ttl_s=ttl_s)
session = proxy.start_session(token)
initial_session_id = session.jti
_print_json(
{
"status": "session_started",
"mission_file": str(Path(args.mission).expanduser()),
"session_id": session.jti,
"agent_id": mission.agent_id,
"mission": mission.mission,
"token": token,
}
)
serve_proxy(
proxy=proxy,
private_key=private_key,
host=args.host,
port=args.port,
initial_session_id=initial_session_id,
require_auth=args.require_auth,
api_token=args.api_token,
tls_cert=args.tls_cert,
tls_key=args.tls_key,
no_tls=args.no_tls,
)
return 0
def cmd_issue(args: argparse.Namespace) -> int:
private_key, public_key = generate_keypair(keys_dir=args.keys_dir)
mission = MissionPassport(
agent_id=args.agent_id,
mission=args.mission,
allowed_tools=list(args.allowed_tools or []),
forbidden_tools=list(args.forbidden_tools or []),
resource_scope=list(args.resource_scope or []),
max_tool_calls=args.max_tool_calls,
max_duration_s=args.max_duration_s,
delegation_allowed=args.delegation_allowed,
max_delegation_depth=args.max_delegation_depth,
)
token = issue_passport(mission, private_key, ttl_s=args.ttl_s)
claims = verify_passport(token, public_key)
_print_json({"token": token, "claims": claims})
return 0
def _verify_failure_next_steps() -> list[dict[str, str]]:
return [
{
"condition": "invalid_passport_token",
"action": "verify_a_fresh_passport_token",
"command": "ardur verify --token <token> --keys-dir <keys-dir>",
"detail": (
"Use a Mission Passport JWT issued by this Ardur key directory. "
"Keep raw tokens out of shared logs and reports."
),
},
{
"condition": "invalid_passport_token",
"action": "issue_a_new_passport_if_needed",
"command": "ardur issue --agent-id <agent-id> --mission <mission> --keys-dir <keys-dir>",
"detail": "Issue a fresh local Mission Passport when the old token is malformed, expired, or signed by a different key.",
},
]
def _verify_failure_response(exc: Exception) -> dict:
detail = str(exc).strip() or exc.__class__.__name__
return {
"ok": False,
"valid": False,
"error": "invalid_passport_token",
"condition": "invalid_passport_token",
"message": "Mission Passport token could not be verified.",
"detail": detail,
"next_steps": _verify_failure_next_steps(),
}
def cmd_verify(args: argparse.Namespace) -> int:
_, public_key = generate_keypair(keys_dir=args.keys_dir)
try:
claims = verify_passport(args.token, public_key)
except (jwt.PyJWTError, PermissionError, ValueError) as exc:
_print_json(_verify_failure_response(exc))
return 1
_print_json({"valid": True, "claims": claims})
return 0
def _attest_failure_condition(exc: Exception) -> tuple[str, str]:
message = str(exc).lower()
if "invalid session id format" in message:
return (
"invalid_session_id",
"Session identifiers must be UUIDs produced by an Ardur governed session.",
)
if "unknown session" in message:
return (
"session_not_found",
"No persisted session was found for the supplied session id in the selected state directory.",
)
return (
"attestation_failed",
"The session could not be loaded or attested from the selected local state.",
)
def _attest_failure_next_steps(condition: str) -> list[dict[str, str]]:
steps = [
{
"condition": condition,
"action": "retry_with_recorded_session_id",
"command": "ardur attest --session <session-id> --keys-dir <keys-dir> --state-dir <state-dir> --log-path <audit-log>",
"detail": (
"Use the exact session_id emitted by the governed session and the same local state directory. "
"Do not paste raw tokens or local private paths into shared artifacts."
),
}
]
if condition in {"invalid_session_id", "session_not_found"}:
steps.append(
{
"condition": condition,
"action": "start_or_find_a_governed_session",
"command": "ardur start --mission <mission.json> --keys-dir <keys-dir> --state-dir <state-dir> --log-path <audit-log>",
"detail": "Start or locate the governed session first, then attest using its UUID session id.",
}
)
return steps
def _attest_failure_response(exc: Exception) -> dict:
condition, detail = _attest_failure_condition(exc)
return {
"ok": False,
"valid": False,
"error": condition,
"condition": condition,
"message": "Behavioral attestation could not be issued for the requested session.",
"detail": detail,
"next_steps": _attest_failure_next_steps(condition),
}
def cmd_attest(args: argparse.Namespace) -> int:
private_key, public_key = generate_keypair(keys_dir=args.keys_dir)
proxy = GovernanceProxy(
log_path=args.log_path,
state_dir=args.state_dir,
keys_dir=args.keys_dir,
public_key=public_key,
)
try:
token, claims = proxy.issue_attestation_for_session(args.session, private_key)
except (ValueError, PermissionError, jwt.PyJWTError) as exc:
_print_json(_attest_failure_response(exc))
return 1
_print_json({"token": token, "claims": claims})
return 0
def cmd_claude_code_hook(args: argparse.Namespace) -> int:
argv = [args.phase]
if args.keys_dir:
argv.extend(["--keys-dir", str(args.keys_dir)])
return claude_code_hook_main(argv)
def cmd_claude_code_report(args: argparse.Namespace) -> int:
report = build_claude_code_report(
home=args.home,
chain_dir=args.chain_dir,
keys_dir=args.keys_dir,
verify_expiry=args.verify_expiry,
)
if args.json:
_print_json(report)
return 0
print(f"Ardur Claude Code receipt report: {report['receipt_count']} receipts across {report['chain_count']} chains")
print(f"Home: {report['home']}")
print(f"Chains: {report['chain_dir']}")
print(f"Tools: {report['totals']['tools']}")
print(f"Verdicts: {report['totals']['verdicts']}")
print(f"Side effects: {report['totals']['side_effect_classes']}")
print(
"Subagent dispatches: "
f"{report['totals']['dispatch_launch_count']} launches, "
f"{report['totals']['dispatch_observation_count']} post observations"
)
print(
"Subagent lifecycle: "
f"{report['totals']['subagents_started']} started, "
f"{report['totals']['subagents_stopped']} stopped"
)
print(f"Per-child attribution: {report['coverage']['per_child_attribution']}")
print(f"Attribution: {report['coverage']['attribution']}")
_print_report_next_steps(report)
return 0
def cmd_gemini_cli_hook(args: argparse.Namespace) -> int:
phase = args.phase or args.phase_pos or "pre"
argv = ["--phase", phase]
if args.keys_dir:
argv.extend(["--keys-dir", str(args.keys_dir)])
return gemini_cli_hook_main(argv)
def cmd_gemini_cli_fixture(args: argparse.Namespace) -> int:
fixture = build_gemini_local_fixture(
home=args.home,
project_dir=args.project_dir,
chain_dir=args.chain_dir,
keys_dir=args.keys_dir,
)
_print_json(build_gemini_shareable_context(fixture))
return 0
def cmd_gemini_cli_report(args: argparse.Namespace) -> int:
report = build_gemini_shareable_report(
home=args.home,
chain_dir=args.chain_dir,
keys_dir=args.keys_dir,
verify_expiry=args.verify_expiry,
)
if args.json:
_print_json(report)
return 0
print(f"Ardur Gemini CLI receipt report: {report['receipt_count']} receipts across {report['chain_count']} chains")
print(f"Chains: {report['chain_dir']}")
print(f"Verdicts: {report['policy_verdict_counts']}")
print(f"Coverage gaps: {report['coverage_gaps']}")
_print_report_next_steps(report)
return 0
def _codex_app_server_event_input_next_steps(condition: str) -> list[dict[str, str]]:
return [
{
"condition": condition,
"action": "create_codex_app_server_fixture",
"command": "ardur codex-app-server-fixture --project-dir <your-project>",
"detail": (
"Create a local-only Codex app-server fixture and inspect the generated "
"config/schema before feeding host-event JSON."
),
},
{
"condition": condition,
"action": "rerun_with_event_json_file",
"command": "ardur codex-app-server-event --keys-dir <keys-dir> < <event-json-file>",
"detail": (
"Feed a Codex app-server host-event JSON object from <event-json-file>. "
"Keep raw tokens and local private paths out of shared logs and reports."
),
},
]
def _codex_app_server_event_input_failure_response(exc: Exception) -> dict:
if isinstance(exc, json.JSONDecodeError):
condition = "codex_app_server_event_input_malformed"
message = "Codex app-server host-event input is not valid JSON."
detail = (
"Input must be a valid JSON object; "
f"parsing failed at line {exc.lineno}, column {exc.colno}."
)
else:
condition = "codex_app_server_event_input_not_object"
message = "Codex app-server host-event input must be a JSON object."
detail = (
"Input must be a JSON object from <event-json-file>; arrays, strings, "
"numbers, booleans, and null are not accepted."
)
return {
"ok": False,
"error": condition,
"condition": condition,
"message": message,
"detail": detail,
"next_steps": _codex_app_server_event_input_next_steps(condition),
}
def _load_codex_app_server_event_stdin(raw: str) -> dict:
if not raw.strip():
return {}
payload = json.loads(raw)
if not isinstance(payload, dict):
raise ValueError("Codex app-server host-event payload must be a JSON object")
return payload
def cmd_codex_app_server_event(args: argparse.Namespace) -> int:
raw = sys.stdin.read()
try:
payload = _load_codex_app_server_event_stdin(raw)
except (json.JSONDecodeError, ValueError) as exc:
_print_json(_codex_app_server_event_input_failure_response(exc))
return 1
output = handle_codex_host_event(payload, keys_dir=args.keys_dir)
_print_json(output)
return 2 if output.get("block") else 0
def cmd_codex_app_server_fixture(args: argparse.Namespace) -> int:
fixture = build_codex_local_fixture(
home=args.home,
project_dir=args.project_dir,
chain_dir=args.chain_dir,
keys_dir=args.keys_dir,
)
_print_json(build_codex_shareable_context(fixture))
return 0
def cmd_codex_app_server_report(args: argparse.Namespace) -> int:
report = build_codex_shareable_report(
home=args.home,
chain_dir=args.chain_dir,
keys_dir=args.keys_dir,
verify_expiry=args.verify_expiry,
)
if args.json:
_print_json(report)
return 0
print(f"Ardur Codex app-server receipt report: {report['receipt_count']} receipts across {report['chain_count']} chains")
print(f"Chains: {report['chain_dir']}")
print(f"Verdicts: {report['policy_verdict_counts']}")
print(f"Coverage gaps: {report['coverage_gaps']}")
_print_report_next_steps(report)
return 0
def cmd_posture_scan(args: argparse.Namespace) -> int:
posture = build_posture_index(
receipts=args.receipts,
keys_dir=args.keys_dir,
profile=args.profile,
evidence_bundle=args.evidence_bundle,
verify_expiry=args.verify_expiry,
)
if args.format == "json":
_print_json(posture)
return 0
print(format_posture_report(posture))
return 0
def _posture_report_input_next_steps(condition: str) -> list[dict[str, str]]:
return [
{
"condition": condition,
"action": "create_posture_json",
"command": "ardur posture scan --receipts <chain-dir> --keys-dir <keys-dir> --format json > <posture-json>",
"detail": (
"Create a posture JSON document from local Ardur artifacts first. "
"Keep local paths, private keys, and raw tokens out of shared reports."
),
},
{
"condition": condition,
"action": "rerun_posture_report",
"command": "ardur posture report --input <posture-json> --format json",
"detail": "Render the generated posture JSON after the input file exists and parses successfully.",
},
]
def _posture_report_input_failure_response(exc: Exception) -> dict:
if isinstance(exc, FileNotFoundError):
condition = "posture_report_input_missing"
message = "Posture report input file could not be read."
detail = "No posture JSON file was found at the supplied --input path."
elif isinstance(exc, json.JSONDecodeError):
condition = "posture_report_input_malformed"
message = "Posture report input file is not valid JSON."
detail = f"JSON parsing failed at line {exc.lineno}, column {exc.colno}."
elif isinstance(exc, ValueError):
condition = "posture_report_input_invalid"
message = "Posture report input file is not a posture JSON object."
detail = "The supplied --input file must contain a JSON object produced by ardur posture scan."
else:
condition = "posture_report_input_unreadable"
message = "Posture report input file could not be read."
detail = f"Reading the supplied --input file failed with {exc.__class__.__name__}."
return {
"ok": False,
"error": condition,
"condition": condition,
"message": message,
"detail": detail,
"next_steps": _posture_report_input_next_steps(condition),
}
def cmd_posture_report(args: argparse.Namespace) -> int:
try:
posture = json.loads(args.input.read_text(encoding="utf-8"))
if not isinstance(posture, dict):
raise ValueError("posture report input must be a JSON object")
except (FileNotFoundError, PermissionError, IsADirectoryError, OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc:
response = _posture_report_input_failure_response(exc)
if args.format == "json":
_print_json(response)
else:
print(f"Error: {response['message']}")
print(f"Detail: {response['detail']}")
_print_report_next_steps(response)
return 1
if args.format == "json":
_print_json(posture)
return 0
print(format_posture_report(posture))
return 0
def cmd_hub(args: argparse.Namespace) -> int:
serve_hub(
host=args.host,
port=args.port,
home=args.home,
tls_cert=args.tls_cert,
tls_key=args.tls_key,
no_tls=args.no_tls,
)
return 0
def _kill_switch_next_steps_for_failure(
error: str,
*,
status: int | None = None,
) -> list[dict[str, str]]:
"""Return placeholder-only remediation hints for kill-switch setup failures."""
normalized_error = error.strip().lower().replace("_", " ")
status_text = str(status or "").strip()
proxy_unavailable = any(
marker in normalized_error
for marker in {
"connection refused",
"connection reset",
"connection aborted",
"network is unreachable",
"no route to host",
"name or service not known",
"nodename nor servname",
"timed out",
"urlopen error",
}
)
tls_problem = any(
marker in normalized_error
for marker in {
"ssl",
"tls",
"certificate",
"wrong version number",
"handshake",
}
)
token_problem = (
status_text in {"401", "403"}
or "authorization" in normalized_error
or "unauthorized" in normalized_error
or "bearer token" in normalized_error
or "invalid bearer" in normalized_error
or "api token" in normalized_error
)
endpoint_problem = status_text in {"404", "405"} or "not found" in normalized_error
if not proxy_unavailable and not tls_problem and not token_problem and not endpoint_problem:
return []
steps: list[dict[str, str]] = []
if proxy_unavailable or tls_problem or endpoint_problem:
steps.append(
{
"condition": "proxy_tls_setup" if tls_problem else "proxy_unavailable",
"action": "start_or_check_governance_proxy",
"command": "VIBAP_API_TOKEN=<api-token> ardur start --host 127.0.0.1 --port <proxy-port>",
"detail": (
"Start the local loopback governance proxy and keep its token private. "
"Use --tls-cert/--tls-key if your proxy URL uses https with explicit certs, "
"or --no-tls only for local development."
),
}
)
steps.append(
{
"condition": "proxy_tls_setup" if tls_problem else "proxy_url_check",
"action": "check_proxy_url_scheme",
"command": "ardur kill-switch --proxy-url <proxy-url> --api-token <api-token>",
"detail": (
"Use the scheme, host, and port printed by ardur start; keep any URL "
"credentials or raw tokens out of logs and shared artifacts."
),
}
)
if token_problem:
steps.append(
{
"condition": "proxy_token_required",
"action": "supply_proxy_api_token",
"command": "ardur kill-switch --proxy-url <proxy-url> --api-token <api-token>",
"detail": (
"Pass the configured proxy API token with --api-token <api-token> or "
"ARDUR_API_TOKEN=<api-token>. Do not paste the raw token into shared logs."
),
}
)
steps.append(
{
"condition": "kill_switch_proxy_request_failed",
"action": "rerun_kill_switch_or_health_check",
"command": "ardur kill-switch --proxy-url <proxy-url> --api-token <api-token>",
"detail": (
"After local proxy setup is fixed, rerun ardur kill-switch or check the "
"loopback proxy health endpoint. These hints are local/no-key setup guidance "
"only and do not claim external provider visibility or live enforcement beyond "
"the configured proxy."
),
}
)
return steps
def _kill_switch_failure_response(error: str, *, status: int | None = None) -> dict:
response: dict = {"ok": False, "error": error}
if status is not None:
response["status"] = status
steps = _kill_switch_next_steps_for_failure(error, status=status)
if steps:
response["next_steps"] = steps
return response
def cmd_kill_switch(args: argparse.Namespace) -> int:
import ssl
import urllib.error as urlerror
import urllib.request as urlreq
proxy_url = (
args.proxy_url
or os.environ.get("ARDUR_PROXY_URL")
or "https://127.0.0.1:8443"
)
api_token = args.api_token or os.environ.get("ARDUR_API_TOKEN", "")
payload = json.dumps({"deactivate": args.deactivate}).encode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_token}",
}
req = urlreq.Request(f"{proxy_url.rstrip('/')}/admin/kill-switch", data=payload, headers=headers)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE # localhost self-signed cert
try:
with urlreq.urlopen(req, timeout=5, context=ctx) as resp:
result = json.loads(resp.read().decode("utf-8"))
_print_json(result)
return 0
except urlerror.HTTPError as exc:
error = str(exc)
try:
payload = json.loads(exc.read().decode("utf-8"))
except Exception:
payload = {}
if isinstance(payload, dict) and payload.get("error"):
error = str(payload["error"])
_print_json(_kill_switch_failure_response(error, status=exc.code))
return 1
except Exception as exc:
_print_json(_kill_switch_failure_response(str(exc)))
return 1
def cmd_setup(args: argparse.Namespace) -> int:
_print_json(setup_personal(args))
return 0
def cmd_status(args: argparse.Namespace) -> int:
response = hub_request(
"GET",
"/v1/status",
hub_url=args.hub_url,
hub_token=args.hub_token,
home=args.home,
)
response = status_response_with_next_steps(response)
_print_json(response)
return 0 if response.get("ok") else 1
def cmd_doctor(args: argparse.Namespace) -> int:
response = doctor_personal(args)
_print_json(response)
return 0 if response.get("ok") else 1
def cmd_uninstall(args: argparse.Namespace) -> int:
_print_json(uninstall_personal(args))
return 0
def cmd_run(args: argparse.Namespace) -> int:
return run_under_hub(args)
def cmd_desktop_observe(args: argparse.Namespace) -> int:
response = desktop_observe(args)
_print_json(response)
return 0 if response.get("ok") else 1
def cmd_personal_native_host(args: argparse.Namespace) -> int:
if args.once_json:
message = json.loads(args.once_json.read_text(encoding="utf-8"))
response = handle_native_host_message(message, hub_url=args.hub_url, hub_token=args.hub_token, home=args.home)
_print_json(response)
return 0 if response.get("ok") else 1
run_native_host(sys.stdin.buffer, sys.stdout.buffer, hub_url=args.hub_url, hub_token=args.hub_token, home=args.home)
return 0
def cmd_personal_native_manifest(args: argparse.Namespace) -> int:
_print_json(
build_native_host_manifest(
args.host_path,
args.extension_id,
browser=args.browser,
)
)
return 0
CLAUDE_CODE_PROTECT_MODES = {
"safe-coding": {
"mission": "Safe Claude Code work inside the selected folder.",
"allowed_tools": ["Read", "Glob", "Grep", "Edit", "MultiEdit", "Write"],
"forbidden_tools": ["Bash"],
},
"read-only": {
"mission": "Read-only Claude Code review inside the selected folder.",
"allowed_tools": ["Read", "Glob", "Grep"],
"forbidden_tools": ["Bash", "Edit", "MultiEdit", "Write"],
},
}
def _default_claude_plugin_dir() -> Path:
cwd_candidate = Path.cwd() / "plugins" / "claude-code"
if cwd_candidate.exists():
return cwd_candidate
source_candidate = Path(__file__).resolve().parents[2] / "plugins" / "claude-code"
return source_candidate
def _normalize_protect_mode(value: str) -> str:
return value.strip().lower().replace("_", "-").replace(" ", "-")
def _claude_code_plugin_checks(plugin_dir: Path) -> list[dict[str, object]]:
return [
{
"name": "plugin_dir",
"ok": plugin_dir.exists() and plugin_dir.is_dir(),
"detail": str(plugin_dir),
},
{
"name": "plugin_manifest",
"ok": (plugin_dir / ".claude-plugin" / "plugin.json").is_file(),
"detail": str(plugin_dir / ".claude-plugin" / "plugin.json"),
},
{
"name": "plugin_hooks",
"ok": (plugin_dir / "hooks" / "hooks.json").is_file(),
"detail": str(plugin_dir / "hooks" / "hooks.json"),
},
{
"name": "pre_tool_use",
"ok": (plugin_dir / "hooks" / "pre_tool_use").is_file(),
"detail": str(plugin_dir / "hooks" / "pre_tool_use"),
},
{
"name": "post_tool_use",
"ok": (plugin_dir / "hooks" / "post_tool_use").is_file(),
"detail": str(plugin_dir / "hooks" / "post_tool_use"),
},
{
"name": "subagent_start",
"ok": (plugin_dir / "hooks" / "subagent_start").is_file(),
"detail": str(plugin_dir / "hooks" / "subagent_start"),
},
{
"name": "subagent_stop",
"ok": (plugin_dir / "hooks" / "subagent_stop").is_file(),
"detail": str(plugin_dir / "hooks" / "subagent_stop"),
},
]
def _validate_claude_code_plugin_dir(plugin_dir: Path) -> None:
failed = [check for check in _claude_code_plugin_checks(plugin_dir) if not check["ok"]]
if failed:
details = ", ".join(str(item["detail"]) for item in failed)
raise FileNotFoundError(f"Claude Code plugin is incomplete: {details}")
def _protect_claude_code_plugin_incomplete_response(
failed_checks: list[dict[str, object]],
) -> dict[str, object]:
missing_checks = [str(check["name"]) for check in failed_checks]
return {
"ok": False,
"agent": "claude-code",
"error": "claude_code_plugin_incomplete",
"condition": "claude_code_plugin_incomplete",
"message": "Claude Code plugin directory is missing or incomplete.",
"detail": "Missing Claude Code plugin checks: " + ", ".join(missing_checks),
"missing_checks": missing_checks,
"next_steps": [
{
"action": "check_plugin",
"command": "ardur doctor-claude-code --plugin-dir <claude-code-plugin> --home <ardur-home>",
"detail": "Verify the local Claude Code plugin files before configuring protection.",
},
{
"action": "rerun_protect",
"command": "ardur protect claude-code --scope <your-project> --home <ardur-home> --plugin-dir <claude-code-plugin>",
"detail": "After the plugin path is corrected, rerun protection for the project folder.",
},
],
}
def _write_private_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
fd = -1
handle.write(text)
finally:
if fd != -1:
os.close(fd)
def _claude_code_doctor_next_steps(
checks: list[dict[str, object]],
plugin: Path,
active_passport: Path,
) -> list[dict[str, str]]:
by_name = {str(check["name"]): check for check in checks}
steps: list[dict[str, str]] = []
plugin_check_names = [
"plugin_dir",
"plugin_manifest",
"plugin_hooks",
"pre_tool_use",
"post_tool_use",
"subagent_start",
"subagent_stop",
]
missing_plugin_checks = [
name for name in plugin_check_names if not bool(by_name.get(name, {}).get("ok"))
]
if missing_plugin_checks:
steps.append(
{
"check": "plugin_files",
"action": "repair_plugin_path",
"command": shlex.join(["ardur", "doctor-claude-code", "--plugin-dir", str(plugin)]),
"detail": "Missing Claude Code plugin checks: " + ", ".join(missing_plugin_checks),
}
)
claude_check = by_name.get("claude_binary", {})
if not bool(claude_check.get("ok")):
steps.append(
{
"check": "claude_binary",
"action": "install_claude_code",
"command": "claude --version",
"detail": "Install Claude Code CLI and ensure `claude` is on PATH, then rerun doctor.",
}
)
active_passport_check = by_name.get("active_passport", {})
if not bool(active_passport_check.get("ok")):
steps.append(
{
"check": "active_passport",
"action": "run_protect_claude_code",
"command": shlex.join(
[
"ardur",
"protect",
"claude-code",
"--scope",
"<your-project>",
"--home",
str(active_passport.parent),
"--plugin-dir",
str(plugin),
]
),
"detail": "Create an active Mission Passport for the local Claude Code plugin.",
}
)
plugin_validate_check = by_name.get("plugin_validate", {})
if (
not bool(plugin_validate_check.get("ok"))
and not missing_plugin_checks
and bool(claude_check.get("ok"))
):
steps.append(
{
"check": "plugin_validate",
"action": "validate_plugin",
"command": shlex.join(["claude", "plugin", "validate", str(plugin)]),
"detail": str(
plugin_validate_check.get("detail")
or "Claude Code plugin validation failed; inspect the validation output."
),
}
)
return steps
def claude_code_doctor(plugin_dir: Path | None = None, home: Path | None = None) -> dict[str, object]:
plugin = (plugin_dir or _default_claude_plugin_dir()).expanduser().resolve()
checks = _claude_code_plugin_checks(plugin)
claude_binary = shutil.which("claude")
checks.append({
"name": "claude_binary",
"ok": bool(claude_binary),
"detail": claude_binary or "claude not found on PATH",
})
active_passport = (home.expanduser() if home else DEFAULT_HOME) / "active_mission.jwt"
checks.append({
"name": "active_passport",
"ok": active_passport.is_file(),
"detail": str(active_passport),
})
if claude_binary and all(check["ok"] for check in checks[:5]):
result = subprocess.run(
[claude_binary, "plugin", "validate", str(plugin)],
capture_output=True,
text=True,
)
checks.append({
"name": "plugin_validate",
"ok": result.returncode == 0,
"detail": result.stdout.strip() or result.stderr.strip(),
})
else:
checks.append({
"name": "plugin_validate",
"ok": False,
"detail": "skipped; missing claude binary or plugin files",
})
ok = all(bool(check["ok"]) for check in checks)
return {
"ok": ok,
"checks": checks,
"next_steps": [] if ok else _claude_code_doctor_next_steps(checks, plugin, active_passport),
}
def _resolve_protect_policies(
args: argparse.Namespace,
profile: ArdurProfile | None,
home: Path,
) -> list[dict[str, object]]:
"""Build additional_policies from CLI flags + profile."""
policies: list[dict[str, object]] = []
# CLI flags (highest priority)
if getattr(args, "forbid_rules", None) is not None:
rules = json.loads(Path(args.forbid_rules).read_text("utf-8"))
if not isinstance(rules, list):
rules = [rules]
policies.append({
"backend": "forbid_rules",
"label": "cli-forbid-rules",
"policy_inline": "",
"policy_sha256": hashlib.sha256(
json.dumps(rules, sort_keys=True).encode()
).hexdigest(),
"data_inline": rules,
})
if getattr(args, "cedar_policy", None) is not None:
policy_src = Path(args.cedar_policy).read_text("utf-8")
entities: list[dict[str, object]] = []
if getattr(args, "cedar_entities", None) is not None:
entities = json.loads(Path(args.cedar_entities).read_text("utf-8"))
policies.append({
"backend": "cedar",
"label": "cli-cedar-policy",
"policy_inline": policy_src,
"policy_sha256": hashlib.sha256(policy_src.encode()).hexdigest(),
"data_inline": entities,