diff --git a/docs/net/threat-model.md b/docs/net/threat-model.md index 016589539d..6c028f7d6d 100644 --- a/docs/net/threat-model.md +++ b/docs/net/threat-model.md @@ -257,6 +257,15 @@ An agent can also start a top-level thread on another of the user's computers (` - The mode is the launcher's own (its thread's mode and its run's), narrowed by that computer to the limit it set for this one; no fixed mode caps it, as for remote subagents. The owner holds the thread to that mode from its first write and records the launching agent (`startedFrom.agent`). - The launch is recorded here before any call (`remote_launches` in the run database, beside the `thread_create` receipt), and every write has its own idempotency key from the launch's key, so a lost link, a retry or a restart reaches the same execution there and never makes a second thread or sends the first message twice. A write that is not confirmed is reported as uncertain, never as done or failed. +After the launch, `thread_read`, `thread_wait`, `thread_send`, `thread_steer` and `thread_interrupt` take the thread's qualified id (`src/mms/orchestrator/RemoteLaunchedThreads.ts`): + +- **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. +- **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. + #### Calls marked as an agent's (issue #1160) Seven routed rows take a key `agent: { thread, run, title, hops, mode }`: `threads.create`, `threads.setModel`, `threads.setPermissionMode`, `orchestrator.send`, `orchestrator.steer`, `queue.enqueue` and `orchestrator.abort` (`ROUTED_AGENT_KEY` in `src/shared/bridge/routed.ts`). Remote subagents and threads agents start on another computer send it. diff --git a/docs/run-engine/SPEC.md b/docs/run-engine/SPEC.md index 885d7d9d3f..a19c75d600 100644 --- a/docs/run-engine/SPEC.md +++ b/docs/run-engine/SPEC.md @@ -564,7 +564,9 @@ 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). Reading, waiting on, messaging and stopping the thread there look the launch up in `remote_launches` (by launcher, or by computer and far 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` 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. + - **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. - **The sender's mode holds on every path.** An agent's send, steer or queued message never runs with more than its sender's effective mode: a send narrows the target's turn at admission, and the queued item and the turn payload keep the mode; a narrowed turn's own `queue_enqueue` queues under the mode its run is bound to (when that is stricter than the thread's); a run that continues another (the resume after a pause, a "Continue", a turn the provider starts itself) takes the stricter of its own mode and the continued run's binding (`continuedPermissionMode`, as `runs.access_grant` does for the level); `continue_subagent` passes the calling run's bound mode to the follow-up, so an existing subagent is no way around it. A wake that delivers a subagent's result runs under the thread's own mode: it continues no run, and nothing records which turn asked for the work (a follow-up for a later change). diff --git a/src/mms/MmsProfileServices.ts b/src/mms/MmsProfileServices.ts index 9b4ed90c54..408973da4c 100644 --- a/src/mms/MmsProfileServices.ts +++ b/src/mms/MmsProfileServices.ts @@ -1391,6 +1391,8 @@ export class MmsProfileServices { runInProgress: (threadId) => this.lifecycleOwnedTasks(threadId).some((task) => this.orchestrator.isTurnActive(task.taskId) || this.runEngine.getActiveRun(task.taskId) !== null), stop: async (threadId) => { await this.orchestrator.stopThread(threadId, 'expired', { clearQueue: true }) }, quiesce: (threadId) => { + // What the expired threads launched on other computers is stopped there; nothing there is deleted. + this.orchestrator.stopRemoteLaunches(this.lifecycleOwnedTasks(threadId).map((task) => task.taskId), 'expired') // A question waiting for an answer and an open terminal are not a run: they end at expiry. for (const task of this.lifecycleOwnedTasks(threadId)) { this.questions.dismissAllForThread(task.taskId, 'thread_deleted') @@ -1817,6 +1819,9 @@ export class MmsProfileServices { } private async stopRunsForDelete(threadIds: readonly string[]): Promise { + // What the deleted threads launched on other computers is stopped there, whether or not they run now; nothing there + // is deleted. + this.orchestrator.stopRemoteLaunches(threadIds, 'deleted') const running = (): string[] => this.runningForDelete(threadIds) const stopping = running() if (!stopping.length) return diff --git a/src/mms/bridge/BridgeProfileService.ts b/src/mms/bridge/BridgeProfileService.ts index e717f04a2b..c062c32ead 100644 --- a/src/mms/bridge/BridgeProfileService.ts +++ b/src/mms/bridge/BridgeProfileService.ts @@ -545,7 +545,8 @@ export class BridgeProfileService { services, client: this.router.client, computers: () => (this.router.enabled() ? this.router.pairedComputers() : undefined), - online: (node) => this.router.isOnline(node) + online: (node) => this.router.isOnline(node), + self: () => rt.identity.self()?.node }) services.orchestrator.setRemoteComputers(computersPort) this.disposers.add(() => services.orchestrator.setRemoteComputers(undefined)) diff --git a/src/mms/bridge/routed/RoutedClient.ts b/src/mms/bridge/routed/RoutedClient.ts index 153a48765d..b2254f6ef1 100644 --- a/src/mms/bridge/routed/RoutedClient.ts +++ b/src/mms/bridge/routed/RoutedClient.ts @@ -1,6 +1,7 @@ import { NetError, newId, type NodeId, type RpcId } from '../../../shared/net' import { ROUTED_LARGE_READS, + ROUTED_RUN_WAIT_DEADLINE_MS, ROUTED_LARGE_READS_PER_CALLER, ROUTED_METHODS, ROUTED_DROPPABLE_KEYS, @@ -92,6 +93,8 @@ const SEQUENCED_DEADLINE_MS = 15_000 const deadlineOf = (method: string): number => ROUTED_METHODS[method]?.sequenced ? SEQUENCED_DEADLINE_MS + : method === 'runs.wait' + ? ROUTED_RUN_WAIT_DEADLINE_MS : LONG_METHODS.has(method) ? LONG_DEADLINE_MS : DEFAULT_DEADLINE_MS @@ -176,6 +179,11 @@ export class RoutedClient { return this.guard(node, session, computer, () => this.versions(node, session)) } + /** The name a person knows `node` by. */ + nameOf(node: NodeId): string { + return this.deps.computer(node).name + } + /** Runs one routed row on `node` and returns its result, or throws what the person should see. */ async call( node: NodeId, diff --git a/src/mms/bridge/routed/remoteComputers.ts b/src/mms/bridge/routed/remoteComputers.ts index b9be8a3a13..02e81e22fe 100644 --- a/src/mms/bridge/routed/remoteComputers.ts +++ b/src/mms/bridge/routed/remoteComputers.ts @@ -3,6 +3,7 @@ import { ROUTED_AGENT_METHODS } from '../../../shared/bridge/routed' import type { MmsProfileServices } from '../../MmsProfileServices' import type { RemoteComputer, RemoteComputersPort } from '../../protocol/remoteComputersPort' import { repositoryIdentitiesFor } from '../remote/repositoryIdentity' +import { DomainRpcError } from '../../protocol/domainRegistry' import type { RoutedClient } from './RoutedClient' const isRecord = (value: unknown): value is Record => !!value && typeof value === 'object' && !Array.isArray(value) @@ -18,11 +19,24 @@ export function remoteComputersPort(options: { client: RoutedClient computers: () => Array<{ node: NodeId; name: string }> | undefined online: (node: NodeId) => boolean + self?: () => string | undefined }): RemoteComputersPort { const { services, client } = options return { computers: (): RemoteComputer[] | undefined => options.computers()?.map(({ node, name }) => ({ node, name, online: options.online(node) })), + self: () => options.self?.(), + versions: async (node, signal) => { + const asked = client.versionsOrRefusal(node as NodeId) + if (!signal) return asked + // The connect deadline: a handshake that stalls fails here, whatever the call's own deadline is. + return new Promise((resolve, reject) => { + const give = (): void => reject(new DomainRpcError('computer_offline', `${client.nameOf(node as NodeId)} did not answer in time, so it is taken as offline.`)) + if (signal.aborted) return give() + signal.addEventListener('abort', give, { once: true }) + asked.then(resolve, reject).finally(() => signal.removeEventListener('abort', give)) + }) + }, call: (node, method, params, callOptions) => client.call(node as NodeId, method, params, callOptions), takesAgentMark: async (node) => { const versions = await client.versionsOrRefusal(node as NodeId) diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index 12520e23ea..800c6fc8fd 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -84,9 +84,9 @@ import { delegationRequestKey, followUpRequestKey, narrowCeiling } from '../run/ import { CommandRejection, RunStoreError } from '../run/db/RunStoreError' import { EffectDeferredError, WorkerStoppedError, type EffectExecutor, type EffectWorker } from '../run/EffectWorker' import { steerReleaseWindow, stopStrategy, type SteerDelivery } from '../run/CommandPolicy' -import { agentMessage, AppToolTurns, createAppToolRegistry, McpToolError, unattendedRefusal, type BotAppToolDeps, type BotMemoryToolHost, type AgentApprovalResult, type AgentArchiveResult, type AgentCreatedThread, type AgentRemoteThreadRequest, type AgentRemoteThreadResult, type RemoteProjectCandidate, type AgentQueueCommand, type AgentQueueResult, type AgentScheduleHost, type AgentRunCommandResult, type AgentSendResult, type AgentThreadRequest, type ApprovalRequestInfo, type AppToolHost, type AppToolTurn, type McpCaller, type QueueSnapshot, type ToolRegistry, userMcpProxy } from '../run/mcp/appTools' +import { agentMessage, AppToolTurns, createAppToolRegistry, McpToolError, unattendedRefusal, type BotAppToolDeps, type BotMemoryToolHost, type AgentApprovalResult, type AgentArchiveResult, type AgentCreatedThread, type AgentRemoteThreadRequest, type AgentRemoteThreadResult, type RemoteProjectCandidate, type AgentQueueCommand, type AgentQueueResult, type AgentScheduleHost, type AgentRunCommandResult, type AgentSendResult, type AgentThreadRequest, type ApprovalRequestInfo, type AppToolHost, type RemoteThreadsHost, type AppToolTurn, type McpCaller, type QueueSnapshot, type ToolRegistry, userMcpProxy } from '../run/mcp/appTools' import { AGENT_THREAD_COMMAND, AGENT_THREAD_CREATED_ACTION, AGENT_THREAD_REPAIR_WINDOW_MS, agentThreadFingerprint, readAgentThreadReceipt, type AgentThreadIntent } from './agentThreadIntent' -import { AGENT_QUEUE_MAX_PER_SENDER, AGENT_QUEUE_MAX_PER_THREAD, AGENT_REPEAT_WINDOW_MS, botRequestPrefix, THREAD_CREATE_MAX_ACTIVE_PER_THREAD } from '../run/mcp/appTools/thread' +import { AGENT_QUEUE_MAX_PER_SENDER, AGENT_QUEUE_MAX_PER_THREAD, AGENT_REPEAT_WINDOW_MS, botRequestPrefix, lineageRelation, THREAD_CREATE_MAX_ACTIVE_PER_THREAD } from '../run/mcp/appTools/thread' import { botMessageText } from '../run/mcp/appTools/agentMessage' /** @@ -133,6 +133,8 @@ import { taskCheckpoint } from '../run/delegation/checkpoint' import { remoteSubagentPreamble, subagentPreamble, withoutSubagentPreamble } from '../run/delegation/guidance' import { qualifyId } from '../../shared/threadRef' import { RemoteThreadLaunches, type RemoteLaunchOutcome } from './RemoteThreadLaunches' +import { RemoteLaunchedThreads, RemoteThreadRefusal } from './RemoteLaunchedThreads' +import type { RoutedAgentMark } from '../../shared/bridge/routed' import { REMOTE_THREAD_COMMAND, remoteThreadFingerprint, remoteThreadRefusal } from './remoteThreadRequest' import type { RemoteLaunchRecord } from '../run/delegation/remoteLaunches' import { RemoteSubagents } from './RemoteSubagents' @@ -1191,6 +1193,7 @@ export class OrchestratorService extends EventEmitter { this.beginShutdown() this.remoteSubagents?.close() this.remoteLaunches?.close() + this.remoteThreads?.close() await this.lifecycle.waitForIdle(timeoutMs) for (const timer of this.persistTimers.values()) clearTimeout(timer) this.persistTimers.clear() @@ -1268,6 +1271,8 @@ export class OrchestratorService extends EventEmitter { private remoteSubagents?: RemoteSubagents /** Threads agents here launched on other computers (`thread_create` with `computer`, issue #1160); likewise. */ private remoteLaunches?: RemoteThreadLaunches + /** The thread tools and Stops on those threads (issue #1160); likewise. */ + private remoteThreads?: RemoteLaunchedThreads /** * The user's other computers, for remote subagents (issue #469). Composed with Bridge, which sets it @@ -1278,6 +1283,8 @@ export class OrchestratorService extends EventEmitter { if (port) { this.remoteSubagents?.start() this.remoteLaunches?.start() + // Stops kept while Bridge was off are sent now. + this.remoteThreads?.start() } } @@ -2388,6 +2395,8 @@ export class OrchestratorService extends EventEmitter { this.remoteSubagents = undefined this.remoteLaunches?.close() this.remoteLaunches = undefined + this.remoteThreads?.close() + this.remoteThreads = undefined this.runEngine = engine this.installQueueJournal() if (!engine) return @@ -2411,6 +2420,20 @@ export class OrchestratorService extends EventEmitter { }) // Launches a restart cut off are finished (or archived there) once that computer can be reached. this.remoteLaunches.start() + this.remoteThreads = new RemoteLaunchedThreads({ + records: engine.remoteLaunches, + port: () => this.remoteComputers, + denial: (node, name) => this.remoteThreadDenial(node, name), + related: (callerThreadId, launcherThreadId) => callerThreadId === launcherThreadId || lineageRelation(engine, callerThreadId, launcherThreadId) !== null, + localOnly: (threadId) => this.isLocalOnly(threadId), + note: (launcherThreadId, text) => { + // A launcher that is gone (deleted, expired) gets no note: nothing would show it. + if (!this.threadStore?.getThread(launcherThreadId) || this.isExpired(launcherThreadId)) return + this.noteAgentLaunch(launcherThreadId, text) + } + }) + // Stops a restart left undelivered are sent once that computer answers. + this.remoteThreads.start() this.installTitleGuard() this.attachInFlightCanceller() // Input (4) of the hold predicate: synchronous, in memory, never throws (it is read inside transactions). @@ -3543,7 +3566,11 @@ export class OrchestratorService extends EventEmitter { // A person's Stop reaches the threads the stopped ones launched while they run work an agent started: a creator // that is stopped leaves no fan-out running behind it (an agent's own Stop of a thread does not cascade). // The cascade keeps the cause of the Stop that started it: an agent's `task_cancel` stays the agent's below. - if (!result.replayed && !opts.actor) await this.stopLaunchedThreads(result.threads, opts.byAgent === true) + if (!result.replayed && !opts.actor) { + await this.stopLaunchedThreads(result.threads, opts.byAgent === true) + // And the threads they launched on other computers, there (kept until it is delivered). + this.stopRemoteLaunches(result.threads, reason === 'deleted' || reason === 'expired' ? reason : 'stopped') + } const stoppedAnything = aborted || compactionStopped || worked.some(Boolean) || result.activeRuns.length + result.cancelledRuns.length + result.delegations.length > 0 return { ok: stoppedAnything, ...result } } @@ -4137,6 +4164,7 @@ export class OrchestratorService extends EventEmitter { createThread: (input, options) => this.createThreadAsAgent(input, options), creationStarted: (clientRequestId) => this.agentCreationStarted(clientRequestId), createRemoteThread: (input, options) => this.createRemoteThreadAsAgent(input, options), + ...(this.remoteThreads ? { remoteThreads: this.remoteThreadsHost(this.remoteThreads) } : {}), noteOnThread: (threadId, text, launched) => this.noteAgentLaunch(threadId, text, launched), stopRun: (threadId, runId, options) => this.stopRunAsAgent(threadId, runId, options), setThreadArchived: (threadId, archived, options) => this.setThreadArchivedAsAgent(threadId, archived, options), @@ -4758,7 +4786,7 @@ export class OrchestratorService extends EventEmitter { return refuse(failed.code, failed.message, at) } // However many runs this thread has made, only so many of the threads it launched may be working at once. - const working = this.launchedThreadsWorking(callerThreadId) + const working = await this.launchedThreadsWorking(callerThreadId) if (working >= THREAD_CREATE_MAX_ACTIVE_PER_THREAD) return refuse('creation_limit', `${working} of the threads this thread launched are still working (the limit is ${THREAD_CREATE_MAX_ACTIVE_PER_THREAD}); wait for some to finish before launching more.`, at) // The first message counts as the next agent message in a row: a launch cannot start a chain the limit would stop. @@ -4823,16 +4851,71 @@ export class OrchestratorService extends EventEmitter { return undefined } - /** The threads `launcherThreadId` launched that are working: here, with a run going, and on other computers, while their launch is open. */ - private launchedThreadsWorking(launcherThreadId: string): number { + /** + * The threads `launcherThreadId` launched that are working: here, with a run going, and on other computers, as each + * computer says (a launch still open, or one that computer cannot be asked about, counts as working). + */ + private async launchedThreadsWorking(launcherThreadId: string): Promise { const engine = this.requireRunEngine() const busy = new Set(engine.store.listNonTerminalRuns().map((run) => run.threadId)) const here = this.threadStore?.listAllThreads().filter((thread) => thread.createdByThreadId === launcherThreadId && busy.has(thread.id)).length ?? 0 - const there = engine.remoteLaunches.listForLauncher(launcherThreadId).filter((launch) => - launch.state === 'starting' || launch.state === 'created' || launch.firstMessageState === 'pending' || launch.firstMessageState === 'uncertain').length + const there = this.remoteThreads ? await this.remoteThreads.working(launcherThreadId) : 0 return here + there } + /** + * A person's Stop, the deletion or the expiry of these threads reaches the threads they launched on other computers: a + * marked Stop there, which stops only runs this computer's agents started. Kept until it is delivered (or a day passed). + */ + stopRemoteLaunches(launcherThreadIds: readonly string[], reason: 'stopped' | 'deleted' | 'expired'): void { + try { + this.remoteThreads?.stopLaunchedBy(launcherThreadIds, reason) + } catch (error) { + console.warn('threads launched on other computers could not be stopped', { error: error instanceof Error ? error.message : String(error) }) + } + } + + /** + * The mark of an agent's call to a thread on another computer: the caller's thread, run, title, mode (its own, never + * looser than its run) and, for a message or a steer, the count of agent messages in a row it would be (refused past + * the limit, as on one computer). + */ + private remoteAgentMark(actor: AgentActor, counts: boolean): RoutedAgentMark { + let hops = 1 + if (counts) hops = this.withAgentHops(actor).hops ?? 1 + else { + try { + hops = this.withAgentHops(actor).hops ?? 1 + } catch { + hops = AGENT_MESSAGE_MAX_HOPS + } + } + return { + thread: actor.threadId, + run: actor.runId, + title: this.titleOf(actor.threadId) ?? '', + hops, + mode: narrowPermissionMode(this.requestedPermissionMode(actor.threadId), this.runPermissionMode(actor.runId)) + } + } + + /** What the thread tools call for a thread launched on another computer: the service, with the mark built here. */ + private remoteThreadsHost(service: RemoteLaunchedThreads): RemoteThreadsHost { + return { + reach: (callerThreadId, threadId) => service.reach(callerThreadId, threadId), + events: (target, page) => service.events(target, page), + messages: (target, page) => service.messages(target, page), + wait: (target, request) => { + const denied = this.remoteThreadDenial(target.node, target.computer) + if (denied) return Promise.reject(new RemoteThreadRefusal(denied.code, denied.message, target.computer)) + return service.follow(target, request) + }, + send: (target, input, options) => service.send(target, input, { clientRequestId: options.clientRequestId, mark: this.remoteAgentMark(options.actor, true) }), + steer: (target, runId, text, options) => service.steer(target, runId, text, { clientRequestId: options.clientRequestId, mark: this.remoteAgentMark(options.actor, true) }), + interrupt: (target, runId, options) => service.interrupt(target, runId, { clientRequestId: options.clientRequestId, mark: this.remoteAgentMark(options.actor, false) }) + } + } + /** * The project of `computer` the thread starts in: the one that is the caller's repository, or `wanted` among those * that may be. No strong match, or several, refuses with the candidates; nothing is cloned there (#484). @@ -5236,11 +5319,17 @@ export class OrchestratorService extends EventEmitter { * A thread's visible transcript for a reader that is not working in it: from the live session when it * is open, else straight from the store, so reading does not keep every thread it touches in memory. */ - private visibleMessagesWithoutLoading(threadId: string): ChatMessage[] { + /** A thread's visible messages, read from disk when its session is not loaded (`thread_read`, here or routed). */ + visibleMessagesWithoutLoading(threadId: string): ChatMessage[] { if (this.sessions.has(threadId) || !this.threadStore) return this.getMessages(threadId) return this.threadStore.loadThreadData(threadId).messages.filter((message) => !message.hidden) } + /** Messages waiting in a thread's queue, read from disk without loading it (`runs.wait`). */ + queuedCount(threadId: string): number { + return this.threadActivity(threadId).queuedCount + } + /** What waits on a thread without loading it: its queued messages (from disk) and unanswered questions. */ private threadActivity(threadId: string): { queuedCount: number; pendingQuestions: PendingUserQuestions[] } { let queuedCount = 0 diff --git a/src/mms/orchestrator/RemoteLaunchedThreads.ts b/src/mms/orchestrator/RemoteLaunchedThreads.ts new file mode 100644 index 0000000000..f41c345857 --- /dev/null +++ b/src/mms/orchestrator/RemoteLaunchedThreads.ts @@ -0,0 +1,625 @@ +import { ROUTED_AGENT_KEY, ROUTED_AGENT_READ, ROUTED_RUN_WAIT_DEADLINE_MS, ROUTED_RUN_WAIT_MAX_MS, type RoutedAgentMark } from '../../shared/bridge/routed' +import { outgoingMessageText, qualifyRoutedResult, ROUTED_THREAD_ID_KEYS } from '../../shared/bridge/routedIds' +import { parseQualifiedId, qualifyId } from '../../shared/threadRef' +import { DomainRpcError } from '../protocol/domainRegistry' +import type { RemoteComputersPort } from '../protocol/remoteComputersPort' +import type { RemoteLaunchRecord, RemoteLaunchRecords, RemoteLaunchStop } from '../run/delegation/remoteLaunches' +import type { RunWaitReply, RunWaitRun } from '../run/runWait' +import { TERMINAL_RUN_STATUSES, type RunRecord, type RunStatus, type ThreadEvent } from '../run/types' +import type { MessageRow } from '../run/mcp/appTools/messageRows' + +/** + * The thread tools on a thread this computer's agents launched on another of the user's computers (issue #1160): + * `thread_read`, `thread_wait`, `thread_send`, `thread_steer` and `thread_interrupt` with a qualified id + * (`:`), and the Stop a person's Stop (or the deletion or expiry) of the launcher sends there. + * + * - **Which threads.** `reach` is the one place that decides: a thread `remote_launches` records as launched by the + * calling thread or a thread of its lineage. Any other qualified id is refused, naming why; never a bare not-found. + * - **Calls.** Every call is a routed call through Bridge, the writes marked as the calling agent's. Each first reaches + * the computer (its row versions, with a connect deadline of its own), then runs with its own deadline. A call that finds + * the computer unreachable is tried once more about a second later before the computer is called offline. A refusal + * names which it was (offline, not shared, outdated, not allowed) from that computer's answer to this call, never from + * a state kept from before. + * - **Ids.** Results are named the way this computer names things before a tool sees them: that computer's threads + * qualified, this computer's own plain, and an agent sender (`origin.from`) named by its thread on its computer. + * - **Stops.** A Stop that cannot be delivered is kept in its row (`remote_launches.stop_*`), survives a restart and is + * sent once that computer answers, until its deadline. The launcher's transcript says when it is still on its way. + */ + +/** Codes of a call that did not reach the computer: tried once more before the computer is called offline. */ +const UNREACHED: ReadonlySet = new Set(['computer_offline', 'peer_offline', 'route_unreachable']) +/** How long reaching a computer may take, apart from the call's own deadline. */ +const CONNECT_MS = 10_000 +/** The deadline of a quick call (a read, a send, a Stop). */ +const CALL_MS = 30_000 +/** The deadline of a quick probe (the working count). */ +const PROBE_MS = 8_000 +/** Without `runs.wait`, how often a wait asks the run's status. */ +export const REMOTE_WAIT_POLL_MS = 4_000 +/** A kept Stop is given up after this long. */ +export const REMOTE_STOP_DEADLINE_MS = 24 * 60 * 60_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 : (error as { code?: unknown } | null)?.code === undefined ? 'remote_error' : String((error as { code: unknown }).code)) +const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error)) + +/** A thread on another computer the caller may reach, or why not. */ +export type RemoteReach = + | { ok: true; record: RemoteLaunchRecord; node: string; remoteThreadId: string; computer: string; threadId: string } + | { ok: false; code: string; message: string; computer?: string } + +export type RemoteTarget = Extract + +/** A refusal the tool returns as it is: its code says which reason it was, its message names the computer. */ +export class RemoteThreadRefusal extends DomainRpcError { + constructor(code: string, message: string, readonly computer?: string, details?: Record) { + super(code, message, { ...(computer ? { computer } : {}), ...(details ?? {}) }) + } +} + +/** A write that computer may or may not have done: never reported as done or as failed. */ +export interface RemoteUncertain { + status: 'uncertain' + computer: string + message: string +} + +export type RemoteWaitResult = RunWaitReply & { + /** How the wait learned it: `runs.wait` there, or asking the run's status every few seconds (an older computer). */ + via: 'wait' | 'poll' + /** The caller's own run ended (or its call was cancelled) before the wait did. */ + callerEnded?: true +} + +export interface RemoteLaunchedThreadsDeps { + records: RemoteLaunchRecords + /** The Bridge side; undefined while Bridge is off. */ + port: () => RemoteComputersPort | undefined + /** Why agents here may not work on `node` now (the switch in Agent access, that computer not ticked); undefined when they may. */ + denial: (node: string, name: string) => { code: string; message: string } | undefined + /** Whether a thread of the caller's lineage is `launcherThreadId` (the caller itself, an ancestor or a descendant). */ + related: (callerThreadId: string, launcherThreadId: string) => boolean + /** Whether the thread is private (it stays on this computer). */ + localOnly: (threadId: string) => boolean + /** A note in the launcher's transcript; skipped for a launcher that is gone. */ + note: (launcherThreadId: string, text: string) => void + now?: () => number + sleep?: (ms: number) => Promise + /** How often kept Stops are tried again (default 5 s). */ + stopPollMs?: number + /** How long until a later attempt after one that found the computer unreachable (default 1 s). */ + retryMs?: number +} + +const defaultSleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms).unref?.()) + +/** + * A refusal for a failed call, named for which reason it was: offline, not sharing its threads with this computer, + * outdated, not letting this computer's agents work there, or the thread gone there. Any other code is that computer's own. + */ +export function remoteReachRefusal(error: unknown, computer: string, what: string): RemoteThreadRefusal { + const code = codeOf(error) + const message = messageOf(error) + switch (code) { + case 'computer_offline': + case 'peer_offline': + 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_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': + return new RemoteThreadRefusal('computer_not_allowed', `${computer} does not let this computer's agents change that thread: ${message}`, computer) + case 'thread_not_found': + return new RemoteThreadRefusal('remote_thread_gone', `${computer} has no such thread any more: it was deleted there.`, computer) + case 'deadline_exceeded': + return new RemoteThreadRefusal('computer_slow', `${computer} did not answer ${what} in time; it is connected, so try again in a moment.`, computer) + default: + return new RemoteThreadRefusal(code, message || `${computer} refused ${what}.`, computer) + } +} + +export class RemoteLaunchedThreads { + private timer: ReturnType | undefined + private passing: Promise | undefined + /** No pass runs by itself until `start`; `pass` still runs when called (a test, a restart's first pass). */ + private started = false + private closed = false + + constructor(private readonly deps: RemoteLaunchedThreadsDeps) {} + + private now(): number { + return this.deps.now?.() ?? Date.now() + } + + private sleep(ms: number): Promise { + return (this.deps.sleep ?? defaultSleep)(ms) + } + + /** Starts delivering kept Stops (boot, or Bridge coming up). */ + start(): void { + this.started = true + this.closed = false + this.kick() + } + + close(): void { + this.closed = true + if (this.timer) clearTimeout(this.timer) + this.timer = undefined + } + + /** Waits for a pass under way (tests). */ + async settled(): Promise { + while (this.passing) await this.passing + } + + // ------------------------------------------------------------------ reach + + /** + * Whether `callerThreadId` may reach `threadId`, a qualified id: a thread `remote_launches` says the caller, or a thread + * of its lineage, launched there. The one place that decides it (a later change widens it here). + */ + reach(callerThreadId: string, threadId: string): RemoteReach { + const ref = parseQualifiedId(threadId) + if (!ref) return { ok: false, code: 'invalid_thread_id', message: `${threadId} does not name a thread on another computer.` } + const port = this.deps.port() + const self = port?.self?.() + if (self && ref.node === self) return { ok: false, code: 'invalid_thread_id', message: `That thread is on this computer: use its own id, ${ref.id}.` } + const record = this.deps.records.getByRemoteThread(ref.node, ref.id) + const computer = record?.computerName ?? port?.computers()?.find((entry) => entry.node === ref.node)?.name ?? 'that computer' + if (this.deps.localOnly(callerThreadId)) + return { ok: false, code: 'private_thread', message: 'This is a private thread: it stays on this computer, so it cannot reach threads on other computers.', computer } + if (!record || !this.deps.related(callerThreadId, record.launcherThreadId)) + return { + ok: false, + code: 'not_launched_here', + message: `Thread ${threadId} on ${computer} was not launched by this thread or a thread of its lineage. An agent reaches a thread on another computer only after launching it there with thread_create and computer.`, + computer + } + if (record.state === 'abandoned') + return { ok: false, code: 'launch_abandoned', message: `The launch of «${record.title}» on ${computer} was given up (${record.lastError ?? 'refused'}); the thread there was archived.`, computer } + return { ok: true, record, node: ref.node, remoteThreadId: ref.id, computer, threadId: qualifyId(ref.node, ref.id) } + } + + /** Refuses a call agents here may no longer make on that computer (the user turned it off since the launch). */ + private assertAllowed(target: RemoteTarget): void { + const denied = this.deps.denial(target.node, target.computer) + if (denied) throw new RemoteThreadRefusal(denied.code, denied.message, target.computer) + } + + // ------------------------------------------------------------------ calls + + /** + * One routed call: reach the computer within the connect deadline, then the call within its own. A call that did not + * reach it is tried once more a second later; only then is the computer called offline. A write carries `idem`, so the + * second attempt can never act twice there. + */ + private async call( + target: { node: string; computer: string }, + method: string, + params: Record, + options: { idem?: string; deadlineMs?: number; what: string; signal?: AbortSignal; connectMs?: number; retry?: boolean } + ): Promise<{ result: unknown; versions: Record | undefined }> { + const attempts = options.retry === false ? 1 : 2 + for (let attempt = 0; ; attempt++) { + if (attempt > 0) await this.sleep(this.deps.retryMs ?? 1_000) + const port = this.deps.port() + if (!port) throw new RemoteThreadRefusal('computer_offline', `Connecting to your other computers is turned off on this computer, so ${options.what} did not reach ${target.computer}.`, target.computer) + let versions: Record | undefined + try { + const connect = AbortSignal.timeout(options.connectMs ?? CONNECT_MS) + versions = port.versions ? await port.versions(target.node, options.signal ? AbortSignal.any([connect, options.signal]) : connect) : undefined + } catch (error) { + // Nothing was sent: the computer was not reached. + if (attempt + 1 < attempts && UNREACHED.has(codeOf(error))) continue + throw error + } + try { + const deadline = AbortSignal.timeout(options.deadlineMs ?? CALL_MS) + const result = await port.call(target.node, method, params, { + ...(options.idem ? { idem: options.idem } : {}), + signal: options.signal ? AbortSignal.any([deadline, options.signal]) : deadline + }) + return { result, versions } + } catch (error) { + const lost = UNREACHED.has(codeOf(error)) + // A write the link dropped after it was reached may have gone through there: it is not known, so not retried here. + if (lost && options.idem) throw new DomainRpcError('outcome_uncertain', `${target.computer} went offline while ${options.what} was on its way.`) + if (lost && attempt + 1 < attempts) continue + throw error + } + } + } + + /** A result named as this computer names things: that computer's threads qualified, this computer's own plain. */ + private named(node: string, method: string, value: unknown): unknown { + const self = this.deps.port()?.self?.() + 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 }> { + 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 } + } catch (error) { + throw remoteReachRefusal(error, target.computer, what) + } + } + + // ------------------------------------------------------------------ reading + + /** `thread_read` view `events`: one page of the run events there, `limit` at most (the tool's own page). */ + async events(target: RemoteTarget, page: { afterSeq: number; limit: number }): Promise<{ events: ThreadEvent[]; maxSeq: number }> { + this.assertAllowed(target) + const { value } = await this.read(target, 'runs.events', { afterSeq: page.afterSeq, limit: page.limit }, 'reading the thread') + const events = isRecord(value) && Array.isArray(value.events) ? (value.events as ThreadEvent[]) : [] + const maxSeq = isRecord(value) && typeof value.maxSeq === 'number' ? value.maxSeq : events.at(-1)?.seq ?? page.afterSeq + return { events, maxSeq } + } + + /** + * `thread_read` view `messages`: the rows of one page, built there from `afterIndex` with each text cut to the tool's + * limit, so only what the tool returns crosses. + */ + async messages(target: RemoteTarget, page: { afterIndex: number; limit: number; textOffset: number; textMax: number }): Promise<{ messages: MessageRow[]; total: number }> { + this.assertAllowed(target) + const { value } = await this.read(target, 'thread.messages', { + index: page.afterIndex, + limit: page.limit, + ...(page.textOffset > 0 ? { textOffset: page.textOffset } : {}), + textMax: Math.min(page.textMax, ROUTED_AGENT_READ.textMax) + }, 'reading its messages') + const raw = isRecord(value) && Array.isArray(value.messages) ? value.messages : [] + const messages = raw.filter(isRecord).map(({ content, ...row }) => ({ ...row, text: typeof content === 'string' ? content : '' }) as unknown as MessageRow) + return { messages, total: isRecord(value) && typeof value.total === 'number' ? value.total : messages.length } + } + + // ------------------------------------------------------------------ waiting + + /** + * `thread_wait`: waits up to `timeoutMs` for the run (`runId`, else the one active or paused now) to end there, or to + * wait on a person there. On a computer that has `runs.wait` it waits there, 40 s at a time; on an older one it asks the + * run's status every few seconds. A thread with a run preparing or a message waiting in its queue is never idle. + * + * Also the follower a watch on a thread there uses (`notify` across computers): call it until it returns `finished`, or + * `needs_input` the first time. + */ + async follow(target: Pick, request: { runId?: string; timeoutMs: number; signal?: AbortSignal }): Promise { + const until = this.now() + request.timeoutMs + let runId = request.runId + let continuedFrom: string | undefined + let via: RemoteWaitResult['via'] = 'wait' + let last: RunWaitReply | undefined + for (;;) { + if (request.signal?.aborted) return { ...(last ?? { status: 'timeout' }), via, callerEnded: true } + const left = until - this.now() + if (left <= 0) return { ...(last ?? {}), status: 'timeout', via } + let reply: RunWaitReply + try { + const waited = await this.waitOnce(target, { ...(runId ? { runId } : {}), timeoutMs: Math.min(left, ROUTED_RUN_WAIT_MAX_MS), ...(request.signal ? { signal: request.signal } : {}) }) + via = waited.via + reply = waited.reply + } catch (error) { + if (request.signal?.aborted) return { ...(last ?? { status: 'timeout' }), via, callerEnded: true } + throw remoteReachRefusal(error, target.computer, 'the wait') + } + if (reply.continuedFrom) continuedFrom ??= reply.continuedFrom + if (reply.run?.runId) runId = reply.run.runId + last = { ...reply, ...(continuedFrom ? { continuedFrom } : {}) } + if (reply.status !== 'timeout') return { ...last, via } + } + } + + /** One wait of at most 40 s: `runs.wait` there, or a poll of its status on a computer without it. */ + private async waitOnce(target: Pick, request: { runId?: string; timeoutMs: number; signal?: AbortSignal }): Promise<{ reply: RunWaitReply; via: RemoteWaitResult['via'] }> { + const port = this.deps.port() + if (!port) throw new DomainRpcError('bridge_off', 'Connecting to your other computers is turned off on this computer.') + const versions = port.versions ? await this.reachVersions(target, request.signal) : undefined + if (versions?.['runs.wait'] !== undefined) { + const { result } = await this.call(target, 'runs.wait', { + threadId: target.remoteThreadId, + ...(request.runId ? { runId: request.runId } : {}), + timeoutMs: request.timeoutMs + }, { what: 'the wait', deadlineMs: Math.min(ROUTED_RUN_WAIT_DEADLINE_MS, request.timeoutMs + 10_000), ...(request.signal ? { signal: request.signal } : {}) }) + return { reply: this.named(target.node, 'runs.wait', result) as RunWaitReply, via: 'wait' } + } + return { reply: await this.pollOnce(target, request), via: 'poll' } + } + + private async reachVersions(target: Pick, signal?: AbortSignal): Promise | undefined> { + const port = this.deps.port()! + for (let attempt = 0; ; attempt++) { + try { + const connect = AbortSignal.timeout(CONNECT_MS) + return await port.versions!(target.node, signal ? AbortSignal.any([connect, signal]) : connect) + } catch (error) { + if (attempt > 0 || !UNREACHED.has(codeOf(error))) throw error + await this.sleep(this.deps.retryMs ?? 1_000) + } + } + } + + /** + * A wait on a computer that has no `runs.wait`: the run's status every `REMOTE_WAIT_POLL_MS`, until it ends, waits on a + * person, or `timeoutMs` passes. The final text is not read here (that computer's messages hold it). + */ + private async pollOnce(target: Pick, request: { runId?: string; timeoutMs: number; signal?: AbortSignal }): Promise { + const until = this.now() + request.timeoutMs + let runId = request.runId + const ask = async (method: string, params: Record): Promise => + this.named(target.node, method, (await this.call(target, method, { threadId: target.remoteThreadId, ...params }, { what: 'the wait', ...(request.signal ? { signal: request.signal } : {}) })).result) + for (;;) { + let run: RunRecord | undefined + if (runId) { + const got = await ask('runs.get', { runId }) + run = isRecord(got) && isRecord(got.run) ? (got.run as unknown as RunRecord) : undefined + // A run a pause handed on: the run that continues it answers. + if (run && TERMINAL_RUN_STATUSES.has(run.status) && (run.outcome?.pause?.endedBy === 'resume' || run.outcome?.pause?.endedBy === 'resume_now')) { + const listed = await ask('runs.list', { limit: 20 }) + const next = (isRecord(listed) && Array.isArray(listed.runs) ? (listed.runs as RunRecord[]) : []).find((entry) => entry.outcome?.continuationOf === run!.runId) + if (next) { + runId = next.runId + continue + } + } + } else { + const listed = await ask('runs.list', { limit: 5 }) + const runs = isRecord(listed) && Array.isArray(listed.runs) ? (listed.runs as RunRecord[]) : [] + run = runs.find((entry) => !TERMINAL_RUN_STATUSES.has(entry.status) && entry.status !== 'queued') ?? runs.find((entry) => entry.status === 'queued') + if (run && run.status !== 'queued') runId = run.runId + } + if (run && TERMINAL_RUN_STATUSES.has(run.status)) return { status: 'finished', run: runView(run) } + const pending = await ask('orchestrator.pendingQuestions', {}) + const requests = isRecord(pending) && Array.isArray(pending.pending) ? pending.pending.length : 0 + if (run && requests > 0) return { status: 'needs_input', run: runView(run), needsInput: { requests } } + let queued = 0 + if (!run) { + const queue = await ask('queue.list', {}) + queued = isRecord(queue) && Array.isArray(queue.items) ? queue.items.length : 0 + if (queued === 0) return { status: 'idle', ...(requests > 0 ? { needsInput: { requests } } : {}) } + } + const left = until - this.now() + if (left <= 0 || request.signal?.aborted) + return run ? { status: 'timeout', run: runView(run), ...(run.status === 'queued' ? { pending: 'preparing' as const } : {}) } : { status: 'timeout', pending: 'queued_message' } + await this.sleep(Math.min(REMOTE_WAIT_POLL_MS, left)) + } + } + + // ------------------------------------------------------------------ messaging + + /** + * `thread_send`: a marked `orchestrator.send` there, keyed by the caller's request key, so a retry reaches the first + * send and never makes a second run. A send that computer may or may not have taken is `uncertain`. + */ + async send(target: RemoteTarget, input: { content: string; mode: 'agent' | 'plan' }, options: { clientRequestId: string; mark: RoutedAgentMark }): Promise<{ status: 'sent'; runId?: string; queued: boolean; replayed: boolean; mode?: string } | RemoteUncertain> { + this.assertAllowed(target) + const self = this.deps.port()?.self?.() + // A later message from here is new work: a Stop still on its way there from before must not end it. + if (target.record.stop?.state === 'pending') this.deps.records.settleStop(target.record.creationKey, target.record.stop.key, 'expired', 'A later message from this computer superseded it.') + let result: unknown + try { + result = (await this.call(target, 'orchestrator.send', { + threadId: target.remoteThreadId, + content: outgoingMessageText(input.content, { node: target.node, ...(self ? { self } : {}) }), + mode: input.mode, + clientRequestId: options.clientRequestId, + [ROUTED_AGENT_KEY]: options.mark + }, { idem: options.clientRequestId, what: 'the message' })).result + } catch (error) { + if (codeOf(error) === 'outcome_uncertain' || codeOf(error) === 'cancelled') + return { status: 'uncertain', computer: target.computer, message: `${target.computer} has not confirmed the message. Call thread_send again with the same clientRequestId to learn what became of it; it is never sent twice.` } + throw remoteReachRefusal(error, target.computer, 'the message') + } + const sent = isRecord(result) ? result : {} + return { + status: 'sent', + ...(typeof sent.runId === 'string' ? { runId: sent.runId } : {}), + queued: sent.queued === true, + replayed: sent.replayed === true, + ...(typeof sent.mode === 'string' ? { mode: sent.mode } : {}) + } + } + + /** `thread_steer`: a marked `orchestrator.steer` there. What the owner refuses is thrown with its code. */ + async steer(target: RemoteTarget, runId: string, text: string, options: { clientRequestId: string; mark: RoutedAgentMark }): Promise<{ status: 'accepted'; runId: string } | { status: 'ignored'; reason: string; runId?: string } | RemoteUncertain> { + this.assertAllowed(target) + let result: unknown + try { + result = (await this.call(target, 'orchestrator.steer', { + threadId: target.remoteThreadId, + text, + runId, + clientRequestId: options.clientRequestId, + [ROUTED_AGENT_KEY]: options.mark + }, { idem: options.clientRequestId, what: 'the steer' })).result + } catch (error) { + const code = codeOf(error) + if (code === 'outcome_uncertain' || code === 'cancelled') + return { status: 'uncertain', computer: target.computer, message: `${target.computer} has not confirmed the steer. Call thread_steer again with the same clientRequestId to learn what became of it; it is never sent twice.` } + if (code === 'run_not_found') return { status: 'ignored', reason: 'run_not_found', runId } + // A refusal of that computer about the run or the thread (a looser run, a question waiting) keeps its own code and details. + if (error instanceof DomainRpcError && !UNREACHED.has(code) && !['computer_forbidden', 'computer_outdated', 'agent_reach', 'thread_not_found', 'deadline_exceeded', 'bridge_off'].includes(code)) + throw new RemoteThreadRefusal(code, error.message, target.computer, isRecord(error.details) ? error.details : undefined) + throw remoteReachRefusal(error, target.computer, 'the steer') + } + const steered = isRecord(result) ? result : {} + if (steered.ok === true) return { status: 'accepted', runId: typeof steered.runId === 'string' ? steered.runId : runId } + return { status: 'ignored', reason: typeof steered.reason === 'string' ? steered.reason : 'run_not_active', ...(typeof steered.runId === 'string' ? { runId: steered.runId } : {}) } + } + + /** + * `thread_interrupt`: a marked `orchestrator.abort` there. That computer stops the run only when an agent of this + * computer started it; a thread a person took over is left as it is, and the answer says so. + */ + async interrupt(target: RemoteTarget, runId: string | undefined, options: { clientRequestId: string; mark: RoutedAgentMark }): Promise<{ status: 'stopped' | 'left'; runId?: string; left?: string } | RemoteUncertain> { + // An agent may always stop work it started, even after the user turned agents on that computer off. + let result: unknown + try { + result = (await this.call(target, 'orchestrator.abort', { + threadId: target.remoteThreadId, + ...(runId ? { runId } : {}), + clientRequestId: options.clientRequestId, + [ROUTED_AGENT_KEY]: options.mark + }, { idem: options.clientRequestId, what: 'the Stop' })).result + } catch (error) { + const code = codeOf(error) + if (code === 'outcome_uncertain' || code === 'cancelled') + return { status: 'uncertain', computer: target.computer, message: `${target.computer} has not confirmed the Stop. Call thread_interrupt again with the same clientRequestId to learn what became of it.` } + if (code === 'run_not_found') return { status: 'left', left: 'run_not_active', ...(runId ? { runId } : {}) } + throw remoteReachRefusal(error, target.computer, 'the Stop') + } + const stopped = isRecord(result) ? result : {} + return { + status: stopped.stopped === true ? 'stopped' : 'left', + ...(typeof stopped.runId === 'string' ? { runId: stopped.runId } : runId ? { runId } : {}), + ...(typeof stopped.left === 'string' ? { left: stopped.left } : {}) + } + } + + // ------------------------------------------------------------------ the working count + + /** + * How many of the threads `launcherThreadId` launched on other computers are working: a launch not finished yet, and a + * launched thread whose computer says it has a run going, preparing, or a message waiting. One that cannot be asked + * counts as working: the cap never lets more through on a guess. + */ + async working(launcherThreadId: string): Promise { + const rows = this.deps.records.listForLauncher(launcherThreadId).filter((row) => row.state !== 'abandoned') + const open = rows.filter((row) => row.state === 'starting' || row.state === 'created' || row.firstMessageState === 'pending' || row.firstMessageState === 'uncertain') + const asked = rows.filter((row) => !open.includes(row) && row.remoteThreadId) + const answers = await Promise.all(asked.map(async (row) => { + const target = { node: row.node, computer: row.computerName, remoteThreadId: row.remoteThreadId! } + try { + const port = this.deps.port() + if (!port) return true + const versions = port.versions ? await port.versions(row.node, AbortSignal.timeout(PROBE_MS)) : undefined + if (versions?.['runs.wait'] !== undefined) { + const { result } = await this.call(target, 'runs.wait', { threadId: row.remoteThreadId, timeoutMs: 0 }, { what: 'the count', deadlineMs: PROBE_MS, connectMs: PROBE_MS, retry: false }) + return !(isRecord(result) && (result.status === 'idle' || result.status === 'finished')) + } + const { result } = await this.call(target, 'runs.list', { threadId: row.remoteThreadId, limit: 1 }, { what: 'the count', deadlineMs: PROBE_MS, connectMs: PROBE_MS, retry: false }) + const latest = isRecord(result) && Array.isArray(result.runs) ? (result.runs[0] as RunRecord | undefined) : undefined + return latest !== undefined && !TERMINAL_RUN_STATUSES.has(latest.status) + } catch { + return true + } + })) + return open.length + answers.filter(Boolean).length + } + + // ------------------------------------------------------------------ Stops + + /** + * A person stopped these launchers, or they are deleted or expired: their threads on other computers are stopped there + * too. Each Stop is kept before it is sent, so one that cannot be delivered now is sent once that computer answers. + */ + stopLaunchedBy(launcherThreadIds: readonly string[], reason: RemoteLaunchStop['reason']): void { + let kept = 0 + const deadline = new Date(this.now() + REMOTE_STOP_DEADLINE_MS).toISOString() + for (const launcherThreadId of new Set(launcherThreadIds)) { + for (const row of this.deps.records.listForLauncher(launcherThreadId)) { + if (!row.remoteThreadId || row.state === 'abandoned') continue + this.deps.records.requestStop(row.creationKey, { key: `${row.creationKey}:stop:${this.now()}`, reason, deadline }) + kept += 1 + } + } + if (kept) this.kick() + } + + /** Runs a pass now (and keeps passing while Stops wait). */ + kick(): void { + if (!this.started || this.closed) return + if (this.passing) return + if (this.timer) clearTimeout(this.timer) + this.timer = setTimeout(() => { + this.timer = undefined + this.passing = this.pass().finally(() => { + this.passing = undefined + if (!this.closed && this.deps.records.listPendingStops().length) { + this.timer = setTimeout(() => this.kick(), this.deps.stopPollMs ?? 5_000) + this.timer.unref?.() + } + }) + }, 0) + this.timer.unref?.() + } + + /** One attempt at every kept Stop. Never throws. */ + async pass(): Promise { + for (const row of this.deps.records.listPendingStops()) { + if (this.closed) return + const stop = row.stop! + if (this.now() >= Date.parse(stop.deadline)) { + this.deps.records.settleStop(row.creationKey, stop.key, 'expired', stop.result) + if (stop.reason === 'stopped') + this.safeNote(row.launcherThreadId, `The Stop did not reach «${row.title}» on ${row.computerName} within a day, so Mousse stopped trying. Its run there may still be going.`) + continue + } + try { + const target: RemoteTarget = { ok: true, record: row, node: row.node, remoteThreadId: row.remoteThreadId!, computer: row.computerName, threadId: qualifyId(row.node, row.remoteThreadId!) } + const done = await this.interrupt(target, undefined, { clientRequestId: stop.key, mark: { ...row.mark, hops: 1 } }) + if (done.status === 'uncertain') throw new DomainRpcError('outcome_uncertain', done.message) + const said = done.status === 'stopped' ? `stopped run ${done.runId ?? ''}`.trim() : done.left === 'not_started_by_this_computer' ? 'left alone: a person there took the thread over' : 'nothing was running' + this.deps.records.settleStop(row.creationKey, stop.key, 'sent', said) + // The launcher was told the Stop had not arrived: it is told when it does. + if (stop.reason === 'stopped' && stop.result?.startsWith('undelivered')) + this.safeNote(row.launcherThreadId, `The Stop reached «${row.title}» on ${row.computerName}: ${said}.`) + } catch (error) { + const current = this.deps.records.get(row.creationKey)?.stop + if (!current || current.state !== 'pending' || current.key !== stop.key) continue + const first = !current.result?.startsWith('undelivered') + this.deps.records.updateStopResult(row.creationKey, stop.key, `undelivered: ${messageOf(error)}`) + if (first && stop.reason === 'stopped') + this.safeNote(row.launcherThreadId, `The Stop has not reached «${row.title}» on ${row.computerName} yet (${messageOf(error)}), so its run there may still be going. Mousse sends it when ${row.computerName} answers, for up to a day.`) + } + } + } + + private safeNote(launcherThreadId: string, text: string): void { + try { + this.deps.note(launcherThreadId, text) + } catch (error) { + console.warn('a note about a Stop on another computer could not be written', { error: messageOf(error) }) + } + } +} + +function runView(run: RunRecord): RunWaitRun { + const outcome = run.outcome + const pause = outcome?.pause + return { + runId: run.runId, + status: run.status as RunStatus, + ...(outcome?.error ? { error: String(outcome.error).slice(0, 1_000) } : {}), + ...(outcome?.interruptedBy ? { interruptedBy: outcome.interruptedBy } : {}), + ...(run.status === 'paused' && pause ? { pause: { reason: pause.reason, until: pause.until, estimated: pause.estimated } } : {}) + } +} + +/** + * A qualified result as an agent here reads it: an id this computer's own (`:`, a thread here that thread + * names) is plain again, and an agent sender (`origin.from { node, thread, run }`) names its thread qualified unless it + * is this computer's, so no id of another computer resolves to a thread here. + */ +export function localized(value: unknown, self: string | undefined, depth = 0): unknown { + if (depth > 64) return value + if (Array.isArray(value)) return value.map((item) => localized(item, self, depth + 1)) + if (!isRecord(value)) return value + const out: Record = {} + for (const [key, inner] of Object.entries(value)) { + if (typeof inner === 'string' && ROUTED_THREAD_ID_KEYS.includes(key)) { + const ref = parseQualifiedId(inner) + out[key] = ref && self && ref.node === self ? ref.id : inner + continue + } + if (key === 'from' && value.kind === 'agent' && isRecord(inner) && typeof inner.node === 'string' && typeof inner.thread === 'string') { + out[key] = { ...inner, thread: inner.node === self ? inner.thread : qualifyId(inner.node, inner.thread) } + continue + } + out[key] = localized(inner, self, depth + 1) + } + return out +} diff --git a/src/mms/protocol/gitAccess.ts b/src/mms/protocol/gitAccess.ts index 27a3e12545..dc66500bf7 100644 --- a/src/mms/protocol/gitAccess.ts +++ b/src/mms/protocol/gitAccess.ts @@ -70,6 +70,7 @@ export const GIT_ACCESS = { 'runs.list': 'none', 'runs.get': 'none', 'runs.events': 'none', + 'runs.wait': 'none', 'runs.effects': 'none', 'runs.credentials': 'none', 'runs.transfers': 'none', diff --git a/src/mms/protocol/handlers.ts b/src/mms/protocol/handlers.ts index df26f685d2..5bc2bc4515 100644 --- a/src/mms/protocol/handlers.ts +++ b/src/mms/protocol/handlers.ts @@ -103,7 +103,10 @@ import { import { FIRST_SEND_BINDING_CAPABILITY, PROTOCOL_CAPABILITIES, PROTOCOL_METHODS, MMS_PROTOCOL_VERSION } from './types' import { imageAt, messagesAfter, messagesBefore, newestPage, withoutImageBytes } from './transcriptPaging' import { isOpenActivityRow } from '../run/restartNote' -import { ROUTED_MESSAGES_PAGE_BYTES, ROUTED_SEND_WINDOW_KEY, ROUTED_SNAPSHOT_MESSAGE_BYTES } from '../../shared/bridge/routed' +import { ROUTED_AGENT_READ, ROUTED_MESSAGES_PAGE_BYTES, ROUTED_RUN_WAIT_MAX_MS, ROUTED_SEND_WINDOW_KEY, ROUTED_SNAPSHOT_MESSAGE_BYTES } from '../../shared/bridge/routed' +import { waitOnRun } from '../run/runWait' +import { messageRows, textOffsetProblem } from '../run/mcp/appTools/messageRows' +import { THREAD_RESULT_MAX_CHARS } from '../run/mcp/appTools/thread' import { buildSubagentView } from '../run/delegation/subagentView' import { connectionIsLocal, listedProjectsFor, listedThreadsFor } from './threadVisibility' import { localOnlyThreadIds, threadFolderIsLocalOnly } from '../data/localOnlyThreads' @@ -401,6 +404,35 @@ function questionAnswerer(ctx: HandlerContext): Answerer { /** Messages `thread.messages` returns when the caller names no limit, and the most it will. */ const MESSAGES_PAGE_DEFAULT = 100 +/** `thread.messages` with `index`: at most this many messages in one page (an agent's `thread_read` asks for up to 200). */ +const AGENT_MESSAGES_PAGE_MAX = 200 + +/** + * `thread.messages` with `index` (issue #1160): the page an agent's `thread_read` on another computer shows, built here + * as for this computer's own agents (`messageRows`). Each message's text is cut to `textMax` characters (the first from + * `textOffset`) and the rows stop once they pass the page's bytes, so only what the tool can return crosses. The text + * goes as `content`, so the router names the references in it the way the reader's computer does. + */ +async function agentMessagesPage(ctx: HandlerContext, threadId: string, p: Record): Promise { + if (p.before !== undefined || p.after !== undefined) throw new DomainRpcError('invalid_params', 'index pages without before or after.') + const index = asBoundedInt(p.index, 'index', { min: 0, max: Number.MAX_SAFE_INTEGER }) + const limit = asOptionalBoundedInt(p.limit, 'limit', { min: 1, max: AGENT_MESSAGES_PAGE_MAX }) ?? 50 + const textOffset = asOptionalBoundedInt(p.textOffset, 'textOffset', { min: 0, max: Number.MAX_SAFE_INTEGER }) ?? 0 + const textMax = asOptionalBoundedInt(p.textMax, 'textMax', { min: 1, max: ROUTED_AGENT_READ.textMax }) ?? ROUTED_AGENT_READ.textMax + if (!ctx.mms.threads.getThread(threadId)) throw new DomainRpcError('thread_not_found', 'Thread not found', { threadId }) + const all = ctx.mms.orchestrator.visibleMessagesWithoutLoading(threadId) + const problem = textOffsetProblem(all, index, textOffset) + if (problem) throw new DomainRpcError('invalid_params', problem) + const messages: Array> = [] + let bytes = 0 + for (const { text, ...row } of messageRows(all, { afterIndex: index, limit, textOffset, maxChars: textMax })) { + const shown = { ...row, content: text } + bytes += Buffer.byteLength(JSON.stringify(shown), 'utf8') + if (messages.length > 0 && bytes > ROUTED_AGENT_READ.pageBytes) break + messages.push(shown) + } + return { messages, total: all.length } +} const MESSAGES_PAGE_MAX = 500 /** The most messages a `thread.snapshot` with `newest` returns. */ const SNAPSHOT_NEWEST_MAX = 2000 @@ -2343,8 +2375,10 @@ async function dispatchOwnedMethod(ctx: HandlerContext, method: string, params: case 'thread.messages': { // A page of the messages before (or after) one, for a reader that was given only part of a long transcript. const p = isObject(params) ? params : {} - rejectUnknownKeys(p, ['threadId', 'before', 'after', 'limit']) + rejectUnknownKeys(p, ['threadId', 'before', 'after', 'limit', 'index', 'textOffset', 'textMax']) const threadId = asString(p.threadId, 'threadId', 256) + if (p.index !== undefined) return agentMessagesPage(ctx, threadId, p) + if (p.textOffset !== undefined || p.textMax !== undefined) throw new DomainRpcError('invalid_params', 'textOffset and textMax go with index.') const before = asOptionalString(p.before, 256) const after = asOptionalString(p.after, 256) if ((before === undefined) === (after === undefined)) throw new DomainRpcError('invalid_params', 'Name a message to page before or after.') @@ -2691,6 +2725,22 @@ async function dispatchOwnedMethod(ctx: HandlerContext, method: string, params: maxSeq: ctx.mms.runEngine.maxSeq(threadId) } } + case 'runs.wait': { + // An agent on another computer waits on a run of this thread (`thread_wait`, issue #1160): answered from the run + // events here, at most `ROUTED_RUN_WAIT_MAX_MS` later. + const p = isObject(params) ? params : {} + rejectUnknownKeys(p, ['threadId', 'runId', 'timeoutMs']) + const threadId = asString(p.threadId, 'threadId', 256) + const runId = asOptionalString(p.runId, 256) + const timeoutMs = asOptionalBoundedInt(p.timeoutMs, 'timeoutMs', { min: 0, max: ROUTED_RUN_WAIT_MAX_MS }) ?? ROUTED_RUN_WAIT_MAX_MS + if (!ctx.mms.threads.getThread(threadId)) throw new DomainRpcError('thread_not_found', 'Thread not found', { threadId }) + if (runId !== undefined && ctx.mms.runEngine.getRun(runId)?.threadId !== threadId) throw new DomainRpcError('run_not_found', 'Run not found', { runId }) + return waitOnRun({ + engine: ctx.mms.runEngine, + waitingOnPerson: (id) => ctx.mms.questions.listPendingForThread(id).length, + queued: (id) => ctx.mms.orchestrator.queuedCount(id) + }, { threadId, ...(runId ? { runId } : {}), timeoutMs, resultMaxChars: THREAD_RESULT_MAX_CHARS, ...(ctx.connection?.lifetime ? { signal: ctx.connection.lifetime } : {}) }) + } case 'runs.effects': { // The newest effects of the thread (at most EFFECT_PAGE_MAX), oldest first; `before` pages back. const p = isObject(params) ? params : {} diff --git a/src/mms/protocol/remoteComputersPort.ts b/src/mms/protocol/remoteComputersPort.ts index bd708d7030..dbb80b2c03 100644 --- a/src/mms/protocol/remoteComputersPort.ts +++ b/src/mms/protocol/remoteComputersPort.ts @@ -18,6 +18,13 @@ export interface RemoteComputer { export interface RemoteComputersPort { /** The user's other computers that run threads; undefined while the device list cannot be read. */ computers(): RemoteComputer[] | undefined + /** This computer's own Net node id, when it has one: an id another computer qualifies with it is one of this computer's. */ + self?(): string | undefined + /** + * The versions of the routed rows `node` takes, asked once per link: the step that reaches the computer, which a call + * gives a deadline of its own (`signal`). Throws like `call` when it cannot be asked (offline, Bridge off, not shared). + */ + versions?(node: string, signal?: AbortSignal): Promise | undefined> /** One routed call to `node`. Throws a `DomainRpcError` a person could read (offline, outdated, refused). */ call(node: string, method: string, params: Record, options?: { idem?: string; signal?: AbortSignal }): Promise /** diff --git a/src/mms/protocol/types.ts b/src/mms/protocol/types.ts index a0c31c7306..9bbba28c14 100644 --- a/src/mms/protocol/types.ts +++ b/src/mms/protocol/types.ts @@ -281,6 +281,7 @@ export const PROTOCOL_METHODS = [ 'runs.list', 'runs.get', 'runs.events', + 'runs.wait', 'runs.effects', 'runs.credentials', 'runs.transfers', diff --git a/src/mms/run/db/migrations.ts b/src/mms/run/db/migrations.ts index d0166b802d..e6e9704493 100644 --- a/src/mms/run/db/migrations.ts +++ b/src/mms/run/db/migrations.ts @@ -673,6 +673,24 @@ CREATE TABLE remote_launches( CREATE INDEX remote_launches_launcher ON remote_launches(launcher_thread_id); CREATE INDEX remote_launches_remote ON remote_launches(node, remote_thread_id); CREATE INDEX remote_launches_open ON remote_launches(state, first_message_state); +` + }, + { + version: 22, + sql: ` +-- A person's Stop of a launcher, its deletion or its expiry reaches the threads it launched on other computers +-- (issue #1160): a marked orchestrator.abort there, which stops only runs this computer's agents started. A Stop that +-- could not be delivered is kept here, survives a restart and is sent when that computer answers, until stop_deadline. +-- pending: not delivered yet (stop_key is the idempotency key every attempt uses, so it acts once there); +-- sent: that computer answered (stop_result says what it stopped, or why it left the run); +-- expired: stop_deadline passed first. +-- stop_reason: stopped (a person's Stop), deleted or expired (the launcher's). +ALTER TABLE remote_launches ADD COLUMN stop_state TEXT CHECK(stop_state IS NULL OR stop_state IN ('pending','sent','expired')); +ALTER TABLE remote_launches ADD COLUMN stop_key TEXT; +ALTER TABLE remote_launches ADD COLUMN stop_reason TEXT CHECK(stop_reason IS NULL OR stop_reason IN ('stopped','deleted','expired')); +ALTER TABLE remote_launches ADD COLUMN stop_deadline TEXT; +ALTER TABLE remote_launches ADD COLUMN stop_result TEXT; +CREATE INDEX remote_launches_stops ON remote_launches(stop_state); ` } ] diff --git a/src/mms/run/delegation/remoteLaunches.ts b/src/mms/run/delegation/remoteLaunches.ts index d2ec5e5933..139c120495 100644 --- a/src/mms/run/delegation/remoteLaunches.ts +++ b/src/mms/run/delegation/remoteLaunches.ts @@ -48,10 +48,24 @@ export interface RemoteLaunchRecord { firstMessageState: RemoteLaunchFirstMessage /** Why the latest call there failed; cleared by the next one that works. */ lastError: string | null + /** A Stop of the launcher sent (or still to send) there; null when none was asked for. */ + stop: RemoteLaunchStop | null createdAt: string updatedAt: string } +/** The launcher was stopped, deleted or expired: what reaches the thread there (migration 22). */ +export interface RemoteLaunchStop { + state: 'pending' | 'sent' | 'expired' + /** The idempotency key of every attempt, so the Stop acts once there. */ + key: string + reason: 'stopped' | 'deleted' | 'expired' + /** Given up after this, if not delivered by then. */ + deadline: string + /** What that computer said: what it stopped, or why it left the run. */ + result: string | null +} + const STATES: ReadonlySet = new Set(['starting', 'created', 'launched', 'abandoned']) const FIRST: ReadonlySet = new Set(['none', 'pending', 'sent', 'failed', 'uncertain']) @@ -71,6 +85,20 @@ function parseMark(raw: unknown): RoutedAgentMark { } } +function stopOf(row: Row): RemoteLaunchStop | null { + const state = str(row.stop_state) + const key = str(row.stop_key) + if (!state || !key) return null + const reason = str(row.stop_reason) + return { + state: state === 'sent' || state === 'expired' ? state : 'pending', + key, + reason: reason === 'deleted' || reason === 'expired' ? reason : 'stopped', + deadline: str(row.stop_deadline) ?? new Date(0).toISOString(), + result: str(row.stop_result) + } +} + function fromRow(row: Row): RemoteLaunchRecord { const mode = String(row.permission_mode) const remoteMode = str(row.remote_mode) @@ -97,6 +125,7 @@ function fromRow(row: Row): RemoteLaunchRecord { state: (STATES.has(state) ? state : 'abandoned') as RemoteLaunchState, firstMessageState: (FIRST.has(first) ? first : 'uncertain') as RemoteLaunchFirstMessage, lastError: str(row.last_error), + stop: stopOf(row), createdAt: String(row.created_at), updatedAt: String(row.updated_at) } @@ -114,7 +143,7 @@ const COLUMNS: Record = { lastError: 'last_error' } -export type NewRemoteLaunch = Omit +export type NewRemoteLaunch = Omit /** The rows of `remote_launches`. Synchronous; every write joins the caller's transaction. */ export class RemoteLaunchRecords { @@ -186,6 +215,43 @@ export class RemoteLaunchRecords { ) } + /** + * Keeps a Stop for the launch: a new one with `stop.key`, or the one already pending (its key is kept, so it still acts + * once there). Returns the row as it is now. + */ + requestStop(creationKey: string, stop: { key: string; reason: RemoteLaunchStop['reason']; deadline: string }): RemoteLaunchRecord | null { + this.store.db + .statement( + `UPDATE remote_launches SET stop_state = 'pending', stop_key = ?, stop_reason = ?, stop_deadline = ?, stop_result = NULL, updated_at = ? + WHERE creation_key = ? AND (stop_state IS NULL OR stop_state != 'pending')` + ) + .run(stop.key, stop.reason, stop.deadline, this.now(), creationKey) + return this.get(creationKey) + } + + /** Records what became of a kept Stop: `sent` with what that computer said, or `expired`. */ + settleStop(creationKey: string, key: string, state: 'sent' | 'expired', result: string | null): RemoteLaunchRecord | null { + this.store.db + .statement(`UPDATE remote_launches SET stop_state = ?, stop_result = ?, updated_at = ? WHERE creation_key = ? AND stop_key = ? AND stop_state = 'pending'`) + .run(state, result, this.now(), creationKey, key) + return this.get(creationKey) + } + + /** Notes why a kept Stop is still pending (it stays pending). */ + updateStopResult(creationKey: string, key: string, result: string): void { + this.store.db + .statement(`UPDATE remote_launches SET stop_result = ?, updated_at = ? WHERE creation_key = ? AND stop_key = ? AND stop_state = 'pending'`) + .run(result, this.now(), creationKey, key) + } + + /** Every Stop not delivered yet, oldest first. */ + listPendingStops(): RemoteLaunchRecord[] { + return this.store.db + .statement(`SELECT * FROM remote_launches WHERE stop_state = 'pending' ORDER BY updated_at, rowid`) + .all() + .map(fromRow) + } + update(creationKey: string, patch: RemoteLaunchPatch): RemoteLaunchRecord | null { const sets: string[] = [] const values: Array = [] diff --git a/src/mms/run/mcp/appTools/host.ts b/src/mms/run/mcp/appTools/host.ts index 593015ddbd..f79d768d5c 100644 --- a/src/mms/run/mcp/appTools/host.ts +++ b/src/mms/run/mcp/appTools/host.ts @@ -3,6 +3,9 @@ import type { AgentJobLimits } from '../../../../shared/agentJobLimits' import type { PermissionMode } from '../../../../shared/permissionMode' import type { ModelOverride } from '../../../../shared/providerInstances' import type { ApprovalTag } from '../../../orchestrator/UserQuestionService' +import type { RemoteReach, RemoteTarget, RemoteUncertain, RemoteWaitResult } from '../../../orchestrator/RemoteLaunchedThreads' +import type { MessageRow } from './messageRows' +import type { ThreadEvent } from '../../types' import type { ChatMessage, CreateScheduledJobInput, PendingUserQuestions, QueuedMessage, ScheduledJob, Thread, UserQuestion, UserQuestionAnswers, UserQuestionAttachments } from '../../../../shared/types' import type { ScheduledJobOptionsInput } from '../../../scheduled/validateJobOptions' import type { DevGuiTools } from '../../../devgui/DevGuiTools' @@ -112,6 +115,21 @@ export type AgentRemoteThreadResult = | { status: 'uncertain'; computer: string; message: string } | { status: 'refused'; code: string; message: string; computer?: string; candidates?: RemoteProjectCandidate[]; computers?: Array<{ id: string; name: string }> } +/** + * The thread tools on a thread this computer's agents launched on another computer (issue #1160), named by its qualified + * id. `reach` decides which threads a caller may reach; every other call takes what it returned. Refusals are thrown with + * their code (`RemoteThreadRefusal`); a write that computer did not confirm comes back `uncertain`. + */ +export interface RemoteThreadsHost { + reach(callerThreadId: string, threadId: string): RemoteReach + events(target: RemoteTarget, page: { afterSeq: number; limit: number }): Promise<{ events: ThreadEvent[]; maxSeq: number }> + messages(target: RemoteTarget, page: { afterIndex: number; limit: number; textOffset: number; textMax: number }): Promise<{ messages: MessageRow[]; total: number }> + wait(target: RemoteTarget, request: { runId?: string; timeoutMs: number; signal?: AbortSignal }): Promise + send(target: RemoteTarget, input: { content: string; mode: 'agent' | 'plan' }, options: { clientRequestId: string; actor: AgentActor }): Promise<{ status: 'sent'; runId?: string; queued: boolean; replayed: boolean; mode?: string } | RemoteUncertain> + steer(target: RemoteTarget, runId: string, text: string, options: { clientRequestId: string; actor: AgentActor }): Promise<{ status: 'accepted'; runId: string } | { status: 'ignored'; reason: string; runId?: string } | RemoteUncertain> + interrupt(target: RemoteTarget, runId: string, options: { clientRequestId: string; actor: AgentActor }): Promise<{ status: 'stopped' | 'left'; runId?: string; left?: string } | RemoteUncertain> +} + /** A thread an agent created, as the creation decided it (never as the retry's arguments say). */ export interface AgentCreatedThread { threadId: string @@ -377,6 +395,8 @@ export interface AppToolHost extends DelegationToolsHost { * the caller's, and a retry with the same `clientRequestId` continues that one launch. Refusals are returned, not thrown. */ createRemoteThread?(input: AgentRemoteThreadRequest, options: { clientRequestId: string; actor: AgentActor }): Promise + /** The thread tools on threads launched on other computers; absent without Bridge's run engine. */ + remoteThreads?: RemoteThreadsHost /** * Adds a note row to the thread's transcript (the creator's: what it launched, and on which model). `launched` names * the thread it started, which the transcript draws as a chip. diff --git a/src/mms/run/mcp/appTools/index.ts b/src/mms/run/mcp/appTools/index.ts index 3978a40716..296529517b 100644 --- a/src/mms/run/mcp/appTools/index.ts +++ b/src/mms/run/mcp/appTools/index.ts @@ -25,7 +25,7 @@ import { webTools } from './web' export * from './types' export * from './registry' export * from './turns' -export type { AgentActionDetails, AgentApprovalResult, AgentArchiveResult, AgentCreatedThread, AgentRemoteThreadRequest, AgentRemoteThreadResult, RemoteProjectCandidate, AgentQueueCommand, AgentQueueResult, AgentScheduleHost, AgentRunCommandResult, AgentSendResult, AgentThreadRequest, ApprovalRequestInfo, AppToolHost, QueueSnapshot, ThreadSearchHit } from './host' +export type { AgentActionDetails, AgentApprovalResult, AgentArchiveResult, AgentCreatedThread, AgentRemoteThreadRequest, AgentRemoteThreadResult, RemoteProjectCandidate, AgentQueueCommand, AgentQueueResult, AgentScheduleHost, AgentRunCommandResult, AgentSendResult, AgentThreadRequest, ApprovalRequestInfo, AppToolHost, QueueSnapshot, RemoteThreadsHost, ThreadSearchHit } from './host' export { AGENT_MESSAGE_END, AGENT_MESSAGE_PREFIX, agentMessage, agentMessageText, cleanRemoteSenderTitle, BOT_MESSAGE_END, BOT_MESSAGE_PREFIX, botMessageText, isPersonMessage, personTurnRequest } from './agentMessage' export type { BotAppToolDeps } from './bots' export { AUTOMATION_TOOL_NAMES, type AutomationToolHost } from './automations' diff --git a/src/mms/run/mcp/appTools/messageRows.ts b/src/mms/run/mcp/appTools/messageRows.ts new file mode 100644 index 0000000000..1835170644 --- /dev/null +++ b/src/mms/run/mcp/appTools/messageRows.ts @@ -0,0 +1,64 @@ +/** + * The rows of `thread_read` view `messages`: one per message, from an index, each message's text cut to a number of + * characters (the first one from `textOffset`). The computer that runs the thread builds them, here for its own agents + * and for a routed `thread.messages` with `index` (an agent on another computer, issue #1160), so a page reads the same + * on one computer or two and only what the tool returns crosses. + */ + +/** Where a cut of `text` at `end` falls, moved back one so it never splits a surrogate pair. */ +export function cutEnd(text: string, end: number): number { + if (end >= text.length) return text.length + const code = text.charCodeAt(end - 1) + return end > 0 && code >= 0xd800 && code <= 0xdbff ? end - 1 : end +} + +export interface TranscriptMessage { + id: string + role: string + timestamp?: unknown + content?: unknown +} + +export interface MessageRow { + index: number + id: string + role: string + timestamp: unknown + text: string + textOffset?: number + truncated?: true + totalChars?: number + nextTextOffset?: number +} + +const textOf = (message: TranscriptMessage | undefined): string => (message && typeof message.content === 'string' ? message.content : '') + +/** Why `textOffset` cannot be read in the message at `afterIndex`, or undefined when it can. */ +export function textOffsetProblem(all: readonly TranscriptMessage[], afterIndex: number, textOffset: number): string | undefined { + const first = textOf(all[afterIndex]) + if (textOffset > 0 && afterIndex < all.length && textOffset >= first.length) + return `textOffset ${textOffset} is past the end of message ${afterIndex}, which has ${first.length} characters` + return undefined +} + +/** The rows from `afterIndex`, `limit` at most, built one at a time so a reader that stops early reads no further. */ +export function* messageRows( + all: readonly TranscriptMessage[], + page: { afterIndex: number; limit: number; textOffset: number; maxChars: number } +): Generator { + for (let index = page.afterIndex; index < Math.min(all.length, page.afterIndex + page.limit); index += 1) { + const message = all[index]! + const text = textOf(message) + const from = index === page.afterIndex ? page.textOffset : 0 + const end = cutEnd(text, from + page.maxChars) + yield { + index, + id: message.id, + role: message.role, + timestamp: message.timestamp, + text: text.slice(from, end), + ...(from > 0 ? { textOffset: from } : {}), + ...(end < text.length ? { truncated: true as const, totalChars: text.length, nextTextOffset: end } : {}) + } + } +} diff --git a/src/mms/run/mcp/appTools/thread.ts b/src/mms/run/mcp/appTools/thread.ts index 29e781950c..1872cde4ea 100644 --- a/src/mms/run/mcp/appTools/thread.ts +++ b/src/mms/run/mcp/appTools/thread.ts @@ -11,6 +11,9 @@ 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 { RemoteThreadRefusal, type RemoteTarget, type RemoteWaitResult } from '../../../orchestrator/RemoteLaunchedThreads' +import { cutEnd, messageRows, textOffsetProblem, type MessageRow } from './messageRows' import type { BotActivityContext, BotActivitySink } from '../../../bots/seams' import { CLIENT_REQUEST_ID_SCHEMA, @@ -314,13 +317,6 @@ function boundedInt(value: unknown, name: string, min: number, max: number, fall return value } -/** Where a cut of `text` at `end` falls, moved back one so it never splits a surrogate pair. */ -function cutEnd(text: string, end: number): number { - if (end >= text.length) return text.length - const code = text.charCodeAt(end - 1) - return end > 0 && code >= 0xd800 && code <= 0xdbff ? end - 1 : end -} - const jsonBytes = (value: unknown): number => Buffer.byteLength(JSON.stringify(value), 'utf8') /** @@ -365,6 +361,41 @@ function boundedEvent(event: ThreadEvent): ThreadEvent { return { ...out, payload: { truncated: true, bytes: Buffer.byteLength(raw, 'utf8'), preview: raw.slice(0, cutEnd(raw, THREAD_EVENT_PREVIEW_CHARS)) } } } +/** A page of `thread_read` view `messages`: the rows that fit the byte cap, and how to read on. */ +function messagesPage(envelope: Record, rows: Iterable, afterIndex: number): Record { + const { taken: messages, capped } = fitPage(rows, envelope) + const truncated = messages.some((message) => 'truncated' in message) + return { + ...envelope, + messages, + nextAfterIndex: afterIndex + messages.length, + ...(capped ? { capped: true } : {}), + ...(capped || truncated + ? { + hint: [ + capped ? `This page stopped at ${THREAD_READ_MAX_BYTES / 1024} KB; continue with afterIndex ${afterIndex + messages.length}.` : '', + truncated ? 'A message marked truncated continues: pass its index as afterIndex and its nextTextOffset as textOffset.' : '' + ].filter(Boolean).join(' ') + } + : {}) + } +} + +/** + * A page of `thread_read` view `events`: the events of `visible` that fit the byte cap, each bounded. `nextAfterSeq` pages + * on even when a lineage view filtered events out of `page`; a page cut at the byte cap continues after its last event. + */ +function eventsPage(envelope: Record, page: readonly ThreadEvent[], visible: readonly ThreadEvent[], afterSeq: number): Record { + const { taken: events, capped } = fitPage(visible.map(boundedEvent), envelope) + const nextAfterSeq = capped ? events.at(-1)!.seq : page.at(-1)?.seq ?? afterSeq + return { + ...envelope, + events, + nextAfterSeq, + ...(capped ? { capped: true, hint: `This page stopped at ${THREAD_READ_MAX_BYTES / 1024} KB; continue with afterSeq ${nextAfterSeq}.` } : {}) + } +} + /** The caller's `clientRequestId` when given (a retry), else this call's id. */ function toolRequestId(args: Record, ctx: ToolCallContext): string { if (args.clientRequestId === undefined) return ctx.toolCallId @@ -615,6 +646,80 @@ function showAction(host: AppToolHost, threadId: string, actor: AgentActor, summ } } +/** + * The thread the central check holds a call to: a plain id names a thread here, checked as always; a qualified id names + * a thread on another computer, which only `RemoteThreadsHost.reach` decides (the handler branches at its top). + */ +function localTarget(args: Record, caller: McpCaller): { threadId?: string } | undefined { + if (isQualifiedId(args.threadId)) return undefined + return { threadId: (args.threadId as string | undefined) ?? caller.threadId } +} + +/** A refusal about a thread on another computer, as the tool returns it: its code says which reason it was. */ +function remoteRefusal(error: unknown): ToolOutcome | undefined { + if (!(error instanceof RemoteThreadRefusal)) return undefined + return { text: JSON.stringify({ ok: false, code: error.code, ...(error.computer ? { computer: error.computer } : {}), message: error.message }), isError: true } +} + +/** + * A refusal of the computer that runs the thread about the run itself (a steer into a looser run, a question waiting, a + * run not started yet), as the same conflict the tool gives on one computer. + */ +function remoteRunConflict(error: unknown, runId: string): McpToolError | undefined { + const code = (error as { code?: unknown } | null)?.code + const details = ((error as { details?: unknown } | null)?.details ?? {}) as { callerMode?: unknown; targetMode?: unknown } + if (code === 'ceiling_exceeded') + return new McpToolError( + 'mousse_conflict', + `Run ${runId} is running under a looser permission mode (${String(details.targetMode ?? 'unknown')}) than yours (${String(details.callerMode ?? 'unknown')}); a running turn cannot be narrowed, so your steer would run with more authority than you have. Send a message instead: it runs under your mode.`, + { conflict: 'ceiling_exceeded', callerMode: details.callerMode, targetMode: details.targetMode } + ) + if (code === 'steer_target_not_ready') + return new McpToolError('mousse_conflict', `Run ${runId} has not started its turn yet, so there is nothing to steer. Steer it once it is running, or send a message instead.`, { conflict: code, expectedRunId: runId }) + return sendConflict(error) +} + +/** What `thread_wait` returns for a thread on another computer, in the words it uses on one computer. */ +function remoteWaitView(threadId: string, computer: string, result: RemoteWaitResult): Record { + const base = { threadId, computer, ...(result.run ? { run: result.run } : {}), ...(result.continuedFrom ? { continuedFrom: result.continuedFrom } : {}) } + switch (result.status) { + case 'finished': + return { + status: 'finished', + ...base, + ...(result.resultText !== undefined ? { resultText: result.resultText } : {}), + ...(result.resultChars !== undefined ? { resultTruncated: true, resultChars: result.resultChars, hint: RESULT_READ_ON } : {}), + ...(result.resultText === undefined && result.via === 'poll' ? { hint: `${computer} runs an older Mousse, which does not hand over the run's final text with the wait: read it with thread_read view "messages".` } : {}) + } + case 'needs_input': + return { + status: 'needs_input', + ...base, + needsInput: true, + requests: result.needsInput?.requests ?? 1, + hint: `The run waits on a person on ${computer}: a question, an approval or an MCP request. No agent answers it from here; tell the user it waits for them there.` + } + case 'idle': + return { status: 'idle', ...base } + default: { + const pause = result.run?.status === 'paused' ? result.run.pause : undefined + if (pause) { + const retryAfterMs = Math.min(THREAD_WAIT_MAX_MS, Math.max(1_000, Date.parse(pause.until) - Date.now())) + return { status: 'paused', ...base, pause, retryAfterMs, hint: `A usage limit paused the run; it resumes by itself. Ask again after ${Math.ceil(retryAfterMs / 1000)} s (not sooner), or end it with thread_interrupt.` } + } + return { + status: 'timeout', + ...base, + ...(result.pending ? { pending: result.pending } : {}), + hint: result.pending === 'queued_message' ? 'A message waits in its queue there and starts a run soon; call thread_wait again.' : 'The run is still going; call thread_wait again.' + } + } + } +} + +/** What the descriptions of the five tools say about a thread on another computer. */ +const REMOTE_REACH = 'A thread your thread (or a thread of its lineage) launched on another computer is reached by its qualified id (:, from thread_create with computer); any other thread there is refused. A refusal there names its reason in code: computer_offline, computer_not_shared, computer_outdated, computer_not_allowed, not_launched_here or remote_thread_gone.' + /** How a `thread_wait` ended before its result was read. */ type WaitEnd = { kind: 'finished' } | { kind: 'timeout' } | { kind: 'caller_ended' } | { kind: 'refused'; text: string } @@ -758,6 +863,126 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B : `Started on ${launched.computer}. Its questions and approvals wait on that computer.` }) } + /** + * A thread on another computer (a qualified id), as the caller may reach it, or the refusal that says why not. A + * personal bot reaches only threads here. + */ + const remoteTarget = (threadId: string, ctx: ToolCallContext, tool: string): RemoteTarget => { + if (ctx.turn.bot) throw new McpToolError('mousse_scope_denied', `A personal bot's ${tool} reaches only threads on this computer.`) + if (!host.remoteThreads) + throw new RemoteThreadRefusal('remote_unavailable', 'Threads on other computers need Mousse to be connected to your other computers (Settings → Devices).') + const reach = host.remoteThreads.reach(ctx.caller.threadId, threadId) + if (!reach.ok) throw new RemoteThreadRefusal(reach.code, reach.message, reach.computer) + return reach + } + /** Runs a tool's branch for a thread on another computer: a refusal comes back with its code, never thrown on. */ + const onComputer = async (work: () => Promise): Promise => { + try { + return await work() + } catch (error) { + const refused = remoteRefusal(error) + if (refused) return refused + throw error + } + } + /** `thread_read` of a thread this thread launched on another computer: the same pages, read there. */ + const readOnComputer = (threadId: string, args: Record, ctx: ToolCallContext): Promise => onComputer(async () => { + const view = args.view === undefined ? 'events' : args.view + if (view !== 'events' && view !== 'messages') throw new Error("view must be 'events' or 'messages'") + const target = remoteTarget(threadId, ctx, 'thread_read') + const remote = host.remoteThreads! + const envelope = { threadId: target.threadId, link: threadLink(target.threadId), computer: target.computer, view, scope: 'launched' } + if (view === 'messages') { + const afterIndex = boundedInt(args.afterIndex, 'afterIndex', 0, Number.MAX_SAFE_INTEGER, 0) + const limit = boundedInt(args.limit, 'limit', 1, THREAD_MESSAGES_MAX_LIMIT, THREAD_MESSAGES_DEFAULT_LIMIT) + const textOffset = boundedInt(args.textOffset, 'textOffset', 0, Number.MAX_SAFE_INTEGER, 0) + const page = await remote.messages(target, { afterIndex, limit, textOffset, textMax: THREAD_MESSAGE_MAX_CHARS }) + return json(messagesPage({ ...envelope, total: page.total }, page.messages, afterIndex)) + } + const afterSeq = boundedInt(args.afterSeq, 'afterSeq', 0, Number.MAX_SAFE_INTEGER, 0) + const limit = boundedInt(args.limit, 'limit', 1, THREAD_READ_MAX_LIMIT, THREAD_READ_DEFAULT_LIMIT) + const page = await remote.events(target, { afterSeq, limit }) + return json(eventsPage({ ...envelope, maxSeq: page.maxSeq }, page.events, page.events, afterSeq)) + }) + /** `thread_wait` on a thread this thread launched on another computer: waited for there, 40 s at a time. */ + const waitOnComputer = (threadId: string, args: Record, ctx: ToolCallContext): Promise => onComputer(async () => { + if (args.runId !== undefined && (typeof args.runId !== 'string' || !args.runId)) throw new Error('runId must be a non-empty string') + const timeoutMs = boundedInt(args.timeoutMs, 'timeoutMs', 1, THREAD_WAIT_MAX_MS, THREAD_WAIT_DEFAULT_MS) + const target = remoteTarget(threadId, ctx, 'thread_wait') + if (ctx.signal.aborted) return json({ status: 'caller_ended', threadId: target.threadId }) + const result = await host.remoteThreads!.wait(target, { ...(typeof args.runId === 'string' ? { runId: args.runId } : {}), timeoutMs, signal: ctx.signal }) + if (result.callerEnded) return json({ status: 'caller_ended', threadId: target.threadId }) + return json(remoteWaitView(target.threadId, target.computer, result)) + }) + /** + * `thread_send` to a thread this thread launched on another computer: a message marked as this agent's, keyed by the + * request id (a retry reaches the first send there, never a second run). Unconfirmed is `uncertain`, never sent or failed. + */ + const sendOnComputer = (threadId: string, args: Record, ctx: ToolCallContext): Promise => onComputer(async () => { + 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.') + 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.`) + const target = remoteTarget(threadId, ctx, 'thread_send') + const actor = actorOf(ctx) + const requestKey = `thread_send:${ctx.caller.threadId}:${toolRequestId(args, ctx)}` + reserveSend(actor.runId) + let sent: Awaited['send']>> + try { + sent = await host.remoteThreads!.send(target, { content: args.content, mode }, { clientRequestId: requestKey, actor }) + } catch (error) { + releaseSend(actor.runId) + throw sendConflict(error) ?? error + } + // Unconfirmed: it may have been sent, so it keeps its place under the per-run count. + 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) }) + }) + /** `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 () => { + const runId = requiredId(args, 'runId') + if (typeof args.text !== 'string' || !args.text.trim()) throw new Error('thread_steer requires text') + if (args.text.length > ROUTED_AGENT_BODY_MAX) + throw new Error(`A steer to another computer is at most ${ROUTED_AGENT_BODY_MAX.toLocaleString('en-US')} characters. Nothing was sent.`) + const target = remoteTarget(threadId, ctx, 'thread_steer') + const actor = actorOf(ctx) + let result: Awaited['steer']>> + try { + result = await host.remoteThreads!.steer(target, runId, args.text, { clientRequestId: `thread_steer:${ctx.caller.threadId}:${toolRequestId(args, ctx)}`, actor }) + } catch (error) { + throw remoteRunConflict(error, runId) ?? error + } + if (result.status === 'uncertain') return json({ ok: false, status: 'uncertain', threadId: target.threadId, computer: target.computer, message: result.message }) + if (result.status === 'ignored') { + if (result.reason === 'run_not_found') + throw new McpToolError('mousse_conflict', `Run ${runId} is not a run of this thread.`, { conflict: 'run_not_found', expectedRunId: runId }) + throw new McpToolError('mousse_conflict', `Run ${runId} is not the thread's active run on ${target.computer}, or it is paused; nothing was sent. Read the thread again.`, { conflict: 'run_not_active', expectedRunId: runId, reason: result.reason }) + } + return json({ threadId: target.threadId, computer: target.computer, runId: result.runId }) + }) + /** + * `thread_interrupt` of a run of a thread this thread launched on another computer. That computer stops it only when an + * agent of this computer started it, and leaves a thread a person took over. + */ + const interruptOnComputer = (threadId: string, args: Record, ctx: ToolCallContext): Promise => onComputer(async () => { + const runId = requiredId(args, 'runId') + const target = remoteTarget(threadId, ctx, 'thread_interrupt') + const result = await host.remoteThreads!.interrupt(target, runId, { clientRequestId: `thread_interrupt:${ctx.caller.threadId}:${toolRequestId(args, ctx)}`, actor: actorOf(ctx) }) + if (result.status === 'uncertain') return json({ ok: false, status: 'uncertain', threadId: target.threadId, computer: target.computer, message: result.message }) + if (result.status === 'left') { + if (result.left === 'not_started_by_this_computer') + throw new McpToolError('mousse_scope_denied', `Run ${runId} on ${target.computer} was not started by an agent of this computer (a person there has taken the thread over), so it was left running. Only a person there stops it.`, { conflict: 'not_started_by_this_computer' }) + throw new McpToolError('mousse_conflict', `Run ${runId} is not the thread's active (or paused) run on ${target.computer}; nothing was stopped. Read the thread again.`, { conflict: 'run_not_active', expectedRunId: runId }) + } + return json({ threadId: target.threadId, computer: target.computer, runId: result.runId ?? runId, stopped: true }) + }) /** * `thread_read` for a personal bot: `summary` (default), one line on the thread and its last reply; or `messages`, the * transcript, the newest ones unless it pages from `afterIndex`, each message and the page capped. Never run events. @@ -826,7 +1051,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B return [ { name: 'thread_read', - description: `Read a thread. view "events" (default): run events (runs, attempts, delegations, tool calls) of any thread. Page with afterSeq. view "messages": the transcript of any thread; page with afterIndex. Each message holds at most ${THREAD_MESSAGE_MAX_CHARS} characters: one marked truncated continues when you pass its index as afterIndex and its nextTextOffset as textOffset. A response holds at most ${THREAD_READ_MAX_BYTES / 1024} KB: a page that reaches it has fewer items and capped: true, and nextAfterSeq or nextAfterIndex continues it. A run's final text is cut to ${THREAD_RESULT_MAX_CHARS} characters; read it in full in the messages. A personal bot reads its owner\'s threads with view "summary" (default: one line on the thread and its last reply) or "messages" (the newest ones, or from afterIndex, capped).`, + description: `Read a thread. view "events" (default): run events (runs, attempts, delegations, tool calls) of any thread. Page with afterSeq. view "messages": the transcript of any thread; page with afterIndex. Each message holds at most ${THREAD_MESSAGE_MAX_CHARS} characters: one marked truncated continues when you pass its index as afterIndex and its nextTextOffset as textOffset. A response holds at most ${THREAD_READ_MAX_BYTES / 1024} KB: a page that reaches it has fewer items and capped: true, and nextAfterSeq or nextAfterIndex continues it. A run's final text is cut to ${THREAD_RESULT_MAX_CHARS} characters; read it in full in the messages. A personal bot reads its owner\'s threads with view "summary" (default: one line on the thread and its last reply) or "messages" (the newest ones, or from afterIndex, capped). ${REMOTE_REACH} It is read there, with the same pages and limits, and the ids in it are named the way this computer names them.`, inputSchema: { type: 'object', properties: { @@ -841,9 +1066,11 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B access: 'readsOthers', class: 'read', offered: () => false, + target: localTarget, handler: (args, ctx) => { const threadId = args.threadId === undefined ? ctx.caller.threadId : args.threadId if (typeof threadId !== 'string' || !threadId) throw new Error('threadId must be a non-empty string') + if (isQualifiedId(threadId)) return readOnComputer(threadId, args, ctx) const scope = ctx.scope ?? 'own' // A personal bot ("use your threads"): a one-line summary by default, the transcript only when it asks, capped. if (ctx.turn.bot) return botRead(threadId, args, ctx.caller.threadId) @@ -861,60 +1088,17 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B const limit = boundedInt(args.limit, 'limit', 1, THREAD_MESSAGES_MAX_LIMIT, THREAD_MESSAGES_DEFAULT_LIMIT) const textOffset = boundedInt(args.textOffset, 'textOffset', 0, Number.MAX_SAFE_INTEGER, 0) const all = host.threadMessages(threadId) - const firstText = all[afterIndex] && typeof all[afterIndex].content === 'string' ? all[afterIndex].content : '' - if (textOffset > 0 && afterIndex < all.length && textOffset >= firstText.length) - throw new Error(`textOffset ${textOffset} is past the end of message ${afterIndex}, which has ${firstText.length} characters`) + const problem = textOffsetProblem(all, afterIndex, textOffset) + if (problem) throw new Error(problem) // Built one at a time, so a page that reaches the byte cap stops reading the transcript there. - function* rows() { - for (let index = afterIndex; index < Math.min(all.length, afterIndex + limit); index += 1) { - const message = all[index] - const text = typeof message.content === 'string' ? message.content : '' - const from = index === afterIndex ? textOffset : 0 - const end = cutEnd(text, from + THREAD_MESSAGE_MAX_CHARS) - yield { - index, - id: message.id, - role: message.role, - timestamp: message.timestamp, - text: text.slice(from, end), - ...(from > 0 ? { textOffset: from } : {}), - ...(end < text.length ? { truncated: true, totalChars: text.length, nextTextOffset: end } : {}) - } - } - } - const envelope = { threadId, link: threadLink(threadId), view, scope, total: all.length } - const { taken: messages, capped } = fitPage(rows(), envelope) - const truncated = messages.some((message) => 'truncated' in message) - return json({ - ...envelope, - messages, - nextAfterIndex: afterIndex + messages.length, - ...(capped ? { capped: true } : {}), - ...(capped || truncated - ? { - hint: [ - capped ? `This page stopped at ${THREAD_READ_MAX_BYTES / 1024} KB; continue with afterIndex ${afterIndex + messages.length}.` : '', - truncated ? 'A message marked truncated continues: pass its index as afterIndex and its nextTextOffset as textOffset.' : '' - ].filter(Boolean).join(' ') - } - : {}) - }) + const rows = messageRows(all, { afterIndex, limit, textOffset, maxChars: THREAD_MESSAGE_MAX_CHARS }) + return json(messagesPage({ threadId, link: threadLink(threadId), view, scope, total: all.length }, rows, afterIndex)) } const afterSeq = boundedInt(args.afterSeq, 'afterSeq', 0, Number.MAX_SAFE_INTEGER, 0) const limit = boundedInt(args.limit, 'limit', 1, THREAD_READ_MAX_LIMIT, THREAD_READ_DEFAULT_LIMIT) const page = engine.listEvents(threadId, { afterSeq, limit }) const visible = full ? page : lineageView(page, ctx.caller.threadId, scope) - const envelope = { threadId, link: threadLink(threadId), view, scope, maxSeq: engine.maxSeq(threadId) } - const { taken: events, capped } = fitPage(visible.map(boundedEvent), envelope) - // `nextAfterSeq` pages on even when a lineage view filtered events out of this page; a page cut at the byte cap - // continues after the last event it holds. - const nextAfterSeq = capped ? events.at(-1)!.seq : page.at(-1)?.seq ?? afterSeq - return json({ - ...envelope, - events, - nextAfterSeq, - ...(capped ? { capped: true, hint: `This page stopped at ${THREAD_READ_MAX_BYTES / 1024} KB; continue with afterSeq ${nextAfterSeq}.` } : {}) - }) + return json(eventsPage({ threadId, link: threadLink(threadId), view, scope, maxSeq: engine.maxSeq(threadId) }, page, visible, afterSeq)) } }, { @@ -1072,7 +1256,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.`, + 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.`, inputSchema: { type: 'object', properties: { @@ -1087,8 +1271,10 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B access: 'managesOthers', class: 'mutation', offered: () => false, + target: localTarget, handler: async (args, ctx) => { const threadId = requiredId(args, 'threadId') + if (isQualifiedId(threadId)) return sendOnComputer(threadId, args, ctx) 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' @@ -1141,7 +1327,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_wait', - description: `Wait for a run of another thread to finish, for at most timeoutMs (default ${THREAD_WAIT_DEFAULT_MS}, up to ${THREAD_WAIT_MAX_MS}). Pass the runId thread_send returned; without one, the run that is active now. Returns status finished (with the run's outcome, and its final text where you may read it, cut to ${THREAD_RESULT_MAX_CHARS} characters with resultTruncated when longer), timeout (the run is still going: call again; the wait never interrupts it), paused (a usage limit paused the run and it was still paused when the wait ran out: it resumes by itself, and the result says when to ask again; a wait that is running when it resumes follows it into the run that continues it), idle (no run to wait for) or caller_ended (your own run ended). Use it only when this turn cannot continue without the answer; to hear about the result later, send with notify instead and end your turn.`, + description: `Wait for a run of another thread to finish, for at most timeoutMs (default ${THREAD_WAIT_DEFAULT_MS}, up to ${THREAD_WAIT_MAX_MS}). Pass the runId thread_send returned; without one, the run that is active now. Returns status finished (with the run's outcome, and its final text where you may read it, cut to ${THREAD_RESULT_MAX_CHARS} characters with resultTruncated when longer), timeout (the run is still going: call again; the wait never interrupts it), paused (a usage limit paused the run and it was still paused when the wait ran out: it resumes by itself, and the result says when to ask again; a wait that is running when it resumes follows it into the run that continues it), idle (no run to wait for) or caller_ended (your own run ended). Use it only when this turn cannot continue without the answer; to hear about the result later, send with notify instead and end your turn. ${REMOTE_REACH} There the wait runs on that computer; status needs_input (needsInput: true) says the run waits on a person there (a question, an approval or an MCP request), which no agent answers from here.`, inputSchema: { type: 'object', properties: { @@ -1154,8 +1340,10 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B access: 'readsOthers', class: 'read', offered: () => false, + target: localTarget, handler: async (args, ctx) => { const threadId = requiredId(args, 'threadId') + if (isQualifiedId(threadId)) return waitOnComputer(threadId, args, ctx) if (args.runId !== undefined && (typeof args.runId !== 'string' || !args.runId)) throw new Error('runId must be a non-empty string') const timeoutMs = boundedInt(args.timeoutMs, 'timeoutMs', 1, THREAD_WAIT_MAX_MS, THREAD_WAIT_DEFAULT_MS) if (threadId === ctx.caller.threadId) throw new Error('thread_wait is for other threads: your own run ends only when your turn does.') @@ -1277,7 +1465,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_interrupt', - description: 'Stop a run of another thread: the run you name, which must still be the thread\'s active (or paused) run, and the subagents below it, as a Stop in the app does. Queued messages a person sent stay. Name the run you read; if it has ended or another run started, nothing is stopped and you are told which run is active. A paused run is ended too.', + description: 'Stop a run of another thread: the run you name, which must still be the thread\'s active (or paused) run, and the subagents below it, as a Stop in the app does. Queued messages a person sent stay. Name the run you read; if it has ended or another run started, nothing is stopped and you are told which run is active. A paused run is ended too. ' + REMOTE_REACH + ' There it stops only a run an agent of this computer started: a thread a person there took over is left running.', inputSchema: { type: 'object', properties: { @@ -1291,8 +1479,10 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B class: 'mutation', launchedOk: true, offered: () => false, + target: localTarget, handler: async (args, ctx) => { const threadId = requiredId(args, 'threadId') + if (isQualifiedId(threadId)) return interruptOnComputer(threadId, args, ctx) const runId = requiredId(args, 'runId') if (!host.stopRun) return notAvailable('thread_interrupt') if (threadId === ctx.caller.threadId) throw new Error('thread_interrupt is for other threads; stop your own work by ending your turn.') @@ -1400,7 +1590,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_steer', - description: 'Add guidance to the turn another thread is running now. Name the run you read; if it is not the thread\'s active run, or is paused, nothing is sent and you are told why. The thread\'s model receives the text labelled as a message from an agent, not from the user. Refused when the run is running under a looser permission mode than yours (a running turn cannot be narrowed): send a message instead.', + description: 'Add guidance to the turn another thread is running now. Name the run you read; if it is not the thread\'s active run, or is paused, nothing is sent and you are told why. The thread\'s model receives the text labelled as a message from an agent, not from the user. Refused when the run is running under a looser permission mode than yours (a running turn cannot be narrowed): send a message instead. ' + REMOTE_REACH, inputSchema: { type: 'object', properties: { @@ -1414,8 +1604,10 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B access: 'managesOthers', class: 'mutation', offered: () => false, + target: localTarget, handler: async (args, ctx) => { const threadId = requiredId(args, 'threadId') + if (isQualifiedId(threadId)) return steerOnComputer(threadId, args, ctx) const runId = requiredId(args, 'runId') if (typeof args.text !== 'string' || !args.text.trim()) throw new Error('thread_steer requires text') if (!host.steerRun) return notAvailable('thread_steer') @@ -1431,7 +1623,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'approval_respond', - description: `Answer a pending approval of another thread (a command, a file change or a tool its agent asked to run), as the user would. Needs the profile's switch "Agents may answer approvals on other threads", which is off by default; a refusal names what is missing. You can approve only what your own permission mode would allow without asking, never your own thread's request (nor one of a thread in your lineage other than your direct subagents', which answer_subagent covers), and never "always for this thread": approve once or reject. Read the request first with thread_list (it lists each thread's pending requests with their option ids), then answer with the question id and the option id. The thread's transcript shows "Approved by an agent in thread ..." and the user sees who answered. A request the provider asks for itself (its own safety check, a path outside the allowed folders, one of the user's own ask rules) and one on a turn the user started are the user's alone; they are refused. A plain question for the user (ask_user) cannot be answered here. If a person or another agent answered first you get already_answered with who decided what, and nothing changes.`, + description: `Answer a pending approval of another thread (a command, a file change or a tool its agent asked to run), as the user would. Needs the profile's switch "Agents may answer approvals on other threads", which is off by default; a refusal names what is missing. You can approve only what your own permission mode would allow without asking, never your own thread's request (nor one of a thread in your lineage other than your direct subagents', which answer_subagent covers), and never "always for this thread": approve once or reject. Read the request first with thread_list (it lists each thread's pending requests with their option ids), then answer with the question id and the option id. The thread's transcript shows "Approved by an agent in thread ..." and the user sees who answered. A request the provider asks for itself (its own safety check, a path outside the allowed folders, one of the user's own ask rules) and one on a turn the user started are the user's alone; they are refused. A plain question for the user (ask_user) cannot be answered here. If a person or another agent answered first you get already_answered with who decided what, and nothing changes. An approval of a thread on another computer waits for a person there and is refused.`, inputSchema: { type: 'object', properties: { @@ -1449,8 +1641,12 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B access: 'managesOthers', class: 'mutation', offered: () => false, + target: localTarget, handler: (args, ctx) => { const threadId = requiredId(args, 'threadId') + // A question or approval waits on the computer that runs its thread, for a person there. + if (isQualifiedId(threadId)) + throw new McpToolError('mousse_scope_denied', 'No agent answers an approval on another computer: it waits for a person on that computer. Tell the user it waits for them there.') const requestId = requiredId(args, 'requestId') const answers = approvalAnswers(args.answers) if (!host.approvalRequest || !host.answerApproval) return notAvailable('approval_respond') diff --git a/src/mms/run/mcp/instructions.ts b/src/mms/run/mcp/instructions.ts index e3a468e1f3..2af8bc6e7b 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_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_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/runWait.ts b/src/mms/run/runWait.ts new file mode 100644 index 0000000000..24b28addac --- /dev/null +++ b/src/mms/run/runWait.ts @@ -0,0 +1,150 @@ +import { ROUTED_RUN_WAIT_MAX_MS } from '../../shared/bridge/routed' +import { readRunResultText } from './delegation/hold' +import type { RunEngine } from './RunEngine' +import { TERMINAL_RUN_STATUSES, type RunRecord, type RunStatus } from './types' + +/** + * `runs.wait` on the computer that runs the thread (issue #1160): `thread_wait` of an agent on another computer. It waits + * at most `ROUTED_RUN_WAIT_MAX_MS` for a run of the thread to end, or to wait on a person (a question, an approval or an + * MCP request: nothing an agent elsewhere may answer), and answers from this computer's run events. + * + * - With `runId`, that run; a usage-limit pause that hands it on to the run continuing it is followed, as on one computer. + * - Without, the run that is active or paused now, else the next one waiting to start. A thread with no run but a message + * in its queue is never answered `idle`: the wait goes on until a run starts (or it times out). + */ + +/** A run as a wait reports it: its id and status, and what a reader of another computer may act on. */ +export interface RunWaitRun { + runId: string + status: RunStatus + error?: string + interruptedBy?: unknown + pause?: { reason?: unknown; until: string; estimated?: unknown } +} + +export interface RunWaitReply { + /** + * finished: the run ended. needs_input: it waits on a person there. timeout: still going (or, with `pending`, about to + * start). idle: nothing to wait for. + */ + status: 'finished' | 'needs_input' | 'timeout' | 'idle' + run?: RunWaitRun + /** The run the wait was asked about, when a usage-limit pause handed it on to `run`. */ + continuedFrom?: string + /** What waits on a person there: how many requests. */ + needsInput?: { requests: number } + /** Why a thread with no running work is not idle: a run is preparing, or a message waits in its queue. */ + pending?: 'preparing' | 'queued_message' + /** A finished run's final text, cut to `resultMaxChars`; `resultChars` is its full length when it was cut. */ + resultText?: string + resultChars?: number +} + +export interface RunWaitDeps { + engine: Pick + /** Requests in the thread that wait on a person now. */ + waitingOnPerson(threadId: string): number + /** Messages waiting in the thread's queue. */ + queued(threadId: string): number + /** How often a wait looks for a request that waits on a person (they are not run events). */ + pollMs?: number +} + +const ERROR_MAX_CHARS = 1_000 + +function runView(run: RunRecord): RunWaitRun { + const outcome = run.outcome + const pause = outcome?.pause + return { + runId: run.runId, + status: run.status, + ...(outcome?.error ? { error: outcome.error.slice(0, ERROR_MAX_CHARS) } : {}), + ...(outcome?.interruptedBy ? { interruptedBy: outcome.interruptedBy } : {}), + ...(run.status === 'paused' && pause ? { pause: { reason: pause.reason, until: pause.until, estimated: pause.estimated } } : {}) + } +} + +/** One wait. Never throws for a run that is not there: the routed row already checked `runId` belongs to the thread. */ +export async function waitOnRun( + deps: RunWaitDeps, + request: { threadId: string; runId?: string; timeoutMs: number; resultMaxChars: number; signal?: AbortSignal } +): Promise { + const { engine } = deps + const { threadId } = request + const timeoutMs = Math.max(0, Math.min(request.timeoutMs, ROUTED_RUN_WAIT_MAX_MS)) + let target = request.runId + let continuedFrom: string | undefined + + /** The run that answers for `run`: itself, or the run a pause handed it on to. */ + const followed = (run: RunRecord): RunRecord => { + let current = run + for (let hops = 0; hops < 20 && TERMINAL_RUN_STATUSES.has(current.status); hops++) { + const endedBy = current.outcome?.pause?.endedBy + if (endedBy !== 'resume' && endedBy !== 'resume_now') break + const next = engine.listRuns(threadId, { limit: 20 }).find((entry) => entry.outcome?.continuationOf === current.runId) + if (!next) break + continuedFrom ??= current.runId + current = next + } + return current + } + + const finished = (run: RunRecord): RunWaitReply => { + const text = readRunResultText(engine.store, threadId, run.runId) + const cut = text !== undefined && text.length > request.resultMaxChars + return { + status: 'finished', + run: runView(run), + ...(continuedFrom ? { continuedFrom } : {}), + ...(text !== undefined ? { resultText: cut ? `${text.slice(0, request.resultMaxChars)}…` : text } : {}), + ...(cut ? { resultChars: text!.length } : {}) + } + } + + /** Where the thread stands now; undefined while the wait goes on. */ + const look = (final: boolean): RunWaitReply | undefined => { + let run: RunRecord | null = null + if (target) run = engine.getRun(target) + else { + run = engine.getActiveRun(threadId) ?? engine.store.getPausedRun(threadId) ?? engine.store.listQueuedRuns(threadId)[0] ?? null + if (run && run.status !== 'queued') target = run.runId + } + if (run) run = followed(run) + if (run && target) target = run.runId + if (run && TERMINAL_RUN_STATUSES.has(run.status)) return finished(run) + const requests = deps.waitingOnPerson(threadId) + if (run && requests > 0) return { status: 'needs_input', run: runView(run), needsInput: { requests }, ...(continuedFrom ? { continuedFrom } : {}) } + if (!run) { + const queued = deps.queued(threadId) + if (queued === 0) return { status: 'idle', ...(requests > 0 ? { needsInput: { requests } } : {}) } + return final ? { status: 'timeout', pending: 'queued_message' } : undefined + } + if (!final) return undefined + return { status: 'timeout', run: runView(run), ...(run.status === 'queued' ? { pending: 'preparing' as const } : {}), ...(continuedFrom ? { continuedFrom } : {}) } + } + + const now = look(timeoutMs === 0) + if (now) return now + return new Promise((resolve) => { + let done = false + const finish = (final: boolean): void => { + if (done) return + const reply = look(final) + if (!reply) return + done = true + clearTimeout(timer) + clearInterval(poll) + unsubscribe() + request.signal?.removeEventListener('abort', onAbort) + resolve(reply) + } + // A run's status is an event; a question or approval is not, so it is looked for on a short interval. + const unsubscribe = engine.store.onEvent((event) => { + if (event.threadId === threadId && event.type === 'run.status') finish(false) + }) + const poll = setInterval(() => finish(false), deps.pollMs ?? 500) + const timer = setTimeout(() => finish(true), timeoutMs) + const onAbort = (): void => finish(true) + request.signal?.addEventListener('abort', onAbort, { once: true }) + }) +} diff --git a/src/shared/bridge/routed.ts b/src/shared/bridge/routed.ts index 9e4588b186..61dc49e198 100644 --- a/src/shared/bridge/routed.ts +++ b/src/shared/bridge/routed.ts @@ -173,6 +173,19 @@ export interface RoutedAgentMark { mode: string } +/** + * `runs.wait`: the longest one call waits on the owner, and the deadline the caller gives the call. The deadline is above + * the wait (the owner answers at its end) and below the minute an MCP client waits on a tool call. + */ +export const ROUTED_RUN_WAIT_MAX_MS = 40_000 +export const ROUTED_RUN_WAIT_DEADLINE_MS = 50_000 + +/** + * What an agent's read of a thread on another computer asks for (`thread.messages` with `index`): the most characters of + * one message, and the bytes of rows the owner sends for one page. The caller's tool cuts its own response to the same. + */ +export const ROUTED_AGENT_READ = Object.freeze({ textMax: 16_384, pageBytes: 64 * 1024 }) + /** The longest sender title an envelope carries. */ export const ROUTED_AGENT_TITLE_MAX = 80 /** The longest message an agent on another computer may send (an agent on the same computer may send 100,000). */ @@ -208,7 +221,13 @@ export const ROUTED_METHODS: Readonly> = Object.freeze since: { transcript: 2 } }), // Older messages of a long thread, a page at a time, newest first from `before` (a message id). - 'thread.messages': read('thread', ['threadId', 'before', 'after', 'limit'], { version: 2, since: { after: 2 } }), + // Version 3: `index`, `textOffset` and `textMax`, the page an agent's `thread_read` reads on another computer: from + // the message at `index`, each message's text cut to `textMax` characters (the first one from `textOffset`), so only + // what the tool returns crosses (`ROUTED_AGENT_READ`). + 'thread.messages': read('thread', ['threadId', 'before', 'after', 'limit', 'index', 'textOffset', 'textMax'], { + version: 3, + since: { after: 2, index: 3, textOffset: 3, textMax: 3 } + }), 'thread.changesSince': read('thread', ['threadId', 'seq', 'epoch']), // The image of one message or queued message, by its place in it (the stream carries only the newest images' data). 'thread.messageImage': read('thread', ['threadId', 'messageId', 'queueItemId', 'index'], { @@ -224,6 +243,11 @@ export const ROUTED_METHODS: Readonly> = Object.freeze owned: { runId: 'run' } }), 'runs.events': read('thread', ['threadId', 'afterSeq', 'limit']), + // Waits up to `timeoutMs` (at most `ROUTED_RUN_WAIT_MAX_MS`) for a run of the thread to end or to wait on a person, + // answered from the owner's run events: `thread_wait` on a thread of another computer (issue #1160). Without `runId`, + // the run that is active or paused now; a thread with a run that is preparing or a message waiting in its queue is + // never answered idle. + 'runs.wait': read('thread', ['threadId', 'runId', 'timeoutMs'], { owned: { runId: 'run' } }), 'activity.get': read('thread', ['threadId']), 'subagents.list': read('thread', ['threadId']), 'agents.list': read('thread', ['threadId']), diff --git a/tests/contractVersions.test.ts b/tests/contractVersions.test.ts index bca47fabea..21c4c6d351 100644 --- a/tests/contractVersions.test.ts +++ b/tests/contractVersions.test.ts @@ -10,7 +10,7 @@ describe('contract versions', () => { daemonOwnerLease: 1, netProtocol: '1.0', netEnvelope: 1, - runDatabase: 21, + runDatabase: 22, botsDb: 10, mousseConf: 1, installation: 2, diff --git a/tests/net/bridge/routed/routedVersions.json b/tests/net/bridge/routed/routedVersions.json index 4532642e48..30f0ab7c2f 100644 --- a/tests/net/bridge/routed/routedVersions.json +++ b/tests/net/bridge/routed/routedVersions.json @@ -619,6 +619,11 @@ "digest": "09a87e17128c1172", "security": "56bf730c16aa9cd1" }, + "runs.wait": { + "version": 1, + "digest": "d5478cd8d044d8c0", + "security": "ade27276cc757950" + }, "scheduled.create": { "version": 1, "digest": "2e60c015cf6b49d7", @@ -705,8 +710,8 @@ "security": "04f7c680ffd36337" }, "thread.messages": { - "version": 2, - "digest": "ca37845da10897d3", + "version": 3, + "digest": "e3300eb7696bc9fd", "security": "04f7c680ffd36337" }, "thread.snapshot": { diff --git a/tests/net/bridge/routed/threadToolsRemote.test.ts b/tests/net/bridge/routed/threadToolsRemote.test.ts new file mode 100644 index 0000000000..608fd1c137 --- /dev/null +++ b/tests/net/bridge/routed/threadToolsRemote.test.ts @@ -0,0 +1,414 @@ +/** + * Issue #1160: `thread_read`, `thread_wait`, `thread_send`, `thread_steer` and `thread_interrupt` on a thread this + * computer's agent launched on another computer, and a person's Stop of the launcher reaching it, over two real daemons + * linked by Bridge. The caller's agent calls each tool through the app-tool registry over the caller orchestrator's own + * host, so a call goes through the handler's branch, the reach check, the routed calls (marked as the agent's where they + * change something) and the owner's handling. The owner's turns are stood in for (no provider runs), so a run's status + * there is what the test sets on that computer's run engine. + * + * Inputs listed before the cases: + * - reading: events and messages (with textOffset), ids qualified; a thread the caller did not launch; + * - waiting: the run ends there, it waits on a person there, an older computer without `runs.wait` (polling), nothing to + * wait for; + * - messaging: a send as the agent's, its replay with the same request id, a steer into a looser run; + * - stopping: an agent-started run, a run a person there started, a person's Stop of the launcher with the link up and + * with the link down (kept, delivered after a restart), the launcher deleted; + * - the working count of thread_create's cap: a run going there, a thread idle there, a computer that cannot be asked; + * - reachability: offline (tried twice, named), a qualified id of a thread nobody here launched, approval_respond. + */ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, realpathSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { qualifyId } from '../../../../src/shared/threadRef' +import { DomainRpcError } from '../../../../src/mms/protocol/domainRegistry' +import type { RemoteComputersPort } from '../../../../src/mms/protocol/remoteComputersPort' +import type { SqliteNodePolicy } from '../../../../src/mms/net/store/nodePolicy' +import { localized, RemoteLaunchedThreads } from '../../../../src/mms/orchestrator/RemoteLaunchedThreads' +import type { AppToolHost } from '../../../../src/mms/run/mcp/appTools' +import { appToolRegistry, appTurn } from '../../../run/appToolsFixture' +import { cleanups, cleanupAll, linked } from './routerFixture' + +type Loose = Record +let t: Awaited> +let policy: SqliteNodePolicy +let repo: { path: string; remote: string } +let seq = 0 +/** What the owner's turns were handed. */ +let turns: Array<{ input: Loose; permissionMode?: string; agent?: Loose }> = [] + +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-tools-'))) + cleanups.push(() => rmSync(path, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + return path +} + +const portOf = (): RemoteComputersPort => (t.caller.orchestrator as unknown as { remoteComputers: RemoteComputersPort }).remoteComputers +const remoteOf = (): RemoteLaunchedThreads => (t.caller.orchestrator as unknown as { remoteThreads: RemoteLaunchedThreads }).remoteThreads +const nameOf = (): string => portOf().computers()!.find((entry) => entry.node === t.node)!.name + +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, remote } + 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) +}, 120_000) +afterAll(cleanupAll) +afterEach(() => { + vi.restoreAllMocks() + turns = [] + policy.set(t.callerNode, { maxPermissionMode: 'accept_edits', agentReach: 'launched' }) +}) + +/** The owner's turns are stood in for: what each is handed is recorded, and its run's status is the test's to set. */ +function standInForTurns(): void { + const open = (request: (typeof turns)[number]): Promise => { + turns.push(request) + return Promise.resolve({ message: '', actions: [] }) + } + vi.spyOn(t.owner.orchestrator as unknown as Loose, 'startTurn').mockImplementation(((_session: unknown, request: Loose) => + open({ input: request.input, permissionMode: request.permissionMode, agent: request.agent })) as never) + vi.spyOn(t.owner.orchestrator as unknown as Loose, 'runTurnOnSession').mockImplementation(((_session: unknown, input: Loose, _reuse: boolean, _display: boolean, opts: Loose) => + open({ input, permissionMode: opts.permissionMode, agent: opts.agent })) as never) +} + +/** A thread on the caller with a live run in `mode`, and its agent's tools. */ +async function launcher(options: { mode?: 'auto' | 'full' | 'accept_edits' | 'ask' } = {}) { + const project = t.caller.projects.openProject(repo.path) + const thread = t.caller.threads.createThread(`Launcher ${++seq}`, project.id, project.path, { permissionMode: options.mode ?? '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 mode = options.mode ?? 'auto' + const real = t.caller.orchestrator.runPermissionMode.bind(t.caller.orchestrator) + vi.spyOn(t.caller.orchestrator, 'runPermissionMode').mockImplementation((id) => (id === sent.runId ? mode : real(id))) + const host = (t.caller.orchestrator as unknown as { mcpToolHost(): AppToolHost }).mcpToolHost() + 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 (an argument the tool does not take). + } + return { ...(out.isError ? { isError: true } : {}), body, text: out.text } + } + /** A thread launched on the owner by this launcher's agent; its id there, and the qualified id here. */ + const launch = async (firstMessage?: string) => { + const out = await tool('thread_create', { computer: t.node, title: `Launched ${++seq}`, ...(firstMessage ? { firstMessage } : {}), clientRequestId: `launch-${seq}` }) + if (out.isError) throw new Error(JSON.stringify(out.body)) + 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 } + } + return { thread, runId: sent.runId, tool, launch } +} + +/** Every occurrence of the thread id `id` in `text` is qualified with the owner's node (a run id names its thread inside it). */ +function expectQualified(text: string, id: string): void { + let at = text.indexOf(id) + while (at >= 0) { + if (!text.slice(0, at).endsWith('run:thread:')) + expect(text.slice(Math.max(0, at - t.node.length - 1), at), `${id} in …${text.slice(Math.max(0, at - 60), at + 40)}…`).toBe(`${t.node}:`) + at = text.indexOf(id, at + 1) + } +} + +/** A run there that a person on the owner started, running in `mode`. */ +async function personRun(farThreadId: string, mode: 'accept_edits' | 'auto' | 'full' = 'accept_edits'): Promise { + const person = await t.owner.runEngine.dispatch({ kind: 'send', threadId: farThreadId, clientRequestId: `person-${++seq}`, source: 'gui' }) + if (person.status !== 'accepted') throw new Error('not accepted') + t.owner.runEngine.markStarting(person.runId) + t.owner.runEngine.markRunning(person.runId) + const real = t.owner.runEngine.bindingForRun.bind(t.owner.runEngine) + vi.spyOn(t.owner.runEngine, 'bindingForRun').mockImplementation((id) => (id === person.runId ? ({ policy: { permissionMode: mode } } as never) : real(id))) + return person.runId +} + +/** The run there starts, as its turn would. */ +function running(runId: string): void { + t.owner.runEngine.markStarting(runId) + t.owner.runEngine.markRunning(runId) +} + +const isTerminal = (runId: string): boolean => ['completed', 'interrupted', 'failed', 'cancelled', 'uncertain'].includes(t.owner.runEngine.getRun(runId)!.status) + +describe('the thread tools on a thread launched on another computer (issue #1160)', () => { + it('reads its events and messages there, every id named the way this computer names it', async () => { + standInForTurns() + const { thread, tool, launch } = await launcher() + const { far, id, runId } = await launch('Run the tests on Linux.') + running(runId!) + // A long row in its transcript there (the stood-in turn writes none). + ;(t.owner.orchestrator as unknown as Loose).noteAgentLaunch(far, `Tests on Linux: ${'x'.repeat(5_000)}`) + + const events = await tool('thread_read', { threadId: id }) + expect(events.isError, JSON.stringify(events.body)).toBeUndefined() + expect(events.body).toMatchObject({ threadId: id, computer: nameOf(), view: 'events', maxSeq: expect.any(Number) }) + expect(events.body.events.length).toBeGreaterThan(0) + for (const event of events.body.events) expect(event.threadId).toBe(id) + const eventText = JSON.stringify(events.body) + expectQualified(eventText, far) + // The launcher is this computer's own thread: wherever that computer names it, it reads as its plain id. + expect(eventText).not.toContain(`${t.callerNode}:${thread.id}`) + // Paging on from the last event returns nothing new. + const later = await tool('thread_read', { threadId: id, afterSeq: events.body.nextAfterSeq }) + expect(later.body.events).toEqual([]) + + const messages = await tool('thread_read', { threadId: id, view: 'messages', limit: 10 }) + expect(messages.isError, JSON.stringify(messages.body)).toBeUndefined() + const first = messages.body.messages.find((row: Loose) => row.text.startsWith('Tests on Linux:')) + expect(first).toMatchObject({ role: 'system', truncated: true, totalChars: 5_016, nextTextOffset: 4096 }) + expect(first.text.length).toBeLessThanOrEqual(4096) + expect(messages.body).toMatchObject({ threadId: id, total: expect.any(Number), nextAfterIndex: expect.any(Number) }) + expectQualified(JSON.stringify(messages.body), far) + // textOffset reads on in the long message, from where the first page cut it. + const on = await tool('thread_read', { threadId: id, view: 'messages', afterIndex: first.index, textOffset: first.nextTextOffset, limit: 1 }) + expect(on.body.messages[0]).toMatchObject({ index: first.index, textOffset: 4096 }) + expect(on.body.messages[0].text.startsWith('x')).toBe(true) + }, 120_000) + + it('waits until the run ends there, and says needsInput while it waits on a person there', async () => { + standInForTurns() + const { tool, launch } = await launcher() + const { far, id, runId } = await launch('Build it.') + running(runId!) + // The run waits on a person there: the wait answers at once, and says so. + const asking = vi.spyOn(t.owner.questions, 'listPendingForThread').mockImplementation((threadId) => (threadId === far ? ([{}] as never) : [])) + const waiting = await tool('thread_wait', { threadId: id, timeoutMs: 30_000 }) + expect(waiting.body).toMatchObject({ status: 'needs_input', needsInput: true, threadId: id, computer: nameOf(), run: { runId } }) + asking.mockRestore() + // It ends there while the wait runs: the wait finishes with its outcome. + const wait = tool('thread_wait', { threadId: id, runId, timeoutMs: 30_000 }) + await new Promise((resolve) => setTimeout(resolve, 500)) + t.owner.runEngine.markTerminal(runId!, 'completed') + const done = await wait + expect(done.body).toMatchObject({ status: 'finished', threadId: id, run: { runId } }) + expect(isTerminal(runId!)).toBe(true) + // Nothing to wait for: idle. + expect((await tool('thread_wait', { threadId: id, timeoutMs: 1_000 })).body).toMatchObject({ status: 'idle' }) + }, 120_000) + + it('on a computer without runs.wait, asks the run\'s status every few seconds instead', async () => { + standInForTurns() + const { tool, launch } = await launcher() + const { id, runId } = await launch('Build it.') + running(runId!) + const client = t.client() + const real = client.versions.bind(client) + vi.spyOn(client, 'versions').mockImplementation(async (node, session) => { + const { 'runs.wait': _wait, ...versions } = (await real(node, session)) ?? {} + return versions + }) + const port = portOf() + const calls = vi.spyOn(port, 'call') + const wait = tool('thread_wait', { threadId: id, runId, timeoutMs: 30_000 }) + await vi.waitFor(() => expect(calls.mock.calls.some(([, method]) => method === 'runs.get')).toBe(true)) + t.owner.runEngine.markTerminal(runId!, 'completed') + expect((await wait).body).toMatchObject({ status: 'finished', run: { runId } }) + expect(calls.mock.calls.map(([, method]) => method)).not.toContain('runs.wait') + }, 120_000) + + it('sends a message there as the agent\'s, and a replay with the same request id makes no second run', async () => { + standInForTurns() + const { thread, runId: launcherRun, tool, launch } = await launcher() + const { far, id } = await launch() + const sent = await tool('thread_send', { threadId: id, content: 'Now run the integration tests.', clientRequestId: 'send-1' }) + expect(sent.isError, JSON.stringify(sent.body)).toBeUndefined() + expect(sent.body).toMatchObject({ threadId: id, computer: nameOf(), runId: expect.any(String), delivery: 'started', replayed: false }) + // There: the agent's run, its sender this launcher and its run here, never a person's. + expect(t.owner.runEngine.getRun(sent.body.runId)).toMatchObject({ threadId: far, source: 'mcp', outcome: { sentByAgent: true } }) + await vi.waitFor(() => expect(turns).toHaveLength(1)) + expect(turns[0]!.agent).toMatchObject({ kind: 'agent', from: { node: t.callerNode, thread: thread.id, run: launcherRun } }) + expect(String(turns[0]!.input.content)).toContain('Now run the integration tests.') + // The same request id again: the first result, nothing new there. + 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 () => { + standInForTurns() + const { tool, launch } = await launcher({ mode: 'accept_edits' }) + const { far, id } = await launch() + policy.set(t.callerNode, { maxPermissionMode: 'full' }) + const run = await personRun(far, 'full') + await expect(tool('thread_steer', { threadId: id, runId: run, text: 'Faster.' })).rejects.toMatchObject({ code: 'mousse_conflict', details: { conflict: 'ceiling_exceeded' } }) + }, 120_000) + + it('stops a run an agent here started there, and leaves the run of a person who took the thread over', async () => { + standInForTurns() + const { tool, launch } = await launcher() + const agentWork = await launch('Build it.') + running(agentWork.runId!) + const stopped = await tool('thread_interrupt', { threadId: agentWork.id, runId: agentWork.runId }) + expect(stopped.isError, JSON.stringify(stopped.body)).toBeUndefined() + expect(stopped.body).toMatchObject({ threadId: agentWork.id, runId: agentWork.runId, stopped: true }) + await vi.waitFor(() => expect(isTerminal(agentWork.runId!)).toBe(true)) + + const taken = await launch() + const person = await personRun(taken.far) + await expect(tool('thread_interrupt', { threadId: taken.id, runId: person })).rejects.toMatchObject({ code: 'mousse_scope_denied', message: expect.stringContaining('person') }) + expect(t.owner.runEngine.getRun(person)!.status).toBe('running') + }, 120_000) + + it('a person\'s Stop of the launcher stops the work it started there, also when the link was down at the time', async () => { + standInForTurns() + const first = await launcher() + const up = await first.launch('Build it.') + running(up.runId!) + await t.caller.orchestrator.stopThread(first.thread.id, 'user', { clientRequestId: `person-stop-${++seq}` }) + await vi.waitFor(() => expect(t.caller.runEngine.remoteLaunches.listForLauncher(first.thread.id)[0]!.stop).toMatchObject({ state: 'sent', reason: 'stopped' }), { timeout: 20_000 }) + expect(isTerminal(up.runId!)).toBe(true) + + // The link is down when the person stops the next launcher: the Stop is kept, and the launcher says so. + const second = await launcher() + const down = await second.launch('Build it too.') + running(down.runId!) + const port = portOf() + vi.spyOn(port, 'versions').mockRejectedValue(new DomainRpcError('computer_offline', 'The other computer is offline.')) + await t.caller.orchestrator.stopThread(second.thread.id, 'user', { clientRequestId: `person-stop-${++seq}` }) + const key = t.caller.runEngine.remoteLaunches.listForLauncher(second.thread.id)[0]!.creationKey + await vi.waitFor(() => expect(t.caller.runEngine.remoteLaunches.get(key)!.stop).toMatchObject({ state: 'pending', result: expect.stringContaining('undelivered') }), { timeout: 20_000 }) + const notes = () => t.caller.orchestrator.getMessages(second.thread.id).filter((message) => message.role === 'system').map((message) => String(message.content)) + expect(notes().some((text) => text.includes('may still be going'))).toBe(true) + expect(isTerminal(down.runId!)).toBe(false) + + // A restart: the old service is gone; a new one reads the kept Stop from the run database alone and sends it once + // that computer answers. + remoteOf().close() + vi.mocked(port.versions!).mockRestore() + const fresh = new RemoteLaunchedThreads({ + records: t.caller.runEngine.remoteLaunches, + port: () => port, + denial: () => undefined, + related: () => false, + localOnly: () => false, + note: (threadId, text) => (t.caller.orchestrator as unknown as Loose).noteAgentLaunch(threadId, text) + }) + await fresh.pass() + expect(t.caller.runEngine.remoteLaunches.get(key)!.stop).toMatchObject({ state: 'sent' }) + await vi.waitFor(() => expect(isTerminal(down.runId!)).toBe(true)) + expect(notes().some((text) => text.includes('The Stop reached'))).toBe(true) + // Sent once: another pass sends nothing. + const calls = vi.spyOn(port, 'call') + await fresh.pass() + expect(calls).not.toHaveBeenCalled() + remoteOf().start() + }, 120_000) + + it('deleting the launcher stops the work it started there and deletes nothing there', async () => { + standInForTurns() + const { thread, runId: launcherRun, launch } = await launcher() + const { far, runId } = await launch('Build it.') + running(runId!) + // The launcher is idle when it is deleted: nothing of it runs to stop here, its work there still is. + t.caller.runEngine.markTerminal(launcherRun, 'completed') + // The hook the delete calls before it trashes the thread. + await (t.caller as unknown as Loose).stopRunsForDelete([thread.id]) + await vi.waitFor(() => expect(t.caller.runEngine.remoteLaunches.listForLauncher(thread.id)[0]!.stop).toMatchObject({ state: 'sent', reason: 'deleted' }), { timeout: 20_000 }) + expect(isTerminal(runId!)).toBe(true) + expect(t.owner.threads.getThread(far)).toBeDefined() + }, 120_000) + + it('counts the launched threads working there for thread_create\'s cap, as that computer says', async () => { + standInForTurns() + const { thread, launch } = await launcher() + const busy = await launch('Build it.') + running(busy.runId!) + await launch() + // One runs there, one is idle there. + expect(await remoteOf().working(thread.id)).toBe(1) + // A computer that cannot be asked: its threads count as working, never as free places. + const versions = vi.spyOn(portOf(), 'versions').mockRejectedValue(new DomainRpcError('computer_offline', 'offline')) + expect(await remoteOf().working(thread.id)).toBe(2) + versions.mockRestore() + t.owner.runEngine.markTerminal(busy.runId!, 'completed') + expect(await remoteOf().working(thread.id)).toBe(0) + }, 120_000) + + describe('reachability: a refusal names which it is, with the computer', () => { + it('a thread this thread did not launch there is refused, and nothing is asked of that computer', async () => { + const { launch } = await launcher() + const { id } = await launch() + const other = await launcher() + const calls = vi.spyOn(portOf(), 'call') + const read = await other.tool('thread_read', { threadId: id }) + expect(read).toMatchObject({ isError: true, body: { ok: false, code: 'not_launched_here', computer: nameOf() } }) + // A thread a person there started, which no agent here launched. + const own = t.thread('The owner\'s own') + for (const [name, args] of [ + ['thread_read', {}], + ['thread_wait', {}], + ['thread_send', { content: 'hi' }], + ['thread_steer', { runId: 'run-x', text: 'hi' }], + ['thread_interrupt', { runId: 'run-x' }] + ] as const) { + const out = await other.tool(name, { threadId: t.qualified(own.id), ...args }) + expect(out, name).toMatchObject({ isError: true, body: { code: 'not_launched_here' } }) + } + expect(calls).not.toHaveBeenCalled() + // No agent answers an approval on another computer. + await expect(other.tool('approval_respond', { threadId: id, requestId: 'q-1', answers: { a: 'allow_once' } })).rejects.toMatchObject({ code: 'mousse_scope_denied' }) + }, 120_000) + + it('offline: tried once more a second later, then named offline, from this call\'s answer', async () => { + const { tool, launch } = await launcher() + const { id } = await launch() + const port = portOf() + // Listed as online: the refusal comes from the call, not from the list. + vi.spyOn(port, 'computers').mockReturnValue([{ node: t.node, name: 'Linux box', online: true }]) + const versions = vi.spyOn(port, 'versions').mockRejectedValue(new DomainRpcError('computer_offline', 'Linux box is offline.')) + const out = await tool('thread_read', { threadId: id }) + expect(out).toMatchObject({ isError: true, body: { ok: false, code: 'computer_offline', message: expect.stringContaining('is offline') } }) + expect(out.body.computer).toBeDefined() + expect(versions).toHaveBeenCalledTimes(2) + }, 120_000) + + it('not allowed: the user turned agents on that computer off since the launch', async () => { + const { tool, launch } = await launcher() + const { id } = await launch() + t.caller.settings.set({ agentAccess: { ...t.caller.settings.get().agentAccess, computers: [] } } as never) + try { + expect((await tool('thread_read', { threadId: id })).body).toMatchObject({ code: 'computer_not_allowed' }) + } finally { + t.caller.settings.set({ agentAccess: { ...t.caller.settings.get().agentAccess, computers: [t.node] } } as never) + } + }, 120_000) + }) +}) + +describe('ids an agent here reads from another computer (issue #1160)', () => { + // Rows: an id of that computer (already qualified by the router), one of this computer that it named, an agent sender + // on that computer, on this one, and on a third. + const self = 'nod_00000000000000000000000000' + const far = 'nod_11111111111111111111111111' + const third = 'nod_22222222222222222222222222' + it.each([ + ['that computer\'s thread stays qualified', { threadId: `${far}:t1` }, { threadId: `${far}:t1` }], + ['this computer\'s thread is plain again', { parentThreadId: `${self}:t2` }, { parentThreadId: 't2' }], + ['a sender there is named by its thread there', { origin: { kind: 'agent', from: { node: far, thread: 't3', run: 'r', title: 'A' } } }, { origin: { kind: 'agent', from: { node: far, thread: `${far}:t3`, run: 'r', title: 'A' } } }], + ['a sender here is this computer\'s own thread', { origin: { kind: 'agent', from: { node: self, thread: 't4', run: 'r', title: 'B' } } }, { origin: { kind: 'agent', from: { node: self, thread: 't4', run: 'r', title: 'B' } } }], + ['a sender on a third computer is named by its own', { items: [{ origin: { kind: 'agent', from: { node: third, thread: 't5', run: 'r', title: 'C' } } }] }, { items: [{ origin: { kind: 'agent', from: { node: third, thread: `${third}:t5`, run: 'r', title: 'C' } } }] }] + ])('%s', (_name, given, expected) => { + expect(localized(given, self)).toEqual(expected) + }) +})