Compare commits

...
5 Commits
Author SHA1 Message Date
Mohamed Boudra a9a803be52 chore(release): cut 0.19.1 2026-12-03 19:11:56 +01:00
Mohamed Boudra e7f2913109 docs(changelog): add 0.19.1 release notes 2026-12-03 19:07:34 +01:00
Mohamed Boudra 6e071b60f2 test(app): keep queued message intact when tapping Send to steer (#11928)
* test(app): keep queued message intact when tapping Send to steer

PR #11915 changed direct steer and interrupt sends to preserve queued messages in the composer queue track instead of sweeping them into the direct prompt. Update the browser E2E step to assert that the queued row remains queued when steering with a tap.

* test(app): wait for steer acknowledgement before asserting queue preservation

(cherry picked from commit ee21a56c7f)
2026-12-03 19:07:34 +01:00
Mohamed Boudra 8a8bc76cc6 fix(server): preserve queued messages on direct sends and default agent messages to steer (#11915)
* fix(server): preserve queued messages on direct sends and default agent messages to steer

* fix(server): let Send now promote with steer replace non-steering active turns

* fix(server): preserve outer providerMessageId on bundled rewind and move allowReplace into options

* fix(agent): preserve providerMessageId in provider history sync and timeline import

* fix(agent): omit empty steerOptions unless allowReplace is disabled

* fix(agent): address Neon review blockers in delivery and envelope ownership

* fix(agent): keep 10s collecting cap active for finish notices under waiting human messages

(cherry picked from commit ca2de1d741)
2026-12-03 17:20:25 +01:00
paseo-bot[bot] a246b931ed Notify parent agents when a queued Claude steer finishes (#11872)
* fix(server): notify parents after queued Claude steers finish

Claude can run a queued steer as its own turn. Keep the finish subscription active while that steer is pending in the live query.

* test(server): release Claude Stop hook after the steer queues

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
(cherry picked from commit c9ba30194c)
2026-12-03 17:20:25 +01:00
52 changed files with 2219 additions and 650 deletions
+12
View File
@@ -1,5 +1,17 @@
# Changelog
## 0.19.1 - 2026-12-03
### Changed
- Changed agent messages and subagent finish notifications to default to `steer`, falling back to `queue` on providers that cannot steer mid-turn instead of interrupting the active turn ([#11915](https://github.com/getpaseo/paseo/pull/11915))
### Fixed
- Fixed direct `steer` and `interrupt` prompts clearing queued messages and finish notifications from the queue ([#11915](https://github.com/getpaseo/paseo/pull/11915))
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts ([#11915](https://github.com/getpaseo/paseo/pull/11915))
- Fixed parent agents missing the follow-up completion notice when Claude runs a queued steer as a separate turn ([#11872](https://github.com/getpaseo/paseo/pull/11872))
## 0.19.0 - 2026-12-03
- **Switch providers mid-chat:** Switch a chat to another provider and keep the conversation, with chat history now stored on the host. ([#11410](https://github.com/getpaseo/paseo/pull/11410))
+12
View File
@@ -1,5 +1,17 @@
# Changelog
## 0.19.1 - 2026-12-03
### 变更
- 将 Agent 消息和子 Agent 完成通知的默认行为改为 `steer`,在不支持运行中转向的 Provider 上回退到 `queue` 而不中断当前轮次 ([#11915](https://github.com/getpaseo/paseo/pull/11915))
### 修复
- 修复直接发送 `steer` 或 `interrupt` 消息时清空队列中的消息和完成通知的问题 ([#11915](https://github.com/getpaseo/paseo/pull/11915))
- 修复排队消息批次在临时派发错误或启动超时后被丢弃而不是保留的问题 ([#11915](https://github.com/getpaseo/paseo/pull/11915))
- 修复 Claude 将排队的 steer 作为独立轮次执行后,父 Agent 漏收后续完成通知的问题 ([#11872](https://github.com/getpaseo/paseo/pull/11872))
## 0.19.0 - 2026-12-03
- **对话中切换 Provider**:可将对话切换到其他 Provider 并保留对话内容,对话记录现在存储在主机上。([#11410](https://github.com/getpaseo/paseo/pull/11410))
+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).
@@ -0,0 +1,8 @@
Changed
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
Fixed
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,8 @@
Changed
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
Fixed
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,8 @@
Changed
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
Fixed
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,8 @@
Changed
- Changed agent messages and subagent finish notifications to default to steer, falling back to queue on providers that cannot steer mid-turn instead of interrupting the active turn
Fixed
- Fixed direct steer and interrupt prompts clearing queued messages and finish notifications from the queue
- Fixed queued message batches being dropped instead of held after transient dispatch errors or run-start timeouts
Full notes: https://paseo.sh/changelog
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.19.0",
"version": "0.19.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.19.0",
"version": "0.19.1",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37552,7 +37552,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.19.0",
"version": "0.19.1",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39705,13 +39705,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/server": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/server": "0.19.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39961,11 +39961,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.19.0",
"@getpaseo/relay": "0.19.0",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/relay": "0.19.1",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39977,7 +39977,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40221,7 +40221,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.19.0",
"version": "0.19.1",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40267,7 +40267,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40297,7 +40297,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40305,8 +40305,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40316,8 +40316,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40339,7 +40339,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40366,7 +40366,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.19.0",
"version": "0.19.1",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40382,7 +40382,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40604,17 +40604,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.19.0",
"@getpaseo/highlight": "0.19.0",
"@getpaseo/plugin": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/relay": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/highlight": "0.19.1",
"@getpaseo/plugin": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/relay": "0.19.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -41579,7 +41579,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.19.0",
"version": "0.19.1",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43205,7 +43205,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.19.0",
"version": "0.19.1",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.19.0",
"version": "0.19.1",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -1370,7 +1370,7 @@ test.describe("Agent message submission", () => {
).toHaveCount(0);
});
await test.step("tapping Send still steers and takes the queued row along", async () => {
await test.step("tapping Send still steers without sweeping the queued row", async () => {
const steeredPrompt = "Steer this turn with a tap.";
await fillComposerDraft(page, steeredPrompt);
await page.getByRole("button", { name: "Send and steer", exact: true }).click();
@@ -1379,13 +1379,13 @@ test.describe("Agent message submission", () => {
expect(request.text).toBe(steeredPrompt);
expect(request.activeTurnBehavior).toBe("steer");
gate.accept(1);
await expect(
page.getByTestId("user-message").filter({ hasText: steeredPrompt }),
).toHaveCount(1);
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
const steeredMessage = page.getByTestId("user-message").filter({ hasText: steeredPrompt });
await expect(steeredMessage).toHaveCount(1);
await expect(steeredMessage).toHaveAttribute("aria-busy", "false");
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(1);
await expect(
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
).toHaveCount(1);
).toHaveCount(0);
});
} finally {
await agent.cleanup();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.19.0",
"version": "0.19.1",
"private": true,
"main": "index.ts",
"scripts": {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.19.0",
"version": "0.19.1",
"description": "Paseo CLI - control your AI coding agents from the command line",
"license": "Apache-2.0",
"bin": {
@@ -29,9 +29,9 @@
},
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/server": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/server": "0.19.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+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");
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.19.0",
"version": "0.19.1",
"description": "Paseo client SDK package",
"license": "Apache-2.0",
"files": [
@@ -57,8 +57,8 @@
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
},
"dependencies": {
"@getpaseo/protocol": "0.19.0",
"@getpaseo/relay": "0.19.0",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/relay": "0.19.1",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.19.0",
"version": "0.19.1",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.19.0",
"version": "0.19.1",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.19.0",
"version": "0.19.1",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.19.0",
"version": "0.19.1",
"description": "Paseo plugin SDK package",
"license": "Apache-2.0",
"files": [
@@ -83,8 +83,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -94,8 +94,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.19.0",
"version": "0.19.1",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
@@ -1,6 +1,6 @@
{
"name": "react-native-enriched-markdown",
"version": "0.19.0",
"version": "0.19.1",
"private": true,
"description": "Markdown-based Rich Text solution for React Native",
"main": "./lib/module/index",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.19.0",
"version": "0.19.1",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.19.0",
"version": "0.19.1",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -114,11 +114,11 @@
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.19.0",
"@getpaseo/highlight": "0.19.0",
"@getpaseo/plugin": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/relay": "0.19.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/highlight": "0.19.1",
"@getpaseo/plugin": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/relay": "0.19.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -18408,3 +18408,267 @@ 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", {
allowReplace: 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", { allowReplace: false }),
).resolves.toEqual({ status: "inactive" });
} finally {
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
test("bundled user messages keep distinct row messageIds while preserving outer providerMessageId for rewind", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-bundled-rewind-"));
const rewindMessageIds: string[] = [];
class BundledRewindSession extends SteeringTestSession {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsRewindFiles: true,
};
readonly history: AgentStreamEvent[] = [];
override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
this.startPrompts.push(prompt);
const turnId = `active-turn-${++this.startCount}`;
const text = typeof prompt === "string" ? prompt : "structured";
this.history.push({
type: "timeline",
provider: this.provider,
item: { type: "user_message", text, messageId: "provider-msg-bundle" },
});
setTimeout(() => {
this.pushEvent({ type: "turn_started", provider: this.provider, turnId });
this.pushEvent({
type: "timeline",
provider: this.provider,
turnId,
item: {
type: "user_message",
text,
messageId: "provider-msg-bundle",
clientMessageId: "user-1",
},
});
this.pushEvent({ type: "turn_completed", provider: this.provider, turnId });
}, 0);
return { turnId };
}
override async *streamHistory() {
for (const event of this.history) yield event;
}
override async revertFiles({ messageId }: { messageId: string }) {
rewindMessageIds.push(messageId);
}
}
const session = new BundledRewindSession({ 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,
});
try {
const bundled = [
formatAgentMessage({ id: "user-1", source: null, text: "First bundled prompt" }),
formatAgentMessage({ id: "user-2", source: null, text: "Second bundled prompt" }),
].join("\n\n");
await startAgentRun(manager, agent.id, bundled, logger, {
runOptions: { clientMessageId: "user-1" },
});
await manager.waitForAgentRunStart(agent.id);
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
const rows = (await manager.getTimeline(agent.id)).filter(
(item): item is Extract<typeof item, { type: "user_message" }> =>
item.type === "user_message",
);
expect(rows.map((item) => ({ messageId: item.messageId, text: item.text }))).toEqual([
{ messageId: "user-1", text: "First bundled prompt" },
{ messageId: "user-2", text: "Second bundled prompt" },
]);
await manager.rewind(agent.id, "user-2", "files");
expect(rewindMessageIds).toEqual(["provider-msg-bundle"]);
session.history.push(
{
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "Third prompt", messageId: "provider-msg-3" },
},
{
type: "timeline",
provider: "codex",
item: { type: "assistant_message", text: "Third reply" },
},
);
expect(await manager.reconcileProviderHistory(agent.id)).toEqual({ kind: "appended" });
const reconciledTexts = (await manager.getTimeline(agent.id))
.filter((item) => item.type === "user_message" || item.type === "assistant_message")
.map((item) => item.text);
expect(reconciledTexts).toEqual([
"First bundled prompt",
"Second bundled prompt",
"Third prompt",
"Third reply",
]);
} finally {
await manager.closeAgent(agent.id);
rmSync(workdir, { recursive: true, force: true });
}
});
test("initialTimeline preserves outer providerMessageId across split bundled user messages for rewind and history sync", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-imported-bundled-rewind-"));
const rewindMessageIds: string[] = [];
const bundled = [
formatAgentMessage({ id: "user-1", source: null, text: "First imported prompt" }),
formatAgentMessage({ id: "user-2", source: null, text: "Second imported prompt" }),
].join("\n\n");
const history: AgentStreamEvent[] = [
{
type: "timeline",
provider: "codex",
item: { type: "user_message", text: bundled, messageId: "provider-imported-bundle" },
},
{
type: "timeline",
provider: "codex",
item: { type: "assistant_message", text: "Imported reply" },
},
];
class ImportedBundledSession extends TestAgentSession {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsRewindFiles: true,
};
readonly initialTimeline = history.flatMap((event) =>
event.type === "timeline" ? [{ item: event.item }] : [],
);
override async *streamHistory() {
for (const event of history) yield event;
}
override async revertFiles({ messageId }: { messageId: string }) {
rewindMessageIds.push(messageId);
}
}
const session = new ImportedBundledSession({ 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,
});
try {
const importedRows = (await manager.getTimeline(agent.id)).filter(
(item): item is Extract<typeof item, { type: "user_message" }> =>
item.type === "user_message",
);
expect(
importedRows.map((item) => ({
messageId: item.messageId,
clientMessageId: item.clientMessageId,
text: item.text,
})),
).toEqual([
{
messageId: "provider-imported-bundle",
clientMessageId: "user-1",
text: "First imported prompt",
},
{
messageId: "provider-imported-bundle",
clientMessageId: "user-2",
text: "Second imported prompt",
},
]);
await manager.rewind(agent.id, "provider-imported-bundle", "files");
expect(rewindMessageIds).toEqual(["provider-imported-bundle"]);
history.push(
{
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "Next prompt", messageId: "provider-next" },
},
{
type: "timeline",
provider: "codex",
item: { type: "assistant_message", text: "Next reply" },
},
);
expect(await manager.reconcileProviderHistory(agent.id)).toEqual({ kind: "appended" });
} 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 {
@@ -594,13 +594,15 @@ export interface AgentPromptSubmissionOptions extends AgentRunOptions {
export interface AgentPromptSteerOptions extends AgentSteerOptions {
/** Daemon timeline metadata for uploaded image attachments; never forwarded to providers. */
uploadedImages?: readonly UploadedImage[];
/** Whether unavailable/rejected mid-turn steering may cancel and replace the running turn. */
allowReplace?: boolean;
}
function stripSteerOptions(
options?: AgentPromptSteerOptions,
): AgentPromptSubmissionOptions | undefined {
if (!options) return undefined;
const { clearPendingPermissions: _, ...runOptions } = options;
const { clearPendingPermissions: _, allowReplace: _allowReplace, ...runOptions } = options;
return runOptions;
}
@@ -612,7 +614,7 @@ function toProviderRunOptions(options?: AgentPromptSubmissionOptions): AgentRunO
function toProviderSteerOptions(options?: AgentPromptSteerOptions): AgentSteerOptions | undefined {
if (!options) return undefined;
const { uploadedImages: _, ...providerOptions } = options;
const { uploadedImages: _, allowReplace: _allowReplace, ...providerOptions } = options;
return providerOptions;
}
@@ -4877,7 +4879,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 +5132,7 @@ export class AgentManager {
options?: AgentPromptSteerOptions,
promptStart?: ForegroundPromptStart,
): Promise<ActiveTurnSteerDispatchResult> {
const allowReplace = options?.allowReplace ?? true;
// 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.
await this.runs.waitForForegroundStart(agentId);
@@ -5168,6 +5171,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 {
@@ -7638,17 +7646,21 @@ export class AgentManager {
text: submittedPromptText(prompt),
clientMessageId,
...(images.length > 0 ? { images } : {}),
...(options?.messageId ? { messageId: options.messageId } : {}),
});
const providerPromptText = options?.providerPromptText ?? renderProviderPromptText(prompt);
const writes: Promise<void>[] = [];
for (const item of items) {
// Human attempts stay in history on rejection; delivery notifications require acceptance.
if (outcome === "rejected" && item.type !== "user_message") continue;
// Give each projected user row its own submitted display ID rather than cloning one shared outer ID.
const submittedItem =
item.type === "user_message" && options?.messageId
? { ...item, messageId: item.clientMessageId ?? options.messageId }
: item;
writes.push(
this.recordSubmittedPromptItem(agent, item, {
this.recordSubmittedPromptItem(agent, submittedItem, {
...options,
...(item.type === "user_message" ? { providerPromptText } : {}),
...(submittedItem.type === "user_message" ? { providerPromptText } : {}),
...(outcome === "rejected" ? { rejected: true } : {}),
}),
);
@@ -7685,8 +7697,9 @@ export class AgentManager {
agent: ActiveManagedAgent,
item: Extract<AgentTimelineItem, { type: "user_message" }>,
turnId?: string,
providerMessageId = item.messageId,
): Promise<boolean> {
const { clientMessageId, messageId } = item;
const { clientMessageId } = item;
if (!clientMessageId) return false;
const scope: TimelineScope = { agentId: agent.id };
const existing = await this.timeline.findSubmittedPrompt(scope, clientMessageId);
@@ -7700,7 +7713,7 @@ export class AgentManager {
messageId: clientMessageId,
},
{
...(messageId ? { providerMessageId: messageId } : {}),
...(providerMessageId ? { providerMessageId } : {}),
providerPromptText: item.text,
...(turnId ? { turnId } : {}),
},
@@ -7708,8 +7721,8 @@ export class AgentManager {
return true;
}
if (existing.item.type !== "user_message") return false;
if (messageId) {
await this.timeline.attachProviderMessageId(scope, clientMessageId, messageId, {
if (providerMessageId) {
await this.timeline.attachProviderMessageId(scope, clientMessageId, providerMessageId, {
providerPromptText: item.text,
});
}
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>;
@@ -107,7 +108,7 @@ interface Inbox {
restoring: boolean;
/** The quiet window while collecting, the busy retry while waiting. */
cancelTimer(): void;
cancelCap(): void;
cancelCap: (() => void) | null;
/** A polling queue step is already in line behind the recipient's current operation. */
advancing: boolean;
/** Stops seen. A queue step reserved before a Stop is void, whatever is admitted afterwards. */
@@ -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.
@@ -206,15 +209,15 @@ export interface AgentMessageDelivery {
}): Promise<void>;
/**
* Admit a message and resolve once it is saved. A queued one waits for the running turn to
* end; a steer or an interrupt releases at once, with everything queued before it.
* end; a steer or an interrupt releases at once, and human or promoted ones take queued items
* ahead of them.
*/
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 +264,12 @@ 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 isDirectUrgent = (message: Admitted): boolean =>
isUrgent(message) && (message.promoted || message.source === null);
const canInterruptOrDirectSteer = (message: Admitted): boolean =>
isUrgent(message) && (message.urgency === "interrupt" || isDirectUrgent(message));
const isOfferable = (message: Admitted): boolean =>
isQueued(message) &&
!message.outOfBandDeclined &&
@@ -376,39 +385,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 +468,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 {
@@ -544,11 +526,18 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
function requestFor(
recipientId: string,
batch: Ready[],
idleOnly: boolean,
stopped: () => boolean,
activeTurnBehavior?: QueuedMessageUrgency,
options: {
idleOnly: boolean;
activeTurnBehavior?: QueuedMessageUrgency;
allowReplace?: boolean;
},
): DispatchRequest {
const { idleOnly, activeTurnBehavior, allowReplace = false } = options;
const messages = messagesOf(batch);
const resolvedBehavior =
activeTurnBehavior ??
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer");
return {
recipientId,
idleOnly,
@@ -561,9 +550,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,
@@ -572,9 +560,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
};
}
function clearCap(inbox: Inbox): void {
inbox.cancelCap?.();
inbox.cancelCap = null;
}
function retire(recipientId: string, inbox: Inbox): void {
inbox.cancelTimer();
inbox.cancelCap();
clearCap(inbox);
if (inboxes.get(recipientId) === inbox) inboxes.delete(recipientId);
}
@@ -713,13 +706,68 @@ 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,
batch: Admitted[],
idleOnly: boolean,
stopped: () => boolean,
activeTurnBehavior?: QueuedMessageUrgency,
options: {
idleOnly: boolean;
activeTurnBehavior?: QueuedMessageUrgency;
allowReplace?: boolean;
},
): Promise<void> {
for (;;) {
const prepared = await prepare(recipientId, batch);
@@ -732,35 +780,22 @@ 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, stopped, options);
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);
}
}
@@ -786,7 +821,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await handBack(recipientId, [message]);
continue;
}
const request = requestFor(recipientId, dispatching, true, stopped);
const request = requestFor(recipientId, dispatching, stopped, { idleOnly: true });
try {
const accepted = await tryRunOutOfBand(request, () => {
if (!request.admit()) throw new Error("Queued agent message was withdrawn");
@@ -818,26 +853,44 @@ 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";
const sweepsHumanQueued = prefix.some(isDirectUrgent);
const replaceActiveTurn = behavior === "interrupt" || sweepsHumanQueued;
const running = isRunning(recipientId);
// While a turn is running, agent steers and interrupts leave human-queued items untouched.
// Once idle, release in strict FIFO order so agent steers never overtake waiting human items.
const released =
sweepsHumanQueued || !running
? 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 (running && 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, stopped, {
idleOnly: !replaceActiveTurn && isHumanQueued(head),
activeTurnBehavior: behavior,
allowReplace: replaceActiveTurn,
});
return true;
}
@@ -866,7 +919,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
if (running()) await offerOutOfBand(recipientId, beforeSwitch(ahead), stopped, running);
// Later mode groups stay queued for the turn ends that follow.
if (waiting() && !isRunning(recipientId))
await deliver(recipientId, modeGroups(ahead.filter(isQueued))[0] ?? [], true, stopped);
await deliver(recipientId, modeGroups(ahead.filter(isQueued))[0] ?? [], stopped, {
idleOnly: true,
});
}
/**
@@ -896,12 +951,16 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
const inbox = inboxes.get(recipientId);
if (closed || !inbox || inbox.phase === "held" || inbox.restoring) return;
inbox.cancelTimer();
inbox.cancelCap();
clearCap(inbox);
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) =>
canInterruptOrDirectSteer(message) || (isUrgent(message) && canSteer(recipientId)),
);
const hasOfferable = Boolean(dependencies.tryRunOutOfBand) && inbox.messages.some(isOfferable);
if (running && !hasOfferable && !hasSteerableUrgent) return;
nudge(recipientId, inbox);
}
@@ -911,7 +970,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
phase: "waiting",
restoring: false,
cancelTimer: () => {},
cancelCap: () => {},
cancelCap: null,
advancing: false,
stops: 0,
};
@@ -926,10 +985,12 @@ 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) {
// 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();
const batchesInQuietWindow =
item.source?.kind === "agent-notification" && item.urgency !== "interrupt";
if (item.urgency && !batchesInQuietWindow) {
// A steer or an interrupt closes the window and releases at once without waiting for the
// quiet spell; reserving its place now stops a later prompt from overtaking it.
clearCap(inbox);
inbox.phase = "waiting";
lineUp(item.recipientId, inbox);
return;
@@ -937,15 +998,19 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
if (!item.source) {
// A non-agent queued message skips the coalescing quiet window: it starts a turn now if the
// recipient is idle, or waits for the running turn to end.
inbox.cancelCap();
clearCap(inbox);
inbox.phase = "waiting";
attempt(item.recipientId);
return;
}
inbox.cancelTimer = schedule(QUIET_MS, () => attempt(item.recipientId));
if (inbox.phase === "collecting") return;
// A new window. It closes after a quiet spell, and no later than the cap.
inbox.phase = "collecting";
const hasWaitingHuman =
inbox.phase === "waiting" &&
inbox.messages.some((entry) => isQueued(entry) && entry.source === null);
if (inbox.phase === "collecting" || (hasWaitingHuman && inbox.cancelCap)) return;
// Keep `waiting` intact when a human prompt is waiting so turn end drains immediately, while
// still capping continuous finish reports at MAX_COLLECTING_MS.
if (!hasWaitingHuman) inbox.phase = "collecting";
inbox.cancelCap = schedule(MAX_COLLECTING_MS, () => attempt(item.recipientId));
}
@@ -968,6 +1033,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
resolve,
reject,
state: "queued",
promoted: false,
outOfBandDeclined: false,
saved: Promise.resolve(),
persisted: false,
@@ -984,7 +1050,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
guidance: describeAgentMessage({
activeTurnBehavior,
running: isRunning(recipientId),
canSteer: Boolean(dependencies.canSteer?.(recipientId)),
canSteer: canSteer(recipientId),
immediateWhenIdle: !source,
}),
};
@@ -1043,74 +1109,49 @@ 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();
inbox.cancelCap();
clearCap(inbox);
inbox.phase = "held";
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) return;
if (inbox.phase !== "held" && !inbox.messages.some((message) => message.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 +1260,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 +1355,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 +1367,56 @@ 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 hasHeldMessages = (): boolean =>
Boolean(inboxes.get(recipientId)?.messages.some((message) => message.held));
const queuedBehindCurrentProvider = (): { insertBeforeId: string | undefined } | null => {
if (closed || !direct.providerSwitch) return null;
const current = [...(inboxes.get(recipientId)?.messages ?? [])];
const ahead = beforeSwitch(current);
return ahead.some(isQueued) ? { insertBeforeId: 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 boundary = queuedBehindCurrentProvider();
if (boundary) {
const receipt = await enqueueDirect({ direct, insertBeforeId: boundary.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 deferredBoundary = queuedBehindCurrentProvider();
if (deferredBoundary) {
const receipt = await enqueueDirect({
direct,
insertBeforeId: deferredBoundary.insertBeforeId,
});
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);
const mayReopenHeld = !direct.resumesTurn && !isCommand(direct.prompt);
if (mayReopenHeld && hasHeldMessages() && result.disposition === "turn_started") {
try {
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
} catch {
return;
}
}
if (mayReopenHeld) {
await reopenHeld(recipientId, stopped);
}
});
});
},
@@ -1412,9 +1457,10 @@ 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();
clearCap(inbox);
inbox.phase = "waiting";
lineUp(recipientId, inbox);
return "promoted";
@@ -1501,7 +1547,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
unsubscribeStop?.();
for (const inbox of inboxes.values()) {
inbox.cancelTimer();
inbox.cancelCap();
clearCap(inbox);
}
closing = drain();
return closing;
@@ -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("keeps the outer provider messageId across split bundled user messages", () => {
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: "provider-echo",
},
{
type: "user_message",
text: "Second question",
clientMessageId: "user-2",
messageId: "provider-echo",
},
]);
});
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,8 @@ 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];
return messages.map((message) => projectAgentMessage(item, message));
}
const AGENT_MESSAGE_CALL = "paseo-agent-message:";
@@ -302,7 +303,9 @@ function projectAgentMessage(
message: AgentMessage,
): AgentTimelineItem {
const { source } = message;
if (!source) return { ...item, text: message.text, clientMessageId: message.id };
if (!source) {
return { ...item, text: message.text, clientMessageId: 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,
@@ -91,9 +91,14 @@ async function steerOrReplaceActiveRun(
return null;
}
const submissionOptions = toSubmissionOptions(options.runOptions, options.uploadedImages);
const steerOptions = options.clearPendingPermissions
? { ...submissionOptions, clearPendingPermissions: true }
: submissionOptions;
const steerOptions =
submissionOptions || options.clearPendingPermissions || options.replaceRunning === false
? {
...submissionOptions,
...(options.clearPendingPermissions ? { clearPendingPermissions: true } : {}),
...(options.replaceRunning === false ? { allowReplace: false } : {}),
}
: undefined;
const result = await agentManager.steerOrReplaceActiveTurn(
agentId,
prompt,
@@ -103,6 +108,9 @@ async function steerOrReplaceActiveRun(
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 +333,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;
@@ -339,7 +349,7 @@ export interface SendPromptToAgentParams {
logger: Logger;
}
/** A prompt that does not wait its turn. Messages queued for the agent go with it. */
/** A prompt that does not wait its turn. */
export interface SendDirectPromptParams extends SendPromptToAgentParams {
agentMessages: Pick<AgentMessageDelivery, "sendDirect">;
/** Raw message text when the caller has it, used if queueing behind a boundary. */
@@ -452,8 +462,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 +558,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 = () => {
@@ -4071,9 +4071,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,
@@ -4081,7 +4081,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,
@@ -4095,17 +4111,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.",
},
{
@@ -4306,10 +4323,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 {
@@ -4361,7 +4378,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,
@@ -5229,7 +5251,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");
@@ -5237,10 +5259,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",
@@ -5248,13 +5268,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");
@@ -5268,9 +5291,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();
@@ -5300,7 +5328,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();
@@ -5315,15 +5343,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();
}
@@ -5341,14 +5369,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();
}
@@ -5415,7 +5445,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");
@@ -5425,12 +5455,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);
@@ -2628,7 +2628,7 @@ class ClaudeAgentSession implements AgentSession {
* dequeues one and resumes the turn we just stopped. SDK user UUIDs are provider-private; never
* let them escape the adapter boundary.
*/
private readonly unstartedMessageUuids = new Set<string>();
private readonly unstartedMessages = new Map<string, "prompt" | "steer">();
/** Human steers whose text has not reached Claude yet and therefore supersede blocking cards. */
private readonly permissionClearingSteerUuids = new Set<string>();
private claudeSessionId: string | null;
@@ -2898,7 +2898,7 @@ class ClaudeAgentSession implements AgentSession {
this.contextUsage.beginTurn();
this.transitionTurnState("foreground", "foreground turn started");
this.clearRecentStderr();
if (sdkUserMessageId) this.unstartedMessageUuids.add(sdkUserMessageId);
if (sdkUserMessageId) this.unstartedMessages.set(sdkUserMessageId, "prompt");
let cancelIssued = false;
const requestCancel = () => {
@@ -2913,7 +2913,7 @@ class ClaudeAgentSession implements AgentSession {
// mainTurnInFlight after Claude started it, so the message's own lifecycle counts too.
const claudeStartedTurn =
this.mainTurnInFlight ||
(sdkUserMessageId !== null && !this.unstartedMessageUuids.has(sdkUserMessageId));
(sdkUserMessageId !== null && !this.unstartedMessages.has(sdkUserMessageId));
this.rejectAllPendingPermissions(new Error("Permission request canceled"));
this.finishForegroundTurn({
type: "turn_canceled",
@@ -2932,7 +2932,7 @@ class ClaudeAgentSession implements AgentSession {
await this.ensureQuery();
if (cancelIssued) {
// Stopped while Claude was still starting up: withdrawn by never sending it.
if (sdkUserMessageId) this.unstartedMessageUuids.delete(sdkUserMessageId);
if (sdkUserMessageId) this.unstartedMessages.delete(sdkUserMessageId);
return { turnId };
}
if (!this.input) {
@@ -2952,7 +2952,7 @@ class ClaudeAgentSession implements AgentSession {
}
}, 0);
} catch (error) {
if (sdkUserMessageId) this.unstartedMessageUuids.delete(sdkUserMessageId);
if (sdkUserMessageId) this.unstartedMessages.delete(sdkUserMessageId);
this.finishForegroundTurn(
this.buildTurnFailedEvent(error instanceof Error ? error.message : "Claude stream failed"),
);
@@ -3004,7 +3004,7 @@ class ClaudeAgentSession implements AgentSession {
clearPendingPermissions: boolean,
): void {
const uuid = message.uuid;
if (uuid) this.unstartedMessageUuids.add(uuid);
if (uuid) this.unstartedMessages.set(uuid, "steer");
if (uuid && clearPendingPermissions) {
this.permissionClearingSteerUuids.add(uuid);
}
@@ -3015,7 +3015,7 @@ class ClaudeAgentSession implements AgentSession {
}
} catch (error) {
if (uuid) {
this.unstartedMessageUuids.delete(uuid);
this.unstartedMessages.delete(uuid);
this.permissionClearingSteerUuids.delete(uuid);
}
throw error;
@@ -3062,12 +3062,13 @@ class ClaudeAgentSession implements AgentSession {
return;
}
// Withdraw queued steers before announcing that the autonomous turn settled.
const interrupt = this.interruptActiveTurn();
if (this.autonomousTurn) {
this.flushPendingToolCalls();
this.completeAutonomousTurn();
}
await this.interruptActiveTurn();
await interrupt;
}
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
@@ -3471,8 +3472,13 @@ class ClaudeAgentSession implements AgentSession {
}
hasPendingWakeup(): boolean {
// A delivered task notification opens its turn only with the next init.
return this.notificationTurnId !== null || this.runtimeSafety.hasPendingWakeup();
// A steer queued in Claude can open a new turn after this one settles.
// A delivered task notification also waits for the next init.
return (
[...this.unstartedMessages.values()].includes("steer") ||
this.notificationTurnId !== null ||
this.runtimeSafety.hasPendingWakeup()
);
}
async canStopRuntime(): Promise<boolean> {
@@ -3484,7 +3490,7 @@ class ClaudeAgentSession implements AgentSession {
!this.activeForegroundTurnId &&
!this.autonomousTurn &&
!this.mainTurnInFlight &&
this.unstartedMessageUuids.size === 0 &&
this.unstartedMessages.size === 0 &&
this.pendingPermissions.size === 0 &&
this.processingSdkMessages === 0 &&
this.runtimeSafety.canStopRuntime()
@@ -3527,8 +3533,7 @@ class ClaudeAgentSession implements AgentSession {
// close() already terminates the SDK query. Its control plane is no longer
// available; waiting for interrupt/return here delays our process-tree cleanup
// beyond the daemon's close deadline when the provider stops answering.
this.query = null;
this.input = null;
this.detachQuery();
// Terminate the entire process tree (claude + MCP children) to prevent
// orphan accumulation. The SDK's internal cleanup may only kill the
// direct child process.
@@ -4009,6 +4014,17 @@ class ClaudeAgentSession implements AgentSession {
return { kind: "fresh-session" };
}
private detachQuery(): void {
this.query = null;
this.input = null;
// A steer belongs to the query that accepted it. A foreground prompt can
// already be waiting for a replacement query in startTurn().
for (const [uuid, kind] of this.unstartedMessages) {
if (kind === "steer") this.unstartedMessages.delete(uuid);
}
this.permissionClearingSteerUuids.clear();
}
private async retireQuery(): Promise<void> {
const oldQuery = this.query;
if (!oldQuery) return;
@@ -4016,8 +4032,7 @@ class ClaudeAgentSession implements AgentSession {
for (const finish of this.backgroundStops.values()) finish("connection lost");
// Null out query/input BEFORE awaiting the old iterator's return so the
// old pump sees this.query !== activeQuery and skips failActiveTurns.
this.query = null;
this.input = null;
this.detachQuery();
this.queryRestartNeeded = false;
// Ending the input retires the process on purpose. Detach first so its
// exit is not reported as a crash.
@@ -4728,8 +4743,7 @@ class ClaudeAgentSession implements AgentSession {
!this.notificationTurnId &&
!this.taskProtocolSource.hasRunningTasks()
) {
this.query = null;
this.input = null;
this.detachQuery();
this.failRunningRuntimeTasks();
this.logger.info(
{ agentId: this.agentId, pid: child.pid },
@@ -4750,8 +4764,7 @@ class ClaudeAgentSession implements AgentSession {
}
// Drop the dead handles so the next write spawns a fresh process instead of
// failing against a dead transport forever.
this.query = null;
this.input = null;
this.detachQuery();
// The failure goes first: an idle agent whose background work just ended
// otherwise reads as settled to anyone waiting for it to finish.
this.dispatchEvents([
@@ -4853,8 +4866,7 @@ class ClaudeAgentSession implements AgentSession {
}
} finally {
if (this.query === activeQuery) {
this.query = null;
this.input = null;
this.detachQuery();
}
}
}
@@ -5122,8 +5134,7 @@ class ClaudeAgentSession implements AgentSession {
});
}
if (this.query === activeQuery) {
this.query = null;
this.input = null;
this.detachQuery();
}
this.persistence = null;
this.persistedHistory = [];
@@ -5175,7 +5186,7 @@ class ClaudeAgentSession implements AgentSession {
withdrawal.withdrewCount > 0 &&
this.query === queryToInterrupt &&
!this.mainTurnInFlight &&
this.unstartedMessageUuids.size === 0
this.unstartedMessages.size === 0
) {
this.runtimeSafety.notePromptWithdrawn();
}
@@ -5201,8 +5212,8 @@ class ClaudeAgentSession implements AgentSession {
private async withdrawUnstartedMessages(
query: Query,
): Promise<{ withdrewAll: boolean; withdrewCount: number }> {
const uuids = [...this.unstartedMessageUuids];
this.unstartedMessageUuids.clear();
const uuids = [...this.unstartedMessages.keys()];
this.unstartedMessages.clear();
this.permissionClearingSteerUuids.clear();
if (uuids.length === 0) return { withdrewAll: true, withdrewCount: 0 };
// The SDK runtime supports this, but its public Query type has not caught up. Keep the
@@ -5318,7 +5329,7 @@ class ClaudeAgentSession implements AgentSession {
private forgetStartedMessage(message: unknown): void {
const lifecycle = readClaudeCommandLifecycle(message);
if (!lifecycle || lifecycle.state === "queued") return;
this.unstartedMessageUuids.delete(lifecycle.commandUuid);
this.unstartedMessages.delete(lifecycle.commandUuid);
this.permissionClearingSteerUuids.delete(lifecycle.commandUuid);
}
@@ -1543,6 +1543,44 @@ describe.each(TIMELINE_CONTRACT_BACKENDS)("provider history over a $name backend
expect(result).toEqual({ kind: "unchanged" });
});
it("reconciles split bundled user rows sharing one providerMessageId and appends new turns", async () => {
const bundledRow = (id: string, text: string): TimelineEntry => ({
providerMessageId: "provider-bundle-1",
providerPromptText: text,
item: { type: "user_message", text, messageId: id, clientMessageId: id },
});
const { timeline } = await owned([
bundledRow("u-1", "ping"),
bundledRow("u-2", "ping"),
reply("Bundled reply"),
]);
expect(
await timeline.reconcileProviderHistory(scope, [
bundledRow("u-1", "ping"),
bundledRow("u-2", "ping"),
reply("Bundled reply"),
]),
).toEqual({ kind: "unchanged" });
const appended = await timeline.reconcileProviderHistory(scope, [
bundledRow("u-1", "ping"),
bundledRow("u-2", "ping"),
reply("Bundled reply"),
prompt("p-2"),
reply("Next reply"),
]);
expect(appended).toMatchObject({ kind: "appended" });
expect(texts(await timeline.readRows(scope))).toEqual([
"ping",
"ping",
"Bundled reply",
"p-2",
"Next reply",
]);
});
it("keeps the owned history when the provider repeats a prompt id with other text", async () => {
const { backend, timeline } = await owned([prompt("a")]);
const appendsBefore = backend.appends.length;
@@ -13,6 +13,7 @@ interface Prompt {
interface ProviderPrompt extends Prompt {
start: number;
clientMessageId?: string;
}
/**
@@ -41,7 +42,15 @@ export function planProviderHistory(input: {
if (owned.prompts.length > provider.length) {
return { kind: "diverged", reason: "The provider history is missing turns Paseo shows" };
}
if (provider.some((prompt, index) => index > 0 && prompt.id === provider[index - 1].id)) {
// Adjacent prompts from one bundled batch share a provider ID across distinct `clientMessageId`s.
if (
provider.some(
(prompt, index) =>
index > 0 &&
prompt.id === provider[index - 1].id &&
prompt.clientMessageId === provider[index - 1].clientMessageId,
)
) {
return { kind: "diverged", reason: "The provider history has two prompts with one id" };
}
if (owned.prompts.some((prompt, index) => !samePrompt(prompt, provider[index]))) {
@@ -80,12 +89,26 @@ function ownedPrompts(
function providerPrompts(entries: readonly TimelineEntry[]): ProviderPrompt[] {
const prompts: ProviderPrompt[] = [];
entries.forEach(({ item }, start) => {
entries.forEach((entry, start) => {
const { item } = entry;
if (item.type !== "user_message") return;
const prompt = { id: item.messageId, text: item.text, start };
const prompt: ProviderPrompt = {
id: entry.providerMessageId ?? item.messageId,
text: item.text,
start,
clientMessageId: item.clientMessageId,
};
const previous = prompts.at(-1);
// Some providers replay a prompt twice. Reusing an ID for different text is a mismatch.
if (previous && prompt.id !== undefined && samePrompt(prompt, previous)) return;
// Some providers replay a prompt twice. Reusing an ID for different text (or a second
// bundled row with its own clientMessageId) is kept distinct so validation can judge it.
if (
previous &&
prompt.id !== undefined &&
prompt.clientMessageId === previous.clientMessageId &&
samePrompt(prompt, previous)
) {
return;
}
prompts.push(prompt);
});
return prompts;
@@ -1398,7 +1398,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()
@@ -2102,7 +2102,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: {
@@ -2182,7 +2182,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 });
}
});
@@ -0,0 +1,151 @@
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import pino from "pino";
import { expect, test, vi } from "vitest";
import { z } from "zod";
import { parseAgentMessage } from "../agent/agent-messages/index.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { canRunRealProvider, createRealProviderClients } from "./real-provider-test-config.js";
const CallToolResultSchema = z.object({
structuredContent: z.object({ agentId: z.string() }),
});
async function callAgentTool(
port: number,
callerAgentId: string,
name: string,
args: Record<string, unknown>,
) {
const url = new URL(`http://127.0.0.1:${port}/mcp/agents`);
url.searchParams.set("callerAgentId", callerAgentId);
const mcp = new Client({ name: "claude-steer-finish-test", version: "1.0.0" });
try {
await mcp.connect(new StreamableHTTPClientTransport(url));
return await mcp.callTool({ name, arguments: args });
} finally {
await mcp.close();
}
}
test("notifies the parent after a Claude steer runs in its own turn", async ({ skip }) => {
if (!(await canRunRealProvider("claude"))) return skip();
const logger = pino({ level: "silent" });
const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-claude-steer-finish-"));
// Send the steer after Claude has written its first reply and entered the Stop hook.
// Keep the first turn open until MCP accepts the steer.
mkdirSync(path.join(cwd, ".claude"));
writeFileSync(
path.join(cwd, ".claude/settings.json"),
JSON.stringify({
hooks: {
Stop: [
{
hooks: [
{
type: "command",
command: "touch .stop-started && while [ ! -f .stop-release ]; do sleep 0.1; done",
timeout: 45,
},
],
},
],
},
}),
);
const hookReleasePath = path.join(cwd, ".stop-release");
const callerPrompts: string[] = [];
const daemon = await createTestPaseoDaemon({
agentClients: {
...createTestAgentClients({
onStartTurn(prompt, config) {
if (config.title === "Finish caller" && typeof prompt === "string")
callerPrompts.push(prompt);
},
}),
...createRealProviderClients(["claude"], logger),
},
logger,
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
const token = `FINAL_${Date.now().toString(36)}`;
try {
await client.connect();
const caller = await client.createAgent({
provider: "codex",
cwd,
title: "Finish caller",
modeId: "full-access",
});
const created = await callAgentTool(daemon.port, caller.id, "create_agent", {
relationship: { kind: "subagent" },
workspace: { kind: "current" },
provider: "claude/haiku",
title: "Claude child",
settings: { modeId: "bypassPermissions" },
initialPrompt: "Reply with exactly FIRST_DONE. Use no tools.",
});
const childId = CallToolResultSchema.parse(created).structuredContent.agentId;
await vi.waitFor(
() => {
expect(existsSync(path.join(cwd, ".stop-started"))).toBe(true);
expect(daemon.daemon.agentManager.getAgent(childId)?.lifecycle).toBe("running");
},
{ timeout: 45_000, interval: 50 },
);
const steer = await callAgentTool(daemon.port, caller.id, "send_agent_prompt", {
agentId: childId,
activeTurnBehavior: "steer",
prompt: `Reply with exactly ${token}. Use no tools.`,
});
expect(steer.isError).not.toBe(true);
expect(steer.structuredContent).toMatchObject({ deliveryStatus: "queued" });
writeFileSync(hookReleasePath, "");
await vi.waitFor(
async () => {
const timeline = await client.fetchAgentTimeline(childId, { limit: 30 });
const firstReply = timeline.entries.find(
({ item }) => item.type === "assistant_message" && item.text.includes("FIRST_DONE"),
);
const steerReply = timeline.entries.find(
({ item }) => item.type === "assistant_message" && item.text.includes(token),
);
expect(firstReply?.turnId).toBeTruthy();
expect(steerReply?.turnId).toMatch(/^autonomous/);
expect(steerReply?.turnId).not.toBe(firstReply?.turnId);
expect(daemon.daemon.agentManager.getAgent(childId)?.lifecycle).toBe("idle");
},
{ timeout: 50_000, interval: 250 },
);
await vi.waitFor(() => expect(callerPrompts).toHaveLength(2), {
timeout: 5_000,
interval: 100,
});
const [first, second] = callerPrompts.map((prompt) => parseAgentMessage(prompt)!);
for (const notice of [first, second]) {
expect(notice.source).toMatchObject({
kind: "agent-notification",
agentId: childId,
event: "finished",
});
}
expect(first.text).toContain("FIRST_DONE");
expect(first.text).toContain("You will be notified again");
expect(second.text).toContain(token);
expect(second.text).not.toContain("You will be notified again");
} finally {
writeFileSync(hookReleasePath, "");
await client.close();
await daemon.close();
rmSync(cwd, { recursive: true, force: true });
}
}, 120_000);
@@ -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
@@ -9909,7 +9909,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 {
@@ -9918,7 +9918,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(
@@ -878,6 +878,7 @@ export class VoiceAssistantWebSocketServer {
})
: await sendPreparedPromptToAgent({
...send,
replaceRunning: batch.replaceRunning,
sessionMode: batch.sessionMode,
runOptions: { clientMessageId: batch.messageIds[0] },
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/website",
"version": "0.19.0",
"version": "0.19.1",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/builtin-plugins",
"version": "0.19.0",
"version": "0.19.1",
"private": true,
"type": "module",
"scripts": {
+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`.