diff --git a/docs/net/threat-model.md b/docs/net/threat-model.md index 6c028f7d6d..0d8b574cfd 100644 --- a/docs/net/threat-model.md +++ b/docs/net/threat-model.md @@ -262,6 +262,7 @@ After the launch, `thread_read`, `thread_wait`, `thread_send`, `thread_steer` an - **Only threads launched from here.** A qualified id is reachable only when `remote_launches` records it as launched by the calling thread or a thread of its lineage, and not from a private thread; any other is refused (`not_launched_here`) before anything is sent, so an agent cannot use a launched thread's id to read or change another thread there. The switch and the ticked computer are read again at every call (`computer_not_allowed`), except for a Stop: an agent may always stop work it started. `approval_respond` refuses a qualified id: an approval there waits for a person there. - **Reads** are the routed read rows a window uses (`runs.events`, `thread.messages`, `runs.get`, `runs.list`, `queue.list`, `orchestrator.pendingQuestions`), unmarked, and follow the device's ordinary read access there. They ask for the tool's page, not whole transcripts: `thread.messages` (version 3) takes `index`, `textOffset` and `textMax`, and the owner builds the same rows its own agents get, each text cut to the tool's limit and the page to 64 KB, so a large transcript does not cross and large reads keep sharing the two slots per computer with the windows. Every id in a result is named the way this computer names it before a tool sees it: the owner's threads qualified, this computer's own plain, and an agent sender (`origin.from`) by its thread on its own computer, so no id of another computer resolves to a thread here. - **Waiting** is one new read row, `runs.wait`: the owner waits at most 40 s on its own run events and answers when the run ends or waits on a person (`needs_input`); the caller gives it a 50 s deadline, under the minute an MCP client waits. A thread with a run preparing or a message in its queue is never answered idle. An owner without the row is asked `runs.get` every 4 s instead. +- **Settle watches.** `notify` on `thread_send` to such a thread, or on `thread_create` with `computer`, makes a watch that follows the run there with the same unmarked reads the launcher's own `thread_wait` would make (`runs.wait`, `runs.get`, `runs.list`, `queue.list`), one loop per watch, backing off while the computer does not answer; there is no new routed row and nothing there knows a watch exists. A computer that refuses this device, stops sharing or is too old ends the watch with one notice, and the 24-hour expiry bounds it otherwise. - **Messages, steers and Stops** are the marked `orchestrator.send`, `orchestrator.steer` and `orchestrator.abort` above, keyed by the caller's request key, so the owner's limits, envelope and reach apply exactly as for a launch's first message. A send whose link drops after it reached the computer is reported uncertain and not sent again by the caller. - **A person's Stop** of the launcher (and its deletion or expiry) sends a marked Stop for every thread it launched. A Stop that cannot be delivered is kept in its `remote_launches` row (run database 22), survives a restart, is sent when that computer answers, and is given up after a day; until then the launcher's transcript says the other run may still be going. The owner stops only runs this computer's agents started and leaves a thread a person took over. A later message from this computer to that thread supersedes a Stop still waiting, so it cannot end newer work. Nothing there is deleted. - **Reachability.** Every call first reaches the computer (its row versions) with a 10 s deadline of its own, then runs with its own deadline. A call that did not reach it is tried once more about a second later; only then is the computer called offline. A refusal names which reason it was (`computer_offline`, `computer_not_shared`, `computer_outdated`, `computer_not_allowed`, `remote_thread_gone`) with the computer's name, from that computer's answer to this call, never from the device list's online flag. diff --git a/docs/run-engine/SPEC.md b/docs/run-engine/SPEC.md index a19c75d600..10f26269ba 100644 --- a/docs/run-engine/SPEC.md +++ b/docs/run-engine/SPEC.md @@ -554,6 +554,7 @@ Every runtime except the pi loop reaches Mousse's own tools through one MCP serv - **The notice** is written by Mousse, never by either agent: the thread's title and link (`mousse://thread/`), what happened (finished, failed with its error, stopped, cancelled, never ran, waiting for a person, no longer watched), and for an end the run's reply (`run.result`) cut to `SETTLE_NOTICE_RESULT_CHARS` (2,000) with a pointer to `thread_read`. The message carries it structured (`ChatMessage.settleNotice`), and the chat shows it as a notice row that opens the thread, never as the person's message or an agent's bubble; `isPersonMessage` is false for it. - **Delivery** goes through the sender's message queue, as a `/goal` turn does: one item with source `thread-notice` (`mergeSettleNotice`). It starts a turn when the sender is idle and runs after the running turn when it is busy; notices that meet in the queue are delivered as one item. It never starts a turn (`QueuedMessage.heldNotice`: the drain skips it) in a subagent's thread (its result is its parent's: the held text joins the next `continue_subagent` follow-up), in a sender a person stopped after it subscribed (its stop generation rose), in a sender kept in Plan, or for the 24-hour notice. A held notice runs when a person sends it (Send now), when a notice that may start a turn joins it, or after the next turn a person starts in the thread (not a Plan turn). A paused sender holds it like any queued work (`thread-notice` is in `PAUSE_HELD_SOURCES`), and a Stop holds it with the rest of the queue (`heldAfterStop`). - **Hops.** The turn a notice starts carries the watched run's count of agent messages in a row and adds none of its own (`noticeHops` on the run's `send`; for notices that met, the largest); each further send from it adds one. A sender and a target can therefore go back and forth three times before a person must step in, while a thread that started five threads hears from all five. A notice never creates a watch. + - **A thread on another computer** (issue #1160): `notify` on `thread_send` to a thread this thread launched there, and on `thread_create` with `computer` and a `firstMessage` that was sent, makes a watch with `target_node` set and `target_thread_id` the id there (no new column). `RemoteSettleFollower` (`src/mms/orchestrator/remoteSettleFollow.ts`) follows each active one, and only those, with the reads `thread_wait` makes (`RemoteLaunchedThreads.follow`: `runs.wait`, or `runs.get` every 4 s on an older computer). When the run it follows ends, it reads that computer's newest 30 runs (`runs.list`, plus `runs.get` of the watched run) and its queue (`queue.list`) and resolves them with the same `followMessage`, so a pause handed on, a queued message a person edited and a steer handed back are followed as far as those reads show; the queue item is found on the first read. The first time the message's own run waits on a person there (`needs_input`, not for a run still queued) it writes the needs-input notice, then asks again every 15 s. The notice is the same kind, written here: the qualified link (`mousse://thread/:`), "on ", the reply `runs.wait` returned (cut there to 4,000 characters, here to 2,000, the pointer giving the full length), and the run's count read there, never below the count the send carried (the sender's run count plus one). A computer that does not answer (offline, Bridge off here, slow) is never an end: the loop backs off from 5 s to 5 min, and Bridge coming up wakes it. A computer that refuses this device, stops sharing (`computer_not_shared`), is too old (`computer_outdated`), or that the user stopped letting agents of this computer work on (`computer_not_allowed`) ends the watch once with status `unreachable` and the reason and computer's name; a thread deleted there ends it as `deleted`. A restart resumes every active watch from its row; a notice decided before it and delivered after has the status only, with the count the send carried. The 24-hour notice says the work had not ended when Mousse last reached that computer. - `thread_wait { threadId, runId?, timeoutMs? }` is for a turn that cannot continue without the answer (to hear about a result later, send with `notify`). It waits for a run of another thread (the named one, else the active one) for at most `timeoutMs` (default 45 s, at most 5 min; MCP clients give up on a call after about a minute). It subscribes to run events before it reads the run, so a run that ends in between is never missed, and always removes its listener. Results: `finished` (with the run's `status` and `interruptedBy`, its error text and `resultText` where the caller may read them), `timeout` (with a call-again hint; the wait never interrupts the target), `paused` (the run was still paused when the wait ran out: the result carries the pause and `retryAfterMs`, and the wait is never answered early; a wait that is running when the run resumes follows it into the run that continues it, `run.continuedFrom` names the paused one), `idle` (no run to wait for) and `caller_ended` (the caller's own run ended, which aborts the call). `resultText` is the `run.result` event of the waited run (kept only for what an agent can wait on, a run an agent sent and the run that continues one, besides a subagent's conversational runs; capped at 64 000 characters; deleted with the thread, and for the turns an undo hides; a person's own, a remote send's and a schedule's turns are not retained), never the latest message of the thread, cut to `THREAD_RESULT_MAX_CHARS` (4,000) characters with a marker (`resultTruncated`, `resultChars` and a pointer to `thread_read`; the delegation notice reads the stored text and is not cut by this), and is shown for the caller's own thread and any thread that exists; for an ancestor or sibling whose record is gone there is no text and no error text. - `thread_interrupt { threadId, runId, clientRequestId? }` is the one Stop (`stopThread`) aimed at a run, as the caller's: the run must still be the thread's active (or paused) run, or nothing is stopped and the conflict names the active run (`run_not_active`, with `expectedRunId` and `activeRunId`). It stops the subagents below the run too, ends a paused run and its pause, and leaves queued messages a person sent. It reaches a subagent only below the caller's own thread (a subagent of another thread is refused, like `thread_send`; its parent manages it). Runs it ends are `interruptedBy: 'agent'` (`RunOutcome.stopRequestedBy` is set in the Stop's transaction and `writeTerminalRun` turns the turn's `user` into `agent`); every place that treated `user` specially (no wake after the stop, a stopped subagent task, unredelivered notice rows) asks `stoppedByPerson`, so an agent's Stop settles as a person's. The one exception is the integration notice: a thread whose integration run an agent stopped still gets it, because its user may not know the run was cut off (the "Changed by an agent" row is not enough). - `thread_steer { threadId, runId, text, clientRequestId? }` adds the text, behind the same label, to the live turn named. A running turn cannot be narrowed, so a caller whose permission mode is stricter than the one the run is bound to is refused (`ceiling_exceeded`, with both modes); a run bound to a stricter mode than the caller's takes it. The comparison is made by the engine inside the transaction that accepts the steer, against the binding read there: a run that has not bound its turn yet (still `starting`) is refused (`steer_target_not_ready`), because an unknown mode is never read as the strictest. The sender's mode and origin travel with the steer (the `turn.steer` payload, the turn's steer entry, `SteerEntry`): a steer the turn never reads, one the provider hands back, and one that missed its turn become a turn of their own under the sender's mode, stored as the agent's and never merged into a person's text. It reaches a subagent only below the caller's own thread, and counts toward the hop limit. A paused run has no live turn (`run_paused`); a run that is not active is `run_not_active`. @@ -564,8 +565,8 @@ Every runtime except the pi loop reaches Mousse's own tools through one MCP serv - **First message and counts.** `firstMessage` is sent through `thread_send`'s own path as the caller's message (label, `origin`, the caller's mode on the turn, `preemptQuestions: false`, key `:first`), so it counts as the next agent message in a row: a creation whose message would be past `AGENT_MESSAGE_MAX_HOPS` is refused before anything is recorded or made (`agent_hops_exceeded`), while a thread made without a message is no hop. The count is carried by runs that carry on agent work (`inheritedAgentHops`): a wake that delivers a subagent's result and a provider's own continuation take the count of the thread's previous run, and the resume after a usage-limit pause (timer or "Resume now") that of the paused run; a person's message and a person's "Continue" start at zero. A run may create `THREAD_CREATE_MAX_PER_RUN` (5) threads (counted in memory), and a creator thread may have at most `THREAD_CREATE_MAX_ACTIVE_PER_THREAD` (10) launched threads with a queued, running or paused run at once, counted from the run store whatever its runs or restarts (`creation_limit`). - **A person's Stop.** A Stop that a person (or the system, not an agent) aims at a thread also stops the threads that thread launched while they have work an agent started (`outcome.sentByAgent`), which ends that work and clears the agent messages queued there; a launched thread a person is working in is left alone, and an agent's own Stop does not cascade. - **Decided first, made second.** Everything that can refuse (project, workspace, cap, model, hops) is checked, then the whole launch is written to a receipt (`commandKind: 'thread_create'`, key `thread_create::`): the new thread's id, project path, title, worktree flag, Git flag, model, mode, creator, actor and first message. Every later step, in the same call, in a retry or after a restart, is made from that stored intent, never from the caller's arguments, mode or the settings of the moment; a stored creation whose mode is missing or unknown is refused, not defaulted. A retry with other arguments is `mousse_conflict` (`client_request_id_conflict`), and two calls with one key at once make one thread (the second is told it is a replay). The thread is made with `ThreadDataStore.createThread({ id })`, which refuses an id that exists; the `agent.action` event `created_thread` (ids and names, no message) is the **completion marker**: a thread is complete only once it exists. A retry that finds files without the marker discards the thread (`discardUnusedThread`, which tells clients) and makes it again under the same id, as long as no one has used it. A thread a person has used (open in the daemon, a run, a message) or changed (renamed, another mode or model, archived, touched) is never adopted and never sent the agent's message: the retry is refused (`thread_in_use`) and the creator starts a new creation. A complete thread is returned with `replayed: true`, and the retry sends the first message when its receipt (`:first`) is missing. A retry of a stored creation takes no new place under the per-run cap, so past the cap it still finishes its own thread and first message. A first message that cannot be sent leaves the thread made and the result says why (`firstMessage: { sent: false, reason }`). At boot, a thread with a receipt (made in the last week, read in one query) but no marker that no one has used is discarded and clients are told; nothing is made at boot (the creator's retry makes it), so no half-made launched thread stays listed. `engine fsck` accepts `thread_create` receipts, which name a thread, not a run. The transcript row "created this thread" is added only by the call that made the thread. - - **On another computer** (`computer`, issue #1160). `thread_create { computer, projectId?, title?, workspace?, instanceId?, model?, effort?, firstMessage?, mode?, clientRequestId? }` starts a top-level thread on another of the user's computers instead (`OrchestratorService.createRemoteThreadAsAgent`). `projectId` is then optional and names a project of that computer. `notify` is refused with it: no watch follows a thread on another computer yet. Checked before anything is recorded, and refused with a code that names the reason and the computer: Bridge on (`remote_unavailable`), not a private thread (`private_thread`), not a thread another device started (`remote_from_remote`), the computer known (`unknown_computer`, `ambiguous_computer`), allowed ("Let agents work on your other devices", `agentAccess.remoteSubagents`, and that computer in `agentAccess.computers`: `computer_not_allowed`; the owner's agent reach `none` reads the same), online (`computer_offline`), sharing its threads with this one (`computer_not_shared`), knowing the agent mark on every marked row (`computer_outdated`; never an unmarked call), the working-at-once cap (`creation_limit`, counting this thread's local launched threads that are working and its launches still open), the hop count with a first message (`agent_hops_exceeded`), a model that computer offers (both `instanceId` and `model`, or neither for its default), and the project (`projects.match`: one strong match, or the named `projectId` among the strong candidates; else `no_matching_project` or `several_matching_projects` with `candidates [{ projectId, name, weak? }]`, which `projects.match` now returns when it has no single answer). Then the receipt (`commandKind: 'remote_thread_create'`, the same key as on one computer, with the computer and a fingerprint of the arguments) and a `remote_launches` row are written in one transaction, and `RemoteThreadLaunches` runs the sequence remote subagents use (`runRemoteThreadStart`: `threads.create` → `threads.setModel` → `composer.options` → `threads.setPermissionMode` → `orchestrator.send`), every write marked with `{ thread, run, title, hops, mode }` fixed at launch and keyed `:create|model|mode:|send`. The mode is the launcher's own (the stricter of its thread's and its run's); that computer narrows it to the limit it set for this one. `remote_launches` states: `starting` (nothing confirmed), `created` (the thread exists there), `launched` (set up; `first_message_state` is `none`, `pending`, `sent`, `failed` or `uncertain`), `abandoned` (refused for good, or given up after a day; a thread already made there is archived with `threads.settle`, never deleted). The result is `{ threadId: ":", link, computer, title, permissionMode, model, runId?, firstMessage?: "sent" | "failed" | "uncertain", firstMessageReason?, replayed }`; a thread that exists is returned even when its first message failed or is not confirmed, and a launch whose create is not confirmed answers `status: "uncertain"`. A retry with the same `clientRequestId` continues the same launch and takes no new place under the per-run cap; the same key with other arguments is `client_request_id_conflict`. A launch the call did not finish is finished by the service's passes (at boot, when Bridge comes up, and every few seconds while one is open), which first check that the computer is still allowed. When the thread first exists there, the launcher's thread gets a note drawn as a thread chip (`launchedThread.threadId` qualified). The working-at-once cap counts the launches still open and each launched thread its computer says is working (`runs.wait` with no wait, else its latest run); one that computer cannot be asked about counts as working. - - **The thread tools on it** (`RemoteLaunchedThreads`, issue #1160). `thread_read`, `thread_wait`, `thread_send`, `thread_steer` and `thread_interrupt` take the qualified id; each handler branches at its top (`isQualifiedId`) and the central check does not look at it (`localTarget`). `RemoteLaunchedThreads.reach` is the one place that decides which ids a caller reaches: a `remote_launches` row whose launcher is the caller or a thread of its lineage, not abandoned, from a thread that is not private; anything else is refused with a code (`not_launched_here`, `launch_abandoned`, `private_thread`, `invalid_thread_id`), never a bare not-found. `thread_read` returns the pages and bounds it has on one computer, read there (`runs.events`; `thread.messages` with `index`, `textOffset` and `textMax`, version 3, whose rows the owner builds with the same `messageRows`), with `computer` and `scope: "launched"`. `thread_wait` waits there (`runs.wait`, at most 40 s a call, repeated up to `timeoutMs`; on an owner without it, `runs.get` every 4 s) and returns `finished` (with the result text cut to 4,000 characters), `needs_input` (`needsInput: true`: the run waits on a person there), `paused`, `timeout` (with `pending` when a run is preparing or a message is queued) or `idle`; `RemoteLaunchedThreads.follow` is the same wait for a follower to call. `thread_send` and `thread_steer` are marked `orchestrator.send` and `orchestrator.steer` keyed by the tool's request key (`thread_send::`), at most 16,000 characters, with `delivery`; `notify` with a qualified id is refused. `thread_interrupt` is a marked `orchestrator.abort`; a run a person there started is refused (`not_started_by_this_computer`). A write the computer did not confirm answers `status: "uncertain"`. Every call has a 10 s connect deadline apart from its own, and one that did not reach the computer is tried once more a second later before it is refused `computer_offline`; refusals name the computer and the reason (`computer_offline`, `computer_not_shared`, `computer_outdated`, `computer_not_allowed`, `remote_thread_gone`). `approval_respond` refuses a qualified id. + - **On another computer** (`computer`, issue #1160). `thread_create { computer, projectId?, title?, workspace?, instanceId?, model?, effort?, firstMessage?, mode?, clientRequestId? }` starts a top-level thread on another of the user's computers instead (`OrchestratorService.createRemoteThreadAsAgent`). `projectId` is then optional and names a project of that computer. `notify` with it watches the first message's run there (see "Told when it settles"). Checked before anything is recorded, and refused with a code that names the reason and the computer: Bridge on (`remote_unavailable`), not a private thread (`private_thread`), not a thread another device started (`remote_from_remote`), the computer known (`unknown_computer`, `ambiguous_computer`), allowed ("Let agents work on your other devices", `agentAccess.remoteSubagents`, and that computer in `agentAccess.computers`: `computer_not_allowed`; the owner's agent reach `none` reads the same), online (`computer_offline`), sharing its threads with this one (`computer_not_shared`), knowing the agent mark on every marked row (`computer_outdated`; never an unmarked call), the working-at-once cap (`creation_limit`, counting this thread's local launched threads that are working and its launches still open), the hop count with a first message (`agent_hops_exceeded`), a model that computer offers (both `instanceId` and `model`, or neither for its default), and the project (`projects.match`: one strong match, or the named `projectId` among the strong candidates; else `no_matching_project` or `several_matching_projects` with `candidates [{ projectId, name, weak? }]`, which `projects.match` now returns when it has no single answer). Then the receipt (`commandKind: 'remote_thread_create'`, the same key as on one computer, with the computer and a fingerprint of the arguments) and a `remote_launches` row are written in one transaction, and `RemoteThreadLaunches` runs the sequence remote subagents use (`runRemoteThreadStart`: `threads.create` → `threads.setModel` → `composer.options` → `threads.setPermissionMode` → `orchestrator.send`), every write marked with `{ thread, run, title, hops, mode }` fixed at launch and keyed `:create|model|mode:|send`. The mode is the launcher's own (the stricter of its thread's and its run's); that computer narrows it to the limit it set for this one. `remote_launches` states: `starting` (nothing confirmed), `created` (the thread exists there), `launched` (set up; `first_message_state` is `none`, `pending`, `sent`, `failed` or `uncertain`), `abandoned` (refused for good, or given up after a day; a thread already made there is archived with `threads.settle`, never deleted). The result is `{ threadId: ":", link, computer, title, permissionMode, model, runId?, firstMessage?: "sent" | "failed" | "uncertain", firstMessageReason?, replayed }`; a thread that exists is returned even when its first message failed or is not confirmed, and a launch whose create is not confirmed answers `status: "uncertain"`. A retry with the same `clientRequestId` continues the same launch and takes no new place under the per-run cap; the same key with other arguments is `client_request_id_conflict`. A launch the call did not finish is finished by the service's passes (at boot, when Bridge comes up, and every few seconds while one is open), which first check that the computer is still allowed. When the thread first exists there, the launcher's thread gets a note drawn as a thread chip (`launchedThread.threadId` qualified). The working-at-once cap counts the launches still open and each launched thread its computer says is working (`runs.wait` with no wait, else its latest run); one that computer cannot be asked about counts as working. + - **The thread tools on it** (`RemoteLaunchedThreads`, issue #1160). `thread_read`, `thread_wait`, `thread_send`, `thread_steer` and `thread_interrupt` take the qualified id; each handler branches at its top (`isQualifiedId`) and the central check does not look at it (`localTarget`). `RemoteLaunchedThreads.reach` is the one place that decides which ids a caller reaches: a `remote_launches` row whose launcher is the caller or a thread of its lineage, not abandoned, from a thread that is not private; anything else is refused with a code (`not_launched_here`, `launch_abandoned`, `private_thread`, `invalid_thread_id`), never a bare not-found. `thread_read` returns the pages and bounds it has on one computer, read there (`runs.events`; `thread.messages` with `index`, `textOffset` and `textMax`, version 3, whose rows the owner builds with the same `messageRows`), with `computer` and `scope: "launched"`. `thread_wait` waits there (`runs.wait`, at most 40 s a call, repeated up to `timeoutMs`; on an owner without it, `runs.get` every 4 s) and returns `finished` (with the result text cut to 4,000 characters), `needs_input` (`needsInput: true`: the run waits on a person there), `paused`, `timeout` (with `pending` when a run is preparing or a message is queued) or `idle`; `RemoteLaunchedThreads.follow` is the same wait for a follower to call. `thread_send` and `thread_steer` are marked `orchestrator.send` and `orchestrator.steer` keyed by the tool's request key (`thread_send::`), at most 16,000 characters, with `delivery`; `notify` on `thread_send` watches the message there as on one computer. `thread_interrupt` is a marked `orchestrator.abort`; a run a person there started is refused (`not_started_by_this_computer`). A write the computer did not confirm answers `status: "uncertain"`. Every call has a 10 s connect deadline apart from its own, and one that did not reach the computer is tried once more a second later before it is refused `computer_offline`; refusals name the computer and the reason (`computer_offline`, `computer_not_shared`, `computer_outdated`, `computer_not_allowed`, `remote_thread_gone`). `approval_respond` refuses a qualified id. - **Stops there.** A person's Stop of a launcher (the cascade `stopThread` runs when no agent is the actor), its deletion (`stopRunsForDelete`) and its expiry (the expiry's quiesce) keep a Stop in each of its `remote_launches` rows (run database v22: `stop_state` `pending|sent|expired`, `stop_key`, `stop_reason` `stopped|deleted|expired`, `stop_deadline`, `stop_result`) and send it as a marked `orchestrator.abort` without a run, keyed `stop_key`, which the owner applies to the active or paused run only when an agent of this computer started it. One not delivered is sent again on each pass (every 5 s while any wait, at boot, and when Bridge comes up) until its deadline, a day later; the launcher's transcript says once that the run there may still be going, and again when the Stop arrives or is given up. A later `thread_send` from this computer to that thread supersedes a Stop still waiting. An agent's own Stop of the launcher does not cascade. - `approval_respond { threadId, requestId, answers, clientRequestId? }` answers a pending approval of another thread as the caller (`managesOthers`). It needs `settings.agentAccess.answerApprovals`, a switch that is off by default. It is a thin caller of the one settlement every client uses (`UserQuestionService.settle` -> `ThreadApprovals.settle`, §17.4); `canAnswerApproval` decides, with the caller's access read at that moment: the agent's own permission mode bounds what it may approve (it can never approve what its own mode would ask the user about, so it widens nothing), `allow_always` is refused (an agent never makes a standing rule), and its own thread is refused. The mode is the run's, narrowed by its thread's own mode now, so a thread set to Ask stops the answers of its running turn at once. For a thread outside its lineage it needs the three conditions above (`approvals_disabled`, `project_not_allowed`, else `not_parent`); a subagent is answered by its parent alone, and nothing in the agent's own lineage is answerable through the access branch (`not_parent`): not a subagent of a subagent, not its parent or an ancestor, and not a sibling or cousin (any thread that shares an ancestor with it). **A request the provider reserves for a person is refused to every agent** (`person_only`, also to a direct parent through `answer_subagent`): any request saved with a `reason` (Claude Code's own safety check under Full access, a path outside the allowed folders, one of the user's own ask rules, an ask it will not let be remembered), the same set a standing rule never answers. **A request of a turn a person started** (`startedByPerson`: the app or the CLI) is the person's too (`person_turn`, checked by the tool while the request is pending, so a late agent still learns who won); agents answer for turns that agents, jobs or subagents started. What an agent writes with its answer never reaches the asking agent as the user's words: an agent's `feedback` or typed text is cut to 200 characters on one line and redacted, and the rejection reason the asking agent reads is fixed ("Rejected by an agent in thread , not by the user.") with the note only as a quotation; an allow carries no text. A plain question for the user (`ask_user`) cannot be answered by the tool, and a bot's thread cannot be reached. The tool checks only that the request belongs to `threadId` (`mousse_conflict`, `request_not_pending`) and that the answer is not an "always" option; the request's state and the rule are decided by the settlement, so a person and an agent answering at once leave one winner and the other gets `already_answered` with who decided what (or `cancelled`). The key `approval_respond::` is saved as a receipt (`approval_respond`, filed under the caller's thread and run, naming the approval and its thread in `result`) before the answer: the same key for another request is `client_request_id_conflict`; a retry finds its own answer (the `approval.answered` event names the agent's thread, run and call) and returns `replayed: true`, while the same agent under another key, or another caller under the same key, lost. The answer is recorded by the `approval.answered` event (`answeredBy: { kind: 'agent', threadId, runId, toolCallId }`), and the winning call adds the transcript row "Approved by an agent in thread «title» (id): " (or "Rejected", with the agent's note), which is no message from the user; the action is the prompt collapsed to one line, redacted and capped at 400 characters, so it names the command or the path. An agent's answer to the last request of a run that died starts the continuation only when a person answered one of the group (§17.4); otherwise it waits for the person's Continue. `thread_list` returns each thread's pending requests with their option ids, without the "Always" option. - The engine writes the `agent.action` event of a send, Stop or steer in the same transaction as the change (`commitSend`, `commitControl`, `stopSubtree`: action `sent_message`, `stopped_run`, `steered_run`, with ids and lengths only), so a change never exists without its record; a replayed `clientRequestId` returns the first result and writes none. The transcript row ("Changed by an agent in thread …") is added after the commit by the call that made the change only; the event is the record of truth. The tool ledger of the caller's run records each call as any other tool. diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index 800c6fc8fd..242e7f799c 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -1285,6 +1285,8 @@ export class OrchestratorService extends EventEmitter { this.remoteLaunches?.start() // Stops kept while Bridge was off are sent now. this.remoteThreads?.start() + // Settle watches on threads there that waited to try again try now. + this.settleNotices?.remoteReachable() } } @@ -1958,6 +1960,8 @@ export class OrchestratorService extends EventEmitter { private questionRouterOff: (() => void) | null = null /** The settle notice (`notify`): the watches of messages agents sent, followed on this computer (SPEC §15.1). */ private settleNotices: SettleNotices | undefined + /** The first wait of a settle watch on another computer after a round that did not reach it (tests shorten it). */ + private remoteWatchRetryMs: number | undefined /** Pending retries of a queue item's row release (`releaseQueuedRows`); a shutdown clears them. */ private readonly releaseRetries = new Set>() /** Background repairs of unfinished agent queue commands tried so far, per thread. */ @@ -2901,6 +2905,18 @@ export class OrchestratorService extends EventEmitter { isSubagent: (threadId) => engine.delegations.getLineage(threadId)?.relationship === 'subagent', inPlan: (threadId) => this.lastChatModeOf(threadId) === 'plan', deliver: (threadId, notice, held) => this.queueSettleNotice(threadId, notice, held), + // A thread this computer's agent launched on another computer is followed there through routed reads (issue #1160). + remote: { + reads: () => this.remoteThreads, + launched: (node, remoteThreadId) => { + const record = engine.remoteLaunches.getByRemoteThread(node, remoteThreadId) + return record ? { computer: record.computerName, title: record.title } : undefined + }, + denial: (node, computer) => this.remoteThreadDenial(node, computer), + // What `remoteAgentMark` carried for a message of that run: its own count plus one. + sentHops: (runId) => (engine.getRun(runId)?.outcome?.agentHops ?? 0) + 1, + ...(this.remoteWatchRetryMs !== undefined ? { retryMs: this.remoteWatchRetryMs, needsInputRecheckMs: this.remoteWatchRetryMs } : {}) + }, delivered: (threadId, item) => { if (queueHasSettleNotice(queueOf(threadId), item)) return true try { diff --git a/src/mms/orchestrator/RemoteLaunchedThreads.ts b/src/mms/orchestrator/RemoteLaunchedThreads.ts index f41c345857..983837af09 100644 --- a/src/mms/orchestrator/RemoteLaunchedThreads.ts +++ b/src/mms/orchestrator/RemoteLaunchedThreads.ts @@ -106,8 +106,11 @@ export function remoteReachRefusal(error: unknown, computer: string, what: strin case 'route_unreachable': case 'bridge_off': return new RemoteThreadRefusal('computer_offline', `${computer} is offline, so ${what} did not reach it.`, computer) - case 'computer_forbidden': - return new RemoteThreadRefusal('computer_not_shared', `${computer} does not share its threads with this computer (${message}), so ${what} did not reach it.`, computer) + case 'computer_forbidden': { + // Why it refused (it blocked this device, turned sharing off), for a settle notice that says so. + const reason = error instanceof DomainRpcError && isRecord(error.details) && typeof error.details.reason === 'string' ? error.details.reason : undefined + return new RemoteThreadRefusal('computer_not_shared', `${computer} does not share its threads with this computer (${message}), so ${what} did not reach it.`, computer, reason ? { reason } : undefined) + } case 'computer_outdated': return new RemoteThreadRefusal('computer_outdated', `Update Mousse on ${computer}: it is too old for ${what} from an agent on this computer.`, computer) case 'agent_reach': @@ -240,7 +243,7 @@ export class RemoteLaunchedThreads { return localized(qualifyRoutedResult(method, value, { node, ...(self ? { self } : {}) }), self) } - private async read(target: RemoteTarget, method: string, params: Record, what: string, signal?: AbortSignal): Promise<{ value: unknown; versions: Record | undefined }> { + private async read(target: Pick, method: string, params: Record, what: string, signal?: AbortSignal): Promise<{ value: unknown; versions: Record | undefined }> { try { const { result, versions } = await this.call(target, method, { threadId: target.remoteThreadId, ...params }, { what, ...(signal ? { signal } : {}) }) return { value: this.named(target.node, method, result), versions } @@ -249,6 +252,14 @@ export class RemoteLaunchedThreads { } } + /** + * One read of the thread there, named as this computer names things; a failure is the refusal that says why. The + * settle notice's follower finds a watched message with it (`runs.list`, `runs.get`, `queue.list`). + */ + async readThread(target: Pick, method: string, params: Record, what: string, signal?: AbortSignal): Promise { + return (await this.read(target, method, params, what, signal)).value + } + // ------------------------------------------------------------------ reading /** `thread_read` view `events`: one page of the run events there, `limit` at most (the tool's own page). */ diff --git a/src/mms/orchestrator/remoteSettleFollow.ts b/src/mms/orchestrator/remoteSettleFollow.ts new file mode 100644 index 0000000000..edb2660a3e --- /dev/null +++ b/src/mms/orchestrator/remoteSettleFollow.ts @@ -0,0 +1,308 @@ +import { ROUTED_RUN_WAIT_MAX_MS } from '../../shared/bridge/routed' +import type { QueuedMessage } from '../../shared/types' +import { DomainRpcError } from '../protocol/domainRegistry' +import { followMessage, type Followed, type WatchTarget } from '../run/settle/follow' +import type { ThreadWatchRecord, ThreadWatches } from '../run/settle/ThreadWatches' +import { TERMINAL_RUN_STATUSES, type RunRecord } from '../run/types' +import type { RemoteTarget, RemoteWaitResult } from './RemoteLaunchedThreads' + +/** + * The settle notice for a thread this computer's agent launched on another computer (issue #1160, docs/plans/ + * agent-threads-architecture.md §4.2): a watch whose target is there (`thread_watches.target_node`) is followed through + * the routed reads `thread_wait` already makes (`RemoteLaunchedThreads.follow`: `runs.wait`, or polling on an older + * computer), plus `runs.list`, `runs.get` and `queue.list` to find where the message went. Nothing is written there and + * nothing there knows a watch exists. + * + * - **Only watched threads.** One loop per active watch, started when the watch is made or when the service starts + * (a restart resumes from the watch alone). Nothing follows a launched thread nobody asked about. + * - **Keyed on the message.** When the run it followed ends, the loop reads that computer's runs and queue and resolves + * them with the same `followMessage` as on one computer: a run a pause handed on, a queued message a person edited + * (its run cancelled, a fresh one `queue:` when it drains), a steer handed back to the queue. The message is + * only as visible as those reads: the newest `RUNS_READ` runs and the queue as it is now. + * - **Never a false end.** A computer that does not answer (offline, Bridge off here, slow) is asked again later, backing + * off up to `MAX_RETRY_MS`, until the watch's 24 hours end it. A computer that refuses this device, stops sharing its + * threads or is too old ends the watch once, with a notice that names it; so does the person turning agents on that + * computer off here, as it would refuse the launcher's own `thread_wait`. + * - **Never in the way.** Each loop is its own promise; a failure is caught and waited out, and no loop holds anything + * another call needs. + */ + +/** What a follow needs of the routed reads (`RemoteLaunchedThreads`). */ +export interface RemoteWatchReads { + follow(target: Pick, request: { runId?: string; timeoutMs: number; signal?: AbortSignal }): Promise + readThread(target: Pick, method: string, params: Record, what: string, signal?: AbortSignal): Promise +} + +export interface RemoteSettleHost { + /** The routed reads; undefined while this computer has no run engine attached. */ + reads(): RemoteWatchReads | undefined + /** The launched thread as its launch recorded it: the computer's name and the thread's title. */ + launched(node: string, remoteThreadId: string): { computer: string; title: string } | undefined + /** Why agents here may not work on that computer now (the person turned it off since); undefined when they may. */ + denial(node: string, computer: string): { code: string; message: string } | undefined + /** + * The count of agent messages in a row the watched send carried there: the least the run there counts (it takes the + * larger of that and its own count), and what a notice carries when that run's count cannot be read. + */ + sentHops(watcherRunId: string): number + /** The first wait after a round that did not reach the computer (default 5 s); it doubles up to `maxRetryMs`. */ + retryMs?: number + maxRetryMs?: number + /** How long a round waits while the work waits on a person and the notice is already sent (default 15 s). */ + needsInputRecheckMs?: number +} + +/** What a remote notice says about the run, read when it was decided (kept in memory until it is delivered). */ +export interface RemoteNoticeDetails { + runId?: string + error?: string + hops: number + resultText?: string + /** The reply's full length when that computer cut it before sending it. */ + resultChars?: number +} + +/** How the follower tells `SettleNotices` what it decided; both write the watch, then deliver. */ +export interface RemoteSettleDecisions { + needsInput(watchId: string, details: RemoteNoticeDetails): void + ended(watchId: string, status: string, runId: string | null, details: RemoteNoticeDetails | undefined): void +} + +/** Refusals that end a watch: that computer will not answer this device's reads, or agents here may not work there now. */ +const ENDS_WATCH: ReadonlySet = new Set(['computer_not_shared', 'computer_outdated', 'computer_not_allowed']) +/** Runs one read of that computer's runs takes: the message is followed among these. */ +export const RUNS_READ = 30 +/** One follow of the run lasts at most this long before the watch is read again (its expiry, a cancel). */ +const FOLLOW_SLICE_MS = 10 * 60_000 +/** Rounds of one watch are at least this far apart, so nothing spins on a computer that answers at once. */ +const MIN_ROUND_MS = 1_000 +const DEFAULT_RETRY_MS = 5_000 +const DEFAULT_MAX_RETRY_MS = 5 * 60_000 +const DEFAULT_NEEDS_INPUT_RECHECK_MS = 15_000 + +const isRecord = (value: unknown): value is Record => !!value && typeof value === 'object' && !Array.isArray(value) +const codeOf = (error: unknown): string => (error instanceof DomainRpcError ? error.code : String((error as { code?: unknown } | null)?.code ?? 'remote_error')) + +/** Where a resolve found the message, and the runs it read (the run it ended in, for the notice). */ +interface Located { + followed: Followed + queueItemId: string | null + runs: RunRecord[] +} + +export class RemoteSettleFollower { + private readonly loops = new Map }>() + private readonly wakers = new Set<() => void>() + private stopped = false + + constructor( + private readonly watches: ThreadWatches, + private readonly host: RemoteSettleHost, + private readonly decide: RemoteSettleDecisions, + private readonly now: () => number = () => Date.now() + ) {} + + /** Follows the watch unless a loop already does. */ + follow(watchId: string): void { + if (this.stopped || this.loops.has(watchId)) return + const controller = new AbortController() + const done = this.run(watchId, controller.signal) + .catch((error) => console.warn('a settle watch on another computer stopped following', { watchId, error: error instanceof Error ? error.message : String(error) })) + .finally(() => { + if (this.loops.get(watchId)?.controller === controller) this.loops.delete(watchId) + }) + this.loops.set(watchId, { controller, done }) + } + + /** Stops following one watch (it expired). */ + cancel(watchId: string): void { + this.loops.get(watchId)?.controller.abort() + this.loops.delete(watchId) + } + + /** Cuts every wait between attempts short: the computers may answer now (Bridge came up). */ + wake(): void { + for (const waker of [...this.wakers]) waker() + } + + stop(): void { + this.stopped = true + for (const { controller } of this.loops.values()) controller.abort() + this.loops.clear() + this.wake() + } + + /** The watches followed now (tests). */ + following(): string[] { + return [...this.loops.keys()] + } + + /** Waits for every loop to end (tests, after `stop`). */ + async settled(): Promise { + await Promise.all([...this.loops.values()].map((loop) => loop.done)) + } + + /** Waits `ms`, or less when the watch is cancelled or the computers may answer again. */ + private pause(ms: number, signal: AbortSignal): Promise { + if (ms <= 0 || signal.aborted) return Promise.resolve() + return new Promise((resolve) => { + const done = (): void => { + clearTimeout(timer) + signal.removeEventListener('abort', done) + this.wakers.delete(done) + resolve() + } + const timer = setTimeout(done, ms) + timer.unref?.() + signal.addEventListener('abort', done, { once: true }) + this.wakers.add(done) + }) + } + + private async run(watchId: string, signal: AbortSignal): Promise { + let failures = 0 + // A loop starts by finding the message: a restart may have missed a hand-off. + let locate = true + // The message waits in the queue for its run: the thread's next run is followed, then it is looked for again. + let awaiting = false + let lastRound = 0 + let lastReply: RemoteWaitResult | undefined + while (!signal.aborted && !this.stopped) { + const watch = this.watches.get(watchId) + if (!watch || watch.state !== 'active' || !watch.targetNode) return + const gap = this.now() - lastRound + if (gap < MIN_ROUND_MS) await this.pause(MIN_ROUND_MS - gap, signal) + if (signal.aborted) return + lastRound = this.now() + const target = { node: watch.targetNode, remoteThreadId: watch.targetThreadId, computer: this.host.launched(watch.targetNode, watch.targetThreadId)?.computer ?? 'that computer' } + try { + const denied = this.host.denial(target.node, target.computer) + if (denied) throw new DomainRpcError(denied.code, denied.message) + const reads = this.host.reads() + if (!reads) throw new DomainRpcError('computer_offline', 'Connecting to your other computers is turned off on this computer.') + if (locate) { + const found = await this.locate(reads, target, watch, signal) + locate = false + if (found.followed.kind === 'ended') { + await this.end(reads, target, watch, found, lastReply, signal) + return + } + if (found.followed.runId !== watch.runId || found.queueItemId !== watch.queueItemId) this.watches.follow(watchId, found.followed.runId, found.queueItemId) + awaiting = found.followed.kind === 'awaiting' + lastReply = undefined + continue + } + const reply = await reads.follow(target, { + ...(!awaiting && watch.runId ? { runId: watch.runId } : {}), + timeoutMs: awaiting ? ROUTED_RUN_WAIT_MAX_MS : FOLLOW_SLICE_MS, + signal + }) + failures = 0 + if (reply.callerEnded || signal.aborted) return + if (reply.status === 'timeout') { + // A run a pause handed on goes on in the run that continues it. + if (!awaiting && reply.continuedFrom && reply.run?.runId && reply.run.runId !== watch.runId) this.watches.follow(watchId, reply.run.runId) + if (awaiting) locate = true + continue + } + if (reply.status === 'needs_input') { + // The message's own run waits on a person there (a queued run is not the one asking). + if (!awaiting && reply.run && reply.run.status !== 'queued') { + if (reply.run.runId !== watch.runId) this.watches.follow(watchId, reply.run.runId) + if (watch.needsInput === null) this.decide.needsInput(watchId, { runId: reply.run.runId, hops: await this.hopsOf(reads, target, watch, reply.run.runId, signal) }) + } + if (awaiting) locate = true + // It waits on a person: asked again a little later, not at once (the wait there answers at once meanwhile). + await this.pause(this.host.needsInputRecheckMs ?? DEFAULT_NEEDS_INPUT_RECHECK_MS, signal) + continue + } + // The run ended there (or the thread has nothing to wait for): where is the message now? + lastReply = reply + locate = true + } catch (error) { + if (signal.aborted) return + const code = codeOf(error) + if (ENDS_WATCH.has(code)) { + const reason = isRecord((error as DomainRpcError).details) ? (error as DomainRpcError).details as Record : {} + this.decide.ended(watchId, `unreachable:${code}${typeof reason.reason === 'string' ? `:${reason.reason}` : ''}`, watch.runId, undefined) + return + } + if (code === 'remote_thread_gone') { + this.decide.ended(watchId, 'deleted', watch.runId, undefined) + return + } + // The run is not that thread's any more: the message is looked for among its runs and queue. + if (code === 'run_not_found') { + locate = true + continue + } + // Not reached, slow, or a hiccup: never an end. Asked again later, backing off. + failures += 1 + const first = this.host.retryMs ?? DEFAULT_RETRY_MS + await this.pause(Math.min(this.host.maxRetryMs ?? DEFAULT_MAX_RETRY_MS, first * 2 ** Math.min(failures - 1, 16)), signal) + } + } + } + + /** Reads that computer's runs and queue and resolves where the message is, as `followMessage` does on one computer. */ + private async locate(reads: RemoteWatchReads, target: Pick, watch: ThreadWatchRecord, signal: AbortSignal): Promise { + const read = (method: string, params: Record): Promise => reads.readThread(target, method, params, 'following the thread for a settle notice', signal) + const listed = await read('runs.list', { limit: RUNS_READ }) + const runs = (isRecord(listed) && Array.isArray(listed.runs) ? listed.runs : []).filter(isRecord) as unknown as RunRecord[] + if (watch.runId && !runs.some((run) => run.runId === watch.runId)) { + try { + const got = await read('runs.get', { runId: watch.runId }) + if (isRecord(got) && isRecord(got.run)) runs.push(got.run as unknown as RunRecord) + } catch (error) { + if (codeOf(error) !== 'run_not_found') throw error + } + } + const queue = await read('queue.list', {}) + const items = (isRecord(queue) && Array.isArray(queue.items) ? queue.items : []).filter(isRecord) as unknown as QueuedMessage[] + const byId = (runId: string): RunRecord | undefined => runs.find((run) => run.runId === runId) + const snapshot: WatchTarget = { + getRun: (runId) => byId(runId) ?? null, + continuationOf: (_threadId, runId) => runs.find((run) => run.outcome?.continuationOf === runId), + queueRun: (_threadId, itemId) => runs.filter((run) => run.clientRequestId === `queue:${itemId}`).sort((a, b) => b.ordinal - a.ordinal)[0], + queueItemForRun: (_threadId, runId) => items.find((item) => item.runId === runId && item.state !== 'claimed')?.id, + queueItem: (_threadId, itemId) => items.find((item) => item.id === itemId), + activeRun: () => runs.find((run) => run.status === 'starting' || run.status === 'running' || run.status === 'finalizing') ?? null + } + const queueItemId = watch.queueItemId ?? (watch.runId ? snapshot.queueItemForRun(watch.targetThreadId, watch.runId) ?? null : null) + return { followed: followMessage(snapshot, watch.targetThreadId, watch.runId, queueItemId), queueItemId, runs } + } + + /** The message's work ended there: its reply, error and count are read, then the watch ends. */ + private async end(reads: RemoteWatchReads, target: Pick, watch: ThreadWatchRecord, found: Located, lastReply: RemoteWaitResult | undefined, signal: AbortSignal): Promise { + const followed = found.followed as Extract + const run = followed.runId ? found.runs.find((entry) => entry.runId === followed.runId) : undefined + let details: RemoteNoticeDetails | undefined + if (run && TERMINAL_RUN_STATUSES.has(run.status) && followed.status !== 'removed') { + let reply = lastReply?.status === 'finished' && lastReply.run?.runId === run.runId ? lastReply : undefined + // The reply of a run the follow did not end on (a hand-off, a restart): one short wait on it, which answers at once. + if (!reply) reply = await reads.follow(target, { runId: run.runId, timeoutMs: 1_000, signal }).catch(() => undefined) + const text = reply?.status === 'finished' && reply.run?.runId === run.runId ? reply.resultText : undefined + details = { + runId: run.runId, + ...(run.outcome?.error ? { error: String(run.outcome.error) } : {}), + hops: Math.max(run.outcome?.agentHops ?? 0, this.host.sentHops(watch.watcherRunId)), + ...(text !== undefined ? { resultText: text.endsWith('…') && reply?.resultChars ? text.slice(0, -1) : text } : {}), + ...(reply?.resultChars ? { resultChars: reply.resultChars } : {}) + } + } + if (signal.aborted) return + this.decide.ended(watch.watchId, followed.status, followed.runId, details) + } + + /** The count of agent messages in a row of the run there, never below what the send carried. */ + private async hopsOf(reads: RemoteWatchReads, target: Pick, watch: ThreadWatchRecord, runId: string, signal: AbortSignal): Promise { + const floor = this.host.sentHops(watch.watcherRunId) + try { + const got = await reads.readThread(target, 'runs.get', { runId }, 'following the thread for a settle notice', signal) + const hops = isRecord(got) && isRecord(got.run) && isRecord(got.run.outcome) ? got.run.outcome.agentHops : undefined + return Math.max(typeof hops === 'number' ? hops : 0, floor) + } catch { + return floor + } + } +} diff --git a/src/mms/orchestrator/settleNotices.ts b/src/mms/orchestrator/settleNotices.ts index 3be1b35576..7b470fb852 100644 --- a/src/mms/orchestrator/settleNotices.ts +++ b/src/mms/orchestrator/settleNotices.ts @@ -1,9 +1,11 @@ import { SETTLE_NOTICE_RESULT_CHARS, SETTLE_WATCH_TTL_MS, type SettleNoticeItem } from '../../shared/settleNotice' import { threadLink } from '../../shared/threadLink' +import { qualifyId } from '../../shared/threadRef' import type { RunEngine } from '../run/RunEngine' import { followMessage, type WatchTarget } from '../run/settle/follow' import { ThreadWatches, type ThreadWatchRecord } from '../run/settle/ThreadWatches' import type { ThreadEvent } from '../run/types' +import { RemoteSettleFollower, type RemoteNoticeDetails, type RemoteSettleHost } from './remoteSettleFollow' /** The longest a timer waits before it looks at the watches' expiry again (setTimeout holds 2^31 - 1 ms at most). */ const EXPIRY_CHECK_MAX_MS = 60 * 60 * 1000 @@ -36,6 +38,8 @@ export interface SettleNoticeHost { deliver(watcherThreadId: string, notice: PlannedSettleNotice, held: boolean): void /** The sender's queue already carries this notice (a delivery repeated after a restart). */ delivered(watcherThreadId: string, item: Pick): boolean + /** Threads this computer's agents launched on other computers (issue #1160); without it only threads here are watched. */ + remote?: RemoteSettleHost now?(): Date } @@ -47,6 +51,9 @@ export interface SettleNoticeHost { * `deliver`), so it starts a turn when the sender is idle and waits behind a running one; notices that meet there are * delivered as one. Every decision is written to the watch before the notice is delivered, so a restart delivers what * was decided and re-reads what it missed. + * + * A watch on a thread this computer's agent launched on another computer is followed there by `RemoteSettleFollower` + * through routed reads; what it decides is written and delivered here the same way. */ export class SettleNotices { readonly watches: ThreadWatches @@ -55,9 +62,25 @@ export class SettleNotices { private expiryTimer: ReturnType | undefined private unsubscribe: (() => void) | undefined private stopped = false + /** Follows the watches on threads of other computers; absent without `host.remote`. */ + readonly remote: RemoteSettleFollower | undefined + /** What a remote notice says about its run, read when it was decided, by `:`, until delivered. */ + private readonly remoteDetails = new Map() constructor(private readonly host: SettleNoticeHost) { this.watches = new ThreadWatches(host.engine.store, () => this.now()) + this.remote = host.remote + ? new RemoteSettleFollower(this.watches, host.remote, { + needsInput: (watchId, details) => { + this.remoteDetails.set(`${watchId}:needs_input`, details) + if (this.watches.markNeedsInput(watchId)) this.deliverDue(this.watches.get(watchId)!) + }, + ended: (watchId, status, runId, details) => { + if (details) this.remoteDetails.set(`${watchId}:end`, details) + if (this.watches.markEnded(watchId, status, runId)) this.deliverDue(this.watches.get(watchId)!) + } + }, () => this.now().getTime()) + : undefined } private now(): Date { @@ -70,11 +93,19 @@ export class SettleNotices { this.unsubscribe = this.host.engine.store.onEvent((event) => this.onEvent(event)) for (const watch of this.watches.listDue()) this.deliverDue(watch) for (const watch of this.watches.listActive()) this.checkWatch(watch) + // A watch on another computer resumes from its row alone: its loop finds the message there again. + if (this.remote) for (const watch of this.watches.listActiveRemote()) this.remote.follow(watch.watchId) this.expireDue() } + /** The other computers may answer again (Bridge came up): every remote watch waiting to try again tries now. */ + remoteReachable(): void { + this.remote?.wake() + } + stop(): void { this.stopped = true + this.remote?.stop() this.unsubscribe?.() this.unsubscribe = undefined if (this.expiryTimer) clearTimeout(this.expiryTimer) @@ -85,7 +116,8 @@ export class SettleNotices { * Watches the message `messageKey` an agent just sent (once: a retry of the same send keeps its watch). The message is * read at once, so a run that ended before the watch existed is still told. */ - watch(input: { messageKey: string; watcherThreadId: string; watcherRunId: string; targetThreadId: string; runId: string }): ThreadWatchRecord { + watch(input: { messageKey: string; watcherThreadId: string; watcherRunId: string; targetThreadId: string; runId: string; targetNode?: string }): ThreadWatchRecord { + if (input.targetNode) return this.watchRemote({ ...input, targetNode: input.targetNode }) // A queued message keeps its queue item through an edit, a steer and a hand-back; its run may not. const queued = this.host.target.queueItemForRun(input.targetThreadId, input.runId) const { watch, created } = this.watches.create({ @@ -101,6 +133,24 @@ export class SettleNotices { return this.watches.get(watch.watchId) ?? watch } + /** + * Watches a message sent to a thread on another computer (`targetNode`, `targetThreadId` its id there). The follower + * finds its queue item there itself, on its first read. + */ + private watchRemote(input: { messageKey: string; watcherThreadId: string; watcherRunId: string; targetThreadId: string; runId: string; targetNode: string }): ThreadWatchRecord { + if (!this.remote) throw new Error('Mousse cannot watch threads on other computers here.') + const { watch, created } = this.watches.create({ + ...input, + watcherStopGeneration: this.host.stopGeneration(input.watcherThreadId), + ttlMs: SETTLE_WATCH_TTL_MS + }) + if (created) { + this.remote.follow(watch.watchId) + this.armExpiry() + } + return watch + } + /** Something about the thread changed that may move or settle a watched message (its queue, a question). */ touch(threadId: string): void { if (this.stopped) return @@ -163,11 +213,13 @@ export class SettleNotices { // A sender that is gone hears nothing; the decision is settled so it is not tried again. if (!this.host.threadLive(watch.watcherThreadId) || this.host.delivered(watch.watcherThreadId, { watchId: watch.watchId, event })) { this.watches.markSent(watch.watchId, which) + this.remoteDetails.delete(`${watch.watchId}:${which}`) return } const notice = this.plan(watch, event) this.host.deliver(watch.watcherThreadId, notice, this.held(watch, event)) this.watches.markSent(watch.watchId, which) + this.remoteDetails.delete(`${watch.watchId}:${which}`) } catch (error) { console.warn('a settle notice could not be delivered', { watchId: watch.watchId, event, error: error instanceof Error ? error.message : String(error) }) } @@ -185,6 +237,7 @@ export class SettleNotices { } private plan(watch: ThreadWatchRecord, event: SettleNoticeItem['event']): PlannedSettleNotice { + if (watch.targetNode) return this.planRemote(watch, watch.targetNode, event) const run = watch.runId ? this.host.target.getRun(watch.runId) : null return planSettleNotice({ watch, @@ -195,6 +248,27 @@ export class SettleNotices { }) } + /** + * A notice about a thread on another computer: named by its qualified id and its computer, with what the follower read + * when it decided. A notice decided before a restart and delivered after it has only the watch's row: its status, and + * the count the send carried. + */ + private planRemote(watch: ThreadWatchRecord, node: string, event: SettleNoticeItem['event']): PlannedSettleNotice { + const launched = this.host.remote?.launched(node, watch.targetThreadId) + const details = this.remoteDetails.get(`${watch.watchId}:${event === 'needs_input' ? 'needs_input' : 'end'}`) + const hops = details?.hops ?? this.host.remote?.sentHops(watch.watcherRunId) ?? 1 + const runId = details?.runId ?? watch.runId ?? undefined + return planSettleNotice({ + watch: { ...watch, targetThreadId: qualifyId(node, watch.targetThreadId) }, + event, + title: launched?.title ?? null, + computer: launched?.computer ?? 'another computer', + ...(runId ? { run: { runId, hops, ...(details?.error ? { error: details.error } : {}) } } : {}), + ...(event === 'ended' && details?.resultText !== undefined ? { resultText: details.resultText } : {}), + ...(event === 'ended' && details?.resultChars ? { resultChars: details.resultChars } : {}) + }) + } + /** Ends the watches whose 24 hours are over (each read once more first), and arms the timer for the next. The timer runs it. */ expireDue(): void { if (this.stopped) return @@ -205,6 +279,12 @@ export class SettleNotices { const current = this.watches.get(watch.watchId) if (current?.state === 'active' && this.watches.markExpired(watch.watchId)) this.deliverDue(this.watches.get(watch.watchId)!) } + // A watch on another computer stops following first; what its follow last saw stands. + for (const watch of this.watches.listActiveRemote()) { + if (Date.parse(watch.expiresAt) > now) continue + this.remote?.cancel(watch.watchId) + if (this.watches.markExpired(watch.watchId)) this.deliverDue(this.watches.get(watch.watchId)!) + } this.armExpiry() } @@ -226,8 +306,28 @@ function titleLine(title: string | null): string { return line || 'Untitled' } +/** + * Why a watch on another computer ended without the work ending (`unreachable:[:]`): that computer refused + * this device, stopped sharing its threads, is too old, or agents here may no longer work there. + */ +function unreachablePhrase(status: string, computer: string): string { + const [, code, reason] = status.split(':') + const stopped = `Mousse stopped watching it; read it with thread_read when ${computer} answers again.` + switch (code) { + case 'computer_not_shared': + return `can no longer be followed from here: ${reason === 'blocked' ? `${computer} refused this device` : reason === 'setting_off' ? `works on threads is off on ${computer}` : `${computer} does not share its threads with this computer any more`}. ${stopped}` + case 'computer_outdated': + return `can no longer be followed from here: Mousse on ${computer} is too old to report on it. Update Mousse there; until then Mousse does not watch it.` + case 'computer_not_allowed': + return `is no longer followed: the user turned off agents of this computer working on ${computer} (Settings → Agents → Agent access), so Mousse stopped watching it.` + default: + return `can no longer be followed from here (${code ?? 'refused'}). ${stopped}` + } +} + /** How a run's end reads: "finished", "failed: ", "was stopped". */ -function endPhrase(status: string, error: string | undefined): string { +function endPhrase(status: string, error: string | undefined, computer?: string): string { + if (status.startsWith('unreachable:')) return unreachablePhrase(status, computer ?? 'that computer') switch (status) { case 'completed': return 'finished' case 'failed': @@ -251,9 +351,13 @@ export function planSettleNotice(input: { title: string | null run?: { runId: string; error?: string; hops: number } resultText?: string + /** The thread is on another computer, named so; `watch.targetThreadId` is then its qualified id. */ + computer?: string + /** The reply's full length when it was cut before it got here (that computer sends at most 4,000 characters). */ + resultChars?: number }): PlannedSettleNotice { const { watch, event, run } = input - const thread = `thread "${titleLine(input.title)}" (${threadLink(watch.targetThreadId)})` + const thread = `thread "${titleLine(input.title)}"${input.computer ? ` on ${input.computer}` : ''} (${threadLink(watch.targetThreadId)})` const base: SettleNoticeItem = { watchId: watch.watchId, threadId: watch.targetThreadId, title: input.title, event, ...(run ? { runId: run.runId } : {}) } const hops = run?.hops ?? 0 const header = '[Mousse notice, not from the user or any agent: about the message you sent with notify.]' @@ -268,15 +372,21 @@ export function planSettleNotice(input: { return { item: base, hops, - text: `${header}\nMousse stopped watching ${thread} for you after 24 hours. The work your message started there is still going; read it with thread_read when you need it.` + text: input.computer + ? `${header}\nMousse stopped watching ${thread} for you after 24 hours. The work your message started there had not ended when Mousse last reached ${input.computer}; read it with thread_read when you need it.` + : `${header}\nMousse stopped watching ${thread} for you after 24 hours. The work your message started there is still going; read it with thread_read when you need it.` } } const status = watch.endStatus ?? 'completed' + const unreachable = status.startsWith('unreachable:') const reply = input.resultText?.trim() ?? '' const shown = reply.slice(0, SETTLE_NOTICE_RESULT_CHARS) - const cut = shown.length < reply.length - const lines = [`${header}\nThe work your message started in ${thread} ${endPhrase(status, run?.error)}${run && status !== 'removed' && status !== 'deleted' ? ` (run ${run.runId})` : ''}.`] + const total = Math.max(reply.length, input.resultChars ?? 0) + const cut = shown.length > 0 && shown.length < total + const phrase = endPhrase(status, run?.error, input.computer) + const said = `${phrase}${run && !unreachable && status !== 'removed' && status !== 'deleted' ? ` (run ${run.runId})` : ''}` + const lines = [`${header}\nThe work your message started in ${thread} ${said}${said.endsWith('.') ? '' : '.'}`] if (shown) lines.push(`Its reply:\n${shown}`) - if (cut) lines.push(`[The reply is cut at ${SETTLE_NOTICE_RESULT_CHARS.toLocaleString('en-US')} of ${reply.length.toLocaleString('en-US')} characters; read the rest with thread_read on thread ${watch.targetThreadId}.]`) - return { item: { ...base, status, ...(cut ? { cut: true } : {}) }, hops, text: lines.join('\n') } + if (cut) lines.push(`[The reply is cut at ${SETTLE_NOTICE_RESULT_CHARS.toLocaleString('en-US')} of ${total.toLocaleString('en-US')} characters; read the rest with thread_read on thread ${watch.targetThreadId}.]`) + return { item: { ...base, status: unreachable ? 'unreachable' : status, ...(cut ? { cut: true } : {}) }, hops, text: lines.join('\n') } } diff --git a/src/mms/run/mcp/appTools/host.ts b/src/mms/run/mcp/appTools/host.ts index f79d768d5c..2e9e0bd131 100644 --- a/src/mms/run/mcp/appTools/host.ts +++ b/src/mms/run/mcp/appTools/host.ts @@ -373,9 +373,10 @@ export interface AppToolHost extends DelegationToolsHost { /** * Watches the message `messageKey` sent to `targetThreadId` (`notify` on `thread_send` and `thread_create`): Mousse * tells the sending thread when the work it started waits on a person (once) and when it ends (SPEC §15.1). Once per - * message: a retry keeps its watch. + * message: a retry keeps its watch. With `targetNode`, `targetThreadId` is a thread this caller launched on that + * computer (its id there), followed there through routed reads. */ - watchSettle?(input: { messageKey: string; watcherThreadId: string; watcherRunId: string; targetThreadId: string; runId: string }): { watchId: string } + watchSettle?(input: { messageKey: string; watcherThreadId: string; watcherRunId: string; targetThreadId: string; runId: string; targetNode?: string }): { watchId: string } /** * Creates a thread for `actor` (`thread_create`): in the project's folder or its own worktree, on the model * asked for or the caller's, with a permission mode no wider than the caller's, recorded as launched by the diff --git a/src/mms/run/mcp/appTools/thread.ts b/src/mms/run/mcp/appTools/thread.ts index 1872cde4ea..f46a91c79b 100644 --- a/src/mms/run/mcp/appTools/thread.ts +++ b/src/mms/run/mcp/appTools/thread.ts @@ -11,7 +11,7 @@ import type { AgentCreatedThread, AgentQueueCommand, AgentQueueResult, AgentRunC import type { BotAppToolDeps } from './bots' import { threadLink } from '../../../../shared/threadLink' import { ROUTED_AGENT_BODY_MAX } from '../../../../shared/bridge/routed' -import { isQualifiedId } from '../../../../shared/threadRef' +import { isQualifiedId, parseQualifiedId } from '../../../../shared/threadRef' import { RemoteThreadRefusal, type RemoteTarget, type RemoteWaitResult } from '../../../orchestrator/RemoteLaunchedThreads' import { cutEnd, messageRows, textOffsetProblem, type MessageRow } from './messageRows' import type { BotActivityContext, BotActivitySink } from '../../../bots/seams' @@ -739,8 +739,8 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B * `notify`: one watch for the message sent with `messageKey` (a retry keeps it), and what the result says next. The * sender's turn is told to end rather than poll; Mousse writes the notice into its queue (SPEC §15.1). */ - const watchSent = (threadId: string, messageKey: string, actor: AgentActor, runId: string, ctx: ToolCallContext): { notify: { watchId: string; next: string } } => { - const { watchId } = host.watchSettle!({ messageKey, watcherThreadId: ctx.caller.threadId, watcherRunId: actor.runId, targetThreadId: threadId, runId }) + const watchSent = (threadId: string, messageKey: string, actor: AgentActor, runId: string, ctx: ToolCallContext, on?: { node: string }): { notify: { watchId: string; next: string } } => { + const { watchId } = host.watchSettle!({ messageKey, watcherThreadId: ctx.caller.threadId, watcherRunId: actor.runId, targetThreadId: threadId, runId, ...(on ? { targetNode: on.node } : {}) }) return { notify: { watchId, next: NOTIFY_NEXT } } } /** Messages each run has sent to other threads, in memory: a restart gives every run a fresh count. */ @@ -820,9 +820,9 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (args.mode !== undefined && args.mode !== 'agent' && args.mode !== 'plan') throw new Error('mode must be agent or plan') if (args.mode !== undefined && args.firstMessage === undefined) throw new Error('mode is the mode of firstMessage: give a firstMessage, or leave mode out.') if (args.hidden !== undefined) throw new Error('hidden is for personal bots: a thread an agent starts always shows in the sidebar.') - // Watching a thread on another computer is not built yet: refused rather than ignored, so nobody waits for a notice. - if (args.notify !== undefined && args.notify !== false) - throw new Error('notify does not reach a thread on another computer yet: leave it out, and read the thread there when you need its result.') + const notify = notifyArg(args, ctx) + if (notify && args.firstMessage === undefined) throw new Error('notify tells you when the work of firstMessage settles: give a firstMessage, or leave notify out.') + if (notify && !host.watchSettle) return notAvailable('thread_create with notify') const actor = actorOf(ctx) const requestKey = `thread_create:${ctx.caller.threadId}:${toolRequestId(args, ctx)}` // A retry of a stored launch takes no new place under the cap. @@ -853,8 +853,12 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (result.status === 'uncertain') return json({ ok: false, status: 'uncertain', computer: result.computer, message: result.message }) if (!uncounted && result.replayed) releaseCreation(actor.runId) const { status: _status, ...launched } = result + // Watched there once its first message is: a retry with the same key keeps the watch, or makes it once the message went. + const there = notify && launched.firstMessage === 'sent' && launched.runId ? parseQualifiedId(launched.threadId) : undefined + const watched = there ? watchSent(there.id, requestKey, actor, launched.runId!, ctx, { node: there.node }) : {} return json({ ...launched, + ...watched, link: threadLink(launched.threadId), note: launched.firstMessage === 'failed' ? `The thread exists on ${launched.computer}, but its first message was not delivered: ${launched.firstMessageReason ?? 'refused'}.` @@ -922,9 +926,8 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (typeof args.content !== 'string' || !args.content.trim()) throw new Error('thread_send requires content') if (args.mode !== undefined && args.mode !== 'agent' && args.mode !== 'plan') throw new Error('mode must be agent or plan') const mode = (args.mode as 'agent' | 'plan' | undefined) ?? 'agent' - // Following a thread on another computer to its end is not built yet: refused, so nobody waits for a notice. - if (args.notify !== undefined && args.notify !== false) - throw new Error('notify does not reach a thread on another computer yet, so the message was not sent. Send it again without notify; when this turn needs the result, call thread_wait.') + const notify = notifyArg(args, ctx) + if (notify && !host.watchSettle) return notAvailable('thread_send with notify') if (mode === 'agent' && ctx.caller.modeCeiling === 'plan') throw new McpToolError('mousse_ceiling_exceeded', 'A plan-ceiling caller can only send plan turns.') if (args.content.length > ROUTED_AGENT_BODY_MAX) throw new Error(`A message to another computer is at most ${ROUTED_AGENT_BODY_MAX.toLocaleString('en-US')} characters; this one has ${args.content.length.toLocaleString('en-US')}. Nothing was sent.`) @@ -943,7 +946,9 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (sent.status === 'uncertain') return json({ ok: false, status: 'uncertain', threadId: target.threadId, computer: target.computer, message: sent.message }) if (sent.replayed) releaseSend(actor.runId) const { status: _status, ...rest } = sent - return json({ threadId: target.threadId, computer: target.computer, ...rest, delivery: deliveryOf(sent) }) + // Watched there: Mousse follows that computer's run with reads and tells this thread when it settles. + const watched = notify && sent.runId ? watchSent(target.remoteThreadId, requestKey, actor, sent.runId, ctx, { node: target.node }) : {} + return json({ threadId: target.threadId, computer: target.computer, ...rest, delivery: deliveryOf(sent), ...watched }) }) /** `thread_steer` into the running turn of a thread this thread launched on another computer. */ const steerOnComputer = (threadId: string, args: Record, ctx: ToolCallContext): Promise => onComputer(async () => { @@ -1256,7 +1261,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_send', - description: `Send a message to another thread. The thread's model receives it labelled as a message from an agent in your thread, not from the user, and runs it under your permission mode when that is stricter than the thread's own; it never gets more than the thread itself allows. It starts a turn when the thread is idle and queues behind the running turn otherwise (it never steers the running turn). A thread kept in Plan takes it as a plan turn. Refused while the thread waits for the user to answer a question or approval, is paused by a usage limit, or is archived, when it already has ${AGENT_QUEUE_MAX_PER_SENDER} messages from your thread or ${AGENT_QUEUE_MAX_PER_THREAD} from agents in all waiting, when you sent it the same text in the last ${AGENT_REPEAT_WINDOW_MS / 60_000} minutes, and when it would be more than a few agent messages in a row without a person in between; each refusal names its limit (data.conflict). You may send ${THREAD_SEND_MAX_PER_RUN} messages per run (a personal bot has no such count). Set notify when you need the result: Mousse then tells you when the work settles (and once before that if it waits for a person), and you end your turn instead of waiting. Returns the run it created and delivery: started (a turn began with it) or queued (it waits behind the running turn). Subagents are reached with continue_subagent. ${REMOTE_REACH} A message there is at most ${ROUTED_AGENT_BODY_MAX.toLocaleString('en-US')} characters; status uncertain means that computer did not confirm it (call again with the same clientRequestId: it is never sent twice); notify does not reach it yet.`, + description: `Send a message to another thread. The thread's model receives it labelled as a message from an agent in your thread, not from the user, and runs it under your permission mode when that is stricter than the thread's own; it never gets more than the thread itself allows. It starts a turn when the thread is idle and queues behind the running turn otherwise (it never steers the running turn). A thread kept in Plan takes it as a plan turn. Refused while the thread waits for the user to answer a question or approval, is paused by a usage limit, or is archived, when it already has ${AGENT_QUEUE_MAX_PER_SENDER} messages from your thread or ${AGENT_QUEUE_MAX_PER_THREAD} from agents in all waiting, when you sent it the same text in the last ${AGENT_REPEAT_WINDOW_MS / 60_000} minutes, and when it would be more than a few agent messages in a row without a person in between; each refusal names its limit (data.conflict). You may send ${THREAD_SEND_MAX_PER_RUN} messages per run (a personal bot has no such count). Set notify when you need the result: Mousse then tells you when the work settles (and once before that if it waits for a person), and you end your turn instead of waiting. Returns the run it created and delivery: started (a turn began with it) or queued (it waits behind the running turn). Subagents are reached with continue_subagent. ${REMOTE_REACH} A message there is at most ${ROUTED_AGENT_BODY_MAX.toLocaleString('en-US')} characters; status uncertain means that computer did not confirm it (call again with the same clientRequestId: it is never sent twice); notify works there too: Mousse follows that computer's run and tells you when it settles.`, inputSchema: { type: 'object', properties: { diff --git a/src/mms/run/mcp/instructions.ts b/src/mms/run/mcp/instructions.ts index 2af8bc6e7b..3f19dce5c3 100644 --- a/src/mms/run/mcp/instructions.ts +++ b/src/mms/run/mcp/instructions.ts @@ -15,7 +15,7 @@ export function mousseOrchestrationInstructions(): string { '- A delegated task can never exceed your own mode ceiling: a planning turn may only start planning children.', '- Use ask_user for clarifying questions; use thread_read to read your thread\'s run events (and those of your parent or children).', '- thread_list and thread_search find any thread of the profile and thread_read reads it, at most 64 KB per call and 4,096 characters per message (it says how to read on). Each thread they return has a link (mousse://thread/): put it in a reply and the user can click it to open that thread.', - '- thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person\'s Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one. With computer (a name from list_computers) it starts the thread on another of the user\'s computers instead, in that computer\'s copy of this repository and in your permission mode narrowed to the limit that computer set for this one; its threadId is qualified (:), and firstMessage says sent, failed (the thread is kept) or uncertain (retry with the same clientRequestId, never a new one). thread_read, thread_wait, thread_send, thread_steer and thread_interrupt take that id: they reach a thread your thread (or its lineage) launched there, and no other thread there; a refusal names why (computer_offline, computer_not_shared, computer_outdated, computer_not_allowed, not_launched_here). thread_wait says needsInput when its run waits on a person there, whom no agent answers from here; a send or Stop that computer did not confirm is uncertain (retry with the same clientRequestId). A person\'s Stop of your thread stops the work you started there too.', + '- thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person\'s Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one. With computer (a name from list_computers) it starts the thread on another of the user\'s computers instead, in that computer\'s copy of this repository and in your permission mode narrowed to the limit that computer set for this one; its threadId is qualified (:), and firstMessage says sent, failed (the thread is kept) or uncertain (retry with the same clientRequestId, never a new one). thread_read, thread_wait, thread_send, thread_steer and thread_interrupt take that id: they reach a thread your thread (or its lineage) launched there, and no other thread there; a refusal names why (computer_offline, computer_not_shared, computer_outdated, computer_not_allowed, not_launched_here). thread_wait says needsInput when its run waits on a person there, whom no agent answers from here; a send or Stop that computer did not confirm is uncertain (retry with the same clientRequestId). A person\'s Stop of your thread stops the work you started there too. notify works there as here: Mousse follows that computer\'s run and tells you when it settles; if that computer stops answering this one for good, you are told once.', '- thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread\'s, and is limited to 20 messages per run; its result\'s delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. When you need the result of a thread_send or a thread_create firstMessage, set notify: Mousse tells you when the work it started ends, and once before that if it waits for a person; then do not call thread_wait or thread_read to check, and end your turn when nothing else is left. A notice that starts with "[Mousse notice" is written by Mousse, not by the user or any agent. Use thread_wait only when this turn cannot continue without the answer. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent\'s. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict.', '- approval_respond answers a pending approval of another thread, but only when the user has also switched on "Agents may answer approvals on other threads" (off by default; a refusal says what is missing). Read the request first with thread_list. Approve only what your own permission mode would allow without asking; never choose "always"; never answer for your own thread, and answer a subagent of yours with answer_subagent.', '- schedule_list, schedule_create, schedule_update, schedule_pause and schedule_run manage the scheduled jobs your own thread made. The first job your thread creates is not made at once: the user is asked and answers Allow or Not now (tell them it waits for their answer; do not retry); after Allow your thread may add more within the limits. Creating, starting or changing what a job does works only in a turn the user started (not from a job, another agent, a subagent or a remote send). A job outlives your turn and runs later as a turn of its own, with no permission mode beyond yours; changing one can only narrow that. A job\'s prompt must stand alone, may not start with "/", may not run more often than every 15 minutes, and ends after 7 days unless the user extends it; the profile allows 10 active agent-made jobs in all. The user resumes a paused job.', diff --git a/src/mms/run/settle/ThreadWatches.ts b/src/mms/run/settle/ThreadWatches.ts index b7992c9827..af97650dc4 100644 --- a/src/mms/run/settle/ThreadWatches.ts +++ b/src/mms/run/settle/ThreadWatches.ts @@ -121,6 +121,14 @@ export class ThreadWatches { return rows.map(toWatch) } + /** Active watches on threads of other computers (followed there by `RemoteSettleFollower`), oldest first. */ + listActiveRemote(): ThreadWatchRecord[] { + return this.store.db + .statement(`SELECT * FROM thread_watches WHERE state = 'active' AND target_node IS NOT NULL ORDER BY created_at, rowid`) + .all() + .map(toWatch) + } + /** Watches with a notice decided but not yet in the sender's queue (a restart in between). */ listDue(): ThreadWatchRecord[] { return this.store.db diff --git a/src/renderer/chat/adapters/settleNotice.ts b/src/renderer/chat/adapters/settleNotice.ts index 178f0b4244..74b152c803 100644 --- a/src/renderer/chat/adapters/settleNotice.ts +++ b/src/renderer/chat/adapters/settleNotice.ts @@ -30,6 +30,8 @@ export function settleNoticeOutcome(item: Pick +let t: Awaited> +let policy: SqliteNodePolicy +let repo: { path: string } +let seq = 0 +/** Every notice Mousse handed to a sender on the caller, in order. */ +let delivered: Array<{ threadId: string; notice: PlannedSettleNotice; held: boolean }> = [] + +const git = (cwd: string, ...args: string[]): string => + execFileSync('git', ['-c', 'user.name=T', '-c', 'user.email=t@example.com', ...args], { cwd, encoding: 'utf8' }).trim() +const folder = (): string => { + const path = realpathSync(mkdtempSync(join(tmpdir(), 'remote-settle-'))) + cleanups.push(() => rmSync(path, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + return path +} + +const callerOrch = (): Loose => t.caller.orchestrator as unknown as Loose +const portOf = (): RemoteComputersPort => callerOrch().remoteComputers +const nameOf = (): string => portOf().computers()!.find((entry) => entry.node === t.node)!.name +const service = (): SettleNotices => callerOrch().settleNotices +const watchRow = (watchId: string): Loose => t.caller.runEngine.store.db.statement('SELECT * FROM thread_watches WHERE watch_id = ?').get(watchId) as Loose +const noticesFor = (threadId: string) => delivered.filter((entry) => entry.threadId === threadId) +const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** What a restart of this daemon does to the watches: the service is made again and reads them from the run database alone. */ +function restartWatches(): SettleNotices { + service().stop() + callerOrch().settleNotices = callerOrch().startSettleNotices(t.caller.runEngine as RunEngine) + return service() +} + +beforeAll(async () => { + t = await linked() + policy = (t.insideOwner.routes as unknown as { options: { policy: SqliteNodePolicy } }).options.policy + const path = folder() + git(path, 'init', '-q') + git(path, 'commit', '-q', '--allow-empty', '-m', 'root') + const remote = `https://example.com/acme/${Math.random().toString(36).slice(2)}.git` + git(path, 'remote', 'add', 'origin', remote) + repo = { path } + const copy = folder() + git(copy, 'clone', '-q', path, '.') + git(copy, 'remote', 'set-url', 'origin', remote) + t.owner.projects.openProject(copy) + t.caller.settings.set({ agentAccess: { ...t.caller.settings.get().agentAccess, remoteSubagents: true, computers: [t.node] } } as never) + // A watch that did not reach the computer tries again in a fifth of a second here, not in 5 s. + callerOrch().remoteWatchRetryMs = 200 + restartWatches() +}, 120_000) +afterAll(cleanupAll) +afterEach(() => { + vi.restoreAllMocks() + delivered = [] + policy.set(t.callerNode, { blocked: false, maxPermissionMode: 'accept_edits', agentReach: 'launched' }) +}) + +/** The turns of both computers are stood in for; each notice handed to a sender here is recorded, then queued as usual. */ +function standIn(): void { + const done = (): Promise => Promise.resolve({ message: '', actions: [] }) + for (const orch of [t.owner.orchestrator, t.caller.orchestrator] as unknown as Loose[]) { + vi.spyOn(orch, 'startTurn').mockImplementation(done as never) + vi.spyOn(orch, 'runTurnOnSession').mockImplementation(done as never) + } + const real = callerOrch().queueSettleNotice.bind(t.caller.orchestrator) + vi.spyOn(callerOrch(), 'queueSettleNotice').mockImplementation(((threadId: string, notice: PlannedSettleNotice, held: boolean) => { + delivered.push({ threadId, notice, held }) + return real(threadId, notice, held) + }) as never) +} + +/** A thread on the caller with a live run, and its agent's tools. */ +async function launcher() { + const project = t.caller.projects.openProject(repo.path) + const thread = t.caller.threads.createThread(`Launcher ${++seq}`, project.id, project.path, { permissionMode: 'auto' } as never) + const sent = await t.caller.runEngine.dispatch({ kind: 'send', threadId: thread.id, clientRequestId: `launcher-send-${seq}`, source: 'gui' }) + if (sent.status !== 'accepted') throw new Error('launcher run not accepted') + t.caller.runEngine.markStarting(sent.runId) + t.caller.runEngine.markRunning(sent.runId) + const real = t.caller.orchestrator.runPermissionMode.bind(t.caller.orchestrator) + vi.spyOn(t.caller.orchestrator, 'runPermissionMode').mockImplementation((id) => (id === sent.runId ? 'auto' : real(id))) + const host = callerOrch().mcpToolHost() as AppToolHost + const { registry, turns: appTurns, request } = appToolRegistry(t.caller.runEngine, host) + appTurns.register(appTurn({ threadId: thread.id, runId: sent.runId })) + const tool = async (name: string, args: Record): Promise<{ isError?: boolean; body: Loose; text: string }> => { + const out = await registry.call(name, args, request({ threadId: thread.id, runId: sent.runId })) + let body: Loose = {} + try { + body = JSON.parse(out.text) + } catch { + // A refusal in words. + } + return { ...(out.isError ? { isError: true } : {}), body, text: out.text } + } + /** A thread launched on the owner by this launcher's agent (with `notify` when asked). */ + const launch = async (firstMessage?: string, notify = false) => { + const out = await tool('thread_create', { computer: t.node, title: `Launched ${++seq}`, ...(firstMessage ? { firstMessage } : {}), ...(notify ? { notify: true } : {}), clientRequestId: `launch-${seq}` }) + if (out.isError) throw new Error(out.text) + const far = t.caller.runEngine.remoteLaunches.listForLauncher(thread.id).at(-1)!.remoteThreadId! + return { far, id: qualifyId(t.node, far), runId: out.body.runId as string | undefined, body: out.body } + } + /** The launcher's own turn ends: a notice may then start a turn of its own. */ + const idle = () => t.caller.runEngine.markTerminal(sent.runId, 'completed') + return { thread, runId: sent.runId, tool, launch, idle } +} + +/** The run there starts, as its turn would. */ +function running(runId: string): void { + t.owner.runEngine.markStarting(runId) + t.owner.runEngine.markRunning(runId) +} + +/** The run there ends with `reply` as its final text, as its turn would. */ +function finish(runId: string, reply?: string, status: 'completed' | 'failed' = 'completed'): void { + if (reply) recordRunResultText(t.owner.runEngine.store, t.owner.runEngine.getRun(runId)!, reply) + t.owner.runEngine.markTerminal(runId, status) +} + +describe('notify on a thread launched on another computer (issue #1160)', () => { + it('thread_create with notify: the end is told once, with the reply cut to 2,000 characters and the thread as a qualified link', async () => { + standIn() + const { thread, launch, idle } = await launcher() + const { far, id, runId, body } = await launch('Run the tests on Linux.', true) + expect(body.notify).toMatchObject({ watchId: expect.any(String), next: NOTIFY_NEXT }) + expect(watchRow(body.notify.watchId)).toMatchObject({ state: 'active', target_node: t.node, target_thread_id: far, run_id: runId }) + running(runId!) + idle() + await pause(500) + // Still going there: nothing told. + expect(noticesFor(thread.id)).toHaveLength(0) + + const reply = `${'a'.repeat(SETTLE_NOTICE_RESULT_CHARS)}${'b'.repeat(2_996)}TAIL` + finish(runId!, reply) + await vi.waitFor(() => expect(noticesFor(thread.id)).toHaveLength(1), { timeout: 20_000 }) + const [{ notice, held }] = noticesFor(thread.id) + expect(held).toBe(false) + expect(notice.item).toMatchObject({ watchId: body.notify.watchId, threadId: id, event: 'ended', status: 'completed', runId, cut: true }) + expect(notice.text).toContain(`mousse://thread/${id}`) + expect(notice.text).toContain(`on ${nameOf()}`) + expect(notice.text).toContain('finished') + expect(notice.text).toContain('a'.repeat(SETTLE_NOTICE_RESULT_CHARS)) + expect(notice.text).not.toContain('aab') + expect(notice.text).not.toContain('TAIL') + // The pointer gives the reply's full length, not the 4,000 that computer sent, and the id to read it by. + expect(notice.text).toContain(`of ${reply.length.toLocaleString('en-US')} characters; read the rest with thread_read on thread ${id}`) + expect(watchRow(body.notify.watchId)).toMatchObject({ state: 'ended', end_status: 'completed', end_notice: 'sent', needs_input: null }) + // Told once, and nothing follows the thread any more. + await pause(1_500) + expect(noticesFor(thread.id)).toHaveLength(1) + expect(service().remote!.following()).not.toContain(body.notify.watchId) + }, 120_000) + + it('thread_send with notify: waiting on a person there is told first, and does not use up the end; the notice carries that run\'s count', async () => { + standIn() + const { thread, tool, launch, idle } = await launcher() + const first = await launch('Set it up.') + running(first.runId!) + finish(first.runId!) + const sent = await tool('thread_send', { threadId: first.id, content: 'Now run the tests.', notify: true, clientRequestId: 'send-1' }) + expect(sent.isError, sent.text).toBeUndefined() + expect(sent.body).toMatchObject({ threadId: first.id, computer: nameOf(), delivery: 'started', notify: { next: NOTIFY_NEXT } }) + const runId = sent.body.runId as string + // That computer counts this run as the third agent message in a row there (it takes the larger of its own count and + // the 1 this send carried), so the notice must read the count there. + const outcome = { ...t.owner.runEngine.getRun(runId)!.outcome, agentHops: 3 } + t.owner.runEngine.store.db.statement('UPDATE runs SET outcome = ? WHERE run_id = ?').run(JSON.stringify(outcome), runId) + expect(t.owner.runEngine.getRun(runId)!.outcome?.agentHops).toBe(3) + // A retry with the same request id keeps the one watch. + const again = await tool('thread_send', { threadId: first.id, content: 'Now run the tests.', notify: true, clientRequestId: 'send-1' }) + expect(again.body.notify.watchId).toBe(sent.body.notify.watchId) + idle() + running(runId) + + const asking = vi.spyOn(t.owner.questions, 'listPendingForThread').mockImplementation((threadId) => (threadId === first.far ? ([{}] as never) : [])) + await vi.waitFor(() => expect(noticesFor(thread.id)).toHaveLength(1), { timeout: 20_000 }) + expect(noticesFor(thread.id)[0]!.notice.item).toMatchObject({ event: 'needs_input', threadId: first.id, runId }) + expect(noticesFor(thread.id)[0]!.notice.text).toContain('waiting for a person') + // The count of the run there (3), not the one the send carried from here (1). + expect(noticesFor(thread.id)[0]!.notice.hops).toBe(3) + // Still waiting a while later: told once. + await pause(1_000) + expect(noticesFor(thread.id)).toHaveLength(1) + asking.mockRestore() + + finish(runId, 'All green.') + await vi.waitFor(() => expect(noticesFor(thread.id)).toHaveLength(2), { timeout: 20_000 }) + const end = noticesFor(thread.id)[1]!.notice + expect(end.item).toMatchObject({ event: 'ended', status: 'completed', runId }) + expect(end.text).toContain('All green.') + expect(end.hops).toBe(3) + expect(watchRow(sent.body.notify.watchId)).toMatchObject({ state: 'ended', needs_input: 'sent', end_notice: 'sent' }) + // The idle launcher's turn for it carries that count and adds none. + await vi.waitFor(() => expect(t.caller.runEngine.listRuns(thread.id, { limit: 10 }).some((run) => run.source === 'thread-notice')).toBe(true), { timeout: 20_000 }) + expect(t.caller.runEngine.listRuns(thread.id, { limit: 10 }).find((run) => run.source === 'thread-notice')!.outcome?.agentHops).toBe(3) + }, 120_000) + + it('follows a message a person edited in that computer\'s queue into the run it gets there', async () => { + standIn() + const { thread, tool, launch, idle } = await launcher() + const { far, id } = await launch() + // A person works in the thread there: the agent's message queues behind them. + const person = await t.owner.runEngine.dispatch({ kind: 'send', threadId: far, clientRequestId: `person-${++seq}`, source: 'gui' }) + if (person.status !== 'accepted') throw new Error('not accepted') + running(person.runId) + const owned = (t.owner.orchestrator as unknown as Loose) + // Its turn runs there (stood in for), so a message from here waits in that thread's queue. + const session = owned.getOrCreateSession(far) + const turnRunning = vi.spyOn(session, 'isTurnRunning').mockReturnValue(true) + const sent = await tool('thread_send', { threadId: id, content: 'Then run the tests.', notify: true }) + expect(sent.isError, sent.text).toBeUndefined() + idle() + expect(sent.body.delivery).toBe('queued') + const item = t.owner.orchestrator.queueSnapshot(far).items.find((entry) => entry.runId === sent.body.runId)! + expect(item).toBeDefined() + await pause(1_500) + expect(watchRow(sent.body.notify.watchId).queue_item_id).toBe(item.id) + // The person edits it there: its run is cancelled, and it gets a fresh run when it drains. + t.owner.orchestrator.editQueuedItem(far, item.id, { content: 'Then run the integration tests.' }) + expect(t.owner.runEngine.getRun(sent.body.runId)!.status).toBe('cancelled') + await pause(1_500) + expect(noticesFor(thread.id)).toHaveLength(0) + turnRunning.mockRestore() + finish(person.runId) + owned.scheduleQueueDrain(owned.getOrCreateSession(far)) + let next: string | undefined + await vi.waitFor(() => { + next = t.owner.runEngine.listRuns(far, { limit: 10 }).find((run) => run.clientRequestId === `queue:${item.id}`)?.runId + expect(next).toBeDefined() + }, { timeout: 20_000 }) + if (t.owner.runEngine.getRun(next!)!.status === 'queued') running(next!) + finish(next!, 'Integration tests pass.') + await vi.waitFor(() => expect(noticesFor(thread.id)).toHaveLength(1), { timeout: 20_000 }) + expect(noticesFor(thread.id)[0]!.notice.item).toMatchObject({ event: 'ended', status: 'completed', runId: next }) + expect(noticesFor(thread.id)[0]!.notice.text).toContain('Integration tests pass.') + }, 120_000) + + it('survives a restart of this daemon and a link that was down: the computer offline is never a false end', async () => { + standIn() + const { thread, launch, idle } = await launcher() + const { runId, body } = await launch('Build it.', true) + running(runId!) + idle() + // The link goes down, and this daemon restarts: the new service has only the watch's row. + const versions = vi.spyOn(portOf(), 'versions').mockRejectedValue(new DomainRpcError('computer_offline', 'The other computer is offline.')) + const fresh = restartWatches() + expect(fresh.remote!.following()).toContain(body.notify.watchId) + // The run ends there while nobody can ask: no notice, the watch stays, and it keeps trying. + finish(runId!, 'Built.') + await vi.waitFor(() => expect(versions.mock.calls.length).toBeGreaterThan(4), { timeout: 20_000 }) + expect(noticesFor(thread.id)).toHaveLength(0) + expect(watchRow(body.notify.watchId)).toMatchObject({ state: 'active', end_notice: null }) + // The link is back. + versions.mockRestore() + fresh.remoteReachable() + await vi.waitFor(() => expect(noticesFor(thread.id)).toHaveLength(1), { timeout: 20_000 }) + expect(noticesFor(thread.id)[0]!.notice.item).toMatchObject({ event: 'ended', status: 'completed', runId }) + expect(noticesFor(thread.id)[0]!.notice.text).toContain('Built.') + }, 120_000) + + it('a computer that refuses this device ends the watch with one notice that names it', async () => { + standIn() + const { thread, launch, idle } = await launcher() + const { runId, body } = await launch('Build it.', true) + running(runId!) + idle() + await pause(500) + policy.set(t.callerNode, { blocked: true }) + await vi.waitFor(() => expect(noticesFor(thread.id)).toHaveLength(1), { timeout: 30_000 }) + const { notice, held } = noticesFor(thread.id)[0]! + expect(held).toBe(false) + expect(notice.item).toMatchObject({ event: 'ended', status: 'unreachable' }) + expect(notice.text).toContain(`${nameOf()} refused this device`) + expect(watchRow(body.notify.watchId)).toMatchObject({ state: 'ended', end_status: 'unreachable:computer_not_shared:blocked', end_notice: 'sent' }) + // It does not try again. + const calls = vi.spyOn(portOf(), 'call') + await pause(1_500) + expect(calls).not.toHaveBeenCalled() + expect(noticesFor(thread.id)).toHaveLength(1) + }, 120_000) + + it('after 24 hours the watch ends with one notice that wakes nobody', async () => { + standIn() + const { thread, launch, idle } = await launcher() + const { runId, body } = await launch('Build it.', true) + running(runId!) + idle() + await pause(500) + t.caller.runEngine.store.db.statement('UPDATE thread_watches SET expires_at = ? WHERE watch_id = ?').run(new Date(Date.now() - 1_000).toISOString(), body.notify.watchId) + service().expireDue() + expect(noticesFor(thread.id)).toHaveLength(1) + expect(noticesFor(thread.id)[0]).toMatchObject({ held: true, notice: { item: { event: 'expired' } } }) + expect(noticesFor(thread.id)[0]!.notice.text).toContain(`had not ended when Mousse last reached ${nameOf()}`) + expect(service().remote!.following()).not.toContain(body.notify.watchId) + // The work ending later tells nothing more. + finish(runId!, 'Done late.') + await pause(1_500) + expect(noticesFor(thread.id)).toHaveLength(1) + }, 120_000) + + it.each([ + ['a launcher kept in Plan', () => vi.spyOn(callerOrch(), 'lastChatModeOf').mockReturnValue('plan')], + ['a subagent\'s thread', (threadId: string) => { + const real = t.caller.runEngine.delegations.getLineage.bind(t.caller.runEngine.delegations) + vi.spyOn(t.caller.runEngine.delegations, 'getLineage').mockImplementation((id) => (id === threadId ? ({ relationship: 'subagent', parentThreadId: 'parent' } as never) : real(id))) + }] + ])('never starts a turn in %s: the notice waits in its queue', async (_name, arrange) => { + standIn() + const { thread, launch, idle } = await launcher() + const { runId } = await launch('Build it.', true) + running(runId!) + idle() + arrange(thread.id) + finish(runId!, 'Built.') + await vi.waitFor(() => expect(noticesFor(thread.id)).toHaveLength(1), { timeout: 20_000 }) + expect(noticesFor(thread.id)[0]!.held).toBe(true) + await pause(1_000) + expect(t.caller.orchestrator.queueSnapshot(thread.id).items.find((item) => item.settleNotice)).toMatchObject({ heldNotice: true }) + expect(t.caller.runEngine.listRuns(thread.id, { limit: 10 }).some((run) => run.source === 'thread-notice')).toBe(false) + }, 120_000) +}) diff --git a/tests/net/bridge/routed/threadToolsRemote.test.ts b/tests/net/bridge/routed/threadToolsRemote.test.ts index 608fd1c137..b809f5c91a 100644 --- a/tests/net/bridge/routed/threadToolsRemote.test.ts +++ b/tests/net/bridge/routed/threadToolsRemote.test.ts @@ -239,10 +239,6 @@ describe('the thread tools on a thread launched on another computer (issue #1160 const again = await tool('thread_send', { threadId: id, content: 'Now run the integration tests.', clientRequestId: 'send-1' }) expect(again.body).toMatchObject({ runId: sent.body.runId }) expect(t.owner.runEngine.listRuns(far, { limit: 10 })).toHaveLength(1) - // notify does not reach another computer yet: refused, and nothing is sent. - const notify = await tool('thread_send', { threadId: id, content: 'And tell me.', notify: true }) - expect(notify).toMatchObject({ isError: true, text: expect.stringMatching(/notify does not reach a thread on another computer yet, so the message was not sent/) }) - expect(t.owner.runEngine.listRuns(far, { limit: 10 })).toHaveLength(1) }, 120_000) it('refuses a steer into a run there that is looser than the agent', async () => { diff --git a/tests/run/delegationGuidance.test.ts b/tests/run/delegationGuidance.test.ts index 2e08de9568..0f4b494149 100644 --- a/tests/run/delegationGuidance.test.ts +++ b/tests/run/delegationGuidance.test.ts @@ -36,7 +36,7 @@ describe('subagent guidance', () => { - A delegated task can never exceed your own mode ceiling: a planning turn may only start planning children. - Use ask_user for clarifying questions; use thread_read to read your thread's run events (and those of your parent or children). - thread_list and thread_search find any thread of the profile and thread_read reads it, at most 64 KB per call and 4,096 characters per message (it says how to read on). Each thread they return has a link (mousse://thread/): put it in a reply and the user can click it to open that thread. - - thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person's Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one. + - thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person's Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one. With computer (a name from list_computers) it starts the thread on another of the user's computers instead, in that computer's copy of this repository and in your permission mode narrowed to the limit that computer set for this one; its threadId is qualified (:), and firstMessage says sent, failed (the thread is kept) or uncertain (retry with the same clientRequestId, never a new one). thread_read, thread_wait, thread_send, thread_steer and thread_interrupt take that id: they reach a thread your thread (or its lineage) launched there, and no other thread there; a refusal names why (computer_offline, computer_not_shared, computer_outdated, computer_not_allowed, not_launched_here). thread_wait says needsInput when its run waits on a person there, whom no agent answers from here; a send or Stop that computer did not confirm is uncertain (retry with the same clientRequestId). A person's Stop of your thread stops the work you started there too. notify works there as here: Mousse follows that computer's run and tells you when it settles; if that computer stops answering this one for good, you are told once. - thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread's, and is limited to 20 messages per run; its result's delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. When you need the result of a thread_send or a thread_create firstMessage, set notify: Mousse tells you when the work it started ends, and once before that if it waits for a person; then do not call thread_wait or thread_read to check, and end your turn when nothing else is left. A notice that starts with "[Mousse notice" is written by Mousse, not by the user or any agent. Use thread_wait only when this turn cannot continue without the answer. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent's. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict. - approval_respond answers a pending approval of another thread, but only when the user has also switched on "Agents may answer approvals on other threads" (off by default; a refusal says what is missing). Read the request first with thread_list. Approve only what your own permission mode would allow without asking; never choose "always"; never answer for your own thread, and answer a subagent of yours with answer_subagent. - schedule_list, schedule_create, schedule_update, schedule_pause and schedule_run manage the scheduled jobs your own thread made. The first job your thread creates is not made at once: the user is asked and answers Allow or Not now (tell them it waits for their answer; do not retry); after Allow your thread may add more within the limits. Creating, starting or changing what a job does works only in a turn the user started (not from a job, another agent, a subagent or a remote send). A job outlives your turn and runs later as a turn of its own, with no permission mode beyond yours; changing one can only narrow that. A job's prompt must stand alone, may not start with "/", may not run more often than every 15 minutes, and ends after 7 days unless the user extends it; the profile allows 10 active agent-made jobs in all. The user resumes a paused job. @@ -162,7 +162,7 @@ describe('the delegation tools models are offered', () => { "required": [], }, { - "description": "List the user's other computers you may start subagents on (delegate_task computer): name, whether it is online, whether the user allowed it, and whether it has this repository. Starts nothing.", + "description": "List the user's other computers you may start subagents (delegate_task computer) or threads (thread_create computer) on: name, whether it is online, whether the user allowed it, and whether it has this repository. Starts nothing.", "name": "list_computers", "parameters": [], "required": [], diff --git a/tests/run/remoteSettleFollow.test.ts b/tests/run/remoteSettleFollow.test.ts new file mode 100644 index 0000000000..7f8d8f3dc4 --- /dev/null +++ b/tests/run/remoteSettleFollow.test.ts @@ -0,0 +1,99 @@ +/** + * Which answers of another computer end a settle watch on a thread there, and which are waited out (issue #1160, + * docs/plans/agent-threads-architecture.md §4.2). `SettleNotices` over a real run database, with the routed reads stood + * in for: every read fails with the row's code. The end-to-end cases run over two real daemons in + * `tests/net/bridge/routed/settleNoticeRemote.test.ts`. + * + * Rows: not reached (offline, Bridge off here, slow), refused for good (blocked, sharing off, too old, agents here turned + * off for that computer), and the thread deleted there. + */ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { RemoteThreadRefusal } from '../../src/mms/orchestrator/RemoteLaunchedThreads' +import { SettleNotices, type PlannedSettleNotice } from '../../src/mms/orchestrator/settleNotices' +import type { RemoteWatchReads } from '../../src/mms/orchestrator/remoteSettleFollow' +import { ProfileDatabase } from '../../src/mms/run/db/ProfileDatabase' +import { RunEngine } from '../../src/mms/run/RunEngine' +import { RunStore } from '../../src/mms/run/RunStore' + +const NODE = 'nod_11111111111111111111111111' + +describe('a settle watch on another computer: what ends it', () => { + const homes: string[] = [] + const closers: Array<() => void> = [] + afterEach(() => { + for (const close of closers.splice(0)) close() + for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }) + }) + + const world = (fail: { code: string; details?: Record } | 'no_reads' | 'denied') => { + const home = mkdtempSync(join(tmpdir(), 'mousse-remote-settle-')) + homes.push(home) + const engine = new RunEngine({ store: new RunStore(new ProfileDatabase({ profileHome: home })), pid: 1 }) + const delivered: Array<{ notice: PlannedSettleNotice; held: boolean }> = [] + const refusal = typeof fail === 'object' ? new RemoteThreadRefusal(fail.code, `refused (${fail.code})`, 'Linux box', fail.details) : undefined + const reads: RemoteWatchReads = { + follow: vi.fn(async () => { throw refusal }), + readThread: vi.fn(async () => { throw refusal }) + } + const notices = new SettleNotices({ + engine, + target: { getRun: () => null, continuationOf: () => undefined, queueRun: () => undefined, queueItemForRun: () => undefined, queueItem: () => undefined, activeRun: () => null }, + titleOf: () => undefined, + threadLive: () => true, + waitingForPerson: () => false, + resultText: () => undefined, + stopGeneration: () => 0, + isSubagent: () => false, + inPlan: () => false, + deliver: (_threadId, notice, held) => { delivered.push({ notice, held }) }, + delivered: () => false, + remote: { + reads: () => (fail === 'no_reads' ? undefined : reads), + launched: () => ({ computer: 'Linux box', title: 'Tests on Linux' }), + denial: () => (fail === 'denied' ? { code: 'computer_not_allowed', message: 'turned off' } : undefined), + sentHops: () => 1, + retryMs: 20, + maxRetryMs: 40 + } + }) + closers.push(() => { notices.stop(); engine.store.db.close() }) + notices.start() + const watch = notices.watch({ messageKey: 'thread_send:sender:1', watcherThreadId: 'sender', watcherRunId: 'run-s', targetThreadId: 'far', targetNode: NODE, runId: 'run:far:1' }) + return { notices, watch, delivered, reads } + } + + it.each([ + ['offline', { code: 'computer_offline' }], + ['slow', { code: 'computer_slow' }], + ['Bridge off here', 'no_reads' as const] + ])('%s: never an end; it keeps asking', async (_name, fail) => { + const { notices, watch, delivered, reads } = world(fail) + await new Promise((resolve) => setTimeout(resolve, 1_500)) + expect(delivered).toEqual([]) + expect(notices.watches.get(watch.watchId)).toMatchObject({ state: 'active', endNotice: null }) + expect(notices.remote!.following()).toContain(watch.watchId) + if (fail !== 'no_reads') expect(vi.mocked(reads.readThread).mock.calls.length).toBeGreaterThan(1) + }) + + it.each([ + ['refused this device', { code: 'computer_not_shared', details: { reason: 'blocked' } }, 'unreachable:computer_not_shared:blocked', 'Linux box refused this device'], + ['stopped sharing its threads', { code: 'computer_not_shared', details: { reason: 'setting_off' } }, 'unreachable:computer_not_shared:setting_off', 'works on threads is off on Linux box'], + ['too old', { code: 'computer_outdated' }, 'unreachable:computer_outdated', 'Mousse on Linux box is too old'], + ['agents here turned off for it', 'denied' as const, 'unreachable:computer_not_allowed', 'working on Linux box'], + ['the thread deleted there', { code: 'remote_thread_gone' }, 'deleted', 'that thread was deleted'] + ])('%s: the watch ends with one notice that says so', async (_name, fail, status, words) => { + const { notices, watch, delivered } = world(fail) + await vi.waitFor(() => expect(delivered).toHaveLength(1)) + expect(delivered[0]!.held).toBe(false) + expect(delivered[0]!.notice.item).toMatchObject({ event: 'ended', threadId: `${NODE}:far` }) + expect(delivered[0]!.notice.text).toContain(words) + expect(delivered[0]!.notice.text).toContain(`mousse://thread/${NODE}:far`) + expect(notices.watches.get(watch.watchId)).toMatchObject({ state: 'ended', endStatus: status, endNotice: 'sent' }) + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(delivered).toHaveLength(1) + expect(notices.remote!.following()).not.toContain(watch.watchId) + }) +})