-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
2790 lines (2304 loc) · 94.6 KB
/
cli.py
File metadata and controls
2790 lines (2304 loc) · 94.6 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
"""
cato/cli.py — Command-line interface for CATO.
Commands:
cato init Interactive first-run setup wizard
cato start [--browser conduit] Start the CATO daemon
cato stop Stop the running CATO daemon
cato migrate --from-openclaw Migrate workspace from OpenClaw
cato doctor [--skills] [--attest] Audit workspace health + attestation
cato status Show running state and budget summary
cato vault set/list/delete Manage vault credentials
cato audit --session <id> Export audit log for a session
cato receipt --session <id> Show signed fare receipt for a session
cato replay --session <id> [--live] Replay a recorded session
"""
from __future__ import annotations
import json
import shutil
import sys
from pathlib import Path
from typing import Any, Optional
import click
from rich.console import Console
from rich.table import Table
from cato import __version__
from cato.budget import BudgetManager
from cato.config import CatoConfig
from cato.platform import get_data_dir, safe_print, setup_signal_handlers
from cato.vault import Vault
console = Console()
_CATO_DIR = get_data_dir()
_PID_FILE = _CATO_DIR / "cato.pid"
_PORT_FILE = _CATO_DIR / "cato.port"
def _discover_http_port(config: Optional[CatoConfig] = None) -> int:
"""Return the daemon's active HTTP port, preferring the runtime port file."""
if _PORT_FILE.exists():
try:
return int(_PORT_FILE.read_text().strip())
except (OSError, ValueError):
pass
cfg = config or CatoConfig.load()
return getattr(cfg, "webchat_port", None) or getattr(cfg, "port", None) or 8080
async def _bind_http_site_with_fallback(
runner: Any,
host: str,
preferred_port: int,
*,
max_attempts: int = 5,
retry_delay: float = 1.0,
log: Any = None,
) -> tuple[Any, int]:
"""Bind an aiohttp site, shifting upward when the preferred port is busy."""
import asyncio
from aiohttp import web
if max_attempts < 1:
raise ValueError("max_attempts must be at least 1")
last_error: OSError | None = None
for attempt in range(max_attempts):
candidate_port = preferred_port + attempt
try:
site = web.TCPSite(runner, host, candidate_port)
await site.start()
if attempt > 0 and log is not None:
log.warning(
"Port %d in use — daemon bound to %d instead. "
"If this is unexpected, ensure the old daemon process is fully stopped.",
preferred_port,
candidate_port,
)
return site, candidate_port
except OSError as exc:
last_error = exc
if attempt == max_attempts - 1:
raise
await asyncio.sleep(retry_delay)
raise last_error or RuntimeError("failed to bind daemon HTTP site")
# ---------------------------------------------------------------------------
# CLI group
# ---------------------------------------------------------------------------
@click.group()
@click.version_option(version=__version__, prog_name="cato")
def main() -> None:
"""Cato — The AI agent daemon you can audit in a coffee break."""
# ---------------------------------------------------------------------------
# cato init
# ---------------------------------------------------------------------------
@main.command("init")
def cmd_init() -> None:
"""Interactive first-run setup wizard."""
safe_print("\nCato Setup Wizard")
safe_print("=" * 50)
config = CatoConfig.load()
if not config.is_first_run():
if not click.confirm("Config already exists. Reinitialise?", default=False):
safe_print("Aborted.")
return
# 1. Monthly budget cap
raw_cap = click.prompt(
"Monthly budget cap (USD)",
default="20.00",
show_default=True,
)
try:
monthly_cap = float(raw_cap.replace("$", "").strip())
except ValueError:
monthly_cap = 20.00
config.monthly_cap = monthly_cap
# 2. Session cap
raw_session = click.prompt(
"Session budget cap (USD)",
default="1.00",
show_default=True,
)
try:
session_cap = float(raw_session.replace("$", "").strip())
except ValueError:
session_cap = 1.00
config.session_cap = session_cap
# 3. Vault master password
safe_print("\nVault master password (encrypts all stored API keys)")
import sys as _sys
_hide = _sys.stdin.isatty()
pw = click.prompt("Set a vault master password", hide_input=_hide)
pw_confirm = click.prompt("Confirm master password", hide_input=_hide)
if pw != pw_confirm:
safe_print("Passwords do not match. Aborted.")
sys.exit(1)
vault_path = _CATO_DIR / "vault.enc"
vault = Vault.create(pw, vault_path=vault_path)
safe_print("Vault created.")
# 4. SwarmSync
swarmync = click.confirm(
"\nEnable SwarmSync intelligent routing?",
default=False,
)
config.swarmsync_enabled = swarmync
if swarmync:
config.swarmsync_api_url = click.prompt(
"SwarmSync API URL",
default="https://api.swarmsync.ai/v1/chat/completions",
show_default=True,
)
ss_key = click.prompt("SwarmSync API key (starts with sk-ss-)", hide_input=True)
vault.set("SWARMSYNC_API_KEY", ss_key)
safe_print(" SwarmSync API key stored in vault.")
# 5. Telegram
telegram = click.confirm("\nEnable Telegram?", default=False)
config.telegram_enabled = telegram
if telegram:
bot_token = click.prompt("Telegram bot token")
vault.set("TELEGRAM_BOT_TOKEN", bot_token)
safe_print("Telegram token stored in vault.")
# 6. WhatsApp
whatsapp = click.confirm("Enable WhatsApp?", default=False)
config.whatsapp_enabled = whatsapp
# 7. Create directory structure
dirs = [
_CATO_DIR / "workspace",
_CATO_DIR / "memory",
_CATO_DIR / "logs",
_CATO_DIR / "agents",
]
for d in dirs:
d.mkdir(parents=True, exist_ok=True)
# 8. Save config
config.save()
safe_print(f"\n Config: {config._path}")
safe_print(f" Workspace: {config.workspace_dir}")
# 9. Initialise budget manager with chosen caps
bm = BudgetManager(session_cap=session_cap, monthly_cap=monthly_cap)
bm.set_monthly_cap(monthly_cap)
bm.set_session_cap(session_cap)
safe_print(
f"\nCato initialised. "
f"Monthly cap: ${monthly_cap:.2f} | Session cap: ${session_cap:.2f}"
)
safe_print("Run [cato start] to begin.\n")
def _init_vault(vault: Vault, password: str) -> None:
"""Bootstrap a new vault with a pre-supplied password (bypasses getpass)."""
import secrets as _secrets
from argon2.low_level import hash_secret_raw, Type
from cato.vault import _SALT_SIZE, _ARGON2_TIME_COST, _ARGON2_MEMORY_COST, _ARGON2_PARALLELISM, _KEY_SIZE, _encrypt
import base64, json as _json
salt = _secrets.token_bytes(_SALT_SIZE)
key = hash_secret_raw(
secret=password.encode("utf-8"),
salt=salt,
time_cost=_ARGON2_TIME_COST,
memory_cost=_ARGON2_MEMORY_COST,
parallelism=_ARGON2_PARALLELISM,
hash_len=_KEY_SIZE,
type=Type.ID,
)
vault._key = key # type: ignore[attr-defined]
vault._data = {} # type: ignore[attr-defined]
plaintext = _json.dumps({}).encode("utf-8")
blob = _encrypt(plaintext, key)
vault._path.parent.mkdir(parents=True, exist_ok=True) # type: ignore[attr-defined]
vault._path.write_bytes(base64.b64encode(salt + blob)) # type: ignore[attr-defined]
# ---------------------------------------------------------------------------
# cato vault (key management)
# ---------------------------------------------------------------------------
@main.group("vault")
def vault_cmd() -> None:
"""Manage vault credentials."""
pass
@vault_cmd.command("set")
@click.argument("key")
@click.option("--value", prompt=True, hide_input=True, help="Secret value")
def vault_set(key: str, value: str) -> None:
"""Store a secret in the vault. Example: cato vault set ANTHROPIC_API_KEY"""
vault_path = _CATO_DIR / "vault.enc"
if not vault_path.exists():
safe_print("Vault not initialised — run 'cato init' first.")
return
vault = Vault(vault_path=vault_path)
vault.set(key, value)
safe_print(f"Key '{key}' stored in vault.")
@vault_cmd.command("list")
def vault_list() -> None:
"""List all keys stored in the vault (values hidden)."""
vault_path = _CATO_DIR / "vault.enc"
if not vault_path.exists():
safe_print("Vault not initialised — run 'cato init' first.")
return
vault = Vault(vault_path=vault_path)
keys = vault.list_keys()
if not keys:
safe_print("No keys stored in vault.")
return
safe_print("Vault keys:")
for k in sorted(keys):
safe_print(f" {k}")
@vault_cmd.command("delete")
@click.argument("key")
def vault_delete(key: str) -> None:
"""Delete a key from the vault."""
vault_path = _CATO_DIR / "vault.enc"
if not vault_path.exists():
safe_print("Vault not initialised — run 'cato init' first.")
return
vault = Vault(vault_path=vault_path)
vault.delete(key)
safe_print(f"Key '{key}' deleted from vault.")
# ---------------------------------------------------------------------------
# cato start
# ---------------------------------------------------------------------------
@main.command("start")
@click.option("--agent", default="default", show_default=True, help="Agent workspace name.")
@click.option("--channel", default="webchat", show_default=True,
type=click.Choice(["webchat", "telegram", "whatsapp", "all"]),
help="Which messaging channels to enable. Web UI (HTTP/WS) is always started on webchat_port.")
@click.option("--browser", default="default", show_default=True,
type=click.Choice(["default", "conduit"]),
help="Browser engine to use (conduit = opt-in per-action billing).")
def cmd_start(agent: str, channel: str, browser: str) -> None:
"""Start the CATO daemon."""
# Load .env file if it exists
import os
from pathlib import Path
env_file = Path.cwd() / ".env"
if env_file.exists():
try:
from dotenv import load_dotenv
load_dotenv(env_file)
except ImportError:
pass # dotenv not installed, continue with existing env vars
config = CatoConfig.load()
if browser == "conduit":
config.conduit_enabled = True
safe_print("Conduit browser engine enabled (per-action billing).")
if _PID_FILE.exists():
pid = _PID_FILE.read_text().strip()
safe_print(f"Cato already running (PID {pid}). Use 'cato stop' first.")
return
safe_print(f"Starting Cato — agent=[{agent}] channel=[{channel}] browser=[{browser}]")
safe_print(f" Model: {config.default_model}")
safe_print(f" Workspace: {config.workspace_dir}")
safe_print(f" Log level: {config.log_level}")
# Write PID file
import os
_PID_FILE.write_text(str(os.getpid()))
# Setup cross-platform signal handlers
def _shutdown() -> None:
safe_print("\nCato daemon stopped.")
_PID_FILE.unlink(missing_ok=True)
setup_signal_handlers(_shutdown)
try:
_run_daemon(config, agent, channel)
finally:
if _PID_FILE.exists():
_PID_FILE.unlink()
def _run_daemon(config: CatoConfig, agent: str, channel: str) -> None:
"""Import and launch the Gateway with configured adapters."""
import asyncio
import logging
vault_path = _CATO_DIR / "vault.enc"
vault = Vault(vault_path=vault_path) if vault_path.exists() else None
budget = BudgetManager(
session_cap=config.session_cap,
monthly_cap=config.monthly_cap,
)
async def _main(cfg: CatoConfig, vlt: "Vault", bdg: BudgetManager) -> None:
from .gateway import Gateway
from .adapters.telegram import TelegramAdapter
from .adapters.whatsapp import WhatsAppAdapter
from .ui.server import create_ui_app
from aiohttp import web
log = logging.getLogger("cato")
gateway = Gateway(cfg, bdg, vlt)
if cfg.telegram_enabled:
try:
tg = TelegramAdapter(gateway, vlt, cfg)
gateway.register_adapter(tg)
log.info("Telegram adapter registered")
except Exception as e:
log.warning(f"Telegram adapter failed to register: {e}")
if cfg.whatsapp_enabled:
try:
wa = WhatsAppAdapter(gateway, vlt, cfg)
gateway.register_adapter(wa)
log.info("WhatsApp adapter registered")
except Exception as e:
log.warning(f"WhatsApp adapter failed to register: {e}")
app = await create_ui_app(gateway)
runner = web.AppRunner(app)
await runner.setup()
port = getattr(cfg, "webchat_port", None) or getattr(cfg, "port", None) or 8080
_site, actual_port = await _bind_http_site_with_fallback(
runner,
"127.0.0.1",
port,
max_attempts=5,
retry_delay=1.0,
log=log,
)
log.info(f"Web UI at http://127.0.0.1:{actual_port}")
safe_print(f"Cato daemon running on http://127.0.0.1:{actual_port}. Press Ctrl-C to stop.")
# Write the actual bound port to a file so other tools (watchdog, UI) can discover it
try:
_PORT_FILE.write_text(str(actual_port))
except OSError:
pass
try:
await gateway.start()
# Keep the event loop alive until interrupted.
# gateway.start() creates background tasks and returns immediately.
stop_event = asyncio.Event()
await stop_event.wait()
except asyncio.CancelledError:
pass
finally:
await runner.cleanup()
await gateway.stop()
# Remove port file on clean shutdown
_PORT_FILE.unlink(missing_ok=True)
try:
if vault is None:
safe_print("Warning: vault not initialised — run 'cato init' first.")
asyncio.run(_main(config, vault, budget))
except KeyboardInterrupt:
safe_print("\nCato daemon stopped.")
# ---------------------------------------------------------------------------
# cato stop
# ---------------------------------------------------------------------------
@main.command("stop")
def cmd_stop() -> None:
"""Stop the running CATO daemon."""
if not _PID_FILE.exists():
safe_print("Cato is not running.")
return
import os, signal
pid_str = _PID_FILE.read_text().strip()
try:
pid = int(pid_str)
os.kill(pid, signal.SIGTERM)
_PID_FILE.unlink(missing_ok=True)
safe_print(f"Cato (PID {pid}) stopped.")
except (ValueError, ProcessLookupError, OSError) as exc:
safe_print(f"Could not stop process {pid_str}: {exc}")
_PID_FILE.unlink(missing_ok=True)
# ---------------------------------------------------------------------------
# cato migrate
# ---------------------------------------------------------------------------
@main.command("migrate")
@click.option("--from-openclaw", "from_openclaw", is_flag=True, default=False,
help="Migrate agent workspaces from OpenClaw.")
@click.option("--dry-run", is_flag=True, default=False,
help="Show what would be migrated without making changes.")
@click.option("--browser", default="default",
type=click.Choice(["default", "conduit"]),
help="Browser engine preference to set in migrated config.")
def cmd_migrate(from_openclaw: bool, dry_run: bool, browser: str) -> None:
"""Migrate workspaces from another agent system."""
from cato.migrate import OpenClawMigrator, detect_openclaw_install, estimate_openclaw_last_month_cost, generate_migration_report
if not from_openclaw:
safe_print("Specify a migration source, e.g. --from-openclaw")
return
# Auto-detect OpenClaw if available
oc_dir = detect_openclaw_install()
if oc_dir:
safe_print(f"OpenClaw installation detected at: {oc_dir}")
oc_cost = estimate_openclaw_last_month_cost(oc_dir)
else:
oc_cost = None
migrator = OpenClawMigrator(dry_run=dry_run)
stats = migrator.run()
report = generate_migration_report(
migrated_agents=stats["agents"],
migrated_skills=stats["skills"],
openclaw_cost=oc_cost,
)
safe_print(report)
# ---------------------------------------------------------------------------
# cato doctor
# ---------------------------------------------------------------------------
@main.command("doctor")
@click.option("--skills", is_flag=True, default=False,
help="Validate all SKILL.md files in agent directories.")
@click.option("--attest", is_flag=True, default=False,
help="Emit signed JSON attestation of security properties.")
def cmd_doctor(skills: bool, attest: bool) -> None:
"""Audit token budget, workspace health, and flag potential savings."""
if attest:
_cmd_doctor_attest()
return
if skills:
_cmd_doctor_skills()
return
# Default doctor
from cato.core.context_builder import ContextBuilder
safe_print("\nCato Doctor")
safe_print("=" * 50)
cb = ContextBuilder()
agents_dir = _CATO_DIR / "agents"
if not agents_dir.exists() or not any(agents_dir.iterdir()):
safe_print("No agent workspaces found in agents/")
else:
table = Table(title="Agent Workspace Token Audit", show_lines=True)
table.add_column("Agent", style="cyan")
table.add_column("Files", justify="right")
table.add_column("Tokens", justify="right")
table.add_column("Budget %", justify="right")
table.add_column("Flags", style="yellow")
for agent_dir in sorted(agents_dir.iterdir()):
if not agent_dir.is_dir():
continue
md_files = list(agent_dir.glob("*.md"))
total_tokens = 0
flags: list[str] = []
for md in md_files:
try:
content = md.read_text(encoding="utf-8", errors="replace")
total_tokens += cb.count_tokens(content)
except OSError:
pass
if not any((agent_dir / f).exists() for f in ["SKILL.md", "SOUL.md", "IDENTITY.md"]):
flags.append("no SKILL.md/SOUL.md")
budget_pct = min(999, int(total_tokens / 7000 * 100))
flag_str = ", ".join(flags) if flags else "[green]OK[/green]"
table.add_row(
agent_dir.name,
str(len(md_files)),
str(total_tokens),
f"{budget_pct}%",
flag_str,
)
console.print(table)
# Budget status
safe_print("\nBudget Status")
bm = BudgetManager()
status = bm.get_status()
safe_print(f" Monthly: ${status['monthly_spend']:.4f} / ${status['monthly_cap']:.2f}"
f" ({status['monthly_pct_remaining']:.0f}% remaining)")
safe_print(f" Session: ${status['session_spend']:.4f} / ${status['session_cap']:.2f}")
safe_print(f" All-time: ${status['total_spend_all_time']:.4f}")
# Vault check
safe_print("\nVault")
vault_file = _CATO_DIR / "vault.enc"
if vault_file.exists():
safe_print(f" OK — {vault_file}")
else:
safe_print(" Not initialised — run 'cato init'")
safe_print("")
def _cmd_doctor_skills() -> None:
"""Validate all SKILL.md files and print report."""
from cato.skill_validator import SkillValidator
safe_print("\nCato Skill Validator")
safe_print("=" * 50)
validator = SkillValidator()
agents_dir = _CATO_DIR / "agents"
results = validator.validate_all(agents_dir)
report = validator.format_report(results)
safe_print(report)
def _cmd_doctor_attest() -> None:
"""Emit a signed JSON attestation of Cato security properties."""
import hashlib
import time
vault_file = _CATO_DIR / "vault.enc"
config = CatoConfig.load()
attestation = {
"cato_version": "1.1.0",
"timestamp": time.time(),
"vault_encrypted": vault_file.exists(),
"telemetry_disabled": True, # Cato has zero telemetry by design
"budget_enforced": True, # Hard caps before every LLM call
"audit_enabled": config.audit_enabled,
"safety_mode": config.safety_mode,
"conduit_enabled": config.conduit_enabled,
}
# Sign with SHA-256 of the attestation values (deterministic)
payload = json.dumps(attestation, sort_keys=True, ensure_ascii=True)
sig = hashlib.sha256(payload.encode("utf-8")).hexdigest()
attestation["signature"] = sig
safe_print(json.dumps(attestation, indent=2))
# ---------------------------------------------------------------------------
# cato status
# ---------------------------------------------------------------------------
@main.command("status")
def cmd_status() -> None:
"""Show running state, budget summary, and active channels."""
config = CatoConfig.load()
is_running = _PID_FILE.exists()
safe_print("\nCato Status")
safe_print("=" * 50)
safe_print(f" Config: {getattr(config, '_path', _CATO_DIR / 'config.yaml')}")
safe_print(f" Workspace: {config.workspace_dir}")
if is_running:
pid = _PID_FILE.read_text().strip()
safe_print(f" Daemon: RUNNING (PID {pid})")
else:
safe_print(" Daemon: STOPPED")
safe_print(f" Model: {config.default_model}")
safe_print(f" SwarmSync: {'enabled' if config.swarmsync_enabled else 'disabled'}")
safe_print(f" Safety: {config.safety_mode}")
safe_print(f" Conduit: {'enabled' if config.conduit_enabled else 'disabled'}")
# Listeners: show actual bound port when daemon is running
safe_print("\nListeners")
if is_running and _PORT_FILE.exists():
try:
actual = int(_PORT_FILE.read_text().strip())
safe_print(f" HTTP (Web UI): http://127.0.0.1:{actual}")
safe_print(f" WebSocket: ws://127.0.0.1:{actual}")
except (OSError, ValueError):
safe_print(f" WebChat: port {config.webchat_port} (config)")
else:
safe_print(f" WebChat: port {config.webchat_port} (config)")
safe_print(f" Telegram: {'enabled' if config.telegram_enabled else 'disabled'}")
safe_print(f" WhatsApp: {'enabled' if config.whatsapp_enabled else 'disabled'}")
safe_print("\nBudget")
try:
bm = BudgetManager(
session_cap=config.session_cap,
monthly_cap=config.monthly_cap,
)
status = bm.get_status()
safe_print(f" {bm.format_footer()}")
safe_print(f" Calls this month: {status['monthly_calls']}")
except Exception as exc:
safe_print(f" Could not load budget: {exc}")
safe_print("")
# ---------------------------------------------------------------------------
# cato audit
# ---------------------------------------------------------------------------
@main.command("audit")
@click.option("--session", "session_id", required=True, help="Session ID to export.")
@click.option("--format", "fmt", default="jsonl",
type=click.Choice(["jsonl", "csv"]),
help="Output format.")
@click.option("--verify", is_flag=True, default=False,
help="Verify SHA-256 chain integrity before exporting.")
def cmd_audit(session_id: str, fmt: str, verify: bool) -> None:
"""Export the audit log for a session as JSONL or CSV."""
from cato.audit import AuditLog
log = AuditLog()
log.connect()
if verify:
ok = log.verify_chain(session_id)
status = "CHAIN INTACT" if ok else "CHAIN BROKEN — possible tampering"
safe_print(f"Audit chain verification: {status}")
if not ok:
sys.exit(1)
summary = log.session_summary(session_id)
if summary["count"] == 0:
safe_print(f"No audit records found for session: {session_id}")
return
safe_print(
f"Session {session_id}: {summary['count']} actions, "
f"{summary['total_cost_cents']}c total, "
f"{summary['errors']} errors"
)
safe_print(log.export_session(session_id, fmt=fmt))
# ---------------------------------------------------------------------------
# cato receipt
# ---------------------------------------------------------------------------
@main.command("receipt")
@click.option("--session", "session_id", required=True, help="Session ID.")
@click.option("--format", "fmt", default="text",
type=click.Choice(["text", "jsonl"]),
help="Output format.")
def cmd_receipt(session_id: str, fmt: str) -> None:
"""Show a signed fare receipt for a session."""
from cato.audit import AuditLog
from cato.receipt import ReceiptWriter
log = AuditLog()
log.connect()
writer = ReceiptWriter()
receipt = writer.generate(session_id, log)
if fmt == "jsonl":
safe_print(writer.export_jsonl(receipt))
else:
safe_print(writer.export_text(receipt))
# ---------------------------------------------------------------------------
# cato cron (schedule management)
# ---------------------------------------------------------------------------
@main.group("cron")
def cron_cmd() -> None:
"""Manage scheduled cron tasks for agents."""
pass
@cron_cmd.command("add")
@click.option("--schedule", required=True, help="Cron expression, e.g. '0 9 * * *'")
@click.option("--prompt", required=True, help="Prompt to send to the agent.")
@click.option("--agent", default="default", show_default=True, help="Agent workspace name.")
@click.option("--announce/--no-announce", default=False, show_default=True,
help="Send a message to the channel when the cron fires.")
@click.option("--session", "session_id", default="", help="Session ID (auto-generated if omitted).")
@click.option("--channel", default="web", show_default=True,
help="Channel to deliver announced output to.")
def cron_add(schedule: str, prompt: str, agent: str, announce: bool,
session_id: str, channel: str) -> None:
"""Add a scheduled cron task for an agent.
\b
Example:
cato cron add --schedule "0 9 * * *" --agent personal \\
--prompt "Summarise new emails" --announce
"""
import json as _json, time as _time
try:
from croniter import croniter
if not croniter.is_valid(schedule):
safe_print(f"Invalid cron expression: {schedule!r}")
return
except ImportError:
safe_print("Warning: croniter not installed — schedule not validated. "
"Install with: pip install croniter")
agent_dir = _CATO_DIR / "agents" / agent
agent_dir.mkdir(parents=True, exist_ok=True)
crons_path = agent_dir / "CRONS.json"
crons: list[dict] = []
if crons_path.exists():
try:
crons = _json.loads(crons_path.read_text(encoding="utf-8"))
except Exception:
crons = []
sid = session_id or f"cron-{agent}-{int(_time.time())}"
entry = {
"schedule": schedule,
"prompt": prompt,
"agent_id": agent,
"session_id": sid,
"announce": announce,
"channel": channel,
"created_at": _time.time(),
}
crons.append(entry)
crons_path.write_text(_json.dumps(crons, indent=2, ensure_ascii=False), encoding="utf-8")
safe_print(f"Cron added for agent [{agent}]: {schedule!r} → {prompt!r}")
safe_print(f" session_id: {sid} announce: {announce} total crons: {len(crons)}")
@cron_cmd.command("list")
@click.option("--agent", default="", help="Filter by agent (all agents if omitted).")
def cron_list(agent: str) -> None:
"""List all scheduled cron tasks."""
import json as _json
agents_dir = _CATO_DIR / "agents"
if not agents_dir.exists():
safe_print("No agents directory found.")
return
dirs = [agents_dir / agent] if agent else list(agents_dir.iterdir())
found_any = False
table = Table(title="Cron Schedule", show_lines=True)
table.add_column("#", justify="right", style="dim")
table.add_column("Agent", style="cyan")
table.add_column("Schedule")
table.add_column("Prompt")
table.add_column("Announce")
table.add_column("Session ID", style="dim")
for d in sorted(dirs):
if not d.is_dir():
continue
crons_path = d / "CRONS.json"
if not crons_path.exists():
continue
try:
crons = _json.loads(crons_path.read_text(encoding="utf-8"))
except Exception:
continue
for i, entry in enumerate(crons):
found_any = True
table.add_row(
str(i),
d.name,
entry.get("schedule", ""),
entry.get("prompt", "")[:60],
"yes" if entry.get("announce") else "no",
entry.get("session_id", ""),
)
if found_any:
console.print(table)
else:
safe_print("No cron tasks found. Add one with: cato cron add")
@cron_cmd.command("remove")
@click.option("--agent", required=True, help="Agent workspace name.")
@click.option("--index", required=True, type=int, help="Index from 'cato cron list'.")
def cron_remove(agent: str, index: int) -> None:
"""Remove a cron task by its list index."""
import json as _json
crons_path = _CATO_DIR / "agents" / agent / "CRONS.json"
if not crons_path.exists():
safe_print(f"No CRONS.json found for agent [{agent}].")
return
try:
crons: list[dict] = _json.loads(crons_path.read_text(encoding="utf-8"))
except Exception as exc:
safe_print(f"Could not read CRONS.json: {exc}")
return
if index < 0 or index >= len(crons):
safe_print(f"Index {index} out of range (0..{len(crons)-1}).")
return
removed = crons.pop(index)
crons_path.write_text(_json.dumps(crons, indent=2, ensure_ascii=False), encoding="utf-8")
safe_print(f"Removed cron #{index}: {removed.get('schedule')!r} → {removed.get('prompt')!r}")
@cron_cmd.command("run")
@click.option("--agent", required=True, help="Agent workspace name.")
@click.option("--index", required=True, type=int, help="Index from 'cato cron list' (fires immediately).")
def cron_run(agent: str, index: int) -> None:
"""Fire a cron task immediately (one-shot, ignores schedule)."""
import json as _json, asyncio as _asyncio
crons_path = _CATO_DIR / "agents" / agent / "CRONS.json"
if not crons_path.exists():
safe_print(f"No CRONS.json found for agent [{agent}].")
return
try:
crons: list[dict] = _json.loads(crons_path.read_text(encoding="utf-8"))
except Exception as exc:
safe_print(f"Could not read CRONS.json: {exc}")
return
if index < 0 or index >= len(crons):
safe_print(f"Index {index} out of range (0..{len(crons)-1}).")
return
entry = crons[index]
safe_print(f"Firing cron #{index} for agent [{agent}]: {entry.get('prompt')!r}")
# Run via daemon if it's alive, otherwise run the agent loop directly
if not _PID_FILE.exists():
safe_print("Daemon not running — executing in-process (no channel delivery).")
_run_cron_in_process(entry, agent)
else:
safe_print("Daemon is running — injecting via WebSocket.")
_run_cron_via_ws(entry)
def _run_cron_in_process(entry: dict, agent: str) -> None:
"""Run a cron task in-process when the daemon is not running."""
import asyncio as _asyncio
from cato.config import CatoConfig as _Cfg
from cato.budget import BudgetManager as _BM
from cato.vault import Vault as _Vault
from cato.agent_loop import AgentLoop
from cato.core.context_builder import ContextBuilder
from cato.core.memory import MemorySystem
cfg = _Cfg.load()
vault_path = _CATO_DIR / "vault.enc"
vault = _Vault(vault_path=vault_path) if vault_path.exists() else None
budget = _BM(session_cap=cfg.session_cap, monthly_cap=cfg.monthly_cap)
memory = MemorySystem(agent_id=agent)
ctx = ContextBuilder(max_tokens=cfg.context_budget_tokens)
loop = AgentLoop(config=cfg, budget=budget, vault=vault, memory=memory, context_builder=ctx)
async def _run() -> None:
text, footer = await loop.run(
session_id=entry.get("session_id", f"cron-{agent}"),
message=entry.get("prompt", ""),
agent_id=agent,
)
safe_print(f"\n--- Cron result ---\n{text}\n{footer}")
try:
_asyncio.run(_run())
except Exception as exc:
safe_print(f"Cron run failed: {exc}")
def _run_cron_via_ws(entry: dict) -> None:
"""Inject a cron task into the running daemon via WebSocket."""
import asyncio as _asyncio, json as _json
try:
import websockets as _ws
except ImportError:
safe_print("websockets not installed — cannot inject via daemon. pip install websockets")
return
_config = CatoConfig.load()
_http_port = _discover_http_port(_config)
async def _send() -> None:
uri = f"ws://127.0.0.1:{_http_port}/ws"
try:
async with _ws.connect(uri) as ws:
payload = _json.dumps({
"type": "message",
"text": entry.get("prompt", ""),
"session_id": entry.get("session_id", "cron-manual"),
"agent_id": entry.get("agent_id", "default"),
"channel": entry.get("channel", "web"),
})
await ws.send(payload)
safe_print("Cron task injected into running daemon.")
except Exception as exc:
safe_print(f"Could not reach daemon WebSocket: {exc}")
_asyncio.run(_send())
# ---------------------------------------------------------------------------
# cato node
# ---------------------------------------------------------------------------
@main.group("node")
def node_cmd() -> None:
"""Manage remote node devices and their capabilities."""
pass
@node_cmd.command("list")
def node_list() -> None:
"""List currently registered nodes (requires daemon to be running)."""
import asyncio as _asyncio, json as _json
if not _PID_FILE.exists():
safe_print("Daemon is not running. Start with: cato start")
return
try: