kanban_tools.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. """Kanban tools — structured tool-call surface for worker + orchestrator agents.
  2. Registered only under the dispatcher (``HERMES_KANBAN_TASK`` set) or when the profile
  3. enables the ``kanban`` toolset. Tools rather than ``hermes kanban`` shell-outs: they run
  4. in the agent's process (reach ``kanban.db`` from a container/SSH terminal backend, no
  5. shlex quoting of JSON metadata, structured-JSON failures). Humans use CLI/dashboard.
  6. """
  7. from __future__ import annotations
  8. import functools
  9. import json
  10. import logging
  11. import os
  12. import time
  13. from contextlib import contextmanager
  14. from typing import Any, Callable, Optional
  15. from agent.redact import redact_sensitive_text
  16. from hermes_cli.goals import judge_goal
  17. from tools.registry import no_cache_check_fn, registry, tool_error
  18. from hermes_cli.config import cfg_get, load_config
  19. from tools.kanban_tools_schemas import (
  20. KANBAN_ATTACH_SCHEMA,
  21. KANBAN_ATTACH_URL_SCHEMA, KANBAN_ATTACHMENTS_SCHEMA, KANBAN_BLOCK_SCHEMA, KANBAN_COMMENT_SCHEMA,
  22. KANBAN_COMPLETE_SCHEMA, KANBAN_CREATE_SCHEMA, KANBAN_HEARTBEAT_SCHEMA, KANBAN_LINK_SCHEMA,
  23. KANBAN_LIST_SCHEMA, KANBAN_REQUEST_CHANGES_SCHEMA, KANBAN_REQUEST_REVIEW_SCHEMA,
  24. KANBAN_SCHEDULE_SCHEMA, KANBAN_SHOW_SCHEMA, KANBAN_UNBLOCK_SCHEMA)
  25. logger = logging.getLogger(__name__)
  26. KANBAN_LIST_DEFAULT_LIMIT = 50
  27. KANBAN_LIST_MAX_LIMIT = 200
  28. # --- Gating ---
  29. def _profile_has_kanban_toolset() -> bool:
  30. from tools.kanban_toolset_context import kanban_toolset_requested
  31. requested = kanban_toolset_requested()
  32. if requested:
  33. return True
  34. try:
  35. config = load_config()
  36. # Preserve the legacy profile-wide opt-in for callers using bundles.
  37. if "kanban" in (config.get("toolsets") or []):
  38. return True
  39. if requested is not None:
  40. # Never borrow another platform's opt-in during schema assembly.
  41. return False
  42. # Offer-time skill discovery has no platform selection. A saved opt-in
  43. # makes the playbook relevant; actual schemas still use the scope above.
  44. from hermes_cli.tools_config import _get_platform_tools
  45. platforms = config.get("platform_toolsets") or {}
  46. return any(
  47. "kanban" in _get_platform_tools(config, platform, include_default_mcp_servers=False)
  48. for platform, names in platforms.items() if isinstance(names, list)
  49. )
  50. except Exception:
  51. return False
  52. def _delegation_ctx(predicate: str, default: bool) -> bool:
  53. """``agent.delegation_context.<predicate>()``; ``default`` when it cannot be evaluated."""
  54. try:
  55. from agent import delegation_context
  56. return getattr(delegation_context, predicate)()
  57. except Exception:
  58. return default
  59. def _is_delegated_child_context() -> bool:
  60. return _delegation_ctx("is_delegated_child_context", False)
  61. def _is_dispatcher_owned_worker() -> bool:
  62. """False for delegate_task children AND for cron jobs fired in-process from
  63. a worker — i.e. whenever HERMES_KANBAN_* is present but not ours."""
  64. return _delegation_ctx("is_dispatcher_owned_worker_context", True)
  65. def _visible(*, to_env_worker: bool) -> bool:
  66. """check_fn core: never for delegate children; dispatcher-spawned env workers
  67. (HERMES_KANBAN_TASK) per flag; else the profile toolset decides."""
  68. if _is_delegated_child_context():
  69. return False
  70. if os.environ.get("HERMES_KANBAN_TASK") and _is_dispatcher_owned_worker():
  71. return to_env_worker
  72. return _profile_has_kanban_toolset()
  73. @no_cache_check_fn
  74. def _check_kanban_mode() -> bool:
  75. """Lifecycle tools: dispatcher workers + profiles with the ``kanban`` toolset."""
  76. return _visible(to_env_worker=True)
  77. @no_cache_check_fn
  78. def _check_kanban_orchestrator_mode() -> bool:
  79. """Board-routing tools (kanban_list, kanban_unblock): hidden from task workers."""
  80. return _visible(to_env_worker=False)
  81. # --- Shared helpers: validation failures raise _Reject; _kanban_handler renders it ---
  82. # Worker tools that terminate or transition a run's ownership. An unbound worker
  83. # (HERMES_KANBAN_RUN_ID unresolvable) must not run these: expected_run_id=None
  84. # would silently skip the run-ownership CAS in kanban_db. Non-lifecycle tools
  85. # (heartbeat / attach / attach_url) do not terminate a run and are not gated.
  86. _RUN_LIFECYCLE_TOOLS = frozenset({
  87. "kanban_complete", "kanban_block", "kanban_schedule",
  88. "kanban_request_review", "kanban_request_changes",
  89. })
  90. class _Reject(Exception):
  91. """Carries a finished ``tool_error`` payload out of a validation helper."""
  92. def __init__(self, message: str):
  93. super().__init__(tool_error(message))
  94. def _check(cond: Any, message: str) -> None:
  95. """Reject (as a tool error) unless ``cond`` is truthy."""
  96. if not cond:
  97. raise _Reject(message)
  98. # Keys a handler reads that its LLM-facing schema deliberately does not declare:
  99. # ``session_id`` is provenance stamped by internal callers (31fe2290393), ``project_id``
  100. # the pre-``project`` alias still honoured by ``_handle_create`` (e7811345c17).
  101. _UNDECLARED_ARGS: dict[str, frozenset[str]] = {
  102. "kanban_create": frozenset({"session_id", "project_id"}),
  103. # ``title`` is the pre-schema alias of ``filename`` that ``_handle_attach_url`` still honours.
  104. "kanban_attach_url": frozenset({"title"}),
  105. }
  106. def _persisted_identity() -> str:
  107. """Profile name persisted into board records (comment author, task creator).
  108. ``hermes_cli.profiles.current_profile_name`` resolves the profile this call runs FOR — the bound
  109. home override under a multiplexed tick or turn, else the dispatcher's ``HERMES_PROFILE`` pin,
  110. else the process home; the generic ``"worker"`` only when nothing names a profile. Never taken
  111. from tool args: board records are injected into future workers' prompts, so a caller-supplied
  112. identity could forge an authoritative-looking author (see #19713).
  113. """
  114. from hermes_cli.profiles import current_profile_name
  115. return current_profile_name("worker") or "worker"
  116. def _kanban_handler(tool_name: str) -> Callable:
  117. """Wrap a handler so every failure is a structured tool error. ``ValueError``
  118. (invalid board slug, DB validation such as cycle/self-link, ``AttachmentTooLarge``)
  119. is reported without a traceback; anything else is logged with ``logger.exception``."""
  120. def deco(fn):
  121. @functools.wraps(fn)
  122. def wrapper(args: dict, **kw) -> str:
  123. try:
  124. # Reject typos before a handoff can succeed without its artifacts.
  125. properties = registry.get_schema(tool_name)["parameters"]["properties"]
  126. allowed = set(properties) | _UNDECLARED_ARGS.get(tool_name, frozenset())
  127. unknown = sorted(set(args) - allowed)
  128. _check(not unknown,
  129. f"{tool_name}: unknown parameter(s): {', '.join(unknown)}. "
  130. f"Valid parameters: {', '.join(sorted(properties))}. Nothing changed.")
  131. return fn(args, **kw)
  132. except _Reject as e:
  133. return e.args[0]
  134. except Exception as e:
  135. if not isinstance(e, ValueError):
  136. logger.exception(f"{tool_name} failed")
  137. return tool_error(f"{tool_name}: {e}")
  138. return wrapper
  139. return deco
  140. def _reject_delegated_child_mutation(tool_name: str) -> None:
  141. """A delegate_task child shares the parent's process, so inherited HERMES_KANBAN_*
  142. env is not proof of ownership: it may report findings but must not mutate."""
  143. if _delegation_ctx("is_delegated_child_process_context", False):
  144. raise _Reject(
  145. f"{tool_name} refused: delegate_task child agents are not Kanban run owners. "
  146. "Return findings to the parent agent; the dispatcher worker or an explicitly "
  147. "configured Kanban orchestrator must perform board mutations.")
  148. def _default_task_id(arg: Any) -> Optional[str]:
  149. """Resolve ``task_id`` arg or fall back to the env var the dispatcher set."""
  150. if arg is not None:
  151. val = str(arg).strip()
  152. if val:
  153. return val
  154. if _is_delegated_child_context():
  155. return None
  156. if not _is_dispatcher_owned_worker():
  157. # A cron job fired in-process from a worker must never inherit the
  158. # worker's task id as an implicit default.
  159. return None
  160. env_tid = os.environ.get("HERMES_KANBAN_TASK")
  161. if env_tid:
  162. val = env_tid.strip()
  163. if val:
  164. return val
  165. return None
  166. def _require_task_id(args: dict) -> str:
  167. """Resolve the target task or reject with a message the caller can act on.
  168. The env default only exists for a dispatcher-spawned worker; every other
  169. caller must name a task, so a rejection points at ``kanban_list`` instead of
  170. an env var a chat caller cannot set (#91431).
  171. """
  172. tid = _default_task_id(args.get("task_id"))
  173. if tid:
  174. return tid
  175. if os.environ.get("HERMES_KANBAN_TASK"):
  176. # Env task present but not usable here (delegate child / cron run beside
  177. # a worker): it is not this session's to default to.
  178. raise _Reject(
  179. "task_id is required: this session does not own the inherited "
  180. "HERMES_KANBAN_TASK, so it is not a valid default. Pass an explicit "
  181. "task_id.")
  182. raise _Reject(
  183. "task_id is required: this session has no dispatcher-assigned task to "
  184. "default to. Pass an explicit task_id; discover task ids with kanban_list.")
  185. def _own_task_env(task_id: str, var: str) -> Optional[str]:
  186. """``$var`` only when this worker is scoped to ``task_id``; else None."""
  187. return os.environ.get(var) if os.environ.get("HERMES_KANBAN_TASK") == task_id else None
  188. def _worker_run_id(task_id: str) -> Optional[int]:
  189. """This worker's dispatcher run id when it is scoped to task_id."""
  190. raw = _own_task_env(task_id, "HERMES_KANBAN_RUN_ID")
  191. try:
  192. return int(raw) if raw else None
  193. except ValueError:
  194. return None
  195. def _stamp_worker_session_metadata(task_id: str, metadata: Optional[dict]) -> Optional[dict]:
  196. """Add trusted worker session id metadata for this worker's own task."""
  197. session_id = _own_task_env(task_id, "HERMES_SESSION_ID")
  198. return {**(metadata or {}), "worker_session_id": session_id} if session_id else metadata
  199. def _enforce_worker_task_ownership(tid: str) -> None:
  200. """A dispatcher-spawned worker may only mutate its own HERMES_KANBAN_TASK; a
  201. prompt-injected ``task_id`` must not corrupt sibling/cross-tenant runs.
  202. Orchestrators (toolset enabled, no env task) legitimately route child tasks.
  203. Tools like ``kanban_complete`` / ``kanban_block`` / ``kanban_heartbeat`` mutate run-lifecycle state, so
  204. a buggy or prompt-injected worker that passed an explicit ``task_id`` for some other task could corrupt
  205. sibling or cross-tenant runs (see #19534).
  206. """
  207. env_tid = os.environ.get("HERMES_KANBAN_TASK")
  208. if env_tid and tid != env_tid:
  209. raise _Reject(
  210. f"worker is scoped to task {env_tid}; refusing to mutate {tid}. Use kanban_comment "
  211. f"to hand off information to other tasks, or kanban_create to spawn follow-up work.")
  212. def _worker_guard(tool_name: str, args: dict) -> str:
  213. """Worker mutation preamble, in order: delegate-child rejection, task id
  214. resolution, task-scope ownership, run-identity proof. Returns the task id.
  215. A dispatcher-spawned worker (``HERMES_KANBAN_TASK`` set) that cannot name
  216. its run id is refused on the run-lifecycle mutations: ``expected_run_id=None``
  217. would silently skip the run-ownership CAS in ``kanban_db`` (``complete_task`` /
  218. ``block_task`` / ``request_review`` / ``request_changes`` only append
  219. ``AND current_run_id = ?`` when the value is not ``None``), so an unbound
  220. stale worker could complete a card a live successor owns. This mirrors
  221. ``agent/kanban_stop.py``, which already treats an unbound run id as unknown
  222. and fails closed. CLI / human / orchestrator paths (no ``HERMES_KANBAN_TASK``)
  223. legitimately pass ``expected_run_id=None`` and are unaffected. Non-lifecycle
  224. worker tools (heartbeat / attach / attach_url) do not terminate a run and are
  225. not gated here.
  226. """
  227. _reject_delegated_child_mutation(tool_name)
  228. tid = _require_task_id(args)
  229. _enforce_worker_task_ownership(tid)
  230. if (
  231. tool_name in _RUN_LIFECYCLE_TOOLS
  232. and os.environ.get("HERMES_KANBAN_TASK")
  233. and _worker_run_id(tid) is None
  234. ):
  235. raise _Reject(
  236. f"{tool_name} refused: this worker cannot resolve its "
  237. "HERMES_KANBAN_RUN_ID, so it cannot prove ownership of the card's "
  238. "current run. A stale or unbound worker must not terminate a run a "
  239. "live successor owns. Re-run through the dispatcher so the run id is "
  240. "pinned, or use an orchestrator/CLI path that passes an explicit "
  241. "expected_run_id."
  242. )
  243. return tid
  244. def _require_orchestrator_tool(tool_name: str) -> None:
  245. """The check_fn already hides orchestrator tools from workers; this catches
  246. a stale registration or test harness routing a worker here anyway."""
  247. if os.environ.get("HERMES_KANBAN_TASK"):
  248. raise _Reject(
  249. f"{tool_name} is orchestrator-only; dispatcher-spawned workers must use "
  250. "kanban_complete, kanban_request_review, kanban_request_changes, kanban_block, "
  251. "kanban_heartbeat, or kanban_comment for their assigned task.")
  252. @contextmanager
  253. def _board(board: Optional[str], *, quiet_close: bool = False):
  254. """``with _board(slug) as (kb, conn)``; lazy import so the module loads in non-kanban
  255. contexts. ``board=None`` keeps the env/symlink resolution chain; an explicit slug
  256. overrides it per call. ``quiet_close`` swallows close() errors (best-effort bridges)."""
  257. from hermes_cli import kanban_db as kb
  258. from hermes_cli import kanban_db_connect as kbc
  259. conn = kbc.connect(board=board)
  260. try:
  261. yield kb, conn
  262. finally:
  263. try:
  264. conn.close()
  265. except Exception:
  266. if not quiet_close:
  267. raise
  268. def _existing_task(kb, conn, tid: str):
  269. task = kb.get_task(conn, tid)
  270. _check(task is not None, f"task {tid} not found")
  271. return task
  272. def _ok(**fields: Any) -> str:
  273. return json.dumps({"ok": True, **fields})
  274. def _ok_landed(kb, conn, tid: str, default_status: str, **extra: Any) -> str:
  275. """Success payload reporting where the task actually landed (routing may
  276. not leave it in the requested status)."""
  277. run = kb.latest_run(conn, tid)
  278. landed = kb.get_task(conn, tid)
  279. return _ok(task_id=tid, run_id=run.id if run else None,
  280. status=landed.status if landed else default_status, **extra)
  281. def _redact(value: Any) -> str:
  282. return redact_sensitive_text(str(value), force=True)
  283. def _redact_opt(value: Any) -> Any:
  284. return _redact(value) if value else value
  285. def _redact_metadata(metadata: dict) -> Optional[dict]:
  286. """Redact via a JSON round-trip; None if the result can't be re-parsed."""
  287. try:
  288. return json.loads(redact_sensitive_text(json.dumps(metadata), force=True))
  289. except json.JSONDecodeError:
  290. return None
  291. def _coerce_str_list(value: Any, name: str, what: str, *, strip: bool = False):
  292. """Accept a single string (convenience) or a list/tuple; with ``strip`` the
  293. items are stringified, stripped, and empties dropped."""
  294. if value is None:
  295. return None
  296. if isinstance(value, str):
  297. value = [value]
  298. if not isinstance(value, (list, tuple)):
  299. raise _Reject(f"{name} must be a list of {what}, got {type(value).__name__}")
  300. if strip:
  301. value = [str(x).strip() for x in value if str(x).strip()]
  302. return value
  303. def _require_dict_metadata(metadata: Any) -> None:
  304. _check(metadata is None or isinstance(metadata, dict),
  305. f"metadata must be an object/dict, got {type(metadata).__name__}")
  306. def _merge_artifacts(metadata: Any, artifacts: list[str]) -> dict:
  307. """Fold ``artifacts`` into ``metadata["artifacts"]`` (merged with, never overwriting, a
  308. list the worker passed manually). Artifacts ride inside metadata so the completed-event
  309. payload needs no DB schema change; the gateway notifier uploads each as an attachment."""
  310. _require_dict_metadata(metadata)
  311. metadata = {} if metadata is None else metadata
  312. existing = metadata.get("artifacts")
  313. if isinstance(existing, (list, tuple)):
  314. merged = (str(item).strip() for item in [*existing, *artifacts])
  315. metadata["artifacts"] = list(dict.fromkeys(s for s in merged if s))
  316. else:
  317. metadata["artifacts"] = artifacts
  318. return metadata
  319. def _require_text(args: dict, name: str, message: Optional[str] = None) -> Any:
  320. """``args[name]``; rejects when missing or blank."""
  321. value = args.get(name)
  322. _check(value and str(value).strip(), message or f"{name} is required")
  323. return value
  324. _BOOL_WORDS = {"true": True, "1": True, "yes": True, "false": False, "0": False, "no": False}
  325. def _parse_bool_arg(args: dict, name: str) -> bool:
  326. value = args.get(name)
  327. if value is None or isinstance(value, bool):
  328. return bool(value)
  329. parsed = _BOOL_WORDS.get(str(value).strip().lower())
  330. _check(parsed is not None, f"{name} must be a boolean or 'true'/'false'")
  331. return parsed
  332. def _opt_int(value: Any, default: Optional[int] = None) -> Optional[int]:
  333. return int(value) if value is not None else default
  334. _TASK_FIELDS = tuple(
  335. "id title body assignee status tenant priority workspace_kind workspace_path created_by "
  336. "created_at started_at completed_at result current_run_id model_override "
  337. "provider_override completion_contract last_failure_error".split())
  338. _TASK_SUMMARY_FIELDS = tuple(
  339. "id title assignee status priority tenant workspace_kind workspace_path project_id created_by "
  340. "created_at started_at completed_at current_run_id model_override provider_override".split())
  341. _RUN_FIELDS = tuple("id profile status outcome summary error metadata started_at ended_at".split())
  342. _COMMENT_FIELDS = ("author", "body", "created_at")
  343. _EVENT_FIELDS = ("kind", "payload", "created_at", "run_id")
  344. _ATTACHMENT_FIELDS = tuple(
  345. "id filename content_type size uploaded_by stored_path created_at".split())
  346. _CREATED_FIELDS = ("status", "workspace_kind", "workspace_path", "project_id")
  347. def _fields(obj: Any, names: tuple[str, ...]) -> dict[str, Any]:
  348. """``{name: getattr(obj, name)}``; every value None when ``obj`` is None."""
  349. return {n: getattr(obj, n) if obj is not None else None for n in names}
  350. def _task_summary_dict(kb, conn, task) -> dict[str, Any]:
  351. parents = kb.parent_ids(conn, task.id)
  352. children = kb.child_ids(conn, task.id)
  353. return {
  354. **_fields(task, _TASK_SUMMARY_FIELDS), "parents": parents, "children": children,
  355. "parent_count": len(parents), "child_count": len(children)}
  356. # --- Goal-mode judge gate ---
  357. _GOAL_MODE_BLOCK_ALLOWED_KINDS = frozenset({"dependency", "needs_input"})
  358. def _goal_judge_available() -> bool:
  359. """``judge_goal`` fails open (no auxiliary model -> ``"continue"``), which is
  360. indistinguishable from "not done yet" and would wedge every goal_mode
  361. worker; so the gate is enforced only when a judge is actually reachable."""
  362. try:
  363. from agent.auxiliary_client import get_text_auxiliary_client
  364. client, model = get_text_auxiliary_client("goal_judge")
  365. except Exception:
  366. return False
  367. return client is not None and bool(model)
  368. # Per-tool guidance for a judge rejection: verdict -> message. ``{reason}``/``{tid}`` are filled in.
  369. _GOAL_GATE_MESSAGES = {
  370. "kanban_complete": {
  371. "blocked": (
  372. "Goal completion rejected: judge ruled the goal unachievable — {reason}. The task "
  373. "will NOT complete silently. Either re-scope the task with kanban_edit, or record "
  374. "the block with kanban_block and hand the decision to a human / reviewer."),
  375. "continue": (
  376. "Goal completion rejected by judge: {reason}. To proceed, either: (1) provide "
  377. "explicit acceptance evidence in your summary matching the task's criteria, or (2) "
  378. "create continuation tasks with parents=[{tid}] and keep this task alive.")},
  379. "kanban_request_review": {
  380. "blocked": (
  381. "Goal review handoff rejected: judge ruled the goal unachievable — {reason}. "
  382. "Record the block with kanban_block instead of requesting review."),
  383. "continue": (
  384. "Goal review handoff rejected by judge: {reason}. Provide acceptance evidence "
  385. "matching the card before requesting review.")}}
  386. def _goal_gate(tool_name: str, task, tid: str, evidence: str) -> None:
  387. """Goal-mode pre-handoff judge gate: a worker must not complete / request
  388. review before acceptance criteria are met. ``blocked`` gets its own
  389. guidance; any other non-``done`` verdict gets the ``continue`` guidance.
  390. A broken judge fails open (logged) so it cannot permanently wedge work."""
  391. if not task or not task.goal_mode or not _goal_judge_available():
  392. return
  393. try:
  394. # Headless gate runs outside any agent turn: bind the per-task relay-affinity scope
  395. # (mirrors kanban_specify) so the relay does not reject the judge call (#113669).
  396. from agent.portal_tags import get_affinity_scope, reset_affinity_scope, set_affinity_scope
  397. affinity_token = None if get_affinity_scope() else set_affinity_scope(f"kanban:{tid}")
  398. try:
  399. verdict, reason, _, _, transport_failed = judge_goal(
  400. goal=f"{task.title}\n\n{task.body or ''}".strip(), last_response=evidence.strip())
  401. finally:
  402. if affinity_token is not None:
  403. reset_affinity_scope(affinity_token)
  404. except Exception as judge_exc:
  405. logger.warning(
  406. "goal judge check failed, allowing lifecycle handoff: %s", judge_exc, exc_info=True)
  407. return
  408. if transport_failed:
  409. # ``judge_goal`` fails open to ``continue`` on transport errors (relay 400, auth, timeout);
  410. # an unreachable judge is not a human "not done" and must not reject the handoff (#83610).
  411. logger.warning("goal judge unreachable (%s), allowing lifecycle handoff", reason)
  412. return
  413. if verdict == "done":
  414. return
  415. key = "blocked" if verdict == "blocked" else "continue"
  416. raise _Reject(_GOAL_GATE_MESSAGES[tool_name][key].format(reason=reason, tid=tid))
  417. # --- Runtime-activity → board bridges (auto-heartbeat, live comment injection) ---
  418. # The dispatcher watchdog reads ``tasks.last_heartbeat_at``, not the agent's in-process
  419. # activity timestamp, so normal work is mirrored onto the board here (``kanban_heartbeat``
  420. # stays for notes / pre-extending a claim). Best-effort: never raise into the agent loop;
  421. # rate-limited per process (a race costs one harmless extra write); no-op outside a
  422. # dispatcher-spawned worker.
  423. # --------------------------------------------------------------------------- Runtime-activity →
  424. # board-heartbeat bridge (#31752)
  425. # --------------------------------------------------------------------------- When the agent ticks
  426. # ``_touch_activity`` during normal work (between tool calls, mid-stream chunks, etc.), we want the kanban
  427. # board's ``last_heartbeat_at`` columns to reflect that liveness so the dispatcher watchdog (which reads
  428. # ``tasks.last_heartbeat_at``, not the agent's in-process timestamp) doesn't reclaim an actively-running
  429. # worker as stale. The model is not required to call the explicit ``kanban_heartbeat`` tool for this to work
  430. # — that tool stays available for workers that want to attach a note or pre-emptively extend a claim across
  431. # a known-long op. Constraints: - Best-effort: never raise. The agent loop must not care if the bridge fails
  432. # (board missing, DB locked, etc.). - Rate-limited to one DB write per 60s per-process; runtime activity can
  433. # tick on every chunk/tool result and we don't need that resolution. - No-op outside dispatcher-spawned
  434. # worker context (no ``HERMES_KANBAN_TASK``). - No durable note on these auto-heartbeats; that's reserved
  435. # for the explicit tool which carries a model-supplied note.
  436. _AUTO_HEARTBEAT_MIN_INTERVAL_SECONDS = 60.0
  437. _auto_heartbeat_last_attempt: float = 0.0
  438. _auto_heartbeat_fence_warned = False
  439. def register_current_worker_from_env() -> bool:
  440. """Record this worker's pid on its run when the dispatcher died before it could
  441. (``adopt_worker_pid``). False only when the board says the run was already reclaimed:
  442. the caller must exit. Anything unreadable (no run id, delegate child, board error)
  443. lets the worker run, as before."""
  444. tid = os.environ.get("HERMES_KANBAN_TASK")
  445. run_id = _worker_run_id(tid) if tid else None
  446. if run_id is None or _is_delegated_child_context():
  447. return True
  448. try:
  449. from hermes_cli import kanban_db_dispatch as kbd
  450. with _board(None, quiet_close=True) as (_kb, conn):
  451. return kbd.adopt_worker_pid(conn, tid, run_id, os.getpid())
  452. except Exception:
  453. logger.debug("kanban worker registration for %s failed", tid, exc_info=True)
  454. return True
  455. def heartbeat_current_worker_from_env() -> bool:
  456. """Claim extension + board heartbeat for the current worker; True iff both writes
  457. succeed. ``HERMES_KANBAN_RUN_ID`` pins the run row so a reclaimed stale run is not
  458. heartbeated; ``HERMES_KANBAN_CLAIM_LOCK`` absent -> default claimer (local workers)."""
  459. global _auto_heartbeat_last_attempt, _auto_heartbeat_fence_warned
  460. tid = os.environ.get("HERMES_KANBAN_TASK")
  461. now = time.monotonic()
  462. if not tid or (now - _auto_heartbeat_last_attempt) < _AUTO_HEARTBEAT_MIN_INTERVAL_SECONDS:
  463. return False
  464. if _is_delegated_child_context():
  465. # An in-process delegate child's activity is not the worker's liveness; checked before
  466. # stamping the window so a chatty child cannot starve the worker's own heartbeat.
  467. return False
  468. _auto_heartbeat_last_attempt = now
  469. try:
  470. from hermes_cli import kanban_db_dispatch as kbd
  471. with _board(None, quiet_close=True) as (kb, conn):
  472. ops = ((kb.heartbeat_claim, {"claimer": os.environ.get("HERMES_KANBAN_CLAIM_LOCK")}),
  473. (kbd.heartbeat_worker, {"note": None, "expected_run_id": _worker_run_id(tid)}))
  474. succeeded = True
  475. for fn, kwargs in ops:
  476. op = fn.__name__
  477. try:
  478. succeeded = bool(fn(conn, tid, **kwargs)) and succeeded
  479. except PermissionError as exc:
  480. # The board fence rejected the worker's own liveness write: this process
  481. # inherited HERMES_DELEGATED_CHILD_CONTEXT next to HERMES_KANBAN_TASK, so it is
  482. # a delegate descendant, not the dispatcher's worker (kanban_complete refuses
  483. # too). Loud once: at DEBUG the board just showed a worker that never beats.
  484. succeeded = False
  485. if not _auto_heartbeat_fence_warned:
  486. _auto_heartbeat_fence_warned = True
  487. logger.warning(
  488. "kanban auto-heartbeat for task %s refused (%s): this process carries "
  489. "HERMES_DELEGATED_CHILD_CONTEXT together with HERMES_KANBAN_TASK, so the board "
  490. "treats it as a delegate_task descendant and its claim will not be extended by "
  491. "activity. Only the dispatcher's own spawn grants worker scope; do not copy a "
  492. "worker's environment into a hand-launched process.", tid, exc)
  493. except Exception:
  494. logger.debug("auto-heartbeat: %s failed", op, exc_info=True)
  495. succeeded = False
  496. return succeeded
  497. except Exception:
  498. logger.debug("auto-heartbeat: bridge failed", exc_info=True)
  499. return False
  500. # Live operator-note injection: poll the task for new comments and steer them in
  501. # OUT-OF-BAND, so a user can talk to a running task without block → comment → unblock.
  502. # Watermarked per task (seeded on first poll: that history is already in the context).
  503. _COMMENT_POLL_MIN_INTERVAL_SECONDS = 6.0
  504. _comment_poll_last_attempt: float = 0.0
  505. _comment_watermark: dict[str, int] = {}
  506. def inject_new_comments_from_env(agent: Any) -> bool:
  507. """Steer new operator comments on the worker's task into ``agent``; True iff a
  508. steer was injected; never raises. Own comments (``_persisted_identity``) are skipped."""
  509. global _comment_poll_last_attempt
  510. # Operator notes address the dispatcher-owned worker; a delegate_task child sharing
  511. # this process must neither receive them nor advance the shared watermark (#112817).
  512. tid = os.environ.get("HERMES_KANBAN_TASK") if _is_dispatcher_owned_worker() else None
  513. now = time.monotonic()
  514. if (not tid or agent is None or not hasattr(agent, "steer")
  515. or (now - _comment_poll_last_attempt) < _COMMENT_POLL_MIN_INTERVAL_SECONDS):
  516. return False
  517. _comment_poll_last_attempt = now
  518. seen = _comment_watermark.get(tid)
  519. try:
  520. with _board(None, quiet_close=True) as (kb, conn):
  521. rows = kb.list_comments_after(conn, tid, after_id=seen or 0)
  522. except Exception:
  523. logger.debug("comment-inject: bridge failed", exc_info=True)
  524. return False
  525. if seen is None:
  526. _comment_watermark[tid] = max((c.id for c in rows), default=0)
  527. if seen is None or not rows:
  528. return False
  529. # Advance past everything read (including our own notes) so nothing is re-injected.
  530. _comment_watermark[tid] = max(c.id for c in rows)
  531. # Same resolution the write side used, so a worker skips its OWN comments even
  532. # when the dispatcher did not pin HERMES_PROFILE (echoed notes would otherwise
  533. # re-enter the live turn as fake operator steering).
  534. own = _persisted_identity()
  535. fresh = [c for c in rows if (c.author or "").strip() != own and (c.body or "").strip()]
  536. if not fresh:
  537. return False
  538. lines = [f"- {c.author or 'operator'}: {c.body.strip()}" for c in fresh]
  539. note = ("New note" + ("s" if len(fresh) > 1 else "")
  540. + " on your kanban task from the operator (delivered mid-run). "
  541. + "Take it into account for the work you're doing right now:\n" + "\n".join(lines))
  542. try:
  543. return bool(agent.steer(note))
  544. except Exception:
  545. logger.debug("comment-inject: steer failed", exc_info=True)
  546. return False
  547. # --- Handlers ---
  548. @_kanban_handler("kanban_show")
  549. def _handle_show(args: dict, **kw) -> str:
  550. """Full task state: row, parents, children, comments, runs, last 50 events."""
  551. tid = _default_task_id(args.get("task_id"))
  552. if not tid:
  553. # No dispatcher task in scope and no explicit id: the caller asked "what
  554. # should I be looking at". A chat profile cannot set HERMES_KANBAN_TASK,
  555. # so an error naming the env var is dead end (#91431) — answer instead.
  556. return json.dumps({
  557. "current_task": None,
  558. "hint": (
  559. "No dispatcher-assigned task in this session, so there is no "
  560. "task to show by default. Call kanban_list to see task ids on "
  561. "the board, then kanban_show(task_id=<id>) for full state."),
  562. })
  563. with _board(args.get("board")) as (kb, conn):
  564. task = _existing_task(kb, conn, tid)
  565. return json.dumps({
  566. "task": _fields(task, _TASK_FIELDS),
  567. "parents": kb.parent_ids(conn, tid),
  568. # Non-terminal parents; on a running card this means the dependency
  569. # gate is not holding it and kanban_complete will refuse.
  570. "unsatisfied_parents": [
  571. {"id": pid, "status": status} for pid, status in kb.unsatisfied_parents(conn, tid)],
  572. "children": kb.child_ids(conn, tid),
  573. "comments": [_fields(c, _COMMENT_FIELDS) for c in kb.list_comments(conn, tid)],
  574. # Capped; full log via CLI.
  575. "events": [_fields(e, _EVENT_FIELDS) for e in kb.list_events(conn, tid)[-50:]],
  576. "runs": [_fields(r, _RUN_FIELDS) for r in kb.list_runs(conn, tid)],
  577. # Same string build_worker_context hands the dispatcher at spawn time.
  578. "worker_context": kb.build_worker_context(conn, tid)})
  579. @_kanban_handler("kanban_list")
  580. def _handle_list(args: dict, **kw) -> str:
  581. """Task summaries with the same core filters as the CLI."""
  582. _require_orchestrator_tool("kanban_list")
  583. include_archived = _parse_bool_arg(args, "include_archived")
  584. limit = args.get("limit")
  585. try:
  586. limit = KANBAN_LIST_DEFAULT_LIMIT if limit is None else int(limit)
  587. except (TypeError, ValueError):
  588. return tool_error("limit must be an integer")
  589. _check(limit >= 1, "limit must be >= 1")
  590. _check(limit <= KANBAN_LIST_MAX_LIMIT, f"limit must be <= {KANBAN_LIST_MAX_LIMIT}")
  591. with _board(args.get("board")) as (kb, conn):
  592. # Match CLI list: dependencies cleared since the last dispatcher tick
  593. # should be visible to orchestrators immediately.
  594. promoted = kb.recompute_ready(conn)
  595. # One extra row lets the output report truncation without dumping the board.
  596. rows = kb.list_tasks(
  597. conn, assignee=args.get("assignee"), status=args.get("status"),
  598. tenant=args.get("tenant"), include_archived=include_archived, limit=limit + 1)
  599. truncated = len(rows) > limit
  600. tasks = rows[:limit]
  601. return json.dumps({
  602. "tasks": [_task_summary_dict(kb, conn, t) for t in tasks],
  603. "count": len(tasks), "limit": limit, "truncated": truncated,
  604. "next_limit": (min(limit * 2, KANBAN_LIST_MAX_LIMIT)
  605. if truncated and limit < KANBAN_LIST_MAX_LIMIT else None),
  606. "promoted": promoted})
  607. @_kanban_handler("kanban_complete")
  608. def _handle_complete(args: dict, **kw) -> str:
  609. """Mark the current task done with a structured handoff."""
  610. tid = _worker_guard("kanban_complete", args)
  611. summary = _redact_opt(args.get("summary"))
  612. result = _redact_opt(args.get("result"))
  613. metadata = args.get("metadata")
  614. if isinstance(metadata, dict):
  615. # Keep the unredacted dict if the redacted JSON cannot be re-parsed.
  616. metadata = _redact_metadata(metadata) or metadata
  617. created_cards = _coerce_str_list(
  618. args.get("created_cards"), "created_cards", "task ids", strip=True)
  619. artifacts = _coerce_str_list(args.get("artifacts"), "artifacts", "file paths", strip=True)
  620. if artifacts:
  621. metadata = _merge_artifacts(metadata, artifacts)
  622. _check(summary or result, "provide at least one of: summary (preferred), result")
  623. _require_dict_metadata(metadata)
  624. metadata = _stamp_worker_session_metadata(tid, metadata)
  625. with _board(args.get("board")) as (kb, conn):
  626. # Goal-mode pre-completion judge gate (Issue #38367). Prevent workers from bypassing the auxiliary
  627. # judge by calling kanban_complete before acceptance criteria are met. Only enforce when a judge is
  628. # actually reachable — see _goal_judge_available for why an unavailable judge fails open.
  629. task = kb.get_task(conn, tid)
  630. _goal_gate("kanban_complete", task, tid, (summary or result or "").strip())
  631. try:
  632. ok = kb.complete_task(
  633. conn, tid, result=result, summary=summary, metadata=metadata,
  634. created_cards=created_cards, expected_run_id=_worker_run_id(tid))
  635. except kb.ArtifactPreservationError as artifact_err:
  636. # Structured rejection — surface the phantom ids so the worker can retry with a corrected list
  637. # or drop the field. Audit event already landed in the DB. The task itself was NOT mutated (the
  638. # gate runs before the write txn), so the worker can simply call kanban_complete again. Spell
  639. # that out — without it the model often interprets a tool_error as a terminal failure and either
  640. # blocks or crashes the run instead of retrying. See #22923.
  641. return tool_error(
  642. f"kanban_complete could not preserve the declared artifacts: {artifact_err}. "
  643. f"Your task is still in-flight and its scratch workspace was kept. Fix the "
  644. f"artifact path or storage error, then retry kanban_complete with the same "
  645. f"handoff.")
  646. except kb.LiveClaimError as claim_err:
  647. # Env-less caller (orchestrator, another session) on a card a dispatcher
  648. # worker is executing: refusing here is what keeps that worker's run open.
  649. return tool_error(
  650. f"kanban_complete refused: {claim_err}. Nothing changed. Wait for the worker "
  651. f"to finish, or an operator can run `hermes kanban complete --force {tid}`.")
  652. except kb.HallucinatedCardsError as hall_err:
  653. # The gate runs before the write txn, so the task was NOT mutated;
  654. # say so explicitly or the model treats the error as terminal and
  655. # blocks/crashes instead of retrying. Audit event already landed.
  656. return tool_error(
  657. f"kanban_complete blocked: the following created_cards do not exist or were not "
  658. f"created by this worker: {', '.join(hall_err.phantom)}. Your task is still "
  659. f"in-flight (no state change). Retry kanban_complete with the same "
  660. f"summary/metadata and either drop these ids from created_cards, or pass "
  661. f"created_cards=[] to skip the card-claim check entirely.")
  662. except kb.EmptyCompletionError as empty_err:
  663. # Same shape as the card gate: nothing was mutated, the audit event
  664. # already landed; the worker retries with evidence instead of stalling.
  665. return tool_error(
  666. f"kanban_complete blocked: {empty_err}. Your task is still in-flight (no state "
  667. f"change). Retry kanban_complete with a non-empty summary or result describing "
  668. f"what was done.")
  669. task = kb.get_task(conn, tid)
  670. if not ok:
  671. # complete_task reports every refusal as bare False; a reopened or
  672. # never-finished parent is the actionable one. Name the blockers so
  673. # the worker/operator completes the parents instead of re-running.
  674. blockers = kb.unsatisfied_parents(conn, tid)
  675. if blockers:
  676. detail = ", ".join(f"{pid} ({status})" for pid, status in blockers)
  677. raise _Reject(
  678. f"could not complete {tid}: unsatisfied parent dependencies: "
  679. f"{detail}; complete the parents first (done or archived)")
  680. _check(False, (task.last_failure_error if task else None) or
  681. f"could not complete {tid} (unknown id, stale run, or already terminal)")
  682. run = kb.latest_run(conn, tid)
  683. # Artifact staging is atomic with the completion write, so a worker that
  684. # read `kanban_attachments` before completing saw an empty list and has
  685. # no way to observe what its completion just registered (#117360).
  686. # Report the card's durable attachment set in the result.
  687. return _ok(task_id=tid, run_id=run.id if run else None,
  688. attachments=[
  689. _fields(a, _ATTACHMENT_FIELDS)
  690. for a in kb.list_attachments(conn, tid)])
  691. @_kanban_handler("kanban_block")
  692. def _handle_block(args: dict, **kw) -> str:
  693. """Transition the task to blocked with a reason a human will read."""
  694. tid = _worker_guard("kanban_block", args)
  695. reason = _redact(
  696. _require_text(args, "reason", "reason is required — explain what input you need"))
  697. kind = args.get("kind")
  698. with _board(args.get("board")) as (kb, conn):
  699. _check(kind is None or kind in kb.VALID_BLOCK_KINDS,
  700. f"kind must be one of {sorted(kb.VALID_BLOCK_KINDS)} (or omit it)")
  701. # The goal loop treats ANY blocked status as terminal, so kanban_block
  702. # would be an escape hatch around the completion judge: goal_mode tasks
  703. # may only block on genuine external blockers.
  704. # Goal-mode block gate (Issue #38696, sibling of the kanban_complete judge gate in #38367).
  705. # kanban_block is a second exit path out of the goal loop — run_kanban_goal_loop() treats ANY
  706. # `blocked` status as terminal, identically to `done`, regardless of kind. Without this, a worker
  707. # that learns kanban_complete is gated can just call kanban_block(reason="anything") to escape the
  708. # loop instead. Restrict goal_mode tasks to the kinds that represent a genuine external blocker the
  709. # worker cannot resolve itself; `capability` and `transient` (or an unset kind) route back through
  710. # kanban_complete, which the judge now gates.
  711. task = kb.get_task(conn, tid)
  712. _check(not (task and task.goal_mode and kind not in _GOAL_MODE_BLOCK_ALLOWED_KINDS),
  713. f"goal_mode tasks can only block with kind in "
  714. f"{sorted(_GOAL_MODE_BLOCK_ALLOWED_KINDS)} (got {kind!r}). If the task is actually "
  715. f"finished or cannot proceed for another reason, call kanban_complete instead — "
  716. f"the completion judge will evaluate it.")
  717. ok = kb.block_task(conn, tid, reason=reason, kind=kind, expected_run_id=_worker_run_id(tid))
  718. _check(ok, f"could not block {tid} (unknown id or not in running/ready)")
  719. landed_kind = kb.get_task(conn, tid).block_kind
  720. extra: dict = {"block_kind": landed_kind}
  721. if kind == "dependency" and landed_kind != kind:
  722. # block_task re-kinds a dependency wait that no open parent can satisfy.
  723. extra["requested_kind"] = kind
  724. extra["note"] = (
  725. "kind='dependency' only waits on an incomplete parent; no parent is open, "
  726. "so this was recorded as needs_input (sticky until a human unblocks) "
  727. "instead of parking in todo where the dispatcher would respawn it."
  728. )
  729. return _ok_landed(kb, conn, tid, "blocked", **extra)
  730. @_kanban_handler("kanban_schedule")
  731. def _handle_schedule(args: dict, **kw) -> str:
  732. """Park the current task until an orchestrator re-gates it."""
  733. tid = _worker_guard("kanban_schedule", args)
  734. raw_reason = args.get("reason")
  735. _check(raw_reason is None or isinstance(raw_reason, str), "reason must be a string")
  736. reason = _redact(raw_reason.strip()) if raw_reason and raw_reason.strip() else None
  737. with _board(args.get("board")) as (kb, conn):
  738. # The goal loop treats ``scheduled`` as terminal like ``blocked``, so
  739. # parking would bypass the completion judge (see kanban_block, #38696).
  740. task = kb.get_task(conn, tid)
  741. _check(not (task and task.goal_mode),
  742. "goal_mode tasks cannot be scheduled: use kanban_block with kind "
  743. f"in {sorted(_GOAL_MODE_BLOCK_ALLOWED_KINDS)} for a genuine external "
  744. "blocker, or kanban_complete so the completion judge can evaluate it.")
  745. ok = kb.schedule_task(
  746. conn, tid, reason=reason, expected_run_id=_worker_run_id(tid))
  747. _check(ok, f"could not schedule {tid} (unknown id or not in todo/ready/running/blocked)")
  748. return _ok_landed(kb, conn, tid, "scheduled", reason=reason)
  749. @_kanban_handler("kanban_request_review")
  750. def _handle_request_review(args: dict, **kw) -> str:
  751. """Move implementation into the first-class review phase."""
  752. tid = _worker_guard("kanban_request_review", args)
  753. summary = _redact(_require_text(
  754. args, "summary", "summary is required — describe what was implemented and how it "
  755. "was verified so the reviewer has context"))
  756. metadata = args.get("metadata")
  757. _require_dict_metadata(metadata)
  758. if metadata is not None:
  759. metadata = _redact_metadata(metadata)
  760. _check(metadata is not None, "metadata could not be safely serialized")
  761. artifacts = _coerce_str_list(args.get("artifacts"), "artifacts", "file paths", strip=True)
  762. if artifacts:
  763. metadata = _merge_artifacts(metadata, artifacts)
  764. metadata = _stamp_worker_session_metadata(tid, metadata)
  765. # Reviewer is model-supplied free text stored durably on the event payload.
  766. reviewer = _redact_opt(args.get("reviewer") or None)
  767. if reviewer:
  768. from hermes_cli.profiles import list_profile_names, profile_exists
  769. # A non-profile reviewer would park the card in `review` on an assignee
  770. # the dispatcher can never spawn (#106163).
  771. _check(profile_exists(reviewer),
  772. f"reviewer profile {reviewer!r} is not installed. "
  773. f"Installed profiles: {', '.join(list_profile_names())}")
  774. with _board(args.get("board")) as (kb, conn):
  775. _goal_gate("kanban_request_review", kb.get_task(conn, tid), tid, summary)
  776. try:
  777. ok, fail_reason = kb.request_review(
  778. conn, tid, summary=summary, metadata=metadata, reviewer=reviewer,
  779. expected_run_id=_worker_run_id(tid), with_reason=True)
  780. except kb.ArtifactPreservationError as artifact_err:
  781. # Same contract as kanban_complete (#22923): the transition rolled
  782. # back, the task is untouched and retryable — say so explicitly or
  783. # the model treats the tool_error as terminal.
  784. return tool_error(
  785. f"kanban_request_review could not preserve the declared artifacts: {artifact_err}. "
  786. f"Your task is still in-flight (no state change) and its scratch workspace was "
  787. f"kept. Fix the artifact path or storage error, then retry "
  788. f"kanban_request_review with the same handoff.")
  789. _check(ok, f"could not request review for {tid}: "
  790. f"{fail_reason or 'unknown id or not in running/ready'}")
  791. return _ok_landed(kb, conn, tid, "review")
  792. @_kanban_handler("kanban_request_changes")
  793. def _handle_request_changes(args: dict, **kw) -> str:
  794. """Return a reviewer-owned running task to its implementer."""
  795. tid = _worker_guard("kanban_request_changes", args)
  796. reason = _redact(
  797. _require_text(args, "reason", "reason is required — describe the changes needed"))
  798. with _board(args.get("board")) as (kb, conn):
  799. ok, detail = kb.request_changes(
  800. conn, tid, reason=reason, expected_run_id=_worker_run_id(tid))
  801. _check(ok, f"could not request changes for {tid}: {detail or 'invalid review state'}")
  802. return _ok_landed(kb, conn, tid, "ready", implementer=detail)
  803. @_kanban_handler("kanban_heartbeat")
  804. def _handle_heartbeat(args: dict, **kw) -> str:
  805. """Signal liveness: extend the claim TTL AND record a heartbeat event.
  806. Without the claim half, a worker blocked in one long tool call would still
  807. be reclaimed by ``release_stale_claims``."""
  808. tid = _worker_guard("kanban_heartbeat", args)
  809. from hermes_cli import kanban_db_dispatch as kbd
  810. with _board(args.get("board")) as (kb, conn):
  811. # The dispatcher pins HERMES_KANBAN_CLAIM_LOCK at spawn; the default
  812. # claimer covers locally-driven workers that bypassed the dispatcher.
  813. kb.heartbeat_claim(conn, tid, claimer=os.environ.get("HERMES_KANBAN_CLAIM_LOCK"))
  814. ok = kbd.heartbeat_worker(
  815. conn, tid, note=args.get("note"), expected_run_id=_worker_run_id(tid))
  816. _check(ok, f"could not heartbeat {tid} (unknown id or not running)")
  817. return _ok(task_id=tid)
  818. @_kanban_handler("kanban_comment")
  819. def _handle_comment(args: dict, **kw) -> str:
  820. """Append a comment to a task's thread."""
  821. _reject_delegated_child_mutation("kanban_comment")
  822. tid = args.get("task_id")
  823. if not tid:
  824. # A comment writes to the board, so a bare call must stay an error — but
  825. # point at kanban_list, not an env var a chat caller cannot set (#91431).
  826. raise _Reject(
  827. "task_id is required: comments are per-task and this session has no "
  828. "dispatcher-assigned task to default to. Discover task ids with "
  829. "kanban_list, or pass the task id you mean.")
  830. body = _redact(_require_text(args, "body"))
  831. # Author comes from the worker's runtime identity (``_persisted_identity``), never
  832. # caller args: comments are injected into future workers' system prompts, so an
  833. # args["author"] override could forge a directive from ``hermes-system``.
  834. # Cross-task commenting stays unrestricted — it is the handoff channel between tasks.
  835. # Comments are injected into the next worker's system prompt by ``build_worker_context`` as
  836. # ``**{author}** (timestamp): {body}`` — accepting an ``args["author"]`` override let a worker forge a
  837. # comment from an authoritative-looking name like ``hermes-system`` and poison the future-worker context
  838. # with what reads as a system directive. See #19713.
  839. author = _persisted_identity()
  840. with _board(args.get("board")) as (kb, conn):
  841. cid = kb.add_comment(conn, tid, author=author, body=str(body))
  842. return _ok(task_id=tid, comment_id=cid)
  843. def _store_attachment(board, tid, filename, data, content_type) -> str:
  844. """Store via ``kanban_db.store_attachment_bytes`` (shared size cap, per-task
  845. dir, metadata row) so agent, dashboard, and CLI surfaces stay in lockstep."""
  846. with _board(board) as (kb, conn):
  847. att_id = kb.store_attachment_bytes(
  848. conn, tid, str(filename), data,
  849. content_type=content_type, uploaded_by="agent", board=board)
  850. return _ok(task_id=tid, attachment_id=att_id, size=len(data))
  851. @_kanban_handler("kanban_attach")
  852. def _handle_attach(args: dict, **kw) -> str:
  853. """Attach an inline (base64) file to a task."""
  854. tid = _worker_guard("kanban_attach", args)
  855. filename = _require_text(args, "filename")
  856. content_b64 = _require_text(args, "content_base64")
  857. import base64
  858. import binascii
  859. try:
  860. data = base64.b64decode(str(content_b64), validate=True)
  861. except (binascii.Error, ValueError) as e:
  862. raise _Reject(f"content_base64 is not valid base64: {e}")
  863. return _store_attachment(args.get("board"), tid, filename, data, args.get("content_type"))
  864. _MAX_ATTACH_URL_REDIRECTS = 5
  865. def _download_url_with_cap(url: str, max_bytes: int) -> tuple[bytes, Optional[str]]:
  866. """Fetch ``url`` over http(s) capped at ``max_bytes`` -> ``(data, content_type)``.
  867. Every hop is SSRF-checked (redirects followed manually) so a model-controlled URL, or a
  868. public host 302ing, cannot reach loopback/private/cloud-metadata ranges. ``ValueError``
  869. for bad scheme, blocked target, too many redirects, or a body over the cap (checked
  870. while streaming, so nothing oversize is buffered)."""
  871. from urllib.parse import urljoin, urlparse
  872. import httpx
  873. from tools.url_safety import is_safe_url
  874. current_url = url
  875. for _ in range(_MAX_ATTACH_URL_REDIRECTS + 1):
  876. scheme = (urlparse(current_url).scheme or "").lower()
  877. if scheme not in ("http", "https"):
  878. raise ValueError(f"unsupported URL scheme {scheme!r}; only http/https are allowed")
  879. if not is_safe_url(current_url):
  880. raise ValueError(
  881. f"URL blocked by SSRF protection (private/internal address): {current_url}")
  882. chunks: list[bytes] = []
  883. total = 0
  884. with httpx.stream("GET", current_url, headers={"User-Agent": "hermes-kanban/attach"},
  885. timeout=30, follow_redirects=False) as resp:
  886. if resp.is_redirect:
  887. location = resp.headers.get("location")
  888. if not location:
  889. raise ValueError(f"redirect without Location header from {current_url}")
  890. current_url = urljoin(current_url, location)
  891. continue
  892. resp.raise_for_status()
  893. content_type = (resp.headers.get("content-type") or "").split(";")[0].strip() or None
  894. for chunk in resp.iter_bytes(1024 * 1024):
  895. total += len(chunk)
  896. if total > max_bytes:
  897. raise ValueError(f"attachment exceeds {max_bytes // (1024 * 1024)} MB limit")
  898. chunks.append(chunk)
  899. return b"".join(chunks), content_type
  900. raise ValueError(f"too many redirects fetching {url}")
  901. @_kanban_handler("kanban_attach_url")
  902. def _handle_attach_url(args: dict, **kw) -> str:
  903. """Attach a file fetched server-side from an http(s) URL (shared size cap)."""
  904. from hermes_cli import kanban_db as kb
  905. tid = _worker_guard("kanban_attach_url", args)
  906. url = str(_require_text(args, "url")).strip()
  907. filename = args.get("filename") or args.get("title")
  908. if not filename or not str(filename).strip():
  909. # Derive a name from the URL path's leaf component.
  910. from urllib.parse import unquote, urlparse
  911. filename = unquote(urlparse(url).path.rsplit("/", 1)[-1]).strip() or "download"
  912. try:
  913. data, fetched_ct = _download_url_with_cap(url, kb.KANBAN_ATTACHMENT_MAX_BYTES)
  914. except ValueError as e:
  915. return tool_error(f"kanban_attach_url: {e}")
  916. except Exception as e:
  917. logger.exception("kanban_attach_url download failed")
  918. return tool_error(f"kanban_attach_url: failed to fetch {url}: {e}")
  919. return _store_attachment(
  920. args.get("board"), tid, filename, data, args.get("content_type") or fetched_ct)
  921. @_kanban_handler("kanban_attachments")
  922. def _handle_attachments(args: dict, **kw) -> str:
  923. """List a task's attachments (read-only; no ownership restriction)."""
  924. tid = _require_task_id(args)
  925. with _board(args.get("board")) as (kb, conn):
  926. _existing_task(kb, conn, tid)
  927. return json.dumps({
  928. "ok": True, "task_id": tid,
  929. "attachments": [
  930. _fields(a, _ATTACHMENT_FIELDS) for a in kb.list_attachments(conn, tid)]})
  931. def _persisted_session_id(session_id: Optional[str]) -> Optional[str]:
  932. """Return a session id only when it is present in this profile's state.db."""
  933. if not session_id:
  934. return None
  935. try:
  936. from hermes_state import SessionDB
  937. from hermes_constants import get_hermes_home
  938. state = SessionDB(db_path=get_hermes_home() / "state.db", read_only=True)
  939. except Exception: # state.db may not exist for a CLI/dashboard invocation
  940. logger.debug("Could not open state.db to verify Kanban provenance", exc_info=True)
  941. return None
  942. try:
  943. return session_id if state.get_session(session_id) else None
  944. finally:
  945. state.close()
  946. @_kanban_handler("kanban_create")
  947. def _handle_create(args: dict, **kw) -> str:
  948. """Create a (child) task; orchestrator workers use this to fan out."""
  949. _reject_delegated_child_mutation("kanban_create")
  950. title = _require_text(args, "title")
  951. assignee = args.get("assignee")
  952. _check(assignee, "assignee is required — name the profile that should execute this "
  953. "task (the dispatcher will only spawn tasks with an assignee)")
  954. # Workspace sharing is always explicit: omitted fields mean a fresh scratch workspace
  955. # even for a dispatcher-spawned creator (reusing the parent's path would let a child
  956. # mutate review evidence or race its checkout). Project identity is the one safe thing
  957. # to inherit implicitly (the DB turns it into a fresh per-task worktree).
  958. workspace_kind, workspace_path = args.get("workspace_kind"), args.get("workspace_path")
  959. # See #67567. ``project=""`` is an explicit "no project" (no ``or`` collapse, #106342).
  960. project_id = args["project"] if "project" in args else args.get("project_id")
  961. project_source_task_id = None
  962. triage, skills, goal_mode = (
  963. _parse_bool_arg(args, "triage"), _coerce_str_list(args.get("skills"), "skills", "skill names"),
  964. _parse_bool_arg(args, "goal_mode"))
  965. model_override, provider_override = args.get("model"), args.get("provider")
  966. _check(model_override or not provider_override, "'provider' requires 'model' to be set as well")
  967. parents = _coerce_str_list(args.get("parents") or [], "parents", "task ids")
  968. with _board(args.get("board")) as (kb, conn):
  969. from gateway.session_context import get_session_env
  970. from tools.async_delegation import _current_origin_session_id
  971. self_tid = (os.environ.get("HERMES_KANBAN_TASK")
  972. if _is_dispatcher_owned_worker() else None)
  973. self_task = kb.get_task(conn, self_tid) if self_tid else None
  974. # The worker/API runtime may be transient; the owning task's origin is durable.
  975. # The ambient id is the request-scoped ContextVar binding, not the process-global
  976. # os.environ: in a multi-session gateway the env holds the LAST agent built, and an
  977. # id that never reached its ``sessions`` row is provenance pointing at nothing.
  978. session_id = (_persisted_session_id(args.get("session_id"))
  979. or (self_task.session_id if self_task else None)
  980. or _persisted_session_id(_current_origin_session_id())
  981. or _persisted_session_id(get_session_env("HERMES_SESSION_ID", "")))
  982. if project_id is None and workspace_kind is None and workspace_path is None:
  983. if self_task is not None and self_task.project_id:
  984. project_id, project_source_task_id = self_task.project_id, self_task.id
  985. new_tid = kb.create_task(
  986. conn, title=str(title).strip(), body=args.get("body"), assignee=str(assignee),
  987. parents=tuple(parents), tenant=args.get("tenant") or os.environ.get("HERMES_TENANT"),
  988. priority=_opt_int(args.get("priority"), 0),
  989. workspace_kind=workspace_kind, workspace_path=workspace_path, project_id=project_id,
  990. # Board-project inheritance must read the board this call opened, not the
  991. # session's current board.
  992. board=args.get("board"),
  993. project_source_task_id=project_source_task_id, triage=triage,
  994. creator_task_id=self_tid,
  995. idempotency_key=args.get("idempotency_key"),
  996. max_runtime_seconds=_opt_int(args.get("max_runtime_seconds")), skills=skills,
  997. model_override=model_override, provider_override=provider_override,
  998. goal_mode=goal_mode, goal_max_turns=_opt_int(args.get("goal_max_turns")),
  999. completion_contract=args.get("completion_contract"),
  1000. initial_status=str(args.get("initial_status") or "running"),
  1001. created_by=_persisted_identity(), session_id=session_id)
  1002. landed = _fields(kb.get_task(conn, new_tid), _CREATED_FIELDS)
  1003. wait = [e for e in kb.list_events(conn, new_tid) if e.kind == "dependency_wait"]
  1004. gate = {"gated": True, "gated_by": wait[-1].payload["parent"]} if wait else {"gated": False}
  1005. return _ok(task_id=new_tid, **landed, **gate,
  1006. subscribed=_maybe_auto_subscribe(conn, new_tid))
  1007. def _live_tui_session_key(session_key: str, profile: Optional[str]) -> str:
  1008. """Re-resolve a TUI session key at subscribe time: the inherited ``HERMES_SESSION_KEY``
  1009. can name a session already superseded by a compaction fork, and a subscription bound to
  1010. the dead key silently drops every later completion notification (#110068). Maps the key
  1011. to its continuation tip via the session store's lineage walk. Best-effort, fail-open:
  1012. any error (or an unresolvable key) returns *session_key* unchanged."""
  1013. db_path = None
  1014. if profile and profile != "default":
  1015. try:
  1016. from pathlib import Path
  1017. from hermes_cli.profiles import get_profile_dir, profile_exists
  1018. if profile_exists(profile):
  1019. db_path = Path(get_profile_dir(profile)) / "state.db"
  1020. except Exception:
  1021. db_path = None
  1022. try:
  1023. from hermes_state_registry import acquire, release_or_close
  1024. db = acquire(db_path)
  1025. try:
  1026. return db.resolve_resume_session_id(session_key) or session_key
  1027. finally:
  1028. release_or_close(db)
  1029. except Exception:
  1030. return session_key
  1031. def _resolve_notify_target() -> Optional[dict[str, Any]]:
  1032. """``kanban_db.add_notify_sub`` kwargs for the calling session, or None (CLI/cron/tests).
  1033. Gateway sessions: ``HERMES_SESSION_PLATFORM``/``CHAT_ID`` ContextVars. TUI/desktop:
  1034. those are cleared but the subprocess inherits ``HERMES_SESSION_KEY`` -> ``platform="tui"``
  1035. for the TUI poller. ``HERMES_SESSION_ID`` is deliberately NOT a fallback: it is set for
  1036. every CLI/ACP invocation and would auto-subscribe every CLI run."""
  1037. from gateway.session_context import get_session_env as env
  1038. platform, chat_id = env("HERMES_SESSION_PLATFORM", ""), env("HERMES_SESSION_CHAT_ID", "")
  1039. if not platform or not chat_id:
  1040. session_key = env("HERMES_SESSION_KEY", "") or os.environ.get("HERMES_SESSION_KEY", "")
  1041. if not session_key:
  1042. return None
  1043. platform, chat_id = "tui", session_key
  1044. chat_type = env("HERMES_SESSION_CHAT_TYPE", "") or None
  1045. thread_id = env("HERMES_SESSION_THREAD_ID", "") or None
  1046. message_id = env("HERMES_SESSION_MESSAGE_ID", "") or ""
  1047. notifier_profile = env("HERMES_SESSION_PROFILE", "")
  1048. if not notifier_profile:
  1049. from hermes_cli.profiles import current_profile_name
  1050. notifier_profile = current_profile_name("default")
  1051. if platform == "tui":
  1052. # The inherited key can be stale after a compaction fork (#110068): bind the
  1053. # subscription to the live continuation tip, not the key the process started with.
  1054. chat_id = _live_tui_session_key(chat_id, notifier_profile)
  1055. delivery_metadata: dict[str, Any] = {
  1056. k: v for k, v in (
  1057. ("thread_id", thread_id), ("chat_type", chat_type),
  1058. ("scope_id", env("HERMES_SESSION_SCOPE_ID", "")),
  1059. ("parent_chat_id", env("HERMES_SESSION_PARENT_CHAT_ID", "")),
  1060. ) if v}
  1061. if (platform.lower() == "telegram" and thread_id
  1062. and (chat_type or "").lower() in {"dm", "direct", "private"}):
  1063. delivery_metadata["telegram_dm_topic_reply_fallback"] = True
  1064. if str(thread_id) not in {"", "1"}:
  1065. delivery_metadata["direct_messages_topic_id"] = str(thread_id)
  1066. if message_id:
  1067. delivery_metadata["telegram_reply_to_message_id"] = str(message_id)
  1068. return dict(
  1069. platform=platform, chat_id=chat_id, chat_type=chat_type, thread_id=thread_id,
  1070. user_id=env("HERMES_SESSION_USER_ID", "") or None,
  1071. user_id_alt=env("HERMES_SESSION_USER_ID_ALT", "") or None,
  1072. notifier_profile=notifier_profile,
  1073. delivery_mode="notify+wake" if platform != "tui" else None,
  1074. delivery_metadata=delivery_metadata or None)
  1075. def _maybe_auto_subscribe(conn: Any, task_id: str) -> bool:
  1076. """Subscribe the calling session to completion/block events; True iff a row was
  1077. written (surfaced as ``subscribed`` so an orchestrator can fall back to explicit
  1078. ``kanban_notify-subscribe``). Gated by ``kanban.auto_subscribe_on_create`` (default
  1079. True). Failures are logged and swallowed: bookkeeping must never fail kanban_create."""
  1080. try:
  1081. if not cfg_get(load_config(), "kanban", "auto_subscribe_on_create", default=True):
  1082. return False
  1083. except Exception:
  1084. pass # unreadable config keeps the user-friendly default (True)
  1085. target = None
  1086. try:
  1087. target = _resolve_notify_target()
  1088. if target is None:
  1089. return False # CLI / cron / test — no persistent channel
  1090. from hermes_cli import kanban_db_notify as _kbn
  1091. # Inheritance and explicit subscriptions already encode the delivery policy.
  1092. # Auto-subscribe must not turn a passive destination into an agent wake.
  1093. if any(sub["platform"] == target["platform"] and sub["chat_id"] == target["chat_id"]
  1094. and (sub["thread_id"] or "") == (target["thread_id"] or "")
  1095. for sub in _kbn.list_notify_subs(conn, task_id)):
  1096. return True
  1097. _kbn.add_notify_sub(conn, task_id=task_id, **target)
  1098. return True
  1099. except Exception as _exc:
  1100. logger.warning(
  1101. "_maybe_auto_subscribe failed: %r (platform=%r key_set=%r)",
  1102. _exc, target["platform"] if target else "", bool(target and target["chat_id"]))
  1103. return False
  1104. @_kanban_handler("kanban_unblock")
  1105. def _handle_unblock(args: dict, **kw) -> str:
  1106. """Transition a blocked task to ready, or todo while parents remain open."""
  1107. _reject_delegated_child_mutation("kanban_unblock")
  1108. _require_orchestrator_tool("kanban_unblock")
  1109. tid = args.get("task_id")
  1110. _check(tid, "task_id is required")
  1111. tid = str(tid)
  1112. _enforce_worker_task_ownership(tid)
  1113. with _board(args.get("board")) as (kb, conn):
  1114. _check(kb.unblock_task(conn, tid), f"could not unblock {tid} (not blocked or unknown)")
  1115. return _ok(task_id=tid, **_fields(kb.get_task(conn, tid), ("status",)))
  1116. @_kanban_handler("kanban_link")
  1117. def _handle_link(args: dict, **kw) -> str:
  1118. """Add a parent→child dependency edge after the fact (cycles/self-links/running
  1119. children → ValueError). A worker linking its OWN running card proves ownership
  1120. with its run id so the dependency-block handoff still works."""
  1121. _reject_delegated_child_mutation("kanban_link")
  1122. parent_id = args.get("parent_id")
  1123. child_id = args.get("child_id")
  1124. _check(parent_id and child_id, "both parent_id and child_id are required")
  1125. with _board(args.get("board")) as (kb, conn):
  1126. gated = kb.link_tasks(
  1127. conn, parent_id=parent_id, child_id=child_id,
  1128. expected_child_run_id=_worker_run_id(str(child_id)))
  1129. return _ok(parent_id=parent_id, child_id=child_id, gated=gated,
  1130. **({"gated_by": parent_id} if gated else {}))
  1131. # --- Registration (order preserved: it is the order tools appear in the schema) ---
  1132. # kanban_list / kanban_unblock route the board and are hidden from task workers.
  1133. _ORCHESTRATOR_TOOLS = frozenset({"kanban_list", "kanban_unblock"})
  1134. _TOOLS = (
  1135. ("kanban_show", KANBAN_SHOW_SCHEMA, _handle_show, "📋"),
  1136. ("kanban_list", KANBAN_LIST_SCHEMA, _handle_list, "📋"),
  1137. ("kanban_complete", KANBAN_COMPLETE_SCHEMA, _handle_complete, "✔"),
  1138. ("kanban_block", KANBAN_BLOCK_SCHEMA, _handle_block, "⏸"),
  1139. ("kanban_schedule", KANBAN_SCHEDULE_SCHEMA, _handle_schedule, "⏰"),
  1140. ("kanban_request_review", KANBAN_REQUEST_REVIEW_SCHEMA, _handle_request_review, "👀"),
  1141. ("kanban_request_changes", KANBAN_REQUEST_CHANGES_SCHEMA, _handle_request_changes, "↩"),
  1142. ("kanban_heartbeat", KANBAN_HEARTBEAT_SCHEMA, _handle_heartbeat, "💓"),
  1143. ("kanban_comment", KANBAN_COMMENT_SCHEMA, _handle_comment, "💬"),
  1144. ("kanban_attach", KANBAN_ATTACH_SCHEMA, _handle_attach, "📎"),
  1145. ("kanban_attach_url", KANBAN_ATTACH_URL_SCHEMA, _handle_attach_url, "📎"),
  1146. ("kanban_attachments", KANBAN_ATTACHMENTS_SCHEMA, _handle_attachments, "📎"),
  1147. ("kanban_create", KANBAN_CREATE_SCHEMA, _handle_create, "➕"),
  1148. ("kanban_unblock", KANBAN_UNBLOCK_SCHEMA, _handle_unblock, "▶"),
  1149. ("kanban_link", KANBAN_LINK_SCHEMA, _handle_link, "🔗"))
  1150. for _name, _sch, _handler, _emoji in _TOOLS:
  1151. _gate = _check_kanban_orchestrator_mode if _name in _ORCHESTRATOR_TOOLS else _check_kanban_mode
  1152. registry.register(name=_name, toolset="kanban", schema=_sch, handler=_handler, emoji=_emoji,
  1153. check_fn=_gate)