diff --git a/docs/operations.md b/docs/operations.md index 1734d08..1a397aa 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -222,7 +222,7 @@ curl -H 'Tailscale-User-Login: you@example.com' -H 'Tailscale-User-Name: You' ht ## Agent sessions -`POST /api/tasks/{id}/sessions` starts a Claude session in the task's worktree and sends the prompt as its first turn; `POST /api/sessions/{id}/messages` starts later turns and `POST /api/sessions/{id}/interrupt` ends the current one. A message sent while a task session's turn is running, from the app, the lead's `send_message`, a parent's `message_subtask` or byre's review findings, is queued (`Manager.Message` in `internal/agents/queue.go`) in `task_inputs`, keyed by task and team member (`member`, empty on a task with one agent) so it survives a handoff to a new session, and recorded, in the same transaction, as a `user.queued` event (its `text`, `images` and `task_inputs` `id`, the sender as actor), and the request returns the running session with 202. `DELETE /api/tasks/{id}/queue/{input id}` takes a queued message back (`Manager.Withdraw`): under the task's queue lock (`queueLockKey`), which both hand-over paths (`deliverQueued`, `takeQueuedMidTurn`) hold from reading the queue until the message is sent or taken, whichever session of the task is delivering, it deletes the row and records a `user.unqueued` event with its `id`, or answers 409 once the message has been handed over (the row is gone). A model it carries is applied to the session at once and takes effect from the next turn. The agent gets queued messages after its next tool call, the same way as inbox answers (see "Inbox"): each is recorded as its own `user.message` with the sender as actor and `mid_turn: true`, and the agent reads them, headed " sent you this message while you were working", in the hook's `additionalContext` (Codex: `turn/steer`; Antigravity: a user message injected by its `PreInvocation` hook before the model's next call, `agyBeforeModel` in `internal/agents/antigravity.go`). Messages are handed over oldest first, stopping at the first one with images, since mid-turn delivery carries only text; none are handed over during a handoff turn. Whatever is still queued when the turn ends goes out one message per turn, ahead of held inbox answers, from `Deliver`; startup does the same for idle sessions. An interrupt holds all of that: after a turn ends interrupted, byre starts no turn on its own until someone sends the session a message (`Manager.interrupted`, true while the live session's `interrupted` flag is set, which the next `user.message` clears). The turn end delivers nothing, the ready-for-merge prompt waits, a message from byre, an agent (`message_subtask`) or the board is queued as if the session were running instead of starting a turn, and a lead holds its signals (a human's queued lead message still goes out). Whatever was held goes out mid-turn during, or at the end of, the next turn the human (or the lead's `send_message`) starts; an inbox answer starts a turn as usual. The flag is in memory only, so a byre restart releases what was held. Closing the task deletes its queued messages. `sqlite3 byre.db 'SELECT * FROM task_inputs'` lists them. A task has at most one session that isn't `completed` per team member, so a task with one agent has at most one (see "Teams"). A message may carry `model`; when it differs from the session's, byre writes it to `agent_sessions.model`, records a `session.model` event (shown as a note), and sends the live CLI a `set_model` control request before the message, so the switch applies from that turn and survives a resume (`--model`) or compaction. The composer's model menu sends `model` only when the choice differs from the session's model, or from the `session.context` model when the session has none. The session's commits use the git identity of the user who created it, so that user must have set one with `PUT /api/me`. +`POST /api/tasks/{id}/sessions` starts a Claude session in the task's worktree and sends the prompt as its first turn; `POST /api/sessions/{id}/messages` starts later turns and `POST /api/sessions/{id}/interrupt` ends the current one. A message sent while a task session's turn is running, from the app, the lead's `send_message`, a parent's `message_subtask` or byre's review findings, is queued (`Manager.Message` in `internal/agents/queue.go`) in `task_inputs`, keyed by task and team member (`member`, empty on a task with one agent) so it survives a handoff to a new session, and recorded, in the same transaction, as a `user.queued` event (its `text`, `images` and `task_inputs` `id`, the sender as actor), and the request returns the running session with 202. `DELETE /api/tasks/{id}/queue/{input id}` takes a queued message back (`Manager.Withdraw`): under the task's queue lock (`queueLockKey`), which both hand-over paths (`deliverQueued`, `takeQueuedMidTurn`) hold from reading the queue until the message is sent or taken, whichever session of the task is delivering, it deletes the row and records a `user.unqueued` event with its `id`, or answers 409 once the message has been handed over (the row is gone). A model it carries is applied to the session at once and takes effect from the next turn. The agent gets queued messages after its next tool call, the same way as inbox answers (see "Inbox"): each is recorded as its own `user.message` with the sender as actor and `mid_turn: true`, and the agent reads them, headed " sent you this message while you were working", in the hook's `additionalContext` (Codex: `turn/steer`; Antigravity: a user message injected by its `PreInvocation` hook before the model's next call, `agyBeforeModel` in `internal/agents/antigravity.go`). Messages are handed over oldest first, stopping at the first one with images, since mid-turn delivery carries only text; none are handed over during a handoff turn. Whatever is still queued when the turn ends goes out one message per turn, ahead of held inbox answers, from `Deliver`; startup does the same for idle sessions. An interrupt holds all of that: after a turn ends interrupted, byre starts no turn on its own until someone sends the session a message (`Manager.interrupted`, true while the live session's `interrupted` flag is set, which the next `user.message` clears). The turn end delivers nothing, the ready-for-merge prompt waits, a message from byre, an agent (`message_subtask`) or the board is queued as if the session were running instead of starting a turn, and a lead holds its signals (a human's queued lead message still goes out). Whatever was held goes out mid-turn during, or at the end of, the next turn the human starts; an inbox answer starts a turn as usual. The flag is in memory only, so a byre restart releases what was held. The lead can't start that turn either: every turn end whose turn was interrupted or ended in an error, and every process exit mid-turn, marks its `session.state` idle event `stopped: true`, and while a session's latest `session.state` event carries it (`Store.SessionStopped`), the lead's `send_message`, `answer_question`, `compact_task`, `merge_task` (for `target` `parent`, the parent's agent) and `discard_task` refuse with an error (`checkNotStopped` in `internal/agents/leadtools.go`), telling the lead to put it to the human in chat instead. For `send_message` the check is in `Manager.Message`, under the session's delivery lock, once it has read the session as idle; the idle state and its mark are written in one transaction (`Store.EndTurn`), so a turn that ends just as the lead sends can't slip past it. On a team task, `send_message` refuses the board post while any member is stopped. The mark is in the event log, so it survives a restart, and the next turn's `running` state lifts it, as does an answer to one of the session's questions recorded after it (an `inbox.updated` event with state `answered`), even one held behind another open question; the lead's own `answer_question` is refused meanwhile, so such an answer is the human's; the human's own message, answer, merge or discard is never refused. Closing the task deletes its queued messages. `sqlite3 byre.db 'SELECT * FROM task_inputs'` lists them. A task has at most one session that isn't `completed` per team member, so a task with one agent has at most one (see "Teams"). A message may carry `model`; when it differs from the session's, byre writes it to `agent_sessions.model`, records a `session.model` event (shown as a note), and sends the live CLI a `set_model` control request before the message, so the switch applies from that turn and survives a resume (`--model`) or compaction. The composer's model menu sends `model` only when the choice differs from the session's model, or from the `session.context` model when the session has none. The session's commits use the git identity of the user who created it, so that user must have set one with `PUT /api/me`. `users.default_model` is the model the app starts new work on: ⌘K's Start and New task (whose composer then offers it first), the Project tab's and TODO links' `start`, suggestion links' `start` and `discuss` (when there is no live lead session), and the composer of a task or lead with no live session. It is returned as `default_model` on `GET /api/me`, set with `PUT /api/me/default-model` from the Settings tab's Default model menu, and records `user.updated`, so every open app reloads it. The server itself never reads it: the lead's `create_task` and `start_todo` default to the lead's own model, and `create_subtask` to the parent session's. @@ -296,7 +296,7 @@ Each user has one long-running lead agent, shown in the left pane. It is not tie - **Messages.** `POST /api/me/lead/messages` sends the caller's message to their lead, starting a lead session when there is none. While the lead is mid-turn the message is held in `lead_inputs`; the lead's PostToolUse hook (Codex: `turn/steer` after each completed tool item; Antigravity: the `PreInvocation` hook) hands held messages over after its next tool call, like a task's queued messages (see "Agent sessions"), and any still held become its next turn. Signals are never handed over mid-turn. The composer stays enabled. `GET /api/me/lead/sessions` lists the caller's lead sessions; interrupt and compact use the usual session endpoints. - **Scrollback.** `GET /api/me/lead/events` returns a page of the caller's lead events in whole turns, `turns` of them (default 50): those after the `turns`+1'th `turn.ended` before `before` (or before the latest event, so the page also holds a turn still running), with `more` saying whether earlier events exist. The lead pane loads only the last page (see "Events"); when its top scrolls into view (an empty row kept first in the transcript), it fetches the page before its first event (`loadOlderLead` in `mac/Sources/Byre/Store.swift`), puts its rows in front (`TranscriptBuilder.prepend`) and scrolls back to the row that was first. A page starts just after a `turn.ended`, so rendering it from scratch matches how it drew as part of the whole history. Live events still append without limit until the app is relaunched. - **Signals.** Every published event goes through `Manager.Observe`. These become signals in `lead_inputs` for every user who has a lead session: `inbox.created` (a question with its choices and recommendation), `session.error` and `session.rate_limited` on a task, `inbox.updated` when a human answered a question (the signal also carries its text and the agent's recommendation, so the lead sees where the human departed from it), `task.created` (naming the TODO item it was started from, or a subtask's parent, if any), `task.merge_queued` ("'s merge was requested by and is held until the merge in progress in its project is done."), `task.merge_after_review` (" was set by to merge once the review of snapshot finishes with no findings."), `task.merge_after_review_cancelled` ("'s merge after review was cancelled by ."), `task.merge_after_review_dropped` (" didn't merge after the review: "), `task.merge_started` (" is merging, started by ."), `task.merged`, `task.discarded`, `turn.ended` with `summary: true` (" finished a turn:" with its `result` cut to 1500 characters), `task.workflow_stage` (" started stage "" of workflow "".") and `task.workflow_finished` (" finished workflow "":" with its output cut to 1500 characters), `review.started` (" started a review of snapshot ."), `review.finished` (" review of snapshot :" with the review's summary, `change` and findings, or why it failed or was skipped; `reviewLine` in `internal/agents/review.go`), `user.message` on a task from a human (see "Pane lock"), and `task.state` (" state: → .", or " state: ." for a new task; see "Task state in the store"). The store hands `Observe` all of one transaction's events together, and they become one signal, its `task.state` lines first, so a turn's summary always arrives with the state its turn end left the task in. A batch whose lines are all quiet is dropped instead of held (`quietSignal` in `internal/agents/lead.go`): `task.state`, `review.started`, and `task.created`, `task.merge_started`, `task.merged` and `task.discarded` by a human, unless the line carries "Your right pane is free" (see "Pane lock"). Quiet lines still ride along in a batch with anything else, and the "Tasks now" list that follows every batch shows each task's current state. The human switching the right pane is not a signal. A signal caused by the lead itself (actor ` (lead)`) is skipped, as is the update from an answer it gave. A task's `task.created` event carries the actor that created it, separately from its `created_by` login: tasks the lead creates with `create_task` or `start_todo` keep the human's login as `created_by` but have actor ` (lead)`. Whenever the lead is idle, byre sends the oldest held message from the human as its own turn, or else every held signal as one `byre` message headed "Signals since your last turn (n)", followed by "Tasks now:" with the `list_tasks` text and a line saying what the lead's right pane shows (task or project, and selected tab) and whether the human is working in it (`leadStateText` in `internal/agents/lead.go`). If collecting that fails, for example because a project's repository is gone, the batch is still sent, ending instead with "The task list and right pane state are unavailable:" and the error, which is also logged as `lead state`. Its guidance tells it not to respond to the human's own actions, and to make its final message exactly `NO_REPLY` when a batch needs nothing from it. A transcript (`quietReply` in `mac/Sources/Byre/TranscriptBuilder.swift`) never draws an `agent.message` whose last line is `NO_REPLY` (the model sometimes writes a sentence before it), and hides the live partial message while its text is still a prefix of it, so an empty one never takes up space. A lead turn that byre starts without a handoff (a signal batch or a handoff continuation) is held (`ctx.held`): its `byre` message is never drawn, the turn isn't opened, so the scanner stays off, its partial message stays hidden, and its tool calls, subagents and thinking are built into a held row list instead of the transcript. The turn is released, inserting those rows where the turn belongs, when it draws anything else: a real message, a note, or its own `turn.ended` when it ends without `NO_REPLY`. When it ends in `NO_REPLY` while still held, the held rows are dropped, so nothing of the turn ever appears; a turn that draws a real message anywhere in it keeps all of it, even when a later message is `NO_REPLY`. -- **Tools.** `list_tasks` (each project's active tasks with their state, each subtask noting its parent, a held merge (`merge_queued_at`) and a merge after review (`merge_after_review`) each noted, then a line listing the titles of its `TODO.md` items on the default branch that no active task was started from), `read_transcript` (a task's events in brief, the last `limit` or those after `after_seq`; closed tasks too), `search_closed_tasks` (see "Closing a task"), `read_inbox`, `read_status` (the `GET /api/admin/status` body as JSON, built by the same `Server.status`, which the server hands `agents.New`), `answer_question` (an `option` or `other` response recorded as the user, through the same checks as `POST /api/inbox/responses`), `send_message` (starts the task's agent if it has none; while it is mid-turn the message is queued through `Manager.Message` like the human's, see "Agent sessions", and the tool result says it was queued; on a team task it posts to the board, see "Teams"), `create_task` and `start_todo` (each with an optional `workflow` to freeze and run; `create_task` also takes `agents` to start a team), `create_project` (`name` and `repo_path`, created as the user by the same `Server.createProject` as `POST /api/projects`, which the server hands `agents.New`, so it publishes the same `project.created` event, and returned as JSON), `interrupt`, `compact_task`, `take_snapshot` (see "Snapshots"), `merge_task` (optional `target`: `main`, or `parent` for a subtask, see "Subtasks"), `discard_task`, `show`, `compact_self`, `read_knowledge` (see "Knowledge base"), the note tools (see "Notes") and the workflow tools (see "Workflows"). The lead also has Claude Code's own tools and reads worktrees by path. Messages it sends task agents have actor ` (lead)`, so they don't make the user a participant; tasks, merges, discards and answers are done as the user. Its guidance says to answer a question only when the answer is clear or the human gave it, and to merge or discard only when the human asks. +- **Tools.** `list_tasks` (each project's active tasks with their state, each subtask noting its parent, a held merge (`merge_queued_at`) and a merge after review (`merge_after_review`) each noted, then a line listing the titles of its `TODO.md` items on the default branch that no active task was started from), `read_transcript` (a task's events in brief, the last `limit` or those after `after_seq`; closed tasks too), `search_closed_tasks` (see "Closing a task"), `read_inbox`, `read_status` (the `GET /api/admin/status` body as JSON, built by the same `Server.status`, which the server hands `agents.New`), `answer_question` (an `option` or `other` response recorded as the user, through the same checks as `POST /api/inbox/responses`), `send_message` (starts the task's agent if it has none; while it is mid-turn the message is queued through `Manager.Message` like the human's, see "Agent sessions", and the tool result says it was queued; refused while the agent is stopped after an interrupt or error, see "Agent sessions"; on a team task it posts to the board, see "Teams"), `create_task` and `start_todo` (each with an optional `workflow` to freeze and run; `create_task` also takes `agents` to start a team), `create_project` (`name` and `repo_path`, created as the user by the same `Server.createProject` as `POST /api/projects`, which the server hands `agents.New`, so it publishes the same `project.created` event, and returned as JSON), `interrupt`, `compact_task`, `take_snapshot` (see "Snapshots"), `merge_task` (optional `target`: `main`, or `parent` for a subtask, see "Subtasks"), `discard_task`, `show`, `compact_self`, `read_knowledge` (see "Knowledge base"), the note tools (see "Notes") and the workflow tools (see "Workflows"). The lead also has Claude Code's own tools and reads worktrees by path. Messages it sends task agents have actor ` (lead)`, so they don't make the user a participant; tasks, merges, discards and answers are done as the user. Its guidance says to answer a question only when the answer is clear or the human gave it, and to merge or discard only when the human asks. - **Focus.** `users.focus` holds what the user's right pane shows: `project_id`, `task_id` and `tab` (the selected one). The tabs' order is fixed; neither the lead nor the human can change it. With a `task_id`, `project_id` is always that task's project, filled in by the server; with only a `project_id`, the pane shows that project with no task, which only the Project tab has anything for. `GET /api/me/focus` reads it; `PUT /api/me/focus` and the lead's `show` set it, refusing an unknown tab, a task that isn't active or an unknown project, and record a `focus.updated` event owned by the user. The app applies the focus at startup and on every `focus.updated` it didn't cause itself; the human's own changes (⌘K, the right pane's task picker, clicking a tab, a task link, a notification) are sent with `PUT /api/me/focus`. - **Pane lock.** A `show` of what the pane already shows (the same task, or the same project with no task, on the same selected tab; `sameView`) tells the lead so and changes nothing. Otherwise, while the human is working in the right pane (the app reports `focused` or `drafting`, below), the lead's `show` is refused with an error telling it to say in chat what it would have shown, unless its selected tab is `project` (the fallback the lead shows when nothing needs the human, so the human being there doesn't hold it) or the pane is finished (`Manager.paneFinished`): its task is merged, discarded or merging (`merging_by` or `finalizing` set), or the human is waiting on the task's agent (`Manager.paneWaiting`): the selected tab is `transcript`, the task's implementer session is running, the app reports no unsent text in the pane, and either the `user.message` that started the running turn came from the user after the pane last moved, or the pane last moved 10 seconds ago or more (`watchHold`). The pane's last move is the last `PUT /api/me/focus` or `show` that set it (`Manager.paneMoved`, in memory, so a restart counts as long ago). For the user's own message, unsent text reported before the turn started doesn't count, since the app's report of the composer emptying on send can arrive after the message does. A `user.message` on a task from a human (not `byre`, an agent or a lead) signals every lead " sent a message; its agent is working on it.", and the sender's own lead, when its pane shows that task and is waiting that way, also gets "Your right pane is free: the human is waiting on 's agent." Each `PUT /api/me/focus` from the user starts a 10-second timer (`endWatchHold`); when it fires, if the pane hasn't moved since, the app still reports the human in it, the user hasn't messaged the task since the move (that already freed it, above), and the pane is waiting that way, the lead gets the signal "Your right pane is free: the human has watched 's agent work for 10 seconds without typing." The lead's own `show` starts no timer. When a `task.merge_started`, `task.merged` or `task.discarded` event leaves a user's focused task finished that way, that user's signal for it gets a line "Your right pane is free: is merging." (or "is merged."/"is discarded."). The lead's guidance tells it to show the next thing that needs the human on that line, or, when nothing does, the project's Project tab with a short status in chat: one line per active task, then up to three TODO items it would start next, each with a reason, starting one only when the human picks it. It writes each item as a link to `#/todo//`; Markdown views draw that (`todo` in `mac/Sources/Byre/MarkdownView.swift`) as the title followed by `start` and `discuss` actions, as accent link text so the line stays selectable, that call `POST /api/projects/{id}/todo/tasks` with the user's default model, as the Project tab's do, or, once an active task was started from that item, the task's colour, dot and state, linking to it. When the lead suggests new work that isn't in TODO.md, its guidance tells it to write a link to `#/suggest///`, drawn by the same code with `start` and `discuss` buttons: `start` calls `POST /api/projects/{id}/tasks` with the title, the brief as `prompt` and the user's default model, which checks the user's git identity, creates the task and starts its agent in one request, with no lead turn in between; `discuss` sends the lead `POST /api/me/lead/messages` asking to discuss the suggestion, quoting its title and brief (with the user's default model only when the user has no live lead session). Once an active task in that project has the suggestion's title, it shows that task's state the same way. A chat view refills them whenever its transcript grows or tasks or sessions change. When that status says nothing new since its last one, it replies `NO_REPLY` instead. The app sends `PUT /api/me/pane-focus` with `focused` and `drafting` whenever either changes (`PaneFocus` in `mac/Sources/Byre/PaneFocus.swift`): `focused` is true while the window is key, the app is active and the keyboard focus or the last click is inside the right pane, so a click anywhere in it counts, not only on inputs and buttons; `drafting` while any text field in the right pane other than the terminal holds non-blank text. The window reports to the server it shows. It sends false on deactivating, switching to another server, Forget Server, closing the window and quit, and resends true when its event stream reconnects. byre keeps both flags and the time of the last report in memory per user (`Manager.paneFocus`, `Manager.paneReported`), so they start false after a restart until the app resends them. - **Move hold.** Each `PUT /api/me/focus` from the user (switching task or tab, by any means: the switcher, a tab, a link or a notification) records the time in `Manager.humanMoved`, and for 10 seconds after it (`moveHold`) every `show` that would change the view is refused, whatever the pane lock above would allow, with an error giving how long ago the move was. A `show` of what the pane already shows changes nothing and says so. A refusal also marks the user in `Manager.moveRefused`, which each move by the user clears. When the 10 seconds pass without another move by the user (`endMoveHold`, on a timer), byre clears both and, only if a `show` was refused since that move, sends the lead the signal "The move hold is over: …"; its guidance tells it to show what it held back if the pane's other rules allow, or reply `NO_REPLY`. Because only a refusal arranges the signal, the lead's system prompt and the `show` tool's description tell it to call `show` at once whenever the user asks to see something or it wants to show something, never holding back in expectation of a refusal. It is in memory, so a restart clears it. diff --git a/internal/agents/lead.go b/internal/agents/lead.go index 79e88ef..517d49b 100644 --- a/internal/agents/lead.go +++ b/internal/agents/lead.go @@ -45,6 +45,10 @@ func leadActor(login string) string { return login + " (lead)" } +func isLeadActor(actor string) bool { + return strings.HasSuffix(actor, " (lead)") +} + func humanActor(actor string) bool { return actor != "byre" && actor != agentActor && actor != boardActor && !strings.HasSuffix(actor, leadActor("")) } diff --git a/internal/agents/leadtools.go b/internal/agents/leadtools.go index 372a36d..38f198a 100644 --- a/internal/agents/leadtools.go +++ b/internal/agents/leadtools.go @@ -111,7 +111,7 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { tool("answer_question", "Answer an open question on the human's behalf. Only when the answer is clear or the human told you it. "+ "type option: options holds the chosen choices' exact text (one for pick-one), and text may add notes."+ - "type other: free text.", + "type other: free text."+stoppedRefusal, `{"type": "object", "properties": { "item_id": {"type": "string"}, "type": {"type": "string", "enum": ["option", "other"]}, @@ -124,6 +124,18 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { if err != nil { return "", err } + item, err := m.store.GetInboxItem(ctx, c.ItemId) + if err != nil { + return "", err + } + sess, err := m.store.GetSession(ctx, item.AgentSessionId) + if err != nil { + return "", err + } + err = m.checkNotStopped(ctx, sess) + if err != nil { + return "", err + } m.mu.Lock() m.leadAnswered[c.ItemId] = true m.mu.Unlock() @@ -141,7 +153,8 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { "Send a message to a task's agent; it starts a turn. Starts the agent when the task has none. "+ "If the agent is mid-turn, the message is queued like the human's: the agent reads it with its next tool call's result, "+ "or as its next turn if it makes no further tool call, and gets it only once. "+ - "On a team task, the message is posted to the team's board instead, so every agent of the team gets it the same way; model is refused there.", + "On a team task, the message is posted to the team's board instead, so every agent of the team gets it the same way; model is refused there, "+ + "and so is the post while any agent of the team is stopped."+stoppedRefusal, `{"type": "object", "properties": { "task_id": {"type": "string"}, "text": {"type": "string"}, @@ -172,6 +185,10 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { if args.Model != "" { return "", fmt.Errorf("%w: model can't be given for a team task; its agents keep their own models", ErrInvalid) } + err = m.checkTeamNotStopped(ctx, task.Id) + if err != nil { + return "", err + } err = m.Post(ctx, task, leadActor(user.Login), args.Text) if err != nil { return "", err @@ -359,7 +376,7 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { return "Interrupted.", nil }), - tool("compact_task", "Have a task's idle agent write a handoff and continue in a fresh session.", + tool("compact_task", "Have a task's idle agent write a handoff and continue in a fresh session."+stoppedRefusal, `{"type": "object", "properties": { "task_id": {"type": "string"}, "model": {"type": "string", "description": "Start the fresh session on this model, on either vendor; the current agent still writes the handoff. Defaults to the current model."} @@ -376,6 +393,10 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { if err != nil { return "", err } + err = m.checkNotStopped(ctx, sess) + if err != nil { + return "", err + } _, err = m.Compact(ctx, sess.Id, args.Model) if err != nil { return "", err @@ -387,7 +408,7 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { "Merge a task as the human: its agent merges the default branch in, then byre squashes it into one commit, pushes it to origin and closes the task. "+ "While another task in the project is merging, byre holds the merge and starts it when that one is done. "+ "For a subtask, target parent instead asks its parent task's agent to merge it into the parent's branch, and the subtask closes once the parent has. "+ - "Refused for a task with active subtasks. Only when the human asks. You get a signal when it is merged; failures show as errors in the task's transcript, and you get a signal for each.", + "Refused for a task with active subtasks. Only when the human asks. You get a signal when it is merged; failures show as errors in the task's transcript, and you get a signal for each."+stoppedRefusal, `{"type": "object", "properties": { "task_id": {"type": "string"}, "target": {"type": "string", "enum": ["main", "parent"], "description": "Default main."} @@ -406,7 +427,17 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { } switch args.Target { case "", "main": + err = m.checkTaskNotStopped(ctx, task.Id) + if err != nil { + return "", err + } case "parent": + if task.ParentTaskId != nil { + err = m.checkTaskNotStopped(ctx, *task.ParentTaskId) + if err != nil { + return "", err + } + } _, err = m.MergeIntoParent(ctx, task, user) if err != nil { return "", err @@ -440,13 +471,17 @@ func (m *Manager) leadTools(l *live) []mcp.Tool { tool("discard_task", "Discard a task: its agent gets one turn to write the task summary, then byre stops it and deletes its worktree and branch without merging. This destroys its unmerged work. Refused for a task with active subtasks. Only when the human asks. "+ - "If the agent is mid-turn, the summary turn starts when that turn ends; no other turn runs in between.", + "If the agent is mid-turn, the summary turn starts when that turn ends; no other turn runs in between."+stoppedRefusal, taskOnly, func(ctx context.Context, user api.User, raw json.RawMessage) (string, error) { task, _, err := m.taskArg(ctx, raw) if err != nil { return "", err } + err = m.checkTaskNotStopped(ctx, task.Id) + if err != nil { + return "", err + } _, err = m.Discard(ctx, task, user.Login) if err != nil { return "", err @@ -784,6 +819,38 @@ func (m *Manager) liveSession(ctx context.Context, taskID string) (api.AgentSess return sess, true, nil } +const stoppedRefusal = " Refused while the agent is stopped: the human interrupted its last turn, or that turn ended in an error, and no turn has started since. Then put it to the human in chat instead." + +func (m *Manager) checkTaskNotStopped(ctx context.Context, taskID string) error { + sess, found, err := m.liveSession(ctx, taskID) + if err != nil || !found { + return err + } + return m.checkNotStopped(ctx, sess) +} + +func (m *Manager) checkTeamNotStopped(ctx context.Context, taskID string) error { + sessions, err := m.store.ListSessions(ctx, taskID) + if err != nil { + return err + } + for _, s := range teamSessions(sessions) { + err = m.checkNotStopped(ctx, s) + if err != nil { + return err + } + } + return nil +} + +func (m *Manager) checkNotStopped(ctx context.Context, sess api.AgentSession) error { + stopped, err := m.store.SessionStopped(ctx, sess.TaskId, sess.Id) + if err != nil || !stopped { + return err + } + return fmt.Errorf("%w: the human interrupted task %s's agent (or its last turn ended in an error) and hasn't messaged it since, so byre won't start a turn on it for you; put what you wanted to send or do to the human in chat instead", ErrConflict, sess.TaskId) +} + func (m *Manager) taskArg(ctx context.Context, raw json.RawMessage) (api.Task, api.Project, error) { args := struct { TaskID string `json:"task_id"` diff --git a/internal/agents/manager.go b/internal/agents/manager.go index 7fe955d..60af700 100644 --- a/internal/agents/manager.go +++ b/internal/agents/manager.go @@ -881,7 +881,7 @@ func (m *Manager) pump(l *live) { } } m.endMergeTurn(l.id, true) - next, _, err := m.store.EndTurn(ctx, l.id, agentActor, map[string]any{"error": "agent process exited mid-turn"}, nil, false, false) + next, _, err := m.store.EndTurn(ctx, l.id, agentActor, map[string]any{"error": "agent process exited mid-turn", "stopped": true}, nil, false, false) if err != nil { slog.Error("record session exit", "session", l.id, "err", err) } @@ -1186,8 +1186,12 @@ func (m *Manager) turnEnded(ctx context.Context, l *live, res endResult) error { unlock() held := len(l.subagents) > 0 || interrupted + var state map[string]any + if interrupted || res.isError { + state = map[string]any{"stopped": true} + } turn := m.event(l, agentActor, "turn.ended", payload) - next, finalizeBy, err := m.store.EndTurn(ctx, l.id, agentActor, nil, &turn, review && !held, finished && !handoff) + next, finalizeBy, err := m.store.EndTurn(ctx, l.id, agentActor, state, &turn, review && !held, finished && !handoff) if err != nil { return err } diff --git a/internal/agents/queue.go b/internal/agents/queue.go index d4b9e0c..1d2751c 100644 --- a/internal/agents/queue.go +++ b/internal/agents/queue.go @@ -47,6 +47,12 @@ func (m *Manager) Message(ctx context.Context, sessionID, actor, text, model str if err != nil { return api.AgentSession{}, false, err } + if sess.State == api.AgentSessionStateIdle && isLeadActor(actor) { + err = m.checkNotStopped(ctx, sess) + if err != nil { + return api.AgentSession{}, false, err + } + } held := sess.State == api.AgentSessionStateIdle && sess.Role == api.Implementer && automatedActor(actor) && m.interrupted(sess.Id) if !held && (sess.State != api.AgentSessionStateRunning || sess.Role != api.Implementer) { sess, err = m.Send(ctx, sessionID, actor, text, model, images...) diff --git a/internal/store/store.go b/internal/store/store.go index 53691cd..c8aaa16 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -1061,6 +1061,24 @@ func (s *Store) TaskHandoffs(ctx context.Context, taskID string) ([]Handoff, err return handoffs, rows.Err() } +func (s *Store) SessionStopped(ctx context.Context, taskID, sessionID string) (bool, error) { + stopped := false + err := s.db.QueryRowContext(ctx, ` + SELECT coalesce(json_extract(e.payload, '$.stopped'), 0) = 1 AND NOT EXISTS ( + SELECT 1 FROM events a + WHERE a.task_id = e.task_id AND a.agent_session_id = e.agent_session_id AND a.seq > e.seq + AND a.kind = 'inbox.updated' AND json_extract(a.payload, '$.state') = 'answered' + ) + FROM events e + WHERE e.task_id = ? AND e.agent_session_id = ? AND e.kind = 'session.state' + ORDER BY e.seq DESC LIMIT 1 + `, taskID, sessionID).Scan(&stopped) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + return stopped, err +} + func (s *Store) LeadEvents(ctx context.Context, owner string, after int64, limit int) ([]api.Event, error) { rows, err := s.db.QueryContext(ctx, ` SELECT `+eventColumns+`