Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 9f9fcd3aae Preserve single Codex approval choices 2026-12-03 14:40:25 +00:00
paseo-bot[bot]andKevin Le f6600a003b Update Codex approval persistence fix from main
Co-authored-by: Kevin Le <anhle12892@gmail.com>
2026-12-03 14:18:37 +00:00
Kevin Le 4c56e94c3c Merge branch 'main' into fix/codex-elicitation-always-allow 2026-10-23 21:27:31 +07:00
Kevin Le bdb94d917e fix(codex): keep MCP elicitation persistence choices
Codex sends persistence choices for MCP approvals (for example Computer Use
app access) in _meta.persist. The request parser dropped _meta, so the
approval card only offered Allow/Deny and the reply always sent _meta: null.

Expose the known choices as permission actions and reply with
_meta: {persist: "session" | "always"} when the user picks one. Requests
without _meta.persist keep the previous request and reply shapes.
2026-10-23 18:35:12 +07:00
86 changed files with 1114 additions and 3323 deletions
-12
View File
@@ -1,17 +1,5 @@
# 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,17 +1,5 @@
# 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 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:
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:
- **`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.
- **`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.
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.
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.
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 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
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
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 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.
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.
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`) 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 you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
text.
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, 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".
- **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".
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
@@ -1,8 +0,0 @@
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
@@ -1,8 +0,0 @@
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
@@ -1,8 +0,0 @@
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
@@ -1,8 +0,0 @@
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
+1 -1
View File
@@ -1 +1 @@
sha256-xt1xi8llKklgr6gn21Ae+Jmdke4bjMZ0F+CnR1bh8UE=
sha256-6NRyu5y01d/Hx79kROAwN6xjlTJ4sYWi0LuTQiJ+Zjw=
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.19.1",
"version": "0.19.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.19.1",
"version": "0.19.0",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37552,7 +37552,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.19.1",
"version": "0.19.0",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39705,13 +39705,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.19.1",
"version": "0.19.0",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/server": "0.19.1",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/server": "0.19.0",
"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.1",
"version": "0.19.0",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.19.1",
"@getpaseo/relay": "0.19.1",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/relay": "0.19.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39977,7 +39977,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"version": "0.19.0",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40267,7 +40267,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.19.1",
"version": "0.19.0",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40297,7 +40297,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@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.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"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.1",
"version": "0.19.0",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40366,7 +40366,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.19.1",
"version": "0.19.0",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40382,7 +40382,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.19.1",
"version": "0.19.0",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40604,17 +40604,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"@getpaseo/highlight": "0.19.1",
"@getpaseo/plugin": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/relay": "0.19.1",
"@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",
"@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.1",
"version": "0.19.0",
"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.1",
"version": "0.19.0",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.19.1",
"version": "0.19.0",
"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 without sweeping the queued row", async () => {
await test.step("tapping Send still steers and takes the queued row along", 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);
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: steeredPrompt }),
).toHaveCount(1);
await expect(page.getByRole("button", { name: "Send queued message now" })).toHaveCount(0);
await expect(
page.getByTestId("user-message").filter({ hasText: queuedPrompt }),
).toHaveCount(0);
).toHaveCount(1);
});
} finally {
await agent.cleanup();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.19.1",
"version": "0.19.0",
"private": true,
"main": "index.ts",
"scripts": {
@@ -497,30 +497,6 @@ it("recognizes forge references in prose but not in code, links or paths", async
});
});
it.each([
["见 src/app/main.ts,还有", ["src/app/main.ts"]],
["改了 src/a/b/c,然后", ["src/a/b/c"]],
["src/foo.ts、src/bar.ts", ["src/foo.ts", "src/bar.ts"]],
["查看:docs/说明.md:12。", ["docs/说明.md:12"]],
["see src/app/main.ts, ok", ["src/app/main.ts"]],
])("recognizes bare file paths next to sentence punctuation: %s", async (source, expected) => {
const prepared = prepareMarkdownSource(source, "/repo");
const tree = recognizeTextLinks(
await parseMarkdown(prepared.render(), { latexMath: false }),
prepared.linkRecognition.text,
prepared.linkRecognition.inlineCode,
);
const parts = tree.children?.[0]?.children ?? [];
expect(parts.map((node) => node.content ?? node.children?.[0]?.content).join("")).toBe(source);
expect(parts.filter((node) => node.type === "Link").map((node) => node.attributes?.url)).toEqual(
expected,
);
expect(toNativeLinkRecognition(prepared.linkRecognition).text).toMatchObject({
isDisabled: false,
isDefault: false,
});
});
describe("bare URL sentence punctuation", () => {
it.each([".", ",", ";", ":", "!", "?", ")", ").", "...", "?!"])(
"leaves %s outside the link and preserves the rendered sentence",
@@ -1251,18 +1227,6 @@ it.each([
).toEqual([token]);
});
it.each([
["更正此前的进度说明:A/B/C/D 主实验", ["A/B/C/D"]],
["修改:src/index.ts,然后提交。", ["src/index.ts"]],
["见(docs/说明.md)。", ["docs/说明.md"]],
["参考「src/index.ts:12」、「README.md」", ["src/index.ts:12", "README.md"]],
["“./scripts/run”…", ["./scripts/run"]],
["文档在 docs/说明.md 里", ["docs/说明.md"]],
])("ends prose paths at CJK and typographic punctuation: %s", (source, expected) => {
const { linkRecognition } = prepareMarkdownSource(source, "/repo");
expect([...source.matchAll(linkRecognition.text)].map(([text]) => text)).toEqual(expected);
});
it.each([
"before/after",
"and/or",
+6 -48
View File
@@ -9,56 +9,11 @@ import { decodeString } from "micromark-util-decode-string";
import { fromMarkdown } from "mdast-util-from-markdown";
import type { Link, Nodes, Paragraph, PhrasingContent, Root } from "mdast";
// CJK, fullwidth and typographic punctuation (、。,:()【】「」“”…) ends bare URLs and prose
// paths; CJK letters do not.
const PUNCTUATION_BOUNDARY_RANGES: readonly (readonly [number, number])[] = [
[0x2018, 0x2019],
[0x201c, 0x201d],
[0x2026, 0x2026],
[0x3000, 0x3003],
[0x3008, 0x3011],
[0x3014, 0x301f],
[0xff01, 0xff0f],
[0xff1a, 0xff20],
[0xff3b, 0xff40],
[0xff5b, 0xff65],
];
function formatCharacterRanges(ranges: readonly (readonly [number, number])[]): string {
const escape = (codePoint: number) =>
`\\u${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
return ranges
.map(([start, end]) => (start === end ? escape(start) : `${escape(start)}-${escape(end)}`))
.join("");
}
/** The parts of `from`..`to` that no excluded range covers. */
function subtractCharacterRanges(
from: number,
to: number,
excluded: readonly (readonly [number, number])[],
): [number, number][] {
const kept: [number, number][] = [];
let next = from;
for (const [start, end] of excluded) {
if (start > next) kept.push([next, start - 1]);
next = end + 1;
}
if (next <= to) kept.push([next, to]);
return kept;
}
const URL_BOUNDARY = formatCharacterRanges(PUNCTUATION_BOUNDARY_RANGES);
// Non-ASCII characters a path can contain: everything from U+0080 except boundary punctuation.
const PATH_NON_ASCII = formatCharacterRanges(
subtractCharacterRanges(0x80, 0xffff, PUNCTUATION_BOUNDARY_RANGES),
);
// Keep this regex in the syntax shared by JavaScript, ICU and java.util.regex.
// The Unicode flag makes Metro expand it to escapes rejected by native engines.
const PATH_CHARACTER = String.raw`[a-zA-Z0-9${PATH_NON_ASCII}_@.%+-]`;
const PATH_CHARACTER = String.raw`[a-zA-Z0-9\u0080-\uFFFF_@.%+-]`;
const PATH_LETTER = String.raw`[a-zA-Z]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9${PATH_NON_ASCII}_@%+-]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9\u0080-\uFFFF_@%+-]`;
const LINE_SUFFIX = String.raw`(?::\d+(?::\d+)?(?:-\d+(?::\d+)?)?)?`;
const FILE_EXTENSIONS = [...ASSISTANT_FILE_EXTENSIONS]
.map((extension) => extension.replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`))
@@ -75,13 +30,16 @@ function createTextPattern(path: string, forgeReferencePattern?: string): RegExp
const forgeReference = forgeReferencePattern ? `|${forgeReferencePattern}` : "";
// The native adapter mistakes a literal + in lookbehind for a quantifier; use its hex escape.
return new RegExp(
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9${PATH_NON_ASCII}_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9${PATH_NON_ASCII}_@%+:/\\-]|\.${PATH_CHARACTER}))`,
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9\u0080-\uFFFF_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9\u0080-\uFFFF_@%+:/\\-]|\.${PATH_CHARACTER}))`,
"g",
);
}
// Matches bare URLs that MD4C does not autolink, like single-label or bracketed hosts.
// Quotes and unbalanced closing parentheses end the URL. Trailing sentence punctuation stays outside.
// CJK, fullwidth and typographic punctuation (、。,()【】「」“”…) also ends it; CJK letters do not.
const URL_BOUNDARY =
"\\u2018\\u2019\\u201C\\u201D\\u2026\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65";
const URL_CHARACTER = String.raw`[^\s<>()"'\x60${URL_BOUNDARY}]`;
const URL_GROUP = String.raw`\(${URL_CHARACTER}*\)`;
const BARE_URL = String.raw`https?://(?:${URL_CHARACTER}|${URL_GROUP})*(?:[^\s<>()"'\x60.,;:!?${URL_BOUNDARY}]|${URL_GROUP})`;
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/server": "0.19.1",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/server": "0.19.0",
"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>",
"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",
"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",
).choices(["queue", "steer", "interrupt"]),
)
.option("--no-wait", "Return immediately without waiting for completion");
+1 -2
View File
@@ -1,7 +1,6 @@
import type { Command } from "commander";
import { isCompleteGitRemote } from "@getpaseo/protocol/git-remote";
import { connectToDaemon } from "../utils/client.js";
import { resolveCallerPath } from "../utils/paths.js";
import type { CommandError, OutputSchema, SingleResult } from "../output/index.js";
import type { CommandOptions } from "../output/with-output.js";
@@ -59,7 +58,7 @@ export async function runCloneCommand(
try {
const response = await client.cloneGithubProject({
repo,
targetDirectory: resolveCallerPath(targetDirectory, options.daemonTarget),
targetDirectory,
...(repoIsCompleteRemote ? {} : { cloneProtocol: options.protocol }),
});
if (response.error || !response.project || !response.checkoutPath) {
+3 -12
View File
@@ -11,11 +11,7 @@ import {
resolveConfigFromPersisted,
getMainListenAddress,
} from "@getpaseo/server/configuration";
import {
connectToDaemon,
defaultConnectTimeout,
buildDaemonConnectionCommandError,
} from "../../utils/client.js";
import { connectToDaemon, buildDaemonConnectionCommandError } from "../../utils/client.js";
import { withOutput, toCommandError, type CommandOptions } from "../../output/index.js";
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
import { describeDaemonTarget, type DaemonTarget } from "../../utils/daemon-target.js";
@@ -61,17 +57,12 @@ async function probeDaemonStatus(
instance: Awaited<ReturnType<typeof readDaemonInstance>>,
local: Record<string, unknown>,
) {
const timeout = defaultConnectTimeout(target, 1_500);
let connectedDaemon = "unreachable";
let note: string | undefined;
let live: Record<string, unknown> = {};
let client: Awaited<ReturnType<typeof connectToDaemon>> | undefined;
try {
client = await connectToDaemon({
target,
instance: instance ?? undefined,
timeout,
});
client = await connectToDaemon({ target, instance: instance ?? undefined, timeout: 1_500 });
} catch (error) {
const failure = buildDaemonConnectionCommandError({ target, error });
if (target.kind === "endpoint") throw failure;
@@ -83,7 +74,7 @@ async function probeDaemonStatus(
if (!client) return { connectedDaemon, note };
try {
let requestError: unknown;
const status = await client.getDaemonStatus({ timeout }).catch((error: unknown) => {
const status = await client.getDaemonStatus({ timeout: 1_500 }).catch((error: unknown) => {
requestError = error;
return null;
});
+16 -1
View File
@@ -1,7 +1,10 @@
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
import { resolve } from "node:path";
import type { Command } from "commander";
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
import { resolveCallerPath } from "../../utils/paths.js";
import type { DaemonTarget } from "../../utils/daemon-target.js";
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
@@ -122,6 +125,18 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str
}
}
// A relative --path names a directory relative to where the command runs, so
// it is made absolute here for a local daemon, which would otherwise resolve
// it against its own working directory. For an explicit endpoint the path is
// sent as written, the same rule as resolveRepositoryDirectory. An absolute
// path can target a daemon on a different operating system, and the daemon
// expands a leading ~ to its own home directory.
function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
const isHomeRelative = input === "~" || input.startsWith("~/");
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
return daemonTarget.kind === "instance" ? resolve(input) : input;
}
export function buildWorkspaceSource(options: WorkspaceCreateOptions) {
const callerPath =
options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget);
+10 -2
View File
@@ -1,7 +1,6 @@
import type { Command } from "commander";
import { basename } from "node:path";
import { connectToDaemon } from "../../utils/client.js";
import { shortenHomePath } from "../../utils/paths.js";
import { resolveRepositoryDirectory } from "./repository-directory.js";
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
@@ -13,6 +12,15 @@ export interface WorktreeListItem {
agent: string;
}
/** Shorten home directory in path */
function shortenPath(path: string): string {
const home = process.env.HOME;
if (home && path.startsWith(home)) {
return "~" + path.slice(home.length);
}
return path;
}
/** Extract worktree name from path */
function extractWorktreeName(path: string): string {
return basename(path);
@@ -69,7 +77,7 @@ export async function runLsCommand(
const items: WorktreeListItem[] = response.worktrees.map((wt) => ({
name: extractWorktreeName(wt.worktreePath),
branch: wt.branchName ?? "-",
cwd: shortenHomePath(wt.worktreePath),
cwd: shortenPath(wt.worktreePath),
agent: worktreeAgentMap.get(wt.worktreePath) ?? "-",
}));
+2 -8
View File
@@ -33,13 +33,7 @@ export function resolveClientPaseoHome(
): string {
return target.kind === "instance" ? target.home : resolvePaseoHome(env);
}
export function defaultConnectTimeout(target: DaemonTarget, directTimeout = 15_000): number {
if (target.kind === "endpoint") {
const host = parseHostTarget(target.host);
if (host.kind === "socket" && host.offer) return 90_000;
}
return directTimeout;
}
const DEFAULT_TIMEOUT = 15000;
type TransportTarget =
| { type: "tcp"; url: string }
| { type: "ipc"; url: string; socketPath: string };
@@ -217,7 +211,7 @@ export function resolveDaemonCredential(
}
async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonClient> {
const timeout = options.timeout ?? defaultConnectTimeout(options.target);
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
const host =
options.target.kind === "endpoint"
? options.target.host
@@ -3,7 +3,6 @@ import { test, expect } from "vitest";
import { selectDaemonTarget, describeDaemonTarget } from "./daemon-target.js";
import {
resolveDaemonCredential,
defaultConnectTimeout,
resolveClientPaseoHome,
buildDaemonConnectionCommandError,
} from "./client.js";
@@ -22,15 +21,6 @@ test("explicit selectors win over both environment selectors", () => {
expect(() => selectDaemonTarget({ home: "/tmp/b", host: "chosen:23456" }, {})).toThrow();
});
test("slow relay connections get the full handshake budget, including status probes", () => {
const relay = { kind: "endpoint", host: "relay://relay.example:443/srv?key=key" } as const;
const direct = { kind: "endpoint", host: "127.0.0.1:6767" } as const;
expect(defaultConnectTimeout(relay)).toBe(90_000);
expect(defaultConnectTimeout(relay, 1_500)).toBe(90_000);
expect(defaultConnectTimeout(direct)).toBe(15_000);
expect(defaultConnectTimeout(direct, 1_500)).toBe(1_500);
});
test("endpoint connections resolve local credentials from PASEO_HOME", () => {
expect(
resolveClientPaseoHome(
+3 -11
View File
@@ -1,14 +1,6 @@
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
import { resolve } from "node:path";
import type { DaemonTarget } from "./daemon-target.js";
// Explicit endpoints interpret paths on their host. The daemon also expands ~.
export function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
const isHomeRelative = input === "~" || input.startsWith("~/");
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
return daemonTarget.kind === "instance" ? resolve(input) : input;
}
/**
* Path utilities for cwd filtering in agent commands.
*/
/**
* Check if `candidatePath` is the same directory as `basePath` or a descendant of it.
+26 -35
View File
@@ -21,7 +21,7 @@
import assert from "node:assert";
import { getAvailablePort } from "./helpers/network.ts";
import { $ } from "zx";
import { mkdtemp, rm, mkdir, realpath, writeFile } from "fs/promises";
import { mkdtemp, rm, mkdir } from "fs/promises";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { runPaseoCli, startTestDaemon, type TestDaemonContext } from "./helpers/test-daemon.ts";
@@ -195,37 +195,8 @@ try {
"Initial commit",
]);
const home = join(await realpath(fixtureDir), "home");
await mkdir(home);
await writeFile(
join(home, "config.json"),
JSON.stringify({ version: 1, worktrees: { root: home + "-worktrees" } }),
);
// With an explicit endpoint, relative paths resolve from the daemon cwd.
daemon = await startTestDaemon({ cwd: repo, paseoHome: home, workDir: repo });
const created = await runPaseoCli(
daemon,
[
"worktree",
"create",
"--cwd",
"./repository",
"--mode",
"branch-off",
"--new-branch",
"topic",
"--base",
"main",
"--json",
],
{ cwd: fixtureDir },
);
assert.strictEqual(created.exitCode, 0, created.stderr);
const { worktreePath } = JSON.parse(created.stdout);
const source = await git("git", ["-C", repo, "rev-parse", "HEAD"]);
const checkout = await git("git", ["-C", worktreePath, "rev-parse", "HEAD"]);
assert.strictEqual(checkout.stdout, source.stdout);
daemon = await startTestDaemon({ cwd: repo });
for (const args of [
["worktree", "ls", "--json"],
@@ -239,10 +210,7 @@ try {
env: { FORCE_COLOR: undefined },
});
assert.strictEqual(result.exitCode, 0, result.stderr);
assert.deepStrictEqual(
JSON.parse(result.stdout).map((row: { cwd: string }) => row.cwd),
[worktreePath],
);
assert.deepStrictEqual(JSON.parse(result.stdout), []);
}
for (const args of [
@@ -267,6 +235,29 @@ try {
assert.notStrictEqual(result.exitCode, 0);
assert.strictEqual(JSON.parse(result.stderr).error.code, "WORKTREE_NOT_FOUND", result.stderr);
}
const created = await runPaseoCli(
daemon,
[
"worktree",
"create",
"--cwd",
"./repository",
"--mode",
"branch-off",
"--new-branch",
"topic",
"--base",
"main",
"--json",
],
{ cwd: fixtureDir },
);
assert.strictEqual(created.exitCode, 0, created.stderr);
const { worktreePath } = JSON.parse(created.stdout);
const source = await git("git", ["-C", repo, "rev-parse", "HEAD"]);
const checkout = await git("git", ["-C", worktreePath, "rev-parse", "HEAD"]);
assert.strictEqual(checkout.stdout, source.stdout);
} finally {
try {
await daemon?.stop();
-48
View File
@@ -1,48 +0,0 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdir, realpath } from "node:fs/promises";
import { join } from "node:path";
import { createTempDirs, runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts";
const dirs = await createTempDirs();
const caller = join(dirs.workDir, "caller");
const source = join(dirs.workDir, "source.git");
const gitConfig = join(dirs.paseoHome, ".gitconfig");
const remote = "https://example.test/team/fixture.git";
await mkdir(caller);
execFileSync("git", ["init", "--bare", "--quiet", source]);
execFileSync("git", [
"config",
"--file",
gitConfig,
`url.${source.replaceAll("\\", "/")}.insteadOf`,
remote,
]);
const ctx = await startTestDaemon({
...dirs,
cwd: dirs.workDir,
env: { GIT_CONFIG_GLOBAL: gitConfig },
});
try {
for (const [args, parent] of [
[[], caller],
[["--host", ctx.wsUrl], dirs.workDir],
] as const) {
const result = await runPaseoCli(
ctx,
["clone", remote, "--dir", "./repos", "--json", ...args],
{ cwd: caller },
);
assert.equal(result.exitCode, 0, result.stderr);
const checkout = JSON.parse(result.stdout).checkoutPath;
assert.equal(await realpath(checkout), join(await realpath(parent), "repos", "fixture"));
assert.equal(
execFileSync("git", ["-C", checkout, "rev-parse", "--is-inside-work-tree"], {
encoding: "utf8",
}).trim(),
"true",
);
}
} finally {
await ctx.stop();
}
-63
View File
@@ -56,8 +56,6 @@ function spawnRelayDevServer(port: number): ChildProcess {
String(port),
"--live-reload=false",
"--show-interactive-dev-session=false",
"--var",
"PASEO_RELAY_UPSTREAM:",
],
{
cwd: relayDir,
@@ -119,41 +117,6 @@ async function stopRelayProcess(relayProcess: ChildProcess): Promise<void> {
await waitForProcessExit(relayProcess, Date.now() + 2000);
}
async function withSlowRelay<T>(
relayPort: number,
run: (endpoint: string) => Promise<T>,
): Promise<T> {
const clients = new Set<net.Socket>();
const proxy = net.createServer((client) => {
clients.add(client);
// Delay the client handshake past the old 15-second command deadline.
const connect = setTimeout(() => {
const relay = net.connect(relayPort, "127.0.0.1");
relay.on("error", () => client.destroy());
relay.on("close", () => client.destroy());
client.on("close", () => relay.destroy());
client.pipe(relay).pipe(client);
}, 17_000);
client.on("error", () => client.destroy());
client.on("close", () => {
clearTimeout(connect);
clients.delete(client);
});
});
await new Promise<void>((resolve, reject) => {
proxy.once("error", reject);
proxy.listen(0, "127.0.0.1", resolve);
});
try {
const address = proxy.address();
if (!address || typeof address === "string") throw new Error("Relay proxy did not bind TCP");
return await run(`127.0.0.1:${address.port}`);
} finally {
for (const client of clients) client.destroy();
await new Promise<void>((resolve) => proxy.close(() => resolve()));
}
}
async function probeRelayConnection(offerUrl: string): Promise<boolean> {
const offer = parseConnectionOfferFromUrl(offerUrl);
if (!offer) return false;
@@ -264,30 +227,4 @@ async function waitForDaemonRelayRegistered(offerUrl: string, timeoutMs = 30_000
expect(Array.isArray(relayAgents)).toBe(true);
expect(relayAgents.length).toBe(directAgents.length);
}, 60_000);
it("runs status and ls when the relay handshake takes longer than 15 seconds", async () => {
const context = ctx;
if (!context) throw new Error("test context not initialized");
const direct = await context.paseo(["ls", "--json"]);
expect(direct.exitCode, direct.stderr).toBe(0);
await withSlowRelay(relayPort, async (endpoint) => {
const offer = await generateLocalPairingOffer({
paseoHome: context.paseoHome,
relayEnabled: true,
relayEndpoint: `127.0.0.1:${relayPort}`,
relayPublicEndpoint: endpoint,
includeQr: false,
});
if (!offer.url) throw new Error("generateLocalPairingOffer returned no URL");
const [status, agents] = await Promise.all([
context.paseo(["--host", offer.url, "daemon", "status", "--json"], { timeout: 35_000 }),
context.paseo(["--host", offer.url, "ls", "--json"], { timeout: 35_000 }),
]);
expect(status.exitCode, status.stdout || status.stderr).toBe(0);
expect(JSON.parse(status.stdout).connectedDaemon).toBe("reachable");
expect(agents.exitCode, agents.stdout || agents.stderr).toBe(0);
expect(JSON.parse(agents.stdout)).toEqual(JSON.parse(direct.stdout));
});
}, 45_000);
});
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"@getpaseo/relay": "0.19.1",
"@getpaseo/protocol": "0.19.0",
"@getpaseo/relay": "0.19.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"version": "0.19.0",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.19.1",
"version": "0.19.0",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"@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.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/client": "0.19.0",
"@getpaseo/protocol": "0.19.0",
"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.1",
"version": "0.19.0",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
@@ -169,23 +169,19 @@ describe("published Paseo tool-call detail entry", () => {
path.join(fixture, "node_modules"),
"junction",
);
// Build only the two entries and what they import, with the package's own
// compiler options, so the published layout under dist/ stays the same.
writeFileSync(
path.join(fixture, "tsconfig.json"),
JSON.stringify({
extends: path.join(packageRoot, "tsconfig.json"),
compilerOptions: { outDir: path.join(fixture, "dist"), incremental: false },
files: [
path.join(packageRoot, "src/paseo-tool-call-detail.ts"),
path.join(packageRoot, "src/paseo-tool-presentation/index.ts"),
],
include: [],
}),
execFileSync(
process.execPath,
[
compiler,
"-p",
path.join(packageRoot, "tsconfig.json"),
"--outDir",
path.join(fixture, "dist"),
"--incremental",
"false",
],
{ stdio: "pipe" },
);
execFileSync(process.execPath, [compiler, "-p", path.join(fixture, "tsconfig.json")], {
stdio: "pipe",
});
writeFileSync(
path.join(fixture, "consumer.mts"),
`
@@ -1,6 +1,6 @@
{
"name": "react-native-enriched-markdown",
"version": "0.19.1",
"version": "0.19.0",
"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.1",
"version": "0.19.0",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.19.1",
"version": "0.19.0",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -95,7 +95,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/daemon-e2e/daemon-shutdown.e2e.test.ts src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -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.1",
"@getpaseo/highlight": "0.19.1",
"@getpaseo/plugin": "0.19.1",
"@getpaseo/protocol": "0.19.1",
"@getpaseo/relay": "0.19.1",
"@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",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -18408,267 +18408,3 @@ 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" | "busy" }
| { status: "inactive" | "steered" }
| { status: "replaced"; iterator: AsyncGenerator<AgentStreamEvent> };
export interface AgentPromptSubmissionOptions extends AgentRunOptions {
@@ -594,15 +594,13 @@ 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: _, allowReplace: _allowReplace, ...runOptions } = options;
const { clearPendingPermissions: _, ...runOptions } = options;
return runOptions;
}
@@ -614,7 +612,7 @@ function toProviderRunOptions(options?: AgentPromptSubmissionOptions): AgentRunO
function toProviderSteerOptions(options?: AgentPromptSteerOptions): AgentSteerOptions | undefined {
if (!options) return undefined;
const { uploadedImages: _, allowReplace: _allowReplace, ...providerOptions } = options;
const { uploadedImages: _, ...providerOptions } = options;
return providerOptions;
}
@@ -4880,7 +4878,7 @@ export class AgentManager {
},
"agent.manager.stream.reject",
);
throw new AgentTurnBusyError(`Agent ${agentId} already has an active run`);
throw new Error(`Agent ${agentId} already has an active run`);
}
const agent = existingAgent;
@@ -5133,7 +5131,6 @@ 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);
@@ -5172,11 +5169,6 @@ 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 {
@@ -7647,21 +7639,17 @@ 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, submittedItem, {
this.recordSubmittedPromptItem(agent, item, {
...options,
...(submittedItem.type === "user_message" ? { providerPromptText } : {}),
...(item.type === "user_message" ? { providerPromptText } : {}),
...(outcome === "rejected" ? { rejected: true } : {}),
}),
);
@@ -7698,9 +7686,8 @@ export class AgentManager {
agent: ActiveManagedAgent,
item: Extract<AgentTimelineItem, { type: "user_message" }>,
turnId?: string,
providerMessageId = item.messageId,
): Promise<boolean> {
const { clientMessageId } = item;
const { clientMessageId, messageId } = item;
if (!clientMessageId) return false;
const scope: TimelineScope = { agentId: agent.id };
const existing = await this.timeline.findSubmittedPrompt(scope, clientMessageId);
@@ -7714,7 +7701,7 @@ export class AgentManager {
messageId: clientMessageId,
},
{
...(providerMessageId ? { providerMessageId } : {}),
...(messageId ? { providerMessageId: messageId } : {}),
providerPromptText: item.text,
...(turnId ? { turnId } : {}),
},
@@ -7722,8 +7709,8 @@ export class AgentManager {
return true;
}
if (existing.item.type !== "user_message") return false;
if (providerMessageId) {
await this.timeline.attachProviderMessageId(scope, clientMessageId, providerMessageId, {
if (messageId) {
await this.timeline.attachProviderMessageId(scope, clientMessageId, messageId, {
providerPromptText: item.text,
});
}
@@ -1249,73 +1249,6 @@ describe("agent MCP protocol negotiation", () => {
await daemon.stop();
}
}, 30_000);
test("agent tools resolve 7-char shortId returned by list_agents over HTTP MCP (#8556)", async () => {
const daemon = await startOfflineMcpDaemon();
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-mcp-shortid-"));
try {
const created = await daemon.client.callTool({
name: "create_agent",
args: {
cwd: agentCwd,
title: "ShortId E2E worker",
provider: "claude/claude-test-model",
settings: { modeId: "bypassPermissions" },
initialPrompt: "hello short id",
},
});
expect(created.isError).not.toBe(true);
const createdPayload = getStructuredContent(created);
const fullId = String(createdPayload?.agentId ?? "");
expect(fullId.length).toBeGreaterThan(7);
const listed = await daemon.client.callTool({
name: "list_agents",
args: { cwd: agentCwd },
});
expect(listed.isError).not.toBe(true);
const listedPayload = getStructuredContent(listed);
const agents = listedPayload?.agents as Array<{ id: string; shortId: string }>;
const listedAgent = agents.find((agent) => agent.id === fullId);
expect(listedAgent?.shortId).toBe(fullId.slice(0, 7));
const shortId = listedAgent!.shortId;
const status = await daemon.client.callTool({
name: "get_agent_status",
args: { agentId: shortId },
});
expect(status.isError).not.toBe(true);
expect(getStructuredContent(status)?.snapshot).toMatchObject({
id: fullId,
title: "ShortId E2E worker",
});
const prompted = await daemon.client.callTool({
name: "send_agent_prompt",
args: { agentId: shortId, prompt: "follow-up via shortId" },
});
expect(prompted.isError).not.toBe(true);
const activity = await daemon.client.callTool({
name: "get_agent_activity",
args: { agentId: shortId },
});
expect(activity.isError).not.toBe(true);
expect(getStructuredContent(activity)).toMatchObject({
agentId: fullId,
});
const archived = await daemon.client.callTool({
name: "archive_agent",
args: { agentId: shortId },
});
expect(archived.isError).not.toBe(true);
expect(getStructuredContent(archived)).toEqual({ success: true });
} finally {
await daemon.stop();
await rm(agentCwd, { recursive: true, force: true });
}
}, 30_000);
});
describe("voice-only speak MCP delivery", () => {
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,7 @@
import {
AgentTurnBusyError,
AgentTurnChangedError,
AgentTurnStartRejectedError,
type PromptDispatchDisposition,
type PromptDispatchResult,
} from "../agent-prompt.js";
@@ -72,8 +73,6 @@ 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>;
@@ -108,7 +107,7 @@ interface Inbox {
restoring: boolean;
/** The quiet window while collecting, the busy retry while waiting. */
cancelTimer(): void;
cancelCap: (() => void) | null;
cancelCap(): void;
/** A polling queue step is already in line behind the recipient's current operation. */
advancing: boolean;
/** Stops seen. A queue step reserved before a Stop is void, whatever is admitted afterwards. */
@@ -121,8 +120,6 @@ 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.
@@ -209,15 +206,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, and human or promoted ones take queued items
* ahead of them.
* end; a steer or an interrupt releases at once, with everything queued before it.
*/
enqueue(message: Message): Promise<AgentMessageReceipt>;
/**
* 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.
* 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.
*/
sendDirect<Result extends PromptDispatchResult>(
direct: DirectPrompt,
@@ -264,12 +261,6 @@ 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 &&
@@ -385,10 +376,39 @@ 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" }> {
@@ -468,8 +488,6 @@ 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 {
@@ -526,18 +544,11 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
function requestFor(
recipientId: string,
batch: Ready[],
idleOnly: boolean,
stopped: () => boolean,
options: {
idleOnly: boolean;
activeTurnBehavior?: QueuedMessageUrgency;
allowReplace?: boolean;
},
activeTurnBehavior?: QueuedMessageUrgency,
): 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,
@@ -550,8 +561,9 @@ 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: resolvedBehavior,
replaceRunning: !idleOnly && (resolvedBehavior === "interrupt" || allowReplace),
activeTurnBehavior:
activeTurnBehavior ??
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer"),
// Every message in a batch belongs to one compatible mode group.
sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode,
providerSwitch: messages[0]?.providerSwitch,
@@ -560,14 +572,9 @@ 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();
clearCap(inbox);
inbox.cancelCap();
if (inboxes.get(recipientId) === inbox) inboxes.delete(recipientId);
}
@@ -706,68 +713,13 @@ 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,
options: {
idleOnly: boolean;
activeTurnBehavior?: QueuedMessageUrgency;
allowReplace?: boolean;
},
activeTurnBehavior?: QueuedMessageUrgency,
): Promise<void> {
for (;;) {
const prepared = await prepare(recipientId, batch);
@@ -780,22 +732,35 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await handBack(recipientId, messages);
continue;
}
const request = requestFor(recipientId, dispatching, stopped, options);
const request = requestFor(recipientId, dispatching, idleOnly, stopped, activeTurnBehavior);
let disposition: PromptDispatchDisposition;
try {
for (const message of messages) message.beforeDispatch?.();
const disposition = await dependencies.dispatch(request);
return complete(recipientId, messages, disposition);
disposition = await dependencies.dispatch(request);
} catch (error) {
const outcome = await handleDispatchError({
error,
recipientId,
messages,
request,
stopped,
});
if (outcome === "retry") continue;
return;
// 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);
}
return complete(recipientId, messages, disposition);
}
}
@@ -821,7 +786,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await handBack(recipientId, [message]);
continue;
}
const request = requestFor(recipientId, dispatching, stopped, { idleOnly: true });
const request = requestFor(recipientId, dispatching, true, stopped);
try {
const accepted = await tryRunOutOfBand(request, () => {
if (!request.admit()) throw new Error("Queued agent message was withdrawn");
@@ -853,44 +818,26 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
): Promise<boolean> {
const last = ahead.findLastIndex(isUrgent);
if (last < 0) return false;
const prefix = ahead.slice(0, last + 1).filter(isQueued);
const [first] = prefix;
const released = ahead.slice(0, last + 1).filter(isQueued);
const [first] = released;
if (!first) return false;
// Only releasing the switch itself replaces the running turn with it.
if (first.providerSwitch && !isUrgent(first)) return false;
// 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")
const now = first.providerSwitch ? [first] : (modeGroups(released)[0] ?? []);
const behavior: QueuedMessageUrgency = released.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 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,
});
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);
return true;
}
@@ -919,9 +866,7 @@ 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] ?? [], stopped, {
idleOnly: true,
});
await deliver(recipientId, modeGroups(ahead.filter(isQueued))[0] ?? [], true, stopped);
}
/**
@@ -951,16 +896,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
const inbox = inboxes.get(recipientId);
if (closed || !inbox || inbox.phase === "held" || inbox.restoring) return;
inbox.cancelTimer();
clearCap(inbox);
inbox.cancelCap();
inbox.phase = "waiting";
const running = isRunning(recipientId);
if (running) inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
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;
const nothingToOffer = !dependencies.tryRunOutOfBand || !inbox.messages.some(isOfferable);
if (running && nothingToOffer) return;
nudge(recipientId, inbox);
}
@@ -970,7 +911,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
phase: "waiting",
restoring: false,
cancelTimer: () => {},
cancelCap: null,
cancelCap: () => {},
advancing: false,
stops: 0,
};
@@ -985,12 +926,10 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
if (insertIndex >= 0) inbox.messages.splice(insertIndex, 0, item);
else inbox.messages.push(item);
inbox.cancelTimer();
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);
if (item.urgency) {
// A steer or an interrupt does not wait: it closes the window and takes the queue along. Its place
// is reserved now, so a prompt admitted after it cannot take it away.
inbox.cancelCap();
inbox.phase = "waiting";
lineUp(item.recipientId, inbox);
return;
@@ -998,19 +937,15 @@ 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.
clearCap(inbox);
inbox.cancelCap();
inbox.phase = "waiting";
attempt(item.recipientId);
return;
}
inbox.cancelTimer = schedule(QUIET_MS, () => attempt(item.recipientId));
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";
if (inbox.phase === "collecting") return;
// A new window. It closes after a quiet spell, and no later than the cap.
inbox.phase = "collecting";
inbox.cancelCap = schedule(MAX_COLLECTING_MS, () => attempt(item.recipientId));
}
@@ -1033,7 +968,6 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
resolve,
reject,
state: "queued",
promoted: false,
outOfBandDeclined: false,
saved: Promise.resolve(),
persisted: false,
@@ -1050,7 +984,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
guidance: describeAgentMessage({
activeTurnBehavior,
running: isRunning(recipientId),
canSteer: canSteer(recipientId),
canSteer: Boolean(dependencies.canSteer?.(recipientId)),
immediateWhenIdle: !source,
}),
};
@@ -1109,49 +1043,74 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
}
}
function prepareDirectPrompt(direct: DirectPrompt): JoinedPrompt {
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
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);
return {
prompt: own.prompt,
uploadedImages: direct.uploadedImages ?? [],
prompt: combine([...riders.map(envelopeEntry), own.prompt]),
uploadedImages: [...uploadedImagesOf(riders), ...(direct.uploadedImages ?? [])],
messageId: own.messageId,
sessionMode: direct.sessionMode,
unarchive: direct.unarchive !== false,
sessionMode:
direct.sessionMode ?? queued.findLast((message) => message.sessionMode)?.sessionMode,
unarchive: direct.unarchive !== false || queued.some((message) => message.unarchive),
};
}
/**
* The stopped recipient stays stopped. Its queue, steers and interrupts included, waits until
* a later prompt reopens it or a queued item is promoted.
* 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.
*/
function hold(recipientId: string, inbox: Inbox): void {
inbox.cancelTimer();
clearCap(inbox);
inbox.cancelCap();
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 unpauses any held queue so it drains after this turn. */
async function reopenHeld(recipientId: string, stopped: () => boolean): Promise<void> {
/** A prompt admitted after a Stop releases what it left in the queue. */
function reopen(recipientId: string, messages: Admitted[]): void {
const inbox = inboxes.get(recipientId);
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;
if (inbox?.phase !== "held") return;
for (const message of 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. */
@@ -1260,11 +1219,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
await queued.saved;
return queued.receipt;
}
const requestedBehavior = message.activeTurnBehavior ?? "queue";
const activeTurnBehavior: AgentMessageBehavior =
requestedBehavior === "steer" && isRunning(recipientId) && !canSteer(recipientId)
? "queue"
: requestedBehavior;
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
const source = message.source ?? null;
const item = createAdmitted(
{
@@ -1355,7 +1310,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 duplicating or interrupting the turn ahead of it.
// rather than coalescing with itself or interrupting the turn ahead of it.
if (direct.messageId) {
const existing = inboxes
.get(recipientId)
@@ -1367,56 +1322,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;
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 });
// 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 });
return { disposition: "queued", receipt };
}
return new Promise<DirectSendResult<Result>>((resolve, reject) => {
run(recipientId, async () => {
let riders: Admitted[] = [];
let result: Result;
try {
const deferredBoundary = queuedBehindCurrentProvider();
if (deferredBoundary) {
const receipt = await enqueueDirect({
direct,
insertBeforeId: deferredBoundary.insertBeforeId,
});
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 });
resolve({ disposition: "queued", receipt });
return;
}
result = await send(prepareDirectPrompt(direct));
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));
} catch (error) {
await handBack(recipientId, riders);
reject(error);
return;
}
resolve(result);
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);
}
await ride(recipientId, riders, result);
if (behind.length && !stopped()) reopen(recipientId, behind);
});
});
},
@@ -1457,10 +1412,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
if (!promoted.has(message.id)) continue;
message.urgency = urgency;
message.held = false;
message.promoted = true;
}
inbox.cancelTimer();
clearCap(inbox);
inbox.cancelCap();
inbox.phase = "waiting";
lineUp(recipientId, inbox);
return "promoted";
@@ -1547,7 +1501,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
unsubscribeStop?.();
for (const inbox of inboxes.values()) {
inbox.cancelTimer();
clearCap(inbox);
inbox.cancelCap();
}
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 runs alone, clears the hold, and delivers held messages after the turn ends", async () => {
test("a prompt sent after a restart carries the held messages", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "held");
await first.stop();
await first.delivery.close();
let prompt: AgentPromptInput = "";
const second = openDaemon(home, { running: true });
const second = openDaemon(home);
await second.delivery.start();
let prompt: AgentPromptInput = "";
await second.delivery.sendDirect(
{ recipientId: "parent", prompt: "continue", messageId: "next" },
async (joined) => {
@@ -323,12 +323,7 @@ test("a prompt sent after a restart runs alone, clears the hold, and delivers he
},
);
await second.settle();
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(String(prompt)).toContain('message-id="held"');
expect(await second.saved("parent")).toEqual([]);
await second.delivery.close();
});
@@ -79,28 +79,6 @@ 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,8 +277,7 @@ export function envelopeMessage(
export function projectAgentMessages(item: AgentTimelineItem): AgentTimelineItem[] {
if (item.type !== "user_message") return [item];
const messages = parseAgentMessages(item.text);
if (!messages) return [item];
return messages.map((message) => projectAgentMessage(item, message));
return messages ? messages.map((message) => projectAgentMessage(item, message)) : [item];
}
const AGENT_MESSAGE_CALL = "paseo-agent-message:";
@@ -303,9 +302,7 @@ 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 waits until the current turn ends.';
: 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also stops the turn.';
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 is queued until the running turn ends.";
: "This agent's provider cannot steer, so your message interrupts the running turn. A new turn starts with your message.";
}
@@ -1,7 +1,6 @@
import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js";
import {
assertValidRecipientId,
clearHeldInQueue,
clearQueue,
clearUrgencyInQueue,
cloneQueuedMessage,
@@ -63,7 +62,6 @@ 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,32 +322,6 @@ 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,16 +391,6 @@ 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,19 +562,6 @@ 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,7 +73,6 @@ 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,14 +91,9 @@ async function steerOrReplaceActiveRun(
return null;
}
const submissionOptions = toSubmissionOptions(options.runOptions, options.uploadedImages);
const steerOptions =
submissionOptions || options.clearPendingPermissions || options.replaceRunning === false
? {
...submissionOptions,
...(options.clearPendingPermissions ? { clearPendingPermissions: true } : {}),
...(options.replaceRunning === false ? { allowReplace: false } : {}),
}
: undefined;
const steerOptions = options.clearPendingPermissions
? { ...submissionOptions, clearPendingPermissions: true }
: submissionOptions;
const result = await agentManager.steerOrReplaceActiveTurn(
agentId,
prompt,
@@ -108,9 +103,6 @@ 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 };
}
@@ -333,8 +325,6 @@ 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;
@@ -349,7 +339,7 @@ export interface SendPromptToAgentParams {
logger: Logger;
}
/** A prompt that does not wait its turn. */
/** A prompt that does not wait its turn. Messages queued for the agent go with it. */
export interface SendDirectPromptParams extends SendPromptToAgentParams {
agentMessages: Pick<AgentMessageDelivery, "sendDirect">;
/** Raw message text when the caller has it, used if queueing behind a boundary. */
@@ -462,8 +452,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 does not sweep queued messages:
* existing queued items stay in the queue until the turn settles or are explicitly promoted.
* The prompt does not wait in the agent's message queue, and it does not jump it either:
* messages already queued for the agent are delivered ahead of it in the same provider prompt.
*
* When `unarchive` is false and the agent is archived, the call is a silent
* no-op (returns the normal turn-start disposition) — the agent is not run.
@@ -558,7 +548,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.replaceRunning ?? !params.idleOnly,
replaceRunning: !params.idleOnly,
idleOnly: params.idleOnly,
admit: params.admit,
onDispatch: params.onDispatch,
@@ -74,14 +74,12 @@ 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",
@@ -1069,14 +1067,4 @@ 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 steers when the provider supports it and queues until turn end otherwise.
activeTurnBehavior: "steer",
// A finish report never enters a running turn.
activeTurnBehavior: "queue",
unarchive: false,
});
const acknowledge = () => {
@@ -43,12 +43,9 @@ function isAmbiguousPromptFailure(error: unknown): boolean {
if (error instanceof DaemonConnectionError) return true;
return error instanceof Error && error.message.startsWith("Timeout waiting for message");
}
export interface HostOperationContext extends PaseoToolExecutionContext {
beforeRemotePromptSend?: (resolvedAgentId: string) => Promise<void>;
}
export type HostOperation = (
input: Record<string, unknown>,
context: HostOperationContext,
context: PaseoToolExecutionContext,
) => Promise<PaseoToolResult>;
export interface HostOperations {
createAgent: HostOperation;
@@ -284,16 +281,21 @@ export function createHostResolver(input: {
availableModes: snapshot.availableModes,
});
},
async sendPrompt(args, context) {
const requestedId = args.agentId as string;
async sendPrompt(args) {
const agentId = args.agentId as string;
// Human sends retain the established mode RPC on older connected hosts.
// Agent sends apply their requested mode when the recipient dispatches the batch.
if (!input.callerAgentId && args.sessionMode !== undefined) {
await client.setAgentMode(agentId, args.sessionMode as string);
}
const agent = (
await client.fetchAgent(requestedId).catch((error) => {
await client.fetchAgent(agentId).catch((error) => {
// Snapshot preflight precedes sendMessage, so failure is definitely unsent.
throw new HostOperationRejectedError(error);
})
)?.agent;
if (!agent)
throw new HostOperationRejectedError(new Error(`Agent ${requestedId} not found`));
throw new HostOperationRejectedError(new Error(`Agent ${agentId} not found`));
if (input.callerAgentId && args.sessionMode !== undefined) {
await input.callerPolicy.assertLineage(
{
@@ -323,15 +325,6 @@ export function createHostResolver(input: {
availableModes: agent.availableModes,
});
}
const agentId = agent.id;
// Human sends retain the established mode RPC on older connected hosts.
// Agent sends apply their requested mode when the recipient dispatches the batch.
if (!input.callerAgentId && args.sessionMode !== undefined) {
await client.setAgentMode(agentId, args.sessionMode as string);
}
await context.beforeRemotePromptSend?.(agentId).catch((error) => {
throw new HostOperationRejectedError(error);
});
const receipt = await client
.sendMessage(agentId, args.prompt as string, {
sessionMode: input.callerAgentId
@@ -365,16 +358,16 @@ export function createHostResolver(input: {
return result({ status: agent.status, snapshot: agent });
},
async getActivity(args) {
const requestedId = args.agentId as string;
const agentId = args.agentId as string;
const limit = args.limit as number | undefined;
const agent = (await client.fetchAgent(requestedId))?.agent;
if (!agent) throw new Error(`Agent ${requestedId} not found`);
const timeline = await client.fetchAgentTimeline(agent.id, {
const timeline = await client.fetchAgentTimeline(agentId, {
direction: "tail",
limit: limit ?? 0,
});
const agent = (await client.fetchAgent(agentId))?.agent;
if (!agent) throw new Error(`Agent ${agentId} not found`);
return result({
agentId: agent.id,
agentId,
...summarizeAgentActivity(
timeline.entries.map((entry) => entry.item),
limit,
@@ -24,7 +24,6 @@ import { z } from "zod";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { createAgentMcpServer as createAgentMcpServerWithDependencies } from "./mcp-server.js";
import { PaseoToolInputError } from "./tools/types.js";
import { createMcpHandler } from "@modelcontextprotocol/server";
import { ensureAgentLoaded } from "./agent-loading.js";
import { AgentManager, type ManagedAgent } from "./agent-manager.js";
@@ -4084,9 +4083,9 @@ describe("send_agent_prompt MCP tool", () => {
agentScoped: true,
behavior: undefined,
steering: "accepted",
applied: "steer",
outcome: "steered",
guidance: "Steering the running turn.",
applied: "queue",
outcome: "queued",
guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries',
},
{
agentScoped: true,
@@ -4094,23 +4093,7 @@ describe("send_agent_prompt MCP tool", () => {
steering: "none",
applied: "queue",
outcome: "queued",
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',
guidance: 'provider cannot steer, so "steer" also stops the turn',
},
{
agentScoped: true,
@@ -4124,18 +4107,17 @@ describe("send_agent_prompt MCP tool", () => {
agentScoped: true,
behavior: "steer",
steering: "none",
applied: "queue",
outcome: "queued",
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
applied: "steer",
outcome: "replaced",
guidance: "This agent's provider cannot steer, so your message interrupts the running turn.",
},
// A provider that can steer may refuse one steer mid-turn; keep the message queued instead of
// replacing the running turn.
// A provider that can steer may refuse one steer; the turn is replaced all the same.
{
agentScoped: true,
behavior: "steer",
steering: "unavailable",
applied: "steer",
outcome: "queued",
outcome: "replaced",
guidance: "Steering the running turn.",
},
{
@@ -4336,10 +4318,10 @@ describe("send_agent_prompt MCP tool", () => {
);
expect(response.structuredContent).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "steer",
activeTurnBehavior: "queue",
});
expect(response.structuredContent.guidance).toContain(
"The agent is idle, so your message starts a turn now.",
"Queued. The agent is idle, so your message starts a turn in about 2 seconds.",
);
expect(client.sessions[1]!.prompts).toHaveLength(1);
} finally {
@@ -4391,12 +4373,7 @@ 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",
activeTurnBehavior: "queue",
notifyOnFinish: true,
},
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
});
expect(response.structuredContent).toMatchObject({
success: true,
@@ -5264,7 +5241,7 @@ describe("message order for one recipient", () => {
}
});
it("a person's prompt runs alone without sweeping the queued message, which dispatches after the turn settles", async () => {
it("a person's prompt takes the queued message into its own turn", async () => {
const recipient = await setupRecipient();
try {
await recipient.agentSends("Go ahead and cut the release");
@@ -5272,8 +5249,10 @@ describe("message order for one recipient", () => {
await recipient.personSends("Pause the release");
expect(recipient.session.prompts).toHaveLength(2);
expect(recipient.session.prompts[1]).toBe("Pause the release");
expect(recipient.prompt(1)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Pause the release" },
]);
const rows = await recipient.agentManager.getTimeline(recipient.recipientId);
expect(rows.flatMap((row) => (row.type === "user_message" ? [row.text] : []))).toEqual([
"Pause the release",
@@ -5281,16 +5260,13 @@ describe("message order for one recipient", () => {
recipient.session.finishTurn();
recipient.advance(10 * 60_000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(3);
expect(recipient.prompt(2)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
]);
expect(recipient.session.prompts).toHaveLength(2);
} finally {
await recipient.cleanup();
}
});
it("Stop holds the queued steer until a later prompt reopens the queue without sweeping it", async () => {
it("Stop holds the queued steer for the recipient's next prompt", async () => {
const recipient = await setupRecipient();
try {
await recipient.agentSends("Go ahead and cut the release");
@@ -5304,14 +5280,9 @@ describe("message order for one recipient", () => {
expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle");
await recipient.personSends("Carry on");
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([
expect(recipient.prompt(1)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Carry on" },
]);
} finally {
await recipient.cleanup();
@@ -5341,7 +5312,7 @@ describe("message order for one recipient", () => {
}
});
it("a person's direct prompt does not sweep queued prompts while queued agent messages keep their order", async () => {
it("prompts sent while the provider is still starting a turn reach it in the order sent", async () => {
const recipient = await setupRecipient();
try {
const acknowledgeStart = recipient.session.holdTurnStart();
@@ -5356,15 +5327,15 @@ describe("message order for one recipient", () => {
acknowledgeStart();
await Promise.all([interrupt, person]);
expect(recipient.session.prompts[2]).toBe("Pause the release");
expect(recipient.prompt(2)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Pause the release" },
]);
recipient.session.finishTurn();
recipient.advance(2000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(4);
expect(recipient.prompt(3)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: recipient.senderId, text: "Tests passed" },
]);
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Tests passed" }]);
} finally {
await recipient.cleanup();
}
@@ -5382,16 +5353,14 @@ describe("message order for one recipient", () => {
await recipient.stop();
await person;
// 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.
// The next prompt is sent after the interrupt's dispatch has ended, so a turn the
// interrupt started on its own would show up as a prompt between the two.
await recipient.personSends("Carry on");
expect(recipient.session.prompts).toHaveLength(3);
expect(recipient.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" }]);
expect(recipient.prompt(2)).toEqual([
{ from: recipient.senderId, text: "Skip the backup" },
{ from: "person", text: "Carry on" },
]);
} finally {
await recipient.cleanup();
}
@@ -5458,7 +5427,7 @@ describe("message order for one recipient", () => {
}
});
it("a queued message stays in the queue when the provider rejects the person's turn", async () => {
it("a queued message returns to the queue when the provider rejects the person's turn", async () => {
const recipient = await setupRecipient();
try {
await recipient.agentSends("Go ahead and cut the release");
@@ -5468,9 +5437,12 @@ describe("message order for one recipient", () => {
await expect(recipient.personSends("Pause the release")).rejects.toThrow(
"Provider is overloaded",
);
expect(recipient.session.prompts[1]).toBe("Pause the release");
expect(recipient.prompt(1)).toEqual([
{ from: recipient.senderId, text: "Go ahead and cut the release" },
{ from: "person", text: "Pause the release" },
]);
// The provider rejected the person's prompt; the queued steer still dispatches on its own.
// The provider never took that prompt, so the steer is delivered on its own.
recipient.advance(2000);
await recipient.settled();
expect(recipient.session.prompts).toHaveLength(3);
@@ -8703,205 +8675,3 @@ describe("modern MCP protocol (2026-07-28)", () => {
}
});
});
describe("agent tool shortId prefix resolution (#8556)", () => {
const logger = createTestLogger();
const existingCwd = process.cwd();
it("resolves unique shortId prefixes across live and stored agent tools", async () => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-short-id-live-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const parentClient = new HeldTurnAgentClient("claude", false);
const childClient = new HeldTurnAgentClient("codex", true);
const manager = new AgentManager({
clients: { claude: parentClient, codex: childClient },
registry: storage,
logger,
});
const parentId = "11111111-aaaa-4bbb-8ccc-000000000001";
const childId = "a6d6857c-1111-4222-8333-444444444444";
const storedOnlyId = "c8f8079e-1111-4222-8333-444444444444";
const childShortId = childId.slice(0, 7);
const storedShortId = storedOnlyId.slice(0, 7);
let mcp: Client | undefined;
try {
await manager.createAgent(
{ provider: "claude", cwd: existingCwd, modeId: "bypassPermissions" },
parentId,
{ workspaceId: "wks_short_id" },
);
await manager.createAgent({ provider: "codex", cwd: existingCwd }, childId, {
workspaceId: "wks_short_id",
labels: { [PARENT_AGENT_ID_LABEL]: parentId },
});
await storage.upsert(
createStoredRecord({
id: storedOnlyId,
provider: "claude",
cwd: existingCwd,
workspaceId: "wks_short_id",
title: "Stored worker",
}),
);
const server = await createAgentMcpServer({
agentManager: manager,
agentStorage: storage,
callerAgentId: parentId,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
mcp = await connectInMemoryMcpClient(server);
const statusLower = await registeredTool(server, "get_agent_status").handler({
agentId: childShortId,
});
expect(statusLower.structuredContent.snapshot).toMatchObject({ id: childId });
const statusUpper = await registeredTool(server, "get_agent_status").handler({
agentId: childShortId.toUpperCase(),
});
expect(statusUpper.structuredContent.snapshot).toMatchObject({ id: childId });
const storedStatus = await registeredTool(server, "get_agent_status").handler({
agentId: storedShortId,
});
expect(storedStatus.structuredContent.snapshot).toMatchObject({
id: storedOnlyId,
title: "Stored worker",
});
const sendResult = await mcp.callTool({
name: "send_agent_prompt",
arguments: { agentId: childShortId, prompt: "Short ID work" },
});
expect(sendResult.isError).not.toBe(true);
await serverDeliveries.get(server)!.waitForDispatch(childId, new AbortController().signal);
childClient.sessions[0]!.requestPermission("perm-short");
const respondResult = await mcp.callTool({
name: "respond_to_permission",
arguments: {
agentId: childShortId,
requestId: "perm-short",
response: { behavior: "allow" },
},
});
expect(respondResult.isError).not.toBe(true);
const activity = await registeredTool(server, "get_agent_activity").handler({
agentId: childShortId,
});
expect(activity.structuredContent).toMatchObject({ agentId: childId });
const updateResult = await registeredTool(server, "update_agent").handler({
agentId: childShortId,
name: "Renamed via shortId",
});
expect(updateResult.structuredContent).toEqual({ success: true });
expect((await storage.get(childId))?.title).toBe("Renamed via shortId");
const modeResult = await registeredTool(server, "set_agent_mode").handler({
agentId: childShortId,
modeId: "full-access",
});
expect(modeResult.structuredContent).toEqual({ success: true, newMode: "full-access" });
function readParentNotificationText(): string {
return parentClient.sessions[0]!.prompts.flatMap(
(prompt) => parseAgentMessages(prompt) ?? [],
)
.map((message) => message.text)
.join("\n");
}
childClient.sessions[0]!.finishTurn("Done via shortId");
await vi.waitFor(() => {
expect(readParentNotificationText()).toContain("Done via shortId");
});
const cancelResult = await registeredTool(server, "cancel_agent").handler({
agentId: childShortId,
});
expect(cancelResult.structuredContent).toEqual({ success: false });
const archiveResult = await registeredTool(server, "archive_agent").handler({
agentId: childShortId,
});
expect(archiveResult.structuredContent).toEqual({ success: true });
expect((await storage.get(childId))?.archivedAt).toBeTruthy();
const killResult = await registeredTool(server, "kill_agent").handler({
agentId: parentId.slice(0, 7),
});
expect(killResult.structuredContent).toEqual({ success: true });
expect(manager.getAgent(parentId)).toBeNull();
} finally {
await mcp?.close();
await removeAgentStateDir(manager, storage, workdir);
}
});
it("rejects ambiguous prefixes, empty IDs, internal prefixes, and unknown activity IDs with PaseoToolInputError", async () => {
const workdir = await mkdtemp(join(tmpdir(), "mcp-short-id-errors-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new HeldTurnAgentClient("codex", false);
const manager = new AgentManager({
clients: { codex: client },
registry: storage,
logger,
});
const firstId = "deadbee1-1111-4222-8333-444444444444";
const secondId = "deadbee2-1111-4222-8333-444444444444";
const internalId = "f9a9180f-1111-4222-8333-444444444444";
try {
await manager.createAgent({ provider: "codex", cwd: existingCwd }, firstId, {
workspaceId: "wks_short_id",
});
await manager.createAgent({ provider: "codex", cwd: existingCwd }, secondId, {
workspaceId: "wks_short_id",
});
await storage.upsert(
createStoredRecord({
id: internalId,
provider: "codex",
cwd: existingCwd,
workspaceId: "wks_short_id",
internal: true,
}),
);
const server = await createAgentMcpServer({
agentManager: manager,
agentStorage: storage,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
const statusTool = registeredTool(server, "get_agent_status");
const killTool = registeredTool(server, "kill_agent");
const activityTool = registeredTool(server, "get_agent_activity");
await expect(statusTool.handler({ agentId: "deadbee" })).rejects.toThrow(PaseoToolInputError);
await expect(statusTool.handler({ agentId: "deadbee" })).rejects.toThrow(
new RegExp(`ambiguous.*${firstId}.*${secondId}|ambiguous.*${secondId}.*${firstId}`, "i"),
);
await expect(killTool.handler({ agentId: "deadbee" })).rejects.toThrow(PaseoToolInputError);
expect(manager.getAgent(firstId)).not.toBeNull();
expect(manager.getAgent(secondId)).not.toBeNull();
await expect(statusTool.handler({ agentId: " " })).rejects.toThrow(PaseoToolInputError);
await expect(statusTool.handler({ agentId: internalId.slice(0, 7) })).rejects.toThrow(
PaseoToolInputError,
);
await expect(activityTool.handler({ agentId: "0000000" })).rejects.toThrow(
PaseoToolInputError,
);
} finally {
await removeAgentStateDir(manager, storage, workdir);
}
});
});
@@ -1,7 +1,6 @@
import { getForgeDefinitionOrNeutral } from "@getpaseo/protocol/forge-manifest";
import type {
AgentAttachment,
FirstAgentContext,
UploadedFileAttachment,
UploadedImage,
} from "@getpaseo/protocol/messages";
@@ -284,12 +283,8 @@ function padLineNumber(lineNumber: number | null): string {
return (lineNumber?.toString() ?? "-").padStart(2);
}
export type WorkspaceNamingContext = FirstAgentContext & { imageCount?: number };
export function buildAgentBranchNameSeed(
firstAgentContext:
| { prompt?: string; imageCount?: number; attachments?: readonly AgentAttachment[] }
| undefined,
firstAgentContext: { prompt?: string; attachments?: readonly AgentAttachment[] } | undefined,
): string | undefined {
if (!firstAgentContext) {
return undefined;
@@ -300,12 +295,6 @@ export function buildAgentBranchNameSeed(
parts.push(["<user-prompt>", prompt, "</user-prompt>"].join("\n"));
}
const renderedAttachments: string[] = [];
const { imageCount } = firstAgentContext;
if (imageCount) {
renderedAttachments.push(
imageCount === 1 ? "1 image attachment" : String(imageCount) + " image attachments",
);
}
for (const attachment of firstAgentContext.attachments ?? []) {
const rendered = renderPromptAttachmentAsText(attachment).trim();
if (rendered) {
@@ -2776,7 +2776,6 @@ export class ACPAgentSession implements AgentSession, ACPClient {
const option = findSelectConfigOption({
configOptions: this.configOptions,
category: "thought_level",
value: thinkingOptionId,
});
if (!option) {
throw new Error(`${this.provider} does not expose ACP thought-level selection`);
@@ -3697,7 +3696,6 @@ export class ACPAgentSession implements AgentSession, ACPClient {
const option = findSelectConfigOption({
configOptions: this.configOptions,
category: "thought_level",
value: requested,
});
if (!option || findSelectConfigChoice({ option, value: requested })) {
throw error;
@@ -4209,31 +4207,16 @@ export function findSelectConfigOption({
configOptions,
category,
id,
value,
}: {
configOptions: SessionConfigOption[] | null | undefined;
category: string;
id?: string;
value?: string;
}): SelectConfigOption | null {
const matching = configOptions?.filter(
const option = configOptions?.find(
(entry): entry is SelectConfigOption =>
entry.type === "select" && entry.category === category && (!id || entry.id === id),
);
if (category === "thought_level" && matching && matching.length > 1) {
// Some models offer a thinking toggle and a separate effort selector.
// Display the levels, but send stored toggle values to the selector that accepts them.
const candidates = value
? matching.filter((option) => findSelectConfigChoice({ option, value }))
: matching;
const levels = candidates.find((option) =>
flattenSelectOptions(option.options).some(
(choice) => choice.value !== "true" && choice.value !== "false",
),
);
return levels ?? candidates[0] ?? matching[0] ?? null;
}
return matching?.[0] ?? null;
return option ?? null;
}
function findSelectConfigOptionById({
@@ -4348,7 +4331,10 @@ function deriveCurrentConfigValue(
configOptions: SessionConfigOption[] | null | undefined,
category: string,
): string | null {
const option = findSelectConfigOption({ configOptions, category });
const option = configOptions?.find(
(entry): entry is Extract<SessionConfigOption, { type: "select" }> =>
entry.type === "select" && entry.category === category,
);
return option?.currentValue ?? null;
}
@@ -126,81 +126,73 @@ describe("Claude spawn override", () => {
expect(spawnOptions?.shell).toBe(false);
});
test.each(["2.1.326", undefined])(
"keeps MCP credentials out of argv for Claude %s",
async (version) => {
let capturedOptions: Options | undefined;
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return createQueryMock([]);
});
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => {
if (version === undefined) throw new Error("Unrecognized wrapper version");
return version;
test("keeps the Paseo MCP bearer token off the Claude Code command line", async () => {
let capturedOptions: Options | undefined;
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return createQueryMock([]);
});
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.326",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
await session.close();
if (!capturedOptions) {
throw new Error("Claude query options were not captured");
}
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
await session.close();
if (!capturedOptions) {
throw new Error("Claude query options were not captured");
}
// Feed Paseo's options to the real SDK and record the argv it would launch with.
let launchArgs: string[] | undefined;
let stdinText = "";
const stdin = new PassThrough();
stdin.on("data", (chunk: Buffer) => {
stdinText += chunk.toString("utf8");
});
const abortController = new AbortController();
const sdk = sdkQuery({
prompt: "hello",
options: {
...capturedOptions,
abortController,
spawnClaudeCodeProcess: (spawnOptions: ClaudeSpawnOptions): SpawnedProcess => {
launchArgs = spawnOptions.args;
const child = new EventEmitter() as EventEmitter & SpawnedProcess;
Object.assign(child, {
stdin,
stdout: new PassThrough(),
killed: false,
exitCode: null,
kill: () => true,
});
return child;
},
// Feed Paseo's options to the real SDK and record the argv it would launch with.
let launchArgs: string[] | undefined;
let stdinText = "";
const stdin = new PassThrough();
stdin.on("data", (chunk: Buffer) => {
stdinText += chunk.toString("utf8");
});
const abortController = new AbortController();
const sdk = sdkQuery({
prompt: "hello",
options: {
...capturedOptions,
abortController,
spawnClaudeCodeProcess: (spawnOptions: ClaudeSpawnOptions): SpawnedProcess => {
launchArgs = spawnOptions.args;
const child = new EventEmitter() as EventEmitter & SpawnedProcess;
Object.assign(child, {
stdin,
stdout: new PassThrough(),
killed: false,
exitCode: null,
kill: () => true,
});
return child;
},
});
// The fake process never answers, so the first message never arrives; only the launch matters.
void sdk.next().catch(() => undefined);
try {
await vi.waitFor(() => expect(launchArgs).toBeDefined());
expect(launchArgs?.includes("--mcp-config")).toBe(false);
expect(launchArgs?.some((arg) => arg.includes("secret-token"))).toBe(false);
await vi.waitFor(() => {
expect(stdinText).toContain("secret-token");
});
} finally {
abortController.abort();
}
},
);
},
});
// The fake process never answers, so the first message never arrives; only the launch matters.
void sdk.next().catch(() => undefined);
await vi.waitFor(() => {
expect(stdinText).toContain("secret-token");
});
abortController.abort();
expect(launchArgs).toBeDefined();
expect(launchArgs?.join(" ")).not.toContain("secret-token");
expect(launchArgs).not.toContain("--mcp-config");
});
test("starts Claude Code behind the session's launch wrap", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "claude-launch-wrap-"));
@@ -1097,7 +1097,8 @@ describe("ClaudeAgentSession features", () => {
test.each([
{ claudeCodeVersion: "2.1.326", expected: "initialize" },
{ claudeCodeVersion: "2.2.0", expected: "initialize" },
{ claudeCodeVersion: undefined, expected: "initialize" },
{ claudeCodeVersion: "2.1.325", expected: "argv" },
{ claudeCodeVersion: undefined, expected: "argv" },
])(
"delivers MCP servers by $expected for Claude Code $claudeCodeVersion",
async ({ claudeCodeVersion, expected }) => {
@@ -1157,8 +1158,8 @@ describe("ClaudeAgentSession features", () => {
{ env: { TEST_CLAUDE_WORKSPACE_VERSION: "2.1.325" } },
);
try {
await expect(session.setModel?.("claude-sonnet-4-6")).rejects.toThrow("Update Claude Code");
expect(launches).toHaveLength(0);
await session.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
} finally {
await session.close();
}
@@ -1183,8 +1184,8 @@ describe("ClaudeAgentSession features", () => {
} as const;
const existing = await client.createSession(config);
try {
await expect(existing.setModel?.("claude-sonnet-4-6")).rejects.toThrow("Update Claude Code");
expect(launches).toHaveLength(0);
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
version = "2.1.326";
const fresh = await client.createSession(config);
@@ -1194,6 +1195,7 @@ describe("ClaudeAgentSession features", () => {
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual([
"argv",
"initialize",
"initialize",
]);
@@ -1205,14 +1207,16 @@ describe("ClaudeAgentSession features", () => {
}
});
test("requires a supported Claude Code version only on launches with MCP servers", async () => {
test("warns about argv delivery only on launches with MCP servers", async () => {
const messages: string[] = [];
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
logger,
logger: pino({}, { write: (message: string) => messages.push(JSON.parse(message).msg) }),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.325",
});
const warnings = () => messages.filter((message) => message.includes("MCP server headers"));
const config = { provider: "claude", cwd: process.cwd() } as const;
const launch = async (sessionConfig: Parameters<typeof client.createSession>[0]) => {
const session = await client.createSession(sessionConfig);
@@ -1224,12 +1228,17 @@ describe("ClaudeAgentSession features", () => {
};
await launch(config);
await launch({ ...config, mcpServers: {} });
expect(warnings()).toEqual([]);
const withMcp = {
...config,
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
} as const;
await expect(launch(withMcp)).rejects.toThrow("Update Claude Code to 2.1.326 or later");
await launch(withMcp);
await launch(withMcp);
expect(warnings()).toEqual([
"Claude Code is too old or reports no version; MCP server headers go on its command line",
]);
});
test("passes extra Claude Code CLI arguments to the SDK", async () => {
@@ -50,7 +50,6 @@ import {
} from "./models.js";
import {
CLAUDE_DISABLED_THINKING_OPTION_ID,
CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION,
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
claudeManifestModelSupportsUltracode,
parseClaudeCodeVersion,
@@ -527,10 +526,14 @@ interface ClaudeAgentSessionOptions {
queryFactory?: ClaudeQueryFactory;
resolveBinary: () => Promise<string>;
independentUltracode: boolean;
checkMcpServersLaunchVersion: (launch: ClaudeLaunchVersionProbe) => Promise<void>;
resolveMcpServersDelivery: (
launch: ClaudeLaunchVersionProbe,
) => Promise<ClaudeMcpServersDelivery>;
rewindSdk?: ClaudeRewindSdk;
}
type ClaudeMcpServersDelivery = NonNullable<ClaudeOptions["mcpServersDelivery"]>;
type ClaudeThinkingEffort = "low" | "medium" | "high" | "xhigh" | "max";
type ClaudeThinkingOption =
| ClaudeThinkingEffort
@@ -1792,6 +1795,7 @@ export class ClaudeAgentClient implements AgentClient {
launch: ClaudeLaunchVersionProbe,
) => Promise<string | null>;
private version: Promise<string | undefined> | undefined;
private warnedMcpServersOnArgv = false;
private readonly lookupLatestRelease: LatestReleaseLookup;
private readonly rewindSdk: ClaudeRewindSdk;
private readonly scheduleImportDescriptors = createImportDescriptorScheduler(
@@ -1848,7 +1852,7 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
checkMcpServersLaunchVersion: (launch) => this.checkMcpServersLaunchVersion(launch),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
}
@@ -1880,7 +1884,7 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
checkMcpServersLaunchVersion: (launch) => this.checkMcpServersLaunchVersion(launch),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
try {
@@ -1987,14 +1991,23 @@ export class ClaudeAgentClient implements AgentClient {
return supportsIndependentClaudeUltracode(await this.version);
}
private async checkMcpServersLaunchVersion(launch: ClaudeLaunchVersionProbe): Promise<void> {
private async resolveMcpServersDelivery(
launch: ClaudeLaunchVersionProbe,
): Promise<ClaudeMcpServersDelivery> {
// The installed version can change between SDK launches in the same session.
const version = (await this.resolveLaunchVersion(launch).catch(() => null)) ?? undefined;
if (!supportsClaudeMcpServersViaInitialize(version)) {
throw new Error(
`Update Claude Code to ${CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION} or later to use MCP servers with Paseo (found ${version}).`,
);
if (supportsClaudeMcpServersViaInitialize(version)) {
return "initialize";
}
if (this.warnedMcpServersOnArgv) {
return "argv";
}
this.warnedMcpServersOnArgv = true;
this.logger.warn(
{ claudeCodeVersion: version ?? null },
"Claude Code is too old or reports no version; MCP server headers go on its command line",
);
return "argv";
}
async listImportableSessions(
@@ -2597,7 +2610,7 @@ class ClaudeAgentSession implements AgentSession {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly independentUltracode: boolean;
private readonly checkMcpServersLaunchVersion: ClaudeAgentSessionOptions["checkMcpServersLaunchVersion"];
private readonly resolveMcpServersDelivery: ClaudeAgentSessionOptions["resolveMcpServersDelivery"];
private query: Query | null = null;
private readonly runtimeSafety = new ClaudeRuntimeSafety();
private readonly backgroundStops = new Map<string, (outcome: string) => void>();
@@ -2739,7 +2752,7 @@ class ClaudeAgentSession implements AgentSession {
this.queryFactory = options.queryFactory;
this.resolveBinary = options.resolveBinary;
this.independentUltracode = options.independentUltracode;
this.checkMcpServersLaunchVersion = options.checkMcpServersLaunchVersion;
this.resolveMcpServersDelivery = options.resolveMcpServersDelivery;
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
this.contextUsage = new ClaudeContextUsageState(
getClaudeContextWindowMaxTokens(this.config.model),
@@ -4334,14 +4347,13 @@ class ClaudeAgentSession implements AgentSession {
if (this.config.mcpServers) {
base.mcpServers = this.normalizeMcpServers(this.config.mcpServers);
if (Object.keys(base.mcpServers).length > 0) {
await this.checkMcpServersLaunchVersion({
base.mcpServersDelivery = await this.resolveMcpServersDelivery({
executable: claudeBinary,
cwd: this.config.cwd,
env: sdkEnv,
runtimeSettings: this.runtimeSettings,
launchEnv: this.launchEnv,
});
base.mcpServersDelivery = "initialize";
}
}
@@ -376,12 +376,14 @@ export function supportsIndependentClaudeUltracode(version: string | undefined):
export const CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION = "2.1.326";
/**
* Allow stdin delivery when a wrapper reports no Claude Code version.
* Refuse only versions known to predate stdin support.
* Whether MCP servers can reach Claude Code over stdin instead of `--mcp-config`
* on its command line, where any local user can read their headers and env.
* An unknown version (a wrapper command) stays on the command line so the
* session still starts.
*/
export function supportsClaudeMcpServersViaInitialize(version: string | undefined): boolean {
return (
version === undefined ||
version !== undefined &&
compareVersions(version, CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION) >= 0
);
}
@@ -2537,6 +2537,135 @@ describe("Codex app-server provider", () => {
await session.close();
});
test("offers the persistence choices from a Codex MCP elicitation and returns the selected one", async () => {
const appServer = createFakeCodexAppServer();
const session = new CodexAppServerAgentSession(
createConfig({ cwd: "/workspace/project" }),
null,
createTestLogger(),
async () => appServer.child,
);
await session.connect();
const permissionRequested = waitForNextPermission(session);
appServer.requestMcpElicitation({
threadId: "thread-1",
turnId: "turn-1",
serverName: "computer-use",
message: "Allow Computer Use to use Safari?",
requestedSchema: { type: "object", properties: {} },
_meta: { connector_id: "computer-use", persist: ["session", "always", "forever"] },
});
const permission = await permissionRequested;
expect(permission.request.actions).toEqual([
{ id: "deny", label: "Deny", behavior: "deny", variant: "danger", intent: "dismiss" },
{
id: "mcp_persist_session",
label: "Allow for this session",
behavior: "allow",
variant: "secondary",
},
{ id: "mcp_persist_always", label: "Always allow", behavior: "allow", variant: "secondary" },
{ id: "allow_once", label: "Allow once", behavior: "allow", variant: "primary" },
]);
await session.respondToPermission(permission.request.id, {
behavior: "allow",
selectedActionId: "mcp_persist_always",
});
await expect(appServer.waitForMcpElicitationDecision()).resolves.toEqual({
action: "accept",
content: {},
_meta: { persist: "always" },
});
appServer.resolvesMcpElicitation();
appServer.assertNoErrors();
await session.close();
});
test("offers a single persistence choice from a Codex MCP elicitation", async () => {
const appServer = createFakeCodexAppServer();
const session = new CodexAppServerAgentSession(
createConfig({ cwd: "/workspace/project" }),
null,
createTestLogger(),
async () => appServer.child,
);
await session.connect();
const permissionRequested = waitForNextPermission(session);
appServer.requestMcpElicitation({
threadId: "thread-1",
turnId: "turn-1",
serverName: "computer-use",
message: "Allow Computer Use to use Safari?",
requestedSchema: { type: "object", properties: {} },
_meta: { connector_id: "computer-use", persist: "session" },
});
const permission = await permissionRequested;
expect(permission.request.actions).toEqual([
{ id: "deny", label: "Deny", behavior: "deny", variant: "danger", intent: "dismiss" },
{
id: "mcp_persist_session",
label: "Allow for this session",
behavior: "allow",
variant: "secondary",
},
{ id: "allow_once", label: "Allow once", behavior: "allow", variant: "primary" },
]);
await session.respondToPermission(permission.request.id, {
behavior: "allow",
selectedActionId: "mcp_persist_session",
});
await expect(appServer.waitForMcpElicitationDecision()).resolves.toEqual({
action: "accept",
content: {},
_meta: { persist: "session" },
});
appServer.resolvesMcpElicitation();
appServer.assertNoErrors();
await session.close();
});
test("replies without persistence when the user allows a Codex MCP elicitation once", async () => {
const appServer = createFakeCodexAppServer();
const session = new CodexAppServerAgentSession(
createConfig({ cwd: "/workspace/project" }),
null,
createTestLogger(),
async () => appServer.child,
);
await session.connect();
const permissionRequested = waitForNextPermission(session);
appServer.requestMcpElicitation({
threadId: "thread-1",
turnId: "turn-1",
serverName: "computer-use",
message: "Allow Computer Use to use Safari?",
requestedSchema: { type: "object", properties: {} },
_meta: { connector_id: "computer-use", persist: ["session", "always"] },
});
const permission = await permissionRequested;
await session.respondToPermission(permission.request.id, {
behavior: "allow",
selectedActionId: "allow_once",
});
await expect(appServer.waitForMcpElicitationDecision()).resolves.toEqual({
action: "accept",
content: {},
_meta: null,
});
appServer.resolvesMcpElicitation();
appServer.assertNoErrors();
await session.close();
});
test("initializes Codex app-server without making Paseo the request originator", async () => {
let initializeParams: unknown;
const appServer = createFakeCodexAppServer({
@@ -716,6 +716,63 @@ function decodeEscapedChar(next: string): string {
return next;
}
type CodexMcpElicitationPersistOption = "session" | "always";
const CODEX_MCP_PERSIST_ACTIONS: ReadonlyArray<{
option: CodexMcpElicitationPersistOption;
id: string;
label: string;
}> = [
{ option: "session", id: "mcp_persist_session", label: "Allow for this session" },
{ option: "always", id: "mcp_persist_always", label: "Always allow" },
];
// Codex offers persistence choices for an MCP approval through `_meta.persist`.
// Keep only the choices Paseo can label; ignore unknown values.
function readCodexMcpElicitationPersistOptions(meta: unknown): CodexMcpElicitationPersistOption[] {
const persist = toObjectRecord(meta)?.persist;
const offered = Array.isArray(persist) ? persist : [persist];
return CODEX_MCP_PERSIST_ACTIONS.filter((action) => offered.includes(action.option)).map(
(action) => action.option,
);
}
function buildCodexMcpElicitationActions(
options: CodexMcpElicitationPersistOption[],
): AgentPermissionAction[] {
return [
{ id: "deny", label: "Deny", behavior: "deny", variant: "danger", intent: "dismiss" },
...CODEX_MCP_PERSIST_ACTIONS.filter((action) => options.includes(action.option)).map(
(action): AgentPermissionAction => ({
id: action.id,
label: action.label,
behavior: "allow",
variant: "secondary",
}),
),
{ id: "allow_once", label: "Allow once", behavior: "allow", variant: "primary" },
];
}
function resolveCodexMcpElicitationMeta({
response,
options,
}: {
response: AgentPermissionResponse;
options: CodexMcpElicitationPersistOption[] | undefined;
}): { persist: CodexMcpElicitationPersistOption } | null {
if (response.behavior !== "allow" || !options) {
return null;
}
const action = CODEX_MCP_PERSIST_ACTIONS.find(
(candidate) => candidate.id === response.selectedActionId,
);
if (!action || !options.includes(action.option)) {
return null;
}
return { persist: action.option };
}
function resolvePermissionDecision(
response: AgentPermissionResponse,
): "accept" | "cancel" | "decline" {
@@ -3808,6 +3865,7 @@ interface CodexPendingPermissionHandler {
kind: "command" | "file" | "question" | "mcp_elicitation" | "plan";
questions?: CodexQuestionPrompt[];
plan?: { text: string; turnId: string | undefined };
mcpPersistOptions?: CodexMcpElicitationPersistOption[];
}
interface ConsumedRootCompaction {
@@ -5343,7 +5401,10 @@ export class CodexAppServerAgentSession implements AgentSession {
pending.resolve({
action: resolvePermissionDecision(response),
content: response.behavior === "allow" ? {} : null,
_meta: null,
_meta: resolveCodexMcpElicitationMeta({
response,
options: pending.mcpPersistOptions,
}),
});
return;
}
@@ -8185,6 +8246,7 @@ export class CodexAppServerAgentSession implements AgentSession {
requestedSchema: z.unknown().optional(),
url: z.string().optional(),
elicitationId: z.string().optional(),
_meta: z.unknown().optional(),
})
.parse(params);
if (parsed.mode === "url") {
@@ -8194,6 +8256,7 @@ export class CodexAppServerAgentSession implements AgentSession {
if (Array.isArray(requiredFields) && requiredFields.length > 0) {
return Promise.resolve({ action: "decline", content: null, _meta: null });
}
const persistOptions = readCodexMcpElicitationPersistOptions(parsed._meta);
const requestId = `permission-${randomUUID()}`;
const request: AgentPermissionRequest = {
id: requestId,
@@ -8213,12 +8276,19 @@ export class CodexAppServerAgentSession implements AgentSession {
serverName: parsed.serverName,
elicitationId: parsed.elicitationId ?? null,
},
...(persistOptions.length > 0
? { actions: buildCodexMcpElicitationActions(persistOptions) }
: {}),
};
this.pendingPermissions.set(requestId, request);
this.mcpElicitationPermissionIds.set(serverRequestId, requestId);
this.emitEvent({ type: "permission_requested", provider: CODEX_PROVIDER, request });
return new Promise((resolve) => {
this.pendingPermissionHandlers.set(requestId, { resolve, kind: "mcp_elicitation" });
this.pendingPermissionHandlers.set(requestId, {
resolve,
kind: "mcp_elicitation",
...(persistOptions.length > 0 ? { mcpPersistOptions: persistOptions } : {}),
});
});
}
}
@@ -141,6 +141,7 @@ export interface FakeCodexAppServer {
serverName: string;
message: string;
requestedSchema: Record<string, unknown>;
_meta?: Record<string, unknown> | null;
}): void;
waitForMcpElicitationDecision(): Promise<unknown>;
resolvesMcpElicitation(): void;
@@ -679,7 +680,7 @@ export function createFakeCodexAppServer(
params: {
...params,
mode: "openai/form",
_meta: null,
_meta: params._meta ?? null,
},
})}\n`,
);
@@ -72,33 +72,6 @@ describe("CursorACPAgentClient model discovery", () => {
protected override async closeProbe(): Promise<void> {}
}
test("offers effort levels and routes both effort and saved toggle values to Cursor", async () => {
await withFakeACPAgent(async (command, cwd) => {
const client = new CursorACPAgentClient({
logger: createTestLogger(),
providerId: "cursor",
command: [...command, "dual-select"],
});
const catalog = await client.fetchCatalog({ scope: "workspace", cwd, force: true });
expect(catalog.models[0]).toMatchObject({
thinkingOptions: [{ id: "low" }, { id: "high" }],
defaultThinkingOptionId: "low",
});
const session = await client.createSession({
provider: "acp",
cwd,
thinkingOptionId: "high",
});
try {
expect((await session.getRuntimeInfo()).thinkingOptionId).toBe("high");
await session.setThinkingOption!("false");
expect((await session.getRuntimeInfo()).thinkingOptionId).toBe("false");
} finally {
await session.close();
}
});
});
test("returns only ACP model ids because Cursor CLI ids cannot select ACP models", async () => {
const client = new TestCursorACPAgentClient({
sessionId: "session-1",
@@ -485,13 +458,6 @@ async function withFakeACPAgent(
const fakeACPAgentScript = `
const readline = require("node:readline");
const rl = readline.createInterface({ input: process.stdin });
const dualSelect = process.argv[2] === "dual-select";
const configOptions = [
{ id: "thinking", name: "Thinking", category: "thought_level", type: "select", currentValue: "true",
options: [{value: "false", name: "Off"}, {value: "true", name: "On"}] },
{ id: "effort", name: "Effort", category: "thought_level", type: "select", currentValue: "low",
options: [{value: "low", name: "Low"}, {value: "high", name: "High"}] },
];
function write(message) {
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
}
@@ -500,20 +466,7 @@ rl.on("line", (line) => {
if (message.method === "initialize") {
write({ id: message.id, result: { protocolVersion: message.params?.protocolVersion ?? 1, agentCapabilities: {} } });
} else if (message.method === "session/new") {
write({ id: message.id, result: { sessionId: "session-1", ...(dualSelect ? {
models: { currentModelId: "test-model", availableModels: [{ modelId: "test-model", name: "Test model" }] },
configOptions,
} : {}) } });
} else if (message.method === "cursor/list_available_models" && dualSelect) {
write({ id: message.id, result: { models: [{ value: "test-model", name: "Test model", configOptions }] } });
} else if (message.method === "session/set_config_option" && dualSelect) {
const option = configOptions.find(option => option.id === message.params.configId);
if (option?.options.some(choice => choice.value === message.params.value)) {
option.currentValue = message.params.value;
write({ id: message.id, result: {configOptions} });
} else {
write({ id: message.id, error: {code: -32602, message: "Invalid option value"} });
}
write({ id: message.id, result: { sessionId: "session-1" } });
} else if (message.id !== undefined) {
write({ id: message.id, result: {} });
}
@@ -30,7 +30,6 @@ async function createFakeAcpExecutable(options: {
logFile: string;
models: Array<{ value: string; name: string }>;
version?: string;
startupDelayMs?: number;
}): Promise<string> {
const filePath = path.join(options.dir, options.name);
const script = `#!/usr/bin/env node
@@ -38,10 +37,6 @@ const { appendFileSync } = require("node:fs");
const { createInterface } = require("node:readline");
const args = process.argv.slice(2);
const startupDelayMs = ${options.startupDelayMs ?? 0};
if (startupDelayMs > 0 && args.includes("acp")) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, startupDelayMs);
}
appendFileSync(
${JSON.stringify(options.logFile)},
JSON.stringify({ kind: "spawn", args, cwd: process.cwd() }) + "\\n",
@@ -142,7 +137,6 @@ describe("respectful ACP probing", () => {
dir,
name: "fake-acp",
logFile,
startupDelayMs: 1_400,
models: [{ value: "model-v1", name: "Model V1" }],
});
@@ -163,10 +157,7 @@ describe("respectful ACP probing", () => {
// The global read binds the probe first, as the daemon's warm-up does. When all four start
// together, launch resolution timing decides which read runs the probe and in which cwd.
const globalRead = manager1.getProvider({ provider: "fake-acp", wait: true });
// The Windows shim and Node startup can exceed Vitest's default one-second poll.
await expect
.poll(async () => acpSpawns(await readEvents(logFile)), { timeout: 10_000 })
.toHaveLength(1);
await expect.poll(async () => acpSpawns(await readEvents(logFile))).toHaveLength(1);
await Promise.all([
globalRead,
manager1.getProvider({ provider: "fake-acp", cwd: path.join(dir, "ws-1"), wait: true }),
@@ -1543,44 +1543,6 @@ 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,7 +13,6 @@ interface Prompt {
interface ProviderPrompt extends Prompt {
start: number;
clientMessageId?: string;
}
/**
@@ -42,15 +41,7 @@ export function planProviderHistory(input: {
if (owned.prompts.length > provider.length) {
return { kind: "diverged", reason: "The provider history is missing turns Paseo shows" };
}
// 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,
)
) {
if (provider.some((prompt, index) => index > 0 && prompt.id === provider[index - 1].id)) {
return { kind: "diverged", reason: "The provider history has two prompts with one id" };
}
if (owned.prompts.some((prompt, index) => !samePrompt(prompt, provider[index]))) {
@@ -89,26 +80,12 @@ function ownedPrompts(
function providerPrompts(entries: readonly TimelineEntry[]): ProviderPrompt[] {
const prompts: ProviderPrompt[] = [];
entries.forEach((entry, start) => {
const { item } = entry;
entries.forEach(({ item }, start) => {
if (item.type !== "user_message") return;
const prompt: ProviderPrompt = {
id: entry.providerMessageId ?? item.messageId,
text: item.text,
start,
clientMessageId: item.clientMessageId,
};
const prompt = { id: item.messageId, text: item.text, start };
const previous = prompts.at(-1);
// 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;
}
// Some providers replay a prompt twice. Reusing an ID for different text is a mismatch.
if (previous && prompt.id !== undefined && samePrompt(prompt, previous)) return;
prompts.push(prompt);
});
return prompts;
@@ -222,19 +222,6 @@ interface ProviderSummary {
error?: string;
}
const FULL_AGENT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
const AGENT_ID_INPUT_SCHEMA = z
.string()
.describe(
"Full agent UUID or a unique ID prefix (for example, shortId from list_agents or paseo ls).",
);
function formatAmbiguousAgentMatches(ids: readonly string[]): string {
const preview = ids.slice(0, 5).join(", ");
return ids.length > 5 ? `${preview}, …` : preview;
}
const WorkspaceAutomationSummarySchema = z.object({
parentWorkspaceId: z.string().optional(),
workspaceId: z.string(),
@@ -753,64 +740,9 @@ function createToolCatalog(
if (!options.finishSubscriptions) throw new Error("Finish subscriptions are not configured");
return options.finishSubscriptions();
}
async function resolveToolAgentId(requestedId: string): Promise<string> {
const trimmed = requestedId.trim();
if (!trimmed) {
throw new PaseoToolInputError("Agent ID cannot be empty");
}
const liveAgents = agentManager.listAgents();
const liveExact = liveAgents.find((agent) => !agent.internal && agent.id === trimmed);
if (liveExact) {
return liveExact.id;
}
const storedRecords = await agentStorage.listActive({ includeArchived: true });
const knownIds = new Set<string>();
for (const agent of liveAgents) {
if (!agent.internal) {
knownIds.add(agent.id);
}
}
for (const record of storedRecords) {
if (!record.internal) {
knownIds.add(record.id);
}
}
if (knownIds.has(trimmed)) {
return trimmed;
}
const normalized = trimmed.toLowerCase();
if (FULL_AGENT_UUID_PATTERN.test(trimmed)) {
for (const id of knownIds) {
if (id.toLowerCase() === normalized) {
return id;
}
}
return trimmed;
}
const prefixMatches = Array.from(knownIds).filter((id) =>
id.toLowerCase().startsWith(normalized),
);
if (prefixMatches.length === 1 && prefixMatches[0]) {
return prefixMatches[0];
}
if (prefixMatches.length > 1) {
throw new PaseoToolInputError(
`Agent ID prefix "${trimmed}" is ambiguous (${formatAmbiguousAgentMatches(prefixMatches)}). Pass a longer prefix or the full agent UUID.`,
);
}
return trimmed;
}
async function prepareRemoteNotification(
name: string,
destination: string | undefined,
resolvedAgentId: string,
input: Record<string, unknown>,
): Promise<FinishRegistration | undefined> {
if (
@@ -821,7 +753,7 @@ function createToolCatalog(
)
return undefined;
return finishSubscriptions().register(
{ childAgentId: resolvedAgentId, callerAgentId, serverId: destination },
{ childAgentId: input.agentId as string, callerAgentId, serverId: destination },
true,
);
}
@@ -931,24 +863,10 @@ function createToolCatalog(
};
handler = async ({ serverId, ...input }, context) => {
const destination = serverId ?? options.serverId;
let remoteNotification: FinishRegistration | undefined;
const operationContext =
name === "send_agent_prompt" && destination !== options.serverId
? {
...context,
beforeRemotePromptSend: async (resolvedAgentId: string) => {
remoteNotification = await prepareRemoteNotification(
name,
destination,
resolvedAgentId,
input,
);
},
}
: context;
const remoteNotification = await prepareRemoteNotification(name, destination, input);
try {
const response = await hostResolver.use(serverId, (host) =>
host[operation](input, operationContext),
host[operation](input, context),
);
if (response.isError) await remoteNotification?.reject();
else remoteNotification?.accept();
@@ -1483,14 +1401,14 @@ function createToolCatalog(
.object(legacyTopLevelCreateAgentInputSchema)
.strict();
const commonSendAgentPromptInputSchema = {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
prompt: z.string(),
sessionMode: z.string().optional().describe("Optional mode to set before running the prompt."),
};
const agentToAgentSendAgentPromptInputSchema = {
...commonSendAgentPromptInputSchema,
activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional().describe(
'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.',
'Leave this out unless the message cannot wait. Default "queue": the message waits until the agent\'s running turn ends. "steer": the message joins the running turn; a provider that cannot steer interrupts the turn instead. "interrupt": the running turn stops and a new turn starts with the message. A steer or interrupt carries the messages you queued before it, in order.',
),
notifyOnFinish: z
.boolean()
@@ -2199,7 +2117,7 @@ function createToolCatalog(
title: "Send agent prompt",
description:
scope === "agent"
? "Send a message to another agent. The response returns at once. Its guidance says whether the message 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 message to another agent. The response returns at once. Its guidance says whether the message waits for the running turn to end, joins it, or interrupts it, and how to deliver a waiting message now. Leave activeTurnBehavior out unless the message cannot wait. The recipient reads your messages in the order you sent them. A steer the recipient has not read is lost if its turn stops or is interrupted, along with the messages it carried. Completion reports include the target’s last response by default. Paseo supplies caller identity."
: "Send a prompt to an agent. A running turn is interrupted unless activeTurnBehavior is steer.",
inputSchema: sendAgentPromptInputSchema,
outputSchema: {
@@ -2213,13 +2131,12 @@ function createToolCatalog(
},
},
async ({
agentId: requestedAgentId,
agentId,
prompt,
sessionMode,
notifyOnFinish = Boolean(callerAgentId),
activeTurnBehavior,
}) => {
const agentId = await resolveToolAgentId(requestedAgentId);
if (callerAgentId && !agentManager.getAgent(agentId) && !(await agentStorage.get(agentId))) {
throw new PaseoToolInputError(`Agent ${agentId} not found`);
}
@@ -2284,7 +2201,7 @@ function createToolCatalog(
title: resolveCallerAgent()?.config.title ?? undefined,
},
sessionMode,
activeTurnBehavior: activeTurnBehavior ?? "steer",
activeTurnBehavior,
onDispatch: confirmDispatch,
})
.catch((error) => {
@@ -2369,15 +2286,14 @@ function createToolCatalog(
description:
"Return the latest snapshot for an agent, including lifecycle state, capabilities, and pending permissions.",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
},
outputSchema: {
status: AgentStatusEnum,
snapshot: AgentSnapshotPayloadSchema,
},
},
async ({ agentId: requestedAgentId }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId }) => {
const snapshot = agentManager.getAgent(agentId);
if (snapshot) {
const structuredSnapshot = await projectLiveAgent(snapshot);
@@ -2471,14 +2387,13 @@ function createToolCatalog(
title: "Cancel agent run",
description: "Abort the agent's current run but keep the agent alive for future tasks.",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
},
outputSchema: {
success: z.boolean(),
},
},
async ({ agentId: requestedAgentId }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId }) => {
const { cancelled } = await cancelAgentRunCommand(
{ agentManager, logger: childLogger },
agentId,
@@ -2497,14 +2412,13 @@ function createToolCatalog(
description:
"Archive an agent (soft-delete). The agent is interrupted if running and removed from the active list.",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
},
outputSchema: {
success: z.boolean(),
},
},
async ({ agentId: requestedAgentId }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId }) => {
await archiveAgentCommand(
{
agentManager,
@@ -2526,14 +2440,13 @@ function createToolCatalog(
title: "Kill agent",
description: "Terminate an agent session permanently.",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
},
outputSchema: {
success: z.boolean(),
},
},
async ({ agentId: requestedAgentId }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId }) => {
await closeAgentCommand({ agentManager }, agentId);
return {
content: [],
@@ -2548,7 +2461,7 @@ function createToolCatalog(
title: "Update agent",
description: "Update an agent name, labels, and/or runtime settings.",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
name: z.string().optional(),
labels: z.record(z.string(), z.string()).optional().describe("Labels to set on the agent"),
settings: UpdateAgentSettingsInputSchema.optional().describe(
@@ -2559,8 +2472,7 @@ function createToolCatalog(
success: z.boolean(),
},
},
async ({ agentId: requestedAgentId, name, labels, settings }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId, name, labels, settings }) => {
callerPolicy.assertMutableLabels(labels);
await callerPolicy.assertLineage({ agentId }, "self-or-descendant", "update");
await callerPolicy.assertWithinCeiling({
@@ -3619,7 +3531,7 @@ function createToolCatalog(
title: "Get agent activity",
description: "Return recent agent timeline entries as a curated summary.",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
limit: z
.number()
.optional()
@@ -3632,17 +3544,11 @@ function createToolCatalog(
content: z.string(),
},
},
async ({ agentId: requestedAgentId, limit }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId, limit }) => {
const source = await loadAgentHistory(agentId, {
agentManager,
agentStorage,
logger: childLogger,
}).catch((error) => {
if (error instanceof AgentNotFoundError) {
throw new PaseoToolInputError(error.message);
}
throw error;
});
const timeline = await agentManager.getTimeline(agentId);
const currentModeId =
@@ -3668,7 +3574,7 @@ function createToolCatalog(
description:
"Switch the agent's session mode (plan, bypassPermissions, read-only, auto, etc.).",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
modeId: z.string(),
},
outputSchema: {
@@ -3676,8 +3582,7 @@ function createToolCatalog(
newMode: z.string(),
},
},
async ({ agentId: requestedAgentId, modeId }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId, modeId }) => {
await callerPolicy.assertLineage({ agentId }, "self-or-descendant", "change the mode of");
await callerPolicy.assertWithinCeiling({ agentId, modeId });
const result = await setAgentModeCommand({ agentManager }, { agentId, modeId });
@@ -3735,7 +3640,7 @@ function createToolCatalog(
description:
"Approve or deny a pending permission request with an AgentManager-compatible response payload.",
inputSchema: {
agentId: AGENT_ID_INPUT_SCHEMA,
agentId: z.string(),
requestId: z.string(),
response: AgentPermissionResponseSchema,
},
@@ -3743,8 +3648,7 @@ function createToolCatalog(
success: z.boolean(),
},
},
async ({ agentId: requestedAgentId, requestId, response }) => {
const agentId = await resolveToolAgentId(requestedAgentId);
async ({ agentId, requestId, response }) => {
await callerPolicy.assertLineage({ agentId }, "descendant", "respond to permissions for");
await respondToAgentPermission({
agentManager,
@@ -2346,14 +2346,8 @@ test(
arguments: { serverId, agentId: child.id, prompt: "Never sent" },
});
expect(response.isError).toBe(true);
const records = async () => {
try {
return JSON.parse(await readFile(join(a.paseoHome, "finish-subscriptions.json"), "utf8"));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
throw error;
}
};
const records = () =>
readFile(join(a.paseoHome, "finish-subscriptions.json"), "utf8").then(JSON.parse);
expect(await records()).toEqual([]);
await origin.paseo.hosts.update(saved.registrationId, { enabled: true });
await online(origin.paseo);
@@ -2957,79 +2951,3 @@ test("dropping the physical A to B link tears down B's active routed tunnel sess
await expect.poll(() => target.closed(), { timeout: 10000 }).toBe(1);
await tunnel.closed;
});
test(
"remote agent tools accept unique 7-char shortId prefixes and deliver finish notifications (#8556)",
{ timeout: 30000 },
async () => {
const parentPrompts: string[] = [];
const a = await daemon({
agentClients: createTestAgentClients({
onStartTurn: (prompt, config) => {
if (config.title === "ShortId remote parent") parentPrompts.push(JSON.stringify(prompt));
},
}),
});
const b = await daemon();
const { paseo } = await api(a);
await paseo.hosts.add({ connection: `127.0.0.1:${b.port}`, label: "ShortId B" });
const serverId = (await online(paseo)).hosts[0]!.serverId!;
const workspace = await paseo.workspaces.create({
source: { kind: "directory", path: a.staticDir },
});
const parent = await workspace.agents.create({
config: { provider: "claude/claude-test" },
title: "ShortId remote parent",
});
const destination = await api(b);
const remoteWorkspace = await destination.paseo.workspaces.create({
source: { kind: "directory", path: b.staticDir },
});
const child = await remoteWorkspace.agents.create({
config: { provider: "claude/claude-test", modeId: "full-access" },
title: "ShortId remote child",
});
const shortId = child.id.slice(0, 7);
const mcp = new Client({ name: "remote-shortid-caller", version: "1" });
cleanup.push(() => mcp.close());
await mcp.connect(
new StreamableHTTPClientTransport(
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
),
);
const status = await mcp.callTool({
name: "get_agent_status",
arguments: { serverId, agentId: shortId },
});
expect(status.isError, JSON.stringify(status)).not.toBe(true);
expect(status.structuredContent).toMatchObject({
serverId,
snapshot: { id: child.id, title: "ShortId remote child" },
});
const prompted = await mcp.callTool({
name: "send_agent_prompt",
arguments: { serverId, agentId: shortId, prompt: "REMOTE_SHORTID_MARKER" },
});
expect(prompted.isError, JSON.stringify(prompted)).not.toBe(true);
await destination.client.waitForFinish(child.id, 10000);
const activity = await mcp.callTool({
name: "get_agent_activity",
arguments: { serverId, agentId: shortId },
});
expect(activity.isError, JSON.stringify(activity)).not.toBe(true);
expect(activity.structuredContent).toMatchObject({
serverId,
agentId: child.id,
content: expect.stringContaining("REMOTE_SHORTID_MARKER"),
});
await expect
.poll(() => parentPrompts.join("\n"), { timeout: 10000 })
.toContain(`Agent ${child.id}`);
expect(parentPrompts.join("\n")).toContain(`Server: ${serverId}`);
},
);
@@ -4,7 +4,7 @@ import { BUILTIN_PROVIDER_IDS } from "@getpaseo/protocol/provider-manifest";
import { WebSocket } from "ws";
import { SessionInboundMessageSchema, WSOutboundMessageSchema } from "@getpaseo/protocol/messages";
import { randomUUID } from "node:crypto";
import { mkdir, mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
import { mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test, vi } from "vitest";
@@ -12,7 +12,6 @@ import pino from "pino";
import photon from "@silvia-odwyer/photon-node";
import type { CreationSnapshot, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import type { AgentPromptInput, AgentTimelineItem } from "../agent/agent-sdk-types.js";
import { MockLoadTestAgentClient } from "../agent/providers/mock-load-test-agent.js";
import { readImageDimensions } from "../agent/image-dimensions.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
@@ -484,64 +483,6 @@ test.each(["create_agent_request", "agent.create.request"] as const)(
},
);
test.each(["workspace.create", "agent.create"] as const)(
"%s names a workspace from an inline screenshot",
async (route) => {
const root = await mkdtemp(join(tmpdir(), "creation-image-title-"));
const cwd = join(root, "project");
await mkdir(cwd);
try {
const daemon = await createCreationDaemon({
paseoHomeRoot: root,
staticDir: cwd,
cleanup: false,
isDev: true,
agentClients: { mock: new MockLoadTestAgentClient() },
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
await client.patchDaemonConfig({
metadataGeneration: { providers: [{ provider: "mock", model: "ten-second-stream" }] },
});
const agent = {
provider: "mock",
cwd,
model: "ten-second-stream",
initialPrompt: "",
images: [
{
mimeType: "image/png",
data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==",
},
],
};
const workspaceId =
route === "workspace.create"
? (await client.createWorkspace({ source: { kind: "directory", path: cwd }, agent }))
.workspace?.id
: (await client.createAgent(agent)).workspaceId;
expect(workspaceId).toBeTruthy();
await expect
.poll(
async () => {
const { entries } = await client.fetchWorkspaces();
return entries.find((workspace) => workspace.id === workspaceId)?.title;
},
{ timeout: 5000 },
)
.toBe("1 image attachment");
} finally {
await client.close();
await daemon.close();
}
} finally {
await rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
}
},
20_000,
);
test("creation clamps image attachments before provider dispatch and later turns stay usable", async () => {
const directory = await mkdtemp(join(tmpdir(), "creation-image-clamp-"));
const prompts: AgentPromptInput[] = [];
@@ -79,31 +79,20 @@ async function createWorkingRecipient(options: { olderClient?: boolean } = {}) {
}
}
test("an agent's message without a behavior steers a steering turn and can be overridden to queue", async () => {
test("an agent's message without a behavior waits for the running turn and says how to deliver it now", async () => {
const { client, runtime, recipient, sender, close } = await createWorkingRecipient();
try {
const steered = await client.sendAgentMessage(recipient.id, "Adjust approach", {
const receipt = await client.sendAgentMessage(recipient.id, "Report when done", {
sourceAgentId: sender.id,
});
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);
expect(receipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
expect(receipt.guidance).toContain("Queued, not delivered yet.");
expect(receipt.guidance).toContain('"steer" (it joins the running turn)');
expect(runtime.prompts).toHaveLength(1);
runtime.finishExecution();
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
expect(runtime.prompts[2]).toContain("Report when done");
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2);
expect(runtime.prompts[1]).toContain("Report when done");
} finally {
await close();
}
@@ -240,11 +229,6 @@ 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) {
@@ -293,12 +277,12 @@ async function createModeBoundaryRecipient(input: {
}
}
test("a direct broader-mode send while a plan-mode message is queued runs as two separate turns in their respective modes", async () => {
test("a direct broader-mode send behind a queued plan-mode message 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: ["Edit production files"],
heldPrompts: ["Inspect files read-only"],
});
try {
const queuedReceipt = await client.sendAgentMessage(agent.id, "Inspect files read-only", {
@@ -311,33 +295,34 @@ test("a direct broader-mode send while a plan-mode message is queued runs as two
activeTurnBehavior: "interrupt",
sessionMode: "bypassPermissions",
});
expect(directReceipt).toEqual({});
expect(await waitForTurn(1)).toEqual({
prompt: "Edit production files",
modeId: "bypassPermissions",
expect(directReceipt).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "interrupt",
});
expect((await client.listAgentQueue(agent.id)).items).toMatchObject([
{ text: "Inspect files read-only", state: "queued" },
]);
releaseTurn("Edit production files");
expect(await waitForTurn(2)).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",
});
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
} finally {
await close();
}
});
test("a direct bypassPermissions send while an implicit-mode message is queued on a restricted-mode agent runs as two separate turns", async () => {
test("a direct bypassPermissions send behind a queued implicit-mode message 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: ["Apply edits in bypass mode"],
heldPrompts: ["Queued in existing mode"],
});
try {
const queuedReceipt = await client.sendAgentMessage(agent.id, "Queued in existing mode", {
@@ -349,19 +334,20 @@ test("a direct bypassPermissions send while an implicit-mode message is queued o
activeTurnBehavior: "interrupt",
sessionMode: "bypassPermissions",
});
expect(directReceipt).toEqual({});
expect(await waitForTurn(1)).toEqual({
prompt: "Apply edits in bypass mode",
modeId: "bypassPermissions",
expect(directReceipt).toMatchObject({
deliveryStatus: "queued",
activeTurnBehavior: "interrupt",
});
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({
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",
});
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
@@ -369,136 +355,3 @@ test("a direct bypassPermissions send while an implicit-mode message is queued o
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 });
}
});
@@ -1,134 +0,0 @@
import { fork } from "node:child_process";
import { once } from "node:events";
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { WebSocket } from "ws";
import { expect, test } from "vitest";
import { withTimeout } from "../../utils/promise-timeout.js";
async function withDaemon(run: (listen: string, shutdown: () => Promise<void>) => Promise<void>) {
const artifacts = fileURLToPath(new URL("../../../../../.artifacts/", import.meta.url));
await mkdir(artifacts, { recursive: true });
const home = await mkdtemp(path.join(artifacts, "paseo-shutdown-"));
const worker = fork(fileURLToPath(new URL("../daemon-worker.ts", import.meta.url)), [], {
execArgv: ["--import", "tsx"],
silent: true,
env: {
...Object.fromEntries(
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
),
HOME: home,
USERPROFILE: home,
PASEO_HOME: home,
PASEO_LISTEN: "127.0.0.1:0",
PASEO_RELAY_ENABLED: "false",
PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0",
},
});
let output = "";
worker.stdout?.on("data", (chunk) => {
output += String(chunk);
});
worker.stderr?.on("data", (chunk) => {
output += String(chunk);
});
const closed = once(worker, "close");
const exited = once(worker, "exit");
const heartbeat = setInterval(() => {
if (worker.connected) worker.send({ type: "paseo:supervisor-heartbeat" }, () => {});
}, 500);
try {
const listen = await waitForReady();
await run(listen, shutdown);
} finally {
clearInterval(heartbeat);
if (worker.exitCode === null && worker.signalCode === null) worker.kill("SIGKILL");
await exited;
await rm(home, { recursive: true, force: true });
}
async function waitForReady() {
const ready = new Promise<string>((resolve, reject) => {
worker.on("message", (message) => {
if (message?.type === "paseo:ready" && typeof message.listen === "string") {
resolve(message.listen);
}
});
void exited.then(([code]) =>
reject(new Error(`Daemon exited during startup (${code}): ${output}`)),
);
});
return await withTimeout(ready, 30_000, "Daemon did not start");
}
async function shutdown() {
worker.send({ type: "paseo:graceful-shutdown", reason: "test_shutdown" });
const [code, signal] = await withTimeout(closed, 15_000, "Daemon did not exit");
expect({ code, signal, forced: output.includes("Forcing shutdown") }).toEqual({
code: 0,
signal: null,
forced: false,
});
}
}
async function withPeer(listen: string, run: (socket: WebSocket) => Promise<void>) {
const socket = new WebSocket(`ws://${listen}/ws`, { handshakeTimeout: 5_000 });
try {
await once(socket, "open");
await run(socket);
} finally {
socket.terminate();
}
}
async function startSession(socket: WebSocket) {
const status = once(socket, "message");
socket.send(
JSON.stringify({
type: "hello",
clientId: "shutdown-peer",
clientType: "browser",
protocolVersion: 1,
}),
);
const [data] = await withTimeout(status, 5_000, "Daemon did not send server info");
expect(JSON.parse(String(data))).toMatchObject({
type: "session",
message: { type: "status", payload: { status: "server_info" } },
});
}
test("the daemon exits cleanly and closes a responsive peer", async () => {
await withDaemon((listen, shutdown) =>
withPeer(listen, async (socket) => {
await startSession(socket);
const closed = once(socket, "close");
await shutdown();
const [code] = await withTimeout(closed, 5_000, "Peer did not close");
expect(code).toBe(1005);
}),
);
}, 60_000);
test("the daemon exits cleanly with a silent session", async () => {
await withDaemon((listen, shutdown) =>
withPeer(listen, async (socket) => {
await startSession(socket);
socket.pause();
await shutdown();
}),
);
}, 60_000);
test("the daemon exits cleanly with a silent peer awaiting hello", async () => {
await withDaemon((listen, shutdown) =>
withPeer(listen, async (socket) => {
socket.pause();
await shutdown();
}),
);
}, 60_000);
@@ -7745,89 +7745,4 @@ 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 });
}
});
});
+8 -29
View File
@@ -189,7 +189,6 @@ import {
buildAgentPrompt,
resolveAgentPrompt,
type ResolvedAgentPrompt,
type WorkspaceNamingContext,
} from "./agent/prompt-attachments.js";
import type { StructuredGenerationDaemonConfig } from "./agent/structured-generation-providers.js";
import {
@@ -789,13 +788,6 @@ function resolveWorkspaceLabelService(
return service ?? null;
}
function withInlineImageCount(
context: FirstAgentContext,
images: AgentCreateRequest["images"],
): WorkspaceNamingContext {
return images?.length ? { ...context, imageCount: images.length } : context;
}
function hasInitialCreationPrompt(
request?: Pick<AgentCreateRequest, "initialPrompt" | "images" | "attachments">,
): boolean {
@@ -5104,10 +5096,7 @@ export class Session {
{
...request,
firstAgentContext: agentInput
? {
prompt: agentInput.initialPrompt?.trim() || undefined,
attachments: agentInput.attachments,
}
? { prompt: agentInput.initialPrompt, attachments: agentInput.attachments }
: request.firstAgentContext,
},
id,
@@ -5307,10 +5296,10 @@ export class Session {
initialPrompt: trimmedPrompt,
});
const firstAgentContext = withInlineImageCount(
{ prompt: trimmedPrompt || undefined, attachments },
images,
);
const firstAgentContext: FirstAgentContext = {
...(trimmedPrompt ? { prompt: trimmedPrompt } : {}),
...(attachments && attachments.length > 0 ? { attachments } : {}),
};
const workspacePromptTitle = resolveFirstAgentPromptTitle(firstAgentContext);
const createdWorktree = await this.createAgentLifecycleDispatch.createWorktreeForRequest({
cwd: config.cwd,
@@ -5369,7 +5358,7 @@ export class Session {
await this.agentUpdates.forwardLiveAgent(
this.agentManager.getAgent(snapshot.id) ?? liveSnapshot,
);
if (resolvedIntent.createdDirectoryWorkspace && hasInitialCreationPrompt(msg)) {
if (resolvedIntent.createdDirectoryWorkspace && trimmedPrompt) {
this.workspaceAutoName.scheduleForDirectory(
{
workspaceId: resolvedIntent.intent.workspaceId,
@@ -8140,16 +8129,6 @@ export class Session {
const transformed = await this.pluginRuntime.before("workspace.create.before", input);
creationRequest = { ...transformed, type, requestId };
}
if (creationRequest.firstAgentContext && request.agent?.images?.length) {
// Attach derived naming data after the public workspace hook has validated its result.
creationRequest = {
...creationRequest,
firstAgentContext: withInlineImageCount(
creationRequest.firstAgentContext,
request.agent.images,
),
};
}
return creationRequest.source.kind === "directory"
? this.handleWorkspaceCreateLocal(creationRequest, workspaceId)
: this.handleWorkspaceCreateWorktree(creationRequest, workspaceId);
@@ -9939,7 +9918,7 @@ export class Session {
}
}
/** An agent sender's message steers by default (or queues if its provider cannot steer). */
/** An agent sender's message waits for the running turn to end unless it asks otherwise. */
private agentSenderBehavior(
requested: AgentActiveTurnBehavior | undefined,
): AgentMessageBehavior {
@@ -9948,7 +9927,7 @@ export class Session {
// meaning wait for the turn to end, so only their interrupt stays an interrupt.
if (!this.supports(CLIENT_CAPS.agentActiveTurnBehaviors))
return requested === "interrupt" ? "interrupt" : "queue";
return requested ?? "steer";
return requested ?? "queue";
}
private async handleAgentProviderSwitchRequest(
@@ -9733,26 +9733,6 @@ test("checkout.rename_branch.request renames the branch without a denormalized b
expect(persisted?.title).toBe("Refactor auth flow");
});
test("workspace creation includes inline image count in the naming context", async () => {
const generateWorkspaceName = vi.fn(async () => null);
const session = createSessionForWorkspaceTests({ generateWorkspaceName });
await session.handleMessage({
type: "workspace.create.request",
requestId: "create-with-screenshot",
source: { kind: "directory", path: REPO_CWD },
agent: {
config: { cwd: REPO_CWD, provider: "codex" },
initialPrompt: "",
images: [{ mimeType: "image/png", data: "c2NyZWVuc2hvdA==" }],
},
});
await expect
.poll(() => generateWorkspaceName.mock.calls)
.toContainEqual([
expect.objectContaining({ firstAgentContext: expect.objectContaining({ imageCount: 1 }) }),
]);
});
test("workspace.create.response persists the first prompt as the initial title", async () => {
const emitted: SessionOutboundMessage[] = [];
const workspaces = new Map<string, ReturnType<typeof createPersistedWorkspaceRecord>>();
+21 -27
View File
@@ -585,8 +585,6 @@ interface ClosePhysicalSocketParams {
const SLOW_REQUEST_THRESHOLD_MS = 500;
const EXTERNAL_SESSION_DISCONNECT_GRACE_MS = 90_000;
const HELLO_TIMEOUT_MS = 15_000;
// Leave time for the rest of daemon cleanup before the worker's shutdown deadline.
const SHUTDOWN_SOCKET_CLOSE_GRACE_MS = 1_000;
const WS_CLOSE_HELLO_TIMEOUT = 4001;
const WS_CLOSE_INVALID_HELLO = 4002;
const WS_CLOSE_INCOMPATIBLE_PROTOCOL = 4003;
@@ -958,7 +956,6 @@ export class VoiceAssistantWebSocketServer {
})
: await sendPreparedPromptToAgent({
...send,
replaceRunning: batch.replaceRunning,
sessionMode: batch.sessionMode,
runOptions: { clientMessageId: batch.messageIds[0] },
});
@@ -1473,12 +1470,31 @@ export class VoiceAssistantWebSocketServer {
cleanupPromises.push(Promise.resolve(connection.session.cleanup()));
for (const ws of connection.sockets) {
cleanupPromises.push(this.closeSocketForShutdown(ws));
cleanupPromises.push(
new Promise<void>((resolve) => {
// WebSocket.CLOSED = 3
if (ws.readyState === 3) {
resolve();
return;
}
ws.once("close", () => resolve());
ws.close();
}),
);
}
}
for (const ws of pendingSockets) {
cleanupPromises.push(this.closeSocketForShutdown(ws));
cleanupPromises.push(
new Promise<void>((resolve) => {
if (ws.readyState === 3) {
resolve();
return;
}
ws.once("close", () => resolve());
ws.close();
}),
);
}
await Promise.all(cleanupPromises);
@@ -1492,28 +1508,6 @@ export class VoiceAssistantWebSocketServer {
this.wss.close();
}
private async closeSocketForShutdown(ws: WebSocketLike): Promise<void> {
if (ws.readyState === 3) return; // WebSocket.CLOSED
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await new Promise<void>((resolve, reject) => {
timer = setTimeout(() => {
try {
ws.terminate?.();
resolve();
} catch (error) {
reject(error);
}
}, SHUTDOWN_SOCKET_CLOSE_GRACE_MS);
ws.once("close", () => resolve());
ws.close();
});
} finally {
clearTimeout(timer);
}
}
private sendToClient(ws: WebSocketLike, message: WSOutboundMessage): void {
this.sendMessageToSockets([ws], message, true);
}
@@ -152,26 +152,6 @@ describe("generateBranchNameFromFirstAgentContext", () => {
);
});
test.each([1, 2])(
"names a workspace started with %i inline images and no text",
async (imageCount) => {
const name = { title: "Review screenshot", branch: "review-screenshot" };
const structured = createStructuredGenerator(name);
const result = await generateBranchNameFromFirstAgentContext({
agentManager: {} as AgentManager,
cwd: "/tmp/repo",
firstAgentContext: { prompt: " ", imageCount },
logger: createLogger(),
deps: { generateStructuredAgentResponseWithFallback: structured.generateStructured },
});
expect(result).toEqual(name);
const description = imageCount === 1 ? "1 image attachment" : "2 image attachments";
expect(structured.calls[0]?.prompt).toContain(
["<attachments>", description, "</attachments>"].join("\n"),
);
},
);
test("uses attachment-only context", async () => {
const structured = createStructuredGenerator({
title: "Review flaky checkout",
@@ -1,4 +1,5 @@
import { z } from "zod";
import type { FirstAgentContext } from "@getpaseo/protocol/messages";
import type { AgentManager } from "./agent/agent-manager.js";
import {
StructuredAgentFallbackError,
@@ -9,10 +10,7 @@ import {
resolveStructuredGenerationProviders,
type StructuredGenerationDaemonConfig,
} from "./agent/structured-generation-providers.js";
import {
buildAgentBranchNameSeed,
type WorkspaceNamingContext,
} from "./agent/prompt-attachments.js";
import { buildAgentBranchNameSeed } from "./agent/prompt-attachments.js";
import { buildMetadataPrompt } from "../utils/build-metadata-prompt.js";
import type { WorkspaceGitService } from "./workspace-git-service.js";
import type { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
@@ -34,7 +32,7 @@ export interface GenerateBranchNameFromFirstAgentContextOptions {
model?: string | null;
thinkingOptionId?: string | null;
};
firstAgentContext: WorkspaceNamingContext | undefined;
firstAgentContext: FirstAgentContext | undefined;
logger: BranchNameGeneratorLogger;
deps?: {
generateStructuredAgentResponseWithFallback?: typeof generateStructuredAgentResponseWithFallback;
+8 -11
View File
@@ -185,7 +185,9 @@ test("filters by search and clears to all plugins", async ({ page }) => {
await submitSearch(page, "graphite");
await expect(page).toHaveURL(/\/plugins\/all\?q=graphite$/);
await expectSearchResultsAfterDirectory(page, "graphite");
await expect(
page.getByRole("heading", { level: 1, name: /^Results for “graphite”/ }),
).toBeVisible();
await expect(page.getByRole("main").getByRole("link", { name: /Graphite/ })).toBeVisible();
await expect(page.getByRole("link", { name: /Dracula/ })).toHaveCount(0);
@@ -215,7 +217,10 @@ test("submits the visible search term when its input event was missed", async ({
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/plugins\/all\?q=graphite&window=month$/);
await expectSearchResultsAfterDirectory(page, "graphite");
// The URL changes before the results route finishes loading its data and code.
await expect(
page.getByRole("heading", { level: 1, name: /^Results for “graphite”/ }),
).toBeVisible({ timeout: 10000 });
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
@@ -281,7 +286,7 @@ test("searches from the directory on submit, and Back returns to the directory",
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/plugins\/all\?q=gra$/);
await expectSearchResultsAfterDirectory(page, "gra");
await expect(page.getByRole("heading", { level: 1, name: /^Results for “gra”/ })).toBeVisible();
expect(await historyLength(page)).toBe(entries + 1);
await page.goBack();
@@ -496,14 +501,6 @@ async function expectDirectorySearch(page: Page, term: string, window: string) {
);
}
// The URL changes as soon as the directory submits, but the results route shows only after
// its registry server call returns. On a loaded CI runner that call has taken over 4 s.
async function expectSearchResultsAfterDirectory(page: Page, term: string) {
await expect(
page.getByRole("heading", { level: 1, name: new RegExp(`^Results for “${term}”`) }),
).toBeVisible({ timeout: 10000 });
}
async function typeSearch(page: Page, term: string) {
await page.getByRole("searchbox", { name: "Search plugins" }).pressSequentially(term);
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/website",
"version": "0.19.1",
"version": "0.19.0",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/builtin-plugins",
"version": "0.19.1",
"version": "0.19.0",
"private": true,
"type": "module",
"scripts": {
-2
View File
@@ -434,8 +434,6 @@ Every daemon-connected CLI command accepts global `--home` or `--host`, before o
Local-only `start`, `daemon run`, `config`, `onboard`, and `set-password` reject explicit `--host` and ignore `PASEO_HOST`. Endpoint operations retain TCP, Unix socket, Windows pipe, SSH, and pairing-offer transports. A host-side CLI controlling a container needs `--host` or `PASEO_HOST`.
Relay pairing connections allow up to 90 seconds for the initial handshake.
## Hub
```bash
-2
View File
@@ -413,8 +413,6 @@ PASEO_LISTEN=127.0.0.1:6799 PASEO_RELAY_ENABLED=false paseo daemon run --home ~/
仅限本地的 `start`、`daemon run`、`config`、`onboard` 和 `set-password` 会拒绝显式的 `--host`,并忽略 `PASEO_HOST`。端点操作保留 TCP、Unix 套接字、Windows 管道、SSH 和配对信息等传输方式。在宿主机上控制容器的 CLI 需要 `--host` 或 `PASEO_HOST`。
通过中继配对时,CLI 最多等待 90 秒建立连接。
## Hub {#hub}
```bash
+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 you want non-default handling when the agent is mid-turn:
Leave `activeTurnBehavior` out unless the message cannot wait. It decides what happens when the agent is mid-turn:
- `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.
- `queue` (default): the message waits for the turn to end.
- `steer`: the agent reads the message at its next step and keeps working. If its provider cannot steer, the turn is interrupted instead.
- `interrupt`: the turn stops, and a new turn starts with the message.
Read `guidance` in the response. If 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).
Read `guidance` in the response. If it says your message is waiting and the message cannot wait, such as a course correction, send a short follow-up with `steer` or `interrupt`. Do not resend the message: the follow-up carries it, and a resent message is read twice.
A steer the agent has not read is lost if its turn stops or is interrupted, along with the messages it carried. For a message that must arrive, use `queue` or `interrupt`.