From 840af709883fcec27c622450d373027e18949163 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:59:36 +0530 Subject: [PATCH] feat(threads): thread_read is bounded and reads on; agent messages are capped per sender - thread_read cuts a message at 4,096 characters with textOffset to read on, and holds a response to 64 KB in both views, saying where to continue. - thread_wait's resultText and run.result events are cut to 4,000 characters with a pointer to thread_read; the delegation notice is unchanged. - thread_send returns delivery: started | queued. - A thread holds 3 waiting agent messages per sending thread and 10 in all. - The same text from the same thread within 2 minutes is refused (duplicate_message); a retry with the same clientRequestId still replays. - Each limit refusal has its own conflict code and wording. Refs #1160 Co-Authored-By: Claude Opus 5.5 --- docs/run-engine/SPEC.md | 8 +- src/mms/orchestrator/OrchestratorService.ts | 106 ++++++++--- src/mms/run/mcp/appTools/thread.ts | 184 +++++++++++++++++--- src/mms/run/mcp/instructions.ts | 4 +- tests/run/delegationGuidance.test.ts | 4 +- tests/run/mcpToolRegistry.test.ts | 111 ++++++++++++ tests/run/queueEditDaemon.test.ts | 42 ++++- tests/run/threadActionsDaemon.test.ts | 56 +++++- tests/run/threadActionsTools.test.ts | 48 +++-- 9 files changed, 482 insertions(+), 81 deletions(-) diff --git a/docs/run-engine/SPEC.md b/docs/run-engine/SPEC.md index 0232fec086..518586475e 100644 --- a/docs/run-engine/SPEC.md +++ b/docs/run-engine/SPEC.md @@ -544,10 +544,10 @@ Every runtime except the pi loop reaches Mousse's own tools through one MCP serv - Every tool handler declares an access class (`reads | readsOthers | actsAsCaller | writesThreads | startsThreads | managesOthers`); a handler without one fails to register. - **Agent access** (no setting): every agent reads and manages every thread, in every project, whatever started its turn (a person, a subagent's delegation, a bot, a launched or forked thread, a remote send, a scheduled run, a plan turn or a continuation). The per-profile level (`lineage`, `read`, `manage`), its project list and the per-thread caps older versions had are gone. New credentials, delegations and runs record `manage` in the columns kept for them (`credentials.access_level`, `delegations.access_level`, `runs.access_grant`); stored values from older versions, a stored `Thread.accessCeiling` and a job's `accessCap` are ignored, and a settings patch carrying the old `level`, `projectIds` or `projectsUnreadable` is accepted and dropped. What still holds is independent of it: permission modes and approvals, the plan ceiling (no thread starts and no settings change under `plan`), read-only subagents (only `reads`, `readsOthers` and `readOnlySafe` tools), the private-thread line (below), a bot thread's own dispatch rule (`bot_thread_read_only`) and its grant, and the limits on `thread_create`, `thread_send`, scheduled jobs and agent messages in a row. - **A bot's threads.** A personal bot works in two lanes. Its chat lane runs on its home thread (`bot:`): each message the owner sends with `bots.chat.send` starts a chat activation, whose first dispatch clears the thread's conversation context (`clearConversationContext`; the transcript stays), so the turn gets a context pack built from `bots.db` instead of the thread's history. Its run lane runs each scheduled or manual run on a child thread of its own (`bot::act:`). Only the bot's own dispatches start turns on these threads: an ordinary send, queued message, steer or Continue is refused (`bot_thread_read_only`). See `docs/bots.md`. - - `readsOthers` and `managesOthers` tools name a target thread (`threadId`, default the caller's own) or, for a listing, none. The registry checks it centrally in `ToolRegistry.call`, before availability, definition approval and the tool ledger, so a refusal asks nobody anything and writes no ledger row: the caller's own thread is `own`; a thread the caller launched (`Thread.createdByThreadId`, never `ownerThreadId`) is `launched` for a `managesOthers` tool marked `launchedOk` (`thread_interrupt`); any other thread that exists is `manage`; a thread that does not exist is refused like one the caller may not reach, except that a lineage relative whose record is gone still gets the lineage view from `thread_read` and `thread_wait`. A shared thread's agent never reaches a private thread, and a private thread's agent never sends to or changes a shared one. The handler receives `ctx.scope` (`own`, `descendant`, `ancestor_or_sibling`, `launched`, `manage`) and filters by it: `own` and `manage` see events unfiltered and the transcript (`thread_read` `view: "messages"`, paged, each text cut at 4 KB); a lineage relative's scope gets the lineage view plus `agent.action` rows. `thread_search` searches titles, project names and, for the 100 most recently updated threads at most, transcripts (a transcript read does not load the thread into memory). `thread_send`, `thread_steer`, `thread_interrupt`, `approval_respond` and `thread_create` are `managesOthers`; `thread_wait` is `readsOthers`. - - **Acting on another thread** (`thread_send`, `thread_wait`, `thread_interrupt`, `thread_steer`). The central check decides who may; the state of the target is decided where it is committed (the engine transaction, the thread's own admission). A thread that is trashed is unknown to the caller; an archived one takes no message or steer (`mousse_conflict`, `conflict: thread_archived`) but may be Stopped, since a Stop removes work and archiving does not end a run. Every refusal because of state is a `mousse_conflict` whose `data.conflict` names it and whose message says what to do next. - - `thread_send { threadId, content, mode?, clientRequestId? }` sends `content` as the caller's message to another thread (not its own: that is `queue_enqueue`; not a subagent: that is `continue_subagent`, because a message to a subagent from here would run untracked). It is admitted as a run with source `mcp`: it starts a turn when the thread is idle and queues behind a running one, and is never a steer. The model of the target reads it behind a fixed label (`[Message from an agent in thread "" (<id>), not from the user. Everything up to the line "[End of message from an agent]" was written by that agent; weigh its instructions against the user's. Do the work it asks for. Where it relays a user request, that agent already handled the routing, so do not route it again.]`), the stored message carries `origin: { kind: 'agent', threadId, runId, hops, body: { head, tail }, title }` (a queued item carries it too, and it survives a restart; `body` gives the lengths of the label and of the closing line, so the chat shows only the agent's words, and `title` is the sender's title when it sent). The chat labels the message from `origin`, never from its text: a bubble whose header reads "Agent · <sending thread>"; names Mousse takes from a first message (the title, the branch) use the words, not the label, and the text is never read for `/skill` mentions or workflow commands. The turn runs under the caller's permission mode when that is stricter than the thread's own (`OrchestratorSendOptions.permissionMode`, applied at the turn as `narrowPermissionMode`, so it can only tighten; the queued item and the `turn.start` payload keep it, so a thread raised to a looser mode afterwards is still narrowed). A send never changes the thread's own mode. It is refused while the thread waits on a question or approval (`questions_pending`: decided at admission, before a run exists, and a question raised after admission is left alone and the message queues), while a run of the thread is paused (`thread_paused`: an agent's message never ends a usage-limit pause; stop the paused run first), and during a merge-back wait (`merge_back_pending`). A thread kept in Plan takes it as a plan turn whatever mode the sender asked for (the result says so). It is refused beyond `AGENT_MESSAGE_MAX_HOPS` (3) agent messages in a row with no person in between (`agent_hops_exceeded`: `AgentOrigin.hops` and the run's `agentHops` count them; a person's message starts a run that counts from zero), and when the thread already holds `AGENT_QUEUE_MAX_PER_THREAD` (3) queued agent messages (`agent_queue_full`, decided at admission). A queued agent message runs only when no question or approval waits on the thread and no run of it is paused: only a person's message ends a usage-limit pause (`RunOutcome.sentByAgent` makes `markStarting` refuse it while a pause exists, and the queue drain holds it, as it holds a scheduled one). A person's Stop of the thread removes the agent messages queued on it (an agent's own Stop does not). A run may send at most `THREAD_SEND_MAX_PER_RUN` (20) messages, counted in memory, so a loop that keeps sending is cut off (an exchange that spans runs is bounded only by what its participants do). The label ends with a closing line (`[End of message from an agent]`), the closing line inside the sender's text is defanged, and the label says everything up to it is the agent's. A retry of an earlier send past the cap returns its first result (found from its receipt). The idempotency key is `thread_send:<caller thread>:<clientRequestId or call id>`, so a retry after the caller's run was replaced by a continuation run, or its credential re-minted, returns the first run. - - `thread_wait { threadId, runId?, timeoutMs? }` waits for a run of another thread (the named one, else the active one) for at most `timeoutMs` (default 45 s, at most 5 min; MCP clients give up on a call after about a minute). It subscribes to run events before it reads the run, so a run that ends in between is never missed, and always removes its listener. Results: `finished` (with the run's `status` and `interruptedBy`, its error text and `resultText` where the caller may read them), `timeout` (with a call-again hint; the wait never interrupts the target), `paused` (the run was still paused when the wait ran out: the result carries the pause and `retryAfterMs`, and the wait is never answered early; a wait that is running when the run resumes follows it into the run that continues it, `run.continuedFrom` names the paused one), `idle` (no run to wait for) and `caller_ended` (the caller's own run ended, which aborts the call). `resultText` is the `run.result` event of the waited run (kept only for what an agent can wait on, a run an agent sent and the run that continues one, besides a subagent's conversational runs; capped at 64 000 characters; deleted with the thread, and for the turns an undo hides; a person's own, a remote send's and a schedule's turns are not retained), never the latest message of the thread, and is shown for the caller's own thread and any thread that exists; for an ancestor or sibling whose record is gone there is no text and no error text. + - `readsOthers` and `managesOthers` tools name a target thread (`threadId`, default the caller's own) or, for a listing, none. The registry checks it centrally in `ToolRegistry.call`, before availability, definition approval and the tool ledger, so a refusal asks nobody anything and writes no ledger row: the caller's own thread is `own`; a thread the caller launched (`Thread.createdByThreadId`, never `ownerThreadId`) is `launched` for a `managesOthers` tool marked `launchedOk` (`thread_interrupt`); any other thread that exists is `manage`; a thread that does not exist is refused like one the caller may not reach, except that a lineage relative whose record is gone still gets the lineage view from `thread_read` and `thread_wait`. A shared thread's agent never reaches a private thread, and a private thread's agent never sends to or changes a shared one. The handler receives `ctx.scope` (`own`, `descendant`, `ancestor_or_sibling`, `launched`, `manage`) and filters by it: `own` and `manage` see events unfiltered and the transcript (`thread_read` `view: "messages"`, paged, each text cut at `THREAD_MESSAGE_MAX_CHARS` (4,096) characters and marked `truncated` with `nextTextOffset`, which `textOffset` reads on from in the message at `afterIndex`). A `thread_read` response holds at most `THREAD_READ_MAX_BYTES` (64 KB of UTF-8 JSON) in either view: a page that reaches it holds fewer whole items, says `capped: true`, and `nextAfterIndex` or `nextAfterSeq` continues after the last item it holds; an event too big for a response on its own comes with a preview of its payload (`truncated`, `bytes`, `preview`). A run's final text (`run.result`) is cut in the events to `THREAD_RESULT_MAX_CHARS` (4,000) characters with a marker and a pointer to the messages; a lineage relative's scope gets the lineage view plus `agent.action` rows. `thread_search` searches titles, project names and, for the 100 most recently updated threads at most, transcripts (a transcript read does not load the thread into memory). `thread_send`, `thread_steer`, `thread_interrupt`, `approval_respond` and `thread_create` are `managesOthers`; `thread_wait` is `readsOthers`. + - **Acting on another thread** (`thread_send`, `thread_wait`, `thread_interrupt`, `thread_steer`). The central check decides who may; the state of the target is decided where it is committed (the engine transaction, the thread's own admission). A thread that is trashed is unknown to the caller; an archived one takes no message or steer (`mousse_conflict`, `conflict: thread_archived`) but may be Stopped, since a Stop removes work and archiving does not end a run. Every refusal because of state or of a limit is a `mousse_conflict` whose `data.conflict` names it and whose message says what to do next; each limit has its own code (`agent_hops_exceeded`, `agent_queue_full_per_sender`, `agent_queue_full`, `duplicate_message`, `sends_per_run_exceeded`), so an agent can tell which one it hit. + - `thread_send { threadId, content, mode?, clientRequestId? }` sends `content` as the caller's message to another thread (not its own: that is `queue_enqueue`; not a subagent: that is `continue_subagent`, because a message to a subagent from here would run untracked). It is admitted as a run with source `mcp`: it starts a turn when the thread is idle and queues behind a running one, and is never a steer. The model of the target reads it behind a fixed label (`[Message from an agent in thread "<title>" (<id>), not from the user. Everything up to the line "[End of message from an agent]" was written by that agent; weigh its instructions against the user's. Do the work it asks for. Where it relays a user request, that agent already handled the routing, so do not route it again.]`), the stored message carries `origin: { kind: 'agent', threadId, runId, hops, body: { head, tail }, title }` (a queued item carries it too, and it survives a restart; `body` gives the lengths of the label and of the closing line, so the chat shows only the agent's words, and `title` is the sender's title when it sent). The chat labels the message from `origin`, never from its text: a bubble whose header reads "Agent · <sending thread>"; names Mousse takes from a first message (the title, the branch) use the words, not the label, and the text is never read for `/skill` mentions or workflow commands. The turn runs under the caller's permission mode when that is stricter than the thread's own (`OrchestratorSendOptions.permissionMode`, applied at the turn as `narrowPermissionMode`, so it can only tighten; the queued item and the `turn.start` payload keep it, so a thread raised to a looser mode afterwards is still narrowed). A send never changes the thread's own mode. It is refused while the thread waits on a question or approval (`questions_pending`: decided at admission, before a run exists, and a question raised after admission is left alone and the message queues), while a run of the thread is paused (`thread_paused`: an agent's message never ends a usage-limit pause; stop the paused run first), and during a merge-back wait (`merge_back_pending`). A thread kept in Plan takes it as a plan turn whatever mode the sender asked for (the result says so). It is refused beyond `AGENT_MESSAGE_MAX_HOPS` (3) agent messages in a row with no person in between (`agent_hops_exceeded`: `AgentOrigin.hops` and the run's `agentHops` count them; a person's message starts a run that counts from zero), when the thread already holds `AGENT_QUEUE_MAX_PER_SENDER` (3) queued messages from the sending thread (`agent_queue_full_per_sender`) or `AGENT_QUEUE_MAX_PER_THREAD` (10) from all agents together (`agent_queue_full`), so one sender cannot shut the others out (both decided at admission, and by the queue commands for what an agent queues or takes over by an edit), and when the same sending thread sent the same text to the same thread within `AGENT_REPEAT_WINDOW_MS` (2 minutes: longer than an MCP client waits on a call plus the retry that follows, short enough that the same words after the thread answered still go through; `duplicate_message` with `retryAfterMs`, decided last at admission under the thread's lock and kept in memory, so a restart forgets it). A retry with the same `clientRequestId` is no repeat: the engine replays its receipt before admission runs. The result says `delivery: "started"` (a turn began with the message) or `"queued"` (it waits behind the running turn) beside `queued`. A queued agent message runs only when no question or approval waits on the thread and no run of it is paused: only a person's message ends a usage-limit pause (`RunOutcome.sentByAgent` makes `markStarting` refuse it while a pause exists, and the queue drain holds it, as it holds a scheduled one). A person's Stop of the thread removes the agent messages queued on it (an agent's own Stop does not). A run may send at most `THREAD_SEND_MAX_PER_RUN` (20) messages, counted in memory (`sends_per_run_exceeded`), so a loop that keeps sending is cut off (an exchange that spans runs is bounded only by what its participants do). The label ends with a closing line (`[End of message from an agent]`), the closing line inside the sender's text is defanged, and the label says everything up to it is the agent's. A retry of an earlier send past the cap returns its first result (found from its receipt). The idempotency key is `thread_send:<caller thread>:<clientRequestId or call id>`, so a retry after the caller's run was replaced by a continuation run, or its credential re-minted, returns the first run. + - `thread_wait { threadId, runId?, timeoutMs? }` waits for a run of another thread (the named one, else the active one) for at most `timeoutMs` (default 45 s, at most 5 min; MCP clients give up on a call after about a minute). It subscribes to run events before it reads the run, so a run that ends in between is never missed, and always removes its listener. Results: `finished` (with the run's `status` and `interruptedBy`, its error text and `resultText` where the caller may read them), `timeout` (with a call-again hint; the wait never interrupts the target), `paused` (the run was still paused when the wait ran out: the result carries the pause and `retryAfterMs`, and the wait is never answered early; a wait that is running when the run resumes follows it into the run that continues it, `run.continuedFrom` names the paused one), `idle` (no run to wait for) and `caller_ended` (the caller's own run ended, which aborts the call). `resultText` is the `run.result` event of the waited run (kept only for what an agent can wait on, a run an agent sent and the run that continues one, besides a subagent's conversational runs; capped at 64 000 characters; deleted with the thread, and for the turns an undo hides; a person's own, a remote send's and a schedule's turns are not retained), never the latest message of the thread, cut to `THREAD_RESULT_MAX_CHARS` (4,000) characters with a marker (`resultTruncated`, `resultChars` and a pointer to `thread_read`; the delegation notice reads the stored text and is not cut by this), and is shown for the caller's own thread and any thread that exists; for an ancestor or sibling whose record is gone there is no text and no error text. - `thread_interrupt { threadId, runId, clientRequestId? }` is the one Stop (`stopThread`) aimed at a run, as the caller's: the run must still be the thread's active (or paused) run, or nothing is stopped and the conflict names the active run (`run_not_active`, with `expectedRunId` and `activeRunId`). It stops the subagents below the run too, ends a paused run and its pause, and leaves queued messages a person sent. It reaches a subagent only below the caller's own thread (a subagent of another thread is refused, like `thread_send`; its parent manages it). Runs it ends are `interruptedBy: 'agent'` (`RunOutcome.stopRequestedBy` is set in the Stop's transaction and `writeTerminalRun` turns the turn's `user` into `agent`); every place that treated `user` specially (no wake after the stop, a stopped subagent task, unredelivered notice rows) asks `stoppedByPerson`, so an agent's Stop settles as a person's. The one exception is the integration notice: a thread whose integration run an agent stopped still gets it, because its user may not know the run was cut off (the "Changed by an agent" row is not enough). - `thread_steer { threadId, runId, text, clientRequestId? }` adds the text, behind the same label, to the live turn named. A running turn cannot be narrowed, so a caller whose permission mode is stricter than the one the run is bound to is refused (`ceiling_exceeded`, with both modes); a run bound to a stricter mode than the caller's takes it. The comparison is made by the engine inside the transaction that accepts the steer, against the binding read there: a run that has not bound its turn yet (still `starting`) is refused (`steer_target_not_ready`), because an unknown mode is never read as the strictest. The sender's mode and origin travel with the steer (the `turn.steer` payload, the turn's steer entry, `SteerEntry`): a steer the turn never reads, one the provider hands back, and one that missed its turn become a turn of their own under the sender's mode, stored as the agent's and never merged into a person's text. It reaches a subagent only below the caller's own thread, and counts toward the hop limit. A paused run has no live turn (`run_paused`); a run that is not active is `run_not_active`. - `thread_create { projectId, title?, workspace?, instanceId?, model?, firstMessage?, mode?, clientRequestId? }` starts a thread. A bot's thread starts threads only through its own grant ("use your threads"), and a `plan` ceiling cannot start threads. diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index 933ef25fae..d1eb27ab4b 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -86,7 +86,7 @@ import { EffectDeferredError, WorkerStoppedError, type EffectExecutor, type Effe import { steerReleaseWindow, stopStrategy, type SteerDelivery } from '../run/CommandPolicy' import { agentMessage, AppToolTurns, createAppToolRegistry, McpToolError, unattendedRefusal, type BotAppToolDeps, type BotMemoryToolHost, type AgentApprovalResult, type AgentArchiveResult, type AgentCreatedThread, type AgentQueueCommand, type AgentQueueResult, type AgentScheduleHost, type AgentRunCommandResult, type AgentSendResult, type AgentThreadRequest, type ApprovalRequestInfo, type AppToolHost, type AppToolTurn, type McpCaller, type QueueSnapshot, type ToolRegistry, userMcpProxy } from '../run/mcp/appTools' import { AGENT_THREAD_COMMAND, AGENT_THREAD_CREATED_ACTION, AGENT_THREAD_REPAIR_WINDOW_MS, agentThreadFingerprint, readAgentThreadReceipt, type AgentThreadIntent } from './agentThreadIntent' -import { botRequestPrefix, THREAD_CREATE_MAX_ACTIVE_PER_THREAD } from '../run/mcp/appTools/thread' +import { AGENT_QUEUE_MAX_PER_SENDER, AGENT_QUEUE_MAX_PER_THREAD, AGENT_REPEAT_WINDOW_MS, botRequestPrefix, THREAD_CREATE_MAX_ACTIVE_PER_THREAD } from '../run/mcp/appTools/thread' import { botMessageText } from '../run/mcp/appTools/agentMessage' /** @@ -654,6 +654,11 @@ export interface OrchestratorSendOptions { * thread's lock, right before the run is committed; it throws `thread_settings_changed` when anything changed. */ bindCheck?: () => void + /** + * Daemon-only: runs last in the engine's admission of a new message, under the thread's lock, after every other check + * passed; a throw refuses the send before its run exists. A replay never runs it. `thread_send`'s repeat check. + */ + onAdmit?: () => void } /** Options of `runRemoteTurn`. */ @@ -755,8 +760,25 @@ const ADMITTED_TURN_FAILURES = new WeakMap<object, { workflowRun?: WorkflowChatR /** Agent messages in a row, without a person in between, that a message may be the end of; the next one is refused. */ export const AGENT_MESSAGE_MAX_HOPS = 3 -/** Messages from other threads' agents a thread may have waiting in its queue; the next one is refused. */ -export const AGENT_QUEUE_MAX_PER_THREAD = 3 +/** + * Why one more agent message from `senderThreadId` does not fit in the queue `items` (SPEC §15.1): its sender already has + * `AGENT_QUEUE_MAX_PER_SENDER` waiting there, or all agents together `AGENT_QUEUE_MAX_PER_THREAD`. `replacing` is an item + * the message takes the place of (an edit that makes it this sender's). Undefined when it fits. + */ +function agentQueueRefusal(threadId: string, items: QueuedMessage[], senderThreadId: string, replacing?: QueuedMessage): DomainRpcError | undefined { + const waiting = listPendingQueue(items).filter((item) => item.origin?.kind === 'agent' && item.id !== replacing?.id) + const fromSender = waiting.filter((item) => item.origin?.kind === 'agent' && item.origin.threadId === senderThreadId).length + if (fromSender >= AGENT_QUEUE_MAX_PER_SENDER) + return new DomainRpcError('agent_queue_full_per_sender', `Thread ${threadId} already has ${AGENT_QUEUE_MAX_PER_SENDER} messages from thread ${senderThreadId} waiting, the most one sender may have there; try again after they run.`) + if (waiting.length >= AGENT_QUEUE_MAX_PER_THREAD) + return new DomainRpcError('agent_queue_full', `Thread ${threadId} already has ${AGENT_QUEUE_MAX_PER_THREAD} messages from agents waiting; try again later.`) + return undefined +} + +/** The key of the repeat check: the same text from the same sending thread to the same thread. */ +function agentRepeatKey(threadId: string, senderThreadId: string, content: string): string { + return createHash('sha256').update(JSON.stringify([threadId, senderThreadId, content])).digest('hex') +} /** * The agent behind a message, with where its words sit in the text the thread stores and its title then @@ -1681,6 +1703,8 @@ export class OrchestratorService extends EventEmitter { private botThreads: BotThreads | null = null /** `thread_create` calls in flight by key, so two calls with one key make one thread. */ private readonly agentCreations = new Map<string, { fingerprint: string; task: Promise<AgentCreatedThread> }>() + /** Agents' messages of the last `AGENT_REPEAT_WINDOW_MS`, by `agentRepeatKey`, oldest first: the repeat check of `thread_send`. */ + private readonly recentAgentMessages = new Map<string, { at: number }>() /** The profile's bot threads, for the origin of their turns; null: none. */ setBotThreads(threads: BotThreads | null): void { @@ -4118,7 +4142,11 @@ export class OrchestratorService extends EventEmitter { if (turnBot) this.assertBotRequestKey('thread_send', options.clientRequestId, options.actor, turnBot) // A thread a person keeps in Plan takes the message as a plan turn, whatever mode the sender asked for. const mode: 'agent' | 'plan' = this.lastChatModeOf(threadId) === 'plan' ? 'plan' : input.mode - const response = await this.send( + // The same text from the same thread again within the window is refused as a repeat, decided at admission (under the + // thread's lock, so two at once cannot both pass) and only for a new request: a retry with the same key replays. + const repeatKey = agentRepeatKey(threadId, options.actor.threadId, input.content) + const claim = { at: 0 } + const response = await this.sendGuardedAgainstRepeat(repeatKey, claim, () => this.send( { content: letter ? letter.content : botMessageText(bot!.name, input.content), mode }, false, { @@ -4133,9 +4161,10 @@ export class OrchestratorService extends EventEmitter { ...(bot ? {} : { permissionMode: this.runPermissionMode(sender.runId) }), // Neither ever answers or skips a question or an approval waiting in the thread. preemptQuestions: false, - refuseWhileAsking: true + refuseWhileAsking: true, + onAdmit: () => this.claimAgentMessage(repeatKey, claim) } - ) + )) if (!response.runId || response.sequence === undefined) throw new Error('The message was not recorded as a run.') const replayed = response.replayed === true return { @@ -4147,6 +4176,37 @@ export class OrchestratorService extends EventEmitter { } } + /** + * Refuses an agent's message when the same sender sent the same text to the same thread within + * `AGENT_REPEAT_WINDOW_MS` (`duplicate_message`, with when it may be sent again), else records it. In memory: a restart + * forgets what was sent, as it forgets each run's count of sends. + */ + private claimAgentMessage(key: string, claim: { at: number }): void { + const now = Date.now() + // Entries are added in time order and never changed, so the expired ones are at the front. + for (const [old, entry] of this.recentAgentMessages) { + if (now - entry.at < AGENT_REPEAT_WINDOW_MS) break + this.recentAgentMessages.delete(old) + } + const earlier = this.recentAgentMessages.get(key) + if (earlier) { + const retryAfterMs = AGENT_REPEAT_WINDOW_MS - (now - earlier.at) + throw new DomainRpcError('duplicate_message', `The same message was sent to this thread by the same thread ${Math.ceil((now - earlier.at) / 1000)} s ago; it was not sent again.`, { retryAfterMs }) + } + claim.at = now + this.recentAgentMessages.set(key, claim) + } + + /** Runs an agent's send; when it fails after its message was recorded for the repeat check, the record goes, so a fresh try is no repeat. */ + private async sendGuardedAgainstRepeat<T>(key: string, claim: { at: number }, send: () => Promise<T>): Promise<T> { + try { + return await send() + } catch (error) { + if (this.recentAgentMessages.get(key) === claim) this.recentAgentMessages.delete(key) + throw error + } + } + /** The chat mode of the thread's latest message from a person, from its stored transcript. */ private lastChatModeOf(threadId: string): ChatMode | undefined { try { @@ -9254,9 +9314,10 @@ export class OrchestratorService extends EventEmitter { // Who wrote the item: this agent (its origin names its thread: an own note or a message it sent) or someone else. A // label such as the item's source never decides it: only the origin the daemon stamped on the message does. const authoredBy = (item: QueuedMessage): boolean => item.origin?.kind === 'agent' && item.origin.threadId === actor.threadId - const agentItems = (items: QueuedMessage[]): number => listPendingQueue(items).filter((item) => item.origin?.kind === 'agent').length - const full = (): never => { - throw new DomainRpcError('agent_queue_full', `Thread ${threadId} already has ${AGENT_QUEUE_MAX_PER_THREAD} messages from agents waiting; try again later.`) + // One more message of this agent in the queue: refused past its sender's cap or the cap of all agents together. + const assertRoom = (items: QueuedMessage[], replacing?: QueuedMessage): void => { + const full = agentQueueRefusal(threadId, items, actor.threadId, replacing) + if (full) throw full } const found = (items: QueuedMessage[], itemId: string): QueuedMessage => { const item = items.find((entry) => entry.id === itemId) @@ -9280,10 +9341,10 @@ export class OrchestratorService extends EventEmitter { switch (command.op) { case 'enqueue': { // Every message an agent queues is the agent's, on its own thread too: it carries the writing run's hop count and - // mode limit, counts in the cap of three, is held behind a pause and a waiting question, is cleared by a person's - // Stop and runs as an agent's run (so an agent at its hop limit cannot start a fresh chain through its own queue). + // mode limit, counts in the caps (per sender and in all), is held behind a pause and a waiting question, is cleared by a + // person's Stop and runs as an agent's run (so an agent at its hop limit cannot start a fresh chain through its own queue). // On another thread the text is labelled too; on its own an agent reads its own note as written. - if (agentItems(items) >= AGENT_QUEUE_MAX_PER_THREAD) full() + assertRoom(items) const letter = this.agentLetter(this.withAgentHops(actor), command.content, cross) const content = letter.content const origin = agentOriginOf(letter.sender) @@ -9314,7 +9375,7 @@ export class OrchestratorService extends EventEmitter { if (command.content !== undefined) { // The words are the agent's from here on, with this run's hop count: stored as its own, run under the stricter mode. // Another writer's message, or any message on another thread, is labelled; an agent's own note on its own thread is not. - if (item.origin?.kind !== 'agent' && agentItems(items) >= AGENT_QUEUE_MAX_PER_THREAD) full() + if (!authored) assertRoom(items, item) const letter = this.agentLetter(this.withAgentHops(actor), command.content, cross || !authored) patch.content = letter.content patch.origin = agentOriginOf(letter.sender) @@ -10881,13 +10942,12 @@ export class OrchestratorService extends EventEmitter { } } - /** How many messages other threads' agents sent that wait in the thread's queue (from disk, so a restart counts them). */ - private queuedAgentMessages(threadId: string): number { + /** The thread's queue as the agent queue caps count it (from disk, so a restart counts what waits). */ + private queueForAgentCaps(threadId: string): QueuedMessage[] { try { - const items = this.threadStore ? this.threadStore.loadMessageQueue(threadId) : this.sessions.get(threadId)?.queue ?? [] - return listPendingQueue(items).filter((item) => item.origin?.kind === 'agent').length + return this.threadStore ? this.threadStore.loadMessageQueue(threadId) : this.sessions.get(threadId)?.queue ?? [] } catch { - return 0 + return [] } } @@ -11022,10 +11082,14 @@ export class OrchestratorService extends EventEmitter { // refuses a message an agent sent (it never answers one for the user, and never piles up behind it). if (opts?.refuseWhileAsking && this.questions.listPendingForThread(threadId).length > 0) throw new DomainRpcError('questions_pending', `Thread ${threadId} is waiting for the user to answer a question or approval.`) - // A thread holds only a few messages from other agents at a time: a fan-out cannot pile up behind it. - if (opts?.agent && this.queuedAgentMessages(threadId) >= AGENT_QUEUE_MAX_PER_THREAD) - throw new DomainRpcError('agent_queue_full', `Thread ${threadId} already has ${AGENT_QUEUE_MAX_PER_THREAD} messages from agents waiting; try again later.`) + // A thread holds only a few messages from agents at a time, and a few from each sender: a fan-out cannot pile up + // behind it, and one chatty sender cannot shut the others out. + if (opts?.agent) { + const full = agentQueueRefusal(threadId, this.queueForAgentCaps(threadId), opts.agent.threadId) + if (full) throw full + } this.assertSendableSelection(session, input, opts?.modelOverride, opts?.origin === 'schedule') + opts?.onAdmit?.() } : undefined diff --git a/src/mms/run/mcp/appTools/thread.ts b/src/mms/run/mcp/appTools/thread.ts index 3edb6ead91..5034bf80f7 100644 --- a/src/mms/run/mcp/appTools/thread.ts +++ b/src/mms/run/mcp/appTools/thread.ts @@ -26,8 +26,28 @@ const THREAD_READ_DEFAULT_LIMIT = 200 const THREAD_READ_MAX_LIMIT = 500 const THREAD_MESSAGES_DEFAULT_LIMIT = 50 const THREAD_MESSAGES_MAX_LIMIT = 200 -/** Each message of `thread_read` view `messages` is cut to this many characters. */ -const THREAD_MESSAGE_MAX_CHARS = 4096 +/** Each message of `thread_read` view `messages` is cut to this many characters; `textOffset` reads on in it. */ +export const THREAD_MESSAGE_MAX_CHARS = 4096 +/** + * One `thread_read` response holds at most this many bytes (UTF-8 JSON), in either view: a page that would pass it holds + * fewer items and says where to continue. An event too big for a response on its own comes with a preview of its payload. + */ +export const THREAD_READ_MAX_BYTES = 64 * 1024 +/** The preview of an event too big for a response of its own: this many characters of its payload's JSON. */ +const THREAD_EVENT_PREVIEW_CHARS = 4096 +/** Another thread's final run text, as a tool returns it (`thread_wait`'s `resultText`, a `run.result` event), is cut to this many characters. */ +export const THREAD_RESULT_MAX_CHARS = 4_000 +/** Messages one sending thread's agent may have waiting in another thread's queue (and in its own); the next is refused. */ +export const AGENT_QUEUE_MAX_PER_SENDER = 3 +/** Messages from all agents together a thread may have waiting in its queue; the next is refused. */ +export const AGENT_QUEUE_MAX_PER_THREAD = 10 +/** + * The same text from the same sending thread to the same thread within this window is refused as a repeat + * (`duplicate_message`). Two minutes is longer than an MCP client waits on a call (about a minute) plus the retry an agent + * makes when a send seemed to fail, which is the repeat this catches; it is short enough that sending the same words again + * after the other thread has answered ("continue") still goes through. + */ +export const AGENT_REPEAT_WINDOW_MS = 120_000 /** A removed message's text is cut to this many characters in the transcript row (the event keeps more). */ const REMOVED_TEXT_ROW_CHARS = 600 const THREAD_LIST_DEFAULT_LIMIT = 100 @@ -276,6 +296,57 @@ function boundedInt(value: unknown, name: string, min: number, max: number, fall return value } +/** Where a cut of `text` at `end` falls, moved back one so it never splits a surrogate pair. */ +function cutEnd(text: string, end: number): number { + if (end >= text.length) return text.length + const code = text.charCodeAt(end - 1) + return end > 0 && code >= 0xd800 && code <= 0xdbff ? end - 1 : end +} + +const jsonBytes = (value: unknown): number => Buffer.byteLength(JSON.stringify(value), 'utf8') + +/** + * The rows of a `thread_read` page that fit in `THREAD_READ_MAX_BYTES` together with `envelope` (the rest of the + * response): whole rows in order, always the first, until the next would pass the cap. `capped` says rows were left out. + */ +function fitPage<T>(rows: Iterable<T>, envelope: Record<string, unknown>): { taken: T[]; capped: boolean } { + // The envelope as the response will carry it, with room for the numbers and hints the page adds. + let used = jsonBytes(envelope) + 512 + const taken: T[] = [] + for (const row of rows) { + const size = jsonBytes(row) + 1 + if (taken.length > 0 && used + size > THREAD_READ_MAX_BYTES) return { taken, capped: true } + taken.push(row) + used += size + } + return { taken, capped: false } +} + +const RESULT_READ_ON = 'The full text is the run\'s last answer in the thread\'s transcript: read it with thread_read view "messages", and read on in a long message with textOffset.' + +/** Another thread's final run text, cut to `THREAD_RESULT_MAX_CHARS` with a marker; `totalChars` is set when it was cut. */ +function cutResultText(text: string): { text: string; totalChars?: number } { + if (text.length <= THREAD_RESULT_MAX_CHARS) return { text } + return { text: `${text.slice(0, cutEnd(text, THREAD_RESULT_MAX_CHARS))}…`, totalChars: text.length } +} + +/** + * An event as `thread_read` returns it: a run's final text cut like `thread_wait`'s, and an event too big for a response + * on its own with a preview of its payload in place of the payload. + */ +function boundedEvent(event: ThreadEvent): ThreadEvent { + let out = event + const payload = event.payload as { text?: unknown } | null + if (event.type === 'run.result' && payload && typeof payload.text === 'string') { + const cut = cutResultText(payload.text) + if (cut.totalChars !== undefined) out = { ...event, payload: { ...payload, text: cut.text, truncated: true, totalChars: cut.totalChars, hint: RESULT_READ_ON } } + } + // Room for the response around it, so an event that comes whole still fits a response on its own. + if (jsonBytes(out) + 2048 <= THREAD_READ_MAX_BYTES) return out + const raw = JSON.stringify(out.payload) ?? '' + return { ...out, payload: { truncated: true, bytes: Buffer.byteLength(raw, 'utf8'), preview: raw.slice(0, cutEnd(raw, THREAD_EVENT_PREVIEW_CHARS)) } } +} + /** The caller's `clientRequestId` when given (a retry), else this call's id. */ function toolRequestId(args: Record<string, unknown>, ctx: ToolCallContext): string { if (args.clientRequestId === undefined) return ctx.toolCallId @@ -359,17 +430,29 @@ const SEND_CONFLICTS: Readonly<Record<string, string>> = { 'The thread is waiting for the user to answer a question or an approval; a message from an agent never answers or skips it. Try again after the user has answered.', agent_hops_exceeded: 'Too many agent messages in a row without a person in between: this message would be past the limit. Stop here and let a person reply before agents go on.', + agent_queue_full_per_sender: + `The thread already has ${AGENT_QUEUE_MAX_PER_SENDER} messages from your thread waiting in its queue, the most one thread may have there; nothing was queued. Wait for them to run (thread_wait), or change one of them (queue_list, queue_edit) instead of adding another.`, agent_queue_full: - 'The thread already has several messages from agents waiting in its queue. Wait for them to run (thread_wait), or try again later.', + `The thread already has ${AGENT_QUEUE_MAX_PER_THREAD} messages from agents waiting in its queue, the most it holds from all agents together; nothing was queued. Wait for them to run (thread_wait), or try again later.`, + duplicate_message: + `You sent the same text to this thread less than ${AGENT_REPEAT_WINDOW_MS / 60_000} minutes ago, so it was not sent again. If your earlier call failed or timed out, call again with the same clientRequestId to get its result. To send it again on purpose, wait until retryAfterMs has passed, or write a new message.`, + sends_per_run_exceeded: + `thread_send is limited to ${THREAD_SEND_MAX_PER_RUN} messages per run; nothing was sent. End your turn and let the other threads work.`, device_limit: "Your owner wrote to you from a device this computer holds below that thread's access, so you can't send to it in this turn. Ask your owner to send it from the computer, or to message the thread themselves." } +/** When the refused message may be sent again (`duplicate_message`), as the engine's refusal gives it. */ +function retryAfterOf(error: unknown): { retryAfterMs?: number } { + const value = ((error as { details?: unknown } | null)?.details as { retryAfterMs?: unknown } | undefined)?.retryAfterMs + return typeof value === 'number' ? { retryAfterMs: value } : {} +} + /** An engine refusal that means the thread is not in a state to take the message now, as a `mousse_conflict`. */ function sendConflict(error: unknown): McpToolError | undefined { const code = (error as { code?: unknown } | null)?.code if (typeof code !== 'string') return undefined - if (SEND_CONFLICTS[code]) return new McpToolError('mousse_conflict', SEND_CONFLICTS[code], { conflict: code }) + if (SEND_CONFLICTS[code]) return new McpToolError('mousse_conflict', SEND_CONFLICTS[code], { conflict: code, ...retryAfterOf(error) }) if (code === 'merge_back_pending') return new McpToolError('mousse_conflict', error instanceof Error ? error.message : 'A merge-back waits for the thread.', { conflict: code }) return undefined } @@ -497,6 +580,11 @@ function chosenStandingRule(request: ApprovalRequestInfo, answers: UserQuestionA }) } +/** What became of an agent's message: a turn started with it, or it waits in the thread's queue behind the running turn. */ +function deliveryOf(sent: { queued: boolean }): 'started' | 'queued' { + return sent.queued ? 'queued' : 'started' +} + /** The transcript row of a change the call made; the `agent.action` event is the record, so a row that fails to write is not an error. */ function showAction(host: AppToolHost, threadId: string, actor: AgentActor, summary: string, options?: { notice?: boolean }): void { try { @@ -526,7 +614,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B const reserveSend = (runId: string): void => { const used = sends.get(runId) ?? 0 if (used >= THREAD_SEND_MAX_PER_RUN) - throw new Error(`thread_send is limited to ${THREAD_SEND_MAX_PER_RUN} messages per run; end your turn and let the other threads work.`) + throw new McpToolError('mousse_conflict', SEND_CONFLICTS.sends_per_run_exceeded, { conflict: 'sends_per_run_exceeded', limit: THREAD_SEND_MAX_PER_RUN }) sends.delete(runId) sends.set(runId, used + 1) // The oldest runs fall out first, so the map stays small on a long-lived daemon. @@ -621,7 +709,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B return [ { name: 'thread_read', - description: 'Read a thread. view "events" (default): run events (runs, attempts, delegations, tool calls) of any thread. Page with afterSeq. view "messages": the transcript of any thread; page with afterIndex. A personal bot reads its owner\'s threads with view "summary" (default: one line on the thread and its last reply) or "messages" (the newest ones, or from afterIndex, capped).', + description: `Read a thread. view "events" (default): run events (runs, attempts, delegations, tool calls) of any thread. Page with afterSeq. view "messages": the transcript of any thread; page with afterIndex. Each message holds at most ${THREAD_MESSAGE_MAX_CHARS} characters: one marked truncated continues when you pass its index as afterIndex and its nextTextOffset as textOffset. A response holds at most ${THREAD_READ_MAX_BYTES / 1024} KB: a page that reaches it has fewer items and capped: true, and nextAfterSeq or nextAfterIndex continues it. A run's final text is cut to ${THREAD_RESULT_MAX_CHARS} characters; read it in full in the messages. A personal bot reads its owner\'s threads with view "summary" (default: one line on the thread and its last reply) or "messages" (the newest ones, or from afterIndex, capped).`, inputSchema: { type: 'object', properties: { @@ -629,6 +717,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B view: { type: 'string', enum: ['events', 'messages', 'summary'], description: 'Defaults to events (summary for a personal bot, which has no events view).' }, afterSeq: { type: 'integer', minimum: 0, description: 'events: return events after this sequence number.' }, afterIndex: { type: 'integer', minimum: 0, description: 'messages: return the messages after this many (nextAfterIndex of the previous page).' }, + textOffset: { type: 'integer', minimum: 0, description: 'messages: start the first message returned (the one at afterIndex) at this character, to read on in a message marked truncated (its nextTextOffset).' }, limit: { type: 'integer', minimum: 1, maximum: THREAD_READ_MAX_LIMIT, description: `events: up to ${THREAD_READ_MAX_LIMIT} (default ${THREAD_READ_DEFAULT_LIMIT}); messages: up to ${THREAD_MESSAGES_MAX_LIMIT} (default ${THREAD_MESSAGES_DEFAULT_LIMIT}).` } } }, @@ -653,27 +742,62 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (!host.threadMessages) return notAvailable('thread_read messages') const afterIndex = boundedInt(args.afterIndex, 'afterIndex', 0, Number.MAX_SAFE_INTEGER, 0) const limit = boundedInt(args.limit, 'limit', 1, THREAD_MESSAGES_MAX_LIMIT, THREAD_MESSAGES_DEFAULT_LIMIT) + const textOffset = boundedInt(args.textOffset, 'textOffset', 0, Number.MAX_SAFE_INTEGER, 0) const all = host.threadMessages(threadId) - const messages = all.slice(afterIndex, afterIndex + limit).map((message, offset) => { - const text = typeof message.content === 'string' ? message.content : '' - const truncated = text.length > THREAD_MESSAGE_MAX_CHARS - return { - index: afterIndex + offset, - id: message.id, - role: message.role, - timestamp: message.timestamp, - text: truncated ? text.slice(0, THREAD_MESSAGE_MAX_CHARS) : text, - ...(truncated ? { truncated: true } : {}) + const firstText = all[afterIndex] && typeof all[afterIndex].content === 'string' ? all[afterIndex].content : '' + if (textOffset > 0 && afterIndex < all.length && textOffset >= firstText.length) + throw new Error(`textOffset ${textOffset} is past the end of message ${afterIndex}, which has ${firstText.length} characters`) + // Built one at a time, so a page that reaches the byte cap stops reading the transcript there. + function* rows() { + for (let index = afterIndex; index < Math.min(all.length, afterIndex + limit); index += 1) { + const message = all[index] + const text = typeof message.content === 'string' ? message.content : '' + const from = index === afterIndex ? textOffset : 0 + const end = cutEnd(text, from + THREAD_MESSAGE_MAX_CHARS) + yield { + index, + id: message.id, + role: message.role, + timestamp: message.timestamp, + text: text.slice(from, end), + ...(from > 0 ? { textOffset: from } : {}), + ...(end < text.length ? { truncated: true, totalChars: text.length, nextTextOffset: end } : {}) + } } + } + const envelope = { threadId, link: threadLink(threadId), view, scope, total: all.length } + const { taken: messages, capped } = fitPage(rows(), envelope) + const truncated = messages.some((message) => 'truncated' in message) + return json({ + ...envelope, + messages, + nextAfterIndex: afterIndex + messages.length, + ...(capped ? { capped: true } : {}), + ...(capped || truncated + ? { + hint: [ + capped ? `This page stopped at ${THREAD_READ_MAX_BYTES / 1024} KB; continue with afterIndex ${afterIndex + messages.length}.` : '', + truncated ? 'A message marked truncated continues: pass its index as afterIndex and its nextTextOffset as textOffset.' : '' + ].filter(Boolean).join(' ') + } + : {}) }) - return json({ threadId, link: threadLink(threadId), view, scope, messages, total: all.length, nextAfterIndex: afterIndex + messages.length }) } const afterSeq = boundedInt(args.afterSeq, 'afterSeq', 0, Number.MAX_SAFE_INTEGER, 0) const limit = boundedInt(args.limit, 'limit', 1, THREAD_READ_MAX_LIMIT, THREAD_READ_DEFAULT_LIMIT) const page = engine.listEvents(threadId, { afterSeq, limit }) - const events = full ? page : lineageView(page, ctx.caller.threadId, scope) - // `nextAfterSeq` pages on even when a lineage view filtered events out of this page. - return json({ threadId, link: threadLink(threadId), view, scope, events, maxSeq: engine.maxSeq(threadId), nextAfterSeq: page.at(-1)?.seq ?? afterSeq }) + const visible = full ? page : lineageView(page, ctx.caller.threadId, scope) + const envelope = { threadId, link: threadLink(threadId), view, scope, maxSeq: engine.maxSeq(threadId) } + const { taken: events, capped } = fitPage(visible.map(boundedEvent), envelope) + // `nextAfterSeq` pages on even when a lineage view filtered events out of this page; a page cut at the byte cap + // continues after the last event it holds. + const nextAfterSeq = capped ? events.at(-1)!.seq : page.at(-1)?.seq ?? afterSeq + return json({ + ...envelope, + events, + nextAfterSeq, + ...(capped ? { capped: true, hint: `This page stopped at ${THREAD_READ_MAX_BYTES / 1024} KB; continue with afterSeq ${nextAfterSeq}.` } : {}) + }) } }, { @@ -832,7 +956,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_send', - description: `Send a message to another thread. The thread's model receives it labelled as a message from an agent in your thread, not from the user, and runs it under your permission mode when that is stricter than the thread's own; it never gets more than the thread itself allows. It starts a turn when the thread is idle and queues behind the running turn otherwise (it never steers the running turn). A thread kept in Plan takes it as a plan turn. Refused while the thread waits for the user to answer a question or approval, is paused by a usage limit, or is archived, when it already has several messages from agents waiting, and when it would be more than a few agent messages in a row without a person in between. You may send ${THREAD_SEND_MAX_PER_RUN} messages per run (a personal bot has no such count). Returns the run it created: use thread_wait with it to wait for the answer, only when you need it this turn. Subagents are reached with continue_subagent.`, + description: `Send a message to another thread. The thread's model receives it labelled as a message from an agent in your thread, not from the user, and runs it under your permission mode when that is stricter than the thread's own; it never gets more than the thread itself allows. It starts a turn when the thread is idle and queues behind the running turn otherwise (it never steers the running turn). A thread kept in Plan takes it as a plan turn. Refused while the thread waits for the user to answer a question or approval, is paused by a usage limit, or is archived, when it already has ${AGENT_QUEUE_MAX_PER_SENDER} messages from your thread or ${AGENT_QUEUE_MAX_PER_THREAD} from agents in all waiting, when you sent it the same text in the last ${AGENT_REPEAT_WINDOW_MS / 60_000} minutes, and when it would be more than a few agent messages in a row without a person in between; each refusal names its limit (data.conflict). You may send ${THREAD_SEND_MAX_PER_RUN} messages per run (a personal bot has no such count). Returns the run it created and delivery: started (a turn began with it) or queued (it waits behind the running turn): use thread_wait with it to wait for the answer, only when you need it this turn. Subagents are reached with continue_subagent.`, inputSchema: { type: 'object', properties: { @@ -873,7 +997,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B } catch (limit) { // A retry of a send this run already made is answered with its first result, however many it has made. const earlier = host.earlierSend?.(threadId, requestKey) - if (earlier) return json({ threadId, ...earlier }) + if (earlier) return json({ threadId, ...earlier, delivery: deliveryOf(earlier) }) throw limit } let sent @@ -891,14 +1015,14 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (bot) { const title = titleOf(threadId) if (!sent.replayed) botChip(bot, 'thread_send', threadId, title, args.content) - return json({ threadId, title: title ?? null, ...sent, note: 'It runs in that thread\'s own mode. Approvals and questions there wait for your owner, never for you.' }) + return json({ threadId, title: title ?? null, ...sent, delivery: deliveryOf(sent), note: 'It runs in that thread\'s own mode. Approvals and questions there wait for your owner, never for you.' }) } - return json({ threadId, ...sent }) + return json({ threadId, ...sent, delivery: deliveryOf(sent) }) } }, { name: 'thread_wait', - description: `Wait for a run of another thread to finish, for at most timeoutMs (default ${THREAD_WAIT_DEFAULT_MS}, up to ${THREAD_WAIT_MAX_MS}). Pass the runId thread_send returned; without one, the run that is active now. Returns status finished (with the run's outcome, and its final text where you may read it), timeout (the run is still going: call again; the wait never interrupts it), paused (a usage limit paused the run and it was still paused when the wait ran out: it resumes by itself, and the result says when to ask again; a wait that is running when it resumes follows it into the run that continues it), idle (no run to wait for) or caller_ended (your own run ended). Wait only when you need the answer this turn; otherwise end your turn and read the thread later.`, + description: `Wait for a run of another thread to finish, for at most timeoutMs (default ${THREAD_WAIT_DEFAULT_MS}, up to ${THREAD_WAIT_MAX_MS}). Pass the runId thread_send returned; without one, the run that is active now. Returns status finished (with the run's outcome, and its final text where you may read it, cut to ${THREAD_RESULT_MAX_CHARS} characters with resultTruncated when longer), timeout (the run is still going: call again; the wait never interrupts it), paused (a usage limit paused the run and it was still paused when the wait ran out: it resumes by itself, and the result says when to ask again; a wait that is running when it resumes follows it into the run that continues it), idle (no run to wait for) or caller_ended (your own run ended). Wait only when you need the answer this turn; otherwise end your turn and read the thread later.`, inputSchema: { type: 'object', properties: { @@ -1015,7 +1139,15 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B const cut = resultText !== undefined && resultText.length > BOT_RESULT_CHARS return botData(`What thread «${title}» answered`, { status: 'finished', threadId, title, run: reported, ...(resultText !== undefined ? { resultText: cut ? `${resultText.slice(0, BOT_RESULT_CHARS)}…` : resultText, ...(cut ? { cut: true } : {}) } : {}) }) } - return json({ status: 'finished', threadId, run: reported, ...(resultText !== undefined ? { resultText } : {}) }) + // Cut like every other thread's result a tool returns; the delegation notice reads the stored text, not this. + const cut = resultText === undefined ? undefined : cutResultText(resultText) + return json({ + status: 'finished', + threadId, + run: reported, + ...(cut ? { resultText: cut.text } : {}), + ...(cut?.totalChars !== undefined ? { resultTruncated: true, resultChars: cut.totalChars, hint: RESULT_READ_ON } : {}) + }) } finally { clearTimeout(timer) if (held) clearInterval(held) diff --git a/src/mms/run/mcp/instructions.ts b/src/mms/run/mcp/instructions.ts index f702a04245..8114c0ee06 100644 --- a/src/mms/run/mcp/instructions.ts +++ b/src/mms/run/mcp/instructions.ts @@ -14,9 +14,9 @@ export function mousseOrchestrationInstructions(): string { '- clientRequestId: pass a fresh clientRequestId for every new action that changes state (delegate_task, continue_subagent, answer_subagent). Reuse the same value only when retrying the same call after an error or timeout; Mousse then returns the first result instead of acting twice.', '- A delegated task can never exceed your own mode ceiling: a planning turn may only start planning children.', '- Use ask_user for clarifying questions; use thread_read to read your thread\'s run events (and those of your parent or children).', - '- thread_list and thread_search find any thread of the profile and thread_read reads it. Each thread they return has a link (mousse://thread/<id>): put it in a reply and the user can click it to open that thread.', + '- thread_list and thread_search find any thread of the profile and thread_read reads it, at most 64 KB per call and 4,096 characters per message (it says how to read on). Each thread they return has a link (mousse://thread/<id>): put it in a reply and the user can click it to open that thread.', '- thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person\'s Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one.', - '- thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread\'s, and is limited to 20 messages per run. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. Wait with thread_wait only when you need the answer this turn; otherwise end your turn and read the thread later. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent\'s. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between, and a thread holds only a few waiting messages from agents.', + '- thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread\'s, and is limited to 20 messages per run; its result\'s delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. Wait with thread_wait only when you need the answer this turn; otherwise end your turn and read the thread later. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent\'s. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict.', '- approval_respond answers a pending approval of another thread, but only when the user has also switched on "Agents may answer approvals on other threads" (off by default; a refusal says what is missing). Read the request first with thread_list. Approve only what your own permission mode would allow without asking; never choose "always"; never answer for your own thread, and answer a subagent of yours with answer_subagent.', '- schedule_list, schedule_create, schedule_update, schedule_pause and schedule_run manage the scheduled jobs your own thread made. The first job your thread creates is not made at once: the user is asked and answers Allow or Not now (tell them it waits for their answer; do not retry); after Allow your thread may add more within the limits. Creating, starting or changing what a job does works only in a turn the user started (not from a job, another agent, a subagent or a remote send). A job outlives your turn and runs later as a turn of its own, with no permission mode beyond yours; changing one can only narrow that. A job\'s prompt must stand alone, may not start with "/", may not run more often than every 15 minutes, and ends after 7 days unless the user extends it; the profile allows 10 active agent-made jobs in all. The user resumes a paused job.', '- queue_list, queue_edit, queue_remove, queue_reorder and queue_promote_to_steer work on the messages queued on your thread or another thread. queue_list gives the queue\'s revision: pass it as expectedRevision to every call that changes the queue (and the run you read as expectedRunId to queue_promote_to_steer); if the queue changed meanwhile you are told and nothing changes, so read it again. What you write into a queue is labelled as yours, runs under your permission mode when that is stricter than the message\'s, and counts toward the few agent messages a thread keeps waiting; a removal is recorded with its text. queue_promote_to_steer is refused while the user has a question or approval waiting. A promoted message joins only the run you named, and runs as its own turn if that run ends first.', diff --git a/tests/run/delegationGuidance.test.ts b/tests/run/delegationGuidance.test.ts index 41255f029c..4a6fb5e97b 100644 --- a/tests/run/delegationGuidance.test.ts +++ b/tests/run/delegationGuidance.test.ts @@ -35,9 +35,9 @@ describe('subagent guidance', () => { - clientRequestId: pass a fresh clientRequestId for every new action that changes state (delegate_task, continue_subagent, answer_subagent). Reuse the same value only when retrying the same call after an error or timeout; Mousse then returns the first result instead of acting twice. - A delegated task can never exceed your own mode ceiling: a planning turn may only start planning children. - Use ask_user for clarifying questions; use thread_read to read your thread's run events (and those of your parent or children). - - thread_list and thread_search find any thread of the profile and thread_read reads it. Each thread they return has a link (mousse://thread/<id>): put it in a reply and the user can click it to open that thread. + - thread_list and thread_search find any thread of the profile and thread_read reads it, at most 64 KB per call and 4,096 characters per message (it says how to read on). Each thread they return has a link (mousse://thread/<id>): put it in a reply and the user can click it to open that thread. - thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person's Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one. - - thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread's, and is limited to 20 messages per run. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. Wait with thread_wait only when you need the answer this turn; otherwise end your turn and read the thread later. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent's. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between, and a thread holds only a few waiting messages from agents. + - thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread's, and is limited to 20 messages per run; its result's delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. Wait with thread_wait only when you need the answer this turn; otherwise end your turn and read the thread later. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent's. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict. - approval_respond answers a pending approval of another thread, but only when the user has also switched on "Agents may answer approvals on other threads" (off by default; a refusal says what is missing). Read the request first with thread_list. Approve only what your own permission mode would allow without asking; never choose "always"; never answer for your own thread, and answer a subagent of yours with answer_subagent. - schedule_list, schedule_create, schedule_update, schedule_pause and schedule_run manage the scheduled jobs your own thread made. The first job your thread creates is not made at once: the user is asked and answers Allow or Not now (tell them it waits for their answer; do not retry); after Allow your thread may add more within the limits. Creating, starting or changing what a job does works only in a turn the user started (not from a job, another agent, a subagent or a remote send). A job outlives your turn and runs later as a turn of its own, with no permission mode beyond yours; changing one can only narrow that. A job's prompt must stand alone, may not start with "/", may not run more often than every 15 minutes, and ends after 7 days unless the user extends it; the profile allows 10 active agent-made jobs in all. The user resumes a paused job. - queue_list, queue_edit, queue_remove, queue_reorder and queue_promote_to_steer work on the messages queued on your thread or another thread. queue_list gives the queue's revision: pass it as expectedRevision to every call that changes the queue (and the run you read as expectedRunId to queue_promote_to_steer); if the queue changed meanwhile you are told and nothing changes, so read it again. What you write into a queue is labelled as yours, runs under your permission mode when that is stricter than the message's, and counts toward the few agent messages a thread keeps waiting; a removal is recorded with its text. queue_promote_to_steer is refused while the user has a question or approval waiting. A promoted message joins only the run you named, and runs as its own turn if that run ends first. diff --git a/tests/run/mcpToolRegistry.test.ts b/tests/run/mcpToolRegistry.test.ts index d4e41f8d27..22efc1e004 100644 --- a/tests/run/mcpToolRegistry.test.ts +++ b/tests/run/mcpToolRegistry.test.ts @@ -11,6 +11,8 @@ import { } from '../../src/mms/run/mcp/appTools' import { appToolRegistry, appTurn, fakeAppToolHost } from './appToolsFixture' import { delegationFixture, type DelegationFixture } from './delegationFixture' +import { THREAD_MESSAGE_MAX_CHARS, THREAD_READ_MAX_BYTES, THREAD_RESULT_MAX_CHARS } from '../../src/mms/run/mcp/appTools/thread' +import { AGENT_MESSAGE_END, AGENT_MESSAGE_PREFIX, agentMessage } from '../../src/mms/run/mcp/appTools/agentMessage' /** The tools a credential lists before the app tools joined (still listed, still these classes). */ const PHASE5_TOOLS: Record<string, string> = { @@ -580,6 +582,115 @@ describe('reading and managing other threads (SPEC §15.1)', () => { expect((await call('parent', 'thread_read', { threadId: 'stranger', view: 'messages', limit: 201 })).isError).toBe(true) }) + it('thread_read messages: a message marked truncated is read on with textOffset to its end, never splitting a character', async () => { + const { call, read, messages } = await world() + // A character outside the BMP sits on the cut: the first part stops before it rather than halving it. + const long = `${'a'.repeat(THREAD_MESSAGE_MAX_CHARS - 1)}😀${Array.from({ length: 6000 }, (_, at) => String.fromCharCode(98 + (at % 24))).join('')}` + messages.set('stranger', [message(0, 'before'), message(1, long, 'assistant'), message(2, 'after')]) + const first = await read('parent', { threadId: 'stranger', view: 'messages', afterIndex: 1, limit: 1 }) + expect(first.messages[0]).toMatchObject({ index: 1, truncated: true, totalChars: long.length, nextTextOffset: THREAD_MESSAGE_MAX_CHARS - 1 }) + expect(first.hint).toContain('textOffset') + let text = first.messages[0].text as string + let next: number | undefined = first.messages[0].nextTextOffset + const offsets: number[] = [] + while (next !== undefined) { + offsets.push(next) + const page = await read('parent', { threadId: 'stranger', view: 'messages', afterIndex: 1, textOffset: next, limit: 2 }) + expect(page.messages[0]).toMatchObject({ index: 1, textOffset: next }) + // The offset applies to the message at afterIndex only; the next one starts at its beginning. + expect(page.messages[1]).toMatchObject({ index: 2, text: 'after' }) + text += page.messages[0].text + next = page.messages[0].nextTextOffset + } + expect(text).toBe(long) + expect(offsets).toHaveLength(Math.ceil((long.length - (THREAD_MESSAGE_MAX_CHARS - 1)) / THREAD_MESSAGE_MAX_CHARS)) + expect((await call('parent', 'thread_read', { threadId: 'stranger', view: 'messages', afterIndex: 1, textOffset: long.length })).isError).toBe(true) + }) + + it('thread_read messages: an agent\'s long message reads on over its stored text, label and closing line included', async () => { + const { read, messages } = await world() + const words = Array.from({ length: 9000 }, (_, at) => String.fromCharCode(65 + (at % 26))).join('') + const envelope = agentMessage('sender-thread', 'Sender', words) + messages.set('stranger', [{ ...message(0, envelope.text), origin: { kind: 'agent', threadId: 'sender-thread', runId: 'r', body: { head: envelope.head, tail: envelope.tail } } } as ChatMessage]) + let page = (await read('parent', { threadId: 'stranger', view: 'messages' })).messages[0] + // The offsets count the stored text: the first part starts with the label, and the agent's words start after it. + expect(page.text.startsWith(AGENT_MESSAGE_PREFIX)).toBe(true) + expect(page.totalChars).toBe(envelope.text.length) + let text = page.text as string + while (page.nextTextOffset !== undefined) { + page = (await read('parent', { threadId: 'stranger', view: 'messages', textOffset: page.nextTextOffset })).messages[0] + text += page.text + } + expect(text).toBe(envelope.text) + expect(text.endsWith(AGENT_MESSAGE_END)).toBe(true) + expect(text.slice(envelope.head, text.length - envelope.tail)).toBe(words) + }) + + /** Every page a reader gets by following the continuation, until it says there is no more. */ + const allPages = async (read: (args: Record<string, unknown>) => Promise<Record<string, any>>, args: Record<string, unknown>, cursor: 'afterIndex' | 'afterSeq') => { + const pages: Array<Record<string, any>> = [] + let at = 0 + for (;;) { + const page = await read({ ...args, [cursor]: at }) + pages.push(page) + const next = cursor === 'afterIndex' ? page.nextAfterIndex : page.nextAfterSeq + if (!page.capped || next === at) return pages + at = next + } + } + + it(`thread_read holds a response to ${THREAD_READ_MAX_BYTES / 1024} KB in the messages view, counted in bytes, and continues where it stopped`, async () => { + const { call, messages } = await world() + // Two bytes a character: a cap counted in characters would let twice as much through. + const all = Array.from({ length: 50 }, (_, index) => message(index, `${index}:${'é'.repeat(3_000)}`)) + messages.set('stranger', all) + const raw = async (args: Record<string, unknown>) => (await call('parent', 'thread_read', { threadId: 'stranger', view: 'messages', ...args })).text + const pages = await allPages(async (args) => { + const text = await raw(args) + expect(Buffer.byteLength(text, 'utf8')).toBeLessThanOrEqual(THREAD_READ_MAX_BYTES) + return JSON.parse(text) + }, { limit: 50 }, 'afterIndex') + expect(pages.length).toBeGreaterThan(1) + expect(pages[0]).toMatchObject({ capped: true, hint: expect.stringContaining(`afterIndex ${pages[0].messages.length}`) }) + // Every message once, in order, none cut: the pages fit whole messages and the next page starts at the first left out. + expect(pages.flatMap((page) => page.messages.map((entry: { id: string }) => entry.id))).toEqual(all.map((entry) => entry.id)) + expect(pages.flatMap((page) => page.messages).some((entry: { truncated?: boolean }) => entry.truncated)).toBe(false) + expect(pages.at(-1)!.capped).toBeUndefined() + }) + + it(`thread_read holds a response to ${THREAD_READ_MAX_BYTES / 1024} KB in the events view, continues after the last event it holds, and previews an event too big for a response`, async () => { + const { call, fx, strangerRun } = await world() + const from = fx.engine.maxSeq('stranger') + for (let index = 0; index < 120; index += 1) + fx.engine.store.appendEvent({ threadId: 'stranger', runId: strangerRun.runId, type: 'tool.call', payload: { index, text: 'é'.repeat(1_000) } }) + fx.engine.store.appendEvent({ threadId: 'stranger', runId: strangerRun.runId, type: 'tool.call', payload: { index: 'huge', text: 'z'.repeat(THREAD_READ_MAX_BYTES * 2) } }) + fx.engine.store.appendEvent({ threadId: 'stranger', runId: strangerRun.runId, type: 'tool.call', payload: { index: 'last', text: 'end' } }) + const pages = await allPages(async (args) => { + const text = (await call('parent', 'thread_read', { threadId: 'stranger', limit: 500, ...args })).text + expect(Buffer.byteLength(text, 'utf8')).toBeLessThanOrEqual(THREAD_READ_MAX_BYTES) + return JSON.parse(text) + }, {}, 'afterSeq') + expect(pages.length).toBeGreaterThan(1) + expect(pages[0]).toMatchObject({ capped: true, nextAfterSeq: pages[0].events.at(-1).seq }) + const seqs = pages.flatMap((page) => page.events.map((event: { seq: number }) => event.seq)) + expect(seqs).toEqual(fx.engine.listEvents('stranger', { limit: 1000 }).map((event) => event.seq)) + const ours = pages.flatMap((page) => page.events).filter((event: { seq: number }) => event.seq > from) + expect(ours.slice(0, 120).map((event: { payload: { index: number } }) => event.payload.index)).toEqual(Array.from({ length: 120 }, (_, index) => index)) + expect(ours[120].payload).toMatchObject({ truncated: true, bytes: expect.any(Number), preview: expect.stringContaining('"index":"huge"') }) + expect(ours[120].payload.bytes).toBeGreaterThan(THREAD_READ_MAX_BYTES) + expect(ours[121].payload).toEqual({ index: 'last', text: 'end' }) + }) + + it(`thread_read cuts a run\'s final text in the events to ${THREAD_RESULT_MAX_CHARS} characters with a pointer to the messages`, async () => { + const { read, fx, threads, strangerRun } = await world() + const long = `${'w'.repeat(THREAD_RESULT_MAX_CHARS)}-the rest` + const child = await fx.delegate(strangerRun.runId, 'call-long') + threads.set(child.childThreadId, thread(child.childThreadId)) + fx.finish(child.childRunId, long) + const result = (await read('parent', { threadId: child.childThreadId })).events.find((event: { type: string }) => event.type === 'run.result') + expect(result.payload).toMatchObject({ runId: child.childRunId, text: `${'w'.repeat(THREAD_RESULT_MAX_CHARS)}…`, truncated: true, totalChars: long.length, hint: expect.stringContaining('view "messages"') }) + }) + it('thread_list: every project, started and unsettled by default, filters and limits, with the pending questions', async () => { const { call, fx, threads, activity, strangerRun } = await world() threads.set('draft', thread('draft', { startedAt: undefined })) diff --git a/tests/run/queueEditDaemon.test.ts b/tests/run/queueEditDaemon.test.ts index 7e61964481..066a20bb7c 100644 --- a/tests/run/queueEditDaemon.test.ts +++ b/tests/run/queueEditDaemon.test.ts @@ -14,6 +14,7 @@ import { readDurableQueue } from '../../src/mms/queue/durableQueue' import { CLAUDE_SUBSCRIPTION_CAPABILITIES } from '../../src/mms/harness/drivers/claudeCode/adapter' import type { AdapterHost, ProviderAdapter, ProviderCapabilities, TurnControl, TurnInput, TurnResult, TurnSink } from '../../src/mms/harness/adapter' import { AGENT_MESSAGE_PREFIX, agentMessageText, TURN_TOKEN_KEY } from '../../src/mms/run/mcp/appTools' +import { AGENT_QUEUE_MAX_PER_SENDER, AGENT_QUEUE_MAX_PER_THREAD } from '../../src/mms/run/mcp/appTools/thread' import { McpCredentials } from '../../src/mms/run/mcp/McpCredentials' import { MCP_ERROR_CODES, MousseMcpServer } from '../../src/mms/run/mcp/MousseMcpServer' import type { ProviderDriverKind } from '../../src/shared/providerInstances' @@ -826,7 +827,7 @@ describe('queue tools that change other threads\' queues and the caller\'s own ( return sent.runId } - it('carries the writing run\'s hop count and mode limit, counts in the cap of three, waits behind a usage pause, and runs as an agent\'s run; an agent at its hop limit cannot start a fresh chain through its own queue', async () => { + it('carries the writing run\'s hop count and mode limit, counts in its sender\'s cap of three, waits behind a usage pause, and runs as an agent\'s run; an agent at its hop limit cannot start a fresh chain through its own queue', async () => { const w = world(async () => 'ok') await w.attach() const writer = agentRun(w, 2) @@ -841,8 +842,8 @@ describe('queue tools that change other threads\' queues and the caller\'s own ( expect(() => enqueue('one hop too many', 'k5', third.runId)).toThrow(expect.objectContaining({ code: 'agent_hops_exceeded' })) enqueue('second note', 'k2') enqueue('third note', 'k3') - // The cap of three queued agent messages counts them, whoever's thread they are on. - expect(() => enqueue('fourth note', 'k4')).toThrow(expect.objectContaining({ code: 'agent_queue_full' })) + // The cap of three queued messages per sending thread counts them, whoever's thread they are on. + expect(() => enqueue('fourth note', 'k4')).toThrow(expect.objectContaining({ code: 'agent_queue_full_per_sender' })) expect(w.queue(w.other.id).map((item) => item.content)).toEqual(['note to myself', 'second note', 'third note']) // Behind a usage pause only a person's message goes on: the notes wait, and the pause stays. @@ -1202,7 +1203,7 @@ describe('queue tools that change other threads\' queues and the caller\'s own ( }) describe('limits on what agents put in a thread\'s queue (the caps of thread_send)', () => { - it('a thread keeps three queued messages from agents, whether they were sent or queued: the fourth is refused, and so is an edit that would make a person\'s message the fourth; a person\'s Stop clears them', async () => { + it('a thread keeps three queued messages from each sending thread, whether they were sent or queued: the fourth is refused, and so is an edit that would make a person\'s message the fourth; a person\'s Stop clears them', async () => { const release = deferred() const seen: Response[] = [] const ids: Record<string, string> = {} @@ -1223,8 +1224,8 @@ describe('queue tools that change other threads\' queues and the caller\'s own ( ids.typed = w.typed(w.other.id, 'a note I typed').id await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go' }) expect(seen.slice(0, 3).map(verdict)).toEqual(['ok', 'ok', 'ok']) - expect(seen[3].error).toMatchObject({ code: MCP_ERROR_CODES.mousse_conflict, data: { conflict: 'agent_queue_full' } }) - expect(seen[4].error).toMatchObject({ code: MCP_ERROR_CODES.mousse_conflict, data: { conflict: 'agent_queue_full' } }) + expect(seen[3].error).toMatchObject({ code: MCP_ERROR_CODES.mousse_conflict, data: { conflict: 'agent_queue_full_per_sender' } }) + expect(seen[4].error).toMatchObject({ code: MCP_ERROR_CODES.mousse_conflict, data: { conflict: 'agent_queue_full_per_sender' } }) expect(w.queue(w.other.id).map((item) => item.origin?.kind)).toEqual([undefined, 'agent', 'agent', 'agent']) expect(w.queue(w.other.id)[0].content).toBe('a note I typed') @@ -1235,6 +1236,35 @@ describe('queue tools that change other threads\' queues and the caller\'s own ( release.resolve() }) + it(`a thread keeps ${AGENT_QUEUE_MAX_PER_THREAD} queued messages from all agents together: past it every sender is refused, a person is not`, async () => { + const release = deferred() + const w = world(async (input, _mcp, _d, adapter) => { + if (input.prompt === 'hold') await adapter.hold(input, release.promise) + return 'ok' + }) + await w.attach() + await w.d.orch.send('hold', false, { threadId: w.other.id, clientRequestId: 'hold', awaitMode: 'ack' }) + await waitFor(() => w.turnsOf(w.other.id).length === 1, 'the held turn') + const host = w.d.orch.mcpToolHost() + // Enough sending threads to reach the total with none of them past its own cap. + const senders = Array.from({ length: Math.ceil(AGENT_QUEUE_MAX_PER_THREAD / AGENT_QUEUE_MAX_PER_SENDER) + 1 }, (_, index) => { + const sender = w.thread(`Sender ${index}`) + return { kind: 'agent' as const, threadId: sender.id, runId: w.d.engine.store.createRun({ threadId: sender.id, source: 'gui' }).runId, toolCallId: 'mcp:t' } + }) + const enqueue = (actor: (typeof senders)[number], key: string) => () => host.queueCommand!(w.other.id, { op: 'enqueue', content: key, mode: 'agent' }, { clientRequestId: key, actor }) + let queued = 0 + for (const [index, actor] of senders.entries()) + for (let note = 0; note < AGENT_QUEUE_MAX_PER_SENDER && queued < AGENT_QUEUE_MAX_PER_THREAD; note += 1, queued += 1) enqueue(actor, `s${index}-n${note}`)() + expect(w.queue(w.other.id)).toHaveLength(AGENT_QUEUE_MAX_PER_THREAD) + // The last sender has room under its own cap, yet the thread is full; the first sender is past its own cap first. + expect(enqueue(senders.at(-1)!, 'one more')).toThrow(expect.objectContaining({ code: 'agent_queue_full' })) + expect(enqueue(senders[0], 'and another')).toThrow(expect.objectContaining({ code: 'agent_queue_full_per_sender' })) + // A person's message is never held to the agents' caps. + w.typed(w.other.id, 'a note I typed') + expect(w.queue(w.other.id)).toHaveLength(AGENT_QUEUE_MAX_PER_THREAD + 1) + release.resolve() + }) + it('the chain of agent messages in a row has a limit that queueing and editing respect: a run that is the third hop cannot queue or edit another agent\'s message', async () => { const w = world(async () => 'ok') await w.attach() diff --git a/tests/run/threadActionsDaemon.test.ts b/tests/run/threadActionsDaemon.test.ts index 332eabebd0..02136804b1 100644 --- a/tests/run/threadActionsDaemon.test.ts +++ b/tests/run/threadActionsDaemon.test.ts @@ -14,6 +14,7 @@ import { readDurableQueue } from '../../src/mms/queue/durableQueue' import { CLAUDE_SUBSCRIPTION_CAPABILITIES } from '../../src/mms/harness/drivers/claudeCode/adapter' import type { AdapterHost, ProviderAdapter, ProviderCapabilities, TurnControl, TurnInput, TurnResult, TurnSink } from '../../src/mms/harness/adapter' import { AGENT_MESSAGE_PREFIX, agentMessage, agentMessageText, TURN_TOKEN_KEY } from '../../src/mms/run/mcp/appTools' +import { AGENT_REPEAT_WINDOW_MS } from '../../src/mms/run/mcp/appTools/thread' import { McpCredentials } from '../../src/mms/run/mcp/McpCredentials' import { MCP_ERROR_CODES, MousseMcpServer } from '../../src/mms/run/mcp/MousseMcpServer' import type { ProviderDriverKind } from '../../src/shared/providerInstances' @@ -634,7 +635,8 @@ describe('thread_send, thread_wait, thread_interrupt and thread_steer end to end const sent: string[] = [] const w = world(async (input, mcp, d) => { const target = input.threadId === w.parent.id ? w.other.id : w.parent.id - const reply = await call(mcp!, 'thread_send', { threadId: target, content: `hop from ${input.threadId === w.parent.id ? 'A' : 'B'}` }) + // Each hop says something new: the same words again would be refused as a repeat, before the hop limit. + const reply = await call(mcp!, 'thread_send', { threadId: target, content: `hop from ${input.threadId === w.parent.id ? 'A' : 'B'} in ${input.runId}` }) if (reply.error) refusal.first ??= reply else sent.push((parse(reply) as { runId: string }).runId) // The run the message started carries how many agent messages led to it. @@ -655,26 +657,37 @@ describe('thread_send, thread_wait, thread_interrupt and thread_steer end to end expect(first.outcome?.agentHops).toBeUndefined() }) - it('a thread holds only a few messages from agents in its queue: the next is refused, and a person\'s Stop clears them, leaving what a person queued', async () => { + it('a thread holds only a few messages from each sending thread in its queue: the next is refused, another sender still gets in, and a person\'s Stop clears them, leaving what a person queued', async () => { const release = deferred() const results: Array<Awaited<ReturnType<typeof rpc>>> = [] + const fromThird: Array<Awaited<ReturnType<typeof rpc>>> = [] + let third = '' const w = world(async (input, mcp, _d, adapter) => { if (input.threadId === w.other.id) { await adapter.hold(input, release.promise) return 'held' } + if (input.threadId === third) { + fromThird.push(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'note from the third thread' })) + return 'Sent.' + } for (let index = 0; index < 4; index += 1) results.push(await call(mcp!, 'thread_send', { threadId: w.other.id, content: `note ${index}` })) return 'Sent.' }) + third = w.thread('Third').id await w.attach() await w.d.orch.send('hold', false, { threadId: w.other.id, clientRequestId: 'hold', awaitMode: 'ack' }) await waitFor(() => w.turnsOf(w.other.id).length === 1, 'the held turn') await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go' }) - expect(results.slice(0, 3).every((response) => !response.error && !response.result?.isError)).toBe(true) - expect(results[3].error).toMatchObject({ code: MCP_ERROR_CODES.mousse_conflict, data: { conflict: 'agent_queue_full' } }) - const queuedRuns = results.slice(0, 3).map((response) => (parse(response) as { runId: string }).runId) + expect(results.slice(0, 3).map((response) => parse(response).delivery)).toEqual(['queued', 'queued', 'queued']) + expect(results[3].error).toMatchObject({ code: MCP_ERROR_CODES.mousse_conflict, data: { conflict: 'agent_queue_full_per_sender' } }) + // One chatty sender does not shut the others out: the third thread's message still joins the queue. + await w.d.orch.send(GO, false, { threadId: third, clientRequestId: 'go-third' }) + expect(parse(fromThird[0])).toMatchObject({ queued: true, delivery: 'queued' }) + const queuedRuns = [...results.slice(0, 3), fromThird[0]].map((response) => (parse(response) as { runId: string }).runId) const person = w.d.orch.enqueueForThread(w.other.id, { content: 'a note I typed' }, { source: 'gui' }) - expect(readDurableQueue(w.d.store, w.other.id).map((item) => item.origin?.kind)).toEqual(['agent', 'agent', 'agent', undefined]) + expect(readDurableQueue(w.d.store, w.other.id).map((item) => item.origin?.kind === 'agent' ? item.origin.threadId : 'person')) + .toEqual([w.parent.id, w.parent.id, w.parent.id, third, 'person']) // The person presses Stop: the running turn ends and the agents' queued messages go with it. await w.d.orch.stopThread(w.other.id, 'user') @@ -684,6 +697,37 @@ describe('thread_send, thread_wait, thread_interrupt and thread_steer end to end release.resolve() }) + it('the same text from the same thread again within the window is refused as a repeat and runs once; a retry with the first key returns the first result; another thread may send the same words', async () => { + const seen: Record<string, Awaited<ReturnType<typeof rpc>>> = {} + let third = '' + const w = world(async (input, mcp) => { + if (input.threadId === w.parent.id && input.prompt === GO) { + seen.first = await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Run the checks.', clientRequestId: 'first' }) + seen.repeat = await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Run the checks.', clientRequestId: 'second' }) + seen.retry = await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Run the checks.', clientRequestId: 'first' }) + seen.reworded = await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Run the checks again, please.', clientRequestId: 'third' }) + } + if (input.threadId === third) seen.otherSender = await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Run the checks.' }) + return 'ok' + }) + third = w.thread('Third').id + await w.attach() + await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go' }) + const first = parse(seen.first) as { runId: string; delivery: string } + expect(first.delivery).toBe('started') + expect(seen.repeat.error).toMatchObject({ code: MCP_ERROR_CODES.mousse_conflict, data: { conflict: 'duplicate_message', retryAfterMs: expect.any(Number) } }) + expect(seen.repeat.error!.data!.retryAfterMs as number).toBeGreaterThan(0) + expect(seen.repeat.error!.data!.retryAfterMs as number).toBeLessThanOrEqual(AGENT_REPEAT_WINDOW_MS) + expect(parse(seen.retry)).toMatchObject({ runId: first.runId, replayed: true }) + expect(seen.reworded.error).toBeUndefined() + await w.d.orch.send(GO, false, { threadId: third, clientRequestId: 'go-third' }) + expect(seen.otherSender.error).toBeUndefined() + // The repeated words reached the other thread's model once from the parent: its first message, and the reworded one. + await waitFor(() => w.d.engine.listRuns(w.other.id).every((run) => run.status === 'completed') && w.turnsOf(w.other.id).length === 3, 'the other thread\'s turns') + const fromParent = w.turnsOf(w.other.id).filter((turn) => String(turn.prompt).includes(`(${w.parent.id})`)) + expect(fromParent.map((turn) => String(turn.prompt).includes('Run the checks.\n'))).toEqual([true, false]) + }) + it('an agent\'s own Stop of a run leaves the messages other agents queued on that thread', async () => { const release = deferred() const seen: Record<string, unknown> = {} diff --git a/tests/run/threadActionsTools.test.ts b/tests/run/threadActionsTools.test.ts index 50cda134f1..9798878b52 100644 --- a/tests/run/threadActionsTools.test.ts +++ b/tests/run/threadActionsTools.test.ts @@ -8,7 +8,7 @@ import type { Thread } from '../../src/shared/types' import { McpToolError, type AgentRunCommandResult, type AgentSendResult, type McpCallRequest } from '../../src/mms/run/mcp/appTools' import { AGENT_MESSAGE_END, agentMessage, agentMessageText } from '../../src/mms/run/mcp/appTools/agentMessage' import { agentMessageWords } from '../../src/shared/agentMessageWords' -import { THREAD_SEND_MAX_PER_RUN } from '../../src/mms/run/mcp/appTools/thread' +import { AGENT_QUEUE_MAX_PER_SENDER, AGENT_QUEUE_MAX_PER_THREAD, THREAD_RESULT_MAX_CHARS, THREAD_SEND_MAX_PER_RUN } from '../../src/mms/run/mcp/appTools/thread' import type { RunPause } from '../../src/mms/run/types' import { appToolRegistry, appTurn, fakeAppToolHost } from './appToolsFixture' import { delegationFixture, type DelegationFixture } from './delegationFixture' @@ -200,11 +200,11 @@ describe('tools that act on other threads (SPEC §15.1)', () => { it('shows the transcript row once, for the call that made the send and not for its replay', async () => { const { call, answers, host } = await world() - expect(JSON.parse((await call('thread_send', { threadId: 'target', content: 'x' })).text)).toMatchObject({ threadId: 'target', queued: false, replayed: false }) + expect(JSON.parse((await call('thread_send', { threadId: 'target', content: 'x' })).text)).toMatchObject({ threadId: 'target', queued: false, delivery: 'started', replayed: false }) expect(host.showAgentAction).toHaveBeenCalledTimes(1) expect(host.showAgentAction).toHaveBeenLastCalledWith({ threadId: 'target' }, expect.objectContaining({ kind: 'agent', threadId: 'caller' }), expect.stringContaining('sent a message')) answers.send = async () => ({ runId: 'run:first', sequence: 10, queued: true, replayed: true }) - expect(JSON.parse((await call('thread_send', { threadId: 'target', content: 'x' }, { toolCallId: 'mcp:again' })).text)).toMatchObject({ runId: 'run:first', queued: true, replayed: true }) + expect(JSON.parse((await call('thread_send', { threadId: 'target', content: 'x' }, { toolCallId: 'mcp:again' })).text)).toMatchObject({ runId: 'run:first', queued: true, delivery: 'queued', replayed: true }) expect(host.showAgentAction).toHaveBeenCalledTimes(1) }) @@ -225,11 +225,12 @@ describe('tools that act on other threads (SPEC §15.1)', () => { }) it(`is capped at ${THREAD_SEND_MAX_PER_RUN} messages per caller run: a loop of sends is cut off, retries and failures do not count, another run starts fresh`, async () => { - const { call, answers, host, sent, fx, turns, runs, callerRun } = await world() + const { call, denied, answers, host, sent, fx, turns, runs, callerRun } = await world() for (let index = 0; index < THREAD_SEND_MAX_PER_RUN; index += 1) expect((await call('thread_send', { threadId: 'target', content: `m${index}` })).isError, `send ${index}`).toBeUndefined() - const over = await call('thread_send', { threadId: 'target', content: 'one too many' }) - expect(over).toMatchObject({ isError: true, text: expect.stringContaining(`limited to ${THREAD_SEND_MAX_PER_RUN}`) }) + const over = await denied(call('thread_send', { threadId: 'target', content: 'one too many' })) + expect(over).toMatchObject({ code: 'mousse_conflict', details: { conflict: 'sends_per_run_exceeded', limit: THREAD_SEND_MAX_PER_RUN } }) + expect(over!.message).toContain(`limited to ${THREAD_SEND_MAX_PER_RUN}`) expect(host.sendToThread).toHaveBeenCalledTimes(THREAD_SEND_MAX_PER_RUN) expect(sent).toHaveLength(THREAD_SEND_MAX_PER_RUN) @@ -246,7 +247,7 @@ describe('tools that act on other threads (SPEC §15.1)', () => { answers.send = async () => ({ runId: 'run:fresh', sequence: 10, queued: false, replayed: false }) for (let index = 0; index < THREAD_SEND_MAX_PER_RUN; index += 1) expect((await call('thread_send', { threadId: 'target', content: `n${index}` })).isError, `fresh ${index}`).toBeUndefined() - expect((await call('thread_send', { threadId: 'target', content: 'over again' })).isError).toBe(true) + expect(await denied(call('thread_send', { threadId: 'target', content: 'over again' }))).toMatchObject({ details: { conflict: 'sends_per_run_exceeded' } }) }) it('validates its input before it reaches the host', async () => { @@ -324,27 +325,32 @@ describe('tools that act on other threads (SPEC §15.1)', () => { describe('limits and boundaries (review of PR 3)', () => { it('a retry of an earlier send is answered with its first result after the run has used its budget; a new send is still refused', async () => { - const { call, host, answers } = await world() + const { call, denied, host, answers } = await world() for (let index = 0; index < THREAD_SEND_MAX_PER_RUN; index += 1) await call('thread_send', { threadId: 'target', content: `m${index}`, clientRequestId: `req-${index}` }) // The host knows what `req-19` sent; it knows nothing of `brand-new`. host.earlierSend = vi.fn((_threadId: string, key: string) => key === 'thread_send:caller:req-19' ? { runId: 'run:first', sequence: 3, queued: true, replayed: true } : undefined) const retry = await call('thread_send', { threadId: 'target', content: 'm19', clientRequestId: 'req-19' }) - expect(JSON.parse(retry.text)).toEqual({ threadId: 'target', runId: 'run:first', sequence: 3, queued: true, replayed: true }) - const fresh = await call('thread_send', { threadId: 'target', content: 'one more', clientRequestId: 'brand-new' }) - expect(fresh).toMatchObject({ isError: true, text: expect.stringContaining('limited to') }) + expect(JSON.parse(retry.text)).toEqual({ threadId: 'target', runId: 'run:first', sequence: 3, queued: true, delivery: 'queued', replayed: true }) + const fresh = await denied(call('thread_send', { threadId: 'target', content: 'one more', clientRequestId: 'brand-new' })) + expect(fresh).toMatchObject({ code: 'mousse_conflict', details: { conflict: 'sends_per_run_exceeded' } }) expect(host.sendToThread).toHaveBeenCalledTimes(THREAD_SEND_MAX_PER_RUN) expect(answers).toBeDefined() }) + // Each limit the owner enforces has its own code and says which limit it is and what to do (one "limit reached" sends + // agents looking for the wrong cause). The send-per-run count is the tool's own, tested above. it.each([ ['agent_hops_exceeded', /agent messages in a row/], - ['agent_queue_full', /messages from agents waiting/] - ])('a send refused for the chain it would extend or the queue it would join (%s) is a conflict that says so', async (code, message) => { + ['agent_queue_full_per_sender', new RegExp(`${AGENT_QUEUE_MAX_PER_SENDER} messages from your thread .*the most one thread may have`)], + ['agent_queue_full', new RegExp(`${AGENT_QUEUE_MAX_PER_THREAD} messages from agents .*from all agents together`)], + ['duplicate_message', /same text .*same clientRequestId/] + ])('a send refused by the limit %s is a conflict that names it and what to do', async (code, message) => { const { call, denied, answers } = await world() - answers.send = async () => { throw refusal(code) } + answers.send = async () => { throw Object.assign(refusal(code), code === 'duplicate_message' ? { details: { retryAfterMs: 4_000 } } : {}) } const error = await denied(call('thread_send', { threadId: 'target', content: 'x' })) expect(error).toMatchObject({ code: 'mousse_conflict', details: { conflict: code } }) expect(error!.message).toMatch(message) + if (code === 'duplicate_message') expect(error!.details).toMatchObject({ retryAfterMs: 4_000 }) }) it('a steer past the hop limit, or into a run that has not started its turn, is a conflict that says so', async () => { @@ -502,6 +508,20 @@ describe('tools that act on other threads (SPEC §15.1)', () => { expect(await result(call('thread_wait', { threadId: 'target' }))).toEqual({ status: 'idle', threadId: 'target' }) }) + it(`cuts a long result to ${THREAD_RESULT_MAX_CHARS} characters with a marker and a pointer to thread_read; the subagent\'s result its parent receives keeps the whole text`, async () => { + const { call, result, fx, callerRun, threads } = await world() + const long = 'r'.repeat(THREAD_RESULT_MAX_CHARS) + 'TAIL'.repeat(500) + const child = await fx.delegate(callerRun.runId, 'call-long') + threads.set(child.childThreadId, { id: child.childThreadId, name: 'Child', createdAt: '', updatedAt: '' } as never) + fx.finish(child.childRunId, long) + const waited = await result(call('thread_wait', { threadId: child.childThreadId, runId: child.childRunId })) + expect(waited).toMatchObject({ status: 'finished', resultTruncated: true, resultChars: long.length, hint: expect.stringContaining('thread_read') }) + expect(waited.resultText).toBe(`${'r'.repeat(THREAD_RESULT_MAX_CHARS)}…`) + // The delegation path reads the stored result, not the tool's: the parent's notice row has every character. + const row = fx.engine.inbox.listForChildThread(child.childThreadId, 'child_result')[0] + expect((row.payload as { result: { text: string } }).result.text).toBe(long) + }) + it('a run that left no text is finished without resultText', async () => { const { call, result, fx, targetRun } = await world() fx.engine.markTerminal(targetRun.runId, 'failed', { error: 'the model failed' })