diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index d5eeed4d5..dfa25a925 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -150,13 +150,22 @@ Users can also detach an existing subagent from the subagents track. Detach is d `notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback. -Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches. +Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again. -The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt -crash can lose queued prompts. A durable send receipt remains pending until actual dispatch +- **`steer`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries. +- **`interrupt`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that replaces the running turn: the messages queued before it, then the interrupt. An older `steer` cannot start a turn after the newer `interrupt` that countermands it. +- **A person's prompt** (app, CLI, top-level MCP) is dispatched directly with its existing steer or interrupt behavior and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice. +- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held interrupt no longer interrupts; it waits like a `steer`. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued `steer` keeps its quiet window. + +A command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and an `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text. + +One provider prompt has one session mode. A batch released by an interrupt or a person's prompt uses the latest explicit choice in it, the person's own first. Steers with conflicting choices keep separate ordered dispatches. + +The pending message window is in memory. Clean shutdown flushes it, held messages included, before +closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued -admission within their original timeout and cancellation scope, and return permission checkpoints -while messages are waiting. +admission within their original timeout and cancellation scope, and return at permission +checkpoints and when a Stop holds the queue. Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses diff --git a/packages/cli/src/commands/agent/send.ts b/packages/cli/src/commands/agent/send.ts index 9a0bc465b..64ab32481 100644 --- a/packages/cli/src/commands/agent/send.ts +++ b/packages/cli/src/commands/agent/send.ts @@ -47,7 +47,7 @@ export function addSendOptions(cmd: Command): Command { .addOption( new Option( "--behavior ", - "Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)", + "Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt). An agent's interrupt delivers the messages queued before it first", ).choices(["interrupt", "steer"]), ) .option("--no-wait", "Return immediately without waiting for completion"); @@ -218,7 +218,7 @@ export async function runSendCommand( status: receipt.deliveryStatus ?? "sent", message: receipt.deliveryStatus === "queued" - ? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested" + ? "Message queued for delivery after two quiet seconds and the current turn ends. An interrupt replaces the turn now, after the messages queued before it" : "Message sent, not waiting for completion", }, schema: agentSendSchema, diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 89116f0e6..304520d49 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -7972,6 +7972,75 @@ test("replaceAgentRun does not emit idle or resolve waiters between interrupted unsubscribe(); }); +test("onStop hears a stop before the agent settles and ignores a replacing prompt", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-on-stop-")); + onTestFinished(() => rmSync(workdir, { recursive: true, force: true })); + + class HeldTurnSession extends TestAgentSession { + private turns = 0; + private activeTurnId: string | null = null; + + override async startTurn(): Promise<{ turnId: string }> { + const turnId = `held-turn-${++this.turns}`; + this.activeTurnId = turnId; + setTimeout(() => { + if (this.activeTurnId === turnId) + this.pushEvent({ type: "turn_started", provider: this.provider, turnId }); + }, 0); + return { turnId }; + } + + override async interrupt(): Promise { + const turnId = this.activeTurnId; + if (!turnId) return; + this.activeTurnId = null; + this.pushEvent({ + type: "turn_canceled", + provider: this.provider, + reason: "interrupted", + turnId, + }); + } + } + + class HeldTurnClient extends TestAgentClient { + override async createSession(config: AgentSessionConfig): Promise { + return new HeldTurnSession(config); + } + } + + const manager = new AgentManager({ clients: { codex: new HeldTurnClient() }, logger }); + const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const stops: Array<{ agentId: string; lifecycle: string | undefined }> = []; + const unsubscribe = manager.onStop((agentId) => { + stops.push({ agentId, lifecycle: manager.getAgent(agentId)?.lifecycle }); + }); + const drain = async (run: AsyncGenerator) => { + for await (const _event of run) { + // Drain events so lifecycle updates are applied. + } + }; + + const first = drain(manager.streamAgent(agent.id, "first run")); + await manager.waitForAgentRunStart(agent.id); + const second = drain(await manager.replaceAgentRun(agent.id, "second run")); + await manager.waitForAgentRunStart(agent.id); + expect(stops).toEqual([]); + + await expect(manager.cancelAgentRun(agent.id)).resolves.toEqual({ status: "settled" }); + expect(stops).toEqual([{ agentId: agent.id, lifecycle: "running" }]); + expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle"); + + // Nothing is running, so there is no turn to stop. + await expect(manager.cancelAgentRun(agent.id)).resolves.toEqual({ status: "not_running" }); + expect(stops).toHaveLength(1); + + unsubscribe(); + await Promise.all([first, second]); +}); + test("replaceAgentRun stays running when a stale old terminal arrives before the replacement turn is current", async () => { const workdir = mkdtempSync(join(tmpdir(), "agent-manager-replace-stale-terminal-")); const storagePath = join(workdir, "agents"); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 678ed8efa..0522e4102 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -158,8 +158,10 @@ export class AgentManagerShuttingDownError extends Error { } } +type RunCancellationCause = "reload" | "replace" | "rewind" | "stop"; + export class AgentRunCancellationError extends Error { - constructor(agentId: string, action: "reload" | "replace" | "rewind" | "stop") { + constructor(agentId: string, action: RunCancellationCause) { super( `Cannot ${action} agent ${agentId} because its active run cancellation was not acknowledged`, ); @@ -866,6 +868,7 @@ export class AgentManager { private readonly replacementMutationTails = new Map>(); private readonly runs = new AgentRunState(); private readonly subscribers = new Set(); + private readonly stopListeners = new Set<(agentId: string) => void>(); private readonly idFactory: () => string; private readonly registry?: AgentStorage; private readonly durableTimelineStore?: AgentTimelineStore; @@ -1154,6 +1157,15 @@ export class AgentManager { ); } + /** + * Notify before a running turn is stopped with no prompt replacing it: Stop and `cancel_agent`, + * not a replacing prompt, a reload, or a rewind. Listeners run before the agent settles. + */ + onStop(listener: (agentId: string) => void): () => void { + this.stopListeners.add(listener); + return () => this.stopListeners.delete(listener); + } + subscribe(callback: AgentSubscriber, options?: SubscribeOptions): () => void { const targetAgentId = options?.agentId == null ? null : validateAgentId(options.agentId, "subscribe"); @@ -3762,7 +3774,7 @@ export class AgentManager { this.touchUpdatedAt(agent); this.emitState(agent); try { - const result = await this.cancelAgentRunNow(agent.id); + const result = await this.cancelAgentRunNow(agent.id, "replace"); if (result.status === "refused") { throw new AgentRunCancellationError(agent.id, "replace"); } @@ -3958,10 +3970,18 @@ export class AgentManager { } } - async cancelAgentRun(agentId: string): Promise { + /** Stop the running turn. Nothing replaces it, so `onStop` listeners hear about it first. */ + cancelAgentRun(agentId: string): Promise { + return this.cancelRun(agentId, "stop"); + } + + private async cancelRun( + agentId: string, + cause: RunCancellationCause, + ): Promise { const cancellation = this.runForegroundMutation(agentId, () => { this.requireSessionAgent(agentId).pendingReplacement = false; - return this.cancelAgentRunNow(agentId); + return this.cancelAgentRunNow(agentId, cause); }); this.pendingCancellations.set(agentId, cancellation); try { @@ -3973,7 +3993,10 @@ export class AgentManager { } } - private async cancelAgentRunNow(agentId: string): Promise { + private async cancelAgentRunNow( + agentId: string, + cause: RunCancellationCause, + ): Promise { const agent = this.requireSessionAgent(agentId); const run = this.runs.getRun(agentId) ?? @@ -3981,6 +4004,9 @@ export class AgentManager { if (!run) { return { status: "not_running" }; } + if (cause === "stop") { + for (const listener of this.stopListeners) listener(agentId); + } const interruptAcknowledged = await this.interruptSession(agent.session, agentId); const settlement = await this.waitWithTimeout({ @@ -4038,11 +4064,8 @@ export class AgentManager { return { status: "settled" }; } - private async cancelAgentRunBefore( - agentId: string, - action: "reload" | "replace" | "rewind", - ): Promise { - const result = await this.cancelAgentRun(agentId); + private async cancelAgentRunBefore(agentId: string, action: "reload" | "rewind"): Promise { + const result = await this.cancelRun(agentId, action); if (result.status === "refused") { throw new AgentRunCancellationError(agentId, action); } diff --git a/packages/server/src/server/agent/agent-messages/delivery.test.ts b/packages/server/src/server/agent/agent-messages/delivery.test.ts index 77a9e619f..c441e2118 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.test.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.test.ts @@ -389,14 +389,18 @@ test("a turn starting during dispatch preparation keeps receipts queued and join await delivery.close(); }); -test("explicit interrupt bypasses a running turn while ordinary messages keep waiting", async () => { +test("an interrupt takes the messages queued before it along in one replacing dispatch", async () => { const clock = createClock(); - const sent: Array = []; + const sent: Array<{ ids: readonly string[]; behavior: string; idleOnly: boolean }> = []; const delivery = createAgentMessageDelivery({ schedule: clock.schedule, isRunning: () => true, dispatch: async (request) => { - sent.push(request.messageIds); + sent.push({ + ids: request.messageIds, + behavior: request.activeTurnBehavior, + idleOnly: request.idleOnly, + }); return "turn_started"; }, onError: (error) => { @@ -414,12 +418,12 @@ test("explicit interrupt bypasses a running turn while ordinary messages keep wa messageId: "interrupt", activeTurnBehavior: "interrupt", }); - clock.advance(2000); + // No quiet window: the interrupt releases at admission. await interrupt.dispatched; - expect(sent).toEqual([["interrupt"]]); - expect(delivery.hasPending("parent")).toBe(true); + expect(sent).toEqual([{ ids: ["wait", "interrupt"], behavior: "interrupt", idleOnly: false }]); + expect(delivery.hasPending("parent")).toBe(false); await delivery.close(); - expect(sent).toEqual([["interrupt"], ["wait"]]); + expect(sent).toHaveLength(1); }); test("shutdown flushes a dispatch that discovered a concurrent turn during preparation", async () => { @@ -503,7 +507,7 @@ test("conflicting modes dispatch on separate turn ends without changing the acti await delivery.close(); }); -test("interrupts retain separate mode choices while the recipient is busy", async () => { +test("each interrupt releases at admission and keeps its own mode choice", async () => { const clock = createClock(); const sent: Array<{ ids: readonly string[]; mode?: string }> = []; const delivery = createAgentMessageDelivery({ @@ -523,13 +527,19 @@ test("interrupts retain separate mode choices while the recipient is busy", asyn prompt: "message", activeTurnBehavior: "interrupt" as const, }; - const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" }); - const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" }); - clock.advance(2000); - await Promise.all([a.dispatched, b.dispatched]); + await delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" }).dispatched; + await delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" }).dispatched; + + // Sent back to back, the second still goes after the first, as its own prompt. + const c = delivery.enqueue({ ...message, messageId: "C", sessionMode: "plan" }); + const d = delivery.enqueue({ ...message, messageId: "D", sessionMode: "default" }); + await Promise.all([c.dispatched, d.dispatched]); + expect(sent).toEqual([ { ids: ["A"], mode: "plan" }, { ids: ["B"], mode: "default" }, + { ids: ["C"], mode: "plan" }, + { ids: ["D"], mode: "default" }, ]); await delivery.close(); }); @@ -976,3 +986,780 @@ test("a declined child command offer cannot bring back a withdrawn digest", asyn await delivery.close(); } }); + +interface Dispatched { + ids: readonly string[]; + behavior: string; + idleOnly: boolean; + mode?: string; +} + +/** One recipient with a running turn, observed the way the daemon wires the queue. */ +function createRecipient( + options: { running?: boolean; outOfBand?: (prompt: AgentPromptInput) => boolean } = {}, +) { + const clock = createClock(); + const sent: Dispatched[] = []; + /** Message ids in the order the provider received them, whoever sent the prompt. */ + const received: string[] = []; + const settleListeners = new Set<(recipientId: string) => void>(); + const stopListeners = new Set<(recipientId: string) => void>(); + let running = options.running ?? true; + const answered = Promise.resolve(); + let providerAnswer: Promise = answered; + let managerReady: Promise = answered; + const outOfBand = options.outOfBand; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + subscribe: (listener) => { + settleListeners.add(listener); + return () => settleListeners.delete(listener); + }, + onStop: (listener) => { + stopListeners.add(listener); + return () => stopListeners.delete(listener); + }, + tryRunOutOfBand: outOfBand + ? async (request, onAccepted) => { + const [message] = parseAgentMessages(String(request.prompt)) ?? []; + if (!message || !outOfBand(message.text)) return false; + onAccepted(); + return true; + } + : undefined, + dispatch: async (request) => { + // The manager admits the prompt, the provider gets it, and the provider answers. + await managerReady; + if (!request.admit()) throw new Error("The prompt was not admitted"); + received.push(...request.messageIds); + sent.push({ + ids: request.messageIds, + behavior: request.activeTurnBehavior, + idleOnly: request.idleOnly, + mode: request.sessionMode, + }); + // An accepted dispatch leaves the recipient with a running turn. + running = true; + await providerAnswer; + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const settle = () => new Promise((resolve) => setImmediate(resolve)); + let next = 0; + return { + clock, + sent, + received, + delivery, + settle, + ids: () => sent.flatMap((dispatch) => dispatch.ids), + send(activeTurnBehavior: "steer" | "interrupt", messageId = `m${next++}`, agentId = "sender") { + return delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId }, + messageId, + prompt: messageId, + activeTurnBehavior, + }).messageId; + }, + /** The manager waits, as it does for a turn that is still starting, before it admits a prompt. */ + holdAdmission() { + let ready!: () => void; + managerReady = new Promise((resolve) => { + ready = resolve; + }); + return { + async release() { + ready(); + managerReady = answered; + await settle(); + }, + }; + }, + /** The provider takes its time to answer the dispatches that follow. */ + holdProviderAnswer() { + let accept!: () => void; + let refuse!: (error: Error) => void; + providerAnswer = new Promise((resolve, reject) => { + accept = resolve; + refuse = reject; + }); + void providerAnswer.catch(() => undefined); + return { + async accept() { + accept(); + providerAnswer = answered; + await settle(); + }, + /** The turn never started, so the recipient is idle again. */ + async refuse(error: Error) { + running = false; + refuse(error); + providerAnswer = answered; + await settle(); + }, + }; + }, + /** A person's prompt: the provider turn it starts is running afterwards. */ + async person( + prompt: string, + messageId: string, + outcome: { fail?: Error; started?: Promise } = {}, + ) { + const prompts: AgentPromptInput[] = []; + const result = await delivery + .sendDirect({ recipientId: "recipient", prompt, messageId }, async (joined) => { + prompts.push(joined.prompt); + if (outcome.fail) throw outcome.fail; + const joinedIds = + typeof joined.prompt === "string" + ? parseAgentMessages(joined.prompt)?.map((message) => message.id) + : undefined; + received.push(...(joinedIds ?? [messageId])); + running = true; + return { + disposition: "turn_started" as const, + started: outcome.started ?? Promise.resolve(), + }; + }) + .catch((error: unknown) => error); + const [sentPrompt] = prompts; + return { + prompt: sentPrompt, + result, + ids: + typeof sentPrompt === "string" + ? (parseAgentMessages(sentPrompt)?.map((message) => message.id) ?? null) + : null, + }; + }, + async endTurn() { + running = false; + for (const listener of settleListeners) listener("recipient"); + await settle(); + }, + /** Stop / cancel_agent: the manager announces the stop, then the turn settles. */ + async stop() { + for (const listener of stopListeners) listener("recipient"); + running = false; + for (const listener of settleListeners) listener("recipient"); + await settle(); + }, + async tick(ms = 2000) { + clock.advance(ms); + await settle(); + }, + }; +} + +test.each(["sender", "another-sender"])( + "a steer that waited ten minutes is delivered ahead of a later interrupt from %s, never after it", + async (interrupter) => { + const recipient = createRecipient(); + recipient.send("steer", "go-ahead", "sender"); + for (let elapsed = 0; elapsed < 600_000; elapsed += 2000) await recipient.tick(); + expect(recipient.sent).toEqual([]); + + recipient.send("interrupt", "pause", interrupter); + await recipient.settle(); + expect(recipient.sent).toEqual([ + { ids: ["go-ahead", "pause"], behavior: "interrupt", idleOnly: false, mode: undefined }, + ]); + + await recipient.endTurn(); + await recipient.tick(); + expect(recipient.sent).toHaveLength(1); + expect(recipient.delivery.hasPending("recipient")).toBe(false); + await recipient.delivery.close(); + }, +); + +test("a steer admitted after an interrupt waits for the replacement turn to end", async () => { + const recipient = createRecipient(); + recipient.send("steer", "A"); + recipient.send("interrupt", "B"); + recipient.send("steer", "C"); + await recipient.tick(); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["A", "B"]]); + + await recipient.endTurn(); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["A", "B"], ["C"]]); + expect(recipient.sent[1]).toMatchObject({ behavior: "steer", idleOnly: true }); + await recipient.delivery.close(); +}); + +test("an interrupt is dispatched at admission while other messages keep arriving", async () => { + const recipient = createRecipient(); + recipient.send("interrupt", "pause"); + await recipient.settle(); + expect(recipient.ids()).toEqual(["pause"]); + // Reports that keep the quiet window open cannot hold a later interrupt back either. + for (let i = 0; i < 5; i++) { + recipient.send("steer", `report-${i}`); + await recipient.tick(1900); + } + recipient.send("interrupt", "pause-again"); + await recipient.settle(); + expect(recipient.sent.at(-1)).toMatchObject({ + ids: ["report-0", "report-1", "report-2", "report-3", "report-4", "pause-again"], + behavior: "interrupt", + }); + await recipient.delivery.close(); +}); + +test("steady arrivals cannot keep an idle recipient's quiet window open past ten seconds", async () => { + const recipient = createRecipient({ running: false }); + for (let i = 0; i < 6; i++) { + recipient.send("steer", `report-${i}`); + await recipient.tick(1900); + } + // 11.4 seconds of arrivals under two seconds apart: the window closed at ten. + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([ + ["report-0", "report-1", "report-2", "report-3", "report-4", "report-5"], + ]); + await recipient.delivery.close(); +}); + +test("the provider receives every prompt in admission order for every short interleaving", async () => { + const actions = ["steer", "interrupt", "person", "stop", "end-turn", "tick"] as const; + const length = 5; + for (let scenario = 0; scenario < actions.length ** length; scenario++) { + const recipient = createRecipient(); + const admitted: string[] = []; + const script: string[] = []; + let rest = scenario; + for (let step = 0; step < length; step++) { + const action = actions[rest % actions.length]!; + rest = Math.floor(rest / actions.length); + script.push(action); + if (action === "end-turn") await recipient.endTurn(); + else if (action === "tick") await recipient.tick(); + else if (action === "stop") await recipient.stop(); + else if (action === "person") { + admitted.push(`person-${step}`); + await recipient.person(`person-${step}`, `person-${step}`); + } else admitted.push(recipient.send(action)); + await recipient.settle(); + } + // Let every remaining message out: windows close, turns end, and a last prompt takes + // whatever a Stop still holds. + for (let i = 0; i < 4; i++) { + await recipient.tick(); + await recipient.endTurn(); + } + await recipient.person("last", "last"); + expect(recipient.received, script.join(" → ")).toEqual([...admitted, "last"]); + expect(recipient.delivery.hasPending("recipient"), script.join(" → ")).toBe(false); + await recipient.delivery.close(); + } +}); + +test("order and Stop hold for every short interleaving while the provider is slow to answer", async () => { + const actions = ["steer", "interrupt", "person", "stop", "tick", "hold", "answer"] as const; + const length = 5; + for (let scenario = 0; scenario < actions.length ** length; scenario++) { + // The provider is offered waiting messages as commands, so closed windows line up queue + // steps behind a dispatch the provider has not answered yet. + const recipient = createRecipient({ outOfBand: () => false }); + const admitted: string[] = []; + const admittedAt = new Map(); + const script: string[] = []; + let provider: ReturnType | undefined; + let stoppedWhileHeld = false; + let lastStop = -1; + let checked = 0; + const answer = async () => { + // A turn that Stop canceled while it was starting never starts. + if (stoppedWhileHeld) await provider?.refuse(new Error("run was canceled")); + else await provider?.accept(); + provider = undefined; + stoppedWhileHeld = false; + }; + /** After a Stop, no queue dispatch carries only messages from before it. */ + const checkStop = () => { + for (const dispatch of recipient.sent.slice(checked)) { + const newest = Math.max(...dispatch.ids.map((id) => admittedAt.get(id) ?? -1)); + expect(newest, `${script.join(" → ")}: ${dispatch.ids.join(",")}`).toBeGreaterThan( + lastStop, + ); + } + checked = recipient.sent.length; + }; + let rest = scenario; + for (let step = 0; step < length; step++) { + const action = actions[rest % actions.length]!; + rest = Math.floor(rest / actions.length); + script.push(action); + if (action === "tick") await recipient.tick(); + else if (action === "hold") provider ??= recipient.holdProviderAnswer(); + else if (action === "answer") await answer(); + else if (action === "stop") { + lastStop = step; + stoppedWhileHeld = provider !== undefined; + await recipient.stop(); + } else if (action === "person") { + admitted.push(`person-${step}`); + admittedAt.set(`person-${step}`, step); + void recipient.person(`person-${step}`, `person-${step}`); + } else { + const id = recipient.send(action); + admitted.push(id); + admittedAt.set(id, step); + } + await recipient.settle(); + checkStop(); + } + await answer(); + checkStop(); + // Let every remaining message out: windows close, turns end, and a last prompt takes + // whatever a Stop still holds. + for (let i = 0; i < 4; i++) { + await recipient.tick(); + await recipient.endTurn(); + } + await recipient.person("last", "last"); + // A turn the provider refused is sent again, so each prompt counts where it last arrived. + const arrived = recipient.received.filter( + (id, index) => recipient.received.lastIndexOf(id) === index, + ); + expect(arrived, script.join(" → ")).toEqual([...admitted, "last"]); + expect(recipient.delivery.hasPending("recipient"), script.join(" → ")).toBe(false); + await recipient.delivery.close(); + } +}); + +test("a person's prompt carries the queued messages ahead of it in the same prompt", async () => { + const recipient = createRecipient(); + recipient.send("steer", "go-ahead"); + await recipient.tick(); + + const { prompt, result } = await recipient.person("pause it", "person-1"); + expect(result).toMatchObject({ disposition: "turn_started" }); + expect(typeof prompt === "string" ? parseAgentMessages(prompt) : null).toEqual([ + { id: "go-ahead", source: { kind: "agent-message", agentId: "sender" }, text: "go-ahead" }, + { id: "person-1", source: null, text: "pause it" }, + ]); + expect(recipient.delivery.hasPending("recipient")).toBe(false); + + // Nothing is left to start a turn of its own when the person's turn ends. + await recipient.endTurn(); + await recipient.tick(); + expect(recipient.sent).toEqual([]); + await recipient.delivery.close(); +}); + +test("a person's prompt is untouched when nothing is queued, and a command travels alone", async () => { + const recipient = createRecipient(); + expect((await recipient.person("hello", "person-1")).prompt).toBe("hello"); + + recipient.send("steer", "report"); + await recipient.tick(); + // Providers parse commands from raw text, so the queue stays where it is. + expect((await recipient.person("/compact", "person-2")).prompt).toBe("/compact"); + expect(recipient.delivery.hasPending("recipient")).toBe(true); + await recipient.endTurn(); + expect(recipient.ids()).toEqual(["report"]); + await recipient.delivery.close(); +}); + +test("queued messages survive a person's prompt that fails to send", async () => { + const recipient = createRecipient(); + recipient.send("steer", "report"); + await recipient.tick(); + const failure = new Error("provider refused the prompt"); + expect((await recipient.person("hello", "person-1", { fail: failure })).result).toBe(failure); + expect(recipient.delivery.hasPending("recipient")).toBe(true); + await recipient.endTurn(); + expect(recipient.ids()).toEqual(["report"]); + await recipient.delivery.close(); +}); + +test("Stop holds the messages queued before it until the recipient's next prompt", async () => { + const recipient = createRecipient(); + recipient.send("steer", "go-ahead"); + await recipient.tick(); + + await recipient.stop(); + await recipient.tick(); + await recipient.tick(60_000); + // The stopped recipient stays stopped: no queued message starts a turn. + expect(recipient.sent).toEqual([]); + // Held messages need a prompt, so neither completion waits nor runtime guards wait for them. + expect(recipient.delivery.hasPending("recipient")).toBe(false); + await recipient.delivery.waitForDispatch("recipient", new AbortController().signal); + + // A message admitted after the Stop is a new prompt: the held one goes ahead of it. + recipient.send("steer", "later"); + await recipient.tick(); + expect(recipient.sent).toEqual([ + { ids: ["go-ahead", "later"], behavior: "steer", idleOnly: true, mode: undefined }, + ]); + await recipient.delivery.close(); +}); + +test("a person's prompt after Stop carries the held messages", async () => { + const recipient = createRecipient(); + recipient.send("steer", "go-ahead"); + await recipient.stop(); + + const { prompt } = await recipient.person("continue", "person-1"); + expect( + typeof prompt === "string" ? parseAgentMessages(prompt)?.map((message) => message.id) : null, + ).toEqual(["go-ahead", "person-1"]); + await recipient.endTurn(); + expect(recipient.sent).toEqual([]); + await recipient.delivery.close(); +}); + +test("a turn that ends on its own still releases the queue", async () => { + const recipient = createRecipient(); + recipient.send("steer", "report"); + await recipient.tick(); + await recipient.endTurn(); + expect(recipient.ids()).toEqual(["report"]); + await recipient.delivery.close(); +}); + +test("a prompt's place in line is decided when it is sent, not when the provider gets to it", async () => { + const recipient = createRecipient(); + const provider = recipient.holdProviderAnswer(); + recipient.send("interrupt", "first"); + await recipient.settle(); + + // All three arrive while the provider has not answered the first dispatch yet. + recipient.send("steer", "older"); + const person = recipient.person("stop and wait", "person-1"); + recipient.send("steer", "newer"); + await provider.accept(); + + expect((await person).ids).toEqual(["older", "person-1"]); + await recipient.tick(); + await recipient.endTurn(); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["first"], ["newer"]]); + await recipient.delivery.close(); +}); + +test("an interrupt sent after a person's prompt does not take older messages past that prompt", async () => { + const recipient = createRecipient(); + const provider = recipient.holdProviderAnswer(); + recipient.send("interrupt", "first"); + await recipient.settle(); + + recipient.send("steer", "older"); + const person = recipient.person("stop and wait", "person-1"); + recipient.send("interrupt", "newer"); + await provider.accept(); + + expect((await person).ids).toEqual(["older", "person-1"]); + await recipient.settle(); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["first"], ["newer"]]); + expect(recipient.sent[1]).toMatchObject({ behavior: "interrupt", idleOnly: false }); + await recipient.delivery.close(); +}); + +test("a queue step already in line does not pick up an interrupt sent after a person's prompt", async () => { + // The provider is offered waiting messages as commands, so a closed window lines up a + // queue step behind the dispatch in flight. + const recipient = createRecipient({ outOfBand: () => false }); + const provider = recipient.holdProviderAnswer(); + recipient.send("interrupt", "first"); + await recipient.settle(); + recipient.send("steer", "older"); + await recipient.tick(); + + const person = recipient.person("stop and wait", "person-1"); + recipient.send("interrupt", "newer"); + recipient.send("steer", "newest"); + await provider.accept(); + + expect((await person).ids).toEqual(["older", "person-1"]); + await recipient.settle(); + expect(recipient.received).toEqual(["first", "older", "person-1", "newer"]); + await recipient.tick(); + await recipient.endTurn(); + expect(recipient.received).toEqual(["first", "older", "person-1", "newer", "newest"]); + await recipient.delivery.close(); +}); + +test("Stop holds an interrupt that was still waiting for the provider", async () => { + const recipient = createRecipient(); + const provider = recipient.holdProviderAnswer(); + const first = recipient.send("interrupt", "first"); + await recipient.settle(); + recipient.send("interrupt", "second"); + await recipient.settle(); + expect(recipient.ids()).toEqual([first]); + + // Stop cancels the turn that was starting. The interrupt behind it must not start another. + await recipient.stop(); + await provider.refuse(new Error("run was canceled before its turn started")); + await recipient.tick(); + await recipient.tick(60_000); + expect(recipient.ids()).toEqual(["first"]); + expect(recipient.delivery.hasPending("recipient")).toBe(false); + + // Neither message is lost: both go with the recipient's next prompt, in order. + expect((await recipient.person("continue", "person-1")).ids).toEqual([ + "first", + "second", + "person-1", + ]); + await recipient.delivery.close(); +}); + +test("a held interrupt waits like any other message once a later message releases it", async () => { + const recipient = createRecipient(); + const provider = recipient.holdProviderAnswer(); + recipient.send("interrupt", "first"); + await recipient.settle(); + recipient.send("interrupt", "second"); + await recipient.stop(); + await provider.refuse(new Error("run was canceled before its turn started")); + + recipient.send("steer", "later"); + await recipient.settle(); + expect(recipient.ids()).toEqual(["first"]); + await recipient.tick(); + expect(recipient.sent.at(-1)).toEqual({ + ids: ["first", "second", "later"], + behavior: "steer", + idleOnly: true, + mode: undefined, + }); + await recipient.delivery.close(); +}); + +test("queued messages return to the queue when the provider rejects the person's turn", async () => { + const recipient = createRecipient(); + const report = recipient.delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId: "sender" }, + messageId: "report", + prompt: "report", + }); + await recipient.tick(); + + let rejectStart!: (error: Error) => void; + const started = new Promise((_resolve, reject) => { + rejectStart = reject; + }); + void started.catch(() => undefined); + const person = await recipient.person("hello", "person-1", { started }); + expect(person.result).toMatchObject({ disposition: "turn_started" }); + expect(person.ids).toEqual(["report", "person-1"]); + + // An interrupt sent while the provider decides must not overtake the older report. + recipient.send("interrupt", "pause"); + await recipient.settle(); + expect(recipient.sent).toEqual([]); + + rejectStart(new Error("provider rejected the turn")); + await recipient.settle(); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["report", "pause"]]); + await expect(report.dispatched).resolves.toBe("turn_started"); + await recipient.delivery.close(); +}); + +test("a person's prompt that begins with a path is plain text and carries the queue", async () => { + const recipient = createRecipient(); + recipient.send("steer", "go-ahead"); + await recipient.tick(); + + const path = await recipient.person( + "/tmp/build.log is stale. Wait for my next prompt.", + "person-1", + ); + expect(path.ids).toEqual(["go-ahead", "person-1"]); + + recipient.send("steer", "report"); + await recipient.tick(); + for (const command of ["/compact", " /goal pause", "/review focus on tests"]) { + expect((await recipient.person(command, "person-2")).prompt).toBe(command); + } + expect(recipient.delivery.hasPending("recipient")).toBe(true); + await recipient.delivery.close(); +}); + +test("an interrupt the provider runs as a command beside the turn takes no queued message along", async () => { + const recipient = createRecipient({ outOfBand: (prompt) => prompt === "/compact" }); + recipient.send("steer", "report"); + await recipient.tick(); + + const compact = recipient.delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId: "sender" }, + messageId: "compact", + prompt: "/compact", + activeTurnBehavior: "interrupt", + }); + await expect(compact.dispatched).resolves.toBe("out_of_band"); + // The command replaced nothing, so the report still waits for the turn to end. + expect(recipient.sent).toEqual([]); + await recipient.endTurn(); + expect(recipient.ids()).toEqual(["report"]); + + // An interrupt the provider declines to run beside the turn replaces it, queue first. + recipient.send("steer", "another-report"); + const plain = recipient.delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId: "sender" }, + messageId: "pause", + prompt: "pause", + activeTurnBehavior: "interrupt", + }); + await expect(plain.dispatched).resolves.toBe("turn_started"); + expect(recipient.sent.at(-1)).toMatchObject({ + ids: ["another-report", "pause"], + behavior: "interrupt", + }); + await recipient.delivery.close(); +}); + +test("an interrupt keeps its place ahead of a later person's prompt when a queue step is already in line", async () => { + // The provider is offered waiting messages as commands, so a closed window lines up a + // queue step behind the dispatch in flight. + const recipient = createRecipient({ outOfBand: () => false }); + const provider = recipient.holdProviderAnswer(); + recipient.send("interrupt", "first"); + await recipient.settle(); + recipient.send("steer", "older"); + await recipient.tick(); + + recipient.send("interrupt", "pause"); + const person = recipient.person("carry on", "person-1"); + await provider.accept(); + + // The interrupt replaces the turn itself; the person's prompt follows it and carries nothing. + expect((await person).prompt).toBe("carry on"); + expect(recipient.sent.at(-1)).toEqual({ + ids: ["older", "pause"], + behavior: "interrupt", + idleOnly: false, + mode: undefined, + }); + expect(recipient.received).toEqual(["first", "older", "pause", "person-1"]); + await recipient.delivery.close(); +}); + +test("an interrupt that was waiting when Stop arrived stays held when a later message reopens the queue", async () => { + const recipient = createRecipient(); + const manager = recipient.holdAdmission(); + recipient.send("interrupt", "pause"); + await recipient.settle(); + + // The later steer arrives before the manager gets back to the interrupt. + await recipient.stop(); + recipient.send("steer", "later"); + await manager.release(); + expect(recipient.sent).toEqual([]); + + // The held interrupt goes with the later message, as a steer. + await recipient.tick(); + expect(recipient.sent).toEqual([ + { ids: ["pause", "later"], behavior: "steer", idleOnly: true, mode: undefined }, + ]); + await recipient.delivery.close(); +}); + +test("messages whose starting turn Stop canceled are kept when a later message reopens the queue", async () => { + const recipient = createRecipient({ running: false }); + const provider = recipient.holdProviderAnswer(); + const report = recipient.delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId: "sender" }, + messageId: "report", + prompt: "report", + }); + await recipient.tick(); + expect(recipient.ids()).toEqual(["report"]); + + await recipient.stop(); + recipient.send("steer", "later"); + await provider.refuse(new Error("run was canceled before its turn started")); + + await recipient.tick(); + expect(recipient.sent.at(-1)).toMatchObject({ ids: ["report", "later"] }); + await expect(report.dispatched).resolves.toBe("turn_started"); + await recipient.delivery.close(); +}); + +test("shutdown delivers the messages a rejected person's turn returns to the queue", async () => { + const recipient = createRecipient(); + const report = recipient.delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId: "sender" }, + messageId: "report", + prompt: "report", + }); + await recipient.tick(); + let rejectStart!: (error: Error) => void; + const started = new Promise((_resolve, reject) => { + rejectStart = reject; + }); + void started.catch(() => undefined); + await recipient.person("hello", "person-1", { started }); + + // Shutdown begins while the provider is still deciding, then the provider rejects the turn. + let closed = false; + const closing = recipient.delivery.close().then(() => { + closed = true; + return undefined; + }); + rejectStart(new Error("provider rejected the turn")); + await recipient.settle(); + await recipient.settle(); + + expect(closed).toBe(true); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["report"]]); + await expect(report.dispatched).resolves.toBe("turn_started"); + await closing; +}); + +test("a queue step reserved before Stop releases nothing once the queue reopens", async () => { + // The provider is offered waiting messages as commands, so a closed window lines up a + // queue step behind the dispatch in flight. + const recipient = createRecipient({ outOfBand: () => false }); + const provider = recipient.holdProviderAnswer(); + recipient.send("interrupt", "first"); + await recipient.settle(); + recipient.send("steer", "older"); + await recipient.tick(); + + // The new interrupt arrives before the provider has finished stopping. + await recipient.stop(); + recipient.send("interrupt", "newer"); + await provider.refuse(new Error("run was canceled before its turn started")); + await recipient.settle(); + + // One turn after the Stop: the held messages, then the interrupt that follows them. + expect(recipient.sent.slice(1)).toEqual([ + { ids: ["first", "older", "newer"], behavior: "interrupt", idleOnly: false, mode: undefined }, + ]); + await recipient.delivery.close(); +}); + +test("held messages stay held when the message that reopened the queue is withdrawn", async () => { + const recipient = createRecipient(); + recipient.send("steer", "older"); + await recipient.stop(); + + // A later message reopens the queue, then its sender takes it back before the window closes. + recipient.send("steer", "update", "watcher"); + expect( + recipient.delivery.withdrawPending( + "recipient", + (source) => source.kind === "agent-message" && source.agentId === "watcher", + ), + ).toBe(1); + await recipient.tick(); + await recipient.tick(60_000); + expect(recipient.sent).toEqual([]); + expect(recipient.delivery.hasPending("recipient")).toBe(false); + + expect((await recipient.person("continue", "person-1")).ids).toEqual(["older", "person-1"]); + await recipient.delivery.close(); +}); diff --git a/packages/server/src/server/agent/agent-messages/delivery.ts b/packages/server/src/server/agent/agent-messages/delivery.ts index 3a901aa77..dcfab2d68 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.ts @@ -1,7 +1,16 @@ -import { AgentTurnBusyError, type PromptDispatchDisposition } from "../agent-prompt.js"; +import { + AgentTurnBusyError, + type PromptDispatchDisposition, + type PromptDispatchResult, +} from "../agent-prompt.js"; import { randomUUID } from "node:crypto"; import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js"; -import { prepareAgentMessage, type AgentPromptSource } from "./envelope.js"; +import { envelopeMessage, prepareAgentMessage, type AgentPromptSource } from "./envelope.js"; + +/** A message's quiet window closes this long after the latest arrival. */ +const QUIET_MS = 2000; +/** Steady arrivals cannot keep a quiet window open longer than this. */ +const MAX_COLLECTING_MS = 10_000; interface Message { recipientId: string; @@ -21,50 +30,164 @@ interface Receipt { dispatched: Promise; } interface Admitted extends Message { - sequence: number; - state: "queued" | "claimed" | "withdrawn"; + /** claimed: a dispatch has it. It leaves the queue when the provider admits the prompt. */ + state: "queued" | "claimed" | "withdrawn" | "rejected"; + /** An interrupt that was not released yet. After a Stop it waits like any other message. */ + urgent: boolean; + /** A Stop found it in the queue. It waits for a prompt admitted after that Stop. */ + held: boolean; outOfBandDeclined: boolean; receipt: Receipt; resolve(disposition: PromptDispatchDisposition): void; reject(error: unknown): void; } +/** + * A recipient's queue. A dispatch in flight for the recipient is its entry in `releasing`: + * collecting → waiting → releasing, and Stop moves the queue to held. + */ +interface Inbox { + /** + * Admission order. A message stays, in its place, until the provider admits the prompt that + * carries it, so a Stop or a later prompt always finds it here. + */ + messages: Admitted[]; + phase: + | "collecting" // The quiet window is open. + | "waiting" // The window closed; released as soon as the recipient is idle. + | "held"; // A Stop held it; released with the recipient's next prompt. + /** The quiet window while collecting, the busy retry while waiting. */ + cancelTimer(): void; + cancelCap(): void; + /** A polling queue step is already in line behind the recipient's current operation. */ + advancing: boolean; + /** Stops seen. A queue step reserved before a Stop is void, whatever is admitted afterwards. */ + stops: number; +} interface DispatchRequest { recipientId: string; messageIds: readonly string[]; prompt: AgentPromptInput; activeTurnBehavior: "steer" | "interrupt"; idleOnly: boolean; - /** Claim this exact prompt at provider admission. A withdrawn message invalidates the batch. */ + /** + * Claim this exact prompt at provider admission. A withdrawn message or a Stop that reached + * the recipient first invalidates it. + */ admit(): boolean; sessionMode?: string; clearPendingPermissions: boolean; unarchive: boolean; } +/** A prompt that does not wait its turn: a person's, or the daemon's own. */ +interface DirectPrompt { + recipientId: string; + prompt: AgentPromptInput; + source?: AgentPromptSource; + messageId?: string; + sessionMode?: string; + unarchive?: boolean; +} +/** The provider prompt a direct prompt became. Unchanged when nothing was queued. */ +interface JoinedPrompt { + prompt: AgentPromptInput; + messageId?: string; + sessionMode?: string; + unarchive: boolean; +} interface Dependencies { /** Includes admitted starts and provider turns, including compaction. */ isRunning?: (recipientId: string) => boolean; hasPendingPermission?: (recipientId: string) => boolean; /** Notify when recipient state changes; admission still checks whether it is idle. */ subscribe?: (listener: (recipientId: string) => void) => () => void; + /** Notify before a recipient's turn is stopped with no prompt replacing it. */ + onStop?: (listener: (recipientId: string) => void) => () => void; tryRunOutOfBand?(request: DispatchRequest, onAccepted: () => void): Promise; + /** Hand a batch to the recipient. Resolves once the provider admitted it. */ dispatch(request: DispatchRequest): Promise; + /** Bound the wait for the provider to admit a direct prompt. Unbounded when absent. */ + awaitStart?(recipientId: string, started: Promise): Promise; onError(error: unknown, request: DispatchRequest): void; /** Return a cancellation function. Production uses the daemon's event loop. */ schedule?: (delayMs: number, callback: () => void) => () => void; } export interface AgentMessageDelivery { + /** Admit a message that waits its turn. An interrupt releases at once, with everything queued. */ enqueue(message: Message): Receipt; + /** + * Send a prompt that does not wait its turn. The messages admitted before it go ahead of it + * in the same provider prompt, so none starts a turn of its own afterwards. Its place is + * decided by this call, whenever the recipient gets to it. A command travels alone. + */ + sendDirect( + direct: DirectPrompt, + send: (joined: JoinedPrompt) => Promise, + ): Promise; /** Remove matching messages that the queue still owns before dispatcher handoff. */ withdrawPending(recipientId: string, matches: (source: AgentPromptSource) => boolean): number; - /** Queued messages and provider dispatches still owned by this recipient. */ + /** Messages and dispatches that will proceed without a new prompt. Held messages do not count. */ hasPending(recipientId: string): boolean; /** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */ close(): Promise; - /** Completion waits include admitted messages, but return at permission checkpoints. */ + /** Completion waits include admitted messages, but return at permission checkpoints and holds. */ waitForDispatch(recipientId: string, signal: AbortSignal): Promise; } -/** Recipient-owned agent delivery. Human prompts never enter this module. */ +const isQueued = (message: Admitted): boolean => message.state === "queued"; +const isWithdrawn = (message: Admitted): boolean => message.state === "withdrawn"; +const isUrgent = (message: Admitted): boolean => isQueued(message) && message.urgent; +const isOfferable = (message: Admitted): boolean => + isQueued(message) && !message.outOfBandDeclined && message.sessionMode === undefined; + +/** + * Providers read a command from the raw start of the prompt: a slash and a name with no + * second slash in it. A path such as `/tmp/build.log` is plain text. + */ +function isCommand(prompt: AgentPromptInput): boolean { + const first = typeof prompt === "string" ? prompt : prompt[0]; + if (typeof first !== "string" && first?.type !== "text") return false; + const text = typeof first === "string" ? first : first.text; + return /^\/[^\s/]+(\s|$)/.test(text.trim()); +} + +function combine(prompts: AgentPromptInput[]): AgentPromptInput { + return prompts.every((entry) => typeof entry === "string") + ? prompts.join("\n\n") + : prompts.flatMap((entry): AgentPromptContentBlock[] => + typeof entry === "string" ? [{ type: "text", text: entry }] : entry, + ); +} + +function envelope(message: Admitted): AgentPromptInput { + return prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt; +} + +/** Explicitly conflicting session modes require separate, ordered dispatches. */ +function modeGroups(messages: Admitted[]): Admitted[][] { + const groups: Admitted[][] = []; + let group: Admitted[] = []; + let mode: string | undefined; + for (const message of messages) { + if (mode && message.sessionMode && mode !== message.sessionMode) { + groups.push(group); + group = []; + mode = undefined; + } + group.push(message); + mode ??= message.sessionMode; + } + if (group.length) groups.push(group); + return groups; +} + +/** + * Owns the order in which prompts reach a recipient. Delivery order equals admission order: + * only a prefix of the queue is ever dispatched, except a command a provider runs out of band. + * + * Every prompt for a recipient takes its place when it is admitted, and one operation at a + * time acts on the queue. A message stays in the queue until the provider admits the prompt + * that carries it, so agent messages, a person's prompts, and Stop all decide over the same list. + */ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMessageDelivery { const schedule = dependencies.schedule ?? @@ -72,70 +195,118 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes const timer = setTimeout(callback, delayMs); return () => clearTimeout(timer); }); - const pending = new Map(); - const dispatching = new Map>(); - const admitted = new Map>(); - let sequence = 0; + const inboxes = new Map(); + const releasing = new Map>(); let closed = false; let closing: Promise | undefined; - const isWithdrawn = (message: Admitted): boolean => message.state === "withdrawn"; + const isRunning = (recipientId: string): boolean => + Boolean(dependencies.isRunning?.(recipientId)); + const isHeld = (recipientId: string): boolean => inboxes.get(recipientId)?.phase === "held"; - function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest { - const prompts = messages.map( - (message) => - prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt, - ); - const prompt: AgentPromptInput = prompts.every((entry) => typeof entry === "string") - ? prompts.join("\n\n") - : prompts.flatMap((entry): AgentPromptContentBlock[] => - typeof entry === "string" ? [{ type: "text", text: entry }] : entry, - ); + /** Tells whether a Stop has reached the recipient since this call. */ + function watchForStop(inbox: Inbox): () => boolean { + const seen = inbox.stops; + return () => inbox.stops !== seen; + } + + function requestFor( + recipientId: string, + messages: Admitted[], + idleOnly: boolean, + stopped: () => boolean, + ): DispatchRequest { return { recipientId, - idleOnly: !closed && messages[0]!.activeTurnBehavior !== "interrupt", + idleOnly, admit() { - if (messages.some(isWithdrawn)) return false; + if (messages.some(isWithdrawn) || stopped()) return false; for (const message of messages) message.state = "claimed"; return true; }, messageIds: messages.map((message) => message.receipt.messageId), - prompt, - activeTurnBehavior: messages[0]!.activeTurnBehavior ?? "steer", - sessionMode: messages.find((message) => message.sessionMode)?.sessionMode, + prompt: combine(messages.map(envelope)), + activeTurnBehavior: messages.some((message) => message.urgent) ? "interrupt" : "steer", + // An interrupt may follow a message that asked for another mode; the latest choice wins. + sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode, clearPendingPermissions: messages.some((message) => message.clearPendingPermissions), unarchive: messages.some((message) => message.unarchive !== false), }; } - function withdraw(message: Admitted): void { - message.state = "withdrawn"; - message.reject(new DOMException("Agent message withdrawn", "AbortError")); + function retire(recipientId: string, inbox: Inbox): void { + inbox.cancelTimer(); + inbox.cancelCap(); + if (inboxes.get(recipientId) === inbox) inboxes.delete(recipientId); } - function withdrawPending(recipientId: string, matches: (message: Admitted) => boolean): number { - let removed = 0; - for (const message of admitted.get(recipientId) ?? []) { - if (message.state !== "queued" || !matches(message)) continue; - withdraw(message); - removed++; - } - const entry = pending.get(recipientId); - if (entry && removed) { - entry.messages = entry.messages.filter((message) => !isWithdrawn(message)); - if (!entry.messages.length) { - entry.cancel(); - pending.delete(recipientId); - } - } - return removed; + /** The message reached its end: delivered, failed, or withdrawn. */ + function settle(message: Admitted, state: "claimed" | "rejected" | "withdrawn"): void { + message.state = state; + const inbox = inboxes.get(message.recipientId); + const index = inbox?.messages.indexOf(message) ?? -1; + if (!inbox || index < 0) return; + inbox.messages.splice(index, 1); + if (!inbox.messages.length) retire(message.recipientId, inbox); } - function dispatch(recipientId: string, batch: Admitted[]): void { - queueDispatch(recipientId, async () => { - const messages = batch.filter((message) => message.state === "queued"); + function claim( + message: Admitted, + disposition: PromptDispatchDisposition, + request: DispatchRequest, + ): void { + settle(message, "claimed"); + try { + message.onDispatch?.(disposition); + } catch (error) { + dependencies.onError(error, request); + } + message.resolve(disposition); + } + + /** A dispatch that did not happen leaves its messages queued, each still in its place. */ + function handBack(messages: Admitted[]): void { + for (const message of messages) if (message.state === "claimed") message.state = "queued"; + } + + function fail(message: Admitted, error: unknown): void { + settle(message, "rejected"); + message.reject(error); + } + + /** One operation per recipient at a time, whether the queue or a person started it. */ + function run(recipientId: string, operation: () => Promise): void { + const previous = releasing.get(recipientId) ?? Promise.resolve(); + const tracked = previous + .then(operation) + .catch(() => undefined) + .then(() => rest(recipientId)); + releasing.set(recipientId, tracked); + void tracked.then(() => { + if (releasing.get(recipientId) === tracked) releasing.delete(recipientId); + return undefined; + }); + } + + /** After an operation, a waiting queue keeps polling for the turn to end. */ + function rest(recipientId: string): void { + const inbox = inboxes.get(recipientId); + if (!inbox || inbox.advancing || inbox.phase !== "waiting") return; + inbox.cancelTimer(); + inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId)); + } + + /** Dispatch one batch. A batch that finds the recipient stopped, or busy when idle-only, stays queued. */ + async function deliver( + recipientId: string, + batch: Admitted[], + idleOnly: boolean, + stopped: () => boolean, + ): Promise { + for (;;) { + const messages = batch.filter(isQueued); if (!messages.length) return; - const request = requestFor(recipientId, messages); + const request = requestFor(recipientId, messages, idleOnly && !closed, stopped); try { for (const message of messages) message.beforeDispatch?.(); let disposition: PromptDispatchDisposition; @@ -147,170 +318,236 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes // Shutdown drains admitted messages before closing the recipients. disposition = await dependencies.dispatch({ ...request, idleOnly: false }); } - for (const message of messages) { - message.state = "claimed"; - try { - message.onDispatch?.(disposition); - } catch (error) { - dependencies.onError(error, request); - } - message.resolve(disposition); - } - return undefined; + for (const message of messages) claim(message, disposition, request); + return; } catch (error) { + // A Stop reached the recipient before the provider admitted the prompt. + if (stopped()) { + handBack(messages); + return; + } + // A withdrawal invalidated this exact prompt; the rest goes again without it. if (messages.some(isWithdrawn)) { - requeue(recipientId, messages); - if (closed) flush(recipientId); + handBack(messages); + continue; + } + if (error instanceof AgentTurnBusyError && request.idleOnly) { + handBack(messages); return; } - if (error instanceof AgentTurnBusyError && !closed) { - requeue(recipientId, messages); - return; - } - for (const message of messages) message.reject(error); + for (const message of messages) fail(message, error); dependencies.onError(error, request); throw error; } + } + } + + /** A provider may run a command beside the turn. Each message is offered once, alone. */ + async function offerOutOfBand( + recipientId: string, + candidates: Admitted[], + stopped: () => boolean, + stillDue: () => boolean = () => true, + ): Promise { + const tryRunOutOfBand = dependencies.tryRunOutOfBand; + if (!tryRunOutOfBand) return; + for (const message of candidates) { + if (closed || stopped() || !stillDue()) return; + if (!isOfferable(message)) continue; + const request = requestFor(recipientId, [message], true, stopped); + try { + const accepted = await tryRunOutOfBand(request, () => { + if (!request.admit()) throw new Error("Queued agent message was withdrawn"); + message.beforeDispatch?.(); + }); + if (accepted) claim(message, "out_of_band", request); + else message.outOfBandDeclined = true; + } catch (error) { + if (!isQueued(message) || stopped()) continue; + fail(message, error); + dependencies.onError(error, request); + } + } + } + + /** + * Move the queue forward: an interrupt takes it now, a closed window once the turn has ended. + * `ahead` is what was admitted before this step got in line; it leaves later messages alone. + */ + async function advance( + recipientId: string, + inbox: Inbox, + ahead: Admitted[], + stopped: () => boolean, + ): Promise { + const interrupts = ahead.filter(isUrgent); + if (interrupts.length) { + // A command the provider runs beside the turn replaces nothing, so it takes nothing along. + await offerOutOfBand(recipientId, interrupts, stopped); + const last = ahead.findLastIndex(isUrgent); + if (last >= 0) { + // An interrupt does not jump the queue: everything admitted before it goes first. + await deliver(recipientId, ahead.slice(0, last + 1), false, stopped); + return; + } + } + if (inbox.phase !== "waiting") return; + const running = (): boolean => inbox.phase === "waiting" && isRunning(recipientId); + if (running()) await offerOutOfBand(recipientId, ahead, stopped, running); + // Later mode groups stay queued for the turn ends that follow. + if (inbox.phase === "waiting" && !isRunning(recipientId)) + await deliver(recipientId, modeGroups(ahead.filter(isQueued))[0] ?? [], true, stopped); + } + + /** + * Line up a queue step behind the recipient's current operation, for what is queued now. + * A Stop voids the steps reserved before it: what they covered waits for the next prompt. + */ + function lineUp(recipientId: string, inbox: Inbox, onStart?: () => void): void { + const ahead = [...inbox.messages]; + const stopped = watchForStop(inbox); + run(recipientId, async () => { + onStart?.(); + if (!stopped()) await advance(recipientId, inbox, ahead, stopped); }); } - function queueDispatch(recipientId: string, operation: () => Promise): void { - const previous = dispatching.get(recipientId) ?? Promise.resolve(); - const dispatched = previous.catch(() => undefined).then(operation); - dispatching.set(recipientId, dispatched); - void dispatched - .finally(() => { - if (dispatching.get(recipientId) === dispatched) dispatching.delete(recipientId); - }) - .catch(() => undefined); + /** Polling lines up one step at a time; an interrupt always reserves its own place. */ + function nudge(recipientId: string, inbox: Inbox): void { + if (inbox.advancing) return; + inbox.advancing = true; + lineUp(recipientId, inbox, () => { + inbox.advancing = false; + }); } - function requeue(recipientId: string, messages: Admitted[]): void { - const queued = messages.filter((message) => !isWithdrawn(message)); - if (!queued.length) return; - for (const message of queued) message.state = "queued"; - const entry = pending.get(recipientId) ?? { + /** The quiet window closed, a retry came due, or the recipient settled. */ + function attempt(recipientId: string): void { + const inbox = inboxes.get(recipientId); + if (!inbox || inbox.phase === "held") return; + inbox.cancelTimer(); + inbox.cancelCap(); + inbox.phase = "waiting"; + const running = isRunning(recipientId); + if (running) inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId)); + const nothingToOffer = !dependencies.tryRunOutOfBand || !inbox.messages.some(isOfferable); + if (running && nothingToOffer) return; + nudge(recipientId, inbox); + } + + function admit(item: Admitted): void { + const existing = inboxes.get(item.recipientId); + const inbox = existing ?? { messages: [], - ready: true, - cancel: () => {}, + phase: "waiting", + cancelTimer: () => {}, + cancelCap: () => {}, + advancing: false, + stops: 0, }; - entry.cancel(); - entry.messages.push(...queued); - entry.messages.sort((a, b) => a.sequence - b.sequence); - entry.cancel = schedule(2000, () => flush(recipientId)); - pending.set(recipientId, entry); - } - - function flush(recipientId: string): void { - const entry = pending.get(recipientId); - if (!entry) return; - entry.ready = true; - entry.cancel(); - if (!closed && dependencies.isRunning?.(recipientId)) { - const interrupts = entry.messages.filter( - (message) => message.activeTurnBehavior === "interrupt", - ); - entry.messages = entry.messages.filter( - (message) => message.activeTurnBehavior !== "interrupt", - ); - if (interrupts.length) dispatchGroups(recipientId, interrupts); - if (entry.messages.length && dependencies.tryRunOutOfBand) { - pending.delete(recipientId); - offerOutOfBand(recipientId, entry.messages); - } else if (entry.messages.length) { - entry.cancel = schedule(2000, () => flush(recipientId)); - } else { - pending.delete(recipientId); - } + inboxes.set(item.recipientId, inbox); + inbox.messages.push(item); + inbox.cancelTimer(); + if (item.urgent) { + // An interrupt does not wait: it closes the window and takes the queue along. Its place + // is reserved now, so a prompt admitted after it cannot take it away. + inbox.cancelCap(); + inbox.phase = "waiting"; + lineUp(item.recipientId, inbox); return; } - pending.delete(recipientId); - dispatchGroups(recipientId, entry.messages); + inbox.cancelTimer = schedule(QUIET_MS, () => attempt(item.recipientId)); + if (inbox.phase === "collecting") return; + // A new window. It closes after a quiet spell, and no later than the cap. + inbox.phase = "collecting"; + inbox.cancelCap = schedule(MAX_COLLECTING_MS, () => attempt(item.recipientId)); } - function offerOutOfBand(recipientId: string, messages: Admitted[]): void { - queueDispatch(recipientId, async () => { - const waiting: Admitted[] = []; - for (const message of messages) { - if (isWithdrawn(message)) continue; - if ( - message.outOfBandDeclined || - message.sessionMode !== undefined || - closed || - !dependencies.isRunning?.(recipientId) - ) { - waiting.push(message); - continue; - } - const request = requestFor(recipientId, [message]); - try { - const accepted = await dependencies.tryRunOutOfBand!(request, () => { - if (!request.admit()) throw new Error("Queued agent message was withdrawn"); - message.beforeDispatch?.(); - }); - if (!accepted) { - message.outOfBandDeclined = true; - waiting.push(message); - continue; - } - message.state = "claimed"; - try { - message.onDispatch?.("out_of_band"); - } catch (error) { - dependencies.onError(error, request); - } - message.resolve("out_of_band"); - } catch (error) { - if (isWithdrawn(message)) continue; - message.reject(error); - dependencies.onError(error, request); - } - } - if (waiting.length) requeue(recipientId, waiting); - if (closed || (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId))) - flush(recipientId); - }); - } - - function dispatchGroups(recipientId: string, messages: Admitted[]): void { - const groups: Admitted[][] = []; - let group: Admitted[] = []; - let mode: string | undefined; - for (const message of messages) { - // Explicitly conflicting send options require separate, ordered dispatches. - if ( - group.length && - ((message.activeTurnBehavior ?? "steer") !== (group[0]!.activeTurnBehavior ?? "steer") || - (mode && message.sessionMode && mode !== message.sessionMode)) - ) { - groups.push(group); - group = []; - mode = undefined; - } - group.push(message); - mode ??= message.sessionMode; + function join(queued: Admitted[], direct: DirectPrompt): JoinedPrompt { + if (!queued.length) { + const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId); + return { + prompt: own.prompt, + messageId: own.messageId, + sessionMode: direct.sessionMode, + unarchive: direct.unarchive !== false, + }; } - if (group.length) groups.push(group); - let started = false; - for (const batch of groups) { - if (!closed && started && batch[0]!.activeTurnBehavior !== "interrupt") { - requeue(recipientId, batch); - } else { - dispatch(recipientId, batch); - started = true; + // Sharing a prompt with agent messages, a person's text needs its own envelope to stay + // a separate row with its own identity. + const own = envelopeMessage(direct.prompt, direct.source ?? null, direct.messageId); + return { + prompt: combine([...queued.map(envelope), own.prompt]), + messageId: own.messageId, + sessionMode: + direct.sessionMode ?? queued.findLast((message) => message.sessionMode)?.sessionMode, + unarchive: + direct.unarchive !== false || queued.some((message) => message.unarchive !== false), + }; + } + + /** + * Messages that rode a direct prompt are delivered when the provider admits that prompt. + * Until it answers, nothing later may pass them. + */ + async function ride(riders: Admitted[], result: PromptDispatchResult): Promise { + if (!riders.length) return; + const { recipientId } = riders[0]!; + if (result.disposition === "turn_started") { + try { + await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started); + } catch { + // The provider rejected the prompt that carried them. They go again, in their place. + handBack(riders); + return; } } + const request = requestFor(recipientId, riders, false, () => false); + for (const message of riders) claim(message, result.disposition, request); + } + + /** + * The stopped recipient stays stopped. Its queue, interrupts included, goes with whatever + * prompts it next. + */ + function hold(inbox: Inbox): void { + inbox.cancelTimer(); + inbox.cancelCap(); + inbox.phase = "held"; + inbox.stops++; + for (const message of inbox.messages) { + message.urgent = false; + message.held = true; + } } const unsubscribe = dependencies.subscribe?.((recipientId) => { - if (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId)) - flush(recipientId); + if (inboxes.get(recipientId)?.phase === "waiting" && !isRunning(recipientId)) + attempt(recipientId); + }); + const unsubscribeStop = dependencies.onStop?.((recipientId) => { + const inbox = inboxes.get(recipientId); + if (inbox) hold(inbox); }); return { - withdrawPending: (recipientId, matches) => - withdrawPending(recipientId, (message) => matches(message.source)), - hasPending: (recipientId) => pending.has(recipientId) || dispatching.has(recipientId), + withdrawPending(recipientId, matches) { + const withdrawn = (inboxes.get(recipientId)?.messages ?? []).filter( + (message) => isQueued(message) && matches(message.source), + ); + for (const message of withdrawn) { + settle(message, "withdrawn"); + message.reject(new DOMException("Agent message withdrawn", "AbortError")); + } + // Without the message that reopened it after a Stop, the queue is held again. + const inbox = inboxes.get(recipientId); + if (withdrawn.length && inbox?.messages.every((message) => message.held)) hold(inbox); + return withdrawn.length; + }, + hasPending(recipientId) { + const inbox = inboxes.get(recipientId); + return inbox !== undefined && inbox.phase !== "held"; + }, enqueue(message) { if (closed) throw new Error("Agent message delivery is closed"); let resolve!: Admitted["resolve"]; @@ -325,50 +562,59 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes messageId: message.messageId ?? randomUUID(), dispatched, }; - const item: Admitted = { + admit({ ...message, receipt, resolve, reject, - sequence: sequence++, state: "queued", + urgent: message.activeTurnBehavior === "interrupt", + held: false, outOfBandDeclined: false, - }; - const owned = admitted.get(message.recipientId) ?? new Set(); - owned.add(item); - admitted.set(message.recipientId, owned); - void dispatched - .finally(() => { - owned.delete(item); - if (!owned.size) admitted.delete(message.recipientId); - }) - .catch(() => undefined); - const entry = pending.get(message.recipientId) ?? { - messages: [], - ready: false, - cancel: () => {}, - }; - entry.cancel(); - entry.ready = false; - entry.messages.push(item); - entry.cancel = schedule(2000, () => flush(message.recipientId)); - pending.set(message.recipientId, entry); + }); return receipt; }, + sendDirect( + direct: DirectPrompt, + send: (joined: JoinedPrompt) => Promise, + ): Promise { + // Its place in line is decided now: what is queued goes with it, what comes later follows. + const ahead = + closed || isCommand(direct.prompt) + ? [] + : [...(inboxes.get(direct.recipientId)?.messages ?? [])]; + return new Promise((resolve, reject) => { + run(direct.recipientId, async () => { + const riders = ahead.filter(isQueued); + for (const message of riders) message.state = "claimed"; + let result: Result; + try { + for (const message of riders) message.beforeDispatch?.(); + result = await send(join(riders, direct)); + } catch (error) { + handBack(riders); + reject(error); + return; + } + resolve(result); + await ride(riders, result); + }); + }); + }, async waitForDispatch(recipientId, signal) { signal.throwIfAborted(); - const waiting = Array.from(admitted.get(recipientId) ?? [], (message) => + const waiting = Array.from(inboxes.get(recipientId)?.messages ?? [], (message) => message.receipt.dispatched.catch((error) => { if (message.state !== "withdrawn") throw error; return undefined; }), ); - let unsubscribePermission: (() => void) | undefined; - const permission = new Promise((resolve) => { + let unsubscribeCheckpoint: (() => void) | undefined; + const checkpoint = new Promise((resolve) => { const check = () => { - if (dependencies.hasPendingPermission?.(recipientId)) resolve(); + if (dependencies.hasPendingPermission?.(recipientId) || isHeld(recipientId)) resolve(); }; - unsubscribePermission = dependencies.subscribe?.((agentId) => { + unsubscribeCheckpoint = dependencies.subscribe?.((agentId) => { if (agentId === recipientId) check(); }); check(); @@ -380,26 +626,36 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes }); try { await Promise.race([ - Promise.all([dispatching.get(recipientId), ...waiting]), + Promise.all([releasing.get(recipientId), ...waiting]), cancellation, - permission, + checkpoint, ]); } finally { signal.removeEventListener("abort", aborted); - unsubscribePermission?.(); + unsubscribeCheckpoint?.(); } }, close() { if (closing) return closing; closed = true; unsubscribe?.(); - for (const recipientId of pending.keys()) flush(recipientId); + unsubscribeStop?.(); + const receipts: Promise[] = []; + for (const [recipientId, inbox] of inboxes) { + inbox.cancelTimer(); + inbox.cancelCap(); + // Shutdown delivers held messages too: nothing in memory survives it. + inbox.phase = "waiting"; + receipts.push(...inbox.messages.map((message) => message.receipt.dispatched)); + // The drain reads the queue when its turn comes, so it sees what the operation in + // flight returns to it. + run(recipientId, async () => { + for (const group of modeGroups(inbox.messages.filter(isQueued))) + await deliver(recipientId, group, false, () => false).catch(() => undefined); + }); + } // Each failure is reported and rejects its receipts; shutdown still drains other recipients. - closing = Promise.allSettled( - [...admitted.values()].flatMap((owned) => - [...owned].map((message) => message.receipt.dispatched), - ), - ).then(() => undefined); + closing = Promise.allSettled(receipts).then(() => undefined); return closing; }, }; diff --git a/packages/server/src/server/agent/agent-messages/envelope.ts b/packages/server/src/server/agent/agent-messages/envelope.ts index 45649aa49..f48b866e9 100644 --- a/packages/server/src/server/agent/agent-messages/envelope.ts +++ b/packages/server/src/server/agent/agent-messages/envelope.ts @@ -150,11 +150,23 @@ export function prepareAgentMessage( return { prompt, messageId: id }; } } + return envelopeMessage(prompt, source ?? null, id); +} + +/** + * Wrap a prompt in its envelope unconditionally. A person's prompt (`source` null) needs one + * only when it is quoted or shares a provider prompt with agent messages. + */ +export function envelopeMessage( + prompt: AgentPromptInput, + source: AgentPromptSource | null, + id?: string, +): { prompt: AgentPromptInput; messageId: string } { const messageId = id ?? randomUUID(); const text = typeof prompt === "string" ? prompt : prompt.flatMap(renderMessageText).join("\n\n"); // Render textual attachments before wrapping, so provider replay still contains one // complete envelope instead of an envelope followed by provider-rendered context. - const envelope = formatAgentMessage({ id: messageId, source: source ?? null, text }); + const envelope = formatAgentMessage({ id: messageId, source, text }); return { messageId, prompt: diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index b30b941e1..b301b73d8 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -1,4 +1,8 @@ -import { prepareAgentMessage, type AgentPromptSource } from "./agent-messages/index.js"; +import { + prepareAgentMessage, + type AgentMessageDelivery, + type AgentPromptSource, +} from "./agent-messages/index.js"; import type { Logger } from "pino"; import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js"; @@ -277,6 +281,11 @@ export interface SendPromptToAgentParams { logger: Logger; } +/** A prompt that does not wait its turn. Messages queued for the agent go with it. */ +export interface SendDirectPromptParams extends SendPromptToAgentParams { + agentMessages: Pick; +} + export interface StartCreatedAgentInitialPromptParams { agentStorage: AgentStorage; agentManager: AgentManager; @@ -362,21 +371,36 @@ async function resolvePromptSource( * chat mentions, notify-on-finish) MUST go through this so behavior can never * drift between them. * + * The prompt does not wait in the agent's message queue, and it does not jump it either: + * messages already queued for the agent are delivered ahead of it in the same provider prompt. + * * When `unarchive` is false and the agent is archived, the call is a silent * no-op (returns the normal turn-start disposition) — the agent is not run. */ export async function sendPromptToAgent( - params: SendPromptToAgentParams, + params: SendDirectPromptParams, ): Promise { - const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage); - const delivery = prepareAgentMessage(params.prompt, source, params.messageId); - return sendPreparedPromptToAgent({ - ...params, - prompt: delivery.prompt, - runOptions: delivery.messageId - ? { ...params.runOptions, clientMessageId: delivery.messageId } - : params.runOptions, - }); + const { agentMessages, source, messageId, ...send } = params; + return agentMessages.sendDirect( + { + recipientId: params.agentId, + prompt: params.prompt, + source: await resolvePromptSource(source, params.agentManager, params.agentStorage), + messageId, + sessionMode: params.sessionMode, + unarchive: params.unarchive, + }, + (joined) => + sendPreparedPromptToAgent({ + ...send, + prompt: joined.prompt, + sessionMode: joined.sessionMode, + unarchive: joined.unarchive, + runOptions: joined.messageId + ? { ...send.runOptions, clientMessageId: joined.messageId } + : send.runOptions, + }), + ); } /** Dispatch daemon-prepared context without reclassifying it as human input. */ diff --git a/packages/server/src/server/agent/host-operations/index.ts b/packages/server/src/server/agent/host-operations/index.ts index 4abc9b9d0..920838e70 100644 --- a/packages/server/src/server/agent/host-operations/index.ts +++ b/packages/server/src/server/agent/host-operations/index.ts @@ -298,7 +298,7 @@ export function createHostResolver(input: { status: agent.status, guidance: receipt.deliveryStatus === "queued" - ? "Queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false." + ? "Queued for delivery after two quiet seconds and the current turn ends. An interrupt replaces the turn now, after the messages queued before it. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false." : "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.", }); }, diff --git a/packages/server/src/server/agent/mcp-server.test.ts b/packages/server/src/server/agent/mcp-server.test.ts index 071084b1f..534a15120 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -29,16 +29,17 @@ import { AgentStorage, type StoredAgentRecord } from "./agent-storage.js"; import { createTestAgentClients } from "../test-utils/fake-agent-client.js"; import { OmpAgentClient } from "./providers/omp/agent.js"; import { FakeOmp } from "./providers/omp/test-utils/fake-omp.js"; -import type { - AgentClient, - AgentMode, - AgentPermissionRequest, - AgentPromptInput, - AgentProvider, - AgentRunResult, - AgentSession, - AgentStreamEvent, - ProviderSnapshotEntry, +import { + AgentTurnStartCanceledError, + type AgentClient, + type AgentMode, + type AgentPermissionRequest, + type AgentPromptInput, + type AgentProvider, + type AgentRunResult, + type AgentSession, + type AgentStreamEvent, + type ProviderSnapshotEntry, } from "./agent-sdk-types.js"; import type { ProviderSnapshotManager } from "./provider-snapshot-manager.js"; import { createProviderSnapshotManagerStub } from "../test-utils/session-stubs.js"; @@ -281,6 +282,7 @@ function buildAgentManagerSpies() { steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }), tryRunOutOfBand: vi.fn().mockReturnValue(false), subscribe: vi.fn().mockReturnValue(() => {}), + onStop: () => () => {}, streamAgent: vi.fn( (agentId: string, _prompt: unknown, _options: unknown, start?: ForegroundPromptStart) => { const runs = new AgentRunState(); @@ -637,6 +639,9 @@ class BoundaryAgentManagerFake { subscribe() { return () => {}; } + onStop() { + return () => {}; + } hasPendingPermissions() { return false; } @@ -3497,6 +3502,8 @@ class HeldTurnAgentSession implements AgentSession { private readonly permissions = new Map(); private activeTurnId: string | null = null; private turnStartGate: Promise | null = null; + private cancelHeldStart: (() => void) | null = null; + private interruptGate: Promise | null = null; private nextStartError: Error | null = null; constructor( @@ -3514,6 +3521,15 @@ class HeldTurnAgentSession implements AgentSession { return release; } + /** Hold the next interrupt, as a provider that takes a moment to stop does. */ + holdInterrupt(): () => void { + let release!: () => void; + this.interruptGate = new Promise((resolve) => { + release = resolve; + }); + return release; + } + async run(): Promise { return { sessionId: this.id, finalText: "", timeline: [] }; } @@ -3536,7 +3552,19 @@ class HeldTurnAgentSession implements AgentSession { async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> { this.prompts.push(typeof prompt === "string" ? prompt : JSON.stringify(prompt)); - await this.turnStartGate; + if (this.turnStartGate) { + // An interrupt that arrives before the acknowledgment cancels the start. + const canceled = new Promise<"canceled">((resolve) => { + this.cancelHeldStart = () => resolve("canceled"); + }); + const outcome = await Promise.race([this.turnStartGate, canceled]); + this.cancelHeldStart = null; + if (outcome === "canceled") { + // The hold belonged to the start that was canceled. + this.turnStartGate = null; + throw new AgentTurnStartCanceledError(); + } + } if (this.nextStartError) { const error = this.nextStartError; this.nextStartError = null; @@ -3648,6 +3676,10 @@ class HeldTurnAgentSession implements AgentSession { } async interrupt(): Promise { + const gate = this.interruptGate; + this.interruptGate = null; + await gate; + this.cancelHeldStart?.(); const turnId = this.activeTurnId; if (!turnId) { return; @@ -4499,6 +4531,369 @@ describe("send_agent_prompt MCP tool", () => { }); }); +describe("message order for one recipient", () => { + const logger = createTestLogger(); + const existingCwd = process.cwd(); + + /** A sending agent, a person, and a recipient whose turns end only when the test says so. */ + async function setupRecipient() { + const workdir = await mkdtemp(join(tmpdir(), "mcp-message-order-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new HeldTurnAgentClient("codex", true); + const agentManager = new AgentManager({ + clients: { codex: client }, + registry: storage, + logger, + }); + const sender = await agentManager.createAgent( + { provider: "codex", cwd: existingCwd }, + undefined, + { workspaceId: "wks_parent" }, + ); + const recipient = await agentManager.createAgent( + { provider: "codex", cwd: existingCwd }, + undefined, + { workspaceId: "wks_parent" }, + ); + const session = client.sessions[1]!; + + const timers: Array<{ at: number; callback: () => void }> = []; + let now = 0; + const base = { + agentManager, + agentStorage: storage, + providerSnapshotManager: createOpenCodeManager().manager, + logger, + }; + const agentServer = await createAgentMcpServer( + { ...base, callerAgentId: sender.id }, + undefined, + (delayMs, callback) => { + const timer = { at: now + delayMs, callback }; + timers.push(timer); + return () => { + const index = timers.indexOf(timer); + if (index >= 0) timers.splice(index, 1); + }; + }, + ); + const delivery = serverDeliveries.get(agentServer)!; + let personPromptsAdmitted = 0; + // A person reaches the same daemon queue through a server with no caller agent. + const personServer = await createAgentMcpServer({ + ...base, + agentMessages: () => ({ + ...delivery, + sendDirect(direct, send) { + const sending = delivery.sendDirect(direct, send); + personPromptsAdmitted++; + return sending; + }, + }), + }); + const agentSend = registeredTool(agentServer, "send_agent_prompt"); + const personSend = registeredTool(personServer, "send_agent_prompt"); + + function advance(ms: number): void { + const end = now + ms; + for (;;) { + const due = timers.filter((timer) => timer.at <= end).sort((a, b) => a.at - b.at)[0]; + if (!due) break; + timers.splice(timers.indexOf(due), 1); + now = due.at; + due.callback(); + } + now = end; + } + /** Everything the queue will deliver without a new prompt has been delivered. */ + async function settled(): Promise { + await delivery.waitForDispatch(recipient.id, new AbortController().signal); + expect(delivery.hasPending(recipient.id)).toBe(false); + } + /** Resolves when the message is queued; an interrupt by default when it is dispatched. */ + function agentSends( + prompt: string, + activeTurnBehavior: "steer" | "interrupt" = "steer", + awaitDispatch = activeTurnBehavior === "interrupt", + ) { + return invokeToolWithParsedInput( + agentSend, + { agentId: recipient.id, prompt, notifyOnFinish: false, activeTurnBehavior }, + awaitDispatch, + ); + } + + await agentSends("Original work"); + advance(2000); + await settled(); + expect(session.prompts).toHaveLength(1); + + return { + recipientId: recipient.id, + session, + agentManager, + advance, + settled, + agentSends, + personSends: (prompt: string) => + invokeToolWithParsedInput(personSend, { agentId: recipient.id, prompt }), + /** The person's prompts that have taken their place in the recipient's queue. */ + personPromptsAdmitted: () => personPromptsAdmitted, + /** Stop reached the queue: what it holds waits for the recipient's next prompt. */ + queueIsHeld: () => !delivery.hasPending(recipient.id), + stop: () => + invokeToolWithParsedInput(registeredTool(agentServer, "cancel_agent"), { + agentId: recipient.id, + }), + /** Who wrote each message of a provider prompt, in the order the recipient reads them. */ + prompt: (index: number) => + parseAgentMessages(session.prompts[index]!)?.map((message) => ({ + from: message.source?.kind === "agent-message" ? message.source.agentId : "person", + text: message.text, + })), + senderId: sender.id, + cleanup: () => removeAgentStateDir(agentManager, storage, workdir), + }; + } + + it("an interrupt delivers the steer queued before it first, in the same turn", async () => { + const recipient = await setupRecipient(); + try { + await recipient.agentSends("Go ahead and cut the release"); + recipient.advance(10 * 60_000); + expect(recipient.session.prompts).toHaveLength(1); + + await recipient.agentSends("Pause the release", "interrupt"); + + expect(recipient.prompt(1)).toEqual([ + { from: recipient.senderId, text: "Go ahead and cut the release" }, + { from: recipient.senderId, text: "Pause the release" }, + ]); + // The older steer is spent: the pause turn ending starts nothing. + recipient.session.finishTurn(); + recipient.advance(10 * 60_000); + await recipient.settled(); + expect(recipient.session.prompts).toHaveLength(2); + expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle"); + } finally { + await recipient.cleanup(); + } + }); + + it("a person's prompt takes the queued steer into its own turn", async () => { + const recipient = await setupRecipient(); + try { + await recipient.agentSends("Go ahead and cut the release"); + recipient.advance(2000); + + await recipient.personSends("Pause the release"); + + expect(recipient.prompt(1)).toEqual([ + { from: recipient.senderId, text: "Go ahead and cut the release" }, + { from: "person", text: "Pause the release" }, + ]); + const rows = recipient.agentManager.getTimeline(recipient.recipientId); + expect(rows.flatMap((row) => (row.type === "user_message" ? [row.text] : []))).toEqual([ + "Pause the release", + ]); + recipient.session.finishTurn(); + recipient.advance(10 * 60_000); + await recipient.settled(); + expect(recipient.session.prompts).toHaveLength(2); + } finally { + await recipient.cleanup(); + } + }); + + it("Stop holds the queued steer for the recipient's next prompt", async () => { + const recipient = await setupRecipient(); + try { + await recipient.agentSends("Go ahead and cut the release"); + recipient.advance(2000); + + await recipient.stop(); + + recipient.advance(10 * 60_000); + await recipient.settled(); + expect(recipient.session.prompts).toHaveLength(1); + expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle"); + + await recipient.personSends("Carry on"); + expect(recipient.prompt(1)).toEqual([ + { from: recipient.senderId, text: "Go ahead and cut the release" }, + { from: "person", text: "Carry on" }, + ]); + } finally { + await recipient.cleanup(); + } + }); + + it("cancel_agent with no turn to stop holds nothing: a queued steer keeps its quiet window", async () => { + const recipient = await setupRecipient(); + try { + recipient.session.finishTurn(); + await vi.waitFor(() => + expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle"), + ); + await recipient.agentSends("Go ahead and cut the release"); + + // Nothing is running, so there is no Stop: the tool reports that it canceled no run. + const result = await recipient.stop(); + expect(result.structuredContent).toMatchObject({ success: false }); + + recipient.advance(2000); + await recipient.settled(); + expect(recipient.prompt(1)).toEqual([ + { from: recipient.senderId, text: "Go ahead and cut the release" }, + ]); + } finally { + await recipient.cleanup(); + } + }); + + it("prompts sent while the provider is still starting a turn reach it in the order sent", async () => { + const recipient = await setupRecipient(); + try { + const acknowledgeStart = recipient.session.holdTurnStart(); + const interrupt = recipient.agentSends("Check the logs", "interrupt"); + await vi.waitFor(() => expect(recipient.session.prompts).toHaveLength(2)); + + // The provider has not acknowledged the interrupt's turn when these three arrive. + await recipient.agentSends("Go ahead and cut the release"); + const person = recipient.personSends("Pause the release"); + await vi.waitFor(() => expect(recipient.personPromptsAdmitted()).toBe(1)); + await recipient.agentSends("Tests passed"); + acknowledgeStart(); + await Promise.all([interrupt, person]); + + expect(recipient.prompt(2)).toEqual([ + { from: recipient.senderId, text: "Go ahead and cut the release" }, + { from: "person", text: "Pause the release" }, + ]); + recipient.session.finishTurn(); + recipient.advance(2000); + await recipient.settled(); + expect(recipient.session.prompts).toHaveLength(4); + expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Tests passed" }]); + } finally { + await recipient.cleanup(); + } + }); + + it("Stop during a starting turn holds the interrupt that was waiting to replace it", async () => { + const recipient = await setupRecipient(); + try { + recipient.session.holdTurnStart(); + const person = recipient.personSends("Run the migration").catch(() => undefined); + await vi.waitFor(() => expect(recipient.session.prompts).toHaveLength(2)); + // The interrupt waits for the starting turn before it can replace it. + await recipient.agentSends("Skip the backup", "interrupt", false); + + await recipient.stop(); + await person; + + // The next prompt is sent after the interrupt's dispatch has ended, so a turn the + // interrupt started on its own would show up as a prompt between the two. + await recipient.personSends("Carry on"); + expect(recipient.session.prompts).toHaveLength(3); + expect(recipient.prompt(2)).toEqual([ + { from: recipient.senderId, text: "Skip the backup" }, + { from: "person", text: "Carry on" }, + ]); + } finally { + await recipient.cleanup(); + } + }); + + it("a steer sent while the provider is still stopping does not release the interrupt Stop held", async () => { + const recipient = await setupRecipient(); + try { + recipient.session.holdTurnStart(); + const person = recipient.personSends("Run the migration").catch(() => undefined); + await vi.waitFor(() => expect(recipient.session.prompts).toHaveLength(2)); + await recipient.agentSends("Skip the backup", "interrupt", false); + + const providerStops = recipient.session.holdInterrupt(); + const stopping = recipient.stop(); + await vi.waitFor(() => expect(recipient.queueIsHeld()).toBe(true)); + await recipient.agentSends("Use the staging database"); + providerStops(); + await stopping; + await person; + expect(recipient.session.prompts).toHaveLength(2); + + // The interrupt from before the Stop waits for the later steer's quiet window. + recipient.advance(2000); + await recipient.settled(); + expect(recipient.session.prompts).toHaveLength(3); + expect(recipient.prompt(2)).toEqual([ + { from: recipient.senderId, text: "Skip the backup" }, + { from: recipient.senderId, text: "Use the staging database" }, + ]); + } finally { + await recipient.cleanup(); + } + }); + + it("the first interrupt after Stop takes the held messages along in one turn", async () => { + const recipient = await setupRecipient(); + try { + recipient.session.holdTurnStart(); + const person = recipient.personSends("Run the migration").catch(() => undefined); + await vi.waitFor(() => expect(recipient.session.prompts).toHaveLength(2)); + // The interrupt waits for the starting turn, and the steer's closed window waits behind it. + await recipient.agentSends("Skip the backup", "interrupt", false); + await recipient.agentSends("Use the staging database"); + recipient.advance(2000); + + const providerStops = recipient.session.holdInterrupt(); + const stopping = recipient.stop(); + await vi.waitFor(() => expect(recipient.queueIsHeld()).toBe(true)); + await recipient.agentSends("Stop after the schema step", "interrupt", false); + providerStops(); + await stopping; + await person; + await recipient.settled(); + + expect(recipient.session.prompts).toHaveLength(3); + expect(recipient.prompt(2)).toEqual([ + { from: recipient.senderId, text: "Skip the backup" }, + { from: recipient.senderId, text: "Use the staging database" }, + { from: recipient.senderId, text: "Stop after the schema step" }, + ]); + } finally { + await recipient.cleanup(); + } + }); + + it("a queued steer returns to the queue when the provider rejects the person's turn", async () => { + const recipient = await setupRecipient(); + try { + await recipient.agentSends("Go ahead and cut the release"); + recipient.advance(2000); + + recipient.session.rejectNextTurnStart(new Error("Provider is overloaded")); + await expect(recipient.personSends("Pause the release")).rejects.toThrow( + "Provider is overloaded", + ); + expect(recipient.prompt(1)).toEqual([ + { from: recipient.senderId, text: "Go ahead and cut the release" }, + { from: "person", text: "Pause the release" }, + ]); + + // The provider never took that prompt, so the steer is delivered on its own. + recipient.advance(2000); + await recipient.settled(); + expect(recipient.session.prompts).toHaveLength(3); + expect(recipient.prompt(2)).toEqual([ + { from: recipient.senderId, text: "Go ahead and cut the release" }, + ]); + } finally { + await recipient.cleanup(); + } + }); +}); + describe("send_agent_prompt MCP tool to an OMP child", () => { const logger = createTestLogger(); const existingCwd = process.cwd(); diff --git a/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts b/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts index 0960f9ca6..b3fb42c42 100644 --- a/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts +++ b/packages/server/src/server/agent/providers/opencode/bridge-input-errors.test.ts @@ -17,6 +17,7 @@ import { import { createServiceProxySubsystem } from "../../../service-proxy.js"; import { WorkspaceScriptRuntimeStore } from "../../../workspace-script-runtime-store.js"; import { createTerminalManager } from "../../../../terminal/terminal-manager.js"; +import { createTestAgentMessages } from "../../../test-utils/agent-messages.js"; test("bridge preserves tool failure messages and classifies invalid requests as client errors", async () => { const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-7045-")); @@ -63,10 +64,12 @@ test("bridge preserves tool failure messages and classifies invalid requests as spawnWorkspaceScript: unused, assertAutomationAllowed: unused, }); + const agentMessages = createTestAgentMessages({ agentManager, agentStorage, logger }); const catalog = createPaseoToolCatalog({ workspaceScripts, agentManager, agentStorage, + agentMessages: () => agentMessages, scheduleService, providerSnapshotManager, logger, @@ -196,6 +199,7 @@ test("bridge preserves tool failure messages and classifies invalid requests as ]), }); } finally { + await agentMessages.close(); await bridge.close(); await providerSnapshotManager.shutdown(); await rm(paseoHome, { recursive: true, force: true }); diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 7ed87a845..15ce4e38e 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -1287,7 +1287,7 @@ function createToolCatalog( .strict(); const commonSendAgentPromptInputSchema = { activeTurnBehavior: ActiveTurnBehaviorSchema.optional().describe( - 'Agent callers: "steer" (default) waits until the current turn ends; "interrupt" replaces it. Human callers: "steer" joins the turn, falling back to interrupt; default is interrupt.', + 'Agent callers: "steer" (default) waits until the current turn ends; "interrupt" replaces it at once and delivers the messages queued before it first, in the same turn. Human callers: "steer" joins the turn, falling back to interrupt; default is interrupt.', ), agentId: z.string(), prompt: z.string(), @@ -1974,7 +1974,7 @@ function createToolCatalog( { title: "Send agent prompt", description: - "Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient and waits for the current turn to end unless interrupt is requested. Completion reports include the target’s last response by default. Paseo supplies caller identity.", + "Send a task. Agent callers receive an immediate queued receipt. The recipient reads messages in the order they were queued: a steer follows two quiet seconds and waits for the current turn to end; an interrupt replaces the turn at once and takes the messages queued before it along. A later message does not cancel an earlier one. Completion reports include the target’s last response by default. Paseo supplies caller identity.", inputSchema: sendAgentPromptInputSchema, outputSchema: { success: z.boolean(), @@ -2050,14 +2050,17 @@ function createToolCatalog( deliveryStatus: receipt.status, messageId: receipt.messageId, status: agentManager.getAgent(agentId)?.lifecycle ?? "idle", - guidance: notifying - ? `Queued for delivery after two quiet seconds and the current turn ends. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}` - : "Queued for delivery after two quiet seconds and the current turn ends; provider dispatch has not occurred.", + guidance: `${ + activeTurnBehavior === "interrupt" + ? "Queued to replace the current turn now, after the messages queued before it." + : "Queued for delivery after two quiet seconds and the current turn ends." + } ${notifying ? PROMPTED_AGENT_NOTIFICATION_GUIDANCE : "Provider dispatch has not occurred."}`, }, }; } const dispatch = await sendPromptToAgent({ + agentMessages: agentMessages(), agentManager, agentStorage, agentId, diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 491ffe41f..5f4870b5f 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -1073,8 +1073,18 @@ export async function createPaseoDaemon( }), eligible: async (record) => !record.workspaceId || !(await workspaceRegistry?.get(record.workspaceId))?.archivedAt, - dispatch: (agentId, prompt) => - sendPromptToAgent({ agentId, prompt, agentManager, agentStorage, logger, unarchive: false }), + dispatch: (agentId, prompt) => { + if (!wsServer) throw new Error("Daemon is not accepting agent messages"); + return sendPromptToAgent({ + agentMessages: wsServer.agentMessages, + agentId, + prompt, + agentManager, + agentStorage, + logger, + unarchive: false, + }); + }, report: (agentId, err) => logger.error({ agentId, err }, "Agent restart recovery failed"), }); await restartRecovery.prepareStartup(); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index dd1039e7e..6ffe2de36 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -4610,6 +4610,7 @@ export class Session { try { await sendPromptToAgent({ + agentMessages: this.agentMessages, agentManager: this.agentManager, agentStorage: this.agentStorage, agentId, @@ -9177,6 +9178,7 @@ export class Session { return; } const result = await sendPromptToAgent({ + agentMessages: this.agentMessages, agentManager: this.agentManager, agentStorage: this.agentStorage, agentId, diff --git a/packages/server/src/server/test-utils/agent-messages.ts b/packages/server/src/server/test-utils/agent-messages.ts index 55cc698aa..896f43280 100644 --- a/packages/server/src/server/test-utils/agent-messages.ts +++ b/packages/server/src/server/test-utils/agent-messages.ts @@ -31,6 +31,7 @@ export function createTestAgentMessages(params: { }, { replayState: false }, ), + onStop: (notify) => params.agentManager.onStop(notify), schedule: params.schedule ?? ((_delay, callback) => { @@ -46,6 +47,7 @@ export function createTestAgentMessages(params: { unarchive: request.unarchive, activeTurnBehavior: request.activeTurnBehavior, idleOnly: request.idleOnly, + admit: request.admit, clearPendingPermissions: request.clearPendingPermissions, runOptions: { clientMessageId: request.messageIds[0] }, }); @@ -57,6 +59,8 @@ export function createTestAgentMessages(params: { ); return result.disposition; }, + awaitStart: (agentId, started) => + waitForAgentRunStartWithTimeout(params.agentManager, agentId, started), onError: (error, request) => params.logger.error( { err: error, agentId: request.recipientId, messageIds: request.messageIds }, diff --git a/packages/server/src/server/websocket-server.browser-tools.test.ts b/packages/server/src/server/websocket-server.browser-tools.test.ts index 313d82ff7..d2e328082 100644 --- a/packages/server/src/server/websocket-server.browser-tools.test.ts +++ b/packages/server/src/server/websocket-server.browser-tools.test.ts @@ -283,6 +283,7 @@ function createVoiceAssistantWebSocketServer(params: { const agentManager = { setAgentAttentionCallback() {}, subscribe: () => () => {}, + onStop: () => () => {}, getMetricsSnapshot: () => ({ total: 0, byLifecycle: {}, diff --git a/packages/server/src/server/websocket-server.notifications.test.ts b/packages/server/src/server/websocket-server.notifications.test.ts index 2d0a36f65..6cd3a8a12 100644 --- a/packages/server/src/server/websocket-server.notifications.test.ts +++ b/packages/server/src/server/websocket-server.notifications.test.ts @@ -87,6 +87,7 @@ function createServer(agentManagerOverrides?: Record) { const pushNotifications = new RecordingPushNotificationSender(); const agentManager = { subscribe: vi.fn(() => () => {}), + onStop: () => () => {}, setAgentAttentionCallback: vi.fn(), getAgent: vi.fn(() => ({ workspaceId: WORKSPACE_ID, pendingPermissions: new Map() })), getLastAssistantMessage: vi.fn(async () => null), diff --git a/packages/server/src/server/websocket-server.relay-reconnect.test.ts b/packages/server/src/server/websocket-server.relay-reconnect.test.ts index 7dcb02669..a0922283e 100644 --- a/packages/server/src/server/websocket-server.relay-reconnect.test.ts +++ b/packages/server/src/server/websocket-server.relay-reconnect.test.ts @@ -269,6 +269,7 @@ function createServer(options?: { "srv_test", createStub({ subscribe: vi.fn(() => () => {}), + onStop: () => () => {}, setAgentAttentionCallback: vi.fn(), getAgent: vi.fn(() => null), getMetricsSnapshot: vi.fn(() => ({ diff --git a/packages/server/src/server/websocket-server.terminal-notifications.test.ts b/packages/server/src/server/websocket-server.terminal-notifications.test.ts index e22e5bf9a..0e4b7e2d6 100644 --- a/packages/server/src/server/websocket-server.terminal-notifications.test.ts +++ b/packages/server/src/server/websocket-server.terminal-notifications.test.ts @@ -120,6 +120,7 @@ function createServer(terminalManager: TerminalManager, workspaceRegistry?: Work const agentManager = { setAgentAttentionCallback: vi.fn(), subscribe: vi.fn(() => () => {}), + onStop: () => () => {}, getAgent: vi.fn(() => null), getLastAssistantMessage: vi.fn(async () => null), getMetricsSnapshot: vi.fn(() => ({ diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 2d23e2b4b..4a76dfa7c 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -755,6 +755,7 @@ export class VoiceAssistantWebSocketServer { }, { replayState: false }, ), + onStop: (notify) => agentManager.onStop(notify), dispatch: async (batch) => { const dispatch = await sendPreparedPromptToAgent({ agentManager, @@ -774,6 +775,8 @@ export class VoiceAssistantWebSocketServer { await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId, dispatch.started); return dispatch.disposition; }, + awaitStart: (agentId, started) => + waitForAgentRunStartWithTimeout(agentManager, agentId, started), onError: (err, batch) => this.logger.error( { err, agentId: batch.recipientId, messageIds: batch.messageIds }, diff --git a/skills/paseo/SKILL.md b/skills/paseo/SKILL.md index f3dce11ef..7e4fc4779 100644 --- a/skills/paseo/SKILL.md +++ b/skills/paseo/SKILL.md @@ -84,7 +84,7 @@ Detach is an explicit user action in the subagents track, not an agent tool. A c Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false` when you want explicit reporting or no completion callback. -**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. For agent-scoped calls, `steer` waits until the recipient's current turn ends, and only `interrupt` stops a running turn. For top-level calls, `steer` joins the running turn and falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver together after two quiet seconds, or after the recipient's turn ends if it is running. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback. +**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. For agent-scoped calls, `steer` waits until the recipient's current turn ends, and only `interrupt` stops a running turn. The recipient reads messages in the order they were queued: an `interrupt` replaces the turn at once and delivers the messages queued before it first, in the same turn, so a later message never cancels an earlier one. To withdraw an earlier instruction, say so in the new message. For top-level calls, `steer` joins the running turn and falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver together after two quiet seconds, or after the recipient's turn ends if it is running. A person's prompt to the recipient takes the queued messages into its turn. `cancel_agent` and the stop button hold them until the recipient's next prompt. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback. **`update_agent`** — `{ agentId, name?, labels?, settings? }`. Use `settings` for runtime changes on an existing agent: `modeId`, `model`, `thinkingOptionId`, and provider-specific `features`. For Codex fast mode, pass `settings: { features: { "fast_mode": true } }`.