diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index ee74400fe5..dabf672ede 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -84,7 +84,7 @@ Use these terms in issues, PRs, comments, and docs. If you need a term that is n - **Works on threads:** the signed permission (the `settings` capability in a device's delegation) that lets one of the user's computers act on threads that run on another of their computers. Only computers get it; phones never do, and a phone keeps the smaller phone API. - **Let my other computers work on this computer's threads:** the switch on the computer that runs a thread (Settings, Devices, where its row reads "Let other computers work here" and the switch keeps the full name; or `mousse-cli bridge threads on|off`). It is on by default, and a computer still needs Works on threads, and stays within its highest permission mode and its terminal switch. While it is off, that computer answers none of the thread actions that other computers send it, whoever holds Works on threads. - **Private thread:** a thread that stays on the computer that started it. It is never listed, searched, opened or run from the user's other computers or phones, even with Bridge on, and the Run on menu is locked to this computer. Everything it starts is private too: its subagents, threads its agents create, and workflow agents; its agents cannot start work on other computers or send to a thread that is not private, and agents in other threads do not see it. A thread is private from the moment it is created (the lock button in the new thread's toolbar, or New private thread) and stays that way. Its worktree branch is `mousse/private-` rather than a name from its first message. Its messages still go to the model provider like any other thread's. With its worktree off it works in the project's own folder, whose files and commits other computers can read through Git; a computer that browses the project's files can also see the Git records Mousse keeps for it, and one with terminal access reaches everything on this computer. -- **Expiry (of a thread):** the time a thread deletes itself, set from the new thread's toolbar (the clock), the thread's menu (Delete after…) or the bar above it, where it can be changed or removed before then; a private thread can start with one set in Settings → General → Runs. At expiry the thread, its subagents, worktree, checkpoints and attachments are deleted for good: not Settled, not in Recently deleted. Its branch and anything committed or pushed from it are kept. A run still going waits to end, unless the thread was set to stop it. A thread that expired while the computer was off is deleted on the next start, and no turn starts in an expired thread meanwhile. The agents' own session files (Claude Code, Codex) and the run history Mousse keeps for its runs are not removed, as with a permanent delete. +- **Expiry (of a thread):** the time a thread deletes itself, set from the new thread's toolbar (the clock), the thread's menu (Delete after…) or the bar above it, where it can be changed or removed before then; a private thread can start with one set in Settings → General → Runs. At expiry the thread, its subagents, worktree, checkpoints and attachments are deleted for good: not Settled, not in Recently deleted. Its subagents on other computers expire with it: their computer is given the expiry, and every change or removal of it, and deletes them then, also when it was offline at the time. Its branch and anything committed or pushed from it are kept. A run still going waits to end, unless the thread was set to stop it. A thread that expired while the computer was off is deleted on the next start, and no turn starts in an expired thread meanwhile. The agents' own session files (Claude Code, Codex) and the run history Mousse keeps for its runs are not removed, as with a permanent delete. - **Qualified id:** the name of a thread or project on another of the user's computers, `:`. A thread or project on this computer keeps its plain id. - **Merged lists:** this computer's threads, projects and statuses together with those of the user's other computers, as one list for the windows on this computer (behind the routing flag). A row of another computer carries `node`, and its project says `sameAs` the project of this computer with the same Git history. The CLI and phones get this computer's lists alone. - **Project group:** one entry in the sidebar's Projects view. A project of this computer and the projects of other computers that hold the same repository (they share a Git remote, so `sameAs` names the project here) are one group, with all their threads, each thread row still naming its computer. A project that exists on another computer only, or matches only by its first commit (`similarTo`: forks, templates), is a group of its own, named with its computer. A group stays, with offline rows, while a computer is out of reach. diff --git a/docs/net/threat-model.md b/docs/net/threat-model.md index b9e246c033..eaab6cf448 100644 --- a/docs/net/threat-model.md +++ b/docs/net/threat-model.md @@ -245,7 +245,7 @@ An agent can start a subagent on another of the user's computers (`delegate_task - The thread there runs in the narrowest of the parent thread's mode, the parent's run and the limit that computer set for this one (it refuses a mode above that limit, so the service narrows to it first). A follow-up (`continue_subagent`) runs no looser than the run that sends it and the mode the subagent was started with. No fixed mode caps it (issue #1160): when that computer's limit for this one is Full access and the parent runs in Full access, the subagent runs in Full access there, so an agent on this computer can run commands on that one without anyone being asked. That limit starts at Auto-accept edits, so this happens only after a person on that computer raised it for this one. A task that is read-only here (`workspace: 'shared'`, or a plan ceiling) is sent in Plan mode. - A thread another device started (a remote subagent's thread, or one a phone or another computer started) cannot start remote subagents, so a chain is one computer deep. -Where the other computer knows the agent mark (below), every call that changes a thread there carries it: `threads.create`, `threads.setModel`, `threads.setPermissionMode`, `orchestrator.send` and `orchestrator.abort`. That computer then handles them as an agent's, not a person's. An older computer gets them unmarked and sees a person on this computer, as before. Which form a subagent's calls take is decided by its first call and kept on its rows (`remote_subagents.marked`): the owner's replay ledger is keyed by method, so a task that changed form mid-flight could be sent twice. Either way the other computer's switch for other computers, the block, the device's highest permission mode, the first-use notice and the audit apply, and its thread is marked "from ". A person on that computer can still raise the thread's mode up to the device limit; the subagent's questions and approvals wait there for them. A task runs until it ends or is stopped. The caller may give it a time limit (`maxMinutes`) after which it is stopped there; without one, an approval nobody answers holds its parent until someone answers it or stops the task. +Where the other computer knows the agent mark (below), every call that changes a thread there carries it: `threads.create`, `threads.setModel`, `threads.setPermissionMode`, `orchestrator.send` and `orchestrator.abort`. That computer then handles them as an agent's, not a person's. An older computer gets them unmarked and sees a person on this computer, as before. Which form a subagent's calls take is decided by its first call and kept on its rows (`remote_subagents.marked`): the owner's replay ledger is keyed by method, so a task that changed form mid-flight could be sent twice. Either way the other computer's switch for other computers, the block, the device's highest permission mode, the first-use notice and the audit apply, and its thread is marked "from ". A person on that computer can still raise the thread's mode up to the device limit; the subagent's questions and approvals wait there for them. A task runs until it ends or is stopped. The caller may give it a limit (`maxMinutes`). A computer that takes it (`orchestrator.send` version 8, `deadlineMinutes`, on a marked call only) counts the task's running time itself, not the time it waits on a person there, and stops the run when it is used up (`run_time_limits`); an older computer is stopped by the caller after that many minutes of wall time. Without a limit, an approval nobody answers holds its parent until someone answers it or stops the task. The subagent's thread there gets its root thread's expiry (`threads.setExpiry`, sent until that computer takes it, also after a change or a removal), so that computer deletes it then, as it deletes its own threads. #### Threads agents start on another computer (issue #1160) diff --git a/docs/run-engine/SPEC.md b/docs/run-engine/SPEC.md index 0302f72e5f..42e1bf67d7 100644 --- a/docs/run-engine/SPEC.md +++ b/docs/run-engine/SPEC.md @@ -570,7 +570,7 @@ Every runtime except the pi loop reaches Mousse's own tools through one MCP serv - **On another computer** (`computer`, issue #1160). `thread_create { computer, projectId?, title?, workspace?, instanceId?, model?, effort?, firstMessage?, mode?, clientRequestId? }` starts a top-level thread on another of the user's computers instead (`OrchestratorService.createRemoteThreadAsAgent`). `projectId` is then optional and names a project of that computer. `notify` with it watches the first message's run there (see "Told when it settles"). Checked before anything is recorded, and refused with a code that names the reason and the computer: Bridge on (`remote_unavailable`), not a private thread (`private_thread`), not a thread another device started (`remote_from_remote`), the computer known (`unknown_computer`, `ambiguous_computer`), allowed ("Let agents work on your other devices", `agentAccess.remoteSubagents`, and that computer in `agentAccess.computers`: `computer_not_allowed`; the owner's agent reach `none` reads the same), online (`computer_offline`), sharing its threads with this one (`computer_not_shared`), knowing the agent mark on every marked row (`computer_outdated`; never an unmarked call), the 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; 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 in its record (`launchedThread.threadId` qualified), which the chat does not show. - **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 (`scope: "launched"`); or any other thread of one of the user's computers when the caller may work on that computer now (`scope: "computer"`): not a private thread, not one another device started or whose lineage's top thread was (one computer deep, `remote_from_remote`), and `agentAccess.remoteSubagents` on with that computer in `agentAccess.computers` (`computer_not_allowed`), read at every call. Anything else is refused with a code (`launch_abandoned`, `private_thread`, `remote_from_remote`, `computer_not_allowed`, `unknown_computer`, `invalid_thread_id`), never a bare not-found. Reading such a thread follows what that computer shares with this one; a send, steer or Stop is the same marked call as for a launched thread, and that computer decides it by the agent reach its person gave this device (`net_node_policy.agent_reach`: by default only threads this device's agents started there). Its refusal is `outside_agent_reach` with `reach` (`launched` or `none`), says where it is changed (Settings → Devices on that computer), and is never retried or sent again unmarked. `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`. `thread_wait` waits there (`runs.wait`, at most 40 s a call, repeated up to `timeoutMs`; on an owner without it, `runs.get` every 4 s) and returns `finished` (with the result text cut to 4,000 characters), `needs_input` (`needsInput: true`: the run waits on a person there), `paused`, `timeout` (with `pending` when a run is preparing or a message is queued) or `idle`; `RemoteLaunchedThreads.follow` is the same wait for a follower to call. `thread_send` and `thread_steer` are marked `orchestrator.send` and `orchestrator.steer` keyed by the tool's request key (`thread_send::`), at most 16,000 characters, with `delivery`; `notify` on `thread_send` watches the message there as on one computer, on a thread this device did not launch too (the follower only reads, and names the computer from the device list). `thread_interrupt` is a marked `orchestrator.abort`; a run a person there started is refused (`not_started_by_this_computer`), whatever the reach, so on a thread this device did not launch an agent stops only a run its own message (or another agent here) started. 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`, `outside_agent_reach`, `remote_thread_gone`). `approval_respond` refuses a qualified id. - **Lists and searches of another computer.** `thread_list` and `thread_search` take `computer` (a name or id from `list_computers`); without it they stay on this computer. `RemoteLaunchedThreads.computerFor` resolves it and applies the caller-side rules above (`unknown_computer`, `ambiguous_computer`, `private_thread`, `remote_from_remote`, `computer_not_allowed`). `thread_list` reads `threads.list`, `projects.list` and `activity.snapshot` there (unmarked reads; that computer never answers a private thread or a bot's, and private rows are dropped here too), then filters, sorts and cuts as on one computer (100 rows by default, 500 at most) and to `THREAD_READ_MAX_BYTES` (`capped: true` with a hint); each row has a qualified `id`, its `mousse://thread/` link, `computer`, the project's qualified id and name, `status` from that computer's activity, and `startedByYou` for a thread the caller's lineage launched there (always listed, as here). An offline computer is refused (`computer_offline`). `thread_search` is that computer's `threads.search` (the transcripts of its newest 100 threads only), 50 results by default and 200 at most, cut to the same byte cap; a computer that is offline, stopped sharing, is outdated or does not answer within 10 s (`SEARCH_MS`, reaching it included) is named in `notSearched { code, message }` with no results instead of a refusal. - - **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. + - **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; a computer listed as offline is skipped until it is online) however long that takes, and is given up only when that computer is no longer one of the user's computers (`stop_deadline` is still written, for an older version); 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/bridge/routed/remoteAgent.ts b/src/mms/bridge/routed/remoteAgent.ts index 7b7266888e..e96979435f 100644 --- a/src/mms/bridge/routed/remoteAgent.ts +++ b/src/mms/bridge/routed/remoteAgent.ts @@ -6,6 +6,7 @@ import { ROUTED_AGENT_KEY, ROUTED_AGENT_METHODS, ROUTED_AGENT_TITLE_MAX, + ROUTED_DEADLINE_KEY, type RoutedAgentMark } from '../../../shared/bridge/routed' import type { Thread } from '../../../shared/types' @@ -68,7 +69,7 @@ const MARKED_KEYS: Readonly> = { 'threads.create': ['name', 'projectId', 'worktreeEnabled', 'startedFromProjectId'], 'threads.setModel': ['threadId', 'model', 'ifRevision'], 'threads.setPermissionMode': ['threadId', 'mode', 'ifRevision'], - 'orchestrator.send': ['threadId', 'content', 'mode', 'clientRequestId', 'requestId', 'refuseWhilePaused', 'forceQueue'], + 'orchestrator.send': ['threadId', 'content', 'mode', 'clientRequestId', 'requestId', 'refuseWhilePaused', 'forceQueue', ROUTED_DEADLINE_KEY], 'queue.enqueue': ['threadId', 'content', 'mode', 'requestId'], 'orchestrator.steer': ['threadId', 'text', 'runId', 'clientRequestId'], 'orchestrator.abort': ['threadId', 'runId', 'clientRequestId'] @@ -130,6 +131,9 @@ export class RemoteAgentCalls { case 'queue.enqueue': { const content = String(params.content) this.assertBody(content) + const deadline = params[ROUTED_DEADLINE_KEY] + if (deadline !== undefined && (method !== 'orchestrator.send' || !Number.isSafeInteger(deadline) || (deadline as number) < 1)) + throw new DomainRpcError('invalid_params', `${ROUTED_DEADLINE_KEY} must be a whole number of minutes, at least 1.`) const key = this.requestKey(call, params, method === 'queue.enqueue' ? 'requestId' : 'clientRequestId') const actor = this.actor(call, mode, this.hops(threadId, call, launchedBySender)) if (!this.replay(key)) this.assertLimits(call, threadId, true) @@ -137,7 +141,9 @@ export class RemoteAgentCalls { clientRequestId: key, actor, ...(method === 'queue.enqueue' || params.forceQueue === true ? { forceQueue: true } : {}), - ...(params.refuseWhilePaused === true ? { refuseWhilePaused: true } : {}) + ...(params.refuseWhilePaused === true ? { refuseWhilePaused: true } : {}), + // The running time the run may use here: this computer counts it and stops the run (`RunTimeLimits`). + ...(deadline !== undefined ? { runningMinutes: deadline as number } : {}) }) return sent } diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index 589199290d..34eeb199a1 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -142,6 +142,7 @@ 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' +import { RunTimeLimits } from './RunTimeLimits' import type { RemoteComputersPort } from '../protocol/remoteComputersPort' import { isRunningSubagent, isWorkingSubagent, type BackgroundTaskNoticeItem, type SubagentNoticeItem, type SubagentSummary } from '../../shared/subagents' import type { SettleNoticeItem } from '../../shared/settleNotice' @@ -1231,6 +1232,7 @@ export class OrchestratorService extends EventEmitter { async shutdown(timeoutMs = 30_000): Promise { this.beginShutdown() this.remoteSubagents?.close() + this.runTimeLimits?.close() this.remoteLaunches?.close() this.remoteThreads?.close() await this.lifecycle.waitForIdle(timeoutMs) @@ -1363,6 +1365,8 @@ export class OrchestratorService extends EventEmitter { private remoteComputers?: RemoteComputersPort /** Remote subagents' tasks on other computers (issue #469); present while a run engine is attached. */ private remoteSubagents?: RemoteSubagents + /** Running-time limits agents on other computers gave runs here (issue #685); likewise. */ + private runTimeLimits?: RunTimeLimits /** 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. */ @@ -2601,6 +2605,8 @@ export class OrchestratorService extends EventEmitter { this.unbindApprovals() this.remoteSubagents?.close() this.remoteSubagents = undefined + this.runTimeLimits?.close() + this.runTimeLimits = undefined this.remoteLaunches?.close() this.remoteLaunches = undefined this.remoteThreads?.close() @@ -2615,11 +2621,21 @@ export class OrchestratorService extends EventEmitter { titleOf: (threadId) => this.titleOf(threadId), setRunsOn: (threadId, runsOn) => { this.threadStore?.updateThreadMeta(threadId, { runsOn }, { touch: false }) }, recordMessage: (threadId, role, text) => { this.recordRemoteSubagentMessage(threadId, role, text) }, - changed: (childThreadId) => { this.emit('subagent-changed', { threadId: childThreadId }) } + changed: (childThreadId) => { this.emit('subagent-changed', { threadId: childThreadId }) }, + threadExists: (threadId) => Boolean(this.threadStore?.getThread(threadId)) }) // Tasks left open by the previous daemon go on: their runs on the other computers did not stop with it. // Without Bridge the passes reach no computer, but a task's time limit still ends it here. this.remoteSubagents.start() + // Runs agents on other computers started here with a limit are stopped once they used its running time. + this.runTimeLimits = new RunTimeLimits({ + records: engine.runTimeLimits, + getRun: (runId) => engine.getRun(runId), + waitingOnPerson: (threadId) => this.subtreeWaitsOnPerson(threadId), + stop: (threadId, runId, message) => this.stopAtRunTimeLimit(threadId, runId, message), + log: (message, details) => console.warn(message, details) + }) + this.runTimeLimits.start() this.remoteLaunches = new RemoteThreadLaunches({ records: engine.remoteLaunches, port: () => this.remoteComputers, @@ -5571,11 +5587,17 @@ export class OrchestratorService extends EventEmitter { async sendForRemoteAgent( threadId: string, input: { content: string; mode: 'agent' | 'plan' }, - options: { clientRequestId: string; actor: AgentActor; forceQueue?: boolean; refuseWhilePaused?: boolean } - ): Promise { + options: { clientRequestId: string; actor: AgentActor; forceQueue?: boolean; refuseWhilePaused?: boolean; runningMinutes?: number } + ): Promise { if (!options.actor.remote) throw new Error('sendForRemoteAgent needs an agent on another computer.') this.assertNotBotThread(threadId) - return this.sendToThreadAsAgent(threadId, input, options) + const { runningMinutes, ...sendOptions } = options + const sent = await this.sendToThreadAsAgent(threadId, input, sendOptions) + // A limit binds the run the send started (a retry finds the same run and keeps what it used). A queued message has + // no run yet: the answer then carries no limit, and the agent's computer keeps stopping it by its own clock. + if (runningMinutes === undefined || sent.queued || !sent.runId || !this.runTimeLimits) return sent + this.runTimeLimits.set(sent.runId, threadId, runningMinutes) + return { ...sent, deadlineMinutes: runningMinutes } } /** A routed `orchestrator.steer` marked as an agent's: `thread_steer`'s path, refused for a run looser than the sender. */ @@ -7862,7 +7884,9 @@ export class OrchestratorService extends EventEmitter { projectId: farProjectId, instanceId: input.instanceId?.trim() || input.provider?.trim() || null, model: remoteModel ?? null, - deadlineAt: remoteDeadlineAt(input.maxMinutes) + deadlineAt: remoteDeadlineAt(input.maxMinutes), + // That computer counts it as running time where it takes a limit; `deadlineAt` is the stop for an older one. + limitMinutes: remoteDeadlineAt(input.maxMinutes) ? input.maxMinutes ?? null : null } }) } catch (error) { @@ -7878,6 +7902,8 @@ export class OrchestratorService extends EventEmitter { title: this.titleOf(accepted.childThreadId) ?? title ?? null, computer: computer.name } + // Its thread there expires with this thread's root (issue #685). + this.trackRemoteExpiry(accepted.childThreadId, computer.node) if (accepted.replayed) return { ...value, replayed: true, note: 'Started. Mousse sends you the result when it finishes; end your turn.' } this.recordRemoteSubagentMessage(accepted.childThreadId, 'user', input.prompt) const launched = await remote.launch(accepted.delegationId) @@ -8233,6 +8259,7 @@ export class OrchestratorService extends EventEmitter { } const delegation = engine.delegations.get(accepted.delegationId) if (!delegation) throw new Error('The follow-up was not recorded as a task') + if (base?.node) this.trackRemoteExpiry(target.childThreadId, base.node) if (accepted.replayed) return this.followUpValue(delegation, target.title, { replayed: true }) this.recordRemoteSubagentMessage(target.childThreadId, 'user', target.prompt) const launched = await remote!.launch(accepted.delegationId) @@ -8243,6 +8270,47 @@ export class OrchestratorService extends EventEmitter { return this.followUpValue(delegation, target.title, {}) } + /** + * A remote subagent's thread there expires with its root thread here (issue #685): its row in `remote_expiry` is made + * with the root's expiry as it is now. A subagent already followed keeps its row. + */ + private trackRemoteExpiry(childThreadId: string, node: string): void { + const engine = this.requireRunEngine() + const rootThreadId = this.threadStore?.getThread(childThreadId)?.lineage?.rootThreadId ?? childThreadId + const root = this.threadStore?.getThread(rootThreadId) + engine.remoteExpiry.track({ childThreadId, rootThreadId, node, expiresAt: root?.expiresAt ?? null, stopsRun: root?.expiryStopsRun === true }) + } + + /** + * The expiry of `rootThreadId` was set, changed or removed (`threads.setExpiry`): its subagents on other computers get + * the same there, now or once their computer answers (issue #685). + */ + threadExpiryChanged(rootThreadId: string): void { + const engine = this.runEngine + const root = this.threadStore?.getThread(rootThreadId) + if (!engine || !root || root.lineage) return + if (engine.remoteExpiry.rootChanged(rootThreadId, root.expiresAt ?? null, root.expiryStopsRun === true) > 0) this.remoteSubagents?.kick() + } + + /** Whether something in `threadId` or a subagent below it waits on a person: a question or an approval. */ + private subtreeWaitsOnPerson(threadId: string): boolean { + const subtree = new Set([threadId, ...subagentDescendants(threadId, this.threadStore?.listAllThreads() ?? [])]) + if ([...subtree].some((id) => this.questions.listPendingForThread(id).length > 0)) return true + return this.runEngine?.approvals.listPending().some((row) => subtree.has(row.threadId)) ?? false + } + + /** + * A run reached the running-time limit an agent on another computer gave it (`RunTimeLimits`): the one Stop, as that + * agent's own (no person stopped it), with the reason on the run so the agent there reads why. + */ + private async stopAtRunTimeLimit(threadId: string, runId: string, message: string): Promise { + const engine = this.requireRunEngine() + const run = engine.getRun(runId) + if (!run || TERMINAL_RUN_STATUSES.has(run.status)) return + engine.store.casRunOutcome({ runId, expectedEpoch: run.epoch, outcomePatch: { error: message } }) + await this.stopThread(threadId, 'time_limit', { runId, clientRequestId: `time-limit:${runId}`, byAgent: true }) + } + /** A line a remote subagent's stand-in shows in its transcript: what it was asked, what it answered. Never sent to a model. */ private recordRemoteSubagentMessage(threadId: string, role: 'user' | 'assistant', content: string): void { const text = content.trim() diff --git a/src/mms/orchestrator/RemoteLaunchedThreads.ts b/src/mms/orchestrator/RemoteLaunchedThreads.ts index 24b0165bec..c0c604abc1 100644 --- a/src/mms/orchestrator/RemoteLaunchedThreads.ts +++ b/src/mms/orchestrator/RemoteLaunchedThreads.ts @@ -27,7 +27,8 @@ import type { ThreadActivityState } from '../../shared/types' * - **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. + * sent once that computer answers, however long that takes; it is given up only when that computer is no longer one of + * the user's computers. 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. */ @@ -42,7 +43,10 @@ const PROBE_MS = 8_000 export const SEARCH_MS = 10_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. */ +/** + * The deadline a kept Stop records (`stop_deadline`), for an older version that reads it. This one keeps the Stop until it + * is delivered, or that computer is no longer one of the user's computers. + */ export const REMOTE_STOP_DEADLINE_MS = 24 * 60 * 60_000 const isRecord = (value: unknown): value is Record => !!value && typeof value === 'object' && !Array.isArray(value) @@ -730,12 +734,16 @@ export class RemoteLaunchedThreads { for (const row of this.deps.records.listPendingStops()) { if (this.closed) return const stop = row.stop! - if (this.now() >= Date.parse(stop.deadline)) { + // A computer that left the user's device list can never take it; one listed as offline is tried once it answers. + const listed = this.deps.port()?.computers() + const computer = listed?.find((entry) => entry.node === row.node) + if (listed && !computer) { 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.`) + this.safeNote(row.launcherThreadId, `The Stop cannot reach «${row.title}»: ${row.computerName} is no longer one of your computers, so Mousse stopped trying. Its run there may still be going.`) continue } + if (computer && !computer.online && stop.result?.startsWith('undelivered')) 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 } }) @@ -751,7 +759,7 @@ export class RemoteLaunchedThreads { 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.`) + 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.`) } } } diff --git a/src/mms/orchestrator/RemoteSubagents.ts b/src/mms/orchestrator/RemoteSubagents.ts index fd2e4e9140..3648b72975 100644 --- a/src/mms/orchestrator/RemoteSubagents.ts +++ b/src/mms/orchestrator/RemoteSubagents.ts @@ -1,4 +1,4 @@ -import { ROUTED_AGENT_KEY, type RoutedAgentMark } from '../../shared/bridge/routed' +import { ROUTED_AGENT_KEY, ROUTED_DEADLINE_KEY, ROUTED_DEADLINE_SINCE, type RoutedAgentMark } from '../../shared/bridge/routed' import { qualifyId } from '../../shared/threadRef' import type { ThreadRunsOn } from '../../shared/types' import { DomainRpcError } from '../protocol/domainRegistry' @@ -20,7 +20,16 @@ import { REMOTE_START_TRANSIENT, runRemoteThreadStart, sendRefusal, sentRunId } * `runRemoteThreadStart` shares with `thread_create` on another computer); * - `running`: read the run there until it ends, then end the stand-in with its status and final message, * so the task publishes and the parent hears exactly as for a local subagent; - * - `stopping`: the task ended here first (a Stop, a cancel, the time limit): tell the run there to stop. + * - `stopping`: the task ended here first (a Stop, a cancel, the time limit): tell the run there to stop. The row stays + * until that computer took the Stop, also across restarts; the subagent's row shows the Stop as requested meanwhile. + * + * Besides the tasks, it keeps each subagent's thread there expiring with its root thread here (`remote_expiry`, issue + * #685): the expiry is set there right after the thread is made, and every later change or removal is sent until that + * computer took it. That computer deletes the thread at expiry itself, also when it was offline then. + * + * A task with `maxMinutes` (`limitMinutes`) gives that computer the limit as running time where it takes one + * (`ROUTED_DEADLINE_KEY`): it counts only the time the run works, not the time it waits on a person, and stops the run + * itself. An older computer is stopped from here instead, after that many minutes of wall time (`deadlineAt`). * * Every call is a routed call, so the other computer applies its own limits to it: its switch for working on its * threads, and the permission limit it set for this computer. Where that computer knows the agent mark @@ -43,6 +52,8 @@ export interface RemoteSubagentsDeps { recordMessage: (threadId: string, role: 'user' | 'assistant', text: string) => void /** Something a subagent row shows changed (the computer went offline, a question waits there). */ changed: (childThreadId: string) => void + /** Whether the subagent's stand-in thread still exists here; a gone one's expiry row goes once it was sent. */ + threadExists?: (childThreadId: string) => boolean /** How often open tasks are read (default 4 s). */ pollMs?: number now?: () => number @@ -58,6 +69,8 @@ export type RemoteLaunch = /** A pass waits for one call at most this long, so one slow computer does not hold the others. */ const CALL_TIMEOUT_MS = 20_000 +/** The soonest expiry sent to another computer: it takes none less than a minute away (`expiryRefusal`). */ +const EXPIRY_SOONEST_MS = 90_000 function codeOf(error: unknown): string { return error instanceof DomainRpcError ? error.code : 'remote_error' @@ -154,13 +167,15 @@ export class RemoteSubagents { const computer = this.computers().find((entry) => entry.node === latest.node) const remoteThreadId = tasks.find((task) => task.remoteThreadId)?.remoteThreadId const activity = open ? (open.waitingInput ? 'needs_input' : this.seen.get(open.delegationId) ?? (open.remoteRunId ? undefined : 'starting')) : undefined - const lastError = (open ?? latest).lastError + const stopping = tasks.find((task) => task.state === 'stopping') + const lastError = (open ?? stopping ?? latest).lastError return { node: latest.node, computerName: computer?.name ?? 'the other computer', online: Boolean(computer?.online) && !this.offline.has(latest.node), ...(remoteThreadId ? { ref: qualifyId(latest.node, remoteThreadId) } : {}), ...(activity ? { activity } : {}), + ...(stopping ? { stopRequested: true as const } : {}), ...(lastError ? { lastError } : {}) } } @@ -203,13 +218,17 @@ export class RemoteSubagents { this.passing = undefined const next = this.again ? 0 : this.deps.pollMs ?? 4_000 this.again = false - if (this.records.hasOpen()) this.schedule(next) + if (this.records.hasOpen() || this.expiry.hasPending()) this.schedule(next) }) }, ms) this.timer.unref?.() } - /** One pass over every open task. Never throws. */ + private get expiry() { + return this.deps.engine.remoteExpiry + } + + /** One pass over every open task, then every expiry still to send. Never throws. */ async pass(): Promise { for (const listed of this.records.listOpen()) { if (this.closed) return @@ -226,6 +245,41 @@ export class RemoteSubagents { this.inFlight.delete(record.delegationId) } } + for (const row of this.expiry.listPending()) { + if (this.closed) return + await this.sendExpiry(row.childThreadId) + } + } + + /** + * Sets the expiry the subagent's thread there must have (`remote_expiry`). Kept pending while that computer cannot be + * reached. An expiry less than a minute away (or past: the root here expired while that computer was offline) is + * sent as a minute and a half from now, the soonest that computer takes, so its thread still goes. Never throws. + */ + private async sendExpiry(childThreadId: string): Promise { + const row = this.expiry.get(childThreadId) + if (!row || row.state !== 'pending' || !row.remoteThreadId) return + let expiresAt = row.expiresAt + if (expiresAt !== null) { + const soonest = this.now() + EXPIRY_SOONEST_MS + if (!(Date.parse(expiresAt) >= soonest)) expiresAt = new Date(soonest).toISOString() + } + try { + await this.call({ node: row.node, childThreadId }, 'threads.setExpiry', { + threadId: row.remoteThreadId, + expiresAt, + ...(expiresAt !== null && row.stopsRun ? { stopsRun: true } : {}) + }, `remote-expiry:${childThreadId}:${row.generation}:${expiresAt ?? 'none'}`) + this.expiry.markSent(childThreadId, row.generation) + } catch (error) { + const code = codeOf(error) + // Not reached, or no answer that says what happened: tried again on a later pass. + if (!(error instanceof DomainRpcError) || REMOTE_START_TRANSIENT.has(code)) return this.expiry.noteError(childThreadId, row.generation, messageOf(error)) + // Gone there, or already expired and being deleted there: nothing is left to set. Any other refusal is that + // computer's answer for good (it does not let this one change its threads): kept as the reason, not asked again. + this.expiry.markSent(childThreadId, row.generation, code === 'thread_not_found' || code === 'thread_expired' ? undefined : messageOf(error)) + } + if (this.deps.threadExists && !this.deps.threadExists(childThreadId)) this.expiry.remove(childThreadId) } private async step(record: RemoteSubagentRecord): Promise { @@ -238,7 +292,7 @@ export class RemoteSubagents { } if (record.state === 'stopping') return this.stopThere(record) if (record.deadlineAt && this.now() >= Date.parse(record.deadlineAt)) { - const minutes = Math.round((Date.parse(record.deadlineAt) - Date.parse(record.createdAt)) / 60_000) + const minutes = record.limitMinutes ?? Math.round((Date.parse(record.deadlineAt) - Date.parse(record.createdAt)) / 60_000) const where = this.computerName(record.node) await this.deps.engine.settleRemoteRun(record.childRunId, 'interrupted', { error: record.waitingInput @@ -295,7 +349,7 @@ export class RemoteSubagents { } /** A call to the task's computer, bounded; it notes whether the computer answered. */ - private async call(record: RemoteSubagentRecord, method: string, params: Record, idem?: string): Promise { + private async call(record: Pick, method: string, params: Record, idem?: string): Promise { const port = this.deps.port() if (!port) throw new DomainRpcError('bridge_off', 'Connecting to your other computers is turned off on this computer.') try { @@ -324,6 +378,7 @@ export class RemoteSubagents { let remoteThreadId = record.remoteThreadId try { await this.markedForm(record) + const deadlineMinutes = await this.runningLimitThere(record) const started = await runRemoteThreadStart({ key: `remote-subagent:${record.delegationId}`, name: this.deps.titleOf(record.childThreadId) ?? 'Subagent', @@ -340,7 +395,8 @@ export class RemoteSubagents { clientRequestId: `remote-subagent:${record.delegationId}`, // A follow-up on a thread that may be paused by a usage limit refuses, as a follow-up on one computer does. // A thread made for this task has never run, so the first task sends nothing extra to an older computer. - ...(record.remoteThreadId ? { refuseWhilePaused: true } : {}) + ...(record.remoteThreadId ? { refuseWhilePaused: true } : {}), + ...(deadlineMinutes ? { deadlineMinutes } : {}) } }, { computerName: name, @@ -348,6 +404,7 @@ export class RemoteSubagents { created: (id) => { remoteThreadId = id this.records.update(record.delegationId, { remoteThreadId: id }) + this.expiry.setRemoteThread(record.childThreadId, id) this.deps.setRunsOn(record.childThreadId, { node: record.node, computerName: name, ref: qualifyId(record.node, id) }) } }) @@ -356,9 +413,13 @@ export class RemoteSubagents { const refused = sendRefusal(started.sent, name) throw new DomainRpcError(refused.code, refused.message) } - this.records.update(record.delegationId, { remoteRunId: runId, state: 'running', lastError: null, lastSeenAt: new Date(this.now()).toISOString() }) + // That computer took the limit and stops the run itself, by its running time: this one no longer stops it by the clock. + const limitTaken = deadlineMinutes !== undefined && isRecord(started.sent) && started.sent[ROUTED_DEADLINE_KEY] === deadlineMinutes + this.records.update(record.delegationId, { remoteRunId: runId, state: 'running', lastError: null, lastSeenAt: new Date(this.now()).toISOString(), ...(limitTaken ? { deadlineAt: null } : {}) }) this.seen.set(record.delegationId, 'starting') this.deps.changed(record.childThreadId) + // A new thread there gets its expiry now; one that cannot be set yet is sent on a later pass. + await this.sendExpiry(record.childThreadId) return { ok: true, remoteThreadId: started.remoteThreadId, remoteRunId: runId } } catch (error) { const code = codeOf(error) @@ -375,6 +436,18 @@ export class RemoteSubagents { } } + /** + * The minutes of running time to send with the task: its limit, when its calls are marked and that computer takes a + * limit on a send (`ROUTED_DEADLINE_KEY`). Undefined for no limit, or an older computer (stopped from here instead). + */ + private async runningLimitThere(record: RemoteSubagentRecord): Promise { + if (!record.limitMinutes || record.marked !== true) return undefined + const port = this.deps.port() + if (!port?.versions) return undefined + const versions = await port.versions(record.node, AbortSignal.timeout(CALL_TIMEOUT_MS)) + return (versions?.['orchestrator.send'] ?? 0) >= ROUTED_DEADLINE_SINCE ? record.limitMinutes : undefined + } + /** Reads the far run; once it ended, ends the stand-in with its status and final message. */ private async follow(record: RemoteSubagentRecord): Promise { const name = this.computerName(record.node) diff --git a/src/mms/orchestrator/RunTimeLimits.ts b/src/mms/orchestrator/RunTimeLimits.ts new file mode 100644 index 0000000000..4a34875810 --- /dev/null +++ b/src/mms/orchestrator/RunTimeLimits.ts @@ -0,0 +1,113 @@ +import type { RunTimeLimitRecords } from '../run/runTimeLimits' +import { TERMINAL_RUN_STATUSES, type RunRecord } from '../run/types' + +/** + * The running-time limit of a run on the computer that runs it (issue #685). An agent on another computer that starts a + * subagent here with `maxMinutes` gives its run a limit (`run_time_limits`). Every tick adds the time since the last + * one while the run is starting, running or finalizing and nothing in its thread or the subagents below it waits on a + * person; time queued, paused for a usage limit or waiting for an answer does not count. The run is stopped once it + * used its limit, with a message that says so. + * + * What was used is kept on each tick, so a restart loses at most one tick. A tick counts at most two tick lengths, so a + * computer that slept or a clock that jumped adds nothing it did not run. + */ +export interface RunTimeLimitsDeps { + records: RunTimeLimitRecords + getRun(runId: string): RunRecord | null + /** Whether something in the thread, or a subagent below it, waits on a person: a question or an approval. */ + waitingOnPerson(threadId: string): boolean + /** Stops the run (and what it started) and records why. */ + stop(threadId: string, runId: string, message: string): Promise + /** How often the runs are read (default 15 s). */ + tickMs?: number + now?: () => number + log?(message: string, details: Record): void +} + +const COUNTED: ReadonlySet = new Set(['starting', 'running', 'finalizing']) + +/** The message a run stopped at its limit ends with. */ +export function runTimeLimitMessage(limitMs: number): string { + const minutes = Math.round(limitMs / 60_000) + return `Stopped after its limit of ${minutes} ${minutes === 1 ? 'minute' : 'minutes'} of running time.` +} + +export class RunTimeLimits { + private timer: ReturnType | undefined + private passing: Promise | undefined + private closed = true + /** When each run was last read, by run id; a run read for the first time counts from then. */ + private readonly lastAt = new Map() + /** Runs a stop was asked for, so a slow stop is not asked again on every tick. */ + private readonly stopping = new Set() + + constructor(private readonly deps: RunTimeLimitsDeps) {} + + private now(): number { + return this.deps.now?.() ?? Date.now() + } + + private get tickMs(): number { + return this.deps.tickMs ?? 15_000 + } + + start(): void { + this.closed = false + this.schedule() + } + + close(): void { + this.closed = true + if (this.timer) clearTimeout(this.timer) + this.timer = undefined + } + + /** Gives `runId` a limit of `minutes` of running time. A retry of the same send keeps what the run used. */ + set(runId: string, threadId: string, minutes: number): void { + this.deps.records.set(runId, threadId, minutes * 60_000) + this.schedule() + } + + private schedule(): void { + if (this.closed || this.timer || this.passing) return + if (!this.deps.records.has()) return + this.timer = setTimeout(() => { + this.timer = undefined + this.passing = this.pass().finally(() => { + this.passing = undefined + this.schedule() + }) + }, this.tickMs) + this.timer.unref?.() + } + + /** One tick over every run with a limit. Never throws. */ + async pass(): Promise { + const now = this.now() + for (const limit of this.deps.records.list()) { + try { + const run = this.deps.getRun(limit.runId) + if (!run || TERMINAL_RUN_STATUSES.has(run.status)) { + this.deps.records.remove(limit.runId) + this.lastAt.delete(limit.runId) + this.stopping.delete(limit.runId) + continue + } + const last = this.lastAt.get(limit.runId) + this.lastAt.set(limit.runId, now) + let used = limit.usedMs + if (last !== undefined && COUNTED.has(run.status) && !this.deps.waitingOnPerson(limit.threadId)) { + used += Math.min(Math.max(0, now - last), 2 * this.tickMs) + this.deps.records.setUsed(limit.runId, used) + } + if (used >= limit.limitMs && !this.stopping.has(limit.runId)) { + this.stopping.add(limit.runId) + await this.deps.stop(limit.threadId, limit.runId, runTimeLimitMessage(limit.limitMs)) + } + } catch (error) { + this.stopping.delete(limit.runId) + this.deps.log?.('a run at its running-time limit could not be stopped yet; it is tried again', { runId: limit.runId, error: error instanceof Error ? error.message : String(error) }) + } + } + } +} diff --git a/src/mms/orchestrator/remoteThreadStart.ts b/src/mms/orchestrator/remoteThreadStart.ts index 5e84ccbf7b..9f94c8791d 100644 --- a/src/mms/orchestrator/remoteThreadStart.ts +++ b/src/mms/orchestrator/remoteThreadStart.ts @@ -1,4 +1,4 @@ -import type { RoutedAgentMark } from '../../shared/bridge/routed' +import { ROUTED_DEADLINE_KEY, type RoutedAgentMark } from '../../shared/bridge/routed' import { isPermissionMode, narrowPermissionMode, type PermissionMode } from '../../shared/permissionMode' import { DomainRpcError } from '../protocol/domainRegistry' @@ -69,6 +69,8 @@ export interface RemoteThreadStart { clientRequestId: string /** A follow-up on a thread that may be paused by a usage limit refuses instead of waiting. */ refuseWhilePaused?: boolean + /** The minutes of running time the run may use there (`ROUTED_DEADLINE_KEY`); only to a computer that takes it. */ + deadlineMinutes?: number } } @@ -137,6 +139,7 @@ export async function runRemoteThreadStart(start: RemoteThreadStart, io: RemoteT mode: start.message.mode, clientRequestId: start.message.clientRequestId, ...(start.message.refuseWhilePaused ? { refuseWhilePaused: true } : {}), + ...(start.message.deadlineMinutes ? { [ROUTED_DEADLINE_KEY]: start.message.deadlineMinutes } : {}), ...start.mark }, keys.send) return { remoteThreadId, mode, sent } diff --git a/src/mms/protocol/handlers.ts b/src/mms/protocol/handlers.ts index 5766a4f243..49073ef8a9 100644 --- a/src/mms/protocol/handlers.ts +++ b/src/mms/protocol/handlers.ts @@ -2610,6 +2610,8 @@ async function dispatchOwnedMethod(ctx: HandlerContext, method: string, params: expiryStopsRun: expiresAt !== null && asOptionalBoolean(p.stopsRun, 'stopsRun') === true ? true : undefined }, { touch: false }) ctx.mms.threadExpiry?.reschedule() + // Its subagents on other computers expire with it there too (issue #685). + ctx.mms.orchestrator.threadExpiryChanged(threadId) const { threads, version } = ctx.mms.threads.listAllThreadsVersioned() ctx.emitEvent?.('threads.updated', { threads }) return { thread: updated, threads: listedThreadsFor(ctx, threads), version } diff --git a/src/mms/run/RunEngine.ts b/src/mms/run/RunEngine.ts index 2913321164..4de6bb92cd 100644 --- a/src/mms/run/RunEngine.ts +++ b/src/mms/run/RunEngine.ts @@ -10,6 +10,8 @@ import { isFencedSource, isFollowUpSource, isPauseHeldSource, isResumeSource } f import { cancelAcknowledgedWakes, recoverWakesOnBoot } from './delegation/wake' import { RemoteLaunchRecords } from './delegation/remoteLaunches' import { RemoteSubagentRecords } from './delegation/remoteSubagents' +import { RemoteExpiryRecords } from './delegation/remoteExpiry' +import { RunTimeLimitRecords } from './runTimeLimits' import { Delegations } from './Delegations' import { EffectOutbox } from './EffectOutbox' import { HandoffService } from './handoff/HandoffService' @@ -303,6 +305,8 @@ export interface RemoteDelegationTarget { instanceId: string | null model: string | null deadlineAt: string | null + /** The minutes of running time the task may use (`maxMinutes`); null for no limit. */ + limitMinutes?: number | null /** The far thread, for a follow-up on a subagent that already has one. */ remoteThreadId?: string | null } @@ -477,6 +481,10 @@ export class RunEngine extends EventEmitter { readonly delegations: Delegations /** Remote subagents' tasks and the runs on other computers that do them (issue #469). */ readonly remoteSubagents: RemoteSubagentRecords + /** The expiry each remote subagent's thread there must have ( emote_expiry). */ + readonly remoteExpiry: RemoteExpiryRecords + /** Running-time limits of runs on this computer ( un_time_limits). */ + readonly runTimeLimits: RunTimeLimitRecords /** Threads agents here launched on other computers (`thread_create` with `computer`, issue #1160). */ readonly remoteLaunches: RemoteLaunchRecords /** Saved approval requests (SPEC §17). */ @@ -516,6 +524,8 @@ export class RunEngine extends EventEmitter { this.inbox = new Inbox(opts.store) this.delegations = new Delegations(opts.store, this.inbox) this.remoteSubagents = new RemoteSubagentRecords(opts.store) + this.remoteExpiry = new RemoteExpiryRecords(opts.store) + this.runTimeLimits = new RunTimeLimitRecords(opts.store) this.remoteLaunches = new RemoteLaunchRecords(opts.store) this.approvals = new ThreadApprovals(opts.store, { outbox: this.outbox, lineage: (threadId) => this.delegations.getLineage(threadId) }) this.openQuestions = new OpenQuestions(opts.store) diff --git a/src/mms/run/db/migrations.ts b/src/mms/run/db/migrations.ts index 56f6eba948..b00a36f4a9 100644 --- a/src/mms/run/db/migrations.ts +++ b/src/mms/run/db/migrations.ts @@ -718,6 +718,46 @@ CREATE TABLE open_questions( settled_at TEXT ) STRICT; CREATE INDEX open_questions_thread ON open_questions(thread_id, status); +` + }, + { + version: 24, + sql: ` +-- A remote subagent's limit (issue #685, maxMinutes): the minutes of running time its task may use. The computer that +-- runs it counts them when it takes the limit; deadline_at stays the stop this computer makes for an older one. +ALTER TABLE remote_subagents ADD COLUMN limit_minutes INTEGER CHECK(limit_minutes IS NULL OR limit_minutes >= 1); + +-- The expiry a remote subagent's thread there must have (issue #685): its root thread's here, kept until that +-- computer took it, so a change made while it is offline reaches it when it answers. One row per subagent. +-- pending: expires_at (null: no expiry) is not yet set there; generation rises with each change; +-- sent: that computer took it, or its thread there is gone. +CREATE TABLE remote_expiry( + child_thread_id TEXT PRIMARY KEY, + root_thread_id TEXT NOT NULL, + node TEXT NOT NULL, + remote_thread_id TEXT, + expires_at TEXT, + stops_run INTEGER NOT NULL DEFAULT 0 CHECK(stops_run IN (0,1)), + generation INTEGER NOT NULL DEFAULT 1, + state TEXT NOT NULL CHECK(state IN ('pending','sent')), + last_error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +) STRICT; +CREATE INDEX remote_expiry_root ON remote_expiry(root_thread_id); +CREATE INDEX remote_expiry_state ON remote_expiry(state); + +-- A run's running-time limit on the computer that runs it (an agent on another computer gave one, issue #685). +-- used_ms counts the time the run was starting, running or finalizing and nothing in its thread waited on a person; +-- the run is stopped once it reaches limit_ms. The row goes when the run ends. +CREATE TABLE run_time_limits( + run_id TEXT PRIMARY KEY, + thread_id TEXT NOT NULL, + limit_ms INTEGER NOT NULL CHECK(limit_ms > 0), + used_ms INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +) STRICT; ` } ] diff --git a/src/mms/run/delegation/remoteExpiry.ts b/src/mms/run/delegation/remoteExpiry.ts new file mode 100644 index 0000000000..90ad635eba --- /dev/null +++ b/src/mms/run/delegation/remoteExpiry.ts @@ -0,0 +1,129 @@ +import { int, str, type Row } from '../db/rows' +import type { RunStore } from '../RunStore' + +/** + * The expiry each remote subagent's thread on its computer must have (issue #685): table `remote_expiry`, one row per + * subagent. A subagent expires with its root thread here (`Thread.expiresAt`); its thread there is an ordinary thread of + * that computer, so it is given the same expiry and that computer deletes it then, also after being offline. Setting, + * changing and removing the expiry here marks the rows `pending`; `RemoteSubagents` sends each to its computer + * (`threads.setExpiry`) until that computer takes it, across restarts and while it is offline. + */ + +export type RemoteExpiryState = 'pending' | 'sent' + +export interface RemoteExpiryRecord { + /** The subagent's stand-in thread here. */ + childThreadId: string + /** The thread here whose expiry it follows. */ + rootThreadId: string + node: string + /** Its thread there; null until that computer created it. */ + remoteThreadId: string | null + /** The expiry it must have there; null for none. */ + expiresAt: string | null + stopsRun: boolean + /** Rises with each change, so a change is never mistaken for an older one already sent. */ + generation: number + state: RemoteExpiryState + lastError: string | null + createdAt: string + updatedAt: string +} + +function fromRow(row: Row): RemoteExpiryRecord { + return { + childThreadId: String(row.child_thread_id), + rootThreadId: String(row.root_thread_id), + node: String(row.node), + remoteThreadId: str(row.remote_thread_id), + expiresAt: str(row.expires_at), + stopsRun: int(row.stops_run) === 1, + generation: Number(row.generation), + state: row.state === 'pending' ? 'pending' : 'sent', + lastError: str(row.last_error), + createdAt: String(row.created_at), + updatedAt: String(row.updated_at) + } +} + +/** The rows of `remote_expiry`. Synchronous; every write joins the caller's transaction. */ +export class RemoteExpiryRecords { + constructor(private readonly store: RunStore) {} + + /** + * Starts following the expiry of `rootThreadId` for a subagent (its first task). A subagent already followed keeps its + * row. Nothing is pending without an expiry: a new thread there has none. + */ + track(input: { childThreadId: string; rootThreadId: string; node: string; expiresAt: string | null; stopsRun: boolean }): RemoteExpiryRecord { + const now = this.now() + this.store.db + .statement( + `INSERT INTO remote_expiry(child_thread_id, root_thread_id, node, expires_at, stops_run, generation, state, created_at, updated_at) + VALUES(?, ?, ?, ?, ?, 1, ?, ?, ?) ON CONFLICT(child_thread_id) DO NOTHING` + ) + .run(input.childThreadId, input.rootThreadId, input.node, input.expiresAt, input.expiresAt && input.stopsRun ? 1 : 0, input.expiresAt ? 'pending' : 'sent', now, now) + return this.get(input.childThreadId)! + } + + get(childThreadId: string): RemoteExpiryRecord | null { + const row = this.store.db.statement('SELECT * FROM remote_expiry WHERE child_thread_id = ?').get(childThreadId) + return row ? fromRow(row) : null + } + + /** Its thread there exists now. */ + setRemoteThread(childThreadId: string, remoteThreadId: string): void { + this.store.db + .statement('UPDATE remote_expiry SET remote_thread_id = ?, updated_at = ? WHERE child_thread_id = ? AND remote_thread_id IS NULL') + .run(remoteThreadId, this.now(), childThreadId) + } + + /** + * The root's expiry is now `expiresAt` (null: removed): every subagent that follows it must have it there. A row that + * already has it changes nothing; any other is pending again with a higher generation. Returns how many changed. + */ + rootChanged(rootThreadId: string, expiresAt: string | null, stopsRun: boolean): number { + const stops = expiresAt && stopsRun ? 1 : 0 + const result = this.store.db + .statement( + `UPDATE remote_expiry SET expires_at = ?, stops_run = ?, generation = generation + 1, state = 'pending', last_error = NULL, updated_at = ? + WHERE root_thread_id = ? AND (expires_at IS NOT ? OR stops_run <> ?)` + ) + .run(expiresAt, stops, this.now(), rootThreadId, expiresAt, stops) + return Number(result.changes ?? 0) + } + + /** The rows still to send, oldest first. */ + listPending(): RemoteExpiryRecord[] { + return this.store.db + .statement(`SELECT * FROM remote_expiry WHERE state = 'pending' ORDER BY created_at, rowid`) + .all() + .map(fromRow) + } + + hasPending(): boolean { + return Boolean(this.store.db.statement(`SELECT 1 FROM remote_expiry WHERE state = 'pending' AND remote_thread_id IS NOT NULL LIMIT 1`).get()) + } + + /** That computer took `generation` (or its thread there is gone): sent, unless a newer change came meanwhile. */ + /** Nothing more to send for `generation`; `refused` keeps why that computer would not take it. */ + markSent(childThreadId: string, generation: number, refused?: string): void { + this.store.db + .statement(`UPDATE remote_expiry SET state = 'sent', last_error = ?, updated_at = ? WHERE child_thread_id = ? AND generation = ?`) + .run(refused ?? null, this.now(), childThreadId, generation) + } + + noteError(childThreadId: string, generation: number, error: string): void { + this.store.db + .statement('UPDATE remote_expiry SET last_error = ?, updated_at = ? WHERE child_thread_id = ? AND generation = ?') + .run(error, this.now(), childThreadId, generation) + } + + /** The subagent is gone here and nothing is left to send. */ + remove(childThreadId: string): void { + this.store.db.statement(`DELETE FROM remote_expiry WHERE child_thread_id = ? AND state = 'sent'`).run(childThreadId) + } + + private now(): string { + return new Date(this.store.db.clock()).toISOString() + } +} diff --git a/src/mms/run/delegation/remoteSubagents.ts b/src/mms/run/delegation/remoteSubagents.ts index 914d8e68b4..c64dcf9911 100644 --- a/src/mms/run/delegation/remoteSubagents.ts +++ b/src/mms/run/delegation/remoteSubagents.ts @@ -37,8 +37,13 @@ export interface RemoteSubagentRecord { remoteThreadId: string | null /** The far run's id; null until that computer accepted the send. */ remoteRunId: string | null - /** When the task is stopped if the far run has not ended (`maxMinutes`); null for no limit. */ + /** + * When this computer stops the task if the far run has not ended (`maxMinutes` of wall time); null for no limit, and + * cleared once that computer took the limit as running time (`limitMinutes`) and stops the run itself. + */ deadlineAt: string | null + /** The minutes of running time the task may use (`maxMinutes`); null for no limit. */ + limitMinutes: number | null state: RemoteSubagentState /** The far thread is waiting for an answer to a question or an approval. */ waitingInput: boolean @@ -64,6 +69,8 @@ export interface RemoteSubagentOverlay { ref?: string /** What the far run of the latest open task is doing, as a subagent's activity; undefined until read. */ activity?: 'starting' | 'working' | 'paused' | 'needs_input' + /** A Stop of the subagent has not reached that computer yet; it is sent when that computer answers. */ + stopRequested?: true /** Why the latest call there failed. */ lastError?: string } @@ -88,6 +95,7 @@ function fromRow(row: Row): RemoteSubagentRecord { remoteThreadId: str(row.remote_thread_id), remoteRunId: str(row.remote_run_id), deadlineAt: str(row.deadline_at), + limitMinutes: row.limit_minutes === null || row.limit_minutes === undefined ? null : int(row.limit_minutes), state: (STATES.has(state) ? state : 'done') as RemoteSubagentState, waitingInput: int(row.waiting_input) === 1, lastError: str(row.last_error), @@ -100,12 +108,13 @@ function fromRow(row: Row): RemoteSubagentRecord { /** What a caller may change on a row; `undefined` keeps a field, `null` clears a nullable one. */ export type RemoteSubagentPatch = Partial< - Pick + Pick > const COLUMNS: Record = { remoteThreadId: 'remote_thread_id', remoteRunId: 'remote_run_id', + deadlineAt: 'deadline_at', state: 'state', waitingInput: 'waiting_input', lastError: 'last_error', @@ -117,7 +126,8 @@ const COLUMNS: Record = { export class RemoteSubagentRecords { constructor(private readonly store: RunStore) {} - create(input: Omit & { + create(input: Omit & { + limitMinutes?: number | null /** A follow-up on a subagent whose far thread already exists. */ remoteThreadId?: string | null }): RemoteSubagentRecord { @@ -125,8 +135,8 @@ export class RemoteSubagentRecords { this.store.db .statement( `INSERT INTO remote_subagents(delegation_id, child_thread_id, child_run_id, node, prompt, permission_mode, - chat_mode, worktree, project_id, instance_id, model, remote_thread_id, deadline_at, state, created_at, updated_at) - VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'starting', ?, ?)` + chat_mode, worktree, project_id, instance_id, model, remote_thread_id, deadline_at, limit_minutes, state, created_at, updated_at) + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'starting', ?, ?)` ) .run( input.delegationId, @@ -142,6 +152,7 @@ export class RemoteSubagentRecords { input.model, input.remoteThreadId ?? null, input.deadlineAt, + input.limitMinutes ?? null, now, now ) diff --git a/src/mms/run/delegation/subagentView.ts b/src/mms/run/delegation/subagentView.ts index 608be32cf4..511ac69c3a 100644 --- a/src/mms/run/delegation/subagentView.ts +++ b/src/mms/run/delegation/subagentView.ts @@ -177,7 +177,8 @@ function summarize( name: remote.computerName, online: remote.online, ...(remote.ref ? { ref: remote.ref } : {}), - ...(remote.lastError && activity !== 'idle' ? { lastError: remote.lastError } : {}) + ...(remote.stopRequested ? { stopRequested: true as const } : {}), + ...(remote.lastError && (activity !== 'idle' || remote.stopRequested) ? { lastError: remote.lastError } : {}) } } : {}) diff --git a/src/mms/run/mcp/appTools/delegation.ts b/src/mms/run/mcp/appTools/delegation.ts index 63746748e6..52e1626ca9 100644 --- a/src/mms/run/mcp/appTools/delegation.ts +++ b/src/mms/run/mcp/appTools/delegation.ts @@ -108,7 +108,7 @@ export interface DelegationToolHost { /** Delegation tool schemas (SPEC §14.2) plus the named-agent compatibility wrappers. */ const DELEGATION_TOOLS: Tool[] = [ - { name: 'delegate_task', description: 'Start a new subagent on its own thread and return at once with its delegationId. Mousse sends you a notice with the result when it finishes. title is a short role-like name ("API reviewer"), unique among your subagents: it is how you address the subagent later (continue_subagent, task_status, task_cancel); when it is taken the call returns title_taken and starts nothing. A subagent has everything you have: your shell, your tools, your MCP servers, your skills and your permission mode, never more. workspace isolated gives it a worktree of its own; shared runs it in your own folder, where its edits land in your files as it makes them. readOnly true starts the narrow kind instead (an explorer, a read-only reviewer or researcher): it works in your folder and can only read files and the web and use Mousse\'s read-only tools, with no shell, no edits and no other MCP servers. role is a label and changes nothing. Mousse never merges a subagent\'s files into yours: the notice gives the base and result snapshots (pinned under refs/mousse/), where it worked and the Git state it left, and you bring the work in with git. instanceId (the agent to run, such as "claude" or "pi:openai"), model and effort (its reasoning level) default to yours; take them from list_models, and pass effort only with model. A model or agent that is not offered, or is signed out, is refused with the reason and nothing starts: tell the user, never pick another yourself. provider is the older name form of instanceId. computer runs the subagent on another of the user\'s computers (a name from list_computers), in its copy of this repository and under its own agents; there instanceId and model default to that computer\'s. It runs there until it ends or is stopped; maxMinutes, when you give it, stops it after that many minutes. Its result names the branch its work is on there.', + { name: 'delegate_task', description: 'Start a new subagent on its own thread and return at once with its delegationId. Mousse sends you a notice with the result when it finishes. title is a short role-like name ("API reviewer"), unique among your subagents: it is how you address the subagent later (continue_subagent, task_status, task_cancel); when it is taken the call returns title_taken and starts nothing. A subagent has everything you have: your shell, your tools, your MCP servers, your skills and your permission mode, never more. workspace isolated gives it a worktree of its own; shared runs it in your own folder, where its edits land in your files as it makes them. readOnly true starts the narrow kind instead (an explorer, a read-only reviewer or researcher): it works in your folder and can only read files and the web and use Mousse\'s read-only tools, with no shell, no edits and no other MCP servers. role is a label and changes nothing. Mousse never merges a subagent\'s files into yours: the notice gives the base and result snapshots (pinned under refs/mousse/), where it worked and the Git state it left, and you bring the work in with git. instanceId (the agent to run, such as "claude" or "pi:openai"), model and effort (its reasoning level) default to yours; take them from list_models, and pass effort only with model. A model or agent that is not offered, or is signed out, is refused with the reason and nothing starts: tell the user, never pick another yourself. provider is the older name form of instanceId. computer runs the subagent on another of the user\'s computers (a name from list_computers), in its copy of this repository and under its own agents; there instanceId and model default to that computer\'s. It runs there until it ends or is stopped; maxMinutes, when you give it, stops it after that many minutes of running time (time it waits for a person\'s answer does not count). It expires with your thread. Its result names the branch its work is on there.', parameters: Type.Object({ prompt: Type.String(), title: Type.String(), instanceId: Type.Optional(Type.String()), provider: Type.Optional(Type.String()), model: Type.Optional(Type.String()), effort: Type.Optional(Type.String()), role: Type.Optional(Type.String()), workspace: Type.Union([Type.Literal('isolated'), Type.Literal('shared')]), readOnly: Type.Optional(Type.Boolean()), wake: Type.Optional(Type.Union([Type.Literal('always'), Type.Literal('settled_only')])), diff --git a/src/mms/run/runTimeLimits.ts b/src/mms/run/runTimeLimits.ts new file mode 100644 index 0000000000..99f536a413 --- /dev/null +++ b/src/mms/run/runTimeLimits.ts @@ -0,0 +1,56 @@ +import type { RunStore } from './RunStore' + +/** + * Running-time limits of runs on this computer (issue #685): table `run_time_limits`. An agent on another computer that + * starts a subagent here with `maxMinutes` gives the run it starts a limit; `RunTimeLimits` counts the run's running + * time against it and stops the run when it is used up. The row goes when the run ends. + */ +export interface RunTimeLimitRecord { + runId: string + threadId: string + limitMs: number + usedMs: number +} + +export class RunTimeLimitRecords { + constructor(private readonly store: RunStore) {} + + /** Gives `runId` a limit; a run that has one keeps it and what it used (a retry of the same send). */ + set(runId: string, threadId: string, limitMs: number): void { + const now = this.now() + this.store.db + .statement( + `INSERT INTO run_time_limits(run_id, thread_id, limit_ms, used_ms, created_at, updated_at) VALUES(?, ?, ?, 0, ?, ?) + ON CONFLICT(run_id) DO NOTHING` + ) + .run(runId, threadId, limitMs, now, now) + } + + get(runId: string): RunTimeLimitRecord | null { + const row = this.store.db.statement('SELECT * FROM run_time_limits WHERE run_id = ?').get(runId) + return row ? { runId: String(row.run_id), threadId: String(row.thread_id), limitMs: Number(row.limit_ms), usedMs: Number(row.used_ms) } : null + } + + list(): RunTimeLimitRecord[] { + return this.store.db + .statement('SELECT * FROM run_time_limits ORDER BY created_at, rowid') + .all() + .map((row) => ({ runId: String(row.run_id), threadId: String(row.thread_id), limitMs: Number(row.limit_ms), usedMs: Number(row.used_ms) })) + } + + has(): boolean { + return Boolean(this.store.db.statement('SELECT 1 FROM run_time_limits LIMIT 1').get()) + } + + setUsed(runId: string, usedMs: number): void { + this.store.db.statement('UPDATE run_time_limits SET used_ms = ?, updated_at = ? WHERE run_id = ?').run(Math.round(usedMs), this.now(), runId) + } + + remove(runId: string): void { + this.store.db.statement('DELETE FROM run_time_limits WHERE run_id = ?').run(runId) + } + + private now(): string { + return new Date(this.store.db.clock()).toISOString() + } +} diff --git a/src/renderer/components/sideCard/lineageLogic.ts b/src/renderer/components/sideCard/lineageLogic.ts index 41d61e4857..87d8397fbd 100644 --- a/src/renderer/components/sideCard/lineageLogic.ts +++ b/src/renderer/components/sideCard/lineageLogic.ts @@ -164,8 +164,12 @@ export function waitingLabel(subagent: Pick): stri return count > 0 ? `Waiting on ${count} ${count === 1 ? 'subagent' : 'subagents'}` : 'Waiting on subagents' } -/** Muted text on the right of a row: the state while running, otherwise how long ago it finished. */ -export function lineageStatusLabel(subagent: Pick, now: number): string { +/** + * Muted text on the right of a row: the state while running, otherwise how long ago it finished. A subagent on another + * computer whose Stop has not reached that computer yet says so: its run there may still be going. + */ +export function lineageStatusLabel(subagent: Pick, now: number): string { + if (subagent.computer?.stopRequested) return 'Stop requested' if (subagent.state === 'waiting') return waitingLabel(subagent) const running = RUNNING_LABELS[subagent.state] if (running) return running diff --git a/src/shared/bridge/routed.ts b/src/shared/bridge/routed.ts index 202c45fe63..801583fc11 100644 --- a/src/shared/bridge/routed.ts +++ b/src/shared/bridge/routed.ts @@ -159,6 +159,17 @@ export const ROUTED_AGENT_METHODS: Readonly> = Object.fre 'orchestrator.abort': 2 }) +/** + * On an agent's `orchestrator.send` (with `agent`), set only by the calling computer's daemon: the minutes of running + * time the run it starts may use (a remote subagent's `maxMinutes`, issue #685), a whole number of at least 1. The owner + * counts the time the run works, not the time it waits on a person, stops the run when it is used up, and answers with + * the same key when it took the limit. A caller sends it only to an owner whose row is at `ROUTED_DEADLINE_SINCE`; + * an older owner is stopped by the caller after that many minutes instead. + */ +export const ROUTED_DEADLINE_KEY = 'deadlineMinutes' +/** The version of `orchestrator.send` that added `deadlineMinutes`. */ +export const ROUTED_DEADLINE_SINCE = 8 + /** What the `agent` key carries. */ export interface RoutedAgentMark { /** The sending thread, by its id on the calling computer. */ @@ -373,14 +384,16 @@ export const ROUTED_METHODS: Readonly> = Object.freeze 'conversationBranchId', 'expect', ROUTED_SEND_WINDOW_KEY, - ROUTED_AGENT_KEY + ROUTED_AGENT_KEY, + ROUTED_DEADLINE_KEY ], // Version 3: `refuseWhilePaused`, a parent's follow-up to a subagent, which a thread paused by a usage limit refuses. // Version 4: `conversationBranchId`, the branch an edited prompt must land on. // Version 5: `expect`, the model, mode and settings revision the sender saw; the owner runs nothing on other ones. // Version 6: `window`, set by the calling computer: a window sent this (`ROUTED_SEND_WINDOW_KEY`). // Version 7: `agent`, an agent's message (`ROUTED_AGENT_KEY`). - { required: ['content'], ...staging(['content', 'images']), version: 7, since: { [ROUTED_STAGED_KEY]: 2, refuseWhilePaused: 3, conversationBranchId: 4, expect: 5, [ROUTED_SEND_WINDOW_KEY]: 6, [ROUTED_AGENT_KEY]: 7 } } + // Version 8: `deadlineMinutes`, the running time an agent's task may use there (`ROUTED_DEADLINE_KEY`). + { required: ['content'], ...staging(['content', 'images']), version: 8, since: { [ROUTED_STAGED_KEY]: 2, refuseWhilePaused: 3, conversationBranchId: 4, expect: 5, [ROUTED_SEND_WINDOW_KEY]: 6, [ROUTED_AGENT_KEY]: 7, [ROUTED_DEADLINE_KEY]: ROUTED_DEADLINE_SINCE } } ), // Version 3 (both): `agent`, an agent's steer or Stop (`ROUTED_AGENT_KEY`). 'orchestrator.steer': chat( diff --git a/src/shared/subagents.ts b/src/shared/subagents.ts index 43cbd1b561..3ffb612f90 100644 --- a/src/shared/subagents.ts +++ b/src/shared/subagents.ts @@ -88,6 +88,8 @@ export interface SubagentComputer { ref?: string /** Why the latest call to that computer failed, while its task is still open. */ lastError?: string + /** A Stop has not reached that computer yet; it is sent when that computer answers. */ + stopRequested?: true } /** diff --git a/tests/net/bridge/routed/remoteSubagents.test.ts b/tests/net/bridge/routed/remoteSubagents.test.ts index 8e05728418..5e8868d049 100644 --- a/tests/net/bridge/routed/remoteSubagents.test.ts +++ b/tests/net/bridge/routed/remoteSubagents.test.ts @@ -150,4 +150,71 @@ describe('remote subagents over Bridge (issue #469)', () => { vi.restoreAllMocks() } }, 120_000) + + // Issue #685: the owner counts the task's limit as running time and stops the run; its thread there expires with the + // parent here. + it('the owner keeps the limit and stops the run at it, and its thread there gets the parent\'s expiry', async () => { + const service = serviceOf(t.caller) + service.pause() + vi.spyOn(t.owner.orchestrator, 'send').mockImplementation(async (_input, _reuse, opts) => { + const sent = await t.owner.runEngine.dispatch({ kind: 'send', threadId: opts!.threadId!, clientRequestId: opts!.clientRequestId!, source: opts!.source ?? 'gui', ...(opts!.agent ? { actor: opts!.agent } : {}) }) + if (sent.status !== 'accepted') throw new Error('not accepted') + return { message: '', actions: [], runId: sent.runId, sequence: sent.sequence, accepted: true } as never + }) + try { + const parentThread = t.caller.threads.createThread('Limited parent') + const expiresAt = new Date(Date.now() + 2 * 60 * 60_000).toISOString() + t.caller.threads.updateThreadMeta(parentThread.id, { expiresAt, expiryStopsRun: true }, { touch: false }) + const parent = await t.caller.runEngine.dispatch({ kind: 'send', threadId: parentThread.id, clientRequestId: 'limited-parent-send', source: 'gui' }) + if (parent.status !== 'accepted') throw new Error('parent not accepted') + t.caller.runEngine.markStarting(parent.runId) + t.caller.runEngine.markRunning(parent.runId) + const accepted = await t.caller.runEngine.requestDelegation({ + parentThreadId: parentThread.id, + parentRunId: parent.runId, + clientRequestId: 'delegation:remote-limited', + prompt: 'Soak it there', + workspace: 'shared', + role: 'research', + wake: 'always', + title: 'Remote soak', + remote: { + node: t.node, prompt: 'Soak it there', permissionMode: 'accept_edits', chatMode: 'plan', worktree: false, projectId: null, instanceId: null, model: null, + deadlineAt: new Date(Date.now() + 5 * 60_000).toISOString(), limitMinutes: 5 + } + }) + // What `delegate_task` does for a task on another computer: its expiry follows the parent from now on. + ;(t.caller.orchestrator as unknown as { trackRemoteExpiry(child: string, node: string): void }).trackRemoteExpiry(accepted.childThreadId, t.node) + const launched = await service.launch(accepted.delegationId) + expect(launched, JSON.stringify(launched)).toMatchObject({ ok: true }) + if (launched.ok !== true) return + + // The owner took the limit: it counts it, so the caller no longer stops the task by the clock. + expect(t.owner.runEngine.runTimeLimits.get(launched.remoteRunId)).toMatchObject({ threadId: launched.remoteThreadId, limitMs: 5 * 60_000, usedMs: 0 }) + expect(t.caller.runEngine.remoteSubagents.get(accepted.delegationId)).toMatchObject({ limitMinutes: 5, deadlineAt: null }) + // The thread there expires with the parent here. + expect(t.owner.threads.getThread(launched.remoteThreadId)).toMatchObject({ expiresAt, expiryStopsRun: true }) + expect(t.caller.runEngine.remoteExpiry.get(accepted.childThreadId)).toMatchObject({ state: 'sent', lastError: null }) + + // The run works there until its limit is used: the owner stops it and says why, and the parent's task ends with it. + t.owner.runEngine.markStarting(launched.remoteRunId) + t.owner.runEngine.markRunning(launched.remoteRunId) + const limits = (t.owner.orchestrator as unknown as { runTimeLimits: { pass(): Promise; deps: { now?: () => number } } }).runTimeLimits + let now = Date.now() + limits.deps.now = () => now + await limits.pass() + t.owner.runEngine.runTimeLimits.setUsed(launched.remoteRunId, 5 * 60_000 - 5_000) + now += 10_000 + await limits.pass() + const stopped = t.owner.runEngine.getRun(launched.remoteRunId)! + expect(['cancelled', 'interrupted']).toContain(stopped.status) + expect(stopped.outcome?.error).toBe('Stopped after its limit of 5 minutes of running time.') + expect(stopped.outcome?.interruptedBy).not.toBe('user') + await service.pass() + const task = t.caller.runEngine.delegations.get(accepted.delegationId)! + expect(task.result?.error).toMatch(/^On .+: Stopped after its limit of 5 minutes of running time\.$/) + } finally { + vi.restoreAllMocks() + } + }, 120_000) }) diff --git a/tests/net/bridge/routed/routedVersions.json b/tests/net/bridge/routed/routedVersions.json index 30f0ab7c2f..147b742309 100644 --- a/tests/net/bridge/routed/routedVersions.json +++ b/tests/net/bridge/routed/routedVersions.json @@ -350,8 +350,8 @@ "security": "926c4af141d1208d" }, "orchestrator.send": { - "version": 7, - "digest": "edd94ddc3918527d", + "version": 8, + "digest": "f0c64070d7cee134", "security": "1447c39a3cdfbf97" }, "orchestrator.steer": { diff --git a/tests/net/bridge/routed/table.test.ts b/tests/net/bridge/routed/table.test.ts index 755c022cf0..ac45a86c7f 100644 --- a/tests/net/bridge/routed/table.test.ts +++ b/tests/net/bridge/routed/table.test.ts @@ -294,11 +294,12 @@ describe('the routed method table', () => { ]) for (const method of marked) { const row = ROUTED_METHODS[method] - // The key arrived with the row's newest version: an owner at the version before has not got it, so a caller - // refuses to send it there (`RoutedClient.unsupportedKey`) instead of delivering an agent's call as a person's. - expect(row.since?.[ROUTED_AGENT_KEY], method).toBe(row.version) - expect(ROUTED_AGENT_METHODS[method], method).toBe(row.version) - expect(routedKeysAt(row, row.version - 1), method).not.toContain(ROUTED_AGENT_KEY) + // The key arrived with a version of its own: an owner at the version before has not got it, so a caller refuses + // to send it there (`RoutedClient.unsupportedKey`) instead of delivering an agent's call as a person's. + const since = row.since?.[ROUTED_AGENT_KEY] + expect(since, method).toBeGreaterThan(1) + expect(ROUTED_AGENT_METHODS[method], method).toBe(since) + expect(routedKeysAt(row, since! - 1), method).not.toContain(ROUTED_AGENT_KEY) expect(ROUTED_DROPPABLE_KEYS[method] ?? [], method).not.toContain(ROUTED_AGENT_KEY) } }) diff --git a/tests/net/bridge/routed/threadToolsRemote.test.ts b/tests/net/bridge/routed/threadToolsRemote.test.ts index 461e6c42ed..59959814b5 100644 --- a/tests/net/bridge/routed/threadToolsRemote.test.ts +++ b/tests/net/bridge/routed/threadToolsRemote.test.ts @@ -292,7 +292,7 @@ describe('the thread tools on a thread launched on another computer (issue #1160 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. + // that computer answers, however long that took (issue #685: no day-long cutoff). remoteOf().close() vi.mocked(port.versions!).mockRestore() const fresh = new RemoteLaunchedThreads({ @@ -301,7 +301,8 @@ describe('the thread tools on a thread launched on another computer (issue #1160 denial: () => undefined, related: () => false, localOnly: () => false, - note: (threadId, text) => (t.caller.orchestrator as unknown as Loose).noteAgentLaunch(threadId, text) + note: (threadId, text) => (t.caller.orchestrator as unknown as Loose).noteAgentLaunch(threadId, text), + now: () => Date.now() + 2 * 24 * 60 * 60_000 }) await fresh.pass() expect(t.caller.runEngine.remoteLaunches.get(key)!.stop).toMatchObject({ state: 'sent' }) @@ -314,6 +315,41 @@ describe('the thread tools on a thread launched on another computer (issue #1160 remoteOf().start() }, 120_000) + it('a kept Stop is given up only once that computer is no longer one of the user\'s computers', async () => { + standInForTurns() + const { thread, launch } = await launcher() + const { runId } = await launch('Build it.') + running(runId!) + const port = portOf() + vi.spyOn(port, 'versions').mockRejectedValue(new DomainRpcError('computer_offline', 'The other computer is offline.')) + await t.caller.orchestrator.stopThread(thread.id, 'user', { clientRequestId: `person-stop-${++seq}` }) + const key = t.caller.runEngine.remoteLaunches.listForLauncher(thread.id)[0]!.creationKey + await vi.waitFor(() => expect(t.caller.runEngine.remoteLaunches.get(key)!.stop).toMatchObject({ state: 'pending' }), { timeout: 20_000 }) + remoteOf().close() + vi.mocked(port.versions!).mockRestore() + // That computer was removed from the device list: nothing can deliver the Stop any more. + const listed = vi.spyOn(port, 'computers').mockReturnValue([]) + 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) + }) + try { + await fresh.pass() + expect(t.caller.runEngine.remoteLaunches.get(key)!.stop).toMatchObject({ state: 'expired' }) + const notes = t.caller.orchestrator.getMessages(thread.id).filter((message) => message.role === 'system').map((message) => String(message.content)) + expect(notes.some((text) => text.includes('is no longer one of your computers'))).toBe(true) + } finally { + listed.mockRestore() + // Its run there is still going; the test ends it. + t.owner.runEngine.markTerminal(runId!, 'cancelled') + 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() diff --git a/tests/run/delegationGuidance.test.ts b/tests/run/delegationGuidance.test.ts index 1426527ae6..219d0fc755 100644 --- a/tests/run/delegationGuidance.test.ts +++ b/tests/run/delegationGuidance.test.ts @@ -92,7 +92,7 @@ describe('the delegation tools models are offered', () => { }))).toMatchInlineSnapshot(` [ { - "description": "Start a new subagent on its own thread and return at once with its delegationId. Mousse sends you a notice with the result when it finishes. title is a short role-like name ("API reviewer"), unique among your subagents: it is how you address the subagent later (continue_subagent, task_status, task_cancel); when it is taken the call returns title_taken and starts nothing. A subagent has everything you have: your shell, your tools, your MCP servers, your skills and your permission mode, never more. workspace isolated gives it a worktree of its own; shared runs it in your own folder, where its edits land in your files as it makes them. readOnly true starts the narrow kind instead (an explorer, a read-only reviewer or researcher): it works in your folder and can only read files and the web and use Mousse's read-only tools, with no shell, no edits and no other MCP servers. role is a label and changes nothing. Mousse never merges a subagent's files into yours: the notice gives the base and result snapshots (pinned under refs/mousse/), where it worked and the Git state it left, and you bring the work in with git. instanceId (the agent to run, such as "claude" or "pi:openai"), model and effort (its reasoning level) default to yours; take them from list_models, and pass effort only with model. A model or agent that is not offered, or is signed out, is refused with the reason and nothing starts: tell the user, never pick another yourself. provider is the older name form of instanceId. computer runs the subagent on another of the user's computers (a name from list_computers), in its copy of this repository and under its own agents; there instanceId and model default to that computer's. It runs there until it ends or is stopped; maxMinutes, when you give it, stops it after that many minutes. Its result names the branch its work is on there.", + "description": "Start a new subagent on its own thread and return at once with its delegationId. Mousse sends you a notice with the result when it finishes. title is a short role-like name ("API reviewer"), unique among your subagents: it is how you address the subagent later (continue_subagent, task_status, task_cancel); when it is taken the call returns title_taken and starts nothing. A subagent has everything you have: your shell, your tools, your MCP servers, your skills and your permission mode, never more. workspace isolated gives it a worktree of its own; shared runs it in your own folder, where its edits land in your files as it makes them. readOnly true starts the narrow kind instead (an explorer, a read-only reviewer or researcher): it works in your folder and can only read files and the web and use Mousse's read-only tools, with no shell, no edits and no other MCP servers. role is a label and changes nothing. Mousse never merges a subagent's files into yours: the notice gives the base and result snapshots (pinned under refs/mousse/), where it worked and the Git state it left, and you bring the work in with git. instanceId (the agent to run, such as "claude" or "pi:openai"), model and effort (its reasoning level) default to yours; take them from list_models, and pass effort only with model. A model or agent that is not offered, or is signed out, is refused with the reason and nothing starts: tell the user, never pick another yourself. provider is the older name form of instanceId. computer runs the subagent on another of the user's computers (a name from list_computers), in its copy of this repository and under its own agents; there instanceId and model default to that computer's. It runs there until it ends or is stopped; maxMinutes, when you give it, stops it after that many minutes of running time (time it waits for a person's answer does not count). It expires with your thread. Its result names the branch its work is on there.", "name": "delegate_task", "parameters": [ "prompt", diff --git a/tests/run/remoteSubagents.test.ts b/tests/run/remoteSubagents.test.ts index d35f9c21f3..6a91763a95 100644 --- a/tests/run/remoteSubagents.test.ts +++ b/tests/run/remoteSubagents.test.ts @@ -33,6 +33,8 @@ class FakeComputer implements RemoteComputersPort { marks = false /** How often it was asked. */ asked = 0 + /** The routed versions it reports; undefined is a computer that reports none. */ + routedVersions: Record | undefined private threads = 0 private runs = 0 @@ -52,6 +54,11 @@ class FakeComputer implements RemoteComputersPort { return this.marks } + async versions(node: string): Promise | undefined> { + expect(node).toBe(MAC) + return this.routedVersions + } + async call(node: string, method: string, params: Record, options?: { idem?: string }): Promise { expect(node).toBe(MAC) this.calls.push({ method, params, ...(options?.idem ? { idem: options.idem } : {}) }) @@ -65,9 +72,11 @@ class FakeComputer implements RemoteComputersPort { case 'threads.setPermissionMode': case 'threads.setModel': case 'threads.settle': + case 'threads.setExpiry': return {} case 'orchestrator.send': - return { runId: `far-run-${++this.runs}`, accepted: true } + // A computer that takes a running-time limit says so in its answer. + return { runId: `far-run-${++this.runs}`, accepted: true, ...(params.deadlineMinutes !== undefined ? { deadlineMinutes: params.deadlineMinutes } : {}) } case 'runs.get': return { run: { runId: params.runId, ...this.farRun } } case 'orchestrator.pendingQuestions': @@ -278,6 +287,115 @@ describe('remote subagents (issue #469)', () => { expect(d.engine.delegations.get(out.started.delegationId)!.result).toBeFalsy() }) + // Issue #685: the time limit is running time, counted by the computer that runs the task, where that computer can. + it('a computer that takes a limit on a send gets it as running time, and this one no longer stops the task by the clock', async () => { + const { d, steps, out, say, mac, service, startOnMac } = remoteWorld() + mac.marks = true + mac.routedVersions = { 'orchestrator.send': 8 } + steps['go'] = async (tools) => { out.started = await startOnMac(tools, 'Mac tester', { maxMinutes: 5 }) } + await say('go') + expect(mac.calls.find((call) => call.method === 'orchestrator.send')!.params).toMatchObject({ deadlineMinutes: 5 }) + expect(d.engine.remoteSubagents.get(out.started.delegationId)).toMatchObject({ limitMinutes: 5, deadlineAt: null }) + ;(service as unknown as { deps: { now: () => number } }).deps.now = () => Date.now() + 60 * 60_000 + await service.pass() + expect(d.engine.delegations.get(out.started.delegationId)!.result).toBeFalsy() + expect(mac.methods()).not.toContain('orchestrator.abort') + }) + + it('an older computer gets no limit on the send, and the task keeps its deadline here', async () => { + const { d, steps, out, say, mac, startOnMac } = remoteWorld() + mac.marks = true + mac.routedVersions = { 'orchestrator.send': 7 } + steps['go'] = async (tools) => { + out.started = await startOnMac(tools, 'Mac tester', { maxMinutes: 5 }) + out.free = await startOnMac(tools, 'Mac soak') + } + await say('go') + for (const send of mac.calls.filter((call) => call.method === 'orchestrator.send')) expect(send.params).not.toHaveProperty('deadlineMinutes') + expect(d.engine.remoteSubagents.get(out.started.delegationId)!.deadlineAt).not.toBeNull() + expect(d.engine.remoteSubagents.get(out.free.delegationId)).toMatchObject({ limitMinutes: null, deadlineAt: null }) + }) + + // Issue #685: a subagent on another computer expires with the thread that started it. + it('its thread there gets the parent\'s expiry, then every change and the removal, also once that computer is back', async () => { + const { d, parent, steps, out, say, mac, service, startOnMac } = remoteWorld() + const inTwoHours = new Date(Date.now() + 2 * 60 * 60_000).toISOString() + d.store.updateThreadMeta(parent.id, { expiresAt: inTwoHours, expiryStopsRun: true }, { touch: false }) + steps['go'] = async (tools) => { out.started = await startOnMac(tools, 'Mac tester') } + await say('go') + const expiries = () => mac.calls.filter((call) => call.method === 'threads.setExpiry') + expect(expiries()).toHaveLength(1) + expect(expiries()[0]).toMatchObject({ params: { threadId: 'far-thread-1', expiresAt: inTwoHours, stopsRun: true }, idem: expect.stringContaining('remote-expiry:') }) + + // Changed while that computer is offline: sent once it answers. + const inThreeHours = new Date(Date.now() + 3 * 60 * 60_000).toISOString() + mac.online = false + d.store.updateThreadMeta(parent.id, { expiresAt: inThreeHours, expiryStopsRun: undefined }, { touch: false }) + d.orch.threadExpiryChanged(parent.id) + await service.pass() + expect(d.engine.remoteExpiry.get(out.started.childThreadId)).toMatchObject({ state: 'pending', expiresAt: inThreeHours }) + mac.online = true + await service.pass() + expect(expiries().at(-1)!.params).toEqual({ threadId: 'far-thread-1', expiresAt: inThreeHours }) + expect(d.engine.remoteExpiry.get(out.started.childThreadId)).toMatchObject({ state: 'sent', lastError: null }) + const sentSoFar = expiries().length + // Nothing changed: nothing is sent again. + d.orch.threadExpiryChanged(parent.id) + await service.pass() + expect(expiries()).toHaveLength(sentSoFar) + + // Kept after all: the thread there is kept too. + d.store.updateThreadMeta(parent.id, { expiresAt: undefined, expiryStopsRun: undefined }, { touch: false }) + d.orch.threadExpiryChanged(parent.id) + await service.pass() + expect(expiries().at(-1)!.params).toEqual({ threadId: 'far-thread-1', expiresAt: null }) + }) + + it('an expiry that passed while that computer was offline is sent as soon as it takes, so its thread still goes', async () => { + const { d, parent, steps, out, say, mac, service, startOnMac } = remoteWorld() + steps['go'] = async (tools) => { out.started = await startOnMac(tools, 'Mac tester') } + await say('go') + mac.online = false + d.store.updateThreadMeta(parent.id, { expiresAt: new Date(Date.now() - 60_000).toISOString() }, { touch: false }) + d.orch.threadExpiryChanged(parent.id) + await service.pass() + mac.online = true + await service.pass() + const sent = mac.calls.filter((call) => call.method === 'threads.setExpiry').at(-1)! + // That computer refuses an expiry less than a minute away; a minute and a half is the soonest sent. + expect(Date.parse(String(sent.params.expiresAt))).toBeGreaterThanOrEqual(Date.now() + 60_000) + expect(Date.parse(String(sent.params.expiresAt))).toBeLessThanOrEqual(Date.now() + 2 * 60_000) + }) + + it('an expiry that computer refuses for good is not asked again; one it cannot be reached for is', async () => { + const { d, parent, steps, out, say, mac, service, startOnMac } = remoteWorld() + d.store.updateThreadMeta(parent.id, { expiresAt: new Date(Date.now() + 2 * 60 * 60_000).toISOString() }, { touch: false }) + mac.refuse['threads.setExpiry'] = 'computer_forbidden' + steps['go'] = async (tools) => { out.started = await startOnMac(tools, 'Mac tester') } + await say('go') + await service.pass() + expect(mac.methods().filter((method) => method === 'threads.setExpiry')).toHaveLength(1) + expect(d.engine.remoteExpiry.get(out.started.childThreadId)).toMatchObject({ state: 'sent', lastError: expect.stringContaining('refused threads.setExpiry') }) + }) + + it('a Stop that cannot reach that computer yet shows as Stop requested until it is delivered', async () => { + const { d, parent, steps, out, say, mac, service, startOnMac } = remoteWorld() + steps['go'] = async (tools) => { out.started = await startOnMac(tools, 'Mac tester') } + steps['cancel'] = async (tools) => { out.cancelled = await tools.taskCancel({ subagent: 'Mac tester' }) as Json } + await say('go') + mac.online = false + await say('cancel') + await service.pass() + await service.pass() + expect(d.engine.remoteSubagents.get(out.started.delegationId)!.state).toBe('stopping') + expect((d.orch as any).subagentView(parent.id)[0].computer).toMatchObject({ online: false, stopRequested: true, lastError: 'Studio Mac is offline.' }) + mac.online = true + await service.pass() + expect(mac.methods()).toContain('orchestrator.abort') + expect(d.engine.remoteSubagents.get(out.started.delegationId)!.state).toBe('done') + expect((d.orch as any).subagentView(parent.id)[0].computer).not.toHaveProperty('stopRequested') + }) + it('continues on the same thread there once the last task finished, and never merges here', async () => { const { d, steps, out, say, mac, service, startOnMac } = remoteWorld() steps['go'] = async (tools) => { out.started = await startOnMac(tools, 'Mac tester') } diff --git a/tests/run/runTimeLimits.test.ts b/tests/run/runTimeLimits.test.ts new file mode 100644 index 0000000000..88a0a64997 --- /dev/null +++ b/tests/run/runTimeLimits.test.ts @@ -0,0 +1,105 @@ +/** + * Issue #685: the running-time limit an agent on another computer gives a run here. `RunTimeLimits` counts only the + * time the run works (not queued, paused, or waiting on a person), stops it once at its limit, and forgets it when it + * ends. The records are an in-memory stand-in for `run_time_limits`; the clock is the test's. + */ +import { describe, expect, it } from 'vitest' +import { RunTimeLimits, runTimeLimitMessage } from '../../src/mms/orchestrator/RunTimeLimits' +import type { RunTimeLimitRecord, RunTimeLimitRecords } from '../../src/mms/run/runTimeLimits' +import type { RunRecord } from '../../src/mms/run/types' + +const TICK = 15_000 + +function setup(limitMinutes = 1) { + const rows = new Map() + const records = { + set: (runId: string, threadId: string, limitMs: number) => { if (!rows.has(runId)) rows.set(runId, { runId, threadId, limitMs, usedMs: 0 }) }, + get: (runId: string) => rows.get(runId) ?? null, + list: () => [...rows.values()].map((row) => ({ ...row })), + has: () => rows.size > 0, + setUsed: (runId: string, usedMs: number) => { rows.get(runId)!.usedMs = usedMs }, + remove: (runId: string) => { rows.delete(runId) } + } as unknown as RunTimeLimitRecords + const world = { now: 0, status: 'running' as string | null, waiting: false, stops: [] as Array<{ threadId: string; runId: string; message: string }> } + const limits = new RunTimeLimits({ + records, + getRun: () => (world.status ? { status: world.status } as RunRecord : null), + waitingOnPerson: () => world.waiting, + stop: async (threadId, runId, message) => { world.stops.push({ threadId, runId, message }) }, + tickMs: TICK, + now: () => world.now + }) + limits.set('run-1', 'thread-1', limitMinutes) + /** Moves the clock on by `ms` and runs one tick. */ + const tick = async (ms = TICK) => { + world.now += ms + await limits.pass() + } + const used = () => rows.get('run-1')?.usedMs + return { world, limits, tick, used, rows } +} + +describe('running-time limits (issue #685)', () => { + it('counts only the time the run works: not queued, not paused, not while a person is asked', async () => { + const { world, tick, used } = setup() + await tick() // the first read only starts counting + expect(used()).toBe(0) + await tick() + expect(used()).toBe(TICK) + for (const status of ['queued', 'paused']) { + world.status = status + await tick() + } + world.status = 'running' + world.waiting = true + await tick() + expect(used()).toBe(TICK) + world.waiting = false + world.status = 'finalizing' + await tick() + expect(used()).toBe(2 * TICK) + }) + + it('a computer that slept or a clock that jumped adds at most two ticks', async () => { + const { tick, used } = setup() + await tick() + await tick(60 * 60_000) + expect(used()).toBe(2 * TICK) + }) + + it('stops the run once at its limit, saying so, and forgets it once the run ended', async () => { + const { world, tick, rows } = setup(1) + await tick() + for (let i = 0; i < 3; i += 1) await tick() + expect(world.stops).toEqual([]) + await tick() + expect(world.stops).toEqual([{ threadId: 'thread-1', runId: 'run-1', message: 'Stopped after its limit of 1 minute of running time.' }]) + // A slow stop is not asked for again on the next tick. + await tick() + expect(world.stops).toHaveLength(1) + world.status = 'cancelled' + await tick() + expect(rows.size).toBe(0) + }) + + it('a retry of the same send keeps what the run used', async () => { + const { limits, tick, used } = setup() + await tick() + await tick() + limits.set('run-1', 'thread-1', 1) + expect(used()).toBe(TICK) + }) + + it('a run that is gone is forgotten without a stop', async () => { + const { world, tick, rows } = setup() + world.status = null + await tick() + expect(rows.size).toBe(0) + expect(world.stops).toEqual([]) + }) + + it('says minutes in words', () => { + expect(runTimeLimitMessage(60_000)).toBe('Stopped after its limit of 1 minute of running time.') + expect(runTimeLimitMessage(45 * 60_000)).toBe('Stopped after its limit of 45 minutes of running time.') + }) +}) diff --git a/tests/sideCardLineage.test.ts b/tests/sideCardLineage.test.ts index 9f6dbb685e..de8dfff814 100644 --- a/tests/sideCardLineage.test.ts +++ b/tests/sideCardLineage.test.ts @@ -194,6 +194,12 @@ describe('lineageStatusLabel', () => { expect(label('interrupted', { updatedAt: minutesAgo(1) })).toBe('Interrupted 1m ago') expect(label('idle', { updatedAt: 'nope' })).toBe('Idle') }) + + it('says a Stop of a subagent on another computer is waiting to reach it', () => { + const computer = { node: 'node-mac', name: 'Studio Mac', online: false, ref: 'node-mac:far-1' } + expect(label('stopped', { computer: { ...computer, stopRequested: true } })).toBe('Stop requested') + expect(label('stopped', { computer })).toBe('Stopped 30m ago') + }) }) describe('lineageSubagentName and lineageModelLabel', () => { diff --git a/tests/threadExpiry.test.ts b/tests/threadExpiry.test.ts index 0e1b865e50..43d5838784 100644 --- a/tests/threadExpiry.test.ts +++ b/tests/threadExpiry.test.ts @@ -120,6 +120,20 @@ describe('thread expiry', () => { await expect(gui('threads.setExpiry', { threadId: child.id, expiresAt: new Date(Date.now() + 3_600_000).toISOString() })).rejects.toMatchObject({ code: 'invalid_params' }) }, 60_000) + // Issue #685: a subagent on another computer expires with its root; a change here is queued for that computer. + it('queues a change of the root\'s expiry for its subagents on other computers', async () => { + const root = mms.threads.createThread('Root', undefined, undefined, { started: true }) + const child = mms.threads.createThread('Mac helper', undefined, undefined, { lineage: { parentThreadId: root.id, rootThreadId: root.id, relationship: 'subagent' } }) + const engine = (mms.orchestrator as unknown as { runEngine: import('../src/mms/run/RunEngine').RunEngine }).runEngine + engine.remoteExpiry.track({ childThreadId: child.id, rootThreadId: root.id, node: 'node-mac', expiresAt: null, stopsRun: false }) + engine.remoteExpiry.setRemoteThread(child.id, 'far-thread-1') + const expiresAt = new Date(Date.now() + 3_600_000).toISOString() + await gui('threads.setExpiry', { threadId: root.id, expiresAt, stopsRun: true }) + expect(engine.remoteExpiry.get(child.id)).toMatchObject({ state: 'pending', expiresAt, stopsRun: true, generation: 2 }) + await gui('threads.setExpiry', { threadId: root.id, expiresAt: null }) + expect(engine.remoteExpiry.get(child.id)).toMatchObject({ state: 'pending', expiresAt: null, stopsRun: false, generation: 3 }) + }, 60_000) + it('refuses a message to an expired thread', async () => { const thread = mms.threads.createThread('Gone soon', undefined, undefined, { started: true, expiresAt: new Date(Date.now() - 1000).toISOString() }) await expect(mms.orchestrator.send({ content: 'hello' } as never, false, { threadId: thread.id } as never)).rejects.toMatchObject({ code: 'thread_expired' })