session_kanban.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. """Trusted dispatcher claims enter the ordinary owner's durable admission queue."""
  2. import asyncio
  3. import contextlib
  4. from contextlib import closing
  5. from dataclasses import asdict, replace
  6. import threading
  7. import json
  8. from pathlib import Path
  9. import sqlite3
  10. from hermes_state_runtime import RuntimeStoreError
  11. def build_kanban_policy(connection, params, config):
  12. from hermes_cli import kanban_db as kb
  13. from hermes_cli.profiles import resolve_profile_env
  14. from gateway.session_policy import build_policy
  15. authority, actor = connection.authority, connection.actor
  16. if not connection.native_owner or 'session:create' not in actor.capabilities:
  17. raise RuntimeStoreError('permission_denied')
  18. if actor.profile_id != authority.profile_id:
  19. raise RuntimeStoreError('profile_mismatch')
  20. if (set(params) not in ({'board', 'task_id', 'run_id', 'claim_lock'}, {'board', 'task_id', 'run_id', 'claim_lock', 'db'})
  21. or any(not isinstance(params[k], str) or not params[k] for k in ('board', 'task_id', 'claim_lock'))
  22. or type(params['run_id']) is not int):
  23. raise RuntimeStoreError('invalid_params')
  24. try:
  25. board = kb._require_slug(params['board'])
  26. path = Path(params['db']).resolve(strict=True) if 'db' in params else kb.kanban_db_path(board=board).resolve()
  27. with closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True)) as conn:
  28. conn.row_factory = sqlite3.Row
  29. task = kb.get_task(conn, params['task_id'])
  30. run = conn.execute('SELECT * FROM task_runs WHERE id=?', (params['run_id'],)).fetchone()
  31. if (task is None or run is None or task.status != 'running' or run['status'] != 'running'
  32. or task.current_run_id != params['run_id'] or run['task_id'] != task.id
  33. or task.claim_lock != params['claim_lock'] or run['claim_lock'] != task.claim_lock):
  34. raise RuntimeStoreError('stale_kanban_claim')
  35. if Path(resolve_profile_env(task.assignee)).resolve() != Path(authority.profile_id).resolve():
  36. raise RuntimeStoreError('profile_mismatch')
  37. bound = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='owner_admitted' ORDER BY id DESC LIMIT 1",
  38. (task.id, task.current_run_id)).fetchone()
  39. if bound and json.loads(bound[0])['request_id'] != 'kanban:' + json.dumps([board, task.id, task.current_run_id], separators=(',', ':')):
  40. raise RuntimeStoreError('stale_kanban_claim')
  41. context = kb.build_worker_context(conn, task.id)
  42. skills = list(task.skills or ())
  43. if kb._retry_status_for_run(conn, task.id, task.current_run_id) == 'review':
  44. # Same rule as the dispatcher's review lane: the reviewer always loads sdlc-review.
  45. skills = list(dict.fromkeys([*skills, 'sdlc-review']))
  46. except (ValueError, OSError, sqlite3.Error) as exc:
  47. raise RuntimeStoreError('invalid_kanban_claim') from exc
  48. cwd = task.workspace_path
  49. params_policy = {'source': 'cli', 'cwd': cwd}
  50. for name, value in (('model', task.model_override), ('provider', task.provider_override), ('reasoning', task.reasoning_effort)):
  51. if value:
  52. params_policy[name] = value
  53. private = {}
  54. policy = build_policy(params_policy, config, private_secrets=private)
  55. if policy.model is None:
  56. from gateway.run import _resolve_gateway_model
  57. policy = replace(policy, model=_resolve_gateway_model(policy.config()))
  58. context = dict(params, workspace=cwd, branch=task.branch_name, tenant=task.tenant,
  59. profile=task.assignee, workspaces_root=str(kb.workspaces_root(board=board).resolve()),
  60. skills=skills, goal_mode=task.goal_mode, goal_max_turns=task.goal_max_turns,
  61. goal_text='\n\n'.join(p for p in (task.title, task.body) if p), context=context,
  62. max_runtime_seconds=task.max_runtime_seconds, accept_hooks=True)
  63. context['db'] = str(path)
  64. request = json.loads(policy.request_json)
  65. request.update(source='kanban', board=board, task_id=task.id, run_id=task.current_run_id)
  66. return replace(policy, source='kanban', platform='cli', toolsets=tuple(sorted(set(policy.toolsets) | {'kanban'})),
  67. request_json=json.dumps(request, sort_keys=True), kanban_json=json.dumps(context)), private
  68. async def run_task(connection, params):
  69. if not connection.native_owner or 'session:create' not in connection.actor.capabilities:
  70. raise RuntimeStoreError('permission_denied')
  71. from gateway.run import _load_gateway_config
  72. from gateway.session_local import create_local_session
  73. from gateway.session_contract import Submission
  74. from gateway.session_local_recovery import local_identity
  75. from hermes_state_local import local_receipt
  76. from gateway.session_policy import restore_policy
  77. authority = connection.authority
  78. # Resolved off-loop up front: no await separates the saved-claim check from session
  79. # creation. The Kanban claim check and its marker share one off-loop transaction; a
  80. # concurrent retry of the same attempt meets that marker (same session) or a stale claim.
  81. owner_db = str(await asyncio.to_thread(Path(authority.db.db_path).resolve))
  82. # The dispatcher attempt is the durable request identity, including after the
  83. # task closes. Retry checks the saved claim, never reinterprets updated cards.
  84. request_id = 'kanban:' + json.dumps([params.get('board'), params.get('task_id'), params.get('run_id')], separators=(',', ':'))
  85. sid = local_identity(authority.profile_id, connection.actor.subject, request_id)
  86. saved = local_receipt(authority.db, sid) if authority.db.get_session(sid) is not None else None
  87. if saved:
  88. policy = restore_policy(saved['policy'])
  89. context = json.loads(policy.kanban_json or '{}')
  90. if (not connection.native_owner or set(params) not in ({'board', 'task_id', 'run_id', 'claim_lock'}, {'board', 'task_id', 'run_id', 'claim_lock', 'db'})
  91. or any(params[k] != context.get(k) for k in params)):
  92. raise RuntimeStoreError('permission_denied')
  93. from gateway.session_local_recovery import restore_local_session
  94. ref = restore_local_session(authority, sid)
  95. else:
  96. policy, private = build_kanban_policy(connection, params, _load_gateway_config())
  97. ref = create_local_session(authority, connection.actor, {'request_id': request_id},
  98. trusted_policy=policy, trusted_secrets=private)
  99. from hermes_cli.kanban_db_connect import connect_closing
  100. from hermes_cli import kanban_db as kb
  101. import os
  102. import psutil
  103. from hermes_cli.process_identity import worker_birth
  104. context = json.loads(policy.kanban_json)
  105. def admit_claim():
  106. # The Kanban DB is the cross-profile dispatch bus (busy_timeout up to 120 s): the claim
  107. # check and its marker share one write transaction, off the owner loop.
  108. with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
  109. # Either this exact attempt was already admitted to this session (retry after a
  110. # crash between session creation and admission), or the claim is still current
  111. # now; a reclaimed/closed task never reaches resume/submit.
  112. marker = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='owner_admitted' ORDER BY id DESC LIMIT 1",
  113. (params['task_id'], params['run_id'])).fetchone()
  114. if marker:
  115. if json.loads(marker[0])['session_id'] != ref.session_id:
  116. raise RuntimeStoreError('stale_kanban_claim')
  117. else:
  118. task = kb.get_task(conn, params['task_id'])
  119. if not (task and task.status == 'running' and task.current_run_id == params['run_id'] and task.claim_lock == params['claim_lock']):
  120. raise RuntimeStoreError('stale_kanban_claim')
  121. kb._append_event(conn, task.id, 'owner_admitted',
  122. {'db': owner_db, 'session_id': ref.session_id,
  123. 'request_id': request_id, 'pid': os.getpid(), 'birth': worker_birth(psutil.Process())},
  124. run_id=task.current_run_id)
  125. from gateway.session_runtime_workers import tracked_write
  126. await tracked_write(authority, admit_claim)
  127. await connection.resume(ref, {})
  128. # Finite like the `chat -q` worker it replaced: nobody can answer an approval or clarify in a
  129. # card (approvals.single_query_mode applies). Never unattended: that is `-z`'s auto-approval.
  130. # A retry of an attempt admitted before cards were finite resubmits its committed payload,
  131. # so the store returns the original receipt instead of admission_conflict.
  132. from hermes_state_runtime import find_session_admission
  133. committed = None if not saved else await asyncio.to_thread(find_session_admission, authority.db,
  134. principal_id=connection.actor.subject, session_id=ref.session_id, request_id=request_id)
  135. payload: dict = {'text': f'work kanban task {params["task_id"]}'}
  136. if committed is None or 'finite' in committed['payload']:
  137. payload['finite'] = True
  138. # The dispatcher's trusted producer marker (#134889 KB-8): nobody waits on a card attempt, so one
  139. # lost across an owner restart settles interrupted instead of pausing the card session. An
  140. # attempt main committed without it resubmits unmarked (same digest, original receipt).
  141. card = None
  142. if committed is None or 'kanban_card_v1' in committed['payload']:
  143. card = {'board': context.get('board'), 'task_id': params['task_id'], 'run_id': params['run_id']}
  144. receipt = await authority.submit(connection.actor, Submission(request_id, ref, payload, 'queue'),
  145. _kanban_card=card)
  146. return {'session_id': ref.session_id, 'receipt': asdict(receipt)}
  147. def bind_worker_context(frame):
  148. """Only the adopted private exec calls this, before tool discovery imports."""
  149. import os
  150. context = json.loads(frame['policy'].get('kanban_json') or 'null')
  151. if context is None:
  152. return
  153. if frame['policy']['source'] != 'kanban':
  154. raise ValueError('invalid_kanban_policy')
  155. env = {'HERMES_KANBAN_TASK': context['task_id'], 'HERMES_KANBAN_BOARD': context['board'],
  156. 'HERMES_KANBAN_DB': context['db'], 'HERMES_KANBAN_RUN_ID': str(context['run_id']),
  157. 'HERMES_KANBAN_CLAIM_LOCK': context['claim_lock'], 'HERMES_KANBAN_WORKSPACE': context['workspace'],
  158. 'HERMES_KANBAN_WORKSPACES_ROOT': context['workspaces_root'], 'HERMES_PROFILE': context['profile'],
  159. 'HERMES_SESSION_SOURCE': 'kanban'}
  160. for key, value in (('HERMES_KANBAN_BRANCH', context['branch']), ('HERMES_TENANT', context['tenant'])):
  161. if value:
  162. env[key] = value
  163. if context['goal_mode']:
  164. env['HERMES_KANBAN_GOAL_MODE'] = '1'
  165. from hermes_cli.kanban_db_dispatch import _worker_terminal_timeout_env
  166. for key in ('TERMINAL_TIMEOUT', 'TERMINAL_MAX_FOREGROUND_TIMEOUT'):
  167. value = _worker_terminal_timeout_env(context['max_runtime_seconds'], os.environ.get(key))
  168. if value:
  169. env[key] = value
  170. from hermes_cli.kanban_db_connect import connect_closing
  171. from hermes_cli import kanban_db as kb
  172. with connect_closing(Path(context['db'])) as conn:
  173. with kb.write_txn(conn):
  174. task = kb.get_task(conn, context['task_id'])
  175. if (task is None or task.status != 'running' or task.current_run_id != context['run_id']
  176. or task.claim_lock != context['claim_lock']):
  177. raise RuntimeStoreError('stale_kanban_claim')
  178. # The dispatcher's spawned worker stays the run's pid (reclaim, timeout and operator
  179. # kills target it; ``_watch_submitter`` ties this interpreter's life to it). The bound
  180. # interpreter is recorded beside it so a sweep can tell when the attempt is truly gone.
  181. from hermes_cli.kanban_db_dispatch import UNVERIFIED_WORKER_FINGERPRINT, _process_fingerprint
  182. fingerprint = _process_fingerprint(os.getpid()) or UNVERIFIED_WORKER_FINGERPRINT
  183. kb._append_event(conn, task.id, 'worker_bound', {'pid': os.getpid(), 'claim_lock': context['claim_lock'],
  184. 'started_at': fingerprint}, run_id=context['run_id'])
  185. claimed = conn.execute("SELECT payload, created_at FROM task_events WHERE task_id=? AND run_id=? AND kind='claimed' ORDER BY id DESC LIMIT 1",
  186. (task.id, context['run_id'])).fetchone()
  187. # Heartbeats extend the claim by the TTL the dispatcher claimed it with (a spawned worker
  188. # inherited it from the dispatcher's environment); this daemon's own default is not that.
  189. expires = json.loads(claimed[0]).get('expires') if claimed else None
  190. if isinstance(expires, int) and claimed[1]:
  191. env['HERMES_KANBAN_CLAIM_TTL_SECONDS'] = str(max(1, expires - int(claimed[1])))
  192. _watch_submitter(Path(context['db']), context['run_id'])
  193. os.environ.update(env)
  194. os.chdir(context['workspace'])
  195. _TURNS_DONE = threading.Event()
  196. def _watch_submitter(db, run_id):
  197. """The dispatcher's spawned worker is this attempt's handle: killing it (an operator, a
  198. timeout, an OOM kill) must end the attempt, as it did when the worker ran the agent itself.
  199. Exiting hard leaves no ``worker_result``, so the dead-worker sweep books this run's crash.
  200. The run row is re-read each tick: the dispatcher records the pid only after its spawn returns."""
  201. import os
  202. from hermes_cli.kanban_db_dispatch import _worker_alive
  203. def watch():
  204. with closing(sqlite3.connect(db.resolve().as_uri() + '?mode=ro', uri=True)) as conn:
  205. while not _TURNS_DONE.wait(1.0):
  206. try:
  207. row = conn.execute('SELECT worker_pid, worker_started_at FROM task_runs WHERE id=?', (run_id,)).fetchone()
  208. except sqlite3.Error:
  209. continue
  210. if row and row[0] and row[0] != os.getpid() and not _worker_alive(row[0], row[1]):
  211. os._exit(1)
  212. threading.Thread(target=watch, name='kanban-submitter-watch', daemon=True).start()
  213. def run_worker_turns(agent, frame, history):
  214. from gateway.session_managed_worker import worker_turn_scope
  215. from gateway.session_surface import arm_surface_turn
  216. with worker_turn_scope(frame):
  217. # The agent consumes explicit one-turn attributes, not the ContextVar: arm them exactly as
  218. # the in-process runner does (voice route marker + surface note on the user message).
  219. arm_surface_turn(agent)
  220. return _run_worker_turns(agent, frame, history)
  221. @contextlib.contextmanager
  222. def _worker_workspace(frame):
  223. """A managed worker's chat turn in its session's workspace, as the in-process turn runner binds it
  224. (#140665): the session id as the terminal task id, the route as the session key (persistent Docker
  225. keys the workspace container from it) and the frozen cwd as the session's mount. Yields the task
  226. id, or None for a frame with no session scope (nothing is bound then)."""
  227. session_id = (frame.get('scope') or {}).get('session_id')
  228. if not session_id:
  229. yield None
  230. return
  231. from gateway.session_authorities import served_profile_name
  232. from gateway.session_context import clear_session_vars, set_session_vars
  233. from gateway.session_policy import bind_turn_workspace, restore_policy
  234. from hermes_state_keys import profile_from_session_key
  235. policy = restore_policy(frame['policy'])
  236. route = frame.get('route') or session_id
  237. # The profile its in-process turns bind, so persistent Docker keys the container they and the
  238. # session's side agents use (#140665): a served secondary's name, which its routes carry
  239. # (``agent:<name>:``); none for the launch home, whatever its name (``hermes -p beta gateway``
  240. # keys ``agent:main:``, and only the default profile runs the multiplexer).
  241. profile = served_profile_name(frame.get('home'))
  242. tokens = set_session_vars(session_key=route, session_id=session_id,
  243. profile=profile if profile_from_session_key(route) == profile else '')
  244. try:
  245. bind_turn_workspace(policy, session_id)
  246. yield session_id
  247. finally:
  248. clear_session_vars(tokens)
  249. def _run_worker_turns(agent, frame, history):
  250. context = json.loads(frame['policy'].get('kanban_json') or 'null')
  251. if context is None:
  252. from gateway.session_display import worker_display_kwargs
  253. author = frame.get('turn_author')
  254. with _worker_workspace(frame) as task_id:
  255. return agent.run_conversation(frame['text'], conversation_history=history, **worker_display_kwargs(),
  256. **({'task_id': task_id} if task_id else {}),
  257. **({'turn_author': author} if author is not None else {}))
  258. from hermes_cli.turn_exit import credential_failure_flags, turn_exit_code
  259. code, last_output = 1, ''
  260. try:
  261. result = _run_task_turns(agent, frame, history, context)
  262. code = turn_exit_code(result, kanban_worker=True)
  263. last_output = str(result.get('final_response') or '')[-500:] if isinstance(result, dict) else ''
  264. return result
  265. except Exception as exc:
  266. code = turn_exit_code(None, kanban_worker=True, **credential_failure_flags(exc))
  267. raise
  268. finally:
  269. _record_worker_result(context, code, last_output)
  270. def record_start_failure(frame, exc):
  271. """The worker died before any turn ran (agent construction resolves credentials): book the
  272. one-shot CLI's credential exit (75 quota wall / 78 re-login / 1) instead of a bare crash."""
  273. context = json.loads(frame['policy'].get('kanban_json') or 'null')
  274. if context is None:
  275. return
  276. from hermes_cli.turn_exit import credential_failure_flags, turn_exit_code
  277. _record_worker_result(context, turn_exit_code(None, kanban_worker=True, **credential_failure_flags(exc)), '')
  278. def _record_worker_result(context, code, last_output):
  279. _TURNS_DONE.set()
  280. import os
  281. from hermes_cli.kanban_db_connect import connect_closing
  282. from hermes_cli import kanban_db as kb
  283. with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
  284. if _bound_worker_matches(conn, context):
  285. # Closing a run clears its claim/PID and replaces metadata; keep the
  286. # result in the immutable attempt event stream instead.
  287. kb._append_event(conn, context['task_id'], 'worker_result',
  288. {'pid': os.getpid(), 'claim_lock': context['claim_lock'], 'exit_code': code,
  289. 'last_output': last_output}, run_id=context['run_id'])
  290. def record_worker_loss(policy, reason, *, pid=None, bound=False):
  291. """Append a run-scoped ``worker_lost`` event for this attempt to the card's board.
  292. Dropped when the card has moved past the run (it says nothing about the current attempt).
  293. Never raises: the caller's own loss handling must not depend on the board write.
  294. """
  295. try:
  296. context = json.loads(policy.kanban_json or 'null')
  297. if not context:
  298. return
  299. from hermes_cli.kanban_db_connect import connect_closing
  300. from hermes_cli import kanban_db as kb
  301. run_id = int(context['run_id'])
  302. with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):
  303. row = conn.execute('SELECT status, current_run_id FROM tasks WHERE id=?',
  304. (context['task_id'],)).fetchone()
  305. if row is None or row[0] != 'running' or row[1] != run_id:
  306. return
  307. kb._append_event(conn, context['task_id'], 'worker_lost',
  308. {'reason': str(reason)[:200], 'claim_lock': context['claim_lock'],
  309. 'run_id': run_id, 'pid': pid, 'bound': bool(bound)},
  310. run_id=run_id)
  311. except Exception:
  312. import logging
  313. logging.getLogger(__name__).exception('kanban worker_lost record failed')
  314. def _bound_worker_matches(conn, context):
  315. import os
  316. row = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='worker_bound' ORDER BY id DESC LIMIT 1",
  317. (context['task_id'], context['run_id'])).fetchone()
  318. bound = json.loads(row[0]) if row else {}
  319. return (bound.get('pid'), bound.get('claim_lock')) == (os.getpid(), context['claim_lock'])
  320. def _bound_claim_is_live(context):
  321. """Retry proof for a managed worker: the frame's exact run/claim lease is live and unexpired,
  322. and THIS interpreter is the one ``bind_worker_context`` bound to it. The run's worker_pid is
  323. the dispatcher's spawned submitter here, so pid identity comes from ``worker_bound`` instead."""
  324. from agent.kanban_turn_recovery import worker_claim_is_live
  325. if not worker_claim_is_live(task_id=context['task_id'], db_path=context['db'], run_id=str(context['run_id']),
  326. claim_lock=context['claim_lock'], verify_pid=False):
  327. return False
  328. try:
  329. with closing(sqlite3.connect(Path(context['db']).resolve().as_uri() + '?mode=ro', uri=True)) as conn:
  330. return _bound_worker_matches(conn, context)
  331. except sqlite3.Error:
  332. return False
  333. def worker_result(path, params):
  334. """Read only the dispatcher's exact attempt; never infer success from admission settlement."""
  335. with closing(sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True)) as conn:
  336. row = conn.execute("SELECT payload FROM task_events WHERE run_id=? AND task_id=? AND kind='worker_result' ORDER BY id DESC LIMIT 1",
  337. (params['run_id'], params['task_id'])).fetchone()
  338. result = json.loads(row[0]) if row else {}
  339. return result if result.get('claim_lock') == params['claim_lock'] else {}
  340. def worker_exit_code(path, params):
  341. return worker_result(path, params).get('exit_code', 1)
  342. # Who wrote a card attempt's prompts: the dispatcher, never the operator, so memory providers do not
  343. # file "work kanban task t_..." and the worker's progress notes as the human's own turns (#137406).
  344. # Not a ``bot:<profile>`` id: a Bot Mode profile named ``kanban`` would share its memory key.
  345. KANBAN_TURN_AUTHOR = {'id': 'kanban:dispatcher', 'name': 'Kanban dispatcher', 'is_bot': True}
  346. def _run_task_turns(agent, frame, history, context):
  347. from agent.skill_commands import build_preloaded_skills_prompt
  348. skills, loaded, missing = build_preloaded_skills_prompt(context['skills'], task_id=agent.session_id)
  349. if missing and not loaded:
  350. raise ValueError('kanban_skills_unavailable')
  351. prompt = '\n\n'.join(p for p in (skills, context['context'], frame['text']) if p)
  352. result = agent.run_conversation(prompt, conversation_history=history, turn_author=KANBAN_TURN_AUTHOR)
  353. def recover(nudge):
  354. nonlocal result
  355. prior = result.get('messages') if isinstance(result, dict) else None
  356. result = agent.run_conversation(nudge, conversation_history=prior or
  357. agent._session_db.get_messages_as_conversation(agent.session_id),
  358. turn_author=KANBAN_TURN_AUTHOR)
  359. # Same in-place retry as the one-shot CLI worker (agent/kanban_turn_recovery.py), but the
  360. # carrier is this frame's bound claim, never the owner process's environment.
  361. from agent.kanban_turn_recovery import recover_failed_kanban_turns
  362. recover_failed_kanban_turns(recover, lambda: result, task_id=context['task_id'],
  363. claim_check=lambda: _bound_claim_is_live(context))
  364. from hermes_cli.turn_exit import turn_exit_code
  365. # Only a settled turn may continue the goal loop: an exhausted or denied recovery reaches
  366. # the honest exit path without re-entering the model under an unprovable claim.
  367. if not context['goal_mode'] or turn_exit_code(result, kanban_worker=True) != 0:
  368. return result
  369. from hermes_cli.goals import run_kanban_goal_loop, DEFAULT_MAX_TURNS
  370. from hermes_cli import kanban_db as kb
  371. from hermes_cli.kanban_db_connect import connect_closing
  372. def status():
  373. with connect_closing() as conn:
  374. return kb.goal_run_status(conn, context['task_id'], context['run_id'])
  375. def block(reason):
  376. with connect_closing() as conn:
  377. kb.block_task(conn, context['task_id'], reason=reason, expected_run_id=context['run_id'])
  378. def turn(prompt):
  379. nonlocal result
  380. result = agent.run_conversation(prompt, conversation_history=agent._session_db.get_messages_as_conversation(agent.session_id),
  381. turn_author=KANBAN_TURN_AUTHOR)
  382. return result.get('final_response', '')
  383. run_kanban_goal_loop(task_id=context['task_id'], goal_text=context['goal_text'], run_turn=turn,
  384. task_status_fn=status, block_fn=block, max_turns=context['goal_max_turns'] or DEFAULT_MAX_TURNS,
  385. first_response=result.get('final_response', ''))
  386. return result