Compare commits

...
26 changed files with 1380 additions and 517 deletions
+15 -15
View File
@@ -154,15 +154,15 @@ 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. The daemon saves a queued message, then acknowledges it with a receipt, 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.
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders and finish notifications default to `steer` (falling back to `queue` on providers without `steerActiveTurn`); non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt` (or `steer` in composer settings). Each kind of prompt is released this way:
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages. 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 direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) is dispatched directly 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 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.
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages.
- **`steer`** from an agent sender enters the running turn without cutting it, carrying earlier agent-queued messages ahead of it while leaving human-queued items untouched in the queue. Finish notifications batch across the two-second quiet window before steering so parallel completions arrive together. If the provider cannot steer (`canSteer` is false, e.g., ACP agents) or rejects steering mid-turn without ending the turn, the daemon keeps the message queued until the turn ends rather than interrupting it.
- **`interrupt`** is dispatched at admission the same way, replacing the running turn and carrying earlier non-human-queued messages ahead of it.
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) runs immediately by itself and does **not** sweep queued messages. Queued messages stay intact in the queue track and dispatch once the turn settles, unless the queue is behind a staged provider switch (where the switch queues behind items meant for the current provider). When a non-command, non-resume direct human prompt succeeds on a held queue (after Stop or a refused start), it reopens the held queue so remaining queued items resume after the turn ends.
- **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. Held items wait until reopened by a direct non-command prompt, a newly admitted message, or explicit Send now (`promote`). 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.
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.
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 an agent follow-up carries earlier agent-queued messages ahead of it. On non-steering providers, queued `steer` reports as `queue` and notes that `steer` waits until the turn ends. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
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 new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
@@ -173,8 +173,8 @@ One provider prompt has one session mode. A batch released by a steer, an interr
A provider switch can wait in the queue too (`agent.provider.switch.request` with
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
what follows go to the target. A direct provider switch queues right behind any items queued for
the current provider so those items dispatch first. Promoting the switch cuts the running turn once the target is known to be usable. A chat
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
the message and holds the queue; the reason is in the daemon log.
@@ -184,10 +184,10 @@ queue holds references. An empty message is refused, and a recipient holds at mo
messages.
A message is marked `dispatching` before the provider can receive it and removed when the provider
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
also holds the queue: retrying by itself would be refused again and would add the prompt to the
history each time. A message that cannot be sent is removed so that it does not block the ones
behind it.
admits it. A dispatch that fails transiently (busy/non-steering turn, run-start timeout, mode/RPC
error, or rejected start) returns the batch to the queue rather than deleting it; non-busy failures
also hold the queue until the next prompt reopens it. Only pre-dispatch unresolvable payloads (such
as missing local attachments) or rejected out-of-band commands are discarded so they do not block later messages.
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
@@ -456,8 +456,8 @@ Rows take these commands:
already started sending the row, the draft stays as it is.
- **Cancel** withdraws the row.
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
text.
A message you send directly (`steer` or `interrupt`) runs right away without sweeping the queue track;
queued rows stay visible in place and dispatch after the turn ends (unless held by Stop).
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
row names the target.
+1 -1
View File
@@ -58,7 +58,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 `<thing> 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](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.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 lists the messages the host holds until the turn ends. A queued message does not enter 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 it does for a person's queued message. 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 lists the messages the host holds until the turn ends. A queued message does not enter the running turn, and a person's direct steer leaves queued rows in the queue track. Agent senders and finish notifications default to `steer` (falling back to `queue` when the provider cannot steer) and never sweep human-queued items. 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).
+1 -1
View File
@@ -50,7 +50,7 @@ export function addSendOptions(cmd: Command): Command {
.addOption(
new Option(
"--behavior <behavior>",
"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), steer, or queue",
"From an agent (PASEO_AGENT_ID set): steer (default) joins the running turn or waits until it ends if the provider cannot steer, queue waits for the running turn to end, interrupt replaces it. From a person: interrupt (default), steer, or queue",
).choices(["queue", "steer", "interrupt"]),
)
.option("--no-wait", "Return immediately without waiting for completion");
@@ -18408,3 +18408,76 @@ test.each([
}
},
);
test("streamAgent throws AgentTurnBusyError and non-replacing steerOrReplaceActiveTurn returns busy without replacing an active turn", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-non-replacing-steer-"));
class RejectingSteerSession extends SteeringTestSession {
cancelCalls = 0;
override async steerActiveTurn() {
return { status: "unavailable" as const };
}
override async cancelRun() {
this.cancelCalls += 1;
await super.cancelRun();
}
}
const session = new RejectingSteerSession({ provider: "codex", cwd: workdir });
const client = new (class extends TestAgentClient {
override async createSession(): Promise<AgentSession> {
return session;
}
})();
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const providerStarted = new Promise<void>((resolve) => {
const unsubscribe = session.subscribe((event) => {
if (event.type === "turn_started") {
unsubscribe();
resolve();
}
});
});
try {
await startAgentRun(manager, agent.id, "initial turn", logger);
await manager.waitForAgentRunStart(agent.id);
await providerStarted;
expect(() => manager.streamAgent(agent.id, "competing turn")).toThrow(AgentTurnBusyError);
const steerResult = await manager.steerOrReplaceActiveTurn(
agent.id,
"mid-turn steer",
undefined,
undefined,
false,
);
expect(steerResult).toEqual({ status: "busy" });
expect(session.cancelCalls).toBe(0);
expect(session.startPrompts).toEqual(["initial turn"]);
await expect(
sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: agent.id,
prompt: "mid-turn steer",
activeTurnBehavior: "steer",
replaceRunning: false,
logger,
}),
).rejects.toBeInstanceOf(AgentTurnBusyError);
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
await expect(
manager.steerOrReplaceActiveTurn(agent.id, "after settle", undefined, undefined, false),
).resolves.toEqual({ status: "inactive" });
} finally {
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
@@ -583,7 +583,7 @@ export interface AgentManagerOptions {
}
export type ActiveTurnSteerDispatchResult =
| { status: "inactive" | "steered" }
| { status: "inactive" | "steered" | "busy" }
| { status: "replaced"; iterator: AsyncGenerator<AgentStreamEvent> };
export interface AgentPromptSubmissionOptions extends AgentRunOptions {
@@ -4878,7 +4878,7 @@ export class AgentManager {
},
"agent.manager.stream.reject",
);
throw new Error(`Agent ${agentId} already has an active run`);
throw new AgentTurnBusyError(`Agent ${agentId} already has an active run`);
}
const agent = existingAgent;
@@ -5130,6 +5130,7 @@ export class AgentManager {
prompt: AgentPromptInput,
options?: AgentPromptSteerOptions,
promptStart?: ForegroundPromptStart,
allowReplace = true,
): Promise<ActiveTurnSteerDispatchResult> {
// A turn that is still starting has no id to steer yet. Replacing it would drop its
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
@@ -5169,6 +5170,11 @@ export class AgentManager {
return { status: "inactive" };
}
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
if (!allowReplace) {
return { status: "busy" };
}
await this.beforeSteerUnavailableFallback?.({ agentId, expectedTurnId });
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
return {
File diff suppressed because it is too large Load Diff
@@ -1,7 +1,6 @@
import {
AgentTurnBusyError,
AgentTurnChangedError,
AgentTurnStartRejectedError,
type PromptDispatchDisposition,
type PromptDispatchResult,
} from "../agent-prompt.js";
@@ -73,6 +72,8 @@ interface Admitted extends QueuedContent {
urgency: QueuedMessageUrgency | null;
/** A Stop found it in the queue. It waits for a prompt admitted after that Stop. */
held: boolean;
/** True when explicitly released by Send now (`promote`) and allowed to replace a non-steering turn. */
promoted: boolean;
outOfBandDeclined: boolean;
/** Settles once the store holds it. Nothing dispatches it before that. */
saved: Promise<void>;
@@ -120,6 +121,8 @@ interface DispatchRequest {
uploadedImages: readonly UploadedImage[];
activeTurnBehavior: "steer" | "interrupt";
idleOnly: boolean;
/** True when this batch may interrupt/replace an active turn if steering is unavailable. */
replaceRunning: boolean;
/**
* Claim this exact prompt at provider admission. A withdrawn message or a Stop that reached
* the recipient first invalidates it.
@@ -210,11 +213,10 @@ export interface AgentMessageDelivery {
*/
enqueue(message: Message): Promise<AgentMessageReceipt>;
/**
* Send a prompt that does not wait its turn. Compatible messages admitted before it go ahead
* of it in the same provider prompt, so none starts a turn of its own afterwards. When a
* boundary (conflicting session mode, queued non-agent command, or provider switch) prevents
* coalescing, the prompt is queued behind those messages and releases the first group at once.
* A direct command or restart-resume travels alone.
* Send a prompt directly without sweeping queued messages. Queued messages remain in the queue
* and dispatch once the turn settles. A non-command prompt that starts after a Stop reopens any
* Stop-held queue so it drains after this turn. A direct provider switch behind queued messages
* for the current provider queues behind them so they run on the current provider first.
*/
sendDirect<Result extends PromptDispatchResult>(
direct: DirectPrompt,
@@ -261,6 +263,8 @@ 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.urgency !== null;
const isHumanQueued = (message: Admitted): boolean =>
message.source === null && message.urgency === null;
const isOfferable = (message: Admitted): boolean =>
isQueued(message) &&
!message.outOfBandDeclined &&
@@ -376,39 +380,10 @@ function boundaryOfAdmitted(message: Admitted): DispatchBoundary {
};
}
function boundaryOfDirect(input: {
direct: DirectPrompt;
includeProviderSwitch: boolean;
}): DispatchBoundary {
return {
prompt: input.direct.prompt,
source: input.direct.source,
sessionMode: input.direct.sessionMode,
...(input.includeProviderSwitch ? { providerSwitch: input.direct.providerSwitch } : {}),
};
}
function modeGroups(messages: readonly Admitted[]): Admitted[][] {
return dispatchGroups({ entries: messages, boundaryOf: boundaryOfAdmitted });
}
function canCoalesceDirect(input: { ahead: readonly Admitted[]; direct: DirectPrompt }): boolean {
// A direct provider switch only carries a Stop-held queue when every held message has no
// explicit sessionMode and the switch itself requests no mode override. Any unheld message
// or explicit mode belongs to the current provider and must not move across providers.
const carriesHeldSwitch =
Boolean(input.direct.providerSwitch) &&
!input.direct.providerSwitch?.modeId &&
input.direct.sessionMode === undefined &&
input.ahead.length > 0 &&
input.ahead.every((message) => message.held && message.sessionMode === undefined);
const entries: DispatchBoundary[] = [
...input.ahead.map(boundaryOfAdmitted),
boundaryOfDirect({ direct: input.direct, includeProviderSwitch: !carriesHeldSwitch }),
];
return dispatchGroups({ entries, boundaryOf: (entry) => entry }).length <= 1;
}
function toUploadedImageAttachments(
uploadedImages: readonly UploadedImage[] | undefined,
): Array<UploadedFileAttachment & { role: "image" }> {
@@ -488,6 +463,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
const isRunning = (recipientId: string): boolean =>
Boolean(dependencies.isRunning?.(recipientId));
const canSteer = (recipientId: string): boolean =>
dependencies.canSteer ? dependencies.canSteer(recipientId) : true;
const isHeld = (recipientId: string): boolean => inboxes.get(recipientId)?.phase === "held";
function report(error: unknown, recipientId: string, messageIds: readonly string[] = []): void {
@@ -547,8 +524,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
idleOnly: boolean,
stopped: () => boolean,
activeTurnBehavior?: QueuedMessageUrgency,
allowReplace = false,
): DispatchRequest {
const messages = messagesOf(batch);
const resolvedBehavior =
activeTurnBehavior ??
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer");
return {
recipientId,
idleOnly,
@@ -561,9 +542,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
prompt: formatBatch(batch),
uploadedImages: uploadedImagesOf(batch),
// A batch that waited for the turn to end is dispatched idle-only, so it never steers.
activeTurnBehavior:
activeTurnBehavior ??
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer"),
activeTurnBehavior: resolvedBehavior,
replaceRunning: !idleOnly && (resolvedBehavior === "interrupt" || allowReplace),
// Every message in a batch belongs to one compatible mode group.
sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode,
providerSwitch: messages[0]?.providerSwitch,
@@ -713,6 +693,58 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
}
async function clearUrgency(recipientId: string, messages: Admitted[]): Promise<void> {
if (!messages.length) return;
for (const message of messages) {
message.urgency = null;
message.promoted = false;
}
const ids = idsOf(messages);
await write(store.clearUrgency(recipientId, ids), recipientId, ids);
}
/** Return `"retry"` to loop with remaining messages, or `"done"` once handled. */
async function handleDispatchError(input: {
error: unknown;
recipientId: string;
messages: Admitted[];
request: DispatchRequest;
stopped: () => boolean;
}): Promise<"retry" | "done"> {
const { error, recipientId, messages, request, stopped } = input;
// A Stop reached the recipient before the provider admitted the prompt.
if (stopped()) {
await handBack(recipientId, messages);
return "done";
}
// A withdrawal invalidated this exact prompt, or a steer's turn ended first: try again.
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
await handBack(recipientId, messages);
return "retry";
}
if (error instanceof AgentTurnBusyError) {
await handBack(recipientId, messages);
// A non-replacing steer that found a busy/non-steering turn drops its urgency so it
// waits for turn end rather than spinning immediately.
if (!request.idleOnly && !request.replaceRunning && request.activeTurnBehavior === "steer") {
await clearUrgency(recipientId, messages);
}
return "done";
}
// Shutdown cut this dispatch off. The next start tries it again.
if (closed) {
await handBack(recipientId, messages);
return "done";
}
// Transient timeouts, non-fatal RPC failures, and rejected turn starts stay queued
// and hold until the next user prompt instead of dropping batches.
await handBack(recipientId, messages);
const inbox = inboxes.get(recipientId);
if (inbox) hold(recipientId, inbox);
report(error, recipientId, request.messageIds);
return "done";
}
/** Dispatch one batch. A batch that finds the recipient stopped, or busy when idle-only, stays queued. */
async function deliver(
recipientId: string,
@@ -720,6 +752,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
idleOnly: boolean,
stopped: () => boolean,
activeTurnBehavior?: QueuedMessageUrgency,
allowReplace = false,
): Promise<void> {
for (;;) {
const prepared = await prepare(recipientId, batch);
@@ -732,35 +765,29 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await handBack(recipientId, messages);
continue;
}
const request = requestFor(recipientId, dispatching, idleOnly, stopped, activeTurnBehavior);
let disposition: PromptDispatchDisposition;
const request = requestFor(
recipientId,
dispatching,
idleOnly,
stopped,
activeTurnBehavior,
allowReplace,
);
try {
for (const message of messages) message.beforeDispatch?.();
disposition = await dependencies.dispatch(request);
const disposition = await dependencies.dispatch(request);
return complete(recipientId, messages, disposition);
} catch (error) {
// A Stop reached the recipient before the provider admitted the prompt.
if (stopped()) return handBack(recipientId, messages);
// A withdrawal invalidated this exact prompt; the rest goes again without it.
// A steer whose turn ended first goes again, into the next turn or as a new one.
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
await handBack(recipientId, messages);
continue;
}
if (error instanceof AgentTurnBusyError && request.idleOnly)
return handBack(recipientId, messages);
// The provider refused to start a turn. Retrying by itself would refuse again and add
// the prompt to the history each time, so the queue waits for the next prompt.
if (error instanceof AgentTurnStartRejectedError) {
await handBack(recipientId, messages);
const inbox = inboxes.get(recipientId);
if (inbox) hold(recipientId, inbox);
return report(error, recipientId, request.messageIds);
}
// Shutdown cut this dispatch off. The next start tries it again.
if (closed) return handBack(recipientId, messages);
return discard(recipientId, messages, error);
const outcome = await handleDispatchError({
error,
recipientId,
messages,
request,
stopped,
});
if (outcome === "retry") continue;
return;
}
return complete(recipientId, messages, disposition);
}
}
@@ -818,26 +845,45 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
): Promise<boolean> {
const last = ahead.findLastIndex(isUrgent);
if (last < 0) return false;
const released = ahead.slice(0, last + 1).filter(isQueued);
const [first] = released;
const prefix = ahead.slice(0, last + 1).filter(isQueued);
const [first] = prefix;
if (!first) return false;
// Only releasing the switch itself replaces the running turn with it.
if (first.providerSwitch && !isUrgent(first)) return false;
const now = first.providerSwitch ? [first] : (modeGroups(released)[0] ?? []);
const behavior: QueuedMessageUrgency = released.some(
(message) => message.urgency === "interrupt",
)
// Do not jump over a queued provider switch ahead of urgent items.
const segment = first.providerSwitch ? prefix : beforeSwitch(prefix);
const behavior: QueuedMessageUrgency = prefix.some((message) => message.urgency === "interrupt")
? "interrupt"
: "steer";
// Agent and finish steers must not sweep human-queued items sitting ahead of them, and wait
// until turn end when the provider cannot steer. Explicit interrupts, Send now promotions,
// and direct provider switches release the prefix in order and may replace the active turn.
const replaceActiveTurn =
behavior === "interrupt" ||
prefix.some((message) => isUrgent(message) && (message.promoted || message.source === null));
const released = replaceActiveTurn
? segment
: segment.filter((message) => !isHumanQueued(message));
const [head] = released;
if (!head) return false;
const now = head.providerSwitch ? [head] : (modeGroups(released)[0] ?? []);
// A non-steering provider keeps agent/finish steer messages queued until turn end rather
// than interrupting it. Human promotions ("Send now") and interrupts still replace it.
if (
isRunning(recipientId) &&
behavior === "steer" &&
!replaceActiveTurn &&
!canSteer(recipientId)
) {
await clearUrgency(recipientId, released);
return false;
}
// The rest follows when the turn these start ends. Persist the downgrade before dispatching
// so a daemon restart while the first group runs does not revive consumed urgency.
const deferred = released.slice(now.length);
if (deferred.length) {
for (const message of deferred) message.urgency = null;
const deferredIds = idsOf(deferred);
await write(store.clearUrgency(recipientId, deferredIds), recipientId, deferredIds);
}
await deliver(recipientId, now, false, stopped, behavior);
const nowIds = new Set(idsOf(now));
const deferred = prefix.filter((message) => isUrgent(message) && !nowIds.has(message.id));
await clearUrgency(recipientId, deferred);
await deliver(recipientId, now, false, stopped, behavior, replaceActiveTurn);
return true;
}
@@ -900,8 +946,16 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
inbox.phase = "waiting";
const running = isRunning(recipientId);
if (running) inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
const nothingToOffer = !dependencies.tryRunOutOfBand || !inbox.messages.some(isOfferable);
if (running && nothingToOffer) return;
const hasSteerableUrgent = inbox.messages.some(
(message) =>
isUrgent(message) &&
(message.urgency === "interrupt" ||
message.promoted ||
message.source === null ||
canSteer(recipientId)),
);
const hasOfferable = Boolean(dependencies.tryRunOutOfBand) && inbox.messages.some(isOfferable);
if (running && !hasOfferable && !hasSteerableUrgent) return;
nudge(recipientId, inbox);
}
@@ -926,7 +980,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
if (insertIndex >= 0) inbox.messages.splice(insertIndex, 0, item);
else inbox.messages.push(item);
inbox.cancelTimer();
if (item.urgency) {
const batchesInQuietWindow =
item.source?.kind === "agent-notification" && item.urgency !== "interrupt";
if (item.urgency && !batchesInQuietWindow) {
// 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();
@@ -968,6 +1024,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
resolve,
reject,
state: "queued",
promoted: false,
outOfBandDeclined: false,
saved: Promise.resolve(),
persisted: false,
@@ -984,7 +1041,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
guidance: describeAgentMessage({
activeTurnBehavior,
running: isRunning(recipientId),
canSteer: Boolean(dependencies.canSteer?.(recipientId)),
canSteer: canSteer(recipientId),
immediateWhenIdle: !source,
}),
};
@@ -1043,55 +1100,20 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
}
}
function join(riders: Ready[], direct: DirectPrompt): JoinedPrompt {
if (!riders.length) {
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
return {
prompt: own.prompt,
uploadedImages: direct.uploadedImages ?? [],
messageId: own.messageId,
sessionMode: direct.sessionMode,
unarchive: direct.unarchive !== false,
};
}
// Sharing a prompt with queued messages, each entry needs its own marker to stay
// a separate row with its own identity.
const own = envelopeMessage(direct.prompt, direct.source ?? null, direct.messageId);
const queued = messagesOf(riders);
function prepareDirectPrompt(direct: DirectPrompt): JoinedPrompt {
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
return {
prompt: combine([...riders.map(envelopeEntry), own.prompt]),
uploadedImages: [...uploadedImagesOf(riders), ...(direct.uploadedImages ?? [])],
prompt: own.prompt,
uploadedImages: direct.uploadedImages ?? [],
messageId: own.messageId,
sessionMode:
direct.sessionMode ?? queued.findLast((message) => message.sessionMode)?.sessionMode,
unarchive: direct.unarchive !== false || queued.some((message) => message.unarchive),
sessionMode: direct.sessionMode,
unarchive: direct.unarchive !== false,
};
}
/**
* Messages that rode a direct prompt are delivered when the provider admits that prompt.
* Until it answers, nothing later may pass them.
*/
async function ride(
recipientId: string,
riders: Admitted[],
result: PromptDispatchResult,
): Promise<void> {
if (!riders.length) return;
if (result.disposition === "turn_started") {
try {
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
} catch {
// The provider rejected the prompt that carried them. They go again, in their place.
return handBack(recipientId, riders);
}
}
await complete(recipientId, riders, result.disposition);
}
/**
* The stopped recipient stays stopped. Its queue, steers and interrupts included, goes with whatever
* prompts it next.
* The stopped recipient stays stopped. Its queue, steers and interrupts included, waits until
* a later prompt reopens it or a queued item is promoted.
*/
function hold(recipientId: string, inbox: Inbox): void {
inbox.cancelTimer();
@@ -1100,17 +1122,26 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
inbox.stops++;
for (const message of inbox.messages) {
message.urgency = null;
message.promoted = false;
message.held = true;
}
void write(store.markHeld(recipientId), recipientId);
}
/** A prompt admitted after a Stop releases what it left in the queue. */
function reopen(recipientId: string, messages: Admitted[]): void {
/** A prompt admitted after a Stop unpauses any held queue so it drains after this turn. */
async function reopenHeld(recipientId: string, stopped: () => boolean): Promise<void> {
const inbox = inboxes.get(recipientId);
if (inbox?.phase !== "held") return;
for (const message of messages) message.held = false;
if (closed || stopped() || inbox?.phase !== "held") return;
for (const message of inbox.messages) message.held = false;
inbox.phase = "waiting";
if (inbox.messages.length) {
await write(store.clearHeld(recipientId), recipientId);
} else {
changed(recipientId);
}
if (!closed && !stopped() && !isRunning(recipientId)) {
attempt(recipientId);
}
}
/** Without a message admitted since the Stop, the queue is held again. */
@@ -1219,7 +1250,11 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await queued.saved;
return queued.receipt;
}
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
const requestedBehavior = message.activeTurnBehavior ?? "queue";
const activeTurnBehavior: AgentMessageBehavior =
requestedBehavior === "steer" && isRunning(recipientId) && !canSteer(recipientId)
? "queue"
: requestedBehavior;
const source = message.source ?? null;
const item = createAdmitted(
{
@@ -1310,7 +1345,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
): Promise<DirectSendResult<Result>> {
const { recipientId } = direct;
// A retried direct send whose earlier attempt was queued must return that queued entry
// rather than coalescing with itself or interrupting the turn ahead of it.
// rather than duplicating or interrupting the turn ahead of it.
if (direct.messageId) {
const existing = inboxes
.get(recipientId)
@@ -1322,56 +1357,53 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
return { disposition: "queued", receipt: existing.receipt };
}
}
// Its place in line is decided now: what is queued goes with it, what comes later follows.
// A queued provider switch, and what follows it, waits for the turn this prompt starts.
const takesQueue = !closed && !direct.resumesTurn && !isCommand(direct.prompt);
const inbox = inboxes.get(recipientId);
const queued = takesQueue ? [...(inbox?.messages ?? [])] : [];
const ahead = beforeSwitch(queued);
const behind = queued.slice(ahead.length);
const stopped = inbox ? watchForStop(inbox) : () => false;
// When queued messages ahead of this prompt cross a boundary (conflicting sessionMode or
// queued non-agent command), insert this prompt immediately after `ahead` with urgency so
// the earlier group runs first under its own mode and this prompt follows on its own turn
// before any queued provider switch or later arrival.
if (takesQueue && !canCoalesceDirect({ ahead: ahead.filter(isQueued), direct })) {
const receipt = await enqueueDirect({ direct, insertBeforeId: behind[0]?.id });
const stopsBefore = inboxes.get(recipientId)?.stops ?? 0;
const stopped = () => (inboxes.get(recipientId)?.stops ?? 0) !== stopsBefore;
const queuedBehindCurrentProvider = (): string | null | undefined => {
if (closed || !direct.providerSwitch) return null;
const current = [...(inboxes.get(recipientId)?.messages ?? [])];
const ahead = beforeSwitch(current);
return ahead.some(isQueued) ? current[ahead.length]?.id : null;
};
// A direct provider switch must not move queued messages meant for the current provider
// onto the target provider, so queue it right after them and release them first.
const insertBeforeId = queuedBehindCurrentProvider();
if (insertBeforeId !== null) {
const receipt = await enqueueDirect({ direct, insertBeforeId });
return { disposition: "queued", receipt };
}
return new Promise<DirectSendResult<Result>>((resolve, reject) => {
run(recipientId, async () => {
let riders: Admitted[] = [];
let result: Result;
try {
const pending = closed ? [] : await prepare(recipientId, ahead);
if (
!closed &&
takesQueue &&
!canCoalesceDirect({ ahead: messagesOf(pending), direct })
) {
const aheadSet = new Set(ahead);
const insertBeforeId = inboxes
.get(recipientId)
?.messages.find((entry) => !aheadSet.has(entry))?.id;
const receipt = await enqueueDirect({ direct, insertBeforeId });
const deferredInsertBeforeId = queuedBehindCurrentProvider();
if (deferredInsertBeforeId !== null) {
const receipt = await enqueueDirect({
direct,
insertBeforeId: deferredInsertBeforeId,
});
resolve({ disposition: "queued", receipt });
return;
}
const dispatching = await markDispatching(recipientId, pending);
riders = messagesOf(dispatching);
for (const message of riders) message.state = "claimed";
for (const message of riders) message.beforeDispatch?.();
result = await send(join(dispatching, direct));
result = await send(prepareDirectPrompt(direct));
} catch (error) {
await handBack(recipientId, riders);
reject(error);
return;
}
resolve(result);
await ride(recipientId, riders, result);
if (behind.length && !stopped()) reopen(recipientId, behind);
if (result.disposition === "turn_started") {
try {
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
} catch {
return;
}
}
if (!direct.resumesTurn && !isCommand(direct.prompt)) {
await reopenHeld(recipientId, stopped);
}
});
});
},
@@ -1412,6 +1444,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
if (!promoted.has(message.id)) continue;
message.urgency = urgency;
message.held = false;
message.promoted = true;
}
inbox.cancelTimer();
inbox.cancelCap();
@@ -305,16 +305,16 @@ test("Stop holds the queue across a restart until it is promoted", async () => {
await second.delivery.close();
});
test("a prompt sent after a restart carries the held messages", async () => {
test("a prompt sent after a restart runs alone, clears the hold, and delivers held messages after the turn ends", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "held");
await first.stop();
await first.delivery.close();
const second = openDaemon(home);
await second.delivery.start();
let prompt: AgentPromptInput = "";
const second = openDaemon(home, { running: true });
await second.delivery.start();
await second.delivery.sendDirect(
{ recipientId: "parent", prompt: "continue", messageId: "next" },
async (joined) => {
@@ -323,7 +323,12 @@ test("a prompt sent after a restart carries the held messages", async () => {
},
);
await second.settle();
expect(String(prompt)).toContain('message-id="held"');
expect(prompt).toBe("continue");
expect(await second.saved("parent")).toEqual([{ id: "held", state: "queued", held: false }]);
expect(second.ids()).toEqual([]);
await second.endTurn();
expect(second.ids()).toEqual([["held"]]);
expect(await second.saved("parent")).toEqual([]);
await second.delivery.close();
});
@@ -79,6 +79,28 @@ describe("trailing marker", () => {
}
});
test("gives each bundled user message its own messageId instead of copying the outer one", () => {
const text = [
formatAgentMessage({ id: "user-1", source: null, text: "First question" }),
formatAgentMessage({ id: "user-2", source: null, text: "Second question" }),
].join("\n\n");
expect(project(text, "provider-echo")).toEqual([
{
type: "user_message",
text: "First question",
clientMessageId: "user-1",
messageId: "user-1",
},
{
type: "user_message",
text: "Second question",
clientMessageId: "user-2",
messageId: "user-2",
},
]);
});
test("a body with leading whitespace replays the same after a provider trims the prompt", () => {
const source = { kind: "agent-message" as const, agentId: "lead", title: "Lead" };
for (const text of ["\n indented code", " - list"]) {
@@ -277,7 +277,9 @@ export function envelopeMessage(
export function projectAgentMessages(item: AgentTimelineItem): AgentTimelineItem[] {
if (item.type !== "user_message") return [item];
const messages = parseAgentMessages(item.text);
return messages ? messages.map((message) => projectAgentMessage(item, message)) : [item];
if (!messages) return [item];
const bundled = messages.length > 1;
return messages.map((message) => projectAgentMessage(item, message, bundled));
}
const AGENT_MESSAGE_CALL = "paseo-agent-message:";
@@ -300,9 +302,18 @@ export function projectedMessageIds(item: AgentTimelineItem): string[] {
function projectAgentMessage(
item: Extract<AgentTimelineItem, { type: "user_message" }>,
message: AgentMessage,
bundled: boolean,
): AgentTimelineItem {
const { source } = message;
if (!source) return { ...item, text: message.text, clientMessageId: message.id };
if (!source) {
return {
...item,
text: message.text,
clientMessageId: message.id,
// Keep each bundled human row uniquely identified instead of cloning the outer messageId.
...(bundled && item.messageId !== undefined ? { messageId: message.id } : {}),
};
}
switch (source.kind) {
case "schedule":
return {
@@ -32,7 +32,7 @@ export function describeAgentMessage(admission: Admission): string {
"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.';
: '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 waits until the current turn ends.';
return `${waiting} ${followUp} ${DO_NOT_REPEAT}`;
}
if (!running) return "The agent is idle, so your message starts a turn now.";
@@ -40,5 +40,5 @@ export function describeAgentMessage(admission: Admission): string {
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.";
: "This agent's provider cannot steer, so your message is queued until the running turn ends.";
}
@@ -1,6 +1,7 @@
import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js";
import {
assertValidRecipientId,
clearHeldInQueue,
clearQueue,
clearUrgencyInQueue,
cloneQueuedMessage,
@@ -62,6 +63,7 @@ export function createMemoryAgentMessageQueueStore(): AgentMessageQueueStore {
revertDispatching: (recipientId, ids) =>
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
clearHeld: (recipientId) => mutate(recipientId, (current) => clearHeldInQueue(current)),
clearUrgency: (recipientId, ids) =>
mutate(recipientId, (current) => clearUrgencyInQueue(current, ids)),
promote: (recipientId, targetId, urgency) =>
@@ -322,6 +322,32 @@ export function markHeldInQueue(
};
}
export function clearHeldInQueue(current: RecipientQueueState): TransitionOutcome<void> {
if (current.items.length === 0) {
return { nextState: current, changed: false, result: undefined };
}
let changed = false;
const nextItems = current.items.map((item) => {
const copy = cloneQueuedMessage(item);
if (copy.held) {
copy.held = false;
changed = true;
}
return copy;
});
if (!changed) {
return { nextState: current, changed: false, result: undefined };
}
return {
nextState: { nextSeq: current.nextSeq, items: nextItems },
changed: true,
result: undefined,
};
}
export function promoteInQueue(
current: RecipientQueueState,
targetId: string,
@@ -391,6 +391,16 @@ export function createSqliteAgentMessageQueueStore(
});
},
async clearHeld(recipientId: string): Promise<void> {
assertValidRecipientId(recipientId);
database.write((sql) => {
sql.run(
"UPDATE agent_message_queue_items SET held = 0 WHERE recipient_id = ? AND held = 1",
recipientId,
);
});
},
async clearUrgency(recipientId: string, ids: readonly string[]): Promise<void> {
assertValidRecipientId(recipientId);
if (ids.length === 0) {
@@ -562,6 +562,19 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
state: "queued",
}),
]);
await store.clearHeld("agent-1");
expect(
(await store.listByRecipient("agent-1")).map((item) => ({
id: item.id,
held: item.held,
urgency: item.urgency,
state: item.state,
})),
).toEqual([
{ id: "m1", held: false, urgency: null, state: "dispatching" },
{ id: "m2", held: false, urgency: null, state: "queued" },
]);
});
test("promote promotes FIFO prefix 0..k, clears held, and reports not_found / already_dispatching", async () => {
@@ -73,6 +73,7 @@ export interface AgentMessageQueueStore {
): Promise<PersistedQueuedMessage[]>;
revertDispatching(recipientId: string, ids: readonly string[]): Promise<void>;
markHeld(recipientId: string): Promise<PersistedQueuedMessage[]>;
clearHeld(recipientId: string): Promise<void>;
clearUrgency(recipientId: string, ids: readonly string[]): Promise<void>;
promote(
recipientId: string,
@@ -99,10 +99,14 @@ async function steerOrReplaceActiveRun(
prompt,
steerOptions,
promptStart,
options.replaceRunning,
);
if (result.status === "steered") {
return { disposition: "steered" };
}
if (result.status === "busy") {
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
}
if (result.status === "replaced") {
return { disposition: "turn_started", iterator: result.iterator };
}
@@ -325,6 +329,8 @@ export interface SendPromptToAgentParams {
source?: AgentPromptSource;
messageId?: string;
activeTurnBehavior?: ActiveTurnBehavior;
/** Override whether an active turn that cannot steer may be interrupted/replaced. */
replaceRunning?: boolean;
runOptions?: AgentRunOptions;
/** Optional mode to set on the agent before the run starts. */
sessionMode?: string;
@@ -452,8 +458,8 @@ async function resolvePromptSource(
* chat mentions, notify-on-finish) MUST go through this so behavior can never
* drift between them.
*
* The prompt does not wait in the agent's message queue, and it does not jump it either:
* messages already queued for the agent are delivered ahead of it in the same provider prompt.
* The prompt does not wait in the agent's message queue and does not sweep queued messages:
* existing queued items stay in the queue until the turn settles or are explicitly promoted.
*
* When `unarchive` is false and the agent is archived, the call is a silent
* no-op (returns the normal turn-start disposition) — the agent is not run.
@@ -548,7 +554,7 @@ export async function sendPreparedPromptToAgent(
throw new Error("Queued agent message was withdrawn");
}
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
replaceRunning: !params.idleOnly,
replaceRunning: params.replaceRunning ?? !params.idleOnly,
idleOnly: params.idleOnly,
admit: params.admit,
onDispatch: params.onDispatch,
@@ -74,12 +74,14 @@ class Observation implements FinishObservation {
}
class Delivery implements FinishMessages {
prompts: string[] = [];
behaviors: Array<string | undefined> = [];
/** Prompts as the recipient's provider receives them, inside their envelope. */
enqueued: string[] = [];
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
enqueuedListeners = new Set<Parameters<FinishMessages["onEnqueued"]>[0]>();
async enqueue(message: Parameters<FinishMessages["enqueue"]>[0]) {
this.prompts.push(message.text);
this.behaviors.push(message.activeTurnBehavior);
this.enqueued.push(
formatAgentMessage({
id: "notification",
@@ -1067,4 +1069,14 @@ describe("suppressing redundant finished notices after an explicit child report"
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Done after bash");
});
test("finish notifications default to activeTurnBehavior steer", async () => {
const state = await scenario();
await state.service.register(intent);
await until(() => state.observation.waits.length === 1);
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "All tests passed"));
await until(() => state.delivery.prompts.length === 1);
expect(state.delivery.behaviors).toEqual(["steer"]);
});
});
@@ -337,8 +337,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
title,
event: finishNotificationEvents[reason],
},
// A finish report never enters a running turn.
activeTurnBehavior: "queue",
// A finish report steers when the provider supports it and queues until turn end otherwise.
activeTurnBehavior: "steer",
unarchive: false,
});
const acknowledge = () => {
@@ -4083,9 +4083,9 @@ describe("send_agent_prompt MCP tool", () => {
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',
applied: "steer",
outcome: "steered",
guidance: "Steering the running turn.",
},
{
agentScoped: true,
@@ -4093,7 +4093,23 @@ describe("send_agent_prompt MCP tool", () => {
steering: "none",
applied: "queue",
outcome: "queued",
guidance: 'provider cannot steer, so "steer" also stops the turn',
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
},
{
agentScoped: true,
behavior: "queue",
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: "queue",
steering: "none",
applied: "queue",
outcome: "queued",
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
},
{
agentScoped: true,
@@ -4107,17 +4123,18 @@ describe("send_agent_prompt MCP tool", () => {
agentScoped: true,
behavior: "steer",
steering: "none",
applied: "steer",
outcome: "replaced",
guidance: "This agent's provider cannot steer, so your message interrupts the running turn.",
applied: "queue",
outcome: "queued",
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
},
// A provider that can steer may refuse one steer; the turn is replaced all the same.
// A provider that can steer may refuse one steer mid-turn; keep the message queued instead of
// replacing the running turn.
{
agentScoped: true,
behavior: "steer",
steering: "unavailable",
applied: "steer",
outcome: "replaced",
outcome: "queued",
guidance: "Steering the running turn.",
},
{
@@ -4318,10 +4335,10 @@ describe("send_agent_prompt MCP tool", () => {
);
expect(response.structuredContent).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "queue",
activeTurnBehavior: "steer",
});
expect(response.structuredContent.guidance).toContain(
"Queued. The agent is idle, so your message starts a turn in about 2 seconds.",
"The agent is idle, so your message starts a turn now.",
);
expect(client.sessions[1]!.prompts).toHaveLength(1);
} finally {
@@ -4373,7 +4390,12 @@ describe("send_agent_prompt MCP tool", () => {
if (rejected) session.rejectNextTurnStart(new Error("Start rejected"));
const response = await mcpClient.callTool({
name: "send_agent_prompt",
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
arguments: {
agentId: child.id,
prompt: "New message",
activeTurnBehavior: "queue",
notifyOnFinish: true,
},
});
expect(response.structuredContent).toMatchObject({
success: true,
@@ -5241,7 +5263,7 @@ describe("message order for one recipient", () => {
}
});
it("a person's prompt takes the queued message into its own turn", async () => {
it("a person's prompt runs alone without sweeping the queued message, which dispatches after the turn settles", async () => {
const recipient = await setupRecipient();
try {
await recipient.agentSends("Go ahead and cut the release");
@@ -5249,10 +5271,8 @@ describe("message order for one recipient", () => {
await recipient.personSends("Pause the release");
expect(recipient.prompt(1)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Pause the release" },
]);
expect(recipient.session.prompts).toHaveLength(2);
expect(recipient.session.prompts[1]).toBe("Pause the release");
const rows = await recipient.agentManager.getTimeline(recipient.recipientId);
expect(rows.flatMap((row) => (row.type === "user_message" ? [row.text] : []))).toEqual([
"Pause the release",
@@ -5260,13 +5280,16 @@ describe("message order for one recipient", () => {
recipient.session.finishTurn();
recipient.advance(10 * 60_000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(2);
expect(recipient.session.prompts).toHaveLength(3);
expect(recipient.prompt(2)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
]);
} finally {
await recipient.cleanup();
}
});
it("Stop holds the queued steer for the recipient's next prompt", async () => {
it("Stop holds the queued steer until a later prompt reopens the queue without sweeping it", async () => {
const recipient = await setupRecipient();
try {
await recipient.agentSends("Go ahead and cut the release");
@@ -5280,9 +5303,14 @@ describe("message order for one recipient", () => {
expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle");
await recipient.personSends("Carry on");
expect(recipient.prompt(1)).toEqual([
expect(recipient.session.prompts).toHaveLength(2);
expect(recipient.session.prompts[1]).toBe("Carry on");
recipient.session.finishTurn();
recipient.advance(2000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(3);
expect(recipient.prompt(2)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Carry on" },
]);
} finally {
await recipient.cleanup();
@@ -5312,7 +5340,7 @@ describe("message order for one recipient", () => {
}
});
it("prompts sent while the provider is still starting a turn reach it in the order sent", async () => {
it("a person's direct prompt does not sweep queued prompts while queued agent messages keep their order", async () => {
const recipient = await setupRecipient();
try {
const acknowledgeStart = recipient.session.holdTurnStart();
@@ -5327,15 +5355,15 @@ describe("message order for one recipient", () => {
acknowledgeStart();
await Promise.all([interrupt, person]);
expect(recipient.prompt(2)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Pause the release" },
]);
expect(recipient.session.prompts[2]).toBe("Pause the release");
recipient.session.finishTurn();
recipient.advance(2000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(4);
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Tests passed" }]);
expect(recipient.prompt(3)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: recipient.senderId, text: "Tests passed" },
]);
} finally {
await recipient.cleanup();
}
@@ -5353,14 +5381,16 @@ describe("message order for one recipient", () => {
await recipient.stop();
await person;
// The next prompt is sent after the interrupt's dispatch has ended, so a turn the
// interrupt started on its own would show up as a prompt between the two.
// The next prompt is sent after the interrupt's dispatch has ended, so it runs alone and
// reopens the held interrupt to run after this turn finishes.
await recipient.personSends("Carry on");
expect(recipient.session.prompts).toHaveLength(3);
expect(recipient.prompt(2)).toEqual([
{ from: recipient.senderId, text: "Skip the backup" },
{ from: "person", text: "Carry on" },
]);
expect(recipient.session.prompts[2]).toBe("Carry on");
recipient.session.finishTurn();
recipient.advance(2000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(4);
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Skip the backup" }]);
} finally {
await recipient.cleanup();
}
@@ -5427,7 +5457,7 @@ describe("message order for one recipient", () => {
}
});
it("a queued message returns to the queue when the provider rejects the person's turn", async () => {
it("a queued message stays in 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");
@@ -5437,12 +5467,9 @@ describe("message order for one recipient", () => {
await expect(recipient.personSends("Pause the release")).rejects.toThrow(
"Provider is overloaded",
);
expect(recipient.prompt(1)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Pause the release" },
]);
expect(recipient.session.prompts[1]).toBe("Pause the release");
// The provider never took that prompt, so the steer is delivered on its own.
// The provider rejected the person's prompt; the queued steer still dispatches on its own.
recipient.advance(2000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(3);
@@ -1408,7 +1408,7 @@ function createToolCatalog(
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.',
'Default "steer": the message joins the running turn, or waits until the turn ends if the provider cannot steer. "queue": the message waits until the running turn ends. "interrupt": the running turn stops and a new turn starts with the message. A steer or interrupt carries earlier agent-queued messages ahead of it (never human-queued items), in order.',
),
notifyOnFinish: z
.boolean()
@@ -2117,7 +2117,7 @@ function createToolCatalog(
title: "Send agent prompt",
description:
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 message to another agent. The response returns at once. Its guidance says whether the message steers the running turn, waits for it to end, or interrupts it, and how to deliver a waiting message now. By default activeTurnBehavior is steer (or queue if the provider cannot steer); pass queue to wait for turn end. 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 agent-queued 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: {
@@ -2201,7 +2201,7 @@ function createToolCatalog(
title: resolveCallerAgent()?.config.title ?? undefined,
},
sessionMode,
activeTurnBehavior,
activeTurnBehavior: activeTurnBehavior ?? "steer",
onDispatch: confirmDispatch,
})
.catch((error) => {
@@ -79,20 +79,31 @@ async function createWorkingRecipient(options: { olderClient?: boolean } = {}) {
}
}
test("an agent's message without a behavior waits for the running turn and says how to deliver it now", async () => {
test("an agent's message without a behavior steers a steering turn and can be overridden to queue", async () => {
const { client, runtime, recipient, sender, close } = await createWorkingRecipient();
try {
const receipt = await client.sendAgentMessage(recipient.id, "Report when done", {
const steered = await client.sendAgentMessage(recipient.id, "Adjust approach", {
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);
expect(steered).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "steer" });
expect(steered.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("Adjust approach");
const queued = await client.sendAgentMessage(recipient.id, "Report when done", {
sourceAgentId: sender.id,
activeTurnBehavior: "queue",
});
expect(queued).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
expect(queued.guidance).toContain("Queued, not delivered yet.");
expect(queued.guidance).toContain('"steer" (it joins the running turn)');
expect(runtime.prompts).toHaveLength(2);
runtime.finishExecution();
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2);
expect(runtime.prompts[1]).toContain("Report when done");
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
expect(runtime.prompts[2]).toContain("Report when done");
} finally {
await close();
}
@@ -229,6 +240,11 @@ async function createModeBoundaryRecipient(input: {
onStartTurn: (prompt, config) => {
executedTurns.push({ prompt: String(prompt), modeId: config.modeId });
},
onInterrupt: () => {
for (const gate of gates.values()) {
gate.release();
}
},
beforeTurnComplete: async (prompt) => {
const text = String(prompt);
for (const [needle, gate] of gates) {
@@ -277,12 +293,12 @@ async function createModeBoundaryRecipient(input: {
}
}
test("a direct broader-mode send behind a queued plan-mode message runs as two separate turns in their respective modes", async () => {
test("a direct broader-mode send while a plan-mode message is queued runs as two separate turns in their respective modes", async () => {
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
initialModeId: "default",
title: "Mode Boundary Worker",
initialPrompt: "Initial work",
heldPrompts: ["Inspect files read-only"],
heldPrompts: ["Edit production files"],
});
try {
const queuedReceipt = await client.sendAgentMessage(agent.id, "Inspect files read-only", {
@@ -295,34 +311,33 @@ test("a direct broader-mode send behind a queued plan-mode message runs as two s
activeTurnBehavior: "interrupt",
sessionMode: "bypassPermissions",
});
expect(directReceipt).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "interrupt",
});
expect(directReceipt).toEqual({});
releaseTurn("Initial work");
expect(await waitForTurn(1)).toEqual({
prompt: "Inspect files read-only",
modeId: "plan",
});
releaseTurn("Inspect files read-only");
expect(await waitForTurn(2)).toEqual({
prompt: "Edit production files",
modeId: "bypassPermissions",
});
expect((await client.listAgentQueue(agent.id)).items).toMatchObject([
{ text: "Inspect files read-only", state: "queued" },
]);
releaseTurn("Edit production files");
expect(await waitForTurn(2)).toEqual({
prompt: "Inspect files read-only",
modeId: "plan",
});
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
} finally {
await close();
}
});
test("a direct bypassPermissions send behind a queued implicit-mode message on a restricted-mode agent runs as two separate turns", async () => {
test("a direct bypassPermissions send while an implicit-mode message is queued on a restricted-mode agent runs as two separate turns", async () => {
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
initialModeId: "always-ask",
title: "Implicit Mode Worker",
initialPrompt: "Initial restricted turn",
heldPrompts: ["Queued in existing mode"],
heldPrompts: ["Apply edits in bypass mode"],
});
try {
const queuedReceipt = await client.sendAgentMessage(agent.id, "Queued in existing mode", {
@@ -334,24 +349,156 @@ test("a direct bypassPermissions send behind a queued implicit-mode message on a
activeTurnBehavior: "interrupt",
sessionMode: "bypassPermissions",
});
expect(directReceipt).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "interrupt",
});
expect(directReceipt).toEqual({});
releaseTurn("Initial restricted turn");
expect(await waitForTurn(1)).toEqual({
prompt: "Queued in existing mode",
modeId: "always-ask",
});
releaseTurn("Queued in existing mode");
expect(await waitForTurn(2)).toEqual({
prompt: "Apply edits in bypass mode",
modeId: "bypassPermissions",
});
expect((await client.listAgentQueue(agent.id)).items).toMatchObject([
{ text: "Queued in existing mode", state: "queued" },
]);
releaseTurn("Apply edits in bypass mode");
expect(await waitForTurn(2)).toEqual({
prompt: "Queued in existing mode",
modeId: "bypassPermissions",
});
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
} finally {
await close();
}
});
test.each(["steer", "interrupt"] as const)(
"a human direct %s keeps queued user messages in the host queue and dispatches them after the turn ends",
async (behavior) => {
const { client, runtime, recipient, close } = await createWorkingRecipient();
try {
const queuedReceipt = await client.sendAgentMessage(recipient.id, "Queued user follow-up", {
activeTurnBehavior: "queue",
});
expect(queuedReceipt).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "queue",
});
const directReceipt = await client.sendAgentMessage(recipient.id, "Human direct prompt", {
activeTurnBehavior: behavior,
});
expect(directReceipt).toEqual({});
await expect.poll(() => runtime.prompts.length, { timeout: 5_000 }).toBe(2);
expect(runtime.prompts[1]).toBe("Human direct prompt");
expect(runtime.prompts[1]).not.toContain("Queued user follow-up");
const queueState = await client.listAgentQueue(recipient.id);
expect(queueState.items).toHaveLength(1);
expect(queueState.items[0]).toMatchObject({
text: "Queued user follow-up",
state: "queued",
});
runtime.finishExecution();
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
expect(runtime.prompts[2]).toBe("Queued user follow-up");
await expect
.poll(async () => (await client.listAgentQueue(recipient.id)).items.length, {
timeout: 5_000,
})
.toBe(0);
} finally {
await close();
}
},
);
test("agent steer falls back to queue on a non-steering provider without interrupting, while explicit interrupt replaces the turn", async () => {
const artifacts = path.resolve(".artifacts");
await mkdir(artifacts, { recursive: true });
const root = await mkdtemp(path.join(artifacts, "agent-non-steering-behavior-"));
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" }],
});
let interrupts = 0;
const origInterrupt = runtime.api.session.interrupt;
runtime.api.session.interrupt = async (input, options) => {
interrupts += 1;
return origInterrupt(input, options);
};
runtime.prompt = async (input) => {
runtime.prompts.push(input.text);
runtime.startExecution();
};
const bridge = new OpenCodeBridge({
paseoHome: path.join(root, "bridge"),
logger: createTestLogger(),
});
await bridge.start();
const opencodeClient = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: runtime.runtime,
bridge,
});
// Disable mid-turn steering to model an ACP provider without steerActiveTurn.
const originalCreateSession = opencodeClient.createSession.bind(opencodeClient);
opencodeClient.createSession = async (config) => {
const session = await originalCreateSession(config);
session.steerActiveTurn = undefined;
return session;
};
const daemon = await createTestPaseoDaemon({
agentClients: {
...createTestAgentClients(),
opencode: opencodeClient,
},
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` });
try {
await client.connect();
await client.fetchAgents({ subscribe: {} });
const recipient = await client.createAgent({
provider: "opencode",
cwd: root,
title: "ACP-like",
});
const sender = await client.createAgent({ provider: "claude", cwd: root });
await client.sendMessage(recipient.id, "Long initial turn");
await client.waitForAgentUpsert(recipient.id, (agent) => agent.status === "running");
// Default omitted behavior and explicit steer both fall back to queue without interrupting.
const defaultSteer = await client.sendAgentMessage(recipient.id, "Default steer note", {
sourceAgentId: sender.id,
});
expect(defaultSteer).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
expect(interrupts).toBe(0);
expect(runtime.prompts).toHaveLength(1);
runtime.finishExecution();
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2);
expect(runtime.prompts[1]).toContain("Default steer note");
await client.waitForAgentUpsert(recipient.id, (agent) => agent.status === "running");
// Explicit interrupt still interrupts and starts a new turn.
const interrupt = await client.sendAgentMessage(recipient.id, "Urgent stop", {
sourceAgentId: sender.id,
activeTurnBehavior: "interrupt",
});
expect(interrupt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "interrupt" });
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
expect(interrupts).toBeGreaterThanOrEqual(1);
expect(runtime.prompts[2]).toContain("Urgent stop");
} finally {
await client.close();
await daemon.close();
await bridge.close();
await rm(root, { recursive: true, force: true });
}
});
@@ -7745,4 +7745,89 @@ describe("session agent_update and agent_stream ordering", () => {
await session.cleanup();
}
});
test("agent-originated send_agent_message defaults omitted activeTurnBehavior to steer for modern clients and keeps explicit queue", async () => {
const receiptDir = mkdtempSync(join(tmpdir(), "paseo-agent-default-steer-"));
const dispatched: Array<{ activeTurnBehavior: string; idleOnly: boolean }> = [];
const agentMessages = createAgentMessageDelivery({
store: createMemoryAgentMessageQueueStore(),
paseoHome: receiptDir,
isRunning: () => true,
canSteer: () => true,
dispatch: async (request) => {
dispatched.push({
activeTurnBehavior: request.activeTurnBehavior,
idleOnly: request.idleOnly,
});
return "steered";
},
onError: (error) => {
throw error;
},
});
const messages: SessionOutboundMessage[] = [];
const session = createSessionForTest({
messages,
agentMessages,
messageReceipts: new MessageReceipts(receiptDir),
paseoHome: receiptDir,
agentManager: {
getAgent: (id: string) =>
({
id,
status: "running",
config: { title: id === "sender-1" ? "Sender" : null },
}) as never,
},
agentStorage: {
get: async (id: string) =>
({ id, title: id === "sender-1" ? "Sender" : null, lastUserMessageAt: null }) as never,
},
});
session.updateClientCapabilities({ agent_active_turn_behaviors: true });
try {
await session.handleMessage({
type: "send_agent_message_request",
requestId: "req-default",
agentId: "agent-1",
sourceAgentId: "sender-1",
text: "Steer by default",
messageId: "msg-steer-default",
});
expect(findByType(messages, "send_agent_message_response")).toMatchObject({
payload: {
requestId: "req-default",
accepted: true,
deliveryStatus: "queued",
activeTurnBehavior: "steer",
},
});
await expect.poll(() => dispatched.length).toBe(1);
expect(dispatched[0]).toEqual({ activeTurnBehavior: "steer", idleOnly: false });
messages.length = 0;
await session.handleMessage({
type: "send_agent_message_request",
requestId: "req-explicit-queue",
agentId: "agent-1",
sourceAgentId: "sender-1",
text: "Wait explicitly",
messageId: "msg-explicit-queue",
activeTurnBehavior: "queue",
});
expect(findByType(messages, "send_agent_message_response")).toMatchObject({
payload: {
requestId: "req-explicit-queue",
accepted: true,
deliveryStatus: "queued",
activeTurnBehavior: "queue",
},
});
} finally {
await session.cleanup();
await agentMessages.close();
rmSync(receiptDir, { recursive: true, force: true });
}
});
});
+2 -2
View File
@@ -9918,7 +9918,7 @@ export class Session {
}
}
/** An agent sender's message waits for the running turn to end unless it asks otherwise. */
/** An agent sender's message steers by default (or queues if its provider cannot steer). */
private agentSenderBehavior(
requested: AgentActiveTurnBehavior | undefined,
): AgentMessageBehavior {
@@ -9927,7 +9927,7 @@ export class Session {
// 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";
return requested ?? "steer";
}
private async handleAgentProviderSwitchRequest(
@@ -893,6 +893,7 @@ export class VoiceAssistantWebSocketServer {
})
: await sendPreparedPromptToAgent({
...send,
replaceRunning: batch.replaceRunning,
sessionMode: batch.sessionMode,
runOptions: { clientMessageId: batch.messageIds[0] },
});
+5 -5
View File
@@ -96,13 +96,13 @@ Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false`
**`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:
Leave `activeTurnBehavior` out unless you want non-default handling 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.
- `steer` (default): the agent reads the message at its next step and keeps working. If its provider cannot steer (or refuses steering mid-turn), the message waits until the turn ends instead of interrupting it.
- `queue`: wait until the running turn ends.
- `interrupt`: stop the running turn and start a new turn 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.
Read `guidance` in the response. If your message is waiting for turn end and cannot wait, send a short `interrupt` follow-up instead of resending (agent follow-ups carry earlier agent-queued messages ahead of them).
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`.