Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
1766 lines (1512 loc) · 84.8 KB
/
Copy path__init__.py
File metadata and controls
1766 lines (1512 loc) · 84.8 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
"""Crew: kanban roles with a contract, one writer per card and independent verification.
The owner's surface is five entries:
/crew <what you want> intake by the coordinator in this chat (the `crew` skill). It checks
the ask critically, asks numbered questions while any contract field is
missing and opens the card (kanban_create, guarded and completed by this
plugin) only once the contract is complete, then the turn ends.
/crew-status the cards in flight, each with the coordinator's last decision and, when a
card waits on the owner, its one question.
/crew-graph <card> one card's flow graph: terminal box graph, two frames apart (--watch), or an
HTML file (--html).
/crew-stop [<card>] park one card, or every open crew card: worker killed, card held, history kept
(--archive drops one card for good).
/crew-unstuck <card> the owner's fallback when the coordinator gave up: a triage card leaves triage
unchanged, a blocked card (or one /crew-stop parked) is unblocked.
/crew-diagnose [state] a skill like the intake, so it runs in the invoking session's own turn: every
card in one board state with its id and reason, then how each would resume.
Read-only - it diagnoses, it never retries, unblocks or dispatches.
The plugin commands (/crew-status, /crew-graph, /crew-stop, /crew-unstuck) are deterministic and make no model call, and
each option is its own command, so the command list in /help and in every platform menu IS the option
list. Install and role checks are not commands: `python3 <crew repo>/install.py --check [--profile P]`
(`hermes plugins doctor` only validates that a plugin loads and registers; it prints nothing about roles,
crons or profile drift).
`/crew` is owned by the skill: a plugin slash command is always handled before skills and its
handler can only return text (gateway/run_inbound.py and cli.py treat any registered plugin
command as handled), so the plugin registers `crew-status`, `crew-graph` and `crew-stop`, never `crew`.
Once a card is open the coordinator owns it: the dispatch-tick hook below starts
scripts/crew_coordinator.py (one detached pass, no model unless a card needs a decision) and that pass heals,
retries, rescopes, splits or asks the owner one question. Nothing else routes a blocked card anywhere.
In role profiles (config `crew.role` set by the installer) the plugin also enforces the per-card
token budget as a hard stop and, for the verifier, blocks write/send commands on the terminal.
Roles come from $HERMES_HOME/roles/crew/roles.json; the installer records the package source
under `crew.source_dir`, which the scripts use to find the package when an installed copy lacks one.
"""
import importlib.util
import json
import logging
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import time
def _default_home():
"""Hermes's own answer for its home (this module runs inside Hermes: %LOCALAPPDATA%\\hermes on native Windows,
~/.hermes elsewhere); the POSIX default when Hermes' constants are not importable (a unit test)."""
try:
from hermes_constants import get_hermes_home
return str(get_hermes_home())
except Exception: # noqa: BLE001 - any failure to ask Hermes means "use the documented default"
return os.path.expanduser("~/.hermes")
HOME = os.environ.get("HERMES_HOME") or _default_home()
HERE = os.path.dirname(os.path.abspath(__file__))
USAGE = ("Usage: /crew <what you want> (intake, asks its questions) | /crew-status"
" | /crew-graph <card id|latest> [--watch N | --html [PATH]] | /crew-stop [<card id>] [--archive] [--dry-run] | /crew-unstuck <card id>"
" | /crew-diagnose [state] (read-only)")
# One slash command per option: the option lives in the command name, so /crew-status takes no
# argument and an argument-less option is discoverable in /help instead of hidden behind a sub.
# Each entry: (command name, option, args hint, one-line description for /help and the menus).
# The ORDER is importance, not alphabet. /crew itself and /crew-diagnose are skills and never a row here
# (a plugin command would shadow /crew, and /crew-diagnose must run in the invoking session's own turn),
# so the first row is the most important crew option, and any surface that leads with /crew puts this
# table right behind it (install.py CREW_MENU_ORDER is the same list, skills included).
COMMANDS = [
("crew-status", "status", "", "Crew cards in flight: the coordinator's last decision and any question for you"),
("crew-graph", "graph", "<card id|latest> [--watch N | --html [NAME]]",
"One card's flow graph: terminal box graph, two frames apart (--watch), or an HTML file (--html)"),
("crew-stop", "stop", "[<card id>] [--archive] [--dry-run]",
"Park one card, or every open crew card: kill its worker, close its session, hold the card (/crew-unstuck "
"continues it; --archive drops one for good)"),
("crew-unstuck", "unstuck", "<card id>",
"Put a stuck or parked card back in the queue: out of triage with no change, or unblock it"),
("crew-safety", "safety", "[brave|safe]",
"How careful unattended proof commands are: no argument shows the mode, brave stops asking, safe restores it"),
("crew-proof", "proof", "<card> <yes|brave>",
"Answer a card's proof question: yes accepts a proposed proof command, brave runs a blocked one"),
]
def _hermes_bin():
found = os.environ.get("HERMES_BIN") or _which_hermes()
if sys.platform == "win32" and not os.environ.get("HERMES_BIN"):
card = _card_tool() # a .cmd launcher cuts a multi-line argument at its first newline
if card is not None and (not found or card.is_batch_launcher(found)):
found = card.hermes_exe() or found
return found or "hermes"
def _which_hermes():
"""The first `hermes` on PATH this OS can actually run.
On Windows PATH can lead with a 0-byte stub or the POSIX launcher script, and either makes every
`hermes config get` fail silently - the plugin then reads config as None."""
exts = [e.lower() for e in os.environ.get("PATHEXT", ".EXE;.CMD;.BAT").split(os.pathsep)]
runnable = (".exe", ".cmd", ".bat")
for entry in os.environ.get("PATH", "").split(os.pathsep):
if not entry:
continue
for ext in (exts or [""]):
cand = os.path.join(entry, "hermes" + ext)
try:
if not (os.path.isfile(cand) and os.path.getsize(cand) > 0):
continue
except OSError:
continue
if sys.platform == "win32":
if os.path.splitext(cand)[1].lower() not in runnable:
continue
return cand
return shutil.which("hermes")
def _tasks_db():
"""The active board's kanban.db, or None: scripts/crew_card.py kanban_db() is the one resolver."""
resolve = getattr(_card_tool(), "kanban_db", None)
return resolve() if callable(resolve) else None
def _card_body(task_id):
db = _tasks_db()
if not db or not task_id:
return ""
try:
conn = sqlite3.connect("file:%s?mode=ro" % db, uri=True)
row = conn.execute("select body from tasks where id = ?", (task_id,)).fetchone()
conn.close()
return (row or [""])[0] or ""
except Exception:
return ""
WRITER_ROLES = ("worker", "content")
CREW_ROLES = ("coordinator", "worker", "content", "verifier")
def _card_tool():
"""Load scripts/crew_card.py (the plugin's own copy, see _script_path) as a module."""
return _load_script("crew_card.py", "crew_card_tool")
_RESULT_TOOL = None
def _result_tool():
"""scripts/crew_result.py (the one reader of a tool result row), loaded once per process: the thrash
stop calls it after every tool call, so it must not re-read the file each time."""
global _RESULT_TOOL
if _RESULT_TOOL is None:
_RESULT_TOOL = _load_script("crew_result.py", "crew_result_tool")
return _RESULT_TOOL
def _load_script(name, module_name):
path = _script_path(name)
if not path:
return None
spec = importlib.util.spec_from_file_location(module_name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
# ---------------------------------------------------------------- the option commands
def _session_origin():
"""`<platform>:<chat id>` of the chat this command came from, or "" off a chat (CLI, cron,
kanban worker). The card carries it as `Origin:` so its done report goes back there."""
try:
from gateway.session_context import get_session_env
platform = (get_session_env("HERMES_SESSION_PLATFORM", "") or "").strip().lower()
chat = (get_session_env("HERMES_SESSION_CHAT_ID", "") or "").strip()
except Exception:
return ""
if os.environ.get("HERMES_KANBAN_TASK") or not platform or not chat:
return ""
if platform in ("cli", "tui", "desktop", "kanban", "cron", "api_server", "local", "webhook"):
return ""
return "%s:%s" % (platform, chat)
def _cmd_status(_rest=""):
tool = _card_tool()
if tool is None:
return "crew_card.py not found - run install.py --check"
try:
return tool.status_text()
except Exception as exc: # noqa: BLE001 - a status read must never break the chat turn
return "crew-status failed: %s" % exc
# The one pass that walks the whole board rather than one card: (script, timeout seconds).
_MAINTENANCE = {
# stop kills processes and waits for each signal to land, so it gets the longer ceiling
"stop": ("crew_stop.py", 600),
}
def _cmd_maintenance(action, rest):
"""Run the whole-board stop pass and return its own output, not a summary of it.
The script is the proof: its lines say what it lifted, fixed or decided. Arguments are passed
through as separate words (no shell), so a typo comes back as the script's own usage error.
"""
script, timeout = _MAINTENANCE[action]
path = _script_path(script)
if not path:
return "%s not found - run install.py --check" % script
try:
r = subprocess.run([sys.executable, path] + [a for a in (rest or "").split() if a],
capture_output=True, text=True, errors="replace",
timeout=timeout, env=_utf8_env(), encoding="utf-8")
except subprocess.TimeoutExpired:
return "%s timed out after %ds" % (action, timeout)
except Exception as exc: # noqa: BLE001 - a pass must never break the chat turn
return "%s failed: %s" % (action, exc)
out = ((r.stdout or "") + (r.stderr or "")).strip()
if not out:
return "%s: nothing to do (exit %d)" % (action, r.returncode)
return out if r.returncode == 0 else "%s (exit %d):\n%s" % (action, r.returncode, out)
# Hermes approvals.mode that "brave" sets (hermes_cli config: manual | smart | off). "safe" puts back what each
# profile had before brave (kept in <base home>/crew/safety-approvals.json), "manual" when nothing was kept.
BRAVE_APPROVALS, SAFE_FALLBACK = "off", "manual"
def _cmd_safety(rest=""):
"""/crew-safety [brave|safe]: show, or set for good, how careful unattended proofs are.
The mode lives where Hermes keeps it - approvals.mode in each crew role profile - so one switch covers
the proofs (crew_safety.permanent_mode reads the coordinator's) and the workers' own terminal tool."""
tool = _card_tool()
if tool is None:
return "crew_card.py not found - run install.py --check"
want = (rest or "").strip().lower()
if not want:
mode = tool.crew_safety.permanent_mode()
return ("crew proof safety: %s. %s Change it with /crew-safety brave or /crew-safety safe." % (mode, (
"Nothing stops a proof except Hermes's hardline list and your approvals.deny rules."
if mode == "brave" else "A proof Hermes flags as dangerous stops the card and asks you.")))
if want not in ("brave", "safe"):
return "usage: /crew-safety [brave|safe]"
names = [r.get("name") for r in tool.roles_defaults().get("roles", []) if r.get("name")] or list(CREW_ROLES)
state_path = os.path.join(tool.base_home(), "crew", "safety-approvals.json")
try:
with open(state_path, encoding="utf-8") as fh:
kept = json.load(fh)
except (OSError, ValueError):
kept = {}
def hermes(profile, *args):
return subprocess.run([_hermes_bin(), "-p", profile, "config"] + list(args), capture_output=True, text=True,
timeout=60, encoding="utf-8", errors="replace")
shown, failed = [], []
for name in names:
profile = tool.profile_prefix() + name
if not tool.profile_exists(profile):
continue
try:
got = hermes(profile, "get", "approvals.mode")
cur = (got.stdout or "").strip().splitlines()[-1].strip() if got.returncode == 0 and (got.stdout or "").strip() else ""
if want == "brave":
target = BRAVE_APPROVALS
if cur and cur != BRAVE_APPROVALS:
kept[profile] = cur # what safe puts back
elif cur.lower() in ("off", "false"):
target = kept.pop(profile, None) or SAFE_FALLBACK
else:
target = cur or SAFE_FALLBACK # already careful: leave the owner's value alone
if target != cur:
if hermes(profile, "set", "approvals.mode", target).returncode != 0:
raise OSError("config set failed")
shown.append("%s: %s -> %s" % (profile, cur or "unset", target))
except Exception: # noqa: BLE001 - a missing hermes binary is a failed profile, not a broken chat turn
failed.append(profile)
try:
os.makedirs(os.path.dirname(state_path), exist_ok=True)
with open(state_path, "w", encoding="utf-8") as fh:
json.dump(kept, fh, indent=1)
except OSError:
failed.append("(could not save %s)" % state_path)
text = "crew proof safety: %s (approvals.mode %s)." % (want, "; ".join(shown) or "no profile")
if failed:
text += " FAILED on %s." % ", ".join(failed)
if want == "brave":
text += (" Brave also lets the workers' own terminal commands run unprompted, not only the proofs; "
"Hermes's hardline list and your approvals.deny rules still apply.")
return text
def _cmd_proof(rest):
"""/crew-proof <card> <yes|brave>: the owner's answer to a card's proof question. The one place a proof
command other than the opening one, or a flagged one, gets the owner's go-ahead; a worker, the verifier or
the coordinator can never run it (owner_proof_answer refuses inside any agent run)."""
words = (rest or "").split()
if not words:
return "usage: /crew-proof <card> <yes|brave>"
card = words[0]
flag = words[1].strip().lower() if len(words) > 1 else ""
if flag not in ("yes", "brave"):
return "usage: /crew-proof <card> <yes|brave>"
tool = _card_tool()
if tool is None:
return "crew_card.py not found - run install.py --check"
try:
return tool.owner_proof_answer(card, brave=(flag == "brave"))
except Exception as exc: # noqa: BLE001 - an owner answer must never break the chat turn
return "crew-proof failed: %s" % exc
def _option_handler(action):
"""One slash command per option: the name carries the option, the text after it is its args."""
run = {"status": _cmd_status, "graph": _cmd_graph, "unstuck": _cmd_unstuck,
"stop": lambda rest: _cmd_maintenance("stop", rest), "safety": _cmd_safety,
"proof": _cmd_proof}[action]
def handler(raw_args):
return run((raw_args or "").strip())
return handler
def _config_get(key):
try:
r = subprocess.run([_hermes_bin(), "config", "get", key],
capture_output=True, text=True, timeout=30, encoding="utf-8", errors="replace")
out = r.stdout.strip()
return out if r.returncode == 0 and out else None
except Exception:
return None
def _script_path(name):
"""A crew script from the plugin's own tree: <plugin dir>/scripts first, then `crew.source_dir` (the package
checkout the installer ran from). Never $HERMES_HOME/scripts: that directory is the owner's, and code found
there is not code this plugin shipped."""
path = os.path.join(HERE, "scripts", name)
if os.path.exists(path):
return path
src = _config_get("crew.source_dir")
if src:
path = os.path.join(src, "scripts", name)
if os.path.exists(path):
return path
return None
_WALLS_SEEN = set()
def crew_quota_reroute(status_code=None, error=None, model=None, provider=None, **_kw):
"""api_request_error observer: a card never keeps spinning on a model that hit its quota wall.
The wall is recorded on the card, the card is re-pinned on a fresh Jev pick over the agent-floor menu
(the router's own ledger already holds the spent model) - or, when nothing on that menu is live, its
pin is cleared so the role profile's own model runs - and the next run continues from the previous
run's work through the crew hand-off. When there is nowhere to move and the wall repeats, the card is
stopped with a transient block (the coordinator loop's) instead of burning more stalled attempts.
"""
card = os.environ.get("HERMES_KANBAN_TASK")
if not card or not _crew_role():
return None
low = ("%s %s" % (status_code or "", error or "")).lower()
if not ("429" in low or "rate limit" in low or "rate_limit" in low or "quota" in low):
return None
key = (card, str(os.environ.get("HERMES_KANBAN_RUN_ID") or ""), str(model or ""))
if key in _WALLS_SEEN:
return None
_WALLS_SEEN.add(key)
tool = _card_tool()
if tool is None or not hasattr(tool, "reroute_after_wall"):
return None
try:
res = tool.reroute_after_wall(card, model=model, provider=provider)
except Exception as exc: # noqa: BLE001 - never break the worker's own error path
_log_quota_failure(card, exc)
return None
if res.get("action") == "rerouted":
to = res.get("to") or {}
return {"context": "[crew] your model hit a quota wall. The card has been re-pinned to "
"%s/%s for the next run, and that run is handed the work already done, "
"so nothing is repeated." % (to.get("provider"), to.get("model"))}
if res.get("action") == "unpinned":
return {"context": "[crew] your model hit a quota wall and no free model can carry this card. The "
"pin is cleared: the next run uses the role profile's own model and is handed "
"the work already done, so nothing is repeated."}
return None
def _log_quota_failure(card, exc):
try:
path = os.path.join(HOME, "crew", "quota-errors.log")
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "a", encoding="utf-8") as fh:
fh.write("%s card=%s %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), card, exc))
except Exception:
pass
def _handoff_text(card):
"""The previous runs' work for a retried card, built by scripts/crew_handoff.py."""
path = _script_path("crew_handoff.py")
if not path:
return ""
try:
r = subprocess.run([sys.executable, path, "--card", str(card), "--record"],
capture_output=True, text=True, timeout=60, encoding="utf-8", errors="replace")
except Exception: # noqa: BLE001 - a hand-off must never break the worker's turn
return ""
return (r.stdout or "").strip()
_HANDOFF_GIVEN = set()
def crew_handoff_hook(user_message=None, session_id=None, **_kw):
"""A worker picking up a card that already ran: hand it the work already done, once per session.
Without this the new run (possibly on a different model - the router's pick can change between
attempts) re-explores everything the previous run did.
"""
card = os.environ.get("HERMES_KANBAN_TASK")
role = _crew_role()
if not card or not role:
return None
key = str(session_id or card)
if key in _HANDOFF_GIVEN:
return None
_HANDOFF_GIVEN.add(key)
text = "\n\n".join(t for t in (_handoff_text(card), _lessons_block(role)) if t)
if not text:
return None
return {"context": text}
def _lessons_block(role=None):
"""The lessons file (scripts/crew_lessons.py) as context: a role's own plus `all`, or just `all` for the intake."""
try:
mod = _load_script("crew_lessons.py", "crew_lessons_tool")
if mod is None:
return ""
return mod.block(role) if role else mod.intake_block()
except Exception: # noqa: BLE001 - no lessons is the old behaviour, never a broken turn
return ""
def _graph_script():
return _script_path("crew_graph.py")
def _utf8_env():
"""Child env that prints box-drawing and arrows as UTF-8: a Windows console defaults to the locale
codec (cp1253 here), which cannot encode them and kills the graph mid-print. Assign, never setdefault:
a parent that already exported PYTHONIOENCODING=cp1253 would otherwise pass it straight through."""
env = dict(os.environ)
env["PYTHONIOENCODING"] = "utf-8"
env["PYTHONUTF8"] = "1"
return env
def _run_graph(args, timeout=120):
script = _graph_script()
if not script:
return None, "crew_graph.py not found - run install.py --check"
cmd = [sys.executable, script] + list(args)
try:
r = subprocess.run(cmd, capture_output=True, text=True, errors="replace",
timeout=timeout, env=_utf8_env(), encoding="utf-8")
except subprocess.TimeoutExpired:
return None, "crew graph timed out"
except Exception as exc:
return None, "crew graph failed: %s" % exc
return r.returncode, ((r.stdout or "") + (r.stderr or "")).strip()
def _fence(s):
return "```\n%s\n```" % s
def _cmd_unstuck(rest):
"""The owner's fallback when the coordinator gave up on a card (crew_card.unstuck_card)."""
words = (rest or "").split()
if len(words) != 1:
return "Usage: /crew-unstuck <card id>"
tool = _card_tool()
if tool is None:
return "crew_card.py not found - run install.py --check"
try:
return tool.unstuck_card(words[0])[1]
except Exception as exc: # noqa: BLE001 - a board call must never break the chat turn
return "crew-unstuck failed: %s" % exc
def _cmd_graph(rest):
"""One option, three modes: the terminal graph, `--watch N` (two frames), `--html [PATH]` (a file).
The modes are flags on /crew-graph, not commands of their own."""
parts = (rest or "").strip().split()
card = parts[0] if parts and not parts[0].startswith("-") else "latest"
words = parts[1:] if parts and not parts[0].startswith("-") else parts
watch, html, i = None, None, 0
while i < len(words):
word = words[i]
nxt = words[i + 1] if i + 1 < len(words) else ""
if word in ("--watch", "-w"):
if re.match(r"^\d+(\.\d+)?$", nxt):
watch, i = max(1.0, min(float(nxt), 120.0)), i + 2
else:
watch, i = 4.0, i + 1
continue
if word in ("--html", "--page"):
if nxt and not nxt.startswith("-"):
html, i = nxt, i + 2
else:
html, i = "", i + 1
continue
i += 1
if html is not None:
# the file lands in the profile's own scratch dir and nowhere else: a bare file name only, so a
# chat command cannot make the plugin write to an arbitrary path
outdir = os.path.join(HOME, "cache", "scratch")
if html and (html != os.path.basename(html) or html in (".", "..")):
return "--html takes a file name only (it is written under %s)" % outdir
os.makedirs(outdir, exist_ok=True)
_code, out = _run_graph(["--card", card, "--html", html, "--outdir", outdir])
return out
if watch:
c1, f1 = _run_graph(["--card", card])
if c1 is None:
return f1
time.sleep(watch)
c2, f2 = _run_graph(["--card", card])
head = "live watch: two frames %.0fs apart\n" % watch
return _fence("%s\n--- frame 1 ---\n%s\n--- frame 2 ---\n%s" % (
head, f1 if c1 == 0 else "(error)", f2 if c2 == 0 else "(error)"))
code, out = _run_graph(["--card", card])
if code is None or code != 0:
return out
return _fence(out)
def _profile_name():
h = os.path.abspath(HOME)
if os.path.basename(os.path.dirname(h)) == "profiles":
return os.path.basename(h)
return "default"
# ---------------------------------------------------------------- role profile guards
# Active only in a role profile (config crew.role) and only inside a dispatcher-spawned worker
# (HERMES_KANBAN_TASK set), so the owner's own chat profile is never affected.
_ROLE = None
_BUDGET_CACHE = {}
ALWAYS_ALLOWED_OVER_BUDGET = {"kanban_block", "kanban_comment", "kanban_show", "kanban_heartbeat"}
# Allowed over budget only when the card passes the close rule (a PASS line for its proof command).
CLOSE_TOOLS_AFTER_PASS = {"kanban_complete", "kanban_request_review", "kanban_block"}
VERIFIER_BLOCKED_TOOLS = {"write_file", "patch", "skill_manage", "memory", "kanban_create", "kanban_link",
"cronjob_manage", "delegate_task", "execute_code", "send_message", "crew_plan"}
# The coordinator's decision turn (crew_coordinator.py sets CREW_COORDINATOR_TURN) reads and decides; the loop
# applies the answer. The same write filter as the verifier, plus the verbs that would move the card itself.
COORDINATOR_TURN_BLOCKED = VERIFIER_BLOCKED_TOOLS | {"kanban_complete", "kanban_block", "kanban_unblock",
"kanban_request_review", "kanban_request_changes",
"crew_plan", "crew_verdict", "crew_progress", "crew_lesson"}
# Terminal commands that write, move, delete, commit, publish or send. The proof command itself
# runs inside the verdict (a subprocess), so it is not subject to this filter.
VERIFIER_WRITE_RX = re.compile(
r"(?<![0-9&])>>?(?!&)|\btee\b|\brm\b|\bmv\b|\bcp\b|\bdd\b|\bchmod\b|\bchown\b|\bln\b|\btouch\b|"
r"\bmkdir\b|\btruncate\b|\binstall\b|\bsed\s+-i|\bperl\s+-i|\bgit\s+(commit|push|add|reset|checkout|"
r"merge|rebase|tag|stash|clean|restore|rm|mv)\b|\bcurl\b[^|;]*\s(-X\s*(POST|PUT|PATCH|DELETE)|"
r"--data|-d\s|-F\s|--upload-file|-T\s)|\bwget\b[^|;]*--post|\b(ssh|scp|rsync|sendmail|mail|mutt)\b|"
r"\bhermes\b[^|;]*\b(send|config\s+set|kanban\s+(create|complete|edit|assign|archive|link))\b|"
r"\bsystemctl\b|\bkill\b|\bpip\b|\bnpm\b|\bapt\b|\bsudo\b|\bsqlite3\b|\b(?:python3?|python)\s+-c\b")
# Direct board/consent writes a role agent must never make from its own shell: the sqlite3 CLI, or anything
# (an inline python one-liner, a heredoc) that names the consent function or the board's event tables/kinds.
# Consent and board state change only through the kernel tools and crew scripts, never a raw shell write.
BOARD_WRITE_RX = re.compile(r"\bsqlite3\b|\b(?:owner_proof_answer|proof_confirm|task_events|kanban\.db|kanban_db)\b",
re.I)
# The same write arriving as a FILE: a shell it cannot name the board in, but a script it writes can. A write whose
# body writes the board - an INSERT/UPDATE/DELETE naming a board table, or a call to the consent function - is
# refused for every role, so the script never exists to be run. Reads are untouched: a proof script may select.
BOARD_WRITE_FILE_RX = re.compile(
r"\b(?:insert|replace)\s+into\s+[^\n]{0,30}?\b(?:task_events|task_runs|tasks)\b"
r"|\bdelete\s+from\s+[^\n]{0,30}?\b(?:task_events|task_runs|tasks)\b"
r"|\bupdate\s+[^\n]{0,30}?\b(?:task_events|task_runs|tasks)\b\s+set\b"
r"|\bowner_proof_answer\b", re.I)
# The safety switch and a crew profile's own config are the owner's: `/crew-safety` writes approvals.mode in the
# crew profiles from the owner's session, never through an agent tool call. A role agent flipping it from its
# terminal would make every proof brave, exactly like forging consent, so every crew role is refused here.
CREW_CONFIG_WRITE_RX = re.compile(
r"\bhermes\b[^|;]{0,200}?\bconfig\s+(?:set|unset|edit|import|reset)\b"
r"|\bapprovals\.mode\b", re.I)
CREW_PROFILE_CONFIG_RX = re.compile(r"(?:^|/)profiles/crew-[^/]+/config\.yaml$", re.I)
def _crew_config_write_attempt(tool_name, args):
"""True when this call writes a crew profile's config or flips approvals.mode: a shell running
`hermes ... config set ...`, or a file write to a crew role profile's config.yaml."""
args = args if isinstance(args, dict) else {}
if tool_name == "terminal":
return bool(CREW_CONFIG_WRITE_RX.search(str(args.get("command") or "")))
if tool_name in FILE_WRITE_TOOLS:
return any(CREW_PROFILE_CONFIG_RX.search(p) for p in _file_tool_paths(args))
return False
def _board_write_attempt(tool_name, args):
"""True when this call writes board state or proof consent, however it is dressed: a shell command that names
the board (BOARD_WRITE_RX) or a file write whose body writes it (BOARD_WRITE_FILE_RX)."""
args = args if isinstance(args, dict) else {}
if tool_name == "terminal":
return bool(BOARD_WRITE_RX.search(str(args.get("command") or "")))
if tool_name in FILE_WRITE_TOOLS:
body = " ".join(str(args.get(k) or "") for k in ("content", "patch", "new_string", "new_str", "old_string"))
return bool(BOARD_WRITE_FILE_RX.search(body))
return False
# Proof scripts live in a `.crew/` folder and belong to the verifier: a writer never creates or changes one, and the
# verifier's file tools reach nothing else.
CREW_DIR_RX = re.compile(r"(?:^|[\s'\"=/\\])\.crew(?:[/\\]|$)")
PATCH_FILE_RX = re.compile(r"^\*\*\* (?:Update|Add|Delete|Move to)[^:\n]*:\s*(.+)$", re.M)
FILE_WRITE_TOOLS = ("write_file", "patch")
def _file_tool_paths(args):
"""The paths a file tool call targets, with Windows backslashes read as slashes so the path guards
(CREW_PROFILE_CONFIG_RX, CREW_DIR_RX) see C:\\x\\profiles\\crew-w\\config.yaml exactly like the POSIX form."""
found = [str(args.get("path") or "")] + PATCH_FILE_RX.findall(str(args.get("patch") or ""))
return [p.replace("\\", "/") for p in found if p.strip()]
def _only_crew_dir(args):
"""A file tool call whose every target is under `.crew/`: the one write the verifier has."""
paths = _file_tool_paths(args if isinstance(args, dict) else {})
return bool(paths) and all(CREW_DIR_RX.search(p) for p in paths)
def _writes_crew_dir(tool_name, args):
"""True when this call writes under a `.crew/` folder: write_file / patch on such a path (a V4A patch names its
files in `*** Update File:` lines) or a terminal command that both writes (VERIFIER_WRITE_RX) and names `.crew/`.
Reading a proof script is not a write."""
args = args if isinstance(args, dict) else {}
if tool_name in FILE_WRITE_TOOLS:
return any(CREW_DIR_RX.search(p) for p in _file_tool_paths(args))
if tool_name == "terminal":
cmd = str(args.get("command") or "")
return bool(CREW_DIR_RX.search(cmd) and VERIFIER_WRITE_RX.search(cmd))
return False
def _crew_role():
global _ROLE
if _ROLE is None:
_ROLE = ""
try:
with open(os.path.join(HOME, "config.yaml"), encoding="utf-8") as fh:
inside = False
for line in fh:
if re.match(r"^crew:\s*$", line):
inside = True
continue
if inside:
if line.strip() and not line.startswith(" "):
break
m = re.match(r"^\s+role:\s*['\"]?([a-z]+)", line)
if m:
_ROLE = m.group(1)
break
except OSError:
pass
return _ROLE
def _budget_file(card):
safe = re.sub(r"[^A-Za-z0-9_.-]", "_", str(card))
return os.path.join(HOME, "crew", "budget", safe + ".json")
def _card_budget(card):
if card not in _BUDGET_CACHE:
m = re.search(r"^\s*Budget:\s*([0-9]+)", _card_body(card), re.M | re.I)
_BUDGET_CACHE[card] = int(m.group(1)) if m else None
return _BUDGET_CACHE[card]
def _budget_used(card):
try:
with open(_budget_file(card), encoding="utf-8") as fh:
return int(json.load(fh).get("used", 0))
except Exception:
return 0
CACHE_READ_WEIGHT = 0.1 # a cache read bills at a tenth of the input rate (Anthropic)
CACHE_WRITE_WEIGHT = 1.25 # a cache write bills at 1.25x the input rate (Anthropic)
def _billed_tokens(usage):
"""One call's billed-token count for the card budget.
The budget is a billed-token meter, not raw prompt volume: summing ``total_tokens`` charges a
cache read at the full input rate. Measured on a whole-corpus audit card: 17 calls booked
1,928,928 (1,660,642 of it cache-read, 86.1%) against 5,344 output tokens, so a 1,500,000
ceiling bought ~13 calls while the billed equivalent of the same run was 500,077. Providers
that report no cache buckets keep the old ``total_tokens`` behaviour.
"""
try:
total = int(usage.get("total_tokens") or 0)
except Exception:
total = 0
try:
cache_read = int(usage.get("cache_read_tokens") or 0)
cache_write = int(usage.get("cache_write_tokens") or 0)
except Exception:
cache_read = cache_write = 0
if not (cache_read or cache_write):
return total
try:
plain = int(usage.get("input_tokens") or 0) + int(usage.get("output_tokens") or 0)
except Exception:
plain = max(0, total - cache_read - cache_write)
return int(round(plain + CACHE_READ_WEIGHT * cache_read + CACHE_WRITE_WEIGHT * cache_write))
def crew_budget_account(usage=None, **kwargs):
"""post_api_request observer: add this call's billed tokens to the card's running total."""
card = os.environ.get("HERMES_KANBAN_TASK")
if not card or not _crew_role() or not isinstance(usage, dict):
return None
tokens = _billed_tokens(usage)
if not tokens:
return None
try:
raw = int(usage.get("total_tokens") or 0)
except Exception:
raw = 0
try:
path = _budget_file(card)
os.makedirs(os.path.dirname(path), exist_ok=True)
try:
with open(path, encoding="utf-8") as fh:
prev = json.load(fh)
if not isinstance(prev, dict):
prev = {}
except Exception:
prev = {}
def _int(key):
try:
return int(prev.get(key) or 0)
except (TypeError, ValueError):
return 0
data = dict(prev)
data.update({"card": card, "used": _int("used") + tokens, "budget": _card_budget(card),
"raw_total": _int("raw_total") + raw, "calls": _int("calls") + 1,
"raw_last": raw, "profile": _profile_name(), "updated": time.time()})
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(data, fh)
os.replace(tmp, path)
except Exception:
pass
return None
def _close_ok(card):
"""(ok, reason): the crew close rule for this card (crew_card.close_check), read from the one verdict log."""
tool = _card_tool()
if tool is None:
return True, "crew_card.py not found"
body = _card_body(card)
return tool.close_check(card, body, tool.claimed_at(card))
def _verdict_fails(card):
"""FAIL lines on this card since it was last started over (crew_card.rework_fails)."""
tool = _card_tool()
return tool.rework_fails(card) if tool is not None else 0
def _stop_message(lead, kind, reason):
"""Every hard stop names the exact kanban_block call that ends the run, so the model never has to work out
how to stop: the budget stop, the rework cap and the thrash stop all read through this one sentence."""
return "%s Call kanban_block(kind='%s', reason='%s') and end." % (lead, kind, reason)
# Failed tool calls per card, this process only: a worker process is one card run, and the count is about the
# run in front of it, not about the card's history. kanban_* tools are not counted (a refused kanban_complete
# is the rule working). Two rules read it: a streak (an ok result starts the count again) and a rate (failures
# among the last few calls, for the run whose failures are scattered between ok results).
_FAIL_STREAK = {}
_FAIL_WINDOW = {} # card -> the last `failure_window_calls` results, True where the call failed
_FAIL_LIMIT = None
_WINDOW_LIMITS = None
def _max_consecutive_failures():
"""roles.json `max_consecutive_failures` through crew_card, read once per process."""
global _FAIL_LIMIT
if _FAIL_LIMIT is None:
tool = _card_tool()
_FAIL_LIMIT = int(tool.max_consecutive_failures()) if tool is not None else 5
return _FAIL_LIMIT
def _window_limits():
"""(max_window_failures, failure_window_calls) from roles.json through crew_card, read once per process."""
global _WINDOW_LIMITS
if _WINDOW_LIMITS is None:
tool = _card_tool()
_WINDOW_LIMITS = ((int(tool.max_window_failures()), int(tool.failure_window_calls()))
if tool is not None else (8, 25))
return _WINDOW_LIMITS
def crew_thrash_hook(tool_name=None, result=None, **kwargs):
"""post_tool_call observer in a role profile: count failed tool results for the card, in a row and in a window.
The classifier is crew_result.result_state, the one the dashboard's steps use, so a step the panel draws
as failed is a step this counts as failed.
"""
card = os.environ.get("HERMES_KANBAN_TASK")
if not card or not _crew_role() or not tool_name or str(tool_name).startswith("kanban_"):
return None
reader = _result_tool()
if reader is None:
return None
state, note, _out = reader.result_row(result)
window = _FAIL_WINDOW.setdefault(card, [])
window.append(state == "err")
del window[:-_window_limits()[1]]
if state == "err":
n = _FAIL_STREAK.get(card, (0, ""))[0] + 1
_FAIL_STREAK[card] = (n, note or "no reason given")
else:
_FAIL_STREAK.pop(card, None)
return None
def _thrash_guard(card, tool_name):
"""pre_tool_call: after max_consecutive_failures failed calls in a row, refuse every tool except the ones a
blocked card may still use, and say how to hand the card to the coordinator."""
if tool_name in ALWAYS_ALLOWED_OVER_BUDGET:
return None
n, note = _FAIL_STREAK.get(card, (0, ""))
if n >= _max_consecutive_failures():
lead = "%d tool calls in a row failed (%s). Stop." % (n, note)
else:
window = _FAIL_WINDOW.get(card, [])
if sum(window) < _window_limits()[0]:
return None
lead = "%d of the last %d tool calls failed (%s). Stop." % (
sum(window), len(window), note or "no reason given")
reader = _result_tool()
reason = "crew: %s: %s" % (reader.THRASH_REASON if reader else "repeated tool failure", note)
return {"action": "block", "message": _stop_message(lead, "transient", reason.replace("'", ""))}
def _note_overrun(card, used, budget, tool_name):
"""Record a budget overrun on a PASS card as a warning in the card's budget file."""
try:
path = _budget_file(card)
os.makedirs(os.path.dirname(path), exist_ok=True)
try:
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
except Exception:
data = {"card": card, "used": used, "budget": budget}
data["overrun_warning"] = {"used": used, "budget": budget, "tool": tool_name, "ts": time.time()}
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(data, fh)
os.replace(tmp, path)
except Exception:
pass
# ---------------------------------------------------------------- the /crew trigger
# Crew starts only on /crew. The pre_llm_call preload records (session, turn) and opens an intake
# window for that session when the turn's user message is the literal `/crew ...` command (raw, or
# already expanded into the crew skill by the gateway / CLI slash rewrite).
#
# The guard allows a hand-made `crew_card.py open` inside such a turn, and inside that session's
# live intake window: the owner's answers to the intake's questions arrive in the NEXT turn - the
# reply to a `clarify` form, or a plain answer - which is not a /crew turn, and retyping the command
# to make the card openable is the friction this window removes.
#
# The window closes on the first card opened in it, and expires INTAKE_WINDOW_SECONDS after the owner's last
# turn in it (a /crew turn or, while the window is live, any later owner message: crew_intake_preload extends it,
# so an intake that stays in conversation - the owner chose to discuss first - is not cut off at 30 minutes). A
# session that never saw /crew has no window, so the gate itself is unchanged. Everything lives in
# this process's memory - no session database read on any tool call.
_CREW_TURNS = {} # (session_id, turn_id) -> time recorded
_CREW_TURNS_MAX = 512
# How long a /crew turn (or the owner's latest message in its live window) leaves its session able to open the card. The clarify form's own wait is
# 600s (config clarify_timeout); 1800 leaves room for a slow answer without holding the door open
# for an ordinary session half an hour later.
INTAKE_WINDOW_SECONDS = 1800
_CREW_WINDOWS = {} # session_id -> expiry epoch
# The gateway and the interactive CLI rewrite `/crew <ask>` into the skill prompt before the turn;
# this is the marker agent/skill_commands.build_skill_invocation_message writes for that rewrite.
CREW_SKILL_INVOKED_RX = re.compile(r"\[IMPORTANT: The user has invoked the \"crew\" skill\b")
CARD_OPEN_RX = re.compile(r"crew_card\.py[\"']?\s+open(?=\s|$|[;&|])")
PROBE_TITLE_RX = re.compile(r"--title(?:\s+|=)[\"']?PROBE\b")
# Answering crew's report. The in-session watcher (scripts/crew_watch.py, started by the intake as a
# background process with notify_on_complete) ends by delivering its output into the owner's session as a
# new turn wrapped by Hermes: `[IMPORTANT: Background process <id> completed ...` / `Command: ...crew_card.py
# watch --card <id>`. That turn - seen by the plugin, never written by a model - opens a REPORT window for
# that session and card. The owner's next message there ("do it again") runs the intake for a follow-up card
# without retyping /crew: the window is consumed by that message, which opens the session's intake window
# and gets the crew skill injected once. Other sessions and non-watcher completions open nothing.
REPORT_WINDOW_SECONDS = 1800
_REPORT_WINDOWS = {} # session_id -> (card_id, expiry epoch); consumed by the owner's next message
WATCH_REPORT_RX = re.compile(
r"\A\s*\[IMPORTANT: Background process \S+ completed\b[^\n]*\n\s*Command:[^\n]*"
r"crew_card\.py[\"']?\s+watch\s+--card\s+(\S+)")
def _note_report(session_id, card_id):
sid = str(session_id or "")
if not sid:
return
_REPORT_WINDOWS[sid] = (card_id, time.time() + REPORT_WINDOW_SECONDS)
if len(_REPORT_WINDOWS) > _CREW_TURNS_MAX:
_REPORT_WINDOWS.pop(next(iter(_REPORT_WINDOWS)), None)
def _take_report(session_id):
"""The card id of this session's live report window, consumed (None when absent or expired)."""
entry = _REPORT_WINDOWS.pop(str(session_id or ""), None)
if entry and time.time() <= entry[1]:
return entry[0]
return None
def _crew_skill_text():
try:
with open(os.path.join(HERE, "skills", "crew", "SKILL.md"), encoding="utf-8") as fh:
return _strip_frontmatter(fh.read())
except OSError:
return None
def _turn_key(session_id, turn_id):
return (str(session_id or ""), str(turn_id or ""))
def _record_crew_turn(session_id, turn_id):
if not (session_id or turn_id):
return
_CREW_TURNS[_turn_key(session_id, turn_id)] = time.time()
if len(_CREW_TURNS) > _CREW_TURNS_MAX:
for key, _ts in sorted(_CREW_TURNS.items(), key=lambda kv: kv[1])[:len(_CREW_TURNS) - _CREW_TURNS_MAX]:
_CREW_TURNS.pop(key, None)
def _open_window(session_id):
"""A /crew turn leaves its session able to open the card for INTAKE_WINDOW_SECONDS."""
sid = str(session_id or "")
if not sid:
return
_CREW_WINDOWS[sid] = time.time() + INTAKE_WINDOW_SECONDS
if len(_CREW_WINDOWS) > _CREW_TURNS_MAX:
for key, _exp in sorted(_CREW_WINDOWS.items(), key=lambda kv: kv[1])[:len(_CREW_WINDOWS) - _CREW_TURNS_MAX]:
_CREW_WINDOWS.pop(key, None)
def _close_window(session_id):
"""The window closes on the first card opened from it: one /crew, one card."""
_CREW_WINDOWS.pop(str(session_id or ""), None)