From 08ad7c7271a602234f1e4be46101af456dbda191 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 22 Nov 2026 14:01:15 +0700 Subject: [PATCH] Let agents steer or interrupt another agent's running turn, and tell them how their message was delivered (#10483) * feat(server): let agents queue, steer, or interrupt messages to other agents An agent sender's `steer` used to mean "wait for the turn to end", unlike a person's steer. Agents now get the same three choices a person has, plus a named default: `queue` waits for the turn end, `steer` joins the running turn (interrupting when the provider cannot steer), and `interrupt` replaces it. A steer or interrupt carries the messages queued ahead of it, so delivery order still equals admission order. The receipt returns the applied behavior and guidance built from whether the recipient is running and whether its provider can steer. A queued message's guidance tells the sender to follow up with a short steer or interrupt instead of resending, because a resent message is read twice. Older clients send `steer` for every default agent send, so the daemon maps their agent `steer` to `queue` when the client lacks the `agent_active_turn_behaviors` capability. New clients talking to an older daemon refuse `steer` rather than silently queueing it. * fix(server): keep a steer's carried messages when the turn ends first A steer that reached the provider after the turn ended made the manager throw a plain error, and delivery failed the whole batch, including the queued messages the steer carried. The manager now throws AgentTurnChangedError, and delivery sends the batch again, into the next turn or as a new one. Also report the applied activeTurnBehavior in `paseo send --no-wait` output, and expect the new hello capability in the client test. * docs(skills): warn that an unread steer loses the messages it carried * docs(skills): shorten the send_agent_prompt guidance Keep what a sender acts on: leave activeTurnBehavior out, the three values, read the guidance, follow up instead of resending, and the steer loss case. Drop delivery facts the sender cannot act on. * fix(server): stop the send_agent_prompt description promising an unread steer survives --- docs/agent-lifecycle.md | 17 +- docs/glossary.md | 2 +- docs/hub.md | 5 +- packages/cli/src/cli-surface.test.ts | 4 +- packages/cli/src/commands/agent/send.test.ts | 29 +++ packages/cli/src/commands/agent/send.ts | 38 ++- packages/client/src/connection/index.ts | 1 + packages/client/src/daemon-client.test.ts | 92 +++++++ packages/client/src/daemon-client.ts | 50 +++- packages/protocol/src/client-capabilities.ts | 4 + .../src/messages.active-turn-behavior.test.ts | 42 ++++ packages/protocol/src/messages.ts | 12 +- .../src/server/agent/agent-manager.test.ts | 31 +++ .../server/src/server/agent/agent-manager.ts | 13 +- .../agent/agent-messages/delivery.test.ts | 235 +++++++++++++++--- .../server/agent/agent-messages/delivery.ts | 62 +++-- .../server/agent/agent-messages/guidance.ts | 40 +++ .../src/server/agent/agent-messages/index.ts | 1 + .../server/src/server/agent/agent-prompt.ts | 3 + .../agent/finish-subscriptions/index.ts | 3 +- .../src/server/agent/host-operations/index.ts | 12 +- .../src/server/agent/mcp-server.test.ts | 185 +++++++++++--- .../src/server/agent/plugin-provider.test.ts | 6 +- .../src/server/agent/plugin-provider.ts | 13 +- .../agent/provider-registry-wrap.test.ts | 2 + .../src/server/agent/provider-registry.ts | 4 +- .../src/server/agent/tools/paseo-tools.ts | 31 ++- .../agent-message-behaviors.test.ts | 123 +++++++++ packages/server/src/server/session.ts | 35 ++- .../src/server/test-utils/agent-messages.ts | 1 + .../server/src/server/websocket-server.ts | 3 + public-docs/cli.md | 7 +- public-docs/cli.zh-CN.md | 7 +- public-docs/mcp.md | 2 +- public-docs/mcp.zh-CN.md | 2 +- public-docs/orchestration-workflows.md | 2 +- public-docs/orchestration-workflows.zh-CN.md | 2 +- skills/paseo/SKILL.md | 17 +- 38 files changed, 979 insertions(+), 159 deletions(-) create mode 100644 packages/cli/src/commands/agent/send.test.ts create mode 100644 packages/server/src/server/agent/agent-messages/guidance.ts create mode 100644 packages/server/src/server/daemon-e2e/agent-message-behaviors.test.ts diff --git a/docs/agent-lifecycle.md b/docs/agent-lifecycle.md index dfa25a9252..1a00ca6413 100644 --- a/docs/agent-lifecycle.md +++ b/docs/agent-lifecycle.md @@ -152,14 +152,21 @@ Users can also detach an existing subagent from the subagents track. Detach is d 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. -- **`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. +An agent sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. `steer` and `interrupt` mean what they mean for a person. A person's send has no `queue`. Each kind of prompt is released this way: + +- **`queue`** (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. Finish notifications and change-request updates always queue. +- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer. +- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message 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. +- **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 steer or interrupt no longer enters the turn; it waits like a queued message. 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 message 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. +The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one 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. +Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`. + +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 a `steer` or `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 a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages 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 diff --git a/docs/glossary.md b/docs/glossary.md index acac5f62e9..16f760ef40 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -57,7 +57,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here - **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar". - **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`). - **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the ` track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the queue track is a lane inside the composer itself. Code: queue track inside `Composer` (`packages/app/src/composer/index.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`). -- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. Forbidden: "Delivery", "Queued prompt". +- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as the queue track does for a person. Forbidden: "Delivery", "Queued prompt". - **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term. - **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar". - **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying). diff --git a/docs/hub.md b/docs/hub.md index 1fbe6b92d5..87a8ab633d 100644 --- a/docs/hub.md +++ b/docs/hub.md @@ -72,8 +72,9 @@ hashes, never prompts, environment values, or credentials. Before messaging an archived workspace, call `workspace.recovery.inspect.request`, then `workspace.recovery.restore.request` and await success. The native message handler unarchives the -agent and loads its persisted provider session. `activeTurnBehavior: "steer"` uses the provider's -native steering behavior, including Paseo's existing behavior when that provider cannot steer. +agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so +`activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn +when that provider cannot steer. The daemon rejects `queue` on a direct send. Execution completion and arrival-specific output authority remain Hub responsibilities. The older `hub.execution.*` RPCs remain accepted for existing clients. Their execution ownership diff --git a/packages/cli/src/cli-surface.test.ts b/packages/cli/src/cli-surface.test.ts index 83db3408e6..cd745bb554 100644 --- a/packages/cli/src/cli-surface.test.ts +++ b/packages/cli/src/cli-surface.test.ts @@ -12,9 +12,11 @@ describe("canonical CLI surface", () => { expect(send.opts().behavior).toBe("interrupt"); await send.parseAsync(["target", "message", "--behavior", "steer"], { from: "user" }); expect(send.opts().behavior).toBe("steer"); + await send.parseAsync(["target", "message", "--behavior", "queue"], { from: "user" }); + expect(send.opts().behavior).toBe("queue"); send.exitOverride().configureOutput({ writeErr: () => {} }); await expect( - send.parseAsync(["target", "message", "--behavior", "queue"], { from: "user" }), + send.parseAsync(["target", "message", "--behavior", "wait"], { from: "user" }), ).rejects.toThrow(); }); diff --git a/packages/cli/src/commands/agent/send.test.ts b/packages/cli/src/commands/agent/send.test.ts new file mode 100644 index 0000000000..58249fff0f --- /dev/null +++ b/packages/cli/src/commands/agent/send.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { buildNoWaitResult } from "./send.js"; + +const agentId = "11111111-1111-4111-8111-111111111111"; + +describe("buildNoWaitResult", () => { + it("reports the behavior the host applied to an agent's message", () => { + expect( + buildNoWaitResult(agentId, { + deliveryStatus: "queued", + activeTurnBehavior: "steer", + guidance: "The agent is idle, so your message starts a turn now.", + }), + ).toEqual({ + agentId, + status: "queued", + activeTurnBehavior: "steer", + message: "The agent is idle, so your message starts a turn now.", + }); + }); + + it("leaves the behavior out when the host does not report one", () => { + expect(buildNoWaitResult(agentId, {})).toEqual({ + agentId, + status: "sent", + message: "Message sent, not waiting for completion", + }); + }); +}); diff --git a/packages/cli/src/commands/agent/send.ts b/packages/cli/src/commands/agent/send.ts index 64ab32481c..aca3512864 100644 --- a/packages/cli/src/commands/agent/send.ts +++ b/packages/cli/src/commands/agent/send.ts @@ -1,7 +1,8 @@ import { type Command, Option } from "commander"; -import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages"; +import type { AgentActiveTurnBehavior } from "@getpaseo/protocol/messages"; import { collectMultiple } from "../../utils/command-options.js"; import { connectToDaemon } from "../../utils/client.js"; +import type { AgentMessageReceipt } from "@getpaseo/client/internal/daemon-client"; import type { CommandOptions, SingleResult, @@ -15,6 +16,8 @@ import { extname, resolve } from "node:path"; export interface AgentSendResult { agentId: string; status: "queued" | "sent" | "completed" | "timeout" | "permission" | "error"; + /** What the host applied to an agent's message with a running turn. */ + activeTurnBehavior?: AgentActiveTurnBehavior; message: string; } @@ -29,7 +32,7 @@ export const agentSendSchema: OutputSchema = { }; export interface AgentSendOptions extends CommandOptions { - behavior?: ActiveTurnBehavior; + behavior?: AgentActiveTurnBehavior; wait?: boolean; image?: string[]; prompt?: string; @@ -47,8 +50,8 @@ export function addSendOptions(cmd: Command): Command { .addOption( new Option( "--behavior ", - "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"]), + "Leave out unless the message cannot wait. From an agent (PASEO_AGENT_ID set): queue (default) waits for the running turn to end, steer joins it, interrupt replaces it. From a person: interrupt (default) or steer", + ).choices(["queue", "steer", "interrupt"]), ) .option("--no-wait", "Return immediately without waiting for completion"); } @@ -170,6 +173,22 @@ function buildSendResult(agentIdArg: string, state: SendWaitState): AgentSendRes return { agentId, status: "completed", message: "Agent completed processing the message" }; } +export function buildNoWaitResult(agentId: string, receipt: AgentMessageReceipt): AgentSendResult { + return { + agentId, + status: receipt.deliveryStatus ?? "sent", + ...(receipt.activeTurnBehavior ? { activeTurnBehavior: receipt.activeTurnBehavior } : {}), + message: sendReceiptMessage(receipt), + }; +} + +function sendReceiptMessage(receipt: AgentMessageReceipt): string { + if (receipt.deliveryStatus !== "queued") return "Message sent, not waiting for completion"; + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once daemon + // floor >= v0.17.2. Older hosts return no guidance. + return receipt.guidance ?? "Message queued for delivery after the current turn ends"; +} + export async function runSendCommand( agentIdArg: string, prompt: string | undefined, @@ -204,7 +223,7 @@ export async function runSendCommand( const receipt = await client.sendAgentMessage(agentIdArg, promptInput, { images, sourceAgentId, - activeTurnBehavior: options.behavior ?? (sourceAgentId ? "steer" : "interrupt"), + activeTurnBehavior: options.behavior, }); // If --no-wait, return immediately @@ -213,14 +232,7 @@ export async function runSendCommand( return { type: "single", - data: { - agentId: agentIdArg, - status: receipt.deliveryStatus ?? "sent", - message: - receipt.deliveryStatus === "queued" - ? "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", - }, + data: buildNoWaitResult(agentIdArg, receipt), schema: agentSendSchema, }; } diff --git a/packages/client/src/connection/index.ts b/packages/client/src/connection/index.ts index bf2388e663..3c68c7ecdb 100644 --- a/packages/client/src/connection/index.ts +++ b/packages/client/src/connection/index.ts @@ -125,6 +125,7 @@ export class ConnectionSubscriptions extends OwnedSubscriptions { // Protocol support belongs to the installed client. Only browser hosting needs // a resource supplied by the caller. Keep this exhaustive as the protocol evolves. export const DEFAULT_CLIENT_CAPABILITIES = { + [CLIENT_CAPS.agentActiveTurnBehaviors]: true, [CLIENT_CAPS.terminalChunkedReplay]: true, [CLIENT_CAPS.binaryChunkingV1]: true, [CLIENT_CAPS.helloRejection]: true, diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 9826a287c3..d242205974 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -1127,6 +1127,7 @@ test("advertises client capabilities in hello", async () => { clientType: "cli", protocolVersion: 1, capabilities: { + agent_active_turn_behaviors: true, all_providers: true, selective_agent_timeline: true, timeline_replacement_invalidation: true, @@ -8828,6 +8829,97 @@ test.each([false, true])( }, ); +describe("agent sender active-turn behaviors", () => { + async function connect(features: Record) { + const transport = createMockTransport(); + const client = new DaemonClient({ + url: "ws://test", + clientId: "agent-behaviors", + transportFactory: () => transport.transport, + reconnect: { enabled: false }, + }); + clients.push(client); + const connecting = client.connect(); + transport.triggerOpen({ features: { agentMessageProvenance: true, ...features } }); + await connecting; + return { client, transport }; + } + + function respond( + transport: ReturnType, + payload: Record = {}, + ) { + const request = parseSentFrame(transport.sent.at(-1)); + transport.triggerMessage( + wrapSessionMessage({ + type: "send_agent_message_response", + payload: { + requestId: request.requestId, + agentId: "recipient", + accepted: true, + error: null, + ...payload, + }, + }), + ); + return request; + } + + test("a capable host gets the behavior as asked and returns the applied behavior with guidance", async () => { + const { client, transport } = await connect({ agentActiveTurnBehaviors: true }); + const send = client.sendAgentMessage("recipient", "review", { + sourceAgentId: "sender", + activeTurnBehavior: "steer", + }); + const request = respond(transport, { + deliveryStatus: "queued", + activeTurnBehavior: "steer", + guidance: "Steering the running turn.", + }); + expect(request.activeTurnBehavior).toBe("steer"); + await expect(send).resolves.toEqual({ + deliveryStatus: "queued", + activeTurnBehavior: "steer", + guidance: "Steering the running turn.", + }); + }); + + test("an older host gets its own agent default for queue and refuses a steer", async () => { + const { client, transport } = await connect({}); + const queued = client.sendAgentMessage("recipient", "review", { + sourceAgentId: "sender", + activeTurnBehavior: "queue", + }); + const request = respond(transport, { deliveryStatus: "queued" }); + expect("activeTurnBehavior" in request).toBe(false); + await expect(queued).resolves.toEqual({ deliveryStatus: "queued" }); + + const interrupt = client.sendAgentMessage("recipient", "stop", { + sourceAgentId: "sender", + activeTurnBehavior: "interrupt", + }); + expect(respond(transport, { deliveryStatus: "queued" }).activeTurnBehavior).toBe("interrupt"); + await interrupt; + + const sentBefore = transport.sent.length; + await expect( + client.sendAgentMessage("recipient", "now", { + sourceAgentId: "sender", + activeTurnBehavior: "steer", + }), + ).rejects.toThrow("Update the Paseo host to steer a running turn from an agent"); + expect(transport.sent).toHaveLength(sentBefore); + }); + + test("queue needs an agent sender", async () => { + const { client, transport } = await connect({ agentActiveTurnBehaviors: true }); + await expect( + client.sendAgentMessage("recipient", "review", { activeTurnBehavior: "queue" }), + ).rejects.toThrow('activeTurnBehavior "queue" needs an agent sender'); + expect(transport.sent).toHaveLength(0); + }); +}); + test("measures an outbound message in UTF-8 bytes against the daemon's message limit", async () => { const mock = createMockTransport(); const client = new DaemonClient({ diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index aa68f82c4c..91c888aee7 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -47,7 +47,7 @@ import { ShutdownRequestedStatusPayloadSchema, DaemonUpdateResponseSchema, SessionInboundMessageSchema, - type ActiveTurnBehavior, + type AgentActiveTurnBehavior, type ServerInfoStatusPayload, } from "@getpaseo/protocol/messages"; import { validateWSOutboundMessage } from "@getpaseo/protocol/validation/ws-outbound"; @@ -481,13 +481,23 @@ export interface DaemonClientTrace { endSection(): void; } +/** A queued agent message carries the applied behavior and what happens next. */ +export interface AgentMessageReceipt { + deliveryStatus?: "queued"; + activeTurnBehavior?: AgentActiveTurnBehavior; + guidance?: string; +} + export interface SendMessageOptions { sourceAgentId?: string; sourceAgentServerId?: string; sessionMode?: string; messageId?: string; - /** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */ - activeTurnBehavior?: ActiveTurnBehavior; + /** + * Agent sources default to queue: wait for the running turn to end. Human sources default to + * interrupt and cannot queue. + */ + activeTurnBehavior?: AgentActiveTurnBehavior; images?: Array<{ data: string; mimeType: string }>; attachments?: SendAgentMessageRequest["attachments"]; } @@ -4262,7 +4272,7 @@ export class DaemonClient { agentId: string, text: string, options: SendMessageOptions = {}, - ): Promise<{ deliveryStatus?: "queued" }> { + ): Promise { if ( options.sourceAgentId && this.lastServerInfoMessage?.features?.agentMessageProvenance !== true @@ -4275,6 +4285,7 @@ export class DaemonClient { ) { throw new Error("Update the Paseo host to send messages with a qualified agent address."); } + const activeTurnBehavior = this.activeTurnBehaviorForHost(options); const requestId = this.createRequestId(); const messageId = options.messageId ?? crypto.randomUUID(); const message = SessionInboundMessageSchema.parse({ @@ -4286,7 +4297,7 @@ export class DaemonClient { sourceAgentServerId: options.sourceAgentServerId, sessionMode: options.sessionMode, ...(messageId ? { messageId } : {}), - activeTurnBehavior: options.activeTurnBehavior, + activeTurnBehavior, images: options.images, attachments: options.attachments, }); @@ -4307,14 +4318,39 @@ export class DaemonClient { if (!payload.accepted) { throw new Error(payload.error ?? "sendAgentMessage rejected"); } - return payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}; + return { + ...(payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}), + ...(payload.activeTurnBehavior ? { activeTurnBehavior: payload.activeTurnBehavior } : {}), + ...(payload.guidance ? { guidance: payload.guidance } : {}), + }; + } + + /** The behavior to put on the wire for this host. */ + private activeTurnBehaviorForHost( + options: SendMessageOptions, + ): AgentActiveTurnBehavior | undefined { + const requested = options.activeTurnBehavior; + if (!options.sourceAgentId) { + if (requested === "queue") + throw new Error('activeTurnBehavior "queue" needs an agent sender (sourceAgentId).'); + return requested; + } + if (this.lastServerInfoMessage?.features?.agentActiveTurnBehaviors === true) return requested; + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once daemon + // floor >= v0.17.2. Older hosts reject queue and read an agent's steer as queue, so queue + // goes out as the host's own agent default and a real steer needs an update. + if (requested === "steer") + throw new Error( + "Update the Paseo host to steer a running turn from an agent. Leave the behavior out to queue the message, or use interrupt.", + ); + return requested === "interrupt" ? "interrupt" : undefined; } async sendMessage( agentId: string, text: string, options?: SendMessageOptions, - ): Promise<{ deliveryStatus?: "queued" }> { + ): Promise { return this.sendAgentMessage(agentId, text, options); } diff --git a/packages/protocol/src/client-capabilities.ts b/packages/protocol/src/client-capabilities.ts index bb03d72b89..dd9c711387 100644 --- a/packages/protocol/src/client-capabilities.ts +++ b/packages/protocol/src/client-capabilities.ts @@ -56,6 +56,10 @@ export const CLIENT_CAPS = { // update subscriptions, because older apps auto-open a tab for every replicated root agent. backgroundAgents: "background_agents", browserHost: "browser_host", + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once client floor >= v0.17.2. + // An agent sender's steer means wait-for-turn-end from clients without it, because older + // CLIs and connected hosts send an explicit steer for every default agent send. + agentActiveTurnBehaviors: "agent_active_turn_behaviors", } as const; export type ClientCapability = (typeof CLIENT_CAPS)[keyof typeof CLIENT_CAPS]; diff --git a/packages/protocol/src/messages.active-turn-behavior.test.ts b/packages/protocol/src/messages.active-turn-behavior.test.ts index 729e3ade4f..597daae97a 100644 --- a/packages/protocol/src/messages.active-turn-behavior.test.ts +++ b/packages/protocol/src/messages.active-turn-behavior.test.ts @@ -2,6 +2,8 @@ import { AgentStreamEventPayloadSchema, AgentTimelineEntryPayloadSchema, SendAgentMessageRequestSchema, + SendAgentMessageResponseMessageSchema, + SendAgentMessageSchema, } from "./messages"; import { describe, expect, it } from "vitest"; import { z } from "zod"; @@ -29,6 +31,46 @@ describe("send_agent_message_request active-turn behavior", () => { }); }); +describe("agent sender active-turn behaviors", () => { + it("accepts queue on a send request and reports the applied behavior in the response", () => { + expect( + SendAgentMessageRequestSchema.parse({ + type: "send_agent_message_request", + requestId: "request-3", + agentId: "agent-1", + text: "Report when you are done", + sourceAgentId: "parent", + activeTurnBehavior: "queue", + }).activeTurnBehavior, + ).toBe("queue"); + expect( + SendAgentMessageResponseMessageSchema.parse({ + type: "send_agent_message_response", + payload: { + requestId: "request-3", + agentId: "agent-1", + accepted: true, + deliveryStatus: "queued", + activeTurnBehavior: "queue", + guidance: "Queued.", + error: null, + }, + }).payload, + ).toMatchObject({ activeTurnBehavior: "queue", guidance: "Queued." }); + }); + + it("keeps a person's send_agent_message to interrupt and steer", () => { + expect( + SendAgentMessageSchema.safeParse({ + type: "send_agent_message", + agentId: "agent-1", + text: "hello", + activeTurnBehavior: "queue", + }).success, + ).toBe(false); + }); +}); + describe("canonical timeline turn ID compatibility", () => { it("accepts both new turn-tagged wire rows and legacy rows without IDs", () => { const entry = { diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 747fa01a9e..e8b9142c41 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -1347,6 +1347,9 @@ const ImageAttachmentSchema = z.object({ export const ActiveTurnBehaviorSchema = z.enum(["interrupt", "steer"]); export type ActiveTurnBehavior = z.infer; +/** An agent sender may also queue: wait until the recipient's running turn ends. */ +export const AgentActiveTurnBehaviorSchema = z.enum(["interrupt", "steer", "queue"]); +export type AgentActiveTurnBehavior = z.infer; export const SendAgentMessageSchema = z.object({ type: z.literal("send_agent_message"), @@ -1524,7 +1527,8 @@ export const SendAgentMessageRequestSchema = z.object({ sourceAgentServerId: z.string().min(1).optional(), sessionMode: z.string().optional(), messageId: z.string().optional(), // Client-provided ID for deduplication - activeTurnBehavior: ActiveTurnBehaviorSchema.optional(), + /** queue needs an agent sender. */ + activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(), images: z.array(ImageAttachmentSchema).optional(), attachments: AgentAttachmentsSchema, }); @@ -4178,6 +4182,8 @@ export const ServerInfoStatusPayloadSchema = z canonicalSubmittedPrompts: z.boolean().optional(), agentMessageProvenance: z.boolean().optional(), agentMessageBatching: z.boolean().optional(), + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove gate after 2027-05-22. + agentActiveTurnBehaviors: z.boolean().optional(), // COMPAT(agentTurnIdentity): accept peers that observed pre-release v0.2.6 through 2027-01-31. agentTurnIdentity: z.boolean().optional(), // COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15. @@ -5523,6 +5529,10 @@ export const SendAgentMessageResponseMessageSchema = z.object({ agentId: z.string(), accepted: z.boolean(), deliveryStatus: z.literal("queued").optional(), + /** The behavior applied to a queued agent message. */ + activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(), + /** What happens to a queued agent message, and how the sender can change it. */ + guidance: z.string().optional(), error: z.string().nullable(), }), }); diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 304520d497..a25ccbd99f 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -1224,6 +1224,37 @@ test("starts its own turn when the previous turn fails to start under a steer se } }); +test("answers whether an agent's session can steer a running turn", async () => { + const steering = new SteeringTestSession({ provider: "codex", cwd: process.cwd() }); + const plain = new TestAgentSession({ provider: "claude", cwd: process.cwd() }); + const workdir = mkdtempSync(join(tmpdir(), "agent-manager-can-steer-")); + const clientFor = (session: AgentSession) => + new (class extends TestAgentClient { + override async createSession(): Promise { + return session; + } + })(); + const manager = new AgentManager({ + clients: { codex: clientFor(steering), claude: clientFor(plain) }, + logger, + }); + try { + const steerable = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const unsteerable = await manager.createAgent({ provider: "claude", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + expect(manager.canSteer(steerable.id)).toBe(true); + expect(manager.canSteer(unsteerable.id)).toBe(false); + expect(manager.canSteer("00000000-0000-4000-8000-000000000000")).toBe(false); + await manager.closeAgent(steerable.id); + await manager.closeAgent(unsteerable.id); + } finally { + rmSync(workdir, { recursive: true, force: true }); + } +}); + test("orders an accepted steer before output emitted while acknowledgement is pending", async () => { const entered = deferred(); const release = deferred(); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 0522e41026..4e407407d2 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -3,6 +3,7 @@ import { ProviderOptionsValidationError } from "./provider-options.js"; import type { AgentToolResult } from "@getpaseo/plugin/server"; import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js"; import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js"; +import { AgentTurnChangedError } from "./agent-prompt.js"; import { continuesAssistantMessage, projectTimelineRows } from "./timeline-projection.js"; import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js"; @@ -1144,6 +1145,14 @@ export class AgentManager { return (this.agents.get(agentId)?.pendingPermissions.size ?? 0) > 0; } + /** + * The agent's session can take a prompt into a running turn. A session declares it by offering + * steerActiveTurn. A provider can still refuse one steer; the prompt then replaces the turn. + */ + canSteer(agentId: string): boolean { + return Boolean(this.agents.get(agentId)?.session?.steerActiveTurn); + } + hasInFlightRun(agentId: string): boolean { const agent = this.agents.get(agentId); if (!agent) { @@ -3594,7 +3603,7 @@ export class AgentManager { // An unavailable answer is only safe to fall back from while this admission // still owns the active turn. Never let an A admission replace a later B. if (result.status === "unavailable" && agent.activeTurnId !== expectedTurnId) { - throw new Error("Active turn changed before steering could be delivered"); + throw new AgentTurnChangedError("Active turn changed before steering could be delivered"); } return result; } @@ -3658,7 +3667,7 @@ export class AgentManager { private assertSteerAdmissionOwnsTurn(agent: ActiveManagedAgent, expectedTurnId: string): void { if (agent.activeTurnId !== expectedTurnId) { - throw new Error("Active turn changed before steering could be delivered"); + throw new AgentTurnChangedError("Active turn changed before steering could be delivered"); } } 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 c441e21182..5225c1928f 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.test.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.test.ts @@ -1,4 +1,4 @@ -import { AgentTurnBusyError } from "../agent-prompt.js"; +import { AgentTurnBusyError, AgentTurnChangedError } from "../agent-prompt.js"; import { expect, test } from "vitest"; import { createAgentMessageDelivery, parseAgentMessages } from "./index.js"; import type { AgentPromptInput } from "../agent-sdk-types.js"; @@ -24,7 +24,7 @@ function createClock() { }; } -test("a queued child report and completion reach the recipient in one steer after two quiet seconds", async () => { +test("a queued child report and completion reach the recipient in one prompt after two quiet seconds", async () => { const clock = createClock(); const sent: Array<{ recipientId: string; prompt: AgentPromptInput }> = []; const delivery = createAgentMessageDelivery({ @@ -345,7 +345,7 @@ test("messages wait across quiet windows and batch after the recipient turn ends messageId: "finish", source: { kind: "agent-notification", agentId: "child", event: "finished" }, prompt: "finished", - activeTurnBehavior: "steer", + activeTurnBehavior: "queue", }); clock.advance(2000); await Promise.resolve(); @@ -996,7 +996,11 @@ interface Dispatched { /** One recipient with a running turn, observed the way the daemon wires the queue. */ function createRecipient( - options: { running?: boolean; outOfBand?: (prompt: AgentPromptInput) => boolean } = {}, + options: { + running?: boolean; + canSteer?: boolean; + outOfBand?: (prompt: AgentPromptInput) => boolean; + } = {}, ) { const clock = createClock(); const sent: Dispatched[] = []; @@ -1012,6 +1016,7 @@ function createRecipient( const delivery = createAgentMessageDelivery({ schedule: clock.schedule, isRunning: () => running, + canSteer: () => options.canSteer ?? true, subscribe: (listener) => { settleListeners.add(listener); return () => settleListeners.delete(listener); @@ -1057,7 +1062,11 @@ function createRecipient( delivery, settle, ids: () => sent.flatMap((dispatch) => dispatch.ids), - send(activeTurnBehavior: "steer" | "interrupt", messageId = `m${next++}`, agentId = "sender") { + send( + activeTurnBehavior: "queue" | "steer" | "interrupt", + messageId = `m${next++}`, + agentId = "sender", + ) { return delivery.enqueue({ recipientId: "recipient", source: { kind: "agent-message", agentId }, @@ -1157,10 +1166,10 @@ function createRecipient( } test.each(["sender", "another-sender"])( - "a steer that waited ten minutes is delivered ahead of a later interrupt from %s, never after it", + "a queued message 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"); + recipient.send("queue", "go-ahead", "sender"); for (let elapsed = 0; elapsed < 600_000; elapsed += 2000) await recipient.tick(); expect(recipient.sent).toEqual([]); @@ -1178,11 +1187,11 @@ test.each(["sender", "another-sender"])( }, ); -test("a steer admitted after an interrupt waits for the replacement turn to end", async () => { +test("a queued message admitted after an interrupt waits for the replacement turn to end", async () => { const recipient = createRecipient(); - recipient.send("steer", "A"); + recipient.send("queue", "A"); recipient.send("interrupt", "B"); - recipient.send("steer", "C"); + recipient.send("queue", "C"); await recipient.tick(); expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["A", "B"]]); @@ -1192,6 +1201,158 @@ test("a steer admitted after an interrupt waits for the replacement turn to end" await recipient.delivery.close(); }); +test("a steer enters the running turn at admission and carries the messages queued before it", async () => { + const recipient = createRecipient(); + recipient.send("queue", "report"); + recipient.send("steer", "course-correction"); + await recipient.settle(); + expect(recipient.sent).toEqual([ + { + ids: ["report", "course-correction"], + behavior: "steer", + idleOnly: false, + mode: undefined, + }, + ]); + + await recipient.endTurn(); + await recipient.tick(); + expect(recipient.sent).toHaveLength(1); + await recipient.delivery.close(); +}); + +test("a steer that misses the turn's end goes again with the messages it carries", async () => { + const clock = createClock(); + let running = true; + const sent: Array<{ ids: readonly string[]; behavior: string }> = []; + const delivery = createAgentMessageDelivery({ + schedule: clock.schedule, + isRunning: () => running, + dispatch: async (request) => { + if (running) { + // The turn ended before the provider took the steer. + running = false; + throw new AgentTurnChangedError("Active turn changed before steering could be delivered"); + } + sent.push({ ids: request.messageIds, behavior: request.activeTurnBehavior }); + return "turn_started"; + }, + onError: (error) => { + throw error; + }, + }); + const message = { + recipientId: "recipient", + source: { kind: "agent-message" as const, agentId: "sender" }, + prompt: "message", + }; + const report = delivery.enqueue({ ...message, messageId: "report", activeTurnBehavior: "queue" }); + const steer = delivery.enqueue({ ...message, messageId: "steer", activeTurnBehavior: "steer" }); + await expect(Promise.all([report.dispatched, steer.dispatched])).resolves.toEqual([ + "turn_started", + "turn_started", + ]); + expect(sent).toEqual([{ ids: ["report", "steer"], behavior: "steer" }]); + await delivery.close(); +}); + +test("a queued message sent after a steer waits for the turn to end", async () => { + const recipient = createRecipient(); + recipient.send("steer", "now"); + recipient.send("queue", "later"); + await recipient.tick(); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["now"]]); + + await recipient.endTurn(); + expect(recipient.sent.map((dispatch) => dispatch.ids)).toEqual([["now"], ["later"]]); + expect(recipient.sent[1]).toMatchObject({ idleOnly: true }); + await recipient.delivery.close(); +}); + +test("a message without a behavior is queued", async () => { + const recipient = createRecipient(); + const receipt = recipient.delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId: "sender" }, + prompt: "report", + }); + expect(receipt.activeTurnBehavior).toBe("queue"); + await recipient.tick(); + expect(recipient.sent).toEqual([]); + await recipient.delivery.close(); +}); + +test.each([ + { + behavior: "queue", + running: false, + canSteer: true, + guidance: "Queued. The agent is idle, so your message starts a turn in about 2 seconds.", + }, + { + behavior: "queue", + running: true, + canSteer: true, + guidance: + 'Queued, not delivered yet. The agent is working and reads your message when its current turn ends. If the message cannot wait, send a short follow-up with activeTurnBehavior "steer" (it joins the running turn) or "interrupt" (it stops the turn and starts a new one). The follow-up carries this message ahead of it, so do not send this message again.', + }, + { + behavior: "queue", + running: true, + canSteer: false, + guidance: + 'Queued, not delivered yet. The agent is working and reads your message when its current turn ends. If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also stops the turn. The follow-up carries this message ahead of it, so do not send this message again.', + }, + { + behavior: "steer", + running: true, + canSteer: true, + guidance: + "Steering the running turn. The agent reads your message at its next step and keeps working.", + }, + { + behavior: "steer", + running: true, + canSteer: false, + guidance: + "This agent's provider cannot steer, so your message interrupts the running turn. A new turn starts with your message.", + }, + { + behavior: "interrupt", + running: true, + canSteer: true, + guidance: "Interrupting the running turn. A new turn starts with your message.", + }, + { + behavior: "steer", + running: false, + canSteer: true, + guidance: "The agent is idle, so your message starts a turn now.", + }, + { + behavior: "interrupt", + running: false, + canSteer: false, + guidance: "The agent is idle, so your message starts a turn now.", + }, +] as const)( + "the receipt for $behavior (running: $running, can steer: $canSteer) tells the sender what happens", + async ({ behavior, running, canSteer, guidance }) => { + const recipient = createRecipient({ running, canSteer }); + const receipt = recipient.delivery.enqueue({ + recipientId: "recipient", + source: { kind: "agent-message", agentId: "sender" }, + prompt: "report", + activeTurnBehavior: behavior, + }); + expect({ behavior: receipt.activeTurnBehavior, guidance: receipt.guidance }).toEqual({ + behavior, + guidance, + }); + await recipient.delivery.close(); + }, +); + test("an interrupt is dispatched at admission while other messages keep arriving", async () => { const recipient = createRecipient(); recipient.send("interrupt", "pause"); @@ -1199,7 +1360,7 @@ test("an interrupt is dispatched at admission while other messages keep arriving 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}`); + recipient.send("queue", `report-${i}`); await recipient.tick(1900); } recipient.send("interrupt", "pause-again"); @@ -1214,7 +1375,7 @@ test("an interrupt is dispatched at admission while other messages keep arriving 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}`); + recipient.send("queue", `report-${i}`); await recipient.tick(1900); } // 11.4 seconds of arrivals under two seconds apart: the window closed at ten. @@ -1225,7 +1386,7 @@ test("steady arrivals cannot keep an idle recipient's quiet window open past ten }); 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 actions = ["queue", "steer", "interrupt", "person", "stop", "end-turn", "tick"] as const; const length = 5; for (let scenario = 0; scenario < actions.length ** length; scenario++) { const recipient = createRecipient(); @@ -1259,7 +1420,7 @@ test("the provider receives every prompt in admission order for every short inte }); 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 actions = ["queue", "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 @@ -1334,7 +1495,7 @@ test("order and Stop hold for every short interleaving while the provider is slo 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"); + recipient.send("queue", "go-ahead"); await recipient.tick(); const { prompt, result } = await recipient.person("pause it", "person-1"); @@ -1356,7 +1517,7 @@ test("a person's prompt is untouched when nothing is queued, and a command trave const recipient = createRecipient(); expect((await recipient.person("hello", "person-1")).prompt).toBe("hello"); - recipient.send("steer", "report"); + recipient.send("queue", "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"); @@ -1368,7 +1529,7 @@ test("a person's prompt is untouched when nothing is queued, and a command trave test("queued messages survive a person's prompt that fails to send", async () => { const recipient = createRecipient(); - recipient.send("steer", "report"); + recipient.send("queue", "report"); await recipient.tick(); const failure = new Error("provider refused the prompt"); expect((await recipient.person("hello", "person-1", { fail: failure })).result).toBe(failure); @@ -1380,7 +1541,7 @@ test("queued messages survive a person's prompt that fails to send", async () => test("Stop holds the messages queued before it until the recipient's next prompt", async () => { const recipient = createRecipient(); - recipient.send("steer", "go-ahead"); + recipient.send("queue", "go-ahead"); await recipient.tick(); await recipient.stop(); @@ -1393,7 +1554,7 @@ test("Stop holds the messages queued before it until the recipient's next prompt 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"); + recipient.send("queue", "later"); await recipient.tick(); expect(recipient.sent).toEqual([ { ids: ["go-ahead", "later"], behavior: "steer", idleOnly: true, mode: undefined }, @@ -1403,7 +1564,7 @@ test("Stop holds the messages queued before it until the recipient's next prompt test("a person's prompt after Stop carries the held messages", async () => { const recipient = createRecipient(); - recipient.send("steer", "go-ahead"); + recipient.send("queue", "go-ahead"); await recipient.stop(); const { prompt } = await recipient.person("continue", "person-1"); @@ -1417,7 +1578,7 @@ test("a person's prompt after Stop carries the held messages", async () => { test("a turn that ends on its own still releases the queue", async () => { const recipient = createRecipient(); - recipient.send("steer", "report"); + recipient.send("queue", "report"); await recipient.tick(); await recipient.endTurn(); expect(recipient.ids()).toEqual(["report"]); @@ -1431,9 +1592,9 @@ test("a prompt's place in line is decided when it is sent, not when the provider await recipient.settle(); // All three arrive while the provider has not answered the first dispatch yet. - recipient.send("steer", "older"); + recipient.send("queue", "older"); const person = recipient.person("stop and wait", "person-1"); - recipient.send("steer", "newer"); + recipient.send("queue", "newer"); await provider.accept(); expect((await person).ids).toEqual(["older", "person-1"]); @@ -1449,7 +1610,7 @@ test("an interrupt sent after a person's prompt does not take older messages pas recipient.send("interrupt", "first"); await recipient.settle(); - recipient.send("steer", "older"); + recipient.send("queue", "older"); const person = recipient.person("stop and wait", "person-1"); recipient.send("interrupt", "newer"); await provider.accept(); @@ -1468,12 +1629,12 @@ test("a queue step already in line does not pick up an interrupt sent after a pe const provider = recipient.holdProviderAnswer(); recipient.send("interrupt", "first"); await recipient.settle(); - recipient.send("steer", "older"); + recipient.send("queue", "older"); await recipient.tick(); const person = recipient.person("stop and wait", "person-1"); recipient.send("interrupt", "newer"); - recipient.send("steer", "newest"); + recipient.send("queue", "newest"); await provider.accept(); expect((await person).ids).toEqual(["older", "person-1"]); @@ -1520,7 +1681,7 @@ test("a held interrupt waits like any other message once a later message release await recipient.stop(); await provider.refuse(new Error("run was canceled before its turn started")); - recipient.send("steer", "later"); + recipient.send("queue", "later"); await recipient.settle(); expect(recipient.ids()).toEqual(["first"]); await recipient.tick(); @@ -1566,7 +1727,7 @@ test("queued messages return to the queue when the provider rejects the person's 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"); + recipient.send("queue", "go-ahead"); await recipient.tick(); const path = await recipient.person( @@ -1575,7 +1736,7 @@ test("a person's prompt that begins with a path is plain text and carries the qu ); expect(path.ids).toEqual(["go-ahead", "person-1"]); - recipient.send("steer", "report"); + recipient.send("queue", "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); @@ -1586,7 +1747,7 @@ test("a person's prompt that begins with a path is plain text and carries the qu 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"); + recipient.send("queue", "report"); await recipient.tick(); const compact = recipient.delivery.enqueue({ @@ -1603,7 +1764,7 @@ test("an interrupt the provider runs as a command beside the turn takes no queue expect(recipient.ids()).toEqual(["report"]); // An interrupt the provider declines to run beside the turn replaces it, queue first. - recipient.send("steer", "another-report"); + recipient.send("queue", "another-report"); const plain = recipient.delivery.enqueue({ recipientId: "recipient", source: { kind: "agent-message", agentId: "sender" }, @@ -1626,7 +1787,7 @@ test("an interrupt keeps its place ahead of a later person's prompt when a queue const provider = recipient.holdProviderAnswer(); recipient.send("interrupt", "first"); await recipient.settle(); - recipient.send("steer", "older"); + recipient.send("queue", "older"); await recipient.tick(); recipient.send("interrupt", "pause"); @@ -1653,7 +1814,7 @@ test("an interrupt that was waiting when Stop arrived stays held when a later me // The later steer arrives before the manager gets back to the interrupt. await recipient.stop(); - recipient.send("steer", "later"); + recipient.send("queue", "later"); await manager.release(); expect(recipient.sent).toEqual([]); @@ -1678,7 +1839,7 @@ test("messages whose starting turn Stop canceled are kept when a later message r expect(recipient.ids()).toEqual(["report"]); await recipient.stop(); - recipient.send("steer", "later"); + recipient.send("queue", "later"); await provider.refuse(new Error("run was canceled before its turn started")); await recipient.tick(); @@ -1726,7 +1887,7 @@ test("a queue step reserved before Stop releases nothing once the queue reopens" const provider = recipient.holdProviderAnswer(); recipient.send("interrupt", "first"); await recipient.settle(); - recipient.send("steer", "older"); + recipient.send("queue", "older"); await recipient.tick(); // The new interrupt arrives before the provider has finished stopping. @@ -1744,11 +1905,11 @@ test("a queue step reserved before Stop releases nothing once the queue reopens" test("held messages stay held when the message that reopened the queue is withdrawn", async () => { const recipient = createRecipient(); - recipient.send("steer", "older"); + recipient.send("queue", "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"); + recipient.send("queue", "update", "watcher"); expect( recipient.delivery.withdrawPending( "recipient", diff --git a/packages/server/src/server/agent/agent-messages/delivery.ts b/packages/server/src/server/agent/agent-messages/delivery.ts index dcfab2d684..283a802693 100644 --- a/packages/server/src/server/agent/agent-messages/delivery.ts +++ b/packages/server/src/server/agent/agent-messages/delivery.ts @@ -1,11 +1,13 @@ import { AgentTurnBusyError, + AgentTurnChangedError, type PromptDispatchDisposition, type PromptDispatchResult, } from "../agent-prompt.js"; import { randomUUID } from "node:crypto"; import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js"; import { envelopeMessage, prepareAgentMessage, type AgentPromptSource } from "./envelope.js"; +import { describeAgentMessage, type AgentMessageBehavior } from "./guidance.js"; /** A message's quiet window closes this long after the latest arrival. */ const QUIET_MS = 2000; @@ -20,20 +22,24 @@ interface Message { sessionMode?: string; unarchive?: boolean; clearPendingPermissions?: boolean; - activeTurnBehavior?: "steer" | "interrupt"; + /** Absent: queue. */ + activeTurnBehavior?: AgentMessageBehavior; beforeDispatch?: () => void; onDispatch?: (disposition: PromptDispatchDisposition) => void; } interface Receipt { status: "queued"; messageId: string; + activeTurnBehavior: AgentMessageBehavior; + /** What happens to the message, and how the sender can change it. */ + guidance: string; dispatched: Promise; } interface Admitted extends Message { /** 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 steer or interrupt that was not released yet. After a Stop it waits like any other message. */ + urgency: "steer" | "interrupt" | null; /** A Stop found it in the queue. It waits for a prompt admitted after that Stop. */ held: boolean; outOfBandDeclined: boolean; @@ -97,6 +103,8 @@ interface JoinedPrompt { interface Dependencies { /** Includes admitted starts and provider turns, including compaction. */ isRunning?: (recipientId: string) => boolean; + /** The recipient's provider can take a message into a running turn. */ + canSteer?: (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; @@ -112,7 +120,10 @@ interface Dependencies { schedule?: (delayMs: number, callback: () => void) => () => void; } export interface AgentMessageDelivery { - /** Admit a message that waits its turn. An interrupt releases at once, with everything queued. */ + /** + * Admit a message. A queued one waits for the running turn to end; a steer or an interrupt + * releases at once, with everything queued before it. + */ enqueue(message: Message): Receipt; /** * Send a prompt that does not wait its turn. The messages admitted before it go ahead of it @@ -135,7 +146,7 @@ export interface AgentMessageDelivery { 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 isUrgent = (message: Admitted): boolean => isQueued(message) && message.urgency !== null; const isOfferable = (message: Admitted): boolean => isQueued(message) && !message.outOfBandDeclined && message.sessionMode === undefined; @@ -226,7 +237,10 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes }, messageIds: messages.map((message) => message.receipt.messageId), prompt: combine(messages.map(envelope)), - activeTurnBehavior: messages.some((message) => message.urgent) ? "interrupt" : "steer", + // A batch that waited for the turn to end is dispatched idle-only, so it never steers. + activeTurnBehavior: messages.some((message) => message.urgency === "interrupt") + ? "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), @@ -331,6 +345,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes handBack(messages); continue; } + // The turn a steer targeted ended first. The batch goes again, into the next turn or as + // a new one, so the messages it carries are not lost. + if (error instanceof AgentTurnChangedError) { + handBack(messages); + continue; + } if (error instanceof AgentTurnBusyError && request.idleOnly) { handBack(messages); return; @@ -371,7 +391,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes } /** - * Move the queue forward: an interrupt takes it now, a closed window once the turn has ended. + * Move the queue forward: a steer or 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( @@ -380,13 +401,13 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes ahead: Admitted[], stopped: () => boolean, ): Promise { - const interrupts = ahead.filter(isUrgent); - if (interrupts.length) { + const urgent = ahead.filter(isUrgent); + if (urgent.length) { // A command the provider runs beside the turn replaces nothing, so it takes nothing along. - await offerOutOfBand(recipientId, interrupts, stopped); + await offerOutOfBand(recipientId, urgent, stopped); const last = ahead.findLastIndex(isUrgent); if (last >= 0) { - // An interrupt does not jump the queue: everything admitted before it goes first. + // A steer or an interrupt does not jump the queue: everything admitted before it goes first. await deliver(recipientId, ahead.slice(0, last + 1), false, stopped); return; } @@ -412,7 +433,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes }); } - /** Polling lines up one step at a time; an interrupt always reserves its own place. */ + /** Polling lines up one step at a time; a steer or an interrupt always reserves its own place. */ function nudge(recipientId: string, inbox: Inbox): void { if (inbox.advancing) return; inbox.advancing = true; @@ -448,8 +469,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes 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 + if (item.urgency) { + // A steer or 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"; @@ -507,7 +528,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes } /** - * The stopped recipient stays stopped. Its queue, interrupts included, goes with whatever + * The stopped recipient stays stopped. Its queue, steers and interrupts included, goes with whatever * prompts it next. */ function hold(inbox: Inbox): void { @@ -516,7 +537,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes inbox.phase = "held"; inbox.stops++; for (const message of inbox.messages) { - message.urgent = false; + message.urgency = null; message.held = true; } } @@ -557,9 +578,16 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes reject = failed; }); void dispatched.catch(() => undefined); + const activeTurnBehavior = message.activeTurnBehavior ?? "queue"; const receipt: Receipt = { status: "queued", messageId: message.messageId ?? randomUUID(), + activeTurnBehavior, + guidance: describeAgentMessage({ + activeTurnBehavior, + running: isRunning(message.recipientId), + canSteer: Boolean(dependencies.canSteer?.(message.recipientId)), + }), dispatched, }; admit({ @@ -568,7 +596,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes resolve, reject, state: "queued", - urgent: message.activeTurnBehavior === "interrupt", + urgency: activeTurnBehavior === "queue" ? null : activeTurnBehavior, held: false, outOfBandDeclined: false, }); diff --git a/packages/server/src/server/agent/agent-messages/guidance.ts b/packages/server/src/server/agent/agent-messages/guidance.ts new file mode 100644 index 0000000000..6726c3129b --- /dev/null +++ b/packages/server/src/server/agent/agent-messages/guidance.ts @@ -0,0 +1,40 @@ +/** + * What an agent sender chooses for a recipient with a running turn. + * queue: wait until the turn ends. steer: enter the running turn. interrupt: replace it. + */ +export type AgentMessageBehavior = "queue" | "steer" | "interrupt"; + +interface Admission { + activeTurnBehavior: AgentMessageBehavior; + /** The recipient has a turn running or starting. */ + running: boolean; + /** The recipient's provider can take a message into a running turn. */ + canSteer: boolean; +} + +const DO_NOT_REPEAT = + "The follow-up carries this message ahead of it, so do not send this message again."; + +/** + * Tells the sender, at admission, what happens to its message and how to change it. Built from + * facts known now, not from the outcome: a provider that can steer may still refuse one steer. + */ +export function describeAgentMessage(admission: Admission): string { + const { activeTurnBehavior, running, canSteer } = admission; + if (activeTurnBehavior === "queue") { + if (!running) + return "Queued. The agent is idle, so your message starts a turn in about 2 seconds."; + const waiting = + "Queued, not delivered yet. The agent is working and reads your message when its current turn ends."; + const followUp = canSteer + ? 'If the message cannot wait, send a short follow-up with activeTurnBehavior "steer" (it joins the running turn) or "interrupt" (it stops the turn and starts a new one).' + : 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also stops the turn.'; + return `${waiting} ${followUp} ${DO_NOT_REPEAT}`; + } + if (!running) return "The agent is idle, so your message starts a turn now."; + if (activeTurnBehavior === "interrupt") + return "Interrupting the running turn. A new turn starts with your message."; + return canSteer + ? "Steering the running turn. The agent reads your message at its next step and keeps working." + : "This agent's provider cannot steer, so your message interrupts the running turn. A new turn starts with your message."; +} diff --git a/packages/server/src/server/agent/agent-messages/index.ts b/packages/server/src/server/agent/agent-messages/index.ts index 3615993334..d81da32e4e 100644 --- a/packages/server/src/server/agent/agent-messages/index.ts +++ b/packages/server/src/server/agent/agent-messages/index.ts @@ -9,3 +9,4 @@ export { type AgentPromptSource, } from "./envelope.js"; export { createAgentMessageDelivery, type AgentMessageDelivery } from "./delivery.js"; +export type { AgentMessageBehavior } from "./guidance.js"; diff --git a/packages/server/src/server/agent/agent-prompt.ts b/packages/server/src/server/agent/agent-prompt.ts index b301b73d8d..3a368b146f 100644 --- a/packages/server/src/server/agent/agent-prompt.ts +++ b/packages/server/src/server/agent/agent-prompt.ts @@ -30,6 +30,9 @@ export type AgentRunController = Pick< export class AgentTurnBusyError extends Error {} +/** The turn a steer targeted ended or changed before the provider took the steer. */ +export class AgentTurnChangedError extends Error {} + export interface StartAgentRunOptions { idleOnly?: boolean; admit?: () => boolean; diff --git a/packages/server/src/server/agent/finish-subscriptions/index.ts b/packages/server/src/server/agent/finish-subscriptions/index.ts index 226ed5af51..193c11f321 100644 --- a/packages/server/src/server/agent/finish-subscriptions/index.ts +++ b/packages/server/src/server/agent/finish-subscriptions/index.ts @@ -199,7 +199,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio title, event: finishNotificationEvents[reason], }, - activeTurnBehavior: "steer", + // A finish report never enters a running turn. + activeTurnBehavior: "queue", unarchive: false, }); acknowledgments.push( diff --git a/packages/server/src/server/agent/host-operations/index.ts b/packages/server/src/server/agent/host-operations/index.ts index 920838e701..736f49e440 100644 --- a/packages/server/src/server/agent/host-operations/index.ts +++ b/packages/server/src/server/agent/host-operations/index.ts @@ -1,6 +1,6 @@ import type { AgentStreamEvent } from "../agent-sdk-types.js"; import { parentAddressLabels } from "@getpaseo/protocol/agent-labels"; -import type { ActiveTurnBehavior, AgentSnapshotPayload } from "@getpaseo/protocol/messages"; +import type { AgentActiveTurnBehavior, AgentSnapshotPayload } from "@getpaseo/protocol/messages"; import { randomUUID } from "node:crypto"; import { z } from "zod"; import { @@ -284,9 +284,7 @@ export function createHostResolver(input: { : undefined, sourceAgentId: input.callerAgentId, sourceAgentServerId: input.callerAgentId ? input.serverId : undefined, - activeTurnBehavior: - (args.activeTurnBehavior as ActiveTurnBehavior | undefined) ?? - (input.callerAgentId ? "steer" : "interrupt"), + activeTurnBehavior: args.activeTurnBehavior as AgentActiveTurnBehavior | undefined, }) .catch((error) => { if (isAmbiguousPromptFailure(error)) throw error; @@ -298,7 +296,11 @@ export function createHostResolver(input: { status: agent.status, guidance: receipt.deliveryStatus === "queued" - ? "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." + ? `${ + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after + // 2027-05-22 once connected-host floor >= v0.17.2. Older hosts return no guidance. + receipt.guidance ?? "Queued for delivery after the current turn ends." + } 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 534a151208..105f63b568 100644 --- a/packages/server/src/server/agent/mcp-server.test.ts +++ b/packages/server/src/server/agent/mcp-server.test.ts @@ -278,6 +278,7 @@ function buildAgentManagerSpies() { effectiveOptionsFor: (_provider: string, own?: Record) => own ?? {}, reloadStalePluginSession: async () => {}, hasInFlightRun: vi.fn().mockReturnValue(false), + canSteer: vi.fn().mockReturnValue(false), hasPendingPermissions: () => false, steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }), tryRunOutOfBand: vi.fn().mockReturnValue(false), @@ -3485,6 +3486,8 @@ interface HeldTurnOptions { finishDuringSteer?: boolean; rejectSteer?: boolean; steerResult?: "accepted" | "unavailable"; + /** The session offers no steering at all, as a provider without steering support. */ + noSteering?: boolean; /** Run the whole turn before the turn-start request returns. */ finishTurnsDuringStart?: boolean; } @@ -3510,7 +3513,9 @@ class HeldTurnAgentSession implements AgentSession { readonly provider: AgentProvider, private readonly holdTurns: boolean, private readonly options: HeldTurnOptions = {}, - ) {} + ) { + if (options.noSteering) Object.defineProperty(this, "steerActiveTurn", { value: undefined }); + } /** Hold the next turn's acknowledgment, as a provider awaiting its turn-start request does. */ holdTurnStart(): () => void { @@ -3727,19 +3732,66 @@ class HeldTurnAgentClient implements AgentClient { describe("send_agent_prompt MCP tool", () => { it.each([ - { agentScoped: true, behavior: undefined, available: true }, - { agentScoped: true, behavior: "interrupt", available: true }, - { agentScoped: true, behavior: "steer", available: true }, - { agentScoped: false, behavior: undefined, available: true }, - { agentScoped: false, behavior: "steer", available: true }, - { agentScoped: true, behavior: undefined, available: false }, + { + agentScoped: true, + behavior: undefined, + steering: "accepted", + applied: "queue", + outcome: "queued", + guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries', + }, + { + agentScoped: true, + behavior: undefined, + steering: "none", + applied: "queue", + outcome: "queued", + guidance: 'provider cannot steer, so "steer" also stops the turn', + }, + { + agentScoped: true, + behavior: "steer", + steering: "accepted", + applied: "steer", + outcome: "steered", + guidance: "Steering the running turn.", + }, + { + agentScoped: true, + behavior: "steer", + steering: "none", + applied: "steer", + outcome: "replaced", + guidance: "This agent's provider cannot steer, so your message interrupts the running turn.", + }, + // A provider that can steer may refuse one steer; the turn is replaced all the same. + { + agentScoped: true, + behavior: "steer", + steering: "unavailable", + applied: "steer", + outcome: "replaced", + guidance: "Steering the running turn.", + }, + { + agentScoped: true, + behavior: "interrupt", + steering: "accepted", + applied: "interrupt", + outcome: "replaced", + guidance: "Interrupting the running turn.", + }, + { agentScoped: false, behavior: undefined, steering: "accepted", outcome: "replaced" }, + { agentScoped: false, behavior: "steer", steering: "accepted", outcome: "steered" }, ] as const)( - "dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available", - async ({ agentScoped, behavior, available }) => { + "$behavior from agent-scoped=$agentScoped to a working agent (steering: $steering) is $outcome", + async (scenario) => { + const { agentScoped, behavior, steering, outcome } = scenario; const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-")); const storage = new AgentStorage(join(workdir, "agents"), logger); const client = new HeldTurnAgentClient("codex", true, { - steerResult: available ? "accepted" : "unavailable", + steerResult: steering === "none" ? undefined : steering, + noSteering: steering === "none", }); const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); try { @@ -3766,9 +3818,8 @@ describe("send_agent_prompt MCP tool", () => { prompt: "Original work", notifyOnFinish: false, }); + const session = client.sessions[1]!; const originalTurn = manager.getAgent(child.id)!.activeTurnId; - const queued = agentScoped && behavior !== "interrupt"; - const steered = !agentScoped && behavior === "steer"; const response = await invokeToolWithParsedInput( tool, { @@ -3777,32 +3828,75 @@ describe("send_agent_prompt MCP tool", () => { notifyOnFinish: false, ...(behavior ? { activeTurnBehavior: behavior } : {}), }, - !queued, + outcome !== "queued", ); - expect(response.structuredContent).toMatchObject({ - success: true, - ...(agentScoped - ? { deliveryStatus: "queued" } - : { disposition: steered ? "steered" : "turn_started" }), - }); - if (queued) { - expect(client.sessions[1]!.prompts).toHaveLength(1); - expect(client.sessions[1]!.steeredPrompts).toEqual([]); + if (agentScoped) { + expect(response.structuredContent).toMatchObject({ + success: true, + deliveryStatus: "queued", + activeTurnBehavior: scenario.applied, + }); + expect(response.structuredContent.guidance).toContain(scenario.guidance); + } + if (outcome === "queued") { + expect(session.prompts).toHaveLength(1); expect(manager.getAgent(child.id)!.activeTurnId).toBe(originalTurn); - client.sessions[1]!.finishTurn(); + session.finishTurn(); await serverDeliveries .get(server)! .waitForDispatch(child.id, new AbortController().signal); } - expect(client.sessions[1]!.prompts).toHaveLength(steered ? 1 : 2); - expect(client.sessions[1]!.steeredPrompts).toHaveLength(steered ? 1 : 0); - expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe(steered); + expect(session.prompts).toHaveLength(outcome === "steered" ? 1 : 2); + expect(session.steeredPrompts).toHaveLength(outcome === "steered" ? 1 : 0); + expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe( + outcome === "steered", + ); } finally { await removeAgentStateDir(manager, storage, workdir); } }, ); + it("tells an agent caller that an idle recipient starts a turn with its queued message", async () => { + const workdir = await mkdtemp(join(tmpdir(), "mcp-send-idle-")); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const client = new HeldTurnAgentClient("codex", false, { steerResult: "accepted" }); + const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger }); + try { + const parent = await manager.createAgent({ provider: "codex", cwd: existingCwd }, undefined, { + workspaceId: "wks_parent", + }); + const child = await manager.createAgent({ provider: "codex", cwd: existingCwd }, undefined, { + workspaceId: "wks_parent", + }); + const server = await createAgentMcpServer({ + agentManager: manager, + agentStorage: storage, + callerAgentId: parent.id, + providerSnapshotManager: createOpenCodeManager().manager, + logger, + }); + const response = await invokeToolWithParsedInput( + registeredTool(server, "send_agent_prompt"), + { + agentId: child.id, + prompt: "Start work", + notifyOnFinish: false, + }, + ); + expect(response.structuredContent).toMatchObject({ + deliveryStatus: "queued", + activeTurnBehavior: "queue", + }); + expect(response.structuredContent.guidance).toContain( + "Queued. The agent is idle, so your message starts a turn in about 2 seconds.", + ); + expect(client.sessions[1]!.prompts).toHaveLength(1); + } finally { + await removeAgentStateDir(manager, storage, workdir); + } + }); + it.each([ { rejected: false, priorNotification: false }, { rejected: false, priorNotification: true }, @@ -4231,7 +4325,7 @@ describe("send_agent_prompt MCP tool", () => { { agentId: child.id, prompt: "/side-command", - activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer", + activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "queue", }, scenario !== "out_of_band", ); @@ -4536,10 +4630,10 @@ describe("message order for one recipient", () => { const existingCwd = process.cwd(); /** A sending agent, a person, and a recipient whose turns end only when the test says so. */ - async function setupRecipient() { + async function setupRecipient(options: HeldTurnOptions = {}) { const workdir = await mkdtemp(join(tmpdir(), "mcp-message-order-")); const storage = new AgentStorage(join(workdir, "agents"), logger); - const client = new HeldTurnAgentClient("codex", true); + const client = new HeldTurnAgentClient("codex", true, options); const agentManager = new AgentManager({ clients: { codex: client }, registry: storage, @@ -4610,11 +4704,11 @@ describe("message order for one recipient", () => { 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. */ + /** Resolves when the message is queued; a steer or an interrupt by default when it is dispatched. */ function agentSends( prompt: string, - activeTurnBehavior: "steer" | "interrupt" = "steer", - awaitDispatch = activeTurnBehavior === "interrupt", + activeTurnBehavior: "queue" | "steer" | "interrupt" = "queue", + awaitDispatch = activeTurnBehavior !== "queue", ) { return invokeToolWithParsedInput( agentSend, @@ -4656,7 +4750,7 @@ describe("message order for one recipient", () => { }; } - it("an interrupt delivers the steer queued before it first, in the same turn", async () => { + it("an interrupt delivers the message queued before it first, in the same turn", async () => { const recipient = await setupRecipient(); try { await recipient.agentSends("Go ahead and cut the release"); @@ -4680,7 +4774,28 @@ describe("message order for one recipient", () => { } }); - it("a person's prompt takes the queued steer into its own turn", async () => { + it("a steer carries the message queued before it into the running turn", async () => { + const recipient = await setupRecipient({ steerResult: "accepted" }); + try { + await recipient.agentSends("Report the test results"); + await recipient.agentSends("Use the staging database", "steer"); + + expect(recipient.session.prompts).toHaveLength(1); + expect( + parseAgentMessages(String(recipient.session.steeredPrompts[0]))?.map( + (message) => message.text, + ), + ).toEqual(["Report the test results", "Use the staging database"]); + recipient.session.finishTurn(); + recipient.advance(10 * 60_000); + await recipient.settled(); + expect(recipient.session.prompts).toHaveLength(1); + } finally { + await recipient.cleanup(); + } + }); + + it("a person's prompt takes the queued message into its own turn", async () => { const recipient = await setupRecipient(); try { await recipient.agentSends("Go ahead and cut the release"); @@ -4866,7 +4981,7 @@ describe("message order for one recipient", () => { } }); - it("a queued steer returns to the queue when the provider rejects the person's turn", async () => { + it("a queued message 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"); diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 66691a57a5..4b2b352313 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -2259,7 +2259,7 @@ describe("PluginAgentClientRegistry", () => { } }); - test("returns unavailable when steering a provider without prompt.steer capability", async () => { + test("offers no steering when the provider did not negotiate prompt.steer", async () => { const harness = createProviderHarness({ capabilities: [ "prompt.message", @@ -2276,9 +2276,7 @@ describe("PluginAgentClientRegistry", () => { cwd: "/workspace", }); try { - const result = await session.steerActiveTurn!("hello", { expectedTurnId: "turn-1" }); - expect(result).toEqual({ status: "unavailable" }); - expect(harness.inputs.filter((input) => input.type === "session.prompt")).toHaveLength(0); + expect(session.steerActiveTurn).toBeUndefined(); } finally { await session.close(); registry.replace([]); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index f8e93a0626..c09e4d1494 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -1396,14 +1396,19 @@ class PluginAgentSession implements AgentSession { return { turnId }; } - async steerActiveTurn( + /** Offered only when the provider negotiated prompt.steer, so callers can ask before steering. */ + get steerActiveTurn(): + | ((prompt: AgentPromptInput, options: SteerActiveTurnOptions) => Promise) + | undefined { + if (!this.bridge.negotiatedCapabilities.includes("prompt.steer")) return undefined; + return (prompt, options) => this.steer(prompt, options); + } + + private async steer( prompt: AgentPromptInput, options: SteerActiveTurnOptions, ): Promise { this.assertReplayComplete(); - if (!this.bridge.negotiatedCapabilities.includes("prompt.steer")) { - return { status: "unavailable" }; - } const result = await this.bridge.prompt({ clientMessageId: options.clientMessageId ?? randomUUID(), delivery: "steer", diff --git a/packages/server/src/server/agent/provider-registry-wrap.test.ts b/packages/server/src/server/agent/provider-registry-wrap.test.ts index cfe7b56fe0..b533c82f9a 100644 --- a/packages/server/src/server/agent/provider-registry-wrap.test.ts +++ b/packages/server/src/server/agent/provider-registry-wrap.test.ts @@ -224,6 +224,8 @@ describe("wrapSessionProvider", () => { expect(wrapped.id).toBe("session-2"); expect(wrapped.capabilities).toEqual(session.capabilities); expect(wrapped.initialTimeline).toEqual(session.initialTimeline); + session.steerActiveTurn = undefined; + expect(wrapped.steerActiveTurn).toBeUndefined(); }); test("propagates steering failure without interrupting or replacing the turn", async () => { diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index a80dc2695a..bff07decec 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -460,7 +460,9 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession usageSession: inner.usageSession?.bind(inner), run: (prompt, options) => inner.run(prompt, options), startTurn: (prompt, options) => inner.startTurn(prompt, options), - steerActiveTurn: inner.steerActiveTurn?.bind(inner), + get steerActiveTurn() { + return inner.steerActiveTurn?.bind(inner); + }, subscribe: (callback) => inner.subscribe((event) => callback(mapStreamEvent(provider, event))), async *streamHistory() { for await (const event of inner.streamHistory()) { diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 15ce4e38e1..5da6a7e795 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -18,7 +18,11 @@ import type { Logger } from "pino"; import type { AgentMode, AgentProvider, AgentSessionConfig } from "../agent-sdk-types.js"; import type { AgentManager, ManagedAgent } from "../agent-manager.js"; -import { ActiveTurnBehaviorSchema, AgentProfileSchema } from "@getpaseo/protocol/messages"; +import { + ActiveTurnBehaviorSchema, + AgentActiveTurnBehaviorSchema, + AgentProfileSchema, +} from "@getpaseo/protocol/messages"; import type { DaemonConfigStore } from "../../daemon-config-store.js"; import { featuresFromControls } from "@getpaseo/protocol/option-controls"; import { @@ -1286,15 +1290,15 @@ function createToolCatalog( .object(legacyTopLevelCreateAgentInputSchema) .strict(); const commonSendAgentPromptInputSchema = { - activeTurnBehavior: ActiveTurnBehaviorSchema.optional().describe( - '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(), sessionMode: z.string().optional().describe("Optional mode to set before running the prompt."), }; const agentToAgentSendAgentPromptInputSchema = { ...commonSendAgentPromptInputSchema, + activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional().describe( + 'Leave this out unless the message cannot wait. Default "queue": the message waits until the agent\'s running turn ends. "steer": the message joins the running turn; a provider that cannot steer interrupts the turn instead. "interrupt": the running turn stops and a new turn starts with the message. A steer or interrupt carries the messages you queued before it, in order.', + ), notifyOnFinish: z .boolean() .optional() @@ -1305,6 +1309,9 @@ function createToolCatalog( }; const topLevelSendAgentPromptInputSchema = { ...commonSendAgentPromptInputSchema, + activeTurnBehavior: ActiveTurnBehaviorSchema.optional().describe( + 'Default "interrupt": the running turn stops and a new turn starts with the prompt. "steer": the prompt joins the running turn; a provider that cannot steer interrupts the turn instead.', + ), notifyOnFinish: z .boolean() .optional() @@ -1974,13 +1981,16 @@ function createToolCatalog( { title: "Send agent prompt", description: - "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.", + scope === "agent" + ? "Send a message to another agent. The response returns at once. Its guidance says whether the message waits for the running turn to end, joins it, or interrupts it, and how to deliver a waiting message now. Leave activeTurnBehavior out unless the message cannot wait. The recipient reads your messages in the order you sent them. A steer the recipient has not read is lost if its turn stops or is interrupted, along with the messages it carried. Completion reports include the target’s last response by default. Paseo supplies caller identity." + : "Send a prompt to an agent. A running turn is interrupted unless activeTurnBehavior is steer.", inputSchema: sendAgentPromptInputSchema, outputSchema: { success: z.boolean(), disposition: z.enum(["turn_started", "out_of_band", "steered"]).optional(), deliveryStatus: z.literal("queued").optional(), messageId: z.string().optional(), + activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(), status: AgentStatusEnum, guidance: z.string().optional(), }, @@ -1990,7 +2000,7 @@ function createToolCatalog( prompt, sessionMode, notifyOnFinish = Boolean(callerAgentId), - activeTurnBehavior = callerAgentId ? "steer" : "interrupt", + activeTurnBehavior, }) => { if (callerAgentId && !agentManager.getAgent(agentId) && !(await agentStorage.get(agentId))) { throw new PaseoToolInputError(`Agent ${agentId} not found`); @@ -2049,12 +2059,11 @@ function createToolCatalog( success: true, deliveryStatus: receipt.status, messageId: receipt.messageId, + activeTurnBehavior: receipt.activeTurnBehavior, status: agentManager.getAgent(agentId)?.lifecycle ?? "idle", - 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."}`, + guidance: notifying + ? `${receipt.guidance} ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}` + : receipt.guidance, }, }; } diff --git a/packages/server/src/server/daemon-e2e/agent-message-behaviors.test.ts b/packages/server/src/server/daemon-e2e/agent-message-behaviors.test.ts new file mode 100644 index 0000000000..ce473dbde2 --- /dev/null +++ b/packages/server/src/server/daemon-e2e/agent-message-behaviors.test.ts @@ -0,0 +1,123 @@ +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import path from "node:path"; +import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities"; +import { expect, test } from "vitest"; + +import { createTestLogger } from "../../test-utils/test-logger.js"; +import { OpenCodeV2AgentClient } from "../agent/providers/opencode/v2/agent.js"; +import { V2Harness } from "../agent/providers/opencode/test-utils/v2-harness.js"; +import { createTestAgentClients } from "../test-utils/fake-agent-client.js"; +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; + +/** A recipient whose first turn keeps running until the test ends it. Its provider can steer. */ +async function createWorkingRecipient(options: { olderClient?: boolean } = {}) { + const artifacts = path.resolve(".artifacts"); + await mkdir(artifacts, { recursive: true }); + const root = await mkdtemp(path.join(artifacts, "agent-message-behaviors-")); + const runtime = new V2Harness(); + runtime.autoComplete = false; + runtime.api.model.list = async () => ({ location: runtime.info.location, data: [] }); + runtime.api.provider.list = async () => ({ + location: runtime.info.location, + data: [{ id: "test", name: "Test", activation: "enabled", package: "test" }], + }); + // A steer is admitted to the running execution, rather than starting another one. + runtime.prompt = async (input) => { + runtime.prompts.push(input.text); + if (runtime.prompts.length === 1) runtime.startExecution(); + }; + const daemon = await createTestPaseoDaemon({ + agentClients: { + ...createTestAgentClients(), + opencode: new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime: runtime.runtime }), + }, + paseoHomeRoot: path.join(root, "daemon"), + staticDir: path.join(root, "static"), + cleanup: false, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + // An older CLI or connected host does not advertise the capability. + ...(options.olderClient + ? { capabilities: { [CLIENT_CAPS.agentActiveTurnBehaviors]: false } } + : {}), + }); + const close = async () => { + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true }); + }; + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + const recipient = await client.createAgent({ + provider: "opencode", + cwd: root, + title: "Worker", + }); + const sender = await client.createAgent({ provider: "claude", cwd: root }); + await client.sendMessage(recipient.id, "Long work"); + await client.waitForAgentUpsert(recipient.id, (agent) => agent.status === "running"); + return { client, runtime, recipient, sender, close }; + } catch (error) { + await close(); + throw error; + } +} + +test("an agent's message without a behavior waits for the running turn and says how to deliver it now", async () => { + const { client, runtime, recipient, sender, close } = await createWorkingRecipient(); + try { + const receipt = await client.sendAgentMessage(recipient.id, "Report when done", { + sourceAgentId: sender.id, + }); + expect(receipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" }); + expect(receipt.guidance).toContain("Queued, not delivered yet."); + expect(receipt.guidance).toContain('"steer" (it joins the running turn)'); + expect(runtime.prompts).toHaveLength(1); + + runtime.finishExecution(); + await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2); + expect(runtime.prompts[1]).toContain("Report when done"); + } finally { + await close(); + } +}); + +test("an agent's steer joins the running turn at once", async () => { + const { client, runtime, recipient, sender, close } = await createWorkingRecipient(); + try { + const receipt = await client.sendAgentMessage(recipient.id, "Use the other API", { + sourceAgentId: sender.id, + activeTurnBehavior: "steer", + }); + expect(receipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "steer" }); + expect(receipt.guidance).toBe( + "Steering the running turn. The agent reads your message at its next step and keeps working.", + ); + await expect.poll(() => runtime.prompts.length).toBe(2); + expect(runtime.prompts[1]).toContain("Use the other API"); + } finally { + await close(); + } +}); + +test("an older client's agent steer still waits for the running turn to end", async () => { + const { client, runtime, recipient, sender, close } = await createWorkingRecipient({ + olderClient: true, + }); + try { + // Older CLIs and connected hosts send steer for every default agent send. + const receipt = await client.sendAgentMessage(recipient.id, "Report when done", { + sourceAgentId: sender.id, + activeTurnBehavior: "steer", + }); + expect(receipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" }); + expect(runtime.prompts).toHaveLength(1); + runtime.finishExecution(); + await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2); + } finally { + await close(); + } +}); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 6ffe2de36a..2855c279d6 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -1,6 +1,6 @@ import { DiffSession } from "./diff/index.js"; import { type WorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"; -import type { AgentMessageDelivery } from "./agent/agent-messages/index.js"; +import type { AgentMessageBehavior, AgentMessageDelivery } from "./agent/agent-messages/index.js"; import { AgentDirectory, type BackgroundVisibility } from "./agent/directory.js"; import { ConnectedHostSession } from "./connected-hosts/index.js"; import type { ConnectedHosts } from "./connected-hosts/index.js"; @@ -21,7 +21,11 @@ import type { import { relative } from "node:path"; import { isAbsolute } from "node:path"; import { CreationService, type CreatedAgent } from "./creation/index.js"; -import type { CreationSnapshot, AgentCreateRequest } from "@getpaseo/protocol/messages"; +import type { + AgentActiveTurnBehavior, + CreationSnapshot, + AgentCreateRequest, +} from "@getpaseo/protocol/messages"; import type { MessageReceipts } from "./message-receipts/index.js"; import { isDaemonBackgroundWorkItem, @@ -9118,6 +9122,18 @@ export class Session { } } + /** An agent sender's message waits for the running turn to end unless it asks otherwise. */ + private agentSenderBehavior( + requested: AgentActiveTurnBehavior | undefined, + ): AgentMessageBehavior { + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once client + // floor >= v0.17.2. Older CLIs and connected hosts send steer for every default agent send, + // meaning wait for the turn to end, so only their interrupt stays an interrupt. + if (!this.supports(CLIENT_CAPS.agentActiveTurnBehaviors)) + return requested === "interrupt" ? "interrupt" : "queue"; + return requested ?? "queue"; + } + private async handleSendAgentMessageRequest( msg: Extract, ): Promise { @@ -9152,7 +9168,11 @@ export class Session { const admitted = new Promise((acceptAdmission) => { queued = acceptAdmission; }); + const requested = msg.activeTurnBehavior; + if (!msg.sourceAgentId && requested === "queue") + throw new Error('activeTurnBehavior "queue" needs an agent sender'); let deliveryStatus: "queued" | undefined; + let queuedReceipt: { activeTurnBehavior: AgentMessageBehavior; guidance: string } | undefined; const send = async (beforeDispatch: () => Promise) => { if (msg.sourceAgentId) { await beforeDispatch(); @@ -9168,11 +9188,12 @@ export class Session { ? (this.agentManager.getAgent(msg.sourceAgentId)?.config.title ?? undefined) : undefined, }, - activeTurnBehavior: msg.activeTurnBehavior ?? "steer", + activeTurnBehavior: this.agentSenderBehavior(requested), sessionMode: msg.sessionMode, clearPendingPermissions: false, }); deliveryStatus = "queued"; + queuedReceipt = receipt; queued(); await receipt.dispatched; return; @@ -9184,7 +9205,7 @@ export class Session { agentId, prompt, messageId: msg.messageId, - activeTurnBehavior: msg.activeTurnBehavior ?? "interrupt", + activeTurnBehavior: requested === "steer" ? "steer" : "interrupt", sessionMode: msg.sessionMode, clearPendingPermissions: true, beforeDispatch, @@ -9231,6 +9252,12 @@ export class Session { agentId, accepted: true, ...(deliveryStatus ? { deliveryStatus } : {}), + ...(queuedReceipt + ? { + activeTurnBehavior: queuedReceipt.activeTurnBehavior, + guidance: queuedReceipt.guidance, + } + : {}), error: null, }, }); diff --git a/packages/server/src/server/test-utils/agent-messages.ts b/packages/server/src/server/test-utils/agent-messages.ts index 896f43280c..9443e11d90 100644 --- a/packages/server/src/server/test-utils/agent-messages.ts +++ b/packages/server/src/server/test-utils/agent-messages.ts @@ -23,6 +23,7 @@ export function createTestAgentMessages(params: { onAccepted, ), isRunning: (agentId) => params.agentManager.hasInFlightRun(agentId), + canSteer: (agentId) => params.agentManager.canSteer(agentId), hasPendingPermission: (agentId) => params.agentManager.hasPendingPermissions(agentId), subscribe: (notify) => params.agentManager.subscribe( diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 4a76dfa7c8..75de0205ef 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -747,6 +747,7 @@ export class VoiceAssistantWebSocketServer { onAccepted, ), isRunning: (agentId) => agentManager.hasInFlightRun(agentId), + canSteer: (agentId) => agentManager.canSteer(agentId), hasPendingPermission: (agentId) => agentManager.hasPendingPermissions(agentId), subscribe: (notify) => agentManager.subscribe( @@ -2257,6 +2258,8 @@ export class VoiceAssistantWebSocketServer { canonicalSubmittedPrompts: true, agentMessageProvenance: true, agentMessageBatching: true, + // COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove gate after 2027-05-22. + agentActiveTurnBehaviors: true, // COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15. stableProjectIdentity: true, // COMPAT(workspaceScriptManagement): added in v0.1.105, remove gate after 2027-01-10. diff --git a/public-docs/cli.md b/public-docs/cli.md index 5eefc7adfe..5bcac82bf9 100644 --- a/public-docs/cli.md +++ b/public-docs/cli.md @@ -322,7 +322,12 @@ paseo send --no-wait "run this task" paseo send --behavior interrupt "stop and do this instead" ``` -Agent-originated sends (`PASEO_AGENT_ID` set) default to steering the running turn. Other sends default to interrupting it. Use `--behavior steer` or `--behavior interrupt` to override the default. Steering uses the same fallback as the client: if steering is unavailable, the running turn is interrupted and replaced. +Leave `--behavior` out unless the message cannot wait. The defaults depend on who sends: + +- From an agent (`PASEO_AGENT_ID` set), the default is `queue`. The message waits until the recipient's running turn ends. `--behavior steer` adds the message to the running turn, and `--behavior interrupt` stops the turn and starts a new one with the message. A steer or interrupt also delivers the messages you queued before it, in order. +- From a person, the default is `interrupt`. `--behavior steer` adds the message to the running turn instead. + +If the recipient's provider cannot steer, `steer` interrupts the running turn instead. With `--no-wait`, the output says what happened to an agent's message and how to deliver a queued message now. ## Viewing logs diff --git a/public-docs/cli.zh-CN.md b/public-docs/cli.zh-CN.md index 572bfa5f01..d24b8c5f35 100644 --- a/public-docs/cli.zh-CN.md +++ b/public-docs/cli.zh-CN.md @@ -301,7 +301,12 @@ paseo send --no-wait "run this task" paseo send --behavior interrupt "stop and do this instead" ``` -由 Agent 发起的发送(设置了 `PASEO_AGENT_ID`)默认引导正在进行的轮次。其他发送默认中断它。使用 `--behavior steer` 或 `--behavior interrupt` 覆盖默认行为。引导使用与客户端相同的后备方式:如果无法引导,正在进行的轮次会被中断并替换。 +除非消息不能等待,否则不要设置 `--behavior`。默认行为取决于发送方: + +- 由 Agent 发送(设置了 `PASEO_AGENT_ID`)时,默认是 `queue`。消息会等到接收方正在进行的轮次结束。`--behavior steer` 把消息加入正在进行的轮次,`--behavior interrupt` 停止该轮次,并用这条消息开始新的一轮。steer 或 interrupt 也会按顺序送达你在它之前排队的消息。 +- 由人发送时,默认是 `interrupt`。`--behavior steer` 则把消息加入正在进行的轮次。 + +如果接收方的 Provider 无法引导,`steer` 会改为中断正在进行的轮次。使用 `--no-wait` 时,输出会说明 Agent 发送的消息发生了什么,以及如何立即送达排队中的消息。 ## 查看日志 {#viewing-logs} diff --git a/public-docs/mcp.md b/public-docs/mcp.md index 68b484e852..12797bcd91 100644 --- a/public-docs/mcp.md +++ b/public-docs/mcp.md @@ -90,7 +90,7 @@ MCP does not expose an agent-detach tool. Detaching is a manual user action in t | Tool | Function | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `create_agent` | Create an agent, optionally placing it in an existing workspace with `workspaceId`. Use `initialPrompt` to start work; returns without waiting for completion. `background: true` hides it from tabs, default lists, your subagent track and notifications; you still get its finish notification. Omission inherits your own value. | -| `send_agent_prompt` | Send a prompt using `agentId` and `prompt`; returns without waiting for completion. | +| `send_agent_prompt` | Send a prompt using `agentId` and `prompt`; returns without waiting for completion. From an agent, the prompt waits for a running turn to end unless `activeTurnBehavior` is `steer` or `interrupt`. | | `get_agent_status` | Return the latest snapshot for an agent. | | `list_agents` | List recent agents as compact metadata; `includeBackground: true` includes background work. | | `cancel_agent` | Abort an agent's current run but keep the agent alive. | diff --git a/public-docs/mcp.zh-CN.md b/public-docs/mcp.zh-CN.md index 36f0ff54d9..83521a302c 100644 --- a/public-docs/mcp.zh-CN.md +++ b/public-docs/mcp.zh-CN.md @@ -82,7 +82,7 @@ MCP 不提供解除 Agent 父子关系的工具。解除关系是用户在应用 | 工具 | 功能 | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `create_agent` | 创建 Agent,可用 `workspaceId` 把它放到已有的工作区。用 `initialPrompt` 开始工作;不等待完成就返回。`background: true` 会把它从标签页、默认列表、你的子 Agent 列表和通知中隐藏;你仍会收到它的完成通知。省略时继承你自己的设置。 | -| `send_agent_prompt` | 用 `agentId` 和 `prompt` 发送提示词;不等待完成就返回。 | +| `send_agent_prompt` | 用 `agentId` 和 `prompt` 发送提示词;不等待完成就返回。由 Agent 发送时,除非 `activeTurnBehavior` 是 `steer` 或 `interrupt`,提示词会等到正在进行的轮次结束。 | | `get_agent_status` | 返回 Agent 的最新快照。 | | `list_agents` | 以精简元数据列出最近的 Agent;`includeBackground: true` 会包含后台工作。 | | `cancel_agent` | 中止 Agent 当前的运行,但保留该 Agent。 | diff --git a/public-docs/orchestration-workflows.md b/public-docs/orchestration-workflows.md index 61343e5cff..9cd8cbc4bd 100644 --- a/public-docs/orchestration-workflows.md +++ b/public-docs/orchestration-workflows.md @@ -51,7 +51,7 @@ Agents can prompt each other by **agent ID**, the identifier Paseo uses to addre > Use Paseo to send this prompt to agent [paste agent ID here]: “Review the parser changes in your workspace and report any missing test cases.” -The receiving agent gets the prompt in its existing conversation. Agent-originated sends default to steering a running turn, with interruption fallback when steering is unavailable. Set MCP `activeTurnBehavior` or CLI `--behavior` to `steer` or `interrupt` to override that default. To have it send a separate message back, give it the sender's agent ID too. +The receiving agent gets the prompt in its existing conversation. If the receiving agent is working, the prompt waits until its current turn ends. For a message that cannot wait, the sending agent sets MCP `activeTurnBehavior` or CLI `--behavior` to `steer`, which adds it to the running turn, or `interrupt`, which stops the turn and starts a new one. The response tells the sending agent which happened. To have it send a separate message back, give it the sender's agent ID too. Underneath, the agent calls `send_agent_prompt` with the recipient's `agentId` and a `prompt`. Agents can also discover IDs with `list_agents`; the CLI uses [`paseo send `](/docs/cli#sending-messages). For another host, use the [remote CLI workflow](#work-on-another-machine). diff --git a/public-docs/orchestration-workflows.zh-CN.md b/public-docs/orchestration-workflows.zh-CN.md index ee078081fb..ed231a994f 100644 --- a/public-docs/orchestration-workflows.zh-CN.md +++ b/public-docs/orchestration-workflows.zh-CN.md @@ -49,7 +49,7 @@ Agent 可以通过 **Agent ID** 相互发送提示词,Agent ID 是 Paseo 用 > 用 Paseo 把这段提示词发送给 Agent [在此粘贴 Agent ID]:“审查你工作区中解析器的改动,并报告缺失的测试用例。” -接收方 Agent 会在它现有的对话中收到这段提示词。由 Agent 发起的发送默认会引导正在进行的一轮;无法引导时则退回为中断。把 MCP 的 `activeTurnBehavior` 或 CLI 的 `--behavior` 设置为 `steer` 或 `interrupt` 可以覆盖这个默认行为。如果希望它另外回发一条消息,请把发送方的 Agent ID 也告诉它。 +接收方 Agent 会在它现有的对话中收到这段提示词。如果接收方 Agent 正在工作,这段提示词会等到它当前的轮次结束。对于不能等待的消息,发送方 Agent 把 MCP 的 `activeTurnBehavior` 或 CLI 的 `--behavior` 设置为 `steer` 或 `interrupt`:`steer` 把消息加入正在进行的轮次,`interrupt` 停止该轮次并开始新的一轮。响应会告诉发送方 Agent 实际发生了什么。如果希望它另外回发一条消息,请把发送方的 Agent ID 也告诉它。 在底层,Agent 会用接收方的 `agentId` 和一段 `prompt` 调用 `send_agent_prompt`。Agent 也可以用 `list_agents` 发现 ID;CLI 使用 [`paseo send `](/docs/cli#sending-messages)。对于另一台主机,请使用[远程 CLI 工作流](#work-on-another-machine)。 diff --git a/skills/paseo/SKILL.md b/skills/paseo/SKILL.md index 7e4fc47796..cb6fe4360f 100644 --- a/skills/paseo/SKILL.md +++ b/skills/paseo/SKILL.md @@ -84,14 +84,26 @@ 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. 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 } }`. **`list_agents`** — filter by `cwd`, `statuses`, `sinceHours`, `includeArchived`; set `includeBackground: true` to include agents in background workspaces. **`archive_agent`** — `{ agentId }`. Interrupts if running, removes from active list. +## Sending prompts to agents + +**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Sends a follow-up to an existing agent and returns at once. + +Leave `activeTurnBehavior` out unless the message cannot wait. It decides what happens when the agent is mid-turn: + +- `queue` (default): the message waits for the turn to end. +- `steer`: the agent reads the message at its next step and keeps working. If its provider cannot steer, the turn is interrupted instead. +- `interrupt`: the turn stops, and a new turn starts with the message. + +Read `guidance` in the response. If it says your message is waiting and the message cannot wait, such as a course correction, send a short follow-up with `steer` or `interrupt`. Do not resend the message: the follow-up carries it, and a resent message is read twice. + +A steer the agent has not read is lost if its turn stops or is interrupted, along with the messages it carried. For a message that must arrive, use `queue` or `interrupt`. + ## Agent profiles and provider discovery **`list_profiles`** — named launch bundles configured by the human. Before choosing how to launch a delegated agent, call this tool and read every profile's `notes`. Pick a named profile the user requested, or the profile whose notes best match the work. @@ -142,6 +154,7 @@ paseo workspace create --isolation worktree --mode checkout-pr --pr-number 42 paseo run --provider codex/gpt-5.4 --mode full-access --workspace "" paseo run --provider codex/gpt-5.4 --mode full-access --new-workspace worktree --worktree-mode branch-off --new-branch fix-x --base origin/main "" paseo send "" +paseo send --behavior steer "" paseo ls paseo schedule create --cron "*/15 * * * *" "ping main build" paseo heartbeat create --cron "*/15 * * * *" "check the build"