Something went wrong. Try again.
MCP based ACP agent
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367"""goal_start / goal_done / goal_blocked / goal_reset — the model's four writesto the latch.
A goal is a latch. While the row is ``active``, the driver turns "the turnended" from a full stop into a loop-back edge and sends itself another turnwith nobody asking (:func:`crow_cli.agent2.driver.SessionDriver` at its idletransition). Nothing else about the mechanism is model-visible — no new eventtype, no client round trip, no second injection path — so the row is the wholeinterface: ``goal_start`` arms it, ``goal_done`` and ``goal_blocked`` release it,``goal_reset`` wipes it. The remainingstatuses belong to the user (``paused``) and to the arithmetic(``budget_limited``, and ``blocked`` when a turn errors or a continuationmakes no progress).
Four names, not one ``goal(status=...)``, for the reason:mod:`crow_cli.tools.task_tool` gives: a capability behind a mode-string dispatcheris a capability that does not get reached. The asymmetry here is the argumentlist — ``goal_start`` cannot be called without naming the objective and``goal_blocked`` cannot be called without saying why, and a dispatcher with anargument that is required on one branch and forbidden on the other is where arequirement like that goes to die.
``goal_start`` exists because the model is usually the first to know that along job has arrived: the plan-todo sprint mandate is "work the PLAN untileverything is complete", and a session that has to wait for a human to type``/goal`` stops at the end of the turn that read it. Arming is not the sameauthority as releasing, so it is the guarded one of the three — a goal already``active`` is left exactly as it stands (``set_goal`` mints a fresh id andzeroes ``turns_used``, and ``turns_used`` is the column the turn ceilingcounts, so a call that re-armed a running goal would be a call thatlengthened its own rope), and a goal the user ``paused`` is a refusal ratherthan a no-op: the brake is theirs, and a silent nothing would leave the modelbelieving a loop is running that is not. Over a goal that has already stopped— ``complete``, ``blocked``, ``budget_limited`` — it is the restart gesture``/goal <objective>`` is, and the fresh id and zeroed counters are exactlyright there.
``goal_reset`` is the fourth because one of the five statuses had nomodel-side exit at all. ``paused`` is the user's brake and the model must notlift it — but "must not resume the objective" and "may never touch the rowagain" are different rules, and the second left a session with a paused goalnowhere to go: ``goal_start`` refuses to arm over it (correctly), and the twoexits refuse to move a row that is not ``active`` (also correctly). Resetdeletes the row instead of resuming it, which is what makes it honest ratherthan a brake released — and it refuses an ``active`` goal, because a third wayout of a running loop that claims nothing is the one capability this modulemust not ship.
Neither raises on a goal that is already stopped, and both are idempotent.They are called at the end of a turn the model spent real reasoning on, andthe right answer to "I already said that" is "yes, and nothing changed" — notan exception that reads as though the work failed.
The session id comes off the identity rail execute's prologue injected, neveroff an argument: a model that could name the session whose goal it ends couldend somebody else's."""
from __future__ import annotations
import contextlib
import crow_cli.memory as cmfrom crow_cli.memory.models import ( GOAL_ACTIVE, GOAL_BLOCKED, GOAL_COMPLETE, GOAL_PAUSED,)from crow_cli.memory.reads import get_goalfrom crow_cli.memory.writes import clear_goal, set_goal, update_goal_status
from .register import CellContext, current_cell, db_uri, subtoolfrom .results import GoalError, GoalResult
#: ``GoalResult.status`` when the row is gone. Deliberately NOT in#: :mod:`crow_cli.memory.models` with the five row statuses: those enumerate#: what the column can hold, and this reports that no row is left to hold it.GOAL_CLEARED = "cleared"
# Same reason task.py, rlm.py and memory.py keep theirs in one:# importlib.reload re-executes this source in the EXISTING module dict, so a# module-level ``_engine = None`` would drop the handle on every reload() and# leak its connection pool._state: dict = globals().setdefault("_state", {})
def _dispose() -> None: """Drop the cached engine (test hygiene, and a db_uri that changed).""" engine = _state.get("engine") if engine is not None: with contextlib.suppress(Exception): engine.dispose() _state["engine"] = None _state["uri"] = None
def _engine(): """The WRITE engine for the injected crow.db, cached per uri.
Ending a goal is a write, so this is not the read-only handle rlm keeps. Same rail, same refusal: the kernel reads no config, so a caller outside one has to point the rail at a database itself. """ uri = db_uri() if uri is None: raise GoalError( "no database — ending a goal writes to the crow.db that execute's" " prologue injects on the identity rail; outside a kernel, point" " the rail at one with" " crow_cli.tools.register.begin_cell(db_uri=...)" ) if _state.get("uri") != uri: _dispose() _state["engine"] = cm.get_engine(uri) _state["uri"] = uri return _state["engine"]
def _session() -> str: """The session whose goal this ends, or a refusal.
Off the rail the prologue injected and never off an argument, so a cell can only ever end the goal of the session that is running it. """ cell: CellContext | None = current_cell() if cell is None or not cell.session_id: raise GoalError( "no session identity — a goal belongs to one session and this has" " to know which, which only exists inside an execute cell (the" " prologue injects it)" ) return cell.session_id
def _result(row, *, changed: bool) -> GoalResult: return GoalResult( status=row.status, objective=row.objective, reason=row.blocked_reason or "", changed=changed, turns_used=row.turns_used or 0, tokens_used=row.tokens_used or 0, token_budget=row.token_budget, time_used_seconds=row.time_used_seconds or 0, )
def _end(status: str, reason: str = "") -> GoalResult: """Write the exit, then read the row back and report what it says.
Read back rather than echoed, because the row is the mechanism and three processes write it: the status reported has to be the one the driver will actually find at the idle transition, not the one this call asked for. """ session = _session() engine = _engine() row = get_goal(engine, session) if row is None: raise GoalError( "no goal — this session has none set, so there is nothing to end." " A goal is the user's to set, and until one exists this session" " is not being continued automatically and neither exit applies." ) if row.status != GOAL_ACTIVE: # Somebody already stopped it: the user paused it, the budget ran out, # a turn errored, or an earlier call from this same model ended it. # Not this call's decision to overwrite — the same rule that makes # agent2.goal.eligible return Verdict(None, ...) rather than a status. return _result(row, changed=False) # The id it read, so a goal the user replaced mid-call is left running # rather than ended by a call that was about the previous one. changed = update_goal_status( engine, session, status, expected_goal_id=row.goal_id, blocked_reason=reason or None, ) return _result(get_goal(engine, session) or row, changed=changed)
@subtool(tool="goal_start")async def goal_start(objective: str) -> GoalResult: """Arm the goal: this session keeps working on ``objective`` by itself.
A turn that ends with the row ``active`` sends itself another turn with nobody asking, until the model calls :func:`goal_done` or :func:`goal_blocked` or a ceiling fires. That is the whole effect — no new event, no client round trip — and it is how a long job (a plan-todo sprint, "complete every item in TODO.md") survives the end of the turn that read it. It also survives a compaction: the row is keyed by the WIRE session id, not by the generation, so the next agent inherits the loop rather than the conversation that started it.
``objective`` is required and is stored verbatim. Every continuation turn shows it to the model and ``/goal`` shows it to the user, so it names the outcome and the criterion — "complete every item in TODO.md and PLAN.md, each verified by its stated criteria" — not "continue", not "the work".
Then TELL the user in prose, in the same turn: the objective, that this session now keeps working without them, and that ``/goal pause`` stops it while ``/goal`` shows where it is. The row is not a notification, and a loop the person does not know is running is a loop they cannot stop.
Guarded, because arming is not the same authority as releasing:
* a goal already ``active`` is left alone and comes back with ``changed=False``, objective included so a call that meant to replace it can see that it did not. Re-arming would mint a fresh id and zero ``turns_used`` — the column the turn ceiling counts. * a goal the user ``paused`` raises :class:`GoalError`. The brake is theirs: ``/goal resume`` picks the objective back up and ``/goal <objective>`` starts a new one. :func:`goal_reset` is the model-side way past it — it deletes the row rather than resuming the objective, so the sprint is over and a new one can be armed.
Over a goal that has already stopped (``complete``, ``blocked``, ``budget_limited``) this is a restart: fresh id, zeroed counters, new objective. The ceilings are config-owned (``goal.max_turns``, ``goal.max_tokens``) and deliberately not settable from in here — the kernel reads no config, and a budget the model guessed is either too low for the work or too high to be a limit.
Returns: GoalResult: the row read back — ``active``, the objective, and the spend, which is zero on a fresh arm. ``.changed`` is False when a goal was already running and this call did not move it. """ if not objective or not objective.strip(): raise GoalError( "goal_start needs the objective. Every continuation turn shows it" " to the model and /goal shows it to the user, so it names the" ' outcome and the criterion — goal_start("complete every item in' ' TODO.md and PLAN.md, each verified by its stated criteria") —' ' not goal_start("continue").' ) session = _session() engine = _engine() row = get_goal(engine, session) if row is not None and row.status == GOAL_PAUSED: raise GoalError( "the goal is paused — the user stopped it and lifting that is" " theirs, not yours: /goal resume picks the objective back up," " /goal <objective> starts a new one. Nothing was written, so this" " session is NOT being continued." ) if row is not None and row.status == GOAL_ACTIVE: return _result(row, changed=False) set_goal(engine, session, objective.strip()) return _result(get_goal(engine, session), changed=True)
@subtool(tool="goal_done")async def goal_done() -> GoalResult: """End the goal: the objective is met and no required work remains.
This is how an automatic continuation stops. Call it when what the user asked for is actually there — checked by looking, not by remembering the conversation — and NOT because the turn is over, the budget is running low, or you would like to stop. A goal marked complete that is not complete is worse than one left running: the loop stops and nothing tells anybody it stopped early.
Takes no arguments. What was achieved goes in your reply, where the user reads prose; this call only moves the row.
Returns: GoalResult: the row's status read back (``complete``), the objective, and what the goal spent getting there — turns, tokens against the budget, wall clock. ``.changed`` is False if the goal was already stopped by someone else and this call did not move it. """ return _end(GOAL_COMPLETE)
@subtool(tool="goal_blocked")async def goal_blocked(reason: str) -> GoalResult: """End the goal because it needs a person: the work cannot proceed.
``reason`` is required and is stored on the row verbatim. It is the only thing the user gets to read about why the work stopped, so it names the missing thing — "the deploy key is not in this environment", not "stuck", not "needs input".
Blocked means an external condition: information that is not available, access that is not granted, a decision only the user can make, or the same failure recurring with nothing left to try. It does NOT mean hard, slow, uncertain, unfinished, or "it would help to ask a question" — a goal that is merely not done yet is a goal that keeps going, and that is the feature. Do not use it as a way to end a turn.
Returns: GoalResult: the row's status read back (``blocked``) with the reason on it, plus the spend. ``.changed`` is False if the goal was already stopped by someone else and this call did not move it. """ if not reason or not reason.strip(): raise GoalError( "goal_blocked needs the reason. It is stored on the goal and it is" " the only thing the user reads about why the work stopped, so" ' call it as goal_blocked("the deploy key is not in this' ' environment") — naming the missing thing, not "stuck".' ) return _end(GOAL_BLOCKED, reason.strip())
@subtool(tool="goal_reset")async def goal_reset() -> GoalResult: """Clear the goal row: the latch is gone, and so is the objective.
The status this exists for is ``paused`` — the one a session otherwise has no way out of. ``goal_start`` refuses to arm over a pause, because the brake belongs to whoever pulled it, and the two exits refuse to move a row that is not ``active``; without this call a paused goal is a row the model can never touch again and a session that can never arm a new one.
Resetting is NOT resuming. The row is DELETED — objective, counters, blocked reason — so nothing continues and nothing is remembered. That is the whole difference from ``/goal resume``, and it is why clearing a pause this way is honest rather than a brake being lifted. To go again, arm a new goal with :func:`goal_start`, and tell the user the old one was cleared: a person who paused a loop and later sees a different one running is a person nobody told.
Refuses an ``active`` goal. A running loop has two exits and both say something — ``goal_done`` claims the work is verified complete, ``goal_blocked`` names what is missing — and a third that claims nothing would be a way to quit a goal without accounting for it.
Takes no arguments.
Returns: GoalResult: ``status`` is ``cleared``, which is not one of the five row statuses because there is no row left to read back, carrying the objective and the spend it had so the reply can say what was wiped. ``.changed`` is False when the row was replaced between the read and the delete, so this call deleted nothing. """ session = _session() engine = _engine() row = get_goal(engine, session) if row is None: raise GoalError( "no goal — this session has none set, so there is nothing to reset." " This clears a goal that has stopped, a paused one above all; one" " that was never armed is already nothing." ) if row.status == GOAL_ACTIVE: raise GoalError( "the goal is active, and resetting it would be a third way out of a" " running loop that claims nothing — goal_done says the work is" " verified complete, goal_blocked names what is missing. End it with" " one of those, then reset if the row should go too." ) cleared = clear_goal(engine, session, expected_goal_id=row.goal_id) return GoalResult( status=GOAL_CLEARED, objective=row.objective, reason=row.blocked_reason or "", changed=cleared, turns_used=row.turns_used or 0, tokens_used=row.tokens_used or 0, token_budget=row.token_budget, time_used_seconds=row.time_used_seconds or 0, )