From e114e13de2bcefcc88d0fea816f03aac71c8834a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Thu, 26 Nov 2026 01:09:39 +0700 Subject: [PATCH] Let plugins run agents, terminals, and worktree commands behind a sandbox launcher (#10786) Refs https://github.com/getpaseo/paseo/discussions/8484 Refs https://github.com/getpaseo/paseo/discussions/8017 Co-authored-by: CL Kao Co-authored-by: Josh Bendavid --- .github/workflows/ci.yml | 23 ++ docs/plugins.md | 62 +++- packages/plugin/package.json | 5 + packages/plugin/src/boundaries.test.ts | 35 +- .../src/server/acp-internal/connection.ts | 6 + packages/plugin/src/server/acp.test.ts | 191 ++++++++++- packages/plugin/src/server/acp.ts | 2 + packages/plugin/src/server/index.ts | 4 + packages/plugin/src/server/lifecycle.ts | 65 +++- .../process-internal/windows-command.test.ts | 163 ++++------ .../process-internal/windows-command.ts | 122 +++++-- packages/plugin/src/server/process.test.ts | 301 +++++++++++++++++- packages/plugin/src/server/process.ts | 120 +++++-- packages/plugin/src/server/provider.test.ts | 36 +++ packages/plugin/src/server/provider.ts | 11 + packages/plugin/src/skill-examples.test.ts | 6 +- packages/protocol/src/agent-types.ts | 2 + .../src/messages.providers-snapshot.test.ts | 6 + packages/protocol/src/messages.ts | 1 + packages/server/package.json | 2 +- .../src/server/agent/agent-manager.test.ts | 239 +++++++++++++- .../server/src/server/agent/agent-manager.ts | 13 +- .../src/server/agent/agent-sdk-types.ts | 7 + .../agent/create-agent-lifecycle-dispatch.ts | 3 + .../src/server/agent/mcp-client-connection.ts | 10 +- .../src/server/agent/plugin-provider.test.ts | 54 ++++ .../src/server/agent/plugin-provider.ts | 19 ++ .../src/server/agent/provider-options.ts | 12 + .../server/agent/provider-registry.test.ts | 26 ++ .../src/server/agent/provider-registry.ts | 29 +- .../agent/provider-snapshot-manager.test.ts | 17 + .../server/agent/provider-snapshot-manager.ts | 1 + .../server/agent/providers/acp-agent.test.ts | 61 ++++ .../src/server/agent/providers/acp-agent.ts | 9 + .../providers/claude/agent.spawn.test.ts | 48 +++ .../server/agent/providers/claude/agent.ts | 6 + .../server/agent/providers/claude/query.ts | 6 +- ...codex-app-server-agent.spawn-error.test.ts | 32 ++ .../providers/codex-app-server-agent.test.ts | 54 ++++ .../agent/providers/codex-app-server-agent.ts | 6 + .../agent/providers/jsonl-rpc-process.ts | 3 + .../src/server/agent/providers/omp/agent.ts | 21 +- .../agent/providers/omp/cli-runtime.test.ts | 51 +++ .../server/agent/providers/omp/cli-runtime.ts | 1 + .../server/agent/providers/omp/mcp-bridge.ts | 16 +- .../src/server/agent/providers/omp/runtime.ts | 5 + .../agent/providers/opencode-agent.test.ts | 87 +++++ .../server/agent/providers/opencode-agent.ts | 31 +- .../providers/opencode-bridge-adapter.test.ts | 38 +++ .../providers/opencode-server-manager.test.ts | 25 +- .../providers/opencode/server-manager.ts | 22 +- .../providers/opencode/test-server-manager.ts | 10 +- .../test-utils/test-opencode-harness.ts | 13 +- .../agent/providers/opencode/v2/agent.test.ts | 67 ++++ .../agent/providers/opencode/v2/agent.ts | 54 +++- .../opencode/v2/owned-runtime.test.ts | 73 +++++ .../agent/providers/opencode/v2/runtime.ts | 29 +- .../providers/opencode/v2/session-mcp.ts | 4 + .../src/server/agent/providers/pi/agent.ts | 35 +- .../agent/providers/pi/cli-runtime.test.ts | 58 ++++ .../server/agent/providers/pi/cli-runtime.ts | 1 + .../src/server/agent/providers/pi/runtime.ts | 5 + .../src/server/agent/tools/paseo-tools.ts | 3 + .../auto-archive-on-merge/archive-if-safe.ts | 3 + packages/server/src/server/bootstrap.ts | 24 +- .../server/src/server/command-run-hook.ts | 14 + .../terminal-workspace-sdk.e2e.test.ts | 17 +- .../plugins/agent-configuration.e2e.test.ts | 49 +++ .../server/plugins/agent-tools.e2e.test.ts | 39 +++ .../src/server/plugins/index.posix.test.ts | 30 ++ packages/server/src/server/plugins/index.ts | 1 + .../src/server/plugins/lifecycle.e2e.test.ts | 228 +++++++++++++ .../server/plugins/lifecycle/handlers.test.ts | 208 +++++++++++- .../src/server/plugins/lifecycle/index.ts | 93 +++++- .../server/plugins/plugin-process-protocol.ts | 2 + .../src/server/plugins/plugin-process.ts | 1 + .../src/server/plugins/runtime.posix.test.ts | 94 ++++++ .../src/server/plugins/session-attachments.ts | 11 +- packages/server/src/server/session.ts | 9 + .../src/server/workspace-archive-service.ts | 9 + .../server/src/server/worktree-bootstrap.ts | 5 + .../server/src/server/worktree-session.ts | 9 + .../src/terminal/default-terminal-shell.ts | 13 + .../src/terminal/terminal-create-hook.ts | 36 +++ .../server/src/terminal/terminal-manager.ts | 12 + .../terminal-session-controller.test.ts | 68 ++++ .../terminal/terminal-session-controller.ts | 62 ++-- packages/server/src/terminal/terminal.test.ts | 49 ++- packages/server/src/terminal/terminal.ts | 115 ++----- .../src/utils/git-repository-discovery.ts | 3 +- packages/server/src/utils/launch-wrap.ts | 20 ++ .../src/utils/spawn.launch-regression.test.ts | 15 +- .../src/utils/spawn.percent-escape.test.ts | 7 +- packages/server/src/utils/spawn.ts | 10 +- .../server/src/utils/worktree.posix.test.ts | 94 ++++++ packages/server/src/utils/worktree.test.ts | 39 +++ packages/server/src/utils/worktree.ts | 156 +++++++-- plugin-examples/lifecycle-logger/README.md | 5 +- .../lifecycle-logger/index.server.ts | 10 + .../server/provider.test.ts | 72 +++++ plugins/muse-provider/server/connection.ts | 3 + plugins/muse-provider/server/provider.ts | 3 + plugins/muse-provider/server/session.ts | 1 + plugins/muse-provider/test/provider.test.ts | 46 +++ public-docs/plugins/hooks.md | 170 +++++++--- public-docs/plugins/hooks.zh-CN.md | 170 +++++++--- public-docs/plugins/providers.md | 25 ++ public-docs/plugins/providers.zh-CN.md | 19 ++ scripts/ci-workflow.test.mjs | 12 +- 109 files changed, 4006 insertions(+), 542 deletions(-) create mode 100644 packages/server/src/server/command-run-hook.ts create mode 100644 packages/server/src/terminal/default-terminal-shell.ts create mode 100644 packages/server/src/terminal/terminal-create-hook.ts create mode 100644 packages/server/src/utils/launch-wrap.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 25fd1933f1..265f3e65c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -131,6 +131,29 @@ jobs: if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }} run: npm run typecheck:examples --workspace=@getpaseo/client + # Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks. + sdk-tests-windows: + name: sdk-tests (windows-latest) + needs: changes + if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }} + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: "npm" + + - name: Install dependencies + run: node scripts/npm-retry.mjs ci + + - name: Build plugin SDK + run: npm run build:relay && npm run build:client && npm run build:plugin + + - name: Run plugin SDK tests + run: npm run test --workspace=@getpaseo/plugin + # The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04. typecheck: name: typecheck diff --git a/docs/plugins.md b/docs/plugins.md index d2a4adecff..bef8f5e6af 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -462,13 +462,56 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md) owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved -configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on -every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary. +configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a +[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary. `packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to each live session. A plugin start, stop, or reload reruns only that plugin's callback per session, swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes the provider process, so a reload must not reopen agents the plugin does not change. +### Launch wrap + +An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that +session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell, +except Windows script launchers, which go through cmd.exe like any provider launcher +(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must +be an absolute path. +The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen +reuses the wrap it opened with. + +- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the + provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an + absent field means unsupported, which is also what a host without this feature reports. Core + providers declare it in the provider contract table in `provider-registry.ts`; every core provider + that starts a local harness declares it, and custom ACP providers and providers that extend a core + one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`; + `runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the + registration metadata, so it is in the snapshot before the provider first connects. +- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return + the same value. A different value fails the open. +- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It + throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not + declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host + that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the + spawn; nothing retries the bare command. + +Once an open selects a wrap, a supported provider runs that session's harness through it or fails +before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the +argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it +(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for +the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP +client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated +server instead; an explicitly configured external OpenCode server cannot be wrapped and the open +fails. The guarantee does not cover: + +1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap. +2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog + lookup during create when no model is set. +3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's + initialize probe included), catalog and session listing, version and update commands, usage + queries, and Codex native archive and unarchive. +4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped. + Worktree placement is resolved before Git source planning, so a hook can change the branch and base without undoing fetched refs. Restores use the recorded destination and bypass creation hooks. Workspace records decide ownership, including explicit non-ownership after recovery. Without a record, @@ -487,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi [worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and `plugin-examples/worktrunk`. +`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run. + +Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle +module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's +`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and +no previous-version adapter is needed. A default-shell terminal resolves the shell there through +`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty. +The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not +report command completion. A setup or teardown wrap goes in front of the +`buildStringCommandShellInvocation` argv. + Emit from the operation owner, not a client subscription. Provider history replay must not trigger live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt or answer a permission through its own daemon session. Awaiting it there deadlocks that command. @@ -586,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is no provider reload input. +Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can +run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See +[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both. + For an ACP command, register `runAcpProvider({ id, label, command })` from `@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind` (`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the diff --git a/packages/plugin/package.json b/packages/plugin/package.json index b8c7576c30..f6a7fd6c02 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -58,6 +58,11 @@ "types": "./dist/server/lifecycle.d.ts", "source": "./src/server/lifecycle.ts", "default": "./dist/server/lifecycle.js" + }, + "./internal/windows-command": { + "types": "./dist/server/process-internal/windows-command.d.ts", + "source": "./src/server/process-internal/windows-command.ts", + "default": "./dist/server/process-internal/windows-command.js" } }, "publishConfig": { diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index eff1af756a..9810590849 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -14,6 +14,7 @@ const entries = { "./server/usage": "server", "./server/acp": "server", "./internal/lifecycle": "server", + "./internal/windows-command": "server", "./client": "client", "./client/host": "client", "./client/ui": "client", @@ -392,7 +393,7 @@ describe("lifecycle hook SDK types", () => { it("infers payloads and replacement requests and requires async handlers and new names", () => { expect( typeErrors(` - import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server"; + import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server"; import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types"; export default function contribute(server: PluginServerContext) { server.addHook("worktree.create.before", async ({ request }) => { @@ -427,6 +428,38 @@ describe("lifecycle hook SDK types", () => { const { metadata, ...withoutMetadata } = request; return withoutMetadata; }); + server.addHook("agent.create.before", async ({ request }) => { + const workspace: string | null = request.workspaceId; + // @ts-expect-error The agent's workspace is read-only. + request.workspaceId = "wks_other"; + }); + // Results built before workspaceId existed still typecheck; the daemon keeps the id. + server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env })); + server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env })); + server.addHook("terminal.create.before", async ({ request }) => { + const source: "client" | "agent" | "script" | "worktree" = request.source; + const input: string | null = request.input; + const program: string | null = request.command; + // @ts-expect-error The terminal's workspace is read-only. + request.workspaceId = "wks_other"; + // @ts-expect-error The terminal's program is read-only; return a wrap instead. + request.command = "/usr/bin/other"; + const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId]; + return { ...request, env: { A: "1" }, wrap }; + }); + server.addHook("command.run.before", async ({ request }) => { + const workspace: string | null = request.workspaceId; + const purpose: "setup" | "teardown" = request.purpose; + // @ts-expect-error A command's purpose is read-only. + request.purpose = "setup"; + // @ts-expect-error The configured command is read-only; return a wrap instead. + request.command = "wrapper " + request.command; + return { ...request, wrap: ["/usr/bin/sandbox"] }; + }); + server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"], + })); server.addHook("agent.turn.after", async (event, { paseo, signal }) => { const { agent, outcome } = event; const kind: "completed" | "failed" | "canceled" = outcome.kind; diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index bc7c73cd83..39d52102b5 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -86,6 +86,8 @@ export async function createAcpProviderConnection( emit: () => undefined, }); const supportedCapabilities: ProviderCapability[] = [...ADAPTER_CAPABILITIES]; + // A connector stream has no process of its own to wrap. + if (options.command) supportedCapabilities.push("session.launch_wrap"); if (probe.agentCapabilities.promptCapabilities?.image) { supportedCapabilities.push("prompt.image"); } @@ -333,6 +335,7 @@ async function openSession( boundarySessionId: input.sessionId, cwd: input.config.cwd, env: input.config.env, + wrap: input.config.wrap, emit: state.emit, onRetired: () => retireSession(state, input.sessionId), }); @@ -375,6 +378,7 @@ interface StartRuntimeOptions { boundarySessionId: string; cwd?: string; env: Readonly>; + wrap?: readonly [string, ...string[]]; emit(event: ProviderEvent): void; onRetired?: () => void; } @@ -498,6 +502,7 @@ class AcpRuntime { env: process.env, }; child = spawnProcess(launch.command, launch.args, { + wrap: options.wrap, cwd: options.cwd, env: { ...launch.env, ...options.env }, stdio: "pipe", @@ -511,6 +516,7 @@ class AcpRuntime { >[1]; stream = ndJsonStream(output, input); } else { + if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap"); const owned = ownConnectorStream(await options.options.connector()); stream = owned.stream; closeConnector = owned.close; diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index 752870c0fd..d9c59718cc 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -1,3 +1,5 @@ +import type { ChildProcess } from "node:child_process"; +import diagnosticsChannel from "node:diagnostics_channel"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -6166,7 +6168,6 @@ describe("deferTurnOnRunningTools", () => { ); const childPid = Number((await readFile(pidFile, "utf8")).trim()); - const startedAt = Date.now(); await Promise.all([ connection.send({ type: "session.interrupt", @@ -6188,8 +6189,8 @@ describe("deferTurnOnRunningTools", () => { (event) => event.type === "request.completed" && event.requestId === "int-2", ); - // Both interrupts waited for the 250ms SIGTERM exit, and process is now dead. - expect(Date.now() - startedAt).toBeGreaterThanOrEqual(200); + // Both interrupts waited for the process to exit. On POSIX it lives 250ms past SIGTERM, so an + // interrupt that returned early would find it alive; Windows ends it at once. expect(() => process.kill(childPid, 0)).toThrow(); // Canceled turn and session.closed were each emitted exactly once. @@ -7125,3 +7126,187 @@ describe("ACP tool call rows", () => { } }); }); + +describe("runAcpProvider launch wrap", () => { + async function wrapFixture(): Promise<{ + agent: string; + launchLog: string; + /** The wrap that runs the recording launcher as Node, tagged so the agent can tell. */ + wrap: (tag: string) => [string, ...string[]]; + launches: () => Promise>; + agentStarts: () => Promise; + }> { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-")); + temporaryDirectories.push(directory); + const launchLog = path.join(directory, "launches.jsonl"); + const agentLog = path.join(directory, "agent.log"); + const launcher = path.join(directory, "launcher.cjs"); + // Consumes two arguments of its own (log path, tag), records what it saw, then runs the rest. + await writeFile( + launcher, + `const { appendFileSync } = require("node:fs"); +const { spawn } = require("node:child_process"); +const [log, tag, command, ...args] = process.argv.slice(2); +appendFileSync(log, JSON.stringify({ argv: process.argv.slice(2), token: process.env.SESSION_TOKEN ?? null }) + "\\n"); +const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED_BY: tag } }); +process.on("SIGTERM", () => child.kill("SIGTERM")); +child.on("exit", (code) => process.exit(code ?? 1)); +`, + "utf8", + ); + const agent = path.join(directory, "agent.cjs"); + await writeFile( + agent, + `const { appendFileSync } = require("node:fs"); +const record = (event) => appendFileSync(${JSON.stringify(agentLog)}, event + ":" + (process.env.WRAPPED_BY ?? "bare") + "\\n"); +const readline = require("node:readline"); +const lines = readline.createInterface({ input: process.stdin }); +const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n"); +lines.on("line", (line) => { + const message = JSON.parse(line); + if (message.method === "initialize") { record("init"); send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } }); } + else if (message.method === "session/new") { record("new"); send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-" + Math.random(), modes: null, configOptions: [] } }); } +});`, + "utf8", + ); + const readLines = async (file: string) => + (await readFile(file, "utf8").catch(() => "")).split("\n").filter(Boolean); + return { + agent, + launchLog, + wrap: (tag) => [process.execPath, launcher, launchLog, tag], + launches: async () => (await readLines(launchLog)).map((line) => JSON.parse(line)), + agentStarts: async () => await readLines(agentLog), + }; + } + + function wrappedOpen( + sessionId: string, + wrap: readonly [string, ...string[]] | undefined, + ): Extract { + const input = openInput(); + return { + ...input, + requestId: `open-${sessionId}`, + sessionId, + config: { ...input.config, env: { SESSION_TOKEN: sessionId }, ...(wrap ? { wrap } : {}) }, + }; + } + + async function connectWrapped(command: readonly [string, ...string[]]) { + const registration = runAcpProvider({ id: "wrap-acp", label: "Wrap ACP", command }); + expect(registration.launchWrap).toBe(true); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "session.launch_wrap"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + return { connection, events }; + } + + it("spawns the session as [...wrap, command, ...args] with the session env", async () => { + const fixture = await wrapFixture(); + const { launchLog } = fixture; + const { connection, events } = await connectWrapped([process.execPath, fixture.agent]); + expect(connection.capabilities).toContain("session.launch_wrap"); + try { + await connection.send(wrappedOpen("one", fixture.wrap("sandbox"))); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect(await fixture.launches()).toEqual([ + { argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "one" }, + ]); + expect(await fixture.agentStarts()).toEqual(["init:bare", "init:sandbox", "new:sandbox"]); + } finally { + await connection.close(); + } + }); + + it("passes wrap and command arguments that contain spaces as single argv elements", async () => { + const fixture = await wrapFixture(); + const { launchLog } = fixture; + const { connection, events } = await connectWrapped([ + process.execPath, + fixture.agent, + "--profile name with spaces", + ]); + try { + await connection.send(wrappedOpen("one", fixture.wrap("tag with spaces"))); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect((await fixture.launches())[0]?.argv).toEqual([ + launchLog, + "tag with spaces", + process.execPath, + fixture.agent, + "--profile name with spaces", + ]); + } finally { + await connection.close(); + } + }); + + it("wraps only the session that selected a wrap on a shared connection", async () => { + const fixture = await wrapFixture(); + const { launchLog } = fixture; + const { connection, events } = await connectWrapped([process.execPath, fixture.agent]); + try { + await connection.send(wrappedOpen("wrapped", fixture.wrap("sandbox"))); + await connection.send(wrappedOpen("bare", undefined)); + await waitForEvent( + events, + (event) => event.type === "session.ready" && event.sessionId === "wrapped", + ); + await waitForEvent( + events, + (event) => event.type === "session.ready" && event.sessionId === "bare", + ); + expect(await fixture.launches()).toEqual([ + { argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "wrapped" }, + ]); + expect( + (await fixture.agentStarts()).filter((line) => line.startsWith("new:")).sort(), + ).toEqual(["new:bare", "new:sandbox"]); + } finally { + await connection.close(); + } + }); + + it("fails the open when the launcher is missing and never starts the bare command", async () => { + const fixture = await wrapFixture(); + const missing = path.join(path.dirname(fixture.agent), "missing-launcher"); + const { connection, events } = await connectWrapped([process.execPath, fixture.agent]); + // Node publishes every spawn attempt, a failed one included, before it fills in the fields. + const spawned: ChildProcess[] = []; + const onSpawn = (message: unknown) => + spawned.push((message as { process: ChildProcess }).process); + diagnosticsChannel.subscribe("child_process", onSpawn); + try { + await connection.send(wrappedOpen("one", [missing, "--profile", "a b"])); + expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({ + requestId: "open-one", + error: { message: expect.stringMatching(/ENOENT/u) }, + }); + expect(spawned.map((child) => child.spawnargs)).toEqual([ + [missing, "--profile", "a b", process.execPath, fixture.agent], + ]); + // The only start of the agent is the connection's capability probe, before the open. + expect(await fixture.agentStarts()).toEqual(["init:bare"]); + expect(events.some((event) => event.type === "session.opened")).toBe(false); + } finally { + diagnosticsChannel.unsubscribe("child_process", onSpawn); + await connection.close(); + } + }); + + it("does not offer launch wrap through a connector", async () => { + const { connector } = connectorHarness(); + const registration = runAcpProvider({ id: "connector-acp", label: "Connector", connector }); + expect(registration).not.toHaveProperty("launchWrap"); + const connection = await registration.connect({ + versions: [1], + capabilities: ["prompt.message", "session.launch_wrap"], + }); + expect(connection.capabilities).not.toContain("session.launch_wrap"); + await connection.close(); + }); +}); diff --git a/packages/plugin/src/server/acp.ts b/packages/plugin/src/server/acp.ts index 65631c5e10..b9a5e44bc6 100644 --- a/packages/plugin/src/server/acp.ts +++ b/packages/plugin/src/server/acp.ts @@ -181,6 +181,8 @@ export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistra description: options.description, icon: options.icon, command: options.command, + // Each command-based session spawns its own process, so it can run behind that session's wrap. + ...(hasCommand ? { launchWrap: true } : {}), connect(request) { return createAcpProviderConnection(options, request); }, diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index fe41fac10c..50ff559783 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -23,6 +23,9 @@ export type { PluginHookWorkspace, PluginHookWorktree, PluginWorktreeCreateRequest, + PluginLaunchWrap, + PluginTerminalCreateRequest, + PluginCommandRunRequest, PluginHookAgent, PluginSessionOpenRequest, PluginTurnOutcome, @@ -32,6 +35,7 @@ export type { } from "./lifecycle.js"; export { spawnProcess, execCommand, terminateProcess } from "./process.js"; +export type { SpawnProcessOptions } from "./process.js"; export { defineAgentTool } from "./agent-tools.js"; export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js"; diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index 133e718b12..585de1b2fb 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -68,6 +68,49 @@ export type PluginWorktreeCreateRequest = { } ); +/** + * A launcher Paseo starts a process behind: the process runs as `[...wrap, command, ...args]`. + * The executable is an absolute path on the daemon host. Each element is one argument; no shell + * parses them, except that Windows runs a `.cmd` or `.bat` executable through cmd.exe. A later + * hook may omit the wrap or return the same one; a different wrap fails the operation. + */ +export type PluginLaunchWrap = readonly [executable: string, ...args: string[]]; + +/** A terminal Paseo is about to create in a workspace. */ +export interface PluginTerminalCreateRequest { + readonly workspaceId: string; + readonly cwd: string; + /** + * `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a + * `paseo.json` worktree terminal. `client`: everything else (the app, CLI, SDK, plugins). + */ + readonly source: "client" | "agent" | "script" | "worktree"; + readonly name: string | null; + /** The program the terminal starts, or `null` for the user's default shell. */ + readonly command: string | null; + readonly args: readonly string[]; + /** What Paseo types into the shell once it starts: the command of a script or worktree terminal. */ + readonly input: string | null; + /** Environment overrides for the terminal; excludes the daemon's inherited environment. */ + env: Record; + /** Start the terminal as `[...wrap, command, ...args]`; with no `command`, the default shell. */ + wrap?: PluginLaunchWrap; +} + +/** A `paseo.json` worktree setup or teardown command Paseo is about to run. */ +export interface PluginCommandRunRequest { + /** Null when a worktree is archived by path and no workspace record remains. */ + readonly workspaceId: string | null; + readonly cwd: string; + readonly purpose: "setup" | "teardown"; + /** The command as written in `paseo.json`. Paseo runs it through a shell. */ + readonly command: string; + /** Environment overrides for the command; excludes the daemon's inherited environment. */ + env: Record; + /** Start the command's shell as `[...wrap, shell, ...shellArgs]`. */ + wrap?: PluginLaunchWrap; +} + export interface PluginHookAgent { id: string; workspaceId: string | null; @@ -98,6 +141,12 @@ export interface PluginSessionOpenRequest { tools: AgentToolDefinition[]; env: Record; mcpServers: NonNullable; + /** + * Start the provider's harness as `[...wrap, command, ...args]`. Only a provider whose snapshot + * entry has `launchWrap: true` applies it; any other provider fails the open. Not saved on the + * agent. + */ + wrap?: PluginLaunchWrap; } export type PluginTurnOutcome = @@ -138,18 +187,28 @@ export interface PluginHookRequests { env?: Record; /** Stored on the new agent. Always present in the payload; return it changed to change it. */ metadata?: Record; + /** The workspace the agent is created in, which `config.cwd` alone does not identify. */ + readonly workspaceId: string | null; }; "agent.open.before": PluginSessionOpenRequest; "workspace.create.before": Omit; + "terminal.create.before": PluginTerminalCreateRequest; + "command.run.before": PluginCommandRunRequest; } -/** What a hook may return. An omitted `metadata` stays as it was. */ -type PluginHookRequestResults = Omit & { +/** What a hook may return. An omitted `metadata` or `workspaceId` stays as it was. */ +type PluginHookRequestResults = Omit< + PluginHookRequests, + "agent.open.before" | "agent.create.before" +> & { // Read-only fields added after the first SDK stay optional in a result; omitted means unchanged. "agent.open.before": Omit & { readonly background?: boolean; metadata?: Readonly>; }; + "agent.create.before": Omit & { + readonly workspaceId?: string | null; + }; }; export type PluginHooks = { @@ -217,6 +276,8 @@ export const pluginHookRegistry = { "agent.turn.after": { waits: false }, "agent.permission.before": { waits: false }, "agent.permission.after": { waits: false }, + "terminal.create.before": { waits: true }, + "command.run.before": { waits: true }, } as const satisfies Record; // COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30 diff --git a/packages/plugin/src/server/process-internal/windows-command.test.ts b/packages/plugin/src/server/process-internal/windows-command.test.ts index 3eb5e2e63b..8a677ffdc6 100644 --- a/packages/plugin/src/server/process-internal/windows-command.test.ts +++ b/packages/plugin/src/server/process-internal/windows-command.test.ts @@ -1,117 +1,92 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; import { afterEach, describe, expect, test } from "vitest"; -import { quoteWindowsArgument, quoteWindowsCommand } from "./windows-command.js"; +import { findWindowsCommand, quoteWindowsCommand, windowsCommandLine } from "./windows-command.js"; + +const program = { commandScript: false } as const; +const script = { commandScript: true } as const; describe("quoteWindowsCommand", () => { - const originalPlatform = process.platform; - - function setPlatform(value: string) { - Object.defineProperty(process, "platform", { value, writable: true }); - } - - afterEach(() => { - setPlatform(originalPlatform); - }); - - test("quotes a Windows path with spaces", () => { - setPlatform("win32"); + test("quotes a path with spaces and keeps cmd.exe syntax in it as text", () => { expect(quoteWindowsCommand("C:\\Program Files\\Anthropic\\claude.exe")).toBe( '"C:\\Program Files\\Anthropic\\claude.exe"', ); - }); - - test("does not double-quote an already-quoted path", () => { - setPlatform("win32"); - expect(quoteWindowsCommand('"C:\\Program Files\\Anthropic\\claude.exe"')).toBe( - '"C:\\Program Files\\Anthropic\\claude.exe"', + expect(quoteWindowsCommand("C:\\Program Files (x86)\\Tool & Co\\run.cmd")).toBe( + '"C:\\Program Files (x86)\\Tool & Co\\run.cmd"', ); }); - test("returns the command unchanged when there are no spaces", () => { - setPlatform("win32"); + test("leaves a plain or already quoted path as given", () => { expect(quoteWindowsCommand("C:\\nvm4w\\nodejs\\codex")).toBe("C:\\nvm4w\\nodejs\\codex"); - }); - - test("escapes ampersands", () => { - setPlatform("win32"); - expect(quoteWindowsCommand("feature&bugfix")).toBe("feature^&bugfix"); - }); - - test("escapes pipes", () => { - setPlatform("win32"); - expect(quoteWindowsCommand("feature|bugfix")).toBe("feature^|bugfix"); - }); - - test("does not double percent signs", () => { - setPlatform("win32"); - // cmd.exe only collapses %% → % inside batch files; on the command line - // it stays literal, which corrupts git --format atoms etc. - expect(quoteWindowsCommand("100%")).toBe("100%"); - }); - - test("preserves git --format atoms verbatim", () => { - setPlatform("win32"); - expect(quoteWindowsCommand("--format=%(refname)%09%(committerdate:unix)")).toBe( - "--format=%^(refname^)%09%^(committerdate:unix^)", - ); - }); - - test("escapes carets", () => { - setPlatform("win32"); - expect(quoteWindowsCommand("feature^bugfix")).toBe("feature^^bugfix"); - }); - - test("escapes multiple metacharacters", () => { - setPlatform("win32"); - expect(quoteWindowsCommand("build&(test|deploy)!")).toBe( - "build^&^(test^|deploy^)^!^", - ); - }); - - test("quotes commands with spaces after escaping metacharacters", () => { - setPlatform("win32"); - expect(quoteWindowsCommand("C:\\Program Files\\My Tool&Stuff\\run 100%.cmd")).toBe( - '"C:\\Program Files\\My Tool^&Stuff\\run 100%.cmd"', - ); - }); - - test("returns the command unchanged on non-Windows platforms", () => { - setPlatform("darwin"); - expect(quoteWindowsCommand("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code"); + expect(quoteWindowsCommand('"C:\\Program Files\\x.exe"')).toBe('"C:\\Program Files\\x.exe"'); }); }); -describe("quoteWindowsArgument", () => { - const originalPlatform = process.platform; - - function setPlatform(value: string) { - Object.defineProperty(process, "platform", { value, writable: true }); - } - - afterEach(() => { - setPlatform(originalPlatform); - }); - - test("quotes a Windows argument with spaces", () => { - setPlatform("win32"); - expect(quoteWindowsArgument("C:\\Program Files\\Anthropic\\cli.js")).toBe( - '"C:\\Program Files\\Anthropic\\cli.js"', +describe("windowsCommandLine", () => { + test("passes an argument without a cmd.exe metacharacter as given", () => { + expect(windowsCommandLine("echo", ["hello", "--flag", "feature/x", "C:\\dir"], program)).toBe( + '"echo hello --flag feature/x C:\\dir"', ); }); - test("does not double-quote an already-quoted argument", () => { - setPlatform("win32"); - expect(quoteWindowsArgument('"C:\\Program Files\\Anthropic\\cli.js"')).toBe( - '"C:\\Program Files\\Anthropic\\cli.js"', + test("quotes and caret-escapes every other argument once, the qntm way", () => { + expect(windowsCommandLine("node", ["feature&bugfix", "work profile", ""], program)).toBe( + '"node ^"feature^&bugfix^" ^"work^ profile^" ^"^""', + ); + // A caret before each `%` keeps cmd.exe from reading a variable name, inside the quotes too. + expect(windowsCommandLine("node", ["%PATH%", "100% of %PATH%"], program)).toBe( + '"node ^"^%PATH^%^" ^"100^%^ of^ ^%PATH^%^""', + ); + // Backslashes before the closing quote double, as the program's argv parser expects. + expect(windowsCommandLine("node", ["C:\\path with space\\"], program)).toBe( + '"node ^"C:\\path^ with^ space\\\\^""', ); }); - test("returns the argument unchanged when there are no spaces", () => { - setPlatform("win32"); - expect(quoteWindowsArgument("--version")).toBe("--version"); + test("quotes =, comma and semicolon, where a batch script splits its arguments", () => { + expect(windowsCommandLine("run.cmd", ["--profile=restricted", "a,b;c"], script)).toBe( + '"run.cmd ^"--profile=restricted^" ^"a^,b^;c^""', + ); }); - test("returns the argument unchanged on non-Windows platforms", () => { - setPlatform("darwin"); - expect(quoteWindowsArgument("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code"); + test("escapes an argument with a quote twice for a batch script, which reads it again", () => { + expect(windowsCommandLine("node", ['say "hi"'], program)).toBe('"node ^"say^ \\^"hi\\^"^""'); + expect(windowsCommandLine("run.cmd", ['say "hi"', "a & b"], script)).toBe( + '"run.cmd ^^^"say^^^ \\^^^"hi\\^^^"^^^" ^"a^ ^&^ b^""', + ); + }); + + test("quotes the command path at the start of the line", () => { + expect(windowsCommandLine("C:\\Program Files (x86)\\run.cmd", ["acp"], script)).toBe( + '""C:\\Program Files (x86)\\run.cmd" acp"', + ); + }); + + test("refuses a line break, which ends a cmd.exe command whatever the quoting", () => { + for (const argument of ["line one\nline two", "line one\r\n& calc"]) { + expect(() => windowsCommandLine("run.cmd", ["--", argument], script)).toThrow( + "cmd.exe cannot pass an argument with a line break to run.cmd", + ); + } + }); +}); + +describe("findWindowsCommand", () => { + const roots: string[] = []; + afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); + }); + + test("finds a bare name on PATH with each PATHEXT extension, whatever the env key case", async () => { + const empty = await mkdtemp(path.join(os.tmpdir(), "windows-command-empty-")); + const tools = await mkdtemp(path.join(os.tmpdir(), "windows-command-tools-")); + roots.push(empty, tools); + await writeFile(path.join(tools, "agent.CMD"), ""); + const env = { Path: `${empty};${tools}`, PathExt: ".EXE;.CMD" }; + expect(findWindowsCommand("agent", env)).toBe(path.join(tools, "agent.CMD")); + expect(findWindowsCommand("echo", env)).toBeUndefined(); + expect(findWindowsCommand("agent.cmd", env)).toBeUndefined(); + expect(findWindowsCommand(path.join(tools, "agent"), env)).toBeUndefined(); }); }); diff --git a/packages/plugin/src/server/process-internal/windows-command.ts b/packages/plugin/src/server/process-internal/windows-command.ts index 44b9362ad8..71658df6b9 100644 --- a/packages/plugin/src/server/process-internal/windows-command.ts +++ b/packages/plugin/src/server/process-internal/windows-command.ts @@ -1,46 +1,100 @@ -import { extname } from "node:path"; +import { statSync } from "node:fs"; +import { extname, join } from "node:path"; -export function isWindowsCommandScript(executablePath: string): boolean { +/** + * How Paseo starts a program through cmd.exe on Windows: `cmd.exe /d /s /c ""`, with the line + * passed verbatim. The SDK process functions and the daemon's terminals share this one dialect. + */ + +export function isWindowsCommandScript( + executablePath: string, + platform: NodeJS.Platform = process.platform, +): boolean { const extension = extname(executablePath).toLowerCase(); - return process.platform === "win32" && (extension === ".cmd" || extension === ".bat"); -} - -function escapeWindowsCmdValue(value: string): string { - if (process.platform !== "win32") return value; - - const isQuoted = value.startsWith('"') && value.endsWith('"'); - const unquoted = isQuoted ? value.slice(1, -1) : value; - // Do NOT double `%` here. cmd.exe only collapses `%%` → `%` inside batch - // files; on the command line / `cmd /c "..."` `%%` stays literal, which - // breaks args like git's `--format=%(refname)` (git treats `%%` as the - // escape for a literal `%`, so the format atoms become literals). - const escaped = unquoted.replace(/([&|^<>()!])/g, "^$1"); - - if (isQuoted || /[\s"]/u.test(unquoted)) { - const quoted = escaped - .replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`) - .replace(/\\+$/u, (slashes) => `${slashes}${slashes}`); - return `"${quoted}"`; - } - - return escaped; + return platform === "win32" && (extension === ".cmd" || extension === ".bat"); } /** - * When spawning with `shell: true` on Windows, the command is passed to - * `cmd.exe /d /s /c "command args"`. The `/s` strips outer quotes, so a - * command path with spaces (e.g. `C:\Program Files\...`) is split at the - * space. Wrapping it in quotes produces the correct `"C:\Program Files\..." args`. + * Find a bare command name the way cmd.exe would on `PATH`, trying each `PATHEXT` extension. The + * current directory is not searched. Returns undefined for a name with a path or an extension, and + * for a name that is not on `PATH`, such as a cmd.exe builtin. + */ +export function findWindowsCommand(name: string, env: NodeJS.ProcessEnv): string | undefined { + if (name.includes("/") || name.includes("\\") || extname(name)) return undefined; + const extensions = (readEnv(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean); + for (const directory of (readEnv(env, "PATH") ?? "").split(";").filter(Boolean)) { + for (const extension of extensions) { + const candidate = join(directory, name + extension); + if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate; + } + } + return undefined; +} + +/** The cmd.exe that runs a command line: the child's `ComSpec`, else the daemon's. */ +export function windowsCommandShell(env: NodeJS.ProcessEnv): string { + return readEnv(env, "ComSpec") ?? readEnv(process.env, "ComSpec") ?? "cmd.exe"; +} + +// Windows environment names ignore case, and a copied env object keeps whatever case it had. +function readEnv(env: NodeJS.ProcessEnv, name: string): string | undefined { + const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase()); + return key === undefined ? undefined : env[key] || undefined; +} + +// The cmd.exe metacharacters, as cross-spawn's `lib/util/escape.js` lists them. +const CMD_METACHARACTERS = /([()\][%!^"`<>&|;, *?])/g; +// A batch script also splits its arguments at `=` and tab. +const NEEDS_ESCAPE = /[()\][%!^"`<>&|;, *?=\t]/u; + +/** + * Escape one argument for a `cmd.exe /c` line by the qntm algorithm (https://qntm.org/cmd), the + * one cross-spawn's `lib/util/escape.js` implements: quote it for the program's own argv parser, + * then put a `^` before every cmd.exe metacharacter, the added quotes included. cmd.exe then sees + * no quoted region, so a `%NAME%` never expands, and the program gets the argument unchanged. + * `twice` escapes again for a batch script that reads the argument a second time. + */ +function escapeCmdArgument(argument: string, twice: boolean): string { + const quoted = `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`; + const escaped = quoted.replace(CMD_METACHARACTERS, "^$1"); + return twice ? escaped.replace(CMD_METACHARACTERS, "^$1") : escaped; +} + +/** + * Quote the program path for the start of a cmd.exe line. Inside the quotes cmd.exe reads `&`, `(` + * and `)` as text, so a path such as `C:\Program Files (x86)\...` starts. */ export function quoteWindowsCommand(command: string): string { - return escapeWindowsCmdValue(command); + if (command.startsWith('"') && command.endsWith('"')) return command; + if (command === "" || /[\s()!^"<>&|%;,=]/u.test(command)) return `"${command}"`; + return command; } /** - * `spawn(..., { shell: true })` on Windows also passes argv through `cmd.exe`. - * Any argument containing spaces must be quoted or it will be split before the - * child process sees it. + * The quoted line for `cmd.exe /d /s /c ` that starts `command` with `args`. + * + * - An argument without a metacharacter needs no escape and stays as given, so cmd.exe builtins + * and batch scripts that read `%1` get it unchanged. + * - Any other argument is escaped once. A batch script that reads it as `%~1` gets it without the + * quotes, and one that forwards it with `%*` hands the program the quoted argument, where cmd.exe + * reads every metacharacter as text. + * - For a batch script (`commandScript`), an argument with a `"` is escaped twice. Its quotes + * would otherwise open and close regions when the script reads it again, and leave the + * arguments after it outside the quotes. + * + * cmd.exe ends a command at a line break whatever the quoting, so an argument with one throws. */ -export function quoteWindowsArgument(argument: string): string { - return escapeWindowsCmdValue(argument); +export function windowsCommandLine( + command: string, + args: readonly string[], + { commandScript }: { commandScript: boolean }, +): string { + const escaped = args.map((argument) => { + if (/[\r\n]/u.test(argument)) { + throw new Error(`cmd.exe cannot pass an argument with a line break to ${command}`); + } + if (argument !== "" && !NEEDS_ESCAPE.test(argument)) return argument; + return escapeCmdArgument(argument, commandScript && argument.includes('"')); + }); + return `"${[quoteWindowsCommand(command), ...escaped].join(" ")}"`; } diff --git a/packages/plugin/src/server/process.test.ts b/packages/plugin/src/server/process.test.ts index e9b3000da5..cee1eed9cc 100644 --- a/packages/plugin/src/server/process.test.ts +++ b/packages/plugin/src/server/process.test.ts @@ -3,6 +3,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, expect, test } from "vitest"; import { execCommand, spawnProcess } from "./index.js"; +import { resolveSpawnInvocation } from "./process.js"; const roots: string[] = []; afterEach(async () => { @@ -26,8 +27,8 @@ const argumentsToPreserve = [ "feature^bugfix", ]; -// A bare extensionless command selects the Windows shell; an absolute node.exe path would -// skip that path. The real child checks quoting through the public process capabilities. +// A real child checks quoting through the public process capabilities. On Windows the bare name +// resolves on PATH to node.exe, which starts directly. test("execCommand delivers shell arguments to the real child unchanged", async () => { const script = await writeArgumentReader(); const { stdout } = await execCommand("node", [script, ...argumentsToPreserve]); @@ -51,3 +52,299 @@ test("spawnProcess delivers shell arguments to the real child unchanged", async }); expect(JSON.parse(stdout)).toEqual(argumentsToPreserve); }); + +// A Windows environment with an empty PATH, so a bare name is never found on the test host. +const windowsEnv = { ComSpec: "C:\\Windows\\System32\\cmd.exe", PATH: "" }; + +function onWindows(command: string, args: string[], shell?: boolean | string) { + return resolveSpawnInvocation(command, args, shell, "win32", windowsEnv); +} + +// A launch wrap prepends a Windows script wrapper to the provider launch; spawnProcess starts it as +// one verbatim cmd.exe line. +test("a Windows script launch wrap starts as one verbatim cmd.exe line", () => { + const wrapped = [ + "C:\\Program Files\\Sandbox\\run.cmd", + "--profile", + "work profile", + "", + "C:\\tools\\agy.cmd", + "acp", + ]; + expect(onWindows(wrapped[0]!, wrapped.slice(1))).toEqual({ + command: "C:\\Windows\\System32\\cmd.exe", + args: [ + "/d", + "/s", + "/c", + '""C:\\Program Files\\Sandbox\\run.cmd" --profile ^"work^ profile^" ^"^" C:\\tools\\agy.cmd acp"', + ], + shell: false, + windowsVerbatimArguments: true, + }); + expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "linux")).toEqual({ + command: wrapped[0], + args: wrapped.slice(1), + shell: false, + }); +}); + +// cmd.exe ends a command at a line break, and the text after it would run as a second command. +test("a Windows cmd.exe launch refuses an argument with a line break before it starts", () => { + for (const argument of ["line one\nline two", "line one\r\n& calc"]) { + expect(() => onWindows("C:\\Sandbox\\run.cmd", ["--", argument])).toThrow( + "cmd.exe cannot pass an argument with a line break to C:\\Sandbox\\run.cmd", + ); + expect(() => onWindows("codex", [argument])).toThrow( + "cmd.exe cannot pass an argument with a line break to codex", + ); + } + expect(onWindows("C:\\tools\\node.exe", ["a\nb"]).args).toEqual(["a\nb"]); + expect(resolveSpawnInvocation("/usr/bin/sandbox", ["a\nb"], undefined, "linux").args).toEqual([ + "a\nb", + ]); +}); + +// Only cmd.exe reads cmd.exe quoting. A shell the caller names parses the line by its own rules. +test("a Windows launch quotes for cmd.exe only when cmd.exe parses the command line", () => { + // `shell: true` runs the child's ComSpec; a cmd.exe the caller names runs as named. + for (const [shell, cmd] of [ + [true, windowsEnv.ComSpec], + ["cmd.exe", "cmd.exe"], + ["D:\\Tools\\CMD.EXE", "D:\\Tools\\CMD.EXE"], + ] as const) { + expect(onWindows("echo", ["hello", "a & b"], shell)).toEqual({ + command: cmd, + args: ["/d", "/s", "/c", '"echo hello ^"a^ ^&^ b^""'], + shell: false, + windowsVerbatimArguments: true, + }); + } + for (const shell of ["bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", "pwsh"]) { + expect(onWindows("echo", ["'a & b'", "line\nbreak"], shell)).toEqual({ + command: "echo", + args: ["'a & b'", "line\nbreak"], + shell, + }); + } + // A program starts directly, and `shell: false` keeps a bare name that is not on PATH direct. + expect(onWindows("C:\\tools\\node.exe", ["a & b"])).toEqual({ + command: "C:\\tools\\node.exe", + args: ["a & b"], + shell: false, + }); + expect(onWindows("missing", ["a & b"], false)).toEqual({ + command: "missing", + args: ["a & b"], + shell: false, + }); +}); + +// The daemon runs git with `shell: false` on hot paths that must not block on synchronous IO, so +// an explicit `shell: false` starts a bare name directly and leaves the PATH search to Windows. +test("a Windows bare name searches PATH for a script only when the caller allows a shell", async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), "plugin-path-shim-")); + roots.push(directory); + await writeFile(path.join(directory, "tool.CMD"), ""); + const env = { ...windowsEnv, PATH: directory }; + expect(resolveSpawnInvocation("tool", ["a & b"], false, "win32", env)).toEqual({ + command: "tool", + args: ["a & b"], + shell: false, + }); + expect(resolveSpawnInvocation("tool", ["a & b"], undefined, "win32", env)).toEqual({ + command: windowsEnv.ComSpec, + args: ["/d", "/s", "/c", `"${path.join(directory, "tool.CMD")} ^"a^ ^&^ b^""`], + shell: false, + windowsVerbatimArguments: true, + }); +}); + +// Real Git Bash on Windows: the arguments reach Bash as given, without cmd.exe escapes. +test.runIf(process.platform === "win32")( + "execCommand passes arguments as given to a Windows shell other than cmd.exe", + async () => { + const bash = path.join( + process.env.ProgramFiles ?? "C:\\Program Files", + "Git", + "bin", + "bash.exe", + ); + const { stdout } = await execCommand("printf", ["'%s|'", "hello", "'a & b'"], { + shell: bash, + }); + expect(stdout).toBe("hello|a & b|"); + }, +); + +// A launch wrap starts its executable with the command and its arguments after the wrap's own. +// The caller's shell choice belongs to the unwrapped command, so a wrap ignores it. +test("spawnProcess starts a wrap's executable with the command after the wrap arguments", async () => { + const launcher = await writeArgumentReader(); + const child = spawnProcess("harness", ["--flag", ...argumentsToPreserve], { + wrap: [process.execPath, launcher, "--sandbox profile"], + shell: true, + stdio: "pipe", + }); + let stdout = ""; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + stdout += chunk; + }); + await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", (code) => { + if (code === 0) resolve(); + else reject(new Error(`Launcher exited with ${code}`)); + }); + }); + expect(JSON.parse(stdout)).toEqual([ + "--sandbox profile", + "harness", + "--flag", + ...argumentsToPreserve, + ]); +}); + +// Arguments that cmd.exe reads as syntax unless they are escaped for it. A `.cmd` launcher reads +// its arguments a second time when it forwards them with `%*`. +const commandScriptArguments = [ + ...argumentsToPreserve, + 'say "hi"', + '"quoted"', + "", + "a & b", + "(parenthesized) arg", + "100% done", + "%PATH%", + "!bang!", + "C:\\path with space\\", + 'mixed "a & b" quote', + "--profile=restricted", + "a,b;c", + // cmd.exe expands a set variable inside a quoted region, so this checks that none opens. + "value with %PATH% inside", + 'quote "then %PATH%" & more', +]; + +async function writeCommandScriptLauncher(): Promise { + const reader = await writeArgumentReader(); + const directory = await mkdtemp(path.join(os.tmpdir(), "plugin wrap (x86) & launcher ")); + roots.push(directory); + const launcher = path.join(directory, "sandbox run.cmd"); + await writeFile(launcher, `@"${process.execPath}" "${reader}" %*\r\n`); + return launcher; +} + +async function readStdout(child: ReturnType): Promise { + let stdout = ""; + child.stdout?.setEncoding("utf8"); + child.stdout?.on("data", (chunk: string) => { + stdout += chunk; + }); + await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", (code) => { + if (code === 0) resolve(); + else reject(new Error(`Child exited with ${code}`)); + }); + }); + return stdout; +} + +// Real cmd.exe: a `.cmd` launch wrap in a directory with spaces and cmd.exe syntax forwards the +// harness command and every argument to the program it starts, unchanged. +test.runIf(process.platform === "win32")( + "a .cmd launch wrap forwards the command and its arguments unchanged on Windows", + async () => { + const launcher = await writeCommandScriptLauncher(); + const child = spawnProcess("harness", commandScriptArguments, { + wrap: [launcher, "--sandbox profile", 'say "hi"', ""], + stdio: "pipe", + }); + expect(JSON.parse(await readStdout(child))).toEqual([ + "--sandbox profile", + 'say "hi"', + "", + "harness", + ...commandScriptArguments, + ]); + }, +); + +test.runIf(process.platform === "win32")( + "execCommand runs a .cmd script with its arguments unchanged on Windows", + async () => { + const launcher = await writeCommandScriptLauncher(); + const { stdout } = await execCommand(launcher, commandScriptArguments); + expect(JSON.parse(stdout)).toEqual(commandScriptArguments); + }, +); + +// Real cmd.exe: a script that reads `%~1` gets each argument as given, without escapes. +test.runIf(process.platform === "win32")( + "a .cmd script that reads its arguments one by one gets each one as given on Windows", + async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), "plugin script reader ")); + roots.push(directory); + const script = path.join(directory, "read.cmd"); + // `set /p` without input exits 1, so the script exits 0 on its own. + await writeFile( + script, + '@echo off\r\n { + const reader = await writeArgumentReader(); + const directory = await mkdtemp(path.join(os.tmpdir(), "plugin bare shim ")); + roots.push(directory); + await writeFile( + path.join(directory, "paseo-forward.cmd"), + `@"${process.execPath}" "${reader}" %*\r\n`, + ); + // Windows env names ignore case, so drop the inherited `Path` before setting the new one. + const inherited = Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path"); + const env = { + ...Object.fromEntries(inherited), + PATH: `${directory};${process.env.PATH ?? ""}`, + }; + const shim = await execCommand("paseo-forward", commandScriptArguments, { env }); + expect(JSON.parse(shim.stdout)).toEqual(commandScriptArguments); + const program = await execCommand("node", [reader, ...commandScriptArguments], { env }); + expect(JSON.parse(program.stdout)).toEqual(commandScriptArguments); + }, +); + +// Real cmd.exe: a caller that formats its own cmd.exe line asks Node to pass it verbatim. +test.runIf(process.platform === "win32")( + "spawnProcess passes a caller's verbatim cmd.exe line unchanged on Windows", + async () => { + const reader = await writeArgumentReader(); + const child = spawnProcess( + process.env.ComSpec ?? "cmd.exe", + ["/d", "/s", "/c", `""${process.execPath}" "${reader}" "a b" c"`], + { shell: false, windowsVerbatimArguments: true, stdio: "pipe" }, + ); + expect(JSON.parse(await readStdout(child))).toEqual(["a b", "c"]); + }, +); diff --git a/packages/plugin/src/server/process.ts b/packages/plugin/src/server/process.ts index b2ba70ac12..37a3775044 100644 --- a/packages/plugin/src/server/process.ts +++ b/packages/plugin/src/server/process.ts @@ -8,10 +8,12 @@ import { import { extname } from "node:path"; import { promisify } from "node:util"; import { + findWindowsCommand, isWindowsCommandScript, - quoteWindowsArgument, - quoteWindowsCommand, + windowsCommandLine, + windowsCommandShell, } from "./process-internal/windows-command.js"; +import type { PluginLaunchWrap } from "./lifecycle.js"; const execFileAsync = promisify(execFile); export interface ExecCommandOptions { env?: NodeJS.ProcessEnv; @@ -20,6 +22,10 @@ export interface ExecCommandOptions { killSignal?: NodeJS.Signals; timeout?: number; maxBuffer?: number; + /** + * `true` runs the command through cmd.exe on Windows, quoted for it. A shell named here other + * than cmd.exe gets the command and arguments as given, on every platform; quote for it. + */ shell?: boolean | string; signal?: AbortSignal; } @@ -27,47 +33,96 @@ interface ExecCommandResult { stdout: string; stderr: string; } -function hasPathSeparator(value: string): boolean { - return value.includes("/") || value.includes("\\"); + +export interface SpawnInvocation { + command: string; + args: string[]; + shell: boolean | string; + /** The args are one cmd.exe line that Node must pass as given. */ + windowsVerbatimArguments?: boolean; } -function shouldUseWindowsShell( +function namesCmd(shell: boolean | string | undefined): boolean { + return ( + shell === true || (typeof shell === "string" && /^(?:.*[\\/])?cmd(?:\.exe)?$/iu.test(shell)) + ); +} + +/** + * How `spawnProcess` and `execCommand` start `command` on `platform`. + * + * On Windows a bare name is first found on `PATH`, as cmd.exe would find it, unless the caller + * passes `shell: false`. A program then starts directly. A `.cmd` or `.bat` script, a name that is not on `PATH` (a cmd.exe builtin), or a + * `shell: true` launch runs as `cmd.exe /d /s /c "..."`, quoted by `windowsCommandLine`. A shell + * the caller names other than cmd.exe gets the command and arguments as given. + */ +export function resolveSpawnInvocation( command: string, - requestedShell?: boolean | string, -): boolean | string { - if (isWindowsCommandScript(command)) { - return true; + args: readonly string[], + requestedShell: boolean | string | undefined, + platform: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, +): SpawnInvocation { + if (platform !== "win32") return { command, args: [...args], shell: requestedShell ?? false }; + if (typeof requestedShell === "string" && !namesCmd(requestedShell)) { + return { command, args: [...args], shell: requestedShell }; } - if (requestedShell !== undefined) { - return requestedShell; + const bareName = !/[\\/]/u.test(command) && !extname(command); + // `shell: false` starts a bare name directly, and Windows searches PATH without blocking Node. + const found = bareName && requestedShell !== false ? findWindowsCommand(command, env) : undefined; + const target = found ?? command; + const commandScript = isWindowsCommandScript(target, platform); + // Only cmd.exe knows a builtin, so a bare name off `PATH` goes to it unless the caller said no shell. + const builtin = bareName && !found && requestedShell === undefined; + if (!commandScript && !namesCmd(requestedShell) && !builtin) { + return { command: target, args: [...args], shell: false }; } - return process.platform === "win32" && !hasPathSeparator(command) && !extname(command); + // A cmd.exe the caller names runs the line; otherwise the child's ComSpec does. + return { + command: typeof requestedShell === "string" ? requestedShell : windowsCommandShell(env), + args: ["/d", "/s", "/c", windowsCommandLine(target, args, { commandScript })], + shell: false, + windowsVerbatimArguments: true, + }; +} + +export interface SpawnProcessOptions extends SpawnOptions { + /** + * Start `[...wrap, command, ...args]`: the wrap's executable runs the command. `shell` is then + * ignored; the wrap's executable runs through cmd.exe only when it is a `.cmd` or `.bat` file. + */ + wrap?: PluginLaunchWrap; } /** Launch a CLI with Windows command-script handling and argv quoting. The caller owns env. */ export function spawnProcess( command: string, args: string[], - options: SpawnOptions & { stdio: "pipe" }, + options: SpawnProcessOptions & { stdio: "pipe" }, ): ChildProcessWithoutNullStreams; -export function spawnProcess(command: string, args: string[], options?: SpawnOptions): ChildProcess; export function spawnProcess( command: string, args: string[], - options?: SpawnOptions, + options?: SpawnProcessOptions, +): ChildProcess; +export function spawnProcess( + command: string, + args: string[], + options?: SpawnProcessOptions, ): ChildProcess { - const spawnOptions = options ?? {}; - const isWindows = process.platform === "win32"; - const shell = shouldUseWindowsShell(command, spawnOptions.shell); + const { wrap, ...spawnOptions } = options ?? {}; + const env = options?.env ?? process.env; + const invocation = wrap + ? resolveSpawnInvocation(wrap[0], [...wrap.slice(1), command, ...args], false, undefined, env) + : resolveSpawnInvocation(command, args, spawnOptions.shell, undefined, env); - const shouldQuoteForShell = isWindows && shell !== false; - const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command; - const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args; - - return spawn(resolvedCommand, resolvedArgs, { + return spawn(invocation.command, invocation.args, { ...spawnOptions, env: options?.env, - shell, + shell: invocation.shell, + // Paseo's own cmd.exe line is verbatim; a direct launch keeps the caller's choice. + windowsVerbatimArguments: + invocation.windowsVerbatimArguments ?? spawnOptions.windowsVerbatimArguments, signal: options?.signal, windowsHide: true, }); @@ -78,13 +133,15 @@ export async function execCommand( args: string[], options?: ExecCommandOptions, ): Promise { - const isWindows = process.platform === "win32"; - const shell = shouldUseWindowsShell(command, options?.shell); - const shouldQuoteForShell = isWindows && shell !== false; - const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command; - const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args; + const invocation = resolveSpawnInvocation( + command, + args, + options?.shell, + undefined, + options?.env ?? process.env, + ); - return execFileAsync(resolvedCommand, resolvedArgs, { + return execFileAsync(invocation.command, invocation.args, { cwd: options?.cwd, env: options?.env, encoding: options?.encoding ?? "utf8", @@ -92,7 +149,8 @@ export async function execCommand( killSignal: options?.killSignal, timeout: options?.timeout, maxBuffer: options?.maxBuffer, - shell, + shell: invocation.shell, + windowsVerbatimArguments: invocation.windowsVerbatimArguments, windowsHide: true, }) as Promise; } diff --git a/packages/plugin/src/server/provider.test.ts b/packages/plugin/src/server/provider.test.ts index 909acf1785..f33f568fd1 100644 --- a/packages/plugin/src/server/provider.test.ts +++ b/packages/plugin/src/server/provider.test.ts @@ -3,6 +3,7 @@ import { ProviderEventSchema, ProviderInputSchema, negotiateProviderCapabilities, + requireProviderCapabilities, type ProviderEvent, type ProviderInput, type ProviderMetric, @@ -125,3 +126,38 @@ describe("Provider metrics", () => { ).toBe(false); }); }); + +describe("Provider launch wrap", () => { + const open = (wrap?: readonly [string, ...string[]]): ProviderInput => + ProviderInputSchema.parse({ + type: "session.open", + requestId: "open", + sessionId: "session-1", + history: "skip", + config: { + cwd: "/workspace", + env: {}, + mcpServers: {}, + settings: {}, + persist: true, + ...(wrap ? { wrap } : {}), + }, + }); + + it("requires session.launch_wrap only for an open that carries a wrap", () => { + expect(() => requireProviderCapabilities([], open(["/bin/sandbox", "a b"]))).toThrow( + "session.launch_wrap", + ); + expect(() => + requireProviderCapabilities(["session.launch_wrap"], open(["/bin/sandbox"])), + ).not.toThrow(); + expect(() => requireProviderCapabilities([], open())).not.toThrow(); + }); + + it("keeps each wrap element whole and rejects an empty wrap", () => { + expect(open(["/bin/sandbox", "a b"])).toMatchObject({ + config: { wrap: ["/bin/sandbox", "a b"] }, + }); + expect(() => open([] as unknown as [string])).toThrow(); + }); +}); diff --git a/packages/plugin/src/server/provider.ts b/packages/plugin/src/server/provider.ts index ce8b7be7e5..26ee02a2c0 100644 --- a/packages/plugin/src/server/provider.ts +++ b/packages/plugin/src/server/provider.ts @@ -12,6 +12,7 @@ export const PROVIDER_CAPABILITIES = [ "session.can_stop_runtime", "session.archive", "session.configure", + "session.launch_wrap", "session.list", "session.metrics", "session.persistence", @@ -34,6 +35,12 @@ export interface ProviderRegistration { getCatalogCacheKey?(options: ProviderCatalogOptions): Promise; /** Default executable and arguments; the daemon resolves overrides before status/connect. */ command?: readonly [string, ...string[]]; + /** + * Sessions can run behind an `agent.open.before` wrap: the connection offers `session.launch_wrap` + * and spawns each session as `[...config.wrap, command, ...args]`. Paseo publishes it on the + * provider snapshot before the first connection. + */ + launchWrap?: boolean; status?(request: ProviderStatusRequest): Promise; id: string; label: string; @@ -212,6 +219,8 @@ export interface ProviderSessionConfig { providerOptions?: Readonly>; title?: string; persist: boolean; + /** Spawn the session as `[...wrap, command, ...args]`. Sent only with `session.launch_wrap`. */ + wrap?: readonly [string, ...string[]]; } export interface ProviderConfigChanges { @@ -804,6 +813,7 @@ export function requiredProviderCapabilities(input: ProviderInput): readonly Pro const capabilities: ProviderCapability[] = []; if (input.persistence) capabilities.push("session.persistence"); if (input.config.toolPolicy) capabilities.push("permission.tool_policy"); + if (input.config.wrap) capabilities.push("session.launch_wrap"); return capabilities; } case "session.prompt": @@ -907,6 +917,7 @@ const sessionConfigSchema = z providerOptions: z.record(z.string(), z.unknown()).optional(), title: z.string().optional(), persist: z.boolean(), + wrap: z.tuple([z.string().min(1)], z.string()).optional(), }) .strict(); const externalResourceSchema = z diff --git a/packages/plugin/src/skill-examples.test.ts b/packages/plugin/src/skill-examples.test.ts index 9561641d8f..edafd60fcd 100644 --- a/packages/plugin/src/skill-examples.test.ts +++ b/packages/plugin/src/skill-examples.test.ts @@ -5,7 +5,11 @@ import ts from "typescript"; import { describe, expect, it } from "vitest"; const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); -const skill = readFileSync(path.join(repository, "skills/paseo-plugin/SKILL.md"), "utf8"); +// A Windows checkout writes CRLF line endings. +const skill = readFileSync( + path.join(repository, "skills/paseo-plugin/SKILL.md"), + "utf8", +).replaceAll("\r\n", "\n"); const pluginRoot = path.join(repository, "plugin-examples/skill-example"); interface SkillExample { diff --git a/packages/protocol/src/agent-types.ts b/packages/protocol/src/agent-types.ts index c7c5008c27..9adee2e117 100644 --- a/packages/protocol/src/agent-types.ts +++ b/packages/protocol/src/agent-types.ts @@ -136,6 +136,8 @@ export interface ProviderSnapshotEntry { /** The page that helps users set up and troubleshoot this provider. */ docsUrl?: string; defaultModeId?: string | null; + /** The provider can run a session behind an `agent.open.before` wrap. Absent means it cannot. */ + launchWrap?: boolean; } export interface AgentFeatureToggle { diff --git a/packages/protocol/src/messages.providers-snapshot.test.ts b/packages/protocol/src/messages.providers-snapshot.test.ts index 91b08a3cdc..e2e4c8b36b 100644 --- a/packages/protocol/src/messages.providers-snapshot.test.ts +++ b/packages/protocol/src/messages.providers-snapshot.test.ts @@ -50,6 +50,12 @@ describe("provider snapshot message schemas", () => { expect(parsed.source).toBe("custom"); }); + test("keeps launch-wrap support and leaves it absent when not reported", () => { + const entry = { provider: "codex", status: "loading", label: "Codex" }; + expect(ProviderSnapshotEntrySchema.parse({ ...entry, launchWrap: true }).launchWrap).toBe(true); + expect(ProviderSnapshotEntrySchema.parse(entry)).not.toHaveProperty("launchWrap"); + }); + test("defaults missing enabled state in providers snapshot response entries", () => { const parsed = GetProvidersSnapshotResponseMessageSchema.parse({ type: "get_providers_snapshot_response", diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index d9b4a3f343..d3660496a3 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -432,6 +432,7 @@ export const ProviderSnapshotEntrySchema = z.object({ iconSvg: z.string().optional(), docsUrl: z.string().optional(), defaultModeId: z.string().nullable().optional(), + launchWrap: z.boolean().optional(), }); export const CompactProviderSnapshotModelSchema = AgentModelDefinitionSchema.omit({ diff --git a/packages/server/package.json b/packages/server/package.json index 99b228d1a3..75416863cf 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -90,7 +90,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/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.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/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/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 -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\"", + "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/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/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", diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index d2bc28c18b..81a8ecedcc 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -1,4 +1,4 @@ -import type { PluginSessionsRuntime } from "../plugins/agent-tools.js"; +import type { AttachedAgentTool, PluginSessionsRuntime } from "../plugins/agent-tools.js"; import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js"; import { prepareAgentMessage, @@ -7,7 +7,7 @@ import { } from "./agent-messages/index.js"; import { expect, test, vi, onTestFinished } from "vitest"; import { spawn } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { randomUUID } from "node:crypto"; @@ -23,7 +23,11 @@ import { import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js"; import { AgentTurnStartCanceledError } from "./agent-sdk-types.js"; import { ForegroundPromptStart } from "./agent-run-state.js"; -import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js"; +import { + CodexAppServerAgentClient, + CodexAppServerAgentSession, +} from "./providers/codex-app-server-agent.js"; +import { spawnProcess } from "../../utils/spawn.js"; import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; @@ -16268,3 +16272,232 @@ test("importProviderSession keeps the stats the provider reported with its histo ["assistant_message", null], ]); }); + +class LaunchWrapRecordingClient extends TestAgentClient { + readonly sessions: CloseRecordingTestAgentSession[] = []; + readonly launchContexts: Array = []; + calls = { create: 0, resume: 0, import: 0 }; + + constructor(supportsLaunchWrap: boolean) { + super("codex"); + if (supportsLaunchWrap) this.supportsLaunchWrap = true; + } + + supportsLaunchWrap?: boolean; + + override async createSession( + config: AgentSessionConfig, + launchContext?: AgentLaunchContext, + ): Promise { + this.calls.create += 1; + this.launchContexts.push(launchContext); + const session = new CloseRecordingTestAgentSession(config); + this.sessions.push(session); + return session; + } + + override async resumeSession( + handle: AgentPersistenceHandle, + config?: Partial, + launchContext?: AgentLaunchContext, + ): Promise { + this.calls.resume += 1; + this.launchContexts.push(launchContext); + return await super.resumeSession(handle, config, launchContext); + } + + async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) { + this.calls.import += 1; + return { + session: new TestAgentSession(context.config), + config: context.storedConfig, + persistence: { provider: this.provider, sessionId: input.providerHandleId }, + timeline: [], + }; + } +} + +type TestLaunchWrap = [string, ...string[]]; + +/** + * A session-open plugin that selects `wrap()` and attaches one tool while it does. Like the real runtime, an open's + * tools take over only once its launch does, and a failed launch leaves the running session's tools. + */ +function launchWrapPluginSessions(wrap: () => TestLaunchWrap | undefined) { + const pending = new Map(); + const running = new Map(); + const failedLaunches: string[] = []; + const sessions: PluginSessionsRuntime = { + openSession: async (request) => { + const selected = wrap(); + const tools: AttachedAgentTool[] = selected + ? [ + { + name: "sandbox_status", + description: "Report the sandbox", + inputSchema: {}, + pluginId: "sandbox", + pluginInstanceId: "sandbox-1", + }, + ] + : []; + if (request.purpose === "interactive") pending.set(request.agentId, tools); + return { ...request, ...(selected ? { wrap: selected } : {}), tools, mcpServerOwners: {} }; + }, + sessionLaunched: (agentId) => { + const tools = pending.get(agentId); + pending.delete(agentId); + if (tools) running.set(agentId, tools); + }, + sessionLaunchFailed: (agentId) => { + pending.delete(agentId); + failedLaunches.push(agentId); + }, + refreshSession: async () => ({ stale: false }), + sessionTools: (agentId) => running.get(agentId) ?? [], + closeSession: (agentId) => { + pending.delete(agentId); + running.delete(agentId); + }, + callTool: async () => ({ isError: true, text: "No plugin tools" }), + }; + return { sessions, failedLaunches }; +} + +function createLaunchWrapManager(client: LaunchWrapRecordingClient) { + const workdir = mkdtempSync(join(tmpdir(), "agent-launch-wrap-")); + onTestFinished(() => rmSync(workdir, { recursive: true, force: true })); + const storage = new AgentStorage(join(workdir, "agents"), logger); + const hook: { wrap: TestLaunchWrap | undefined } = { wrap: undefined }; + const { sessions, failedLaunches } = launchWrapPluginSessions(() => hook.wrap); + const manager = new AgentManager({ + clients: { codex: client }, + registry: storage, + logger, + pluginSessions: sessions, + }); + return { manager, storage, workdir, failedLaunches, hook }; +} + +test("a wrapped open rejects on every path for a provider that does not apply wraps", async () => { + const client = new LaunchWrapRecordingClient(false); + const { manager, storage, workdir, failedLaunches, hook } = createLaunchWrapManager(client); + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + const existing = client.sessions[0]!; + hook.wrap = ["/opt/sandbox/bin/run", "--profile", "a b"]; + const calls = { ...client.calls }; + const unsupported = { code: "launch_wrap_unsupported", provider: "codex" }; + + await expect( + manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { workspaceId: undefined }), + ).rejects.toMatchObject(unsupported); + await expect( + manager.resumeAgentFromPersistence({ provider: "codex", sessionId: "saved" }, { cwd: workdir }), + ).rejects.toMatchObject(unsupported); + await expect( + manager.importProviderSession({ + provider: "codex", + providerHandleId: "native", + cwd: workdir, + workspaceId: "import", + }), + ).rejects.toMatchObject(unsupported); + await expect(manager.reloadAgentSession(created.id)).rejects.toMatchObject(unsupported); + + expect(client.calls).toEqual(calls); + expect(existing.closed).toBe(false); + expect(manager.getAgent(created.id)?.session).toBe(existing); + // Each refused open is discarded, so the running session keeps the tools it launched with. + expect(failedLaunches).toHaveLength(4); + expect(failedLaunches.at(-1)).toBe(created.id); + expect(manager.getPluginTools(created.id)).toEqual([]); + await manager.flush(); + expect(JSON.stringify(await storage.get(created.id))).not.toContain("/opt/sandbox"); + await manager.closeAgent(created.id); +}); + +test("a supporting provider receives the wrap at launch and the record never stores it", async () => { + const client = new LaunchWrapRecordingClient(true); + const { manager, storage, workdir, hook } = createLaunchWrapManager(client); + hook.wrap = ["/opt/sandbox/bin/run", "--profile", "a b"]; + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + expect(client.launchContexts[0]?.wrap).toEqual(["/opt/sandbox/bin/run", "--profile", "a b"]); + await manager.flush(); + expect(JSON.stringify(await storage.get(created.id))).not.toContain("/opt/sandbox"); + await manager.closeAgent(created.id); +}); + +// Records its argv, then answers as the Codex app server, so the provider command is only an +// argument: a Windows script name there must reach the wrapper as is. +const RECORDING_CODEX_APP_SERVER = ` +const { appendFileSync } = require("node:fs"); +const [log, ...rest] = process.argv.slice(2); +appendFileSync(log, JSON.stringify(rest) + "\\n"); +const results = { + "collaborationMode/list": { data: [] }, + "config/read": { config: {} }, + getUserSavedConfig: { config: {} }, + "model/list": { data: [{ id: "gpt-5.4", isDefault: true, defaultReasoningEffort: "medium" }] }, + "skills/list": { data: [] }, + "thread/start": { thread: { id: "thread-1" } }, + "thread/resume": { thread: { id: "thread-1" } }, + "thread/loaded/list": { data: [] }, + "thread/backgroundTerminals/list": { data: [], nextCursor: null }, +}; +let buffer = ""; +process.stdin.on("data", (chunk) => { + buffer += chunk.toString(); + for (let index = buffer.indexOf("\\n"); index !== -1; index = buffer.indexOf("\\n")) { + const line = buffer.slice(0, index).trim(); + buffer = buffer.slice(index + 1); + if (!line) continue; + const message = JSON.parse(line); + if (message.id === undefined || !message.method) continue; + process.stdout.write(JSON.stringify({ id: message.id, result: results[message.method] ?? {} }) + "\\n"); + } +}); +`; + +test("a wrapped refresh passes a Windows script provider command to the wrapper through the real spawn", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-launch-wrap-refresh-")); + onTestFinished(() => rmSync(workdir, { recursive: true, force: true })); + const launcher = join(workdir, "recording-app-server.cjs"); + const launches = join(workdir, "launches.jsonl"); + writeFileSync(launcher, RECORDING_CODEX_APP_SERVER); + // The version probes run `node --version`; sessions spawn through the production spawnProcess. + const codex = new CodexAppServerAgentClient( + logger, + { command: { mode: "replace", argv: [process.execPath] } }, + { + appServerProcess: { + resolvePrefix: async () => ({ command: "C:\\codex\\codex.cmd", args: [] }), + spawn: ({ command, args, options }) => spawnProcess(command, args, options), + }, + }, + ); + const client: AgentClient = Object.assign(codex, { supportsLaunchWrap: true }); + const manager = new AgentManager({ + clients: { codex: client }, + logger, + pluginSessions: launchWrapPluginSessions(() => [process.execPath, launcher, launches]).sessions, + }); + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + + await manager.reloadAgentSession(created.id); + + const argv = readFileSync(launches, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as string[]); + expect(argv).toHaveLength(2); + for (const launched of argv) + expect(launched.slice(0, 2)).toEqual(["C:\\codex\\codex.cmd", "app-server"]); + expect(manager.getAgent(created.id)?.lifecycle).not.toBe("error"); + await manager.closeAgent(created.id); +}); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index a422cc4977..006623fdc1 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -3,7 +3,7 @@ import type { PluginSessionsRuntime, SessionOpenAgentFacts, } from "../plugins/agent-tools.js"; -import { ProviderOptionsValidationError } from "./provider-options.js"; +import { LaunchWrapUnsupportedError, ProviderOptionsValidationError } from "./provider-options.js"; import type { AgentToolResult } from "@getpaseo/plugin/server"; import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js"; import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js"; @@ -1721,6 +1721,7 @@ export class AgentManager { config: sent, env: options.env, metadata: options.metadata ?? {}, + workspaceId: options.workspaceId ?? null, }); // COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. A plugin written // against the previous SDK edits `config.featureValues`. @@ -6644,6 +6645,7 @@ export class AgentManager { let appendSystemPrompt: string[] | undefined; let mcpServers: AgentSessionConfig["mcpServers"]; let mcpServerOwners: Record | undefined; + let wrap: AgentLaunchContext["wrap"]; if (this.pluginSessions) { const request = { agentId, @@ -6661,14 +6663,18 @@ export class AgentManager { }; const transformed = await this.pluginSessions.openSession(request); env = transformed.env; + wrap = transformed.wrap; if (request.purpose === "interactive") { appendSystemPrompt = transformed.appendSystemPrompt; mcpServers = transformed.mcpServers; mcpServerOwners = transformed.mcpServerOwners; } + // launchAgent discards this open when the wrap is refused, so a running session keeps its tools. + if (wrap) await requireLaunchWrap(client); } const context: AgentLaunchContext = { agentId, + wrap, ...pluginPromptContext(appendSystemPrompt), mcpServers, mcpServerOwners, @@ -6855,3 +6861,8 @@ function pluginPromptContext( ): Pick { return appendSystemPrompt?.length ? { appendSystemPrompt } : {}; } + +async function requireLaunchWrap(client: AgentClient): Promise { + if (client.supportsLaunchWrap !== true) throw new LaunchWrapUnsupportedError(client.provider); + await client.requireLaunchWrap?.(); +} diff --git a/packages/server/src/server/agent/agent-sdk-types.ts b/packages/server/src/server/agent/agent-sdk-types.ts index 81b652aed5..d044637277 100644 --- a/packages/server/src/server/agent/agent-sdk-types.ts +++ b/packages/server/src/server/agent/agent-sdk-types.ts @@ -147,6 +147,7 @@ export interface ProviderSnapshotEntry { /** The page that helps users set up and troubleshoot this provider. */ docsUrl?: string; defaultModeId?: string | null; + launchWrap?: boolean; } export interface AgentCreateConfigParent { @@ -677,6 +678,8 @@ export interface AgentLaunchContext { mcpServerOwners?: Record; agentId?: string; env?: Record; + /** Spawn the harness as `[...wrap, command, ...args]`. Selected by a plugin hook; never persisted. */ + wrap?: readonly [string, ...string[]]; /** * Runtime-only internal Paseo tools. This must never be persisted into * AgentSessionConfig; providers may adapt it to their native tool surface. @@ -884,6 +887,10 @@ export interface AgentClient { >; readonly provider: AgentProvider; readonly capabilities: AgentCapabilityFlags; + /** Sessions honor `AgentLaunchContext.wrap`. The provider registry sets it from the provider contract. */ + supportsLaunchWrap?: boolean; + /** Throw unless the live provider runtime can apply a wrap. Plugin providers connect to learn it. */ + requireLaunchWrap?(): Promise; /** * Create the agent with `config.providerOptions` (defaults already merged in). Emit nothing * about options while creating. If the agent ended up different from the options, say so in the diff --git a/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts b/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts index 0a8f23b7c0..ebd1aaf3dd 100644 --- a/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts +++ b/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts @@ -1,3 +1,4 @@ +import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import type { CreatePaseoWorktreeInput } from "../paseo-worktree-service.js"; import { randomUUID } from "node:crypto"; import type pino from "pino"; @@ -47,6 +48,7 @@ interface CreateAgentLifecycleDispatchDependencies { clearWorkspaceArchiving: (workspaceIds: Iterable) => void; killTerminalsForWorkspace: (workspaceId: string) => Promise; logger: pino.Logger; + lifecycle: Pick | null; } export interface LifecycleRegistration { @@ -192,6 +194,7 @@ export class CreateAgentLifecycleDispatch { await archiveByScope( { + lifecycle: this.dependencies.lifecycle, paseoHome: this.dependencies.paseoHome, paseoWorktreesBaseRoot: this.dependencies.worktreesRoot, worktreeManagers: this.dependencies.worktreeManagers, diff --git a/packages/server/src/server/agent/mcp-client-connection.ts b/packages/server/src/server/agent/mcp-client-connection.ts index 7eddc2c90b..ee2842847a 100644 --- a/packages/server/src/server/agent/mcp-client-connection.ts +++ b/packages/server/src/server/agent/mcp-client-connection.ts @@ -8,6 +8,7 @@ import { import { CallToolResultSchema, type Tool } from "@modelcontextprotocol/sdk/types.js"; import type { McpServerConfig } from "./agent-sdk-types.js"; import type { PaseoToolResult } from "./tools/types.js"; +import { applyLaunchWrap, type LaunchWrap } from "../../utils/launch-wrap.js"; const SERVER_TIMEOUT_MS = 10_000; const TERMINATE_TIMEOUT_MS = 2_000; @@ -36,6 +37,8 @@ export interface ConnectMcpServerInput { cwd: string; /** Complete environment for a stdio server; the server's own `env` overlays it. */ env: NodeJS.ProcessEnv; + /** Start a stdio server as `[...wrap, command, ...args]`. */ + wrap?: LaunchWrap; clientName: string; } @@ -165,11 +168,12 @@ async function withDeadline( } } -function createTransport({ config, cwd, env }: ConnectMcpServerInput) { +function createTransport({ config, cwd, env, wrap }: ConnectMcpServerInput) { if (config.type === "stdio") { + const launch = applyLaunchWrap({ command: config.command, args: config.args ?? [] }, wrap); return new StdioClientTransport({ - command: config.command, - args: config.args, + command: launch.command, + args: launch.args, cwd, env: definedEnvironment({ ...env, ...config.env }), stderr: "ignore", diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 334d0be0cb..4f22f1f3ab 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -8,6 +8,7 @@ import { execFileSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { runAcpProvider, type AcpStreamMessage } from "@getpaseo/plugin/server/acp"; import type { + ProviderCapability, ProviderConnection, ProviderLaunch, ProviderEvent, @@ -313,6 +314,7 @@ function createRewindProviderHarness( reuseAnswerId?: boolean; forkOnRevert?: boolean; handleInput?: ProviderHarnessOptions["handleInput"]; + extraCapabilities?: ProviderCapability[]; } = {}, ) { const nativeMessages: string[] = []; @@ -324,6 +326,7 @@ function createRewindProviderHarness( "session.revert.conversation", "session.revert.files", "session.revert.both", + ...(options.extraCapabilities ?? []), ], async handleInput(input, emit) { if (await options.handleInput?.(input, emit)) return true; @@ -3680,3 +3683,54 @@ test("bounds settings wait when Stop is queued behind an unanswered steer", asyn await plugins.shutdown(); } }); + +test("a declared launch wrap still needs session.launch_wrap on the live connection", async () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([{ ...harness.registration, launchWrap: true }]); + expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(true); + const client = registry.clients()[harness.registration.id]!; + expect(client.supportsLaunchWrap).toBe(true); + + await expect(client.requireLaunchWrap?.()).rejects.toMatchObject({ + code: "launch_wrap_unsupported", + }); + await expect( + client.createSession( + { provider: harness.registration.id, cwd: tmpdir() }, + { wrap: ["/opt/sandbox/bin/run"] }, + ), + ).rejects.toThrow("session.launch_wrap"); + expect(harness.inputs.some((input) => input.type === "session.open")).toBe(false); + await registry.shutdown(); +}); + +test("a provider that declares no launch wrap is not marked as supporting it", () => { + const harness = createProviderHarness(); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([harness.registration]); + expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(false); + expect(registry.clients()[harness.registration.id]!.supportsLaunchWrap).toBe(false); +}); + +test("a plugin session reopen sends the wrap the session opened with", async () => { + const harness = createRewindProviderHarness({ extraCapabilities: ["session.launch_wrap"] }); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([{ ...harness.registration, launchWrap: true }]); + const client = registry.clients()[harness.registration.id]!; + await expect(client.requireLaunchWrap?.()).resolves.toBeUndefined(); + const wrap: [string, ...string[]] = ["/opt/sandbox/bin/run", "--profile", "a b"]; + const session = await client.createSession( + { provider: harness.registration.id, cwd: tmpdir() }, + { wrap }, + ); + await session.run("A"); + + await session.revertConversation!({ messageId: "user-A" }); + + const opens = harness.inputs.filter((input) => input.type === "session.open"); + expect(opens.length).toBeGreaterThanOrEqual(2); + for (const open of opens) expect(open.config.wrap).toEqual(wrap); + await session.close(); + await registry.shutdown(); +}); diff --git a/packages/server/src/server/agent/plugin-provider.ts b/packages/server/src/server/agent/plugin-provider.ts index 5e52f66032..22c33870a2 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -81,6 +81,7 @@ import { formatProviderDiagnostic, type DiagnosticEntry, } from "./providers/diagnostic-utils.js"; +import { LaunchWrapUnsupportedError } from "./provider-options.js"; import type { RegisteredProviderDefinition } from "./provider-registry.js"; import { runProviderTurn } from "./providers/provider-runner.js"; import { StaleProviderSessionError } from "./stale-provider-session-error.js"; @@ -296,6 +297,11 @@ class ProviderRuntime { return this.connection?.capabilities ?? []; } + /** The live connection's capabilities, connecting first when no connection exists yet. */ + async connectedCapabilities(): Promise { + return (await this.getConnection()).capabilities; + } + get isClosed(): boolean { return this.closed; } @@ -1052,6 +1058,7 @@ function createPluginProviderDefinition( defaultModeId: null, modes: [], supportsExactMcpPreapproval: true, + supportsLaunchWrap: registration.launchWrap === true, createClient, }; } @@ -1070,10 +1077,12 @@ class PluginAgentClient implements AgentClient { readonly getCatalogCacheKey?: AgentClient["getCatalogCacheKey"]; readonly installation?: AgentClientInstallation; + readonly supportsLaunchWrap: boolean; constructor(registration: ProviderRegistration, runtimeSettings?: ProviderRuntimeSettings) { this.provider = registration.id; this.label = registration.label; + this.supportsLaunchWrap = registration.launchWrap === true; this.runtime = new ProviderRuntime(registration, runtimeSettings); if (registration.getCatalogCacheKey) this.getCatalogCacheKey = (options) => this.runtime.catalogCacheKey(options); @@ -1101,6 +1110,15 @@ class PluginAgentClient implements AgentClient { return agentCapabilities(this.runtime.negotiatedCapabilities); } + async requireLaunchWrap(): Promise { + if (!(await this.runtime.connectedCapabilities()).includes("session.launch_wrap")) { + throw new LaunchWrapUnsupportedError( + this.provider, + `Provider '${this.provider}' declares launch wrap support, but its connection does not offer session.launch_wrap`, + ); + } + } + async createSession( config: AgentSessionConfig, launchContext?: AgentLaunchContext, @@ -2143,6 +2161,7 @@ function mapSessionConfig( providerOptions: config.providerOptions, title: config.title ?? undefined, persist, + ...(launchContext?.wrap ? { wrap: launchContext.wrap } : {}), }; } diff --git a/packages/server/src/server/agent/provider-options.ts b/packages/server/src/server/agent/provider-options.ts index 76a9d638b6..cf819a7ced 100644 --- a/packages/server/src/server/agent/provider-options.ts +++ b/packages/server/src/server/agent/provider-options.ts @@ -37,6 +37,18 @@ export class ToolPolicyUnsupportedError extends Error { } } +export class LaunchWrapUnsupportedError extends Error { + readonly code = "launch_wrap_unsupported" as const; + + constructor( + readonly provider: string, + reason?: string, + ) { + super(reason ?? `Provider '${provider}' cannot run a session behind a launch wrap`); + this.name = "LaunchWrapUnsupportedError"; + } +} + export function validateProviderOptions( provider: string, schema: z.ZodType, diff --git a/packages/server/src/server/agent/provider-registry.test.ts b/packages/server/src/server/agent/provider-registry.test.ts index d9096d2fdb..005d062ada 100644 --- a/packages/server/src/server/agent/provider-registry.test.ts +++ b/packages/server/src/server/agent/provider-registry.test.ts @@ -645,6 +645,32 @@ test("new provider extending codex archives and unarchives its native sessions", ]); }); +test("launch-wrap support comes from the provider contract and follows extends", () => { + const registry = buildProviderRegistry(logger, { + isDev: true, + providerOverrides: { + "my-claude": { extends: "claude", label: "My Claude" }, + "my-acp": { extends: "acp", label: "My ACP", command: ["my-acp", "--acp"] }, + }, + }); + + const support = Object.fromEntries( + Object.keys(registry).map((id) => [id, registry[id].createClient(logger).supportsLaunchWrap]), + ); + expect(support).toEqual({ + claude: true, + codex: true, + copilot: true, + opencode: true, + pi: true, + omp: true, + mock: false, + "mock-slow": false, + "my-claude": true, + "my-acp": true, + }); +}); + test("built-in OMP override keeps the real OMP adapter enabled and launchable", async () => { const omp = new FakeOmp(["custom-omp"]); const registry = buildProviderRegistry(logger, { diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index bff07decec..88ca55ed5c 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -78,6 +78,7 @@ export interface ProviderDefinition extends AgentProviderDefinition { */ derivedFromProviderId: string | null; supportsExactMcpPreapproval: boolean; + supportsLaunchWrap: boolean; applyToolPolicy: ( config: AgentSessionConfig, toolPolicy: ToolPolicy | undefined, @@ -101,6 +102,7 @@ export interface RegisteredProviderDefinition extends AgentProviderDefinition { requiresConfiguration?: boolean; iconSvg?: string; supportsExactMcpPreapproval: boolean; + supportsLaunchWrap: boolean; createClient: (logger: Logger, runtimeSettings?: ProviderRuntimeSettings) => AgentClient; } @@ -148,25 +150,38 @@ interface ResolvedProvider { interface ProviderContract { supportsExactMcpPreapproval: boolean; + /** Sessions spawn their harness behind an `agent.open.before` wrap. */ + supportsLaunchWrap?: boolean; applyToolPolicy?: (provider: string, toolPolicy: ToolPolicy) => ToolPolicy; } +// Every built-in provider that starts a local harness honors a wrap; the mock providers start none. const PROVIDER_CONTRACTS: Record = { - claude: { supportsExactMcpPreapproval: true }, - codex: { supportsExactMcpPreapproval: true }, - opencode: { supportsExactMcpPreapproval: true }, + claude: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true }, + codex: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true }, + copilot: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true }, + opencode: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true }, + pi: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true }, + omp: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true }, }; const UNSUPPORTED_PROVIDER_CONTRACT: ProviderContract = { supportsExactMcpPreapproval: false, }; +// A user-defined ACP provider is a local command, which starts behind the wrap. +const CUSTOM_ACP_PROVIDER_CONTRACT: ProviderContract = { + supportsExactMcpPreapproval: false, + supportsLaunchWrap: true, +}; + const HUB_E2E_PROVIDER_ID = "hub-e2e"; const HUB_E2E_MCP_SERVER = "hub"; const HUB_E2E_TOOL_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/u; // The cross-repository Hub harness owns this synthetic provider ID. It exercises the production // registry path without extending exact-preapproval support to user-defined ACP providers. const HUB_E2E_PROVIDER_CONTRACT: ProviderContract = { + ...CUSTOM_ACP_PROVIDER_CONTRACT, supportsExactMcpPreapproval: true, applyToolPolicy: (provider, toolPolicy) => { for (const grant of toolPolicy.preapproved) { @@ -498,6 +513,7 @@ function wrapClientProvider( additionalModels: ProviderProfileModel[], profileModelsAreAdditive: boolean, configuredOptions: ProviderOptions | undefined, + supportsLaunchWrap: boolean, ): AgentClient { const listImportableSessions = inner.listImportableSessions?.bind(inner); const importSession = inner.importSession?.bind(inner); @@ -517,6 +533,7 @@ function wrapClientProvider( get capabilities() { return inner.capabilities; }, + supportsLaunchWrap, shutdown: inner.shutdown?.bind(inner), createSession: async (config, launchContext, options) => wrapSessionProvider( @@ -626,6 +643,7 @@ function wrapClientProvider( ? async (handle) => await unarchiveNativeSession({ ...handle, provider: inner.provider }) : undefined, resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner), + requireLaunchWrap: inner.requireLaunchWrap?.bind(inner), getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner), isAvailable: (signal, options) => inner.isAvailable(signal, options), getDiagnostic: inner.getDiagnostic?.bind(inner), @@ -670,6 +688,7 @@ function createRegistryEntry( enabled: resolved.enabled, derivedFromProviderId: resolved.derivedFromProviderId, supportsExactMcpPreapproval: resolved.contract.supportsExactMcpPreapproval, + supportsLaunchWrap: resolved.contract.supportsLaunchWrap === true, applyToolPolicy: (config, toolPolicy) => { if (toolPolicy && !resolved.contract.supportsExactMcpPreapproval) { throw new ToolPolicyUnsupportedError(provider); @@ -747,6 +766,7 @@ function createResolvedProviderClient( additionalModels, resolved.profileModelsAreAdditive, resolved.providerOptions, + resolved.contract.supportsLaunchWrap === true, ); } @@ -880,7 +900,7 @@ function addDerivedProviders( contract: providerId === HUB_E2E_PROVIDER_ID ? HUB_E2E_PROVIDER_CONTRACT - : UNSUPPORTED_PROVIDER_CONTRACT, + : CUSTOM_ACP_PROVIDER_CONTRACT, }); continue; } @@ -962,6 +982,7 @@ export function buildProviderRegistry( createClient: definition.createClient, contract: { supportsExactMcpPreapproval: definition.supportsExactMcpPreapproval, + supportsLaunchWrap: definition.supportsLaunchWrap, }, }), ); diff --git a/packages/server/src/server/agent/provider-snapshot-manager.test.ts b/packages/server/src/server/agent/provider-snapshot-manager.test.ts index b8c2ed7df7..60698125bd 100644 --- a/packages/server/src/server/agent/provider-snapshot-manager.test.ts +++ b/packages/server/src/server/agent/provider-snapshot-manager.test.ts @@ -542,6 +542,23 @@ describe("ProviderSnapshotManager public surface", () => { } }); + test("loading entries already report launch-wrap support, before any discovery", () => { + const manager = new ProviderSnapshotManager({ + logger: createTestLogger(), + providerOverrides: { "my-codex": { extends: "codex", label: "My Codex" } }, + }); + try { + const snapshot = manager.getSnapshot("/tmp/project").records.map(({ entry }) => entry); + const byProvider = (provider: string) => + snapshot.find((entry) => entry.provider === provider); + expect(byProvider("codex")).toMatchObject({ status: "loading", launchWrap: true }); + expect(byProvider("my-codex")).toMatchObject({ status: "loading", launchWrap: true }); + expect(byProvider("claude")).toMatchObject({ status: "loading", launchWrap: true }); + } finally { + manager.destroy(); + } + }); + test("providerOverrides with enabled:false marks the provider as unavailable without probing", async () => { const isAvailable = vi.fn(async () => true); const fetchCatalog = vi.fn(async () => ({ diff --git a/packages/server/src/server/agent/provider-snapshot-manager.ts b/packages/server/src/server/agent/provider-snapshot-manager.ts index dfc6c88789..4283684d4c 100644 --- a/packages/server/src/server/agent/provider-snapshot-manager.ts +++ b/packages/server/src/server/agent/provider-snapshot-manager.ts @@ -1044,6 +1044,7 @@ export class ProviderSnapshotManager { iconSvg: definition.iconSvg, docsUrl: definition.docsUrl, defaultModeId: definition.defaultModeId ?? null, + ...(definition.supportsLaunchWrap ? { launchWrap: true } : {}), }), }); } diff --git a/packages/server/src/server/agent/providers/acp-agent.test.ts b/packages/server/src/server/agent/providers/acp-agent.test.ts index e7ca0b88e3..c0d46ab380 100644 --- a/packages/server/src/server/agent/providers/acp-agent.test.ts +++ b/packages/server/src/server/agent/providers/acp-agent.test.ts @@ -5864,3 +5864,64 @@ describe("custom ACP provider with configured models", () => { expect((await created.getRuntimeInfo()).model).toBe("advertised-default"); }); }); + +describe("ACPAgentSession launch wrap against an ACP agent", () => { + const fakeAgentPath = fileURLToPath(new URL("./test-utils/fake-acp-agent.mjs", import.meta.url)); + + test("starts the agent and its terminals behind the session's wrap", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-")); + const record = path.join(root, "launches.jsonl"); + const launcher = path.join(root, "launcher.cjs"); + await writeFile( + launcher, + ` + const [, , ...argv] = process.argv; + require("node:fs").appendFileSync(${JSON.stringify(record)}, JSON.stringify(argv) + "\\n"); + const child = require("node:child_process").spawn(argv[0], argv.slice(1), { stdio: "inherit" }); + child.on("exit", (code) => process.exit(code ?? 1)); + `, + ); + const session = new ACPAgentSession( + { provider: "acp", cwd: root }, + { + provider: "acp", + logger: createTestLogger(), + defaultCommand: [process.execPath, fakeAgentPath, "{}"], + defaultModes: [], + capabilities: { + supportsStreaming: true, + supportsSessionPersistence: true, + supportsDynamicModes: true, + supportsMcpServers: true, + supportsReasoningStream: true, + supportsToolInvocations: true, + }, + wrap: [process.execPath, launcher], + }, + ); + try { + await session.initializeNewSession(); + const { terminalId } = await session.createTerminal({ + sessionId: "session-1", + command: process.execPath, + args: ["-e", "process.exit(0)"], + cwd: root, + }); + await expect( + session.waitForTerminalExit({ sessionId: "session-1", terminalId }), + ).resolves.toMatchObject({ exitCode: 0 }); + + const launches = (await readFile(record, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(launches).toEqual([ + [process.execPath, fakeAgentPath, "{}"], + [process.execPath, "-e", "process.exit(0)"], + ]); + } finally { + await session.close(); + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/server/src/server/agent/providers/acp-agent.ts b/packages/server/src/server/agent/providers/acp-agent.ts index f88d3a22dc..b23ac68c97 100644 --- a/packages/server/src/server/agent/providers/acp-agent.ts +++ b/packages/server/src/server/agent/providers/acp-agent.ts @@ -548,6 +548,8 @@ interface ACPAgentSessionOptions { configuredModelIds?: readonly string[]; agentId?: string; launchEnv?: Record; + /** Start the agent, and every terminal it asks for, as `[...wrap, command, ...args]`. */ + wrap?: AgentLaunchContext["wrap"]; waitForInitialCommands?: boolean; initialCommandsWaitTimeoutMs?: number; terminateProcess?: ProcessTerminator; @@ -1152,6 +1154,7 @@ export class ACPAgentClient implements AgentClient { configuredModelIds: options?.configuredModelIds, agentId: launchContext?.agentId, launchEnv: launchContext?.env, + wrap: launchContext?.wrap, extensionCommandsParser: this.extensionCommandsParser, waitForInitialCommands: this.waitForInitialCommands, initialCommandsWaitTimeoutMs: this.initialCommandsWaitTimeoutMs, @@ -1212,6 +1215,7 @@ export class ACPAgentClient implements AgentClient { configuredModelIds: options?.configuredModelIds, agentId: launchContext?.agentId, launchEnv: launchContext?.env, + wrap: launchContext?.wrap, extensionCommandsParser: this.extensionCommandsParser, waitForInitialCommands: this.waitForInitialCommands, initialCommandsWaitTimeoutMs: this.initialCommandsWaitTimeoutMs, @@ -1951,6 +1955,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { ) => Promise; private readonly agentId?: string; private readonly launchEnv?: Record; + private readonly wrap?: AgentLaunchContext["wrap"]; private readonly usageProvider?: string; private readonly usageSessionKey = randomUUID(); private readonly harnessEnvironment: Record; @@ -2023,6 +2028,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { this.availableModes = options.defaultModes; this.agentId = options.agentId; this.launchEnv = options.launchEnv; + this.wrap = options.wrap; this.usageProvider = options.usageProvider; this.harnessEnvironment = createProviderEnv({ runtimeSettings: options.runtimeSettings, @@ -3117,7 +3123,9 @@ export class ACPAgentSession implements AgentSession, ACPClient { terminalCommand.shell === false ? [this.launchEnv, env, createStringCommandShellEnvOverlay()] : [this.launchEnv, env]; + // A terminal runs commands for the agent, so it runs behind the agent's wrap too. const child = spawnProcess(terminalCommand.command, terminalCommand.args, { + wrap: this.wrap, cwd: params.cwd ?? this.config.cwd, ...createProviderEnvSpec({ runtimeSettings: this.runtimeSettings, @@ -3222,6 +3230,7 @@ export class ACPAgentSession implements AgentSession, ACPClient { const command = prefix.command; const args = [...prefix.args, ...this.defaultCommand.slice(1)]; const child = spawnProcess(command, args, { + wrap: this.wrap, cwd: await this.resolveProcessCwd(), ...createProviderEnvSpec({ runtimeSettings: this.runtimeSettings, diff --git a/packages/server/src/server/agent/providers/claude/agent.spawn.test.ts b/packages/server/src/server/agent/providers/claude/agent.spawn.test.ts index d67210af27..612cabbe83 100644 --- a/packages/server/src/server/agent/providers/claude/agent.spawn.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.spawn.test.ts @@ -1,4 +1,7 @@ import { EventEmitter } from "node:events"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; import { PassThrough } from "node:stream"; import type { ChildProcess } from "node:child_process"; import { @@ -173,4 +176,49 @@ describe("Claude spawn override", () => { 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-")); + const launcher = path.join(root, "launcher.mjs"); + await writeFile(launcher, "process.stdout.write(JSON.stringify(process.argv.slice(2)));\n"); + let capturedOptions: Options | undefined; + const client = new ClaudeAgentClient({ + logger: createTestLogger(), + queryFactory: ({ options }: ClaudeQueryInput) => { + capturedOptions = options; + return createQueryMock([]); + }, + resolveBinary: async () => "/test/claude/bin", + resolveVersion: async () => "2.1.326", + }); + const session = await client.createSession( + { provider: "claude", cwd: root }, + { wrap: [process.execPath, launcher, "--sandbox"] }, + ); + try { + await (session as unknown as { ensureQuery(): Promise }).ensureQuery(); + const child = capturedOptions?.spawnClaudeCodeProcess?.({ + command: "/test/claude/bin", + args: ["--output-format", "stream-json"], + cwd: root, + env: {}, + signal: new AbortController().signal, + }) as ChildProcess | undefined; + if (!child?.stdout) throw new Error("Claude Code was not spawned"); + let stdout = ""; + child.stdout.on("data", (chunk: Buffer) => { + stdout += chunk.toString("utf8"); + }); + await new Promise((resolve) => child.once("close", resolve)); + expect(JSON.parse(stdout)).toEqual([ + "--sandbox", + "/test/claude/bin", + "--output-format", + "stream-json", + ]); + } finally { + await session.close(); + await rm(root, { recursive: true, force: true }); + } + }); }); diff --git a/packages/server/src/server/agent/providers/claude/agent.ts b/packages/server/src/server/agent/providers/claude/agent.ts index ce7ac3c68b..ca44e155a4 100644 --- a/packages/server/src/server/agent/providers/claude/agent.ts +++ b/packages/server/src/server/agent/providers/claude/agent.ts @@ -515,6 +515,7 @@ interface ClaudeAgentSessionOptions { handle?: AgentPersistenceHandle; agentId?: string; launchEnv?: Record; + wrap?: AgentLaunchContext["wrap"]; persistSession?: boolean; logger: Logger; queryFactory?: ClaudeQueryFactory; @@ -1713,6 +1714,7 @@ export class ClaudeAgentClient implements AgentClient { runtimeSettings: this.runtimeSettings, agentId: launchContext?.agentId, launchEnv: launchContext?.env, + wrap: launchContext?.wrap, persistSession: options?.persistSession, logger: this.logger, queryFactory: this.queryFactory, @@ -1745,6 +1747,7 @@ export class ClaudeAgentClient implements AgentClient { handle, agentId: launchContext?.agentId, launchEnv: launchContext?.env, + wrap: launchContext?.wrap, logger: this.logger, queryFactory: this.queryFactory, resolveBinary: this.resolveBinary, @@ -2457,6 +2460,7 @@ class ClaudeAgentSession implements AgentSession { private readonly config: ClaudeAgentConfig; private readonly launchEnv?: Record; + private readonly wrap?: AgentLaunchContext["wrap"]; private readonly agentId?: string; private readonly defaults?: { agents?: Record }; private readonly runtimeSettings?: ProviderRuntimeSettings; @@ -2596,6 +2600,7 @@ class ClaudeAgentSession implements AgentSession { this.config = config; assertClaudeThinkingOptionSupported(config.model, config.thinkingOptionId); this.launchEnv = options.launchEnv; + this.wrap = options.wrap; this.agentId = options.agentId; this.defaults = options.defaults; this.runtimeSettings = options.runtimeSettings; @@ -3887,6 +3892,7 @@ class ClaudeAgentSession implements AgentSession { { runtimeSettings: this.runtimeSettings, launchEnv: this.launchEnv, + wrap: this.wrap, queryFactory: this.queryFactory, onChildProcess: (child) => { this.childProcess = child; diff --git a/packages/server/src/server/agent/providers/claude/query.ts b/packages/server/src/server/agent/providers/claude/query.ts index 090351a30e..1e76e70d75 100644 --- a/packages/server/src/server/agent/providers/claude/query.ts +++ b/packages/server/src/server/agent/providers/claude/query.ts @@ -7,6 +7,7 @@ import { } from "../../provider-launch-config.js"; import { buildSelfNodeCommand, createExternalProcessEnv } from "../../../paseo-env.js"; import { execCommand, spawnProcess } from "../../../../utils/spawn.js"; +import type { AgentLaunchContext } from "../../agent-sdk-types.js"; // Keep the raw SDK query import in this module only. Claude process launch behavior // must stay shared between production and tests so Windows .cmd/.bat handling cannot @@ -19,6 +20,8 @@ export type ClaudeQueryFactory = (input: ClaudeQueryInput) => Query; export interface ClaudeQueryContext { runtimeSettings?: ProviderRuntimeSettings; launchEnv?: Record; + /** Start Claude Code as `[...wrap, command, ...args]`. */ + wrap?: AgentLaunchContext["wrap"]; queryFactory?: ClaudeQueryFactory; /** Called with the spawned child process so the caller can tree-kill it on close. */ onChildProcess?: (child: ChildProcess) => void; @@ -90,7 +93,7 @@ function applyRuntimeSettingsToClaudeOptions( options: ClaudeOptions, context: ClaudeQueryContext, ): ClaudeOptions { - const { runtimeSettings, onChildProcess } = context; + const { runtimeSettings, onChildProcess, wrap } = context; return { ...options, spawnClaudeCodeProcess: (spawnOptions) => { @@ -109,6 +112,7 @@ function applyRuntimeSettingsToClaudeOptions( const command = selfNodeCommand?.command ?? resolved.command; const args = selfNodeCommand?.args ?? resolved.args; const child = spawnProcess(command, args, { + wrap, cwd: spawnOptions.cwd, ...(selfNodeCommand ? { env: selfNodeCommand.env, envMode: "internal" as const } diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.spawn-error.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.spawn-error.test.ts index 8cb8649e26..8e7674788d 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.spawn-error.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.spawn-error.test.ts @@ -1,3 +1,4 @@ +import { spawnProcess } from "../../../utils/spawn.js"; import { describe, expect, test, vi } from "vitest"; import { CodexAppServerAgentClient } from "./codex-app-server-agent.js"; @@ -80,4 +81,35 @@ describe("CodexAppServerAgentClient spawn error handling", () => { process.off("uncaughtException", onUncaught); } }); + test("a missing launch wrap fails the open and never starts the bare codex command", async () => { + const spawned: Array<{ command: string; args: string[]; wrap?: readonly string[] }> = []; + const client = new CodexAppServerAgentClient(logger, undefined, { + appServerProcess: { + resolvePrefix: async () => ({ command: process.execPath, args: ["codex.js"] }), + spawn: ({ command, args, options }) => { + spawned.push({ command, args, wrap: options.wrap }); + return spawnProcess(command, args, options); + }, + }, + }); + // Skip the host-side version probes; they are not session spawns. + Object.assign(client, { + goalsEnabledPromise: Promise.resolve(false), + autoReviewEnabledPromise: Promise.resolve(false), + }); + + await expect( + client.createSession( + { provider: "codex", cwd: "/tmp/codex-wrap" }, + { wrap: ["/nonexistent/launch-wrap-that-does-not-exist", "--flag"] }, + ), + ).rejects.toThrow(/ENOENT/u); + expect(spawned).toEqual([ + { + command: process.execPath, + args: ["codex.js", "app-server"], + wrap: ["/nonexistent/launch-wrap-that-does-not-exist", "--flag"], + }, + ]); + }); }); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 90cdd1cbc6..26f0f2e5bd 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -2492,6 +2492,60 @@ describe("Codex app-server provider", () => { appServer.assertNoErrors(); }); + test.each(["interactive", "history"] as const)( + "spawns a wrapped %s resume through the launch wrap", + async (purpose) => { + const spawned: Array<{ command: string; args: string[]; wrap?: readonly string[] }> = []; + let resumes = 0; + // History reads the archived thread; an interactive resume unarchives it and resumes again. + const appServer = createFakeCodexAppServer({ + "thread/loaded/list": () => ({ data: [] }), + "thread/resume": () => + resumes++ === 0 + ? Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))) + : { thread: { id: "archived-thread-id" } }, + "thread/unarchive": () => ({ thread: { id: "archived-thread-id" } }), + "thread/read": () => ({ thread: { turns: [] } }), + }); + const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, { + appServerProcess: { + resolvePrefix: async () => ({ + command: "/opt/codex/bin/codex", + args: ["--profile", "x"], + }), + spawn: ({ command, args, options }) => { + spawned.push({ command, args, wrap: options.wrap }); + return appServer.child; + }, + }, + }); + const internals = castInternals<{ + goalsEnabledPromise: Promise | null; + autoReviewEnabledPromise: Promise | null; + }>(provider); + internals.goalsEnabledPromise = Promise.resolve(false); + internals.autoReviewEnabledPromise = Promise.resolve(false); + + const session = await provider.resumeSession( + archivedThreadHandle(), + undefined, + { wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] }, + { purpose }, + ); + + expect(spawned.length).toBeGreaterThan(0); + for (const input of spawned) { + expect(input).toEqual({ + command: "/opt/codex/bin/codex", + args: ["--profile", "x", "app-server"], + wrap: ["/opt/sandbox/bin/run", "--profile", "a b"], + }); + } + await session.close(); + appServer.assertNoErrors(); + }, + ); + test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => { const threadRequests: string[] = []; let resumeAttempts = 0; diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 2e9b3ee558..a07c27c1ee 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -8272,6 +8272,7 @@ export class CodexAppServerAgentClient implements AgentClient { environment: Record; goalsEnabled?: boolean; agentId?: string; + wrap?: AgentLaunchContext["wrap"]; }): Promise<() => ChildProcessWithoutNullStreams> { const processPort = this.deps.appServerProcess ?? defaultCodexAppServerProcess; const launchPrefix = await processPort.resolvePrefix({ runtimeSettings: this.runtimeSettings }); @@ -8285,14 +8286,17 @@ export class CodexAppServerAgentClient implements AgentClient { agentId: options.agentId, provider: CODEX_PROVIDER, launchPrefix, + wrap: options.wrap, goalsEnabled: options.goalsEnabled === true, }, "provider.codex.spawn", ); + // Every spawn from this closure, including reconnects and startup retries, carries the wrap. const child = processPort.spawn({ command: launchPrefix.command, args, options: { + wrap: options.wrap, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"], baseEnv: options.environment, @@ -8339,6 +8343,7 @@ export class CodexAppServerAgentClient implements AgentClient { environment, goalsEnabled, agentId: launchContext?.agentId, + wrap: launchContext?.wrap, }); const session = new CodexAppServerAgentSession( sessionConfig, @@ -8376,6 +8381,7 @@ export class CodexAppServerAgentClient implements AgentClient { environment, goalsEnabled, agentId: launchContext?.agentId, + wrap: launchContext?.wrap, }); const session = new CodexAppServerAgentSession( merged, diff --git a/packages/server/src/server/agent/providers/jsonl-rpc-process.ts b/packages/server/src/server/agent/providers/jsonl-rpc-process.ts index ddf85eb316..c37b2a7844 100644 --- a/packages/server/src/server/agent/providers/jsonl-rpc-process.ts +++ b/packages/server/src/server/agent/providers/jsonl-rpc-process.ts @@ -23,6 +23,8 @@ export interface JsonlRpcLaunch { args: string[]; cwd: string; env?: Record; + /** Start the process as `[...wrap, command, ...args]`. */ + wrap?: readonly [string, ...string[]]; } interface JsonlRpcResponse { @@ -64,6 +66,7 @@ function assertChildWithPipes( function spawnJsonlRpcProcess(launch: JsonlRpcLaunch): ChildProcessWithoutNullStreams { const child = spawnProcess(launch.command, launch.args, { + wrap: launch.wrap, cwd: launch.cwd, envOverlay: launch.env, stdio: ["pipe", "pipe", "pipe"], diff --git a/packages/server/src/server/agent/providers/omp/agent.ts b/packages/server/src/server/agent/providers/omp/agent.ts index 458b939f82..b2c7038977 100644 --- a/packages/server/src/server/agent/providers/omp/agent.ts +++ b/packages/server/src/server/agent/providers/omp/agent.ts @@ -433,6 +433,7 @@ function buildResumeStartInput(input: { cwd: input.resumeConfig.cwd, protocolMode: "rpc-ui", env: input.launchContext?.env, + wrap: input.launchContext?.wrap, session: input.sessionFile, thinkingOptionId: normalizeOmpThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined, ...(input.launchMode.modeId ? { modeId: input.launchMode.modeId } : {}), @@ -2356,15 +2357,18 @@ export class OmpAgentClient implements AgentClient { runtimeSession: OmpRuntimeSession, catalog: PaseoToolCatalog | undefined, config: AgentSessionConfig, - launchEnv?: NodeJS.ProcessEnv, + launch: Pick, ): Promise { if (!catalog && !config.mcpServers) { return; } - const bridge = await OmpMcpBridge.connect(config.mcpServers, config.cwd, this.logger, { - ...process.env, - ...this.runtimeSettings?.env, - ...launchEnv, + // Paseo starts stdio MCP servers for OMP, so they run behind the agent's wrap as OMP does. + const bridge = await OmpMcpBridge.connect({ + servers: config.mcpServers, + cwd: config.cwd, + logger: this.logger, + env: { ...process.env, ...this.runtimeSettings?.env, ...launch.env }, + wrap: launch.wrap, }); const router = new OmpHostToolRouter({ runtimeSession, catalog, bridge, logger: this.logger }); try { @@ -2407,6 +2411,7 @@ export class OmpAgentClient implements AgentClient { ...(config.pluginAppendSystemPrompt ?? []), ), env: launchContext?.env, + wrap: launchContext?.wrap, }; const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession( startInput, @@ -2417,7 +2422,7 @@ export class OmpAgentClient implements AgentClient { runtimeSession, launchContext?.paseoTools, config, - startInput.env, + startInput, ); const initialState = await this.restoreFastMode( runtimeSession, @@ -2487,7 +2492,7 @@ export class OmpAgentClient implements AgentClient { runtimeSession, launchContext?.paseoTools, resumeConfig.config, - startInput.env, + startInput, ); const resumedState = await this.applyResumeModel(runtimeSession, resumeConfig.model); const config = { @@ -2566,7 +2571,7 @@ export class OmpAgentClient implements AgentClient { next, launchContext?.paseoTools, config, - startInput.env, + startInput, ); const state = await next.getState(); await this.restoreFastMode(next, config, state); diff --git a/packages/server/src/server/agent/providers/omp/cli-runtime.test.ts b/packages/server/src/server/agent/providers/omp/cli-runtime.test.ts index 4c8a81fe46..b91d5d57a1 100644 --- a/packages/server/src/server/agent/providers/omp/cli-runtime.test.ts +++ b/packages/server/src/server/agent/providers/omp/cli-runtime.test.ts @@ -1,5 +1,8 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { EventEmitter } from "node:events"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; import { PassThrough } from "node:stream"; import pino from "pino"; import { describe, expect, test, vi } from "vitest"; @@ -121,6 +124,54 @@ function withoutRequestId(command: Record): Record { + test("starts OMP behind the session's launch wrap and negotiates through the wrap", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "omp-launch-wrap-")); + try { + const fakeOmp = path.join(root, "fake-omp.mjs"); + await writeFile( + fakeOmp, + [ + 'import { createInterface } from "node:readline";', + 'const ready = { type: "ready", protocolVersion: 1, supportedProtocolVersions: [1], maxFrameBytes: 1048576, maxReassembledFrameBytes: 67108864 };', + 'process.stdout.write(JSON.stringify(ready) + "\\n");', + 'createInterface({ input: process.stdin }).on("line", () => undefined);', + "", + ].join("\n"), + ); + const launcher = path.join(root, "launcher.mjs"); + await writeFile( + launcher, + [ + 'import { spawn } from "node:child_process";', + 'import { writeFileSync } from "node:fs";', + "const [command, ...args] = process.argv.slice(2);", + 'writeFileSync(new URL("./wrapped.json", import.meta.url), JSON.stringify([command, ...args]));', + 'const child = spawn(command, args, { stdio: "inherit" });', + 'child.on("exit", (code) => process.exit(code ?? 1));', + "", + ].join("\n"), + ); + const runtime = new OmpCliRuntime({ + logger: pino({ level: "silent" }), + command: [process.execPath, fakeOmp], + }); + + const session = await runtime.startSession({ + cwd: root, + wrap: [process.execPath, launcher], + }); + try { + expect( + JSON.parse(await readFile(path.join(root, "wrapped.json"), "utf8")).slice(0, 2), + ).toEqual([process.execPath, fakeOmp]); + } finally { + await session.close(); + } + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + test("steer waits for OMP's response and surfaces rejection", async () => { const child = createOmpChild(); let pending: Record | null = null; diff --git a/packages/server/src/server/agent/providers/omp/cli-runtime.ts b/packages/server/src/server/agent/providers/omp/cli-runtime.ts index 5ae9d8f9c4..2f9e42edd7 100644 --- a/packages/server/src/server/agent/providers/omp/cli-runtime.ts +++ b/packages/server/src/server/agent/providers/omp/cli-runtime.ts @@ -83,6 +83,7 @@ export class OmpCliRuntime implements OmpRuntime { args, cwd: launch.cwd, env: launch.env, + wrap: launch.wrap, }; const spawn = this.spawnProcess; const processOptions = { diff --git a/packages/server/src/server/agent/providers/omp/mcp-bridge.ts b/packages/server/src/server/agent/providers/omp/mcp-bridge.ts index f3edac03d4..781def66ac 100644 --- a/packages/server/src/server/agent/providers/omp/mcp-bridge.ts +++ b/packages/server/src/server/agent/providers/omp/mcp-bridge.ts @@ -22,12 +22,15 @@ export class OmpMcpBridge { private readonly connections: McpClientConnection[] = []; private closed = false; - static async connect( - servers: Record | undefined, - cwd: string, - logger: Logger, - env: NodeJS.ProcessEnv, - ): Promise { + static async connect(input: { + servers: Record | undefined; + cwd: string; + logger: Logger; + env: NodeJS.ProcessEnv; + /** Start each stdio server as `[...wrap, command, ...args]`. */ + wrap?: readonly [string, ...string[]]; + }): Promise { + const { servers, cwd, logger, env, wrap } = input; const bridge = new OmpMcpBridge(); const connections = await Promise.all( Object.entries(servers ?? {}).map(async ([serverName, config]) => { @@ -36,6 +39,7 @@ export class OmpMcpBridge { config, cwd, env, + wrap, clientName: "paseo-omp-mcp", }); return { serverName, connection }; diff --git a/packages/server/src/server/agent/providers/omp/runtime.ts b/packages/server/src/server/agent/providers/omp/runtime.ts index 523595ed07..2ed3fea4f0 100644 --- a/packages/server/src/server/agent/providers/omp/runtime.ts +++ b/packages/server/src/server/agent/providers/omp/runtime.ts @@ -18,6 +18,8 @@ export interface OmpRuntimeLaunch { cwd: string; argv: string[]; env?: Record; + /** Start OMP as `[...wrap, ...argv]`. */ + wrap?: readonly [string, ...string[]]; protocolMode?: "rpc" | "rpc-ui"; model?: string; thinkingOptionId?: string; @@ -32,6 +34,8 @@ export interface OmpStartSessionInput { cwd: string; signal?: AbortSignal; env?: Record; + /** The agent's launch wrap; every OMP process started for the agent runs behind it. */ + wrap?: readonly [string, ...string[]]; protocolMode?: "rpc" | "rpc-ui"; model?: string; thinkingOptionId?: string; @@ -114,6 +118,7 @@ export function buildOmpLaunch(input: { ...input.session.env, } : undefined, + wrap: input.session.wrap, model: input.session.model, thinkingOptionId: input.session.thinkingOptionId, protocolMode, diff --git a/packages/server/src/server/agent/providers/opencode-agent.test.ts b/packages/server/src/server/agent/providers/opencode-agent.test.ts index c0c16a15d0..b7a958e1b0 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.test.ts @@ -4563,6 +4563,47 @@ describe("OpenCode persisted sessions", () => { ]); }); + test("importSession reads a wrapped session on a server started behind the wrap", async () => { + const runtime = new TestOpenCodeHarness(); + const metadataClient = new TestOpenCodeClient(); + const resumedClient = new TestOpenCodeClient(); + const cwd = "/workspace/repo"; + const selectedSession = { + id: "ses_selected", + directory: cwd, + title: "Selected session", + time: { created: 2000, updated: 3000 }, + }; + metadataClient.sessionGetResponse = { data: selectedSession }; + metadataClient.sessionMessagesResponse = { data: [] }; + resumedClient.sessionGetResponse = { data: selectedSession }; + resumedClient.sessionMessagesResponse = { data: [] }; + runtime.enqueueClient(metadataClient); + runtime.enqueueClient(resumedClient); + const client = new OpenCodeAgentClient(createTestLogger(), undefined, { + serverManager: runtime, + createClient: runtime.createClient, + }); + const wrap = ["/opt/sandbox/bin/run", "--profile", "import"] as const; + + const imported = await client.importSession( + { providerHandleId: "ses_selected", cwd }, + { + config: { provider: "opencode", cwd }, + storedConfig: { provider: "opencode", cwd }, + launchContext: { env: { PASEO_AGENT_ID: "imported" }, wrap }, + }, + ); + await imported.session.close(); + + expect(runtime.acquisitions.map((acquisition) => [acquisition.kind, acquisition.wrap])).toEqual( + [ + ["dedicated", wrap], + ["dedicated", wrap], + ], + ); + }); + test("listImportableSessions matches Windows cwd paths with forward slashes", async () => { const runtime = new TestOpenCodeHarness(); const openCodeClient = new TestOpenCodeClient(); @@ -4749,6 +4790,52 @@ describe("OpenCode provider subagent contract", () => { ]); }); + test("resumes a wrapped child on its own server behind the wrap, not the parent's server", async () => { + const runtime = new TestOpenCodeHarness(); + const parentClient = new TestOpenCodeClient(); + const childClient = new TestOpenCodeClient(); + parentClient.sessionCreateResponse = { data: { id: "ses_parent_wrapped" } }; + runtime.enqueueClient(parentClient); + runtime.enqueueClient(childClient); + const client = new OpenCodeAgentClient(createTestLogger(), undefined, { + serverManager: runtime, + createClient: runtime.createClient, + }); + const parent = await client.createSession( + { provider: "opencode", cwd: "/workspace/repo" }, + { env: { PASEO_AGENT_ID: "parent-agent" } }, + ); + parentClient.emitEvent({ + type: "session.created", + properties: { + info: { id: "ses_child_wrapped", parentID: "ses_parent_wrapped", title: "Live child" }, + }, + }); + await Promise.resolve(); + await Promise.resolve(); + const wrap = ["/opt/sandbox/bin/run", "--profile", "child"] as const; + + const child = await client.resumeSession( + { + provider: "opencode", + sessionId: "ses_child_wrapped", + nativeHandle: "ses_child_wrapped", + metadata: { cwd: "/workspace/repo" }, + }, + undefined, + { env: { PASEO_AGENT_ID: "child-agent" }, wrap }, + ); + await child.close(); + await parent.close(); + + expect(runtime.acquisitions.map((acquisition) => [acquisition.kind, acquisition.wrap])).toEqual( + [ + ["dedicated", undefined], + ["dedicated", wrap], + ], + ); + }); + test("synthesizes an autonomous turn for adopted child timeline events", async () => { const { child, childClient, parent } = await createAdoptedChildSession(); const completed = createTestDeferred(); diff --git a/packages/server/src/server/agent/providers/opencode-agent.ts b/packages/server/src/server/agent/providers/opencode-agent.ts index daf3156e30..c57c7678a9 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.ts @@ -79,6 +79,7 @@ import { } from "../provider-launch-config.js"; import { withTimeout } from "../../../utils/promise-timeout.js"; import { execCommand } from "../../../utils/spawn.js"; +import type { LaunchWrap } from "../../../utils/launch-wrap.js"; import { mapOpencodeToolCall } from "./opencode/tool-call-mapper.js"; import { OPENCODE_EVENT_STREAM_READY_TIMEOUT_MS, @@ -1537,7 +1538,10 @@ export class OpenCodeAgentClient implements AgentClient { cwd, }; const openCodeConfig = this.assertConfig(config); - const registeredServerUrl = getOpenCodeChildSessionServerUrl(handle.sessionId); + // A registered parent server runs outside this launch's wrap, so a wrapped resume starts its own. + const registeredServerUrl = launchContext?.wrap + ? undefined + : getOpenCodeChildSessionServerUrl(handle.sessionId); const registeredAcquisition = registeredServerUrl ? this.serverManager.acquireExisting(registeredServerUrl) : null; @@ -1617,14 +1621,25 @@ export class OpenCodeAgentClient implements AgentClient { config: OpenCodeAgentConfig, launchContext?: AgentLaunchContext, ): Promise { - if (!this.bridge || requiresDedicatedOpenCodeServer(config, launchContext)) { - return launchContext?.env - ? this.serverManager.acquireDedicated(launchContext.env) - : this.serverManager.acquireCurrent(); + if (launchContext?.wrap) + return this.acquireWrappedServer(launchContext.wrap, launchContext.env); + if ( + launchContext?.env && + (!this.bridge || requiresDedicatedOpenCodeServer(config, launchContext)) + ) { + return this.serverManager.acquireDedicated({ env: launchContext.env }); } return this.serverManager.acquireCurrent(); } + /** A wrapped session gets its own server, so it never shares one that runs outside its wrap. */ + private acquireWrappedServer( + wrap: LaunchWrap, + env: Record = {}, + ): Promise { + return this.serverManager.acquireDedicated({ env, wrap }); + } + private bindBridgeSession( sessionId: string, launchContext?: AgentLaunchContext, @@ -1712,7 +1727,11 @@ export class OpenCodeAgentClient implements AgentClient { } async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) { - const acquisition = await this.serverManager.acquireCurrent(); + const wrap = context.launchContext?.wrap; + // A wrapped import reads the session behind its wrap too, so it never starts a server outside it. + const acquisition = wrap + ? await this.acquireWrappedServer(wrap, context.launchContext?.env) + : await this.serverManager.acquireCurrent(); const { url } = acquisition.server; const client = this.createOpenCodeClient({ baseUrl: url, diff --git a/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts b/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts index 6cb15ccb6d..824ec0c2ab 100644 --- a/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts +++ b/packages/server/src/server/agent/providers/opencode-bridge-adapter.test.ts @@ -115,6 +115,44 @@ describe("OpenCode bridge adapter", () => { await customEnv.close(); await customMcp.close(); }); + + test("starts a wrapped session on its own server behind the wrap", async () => { + const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-opencode-adapter-")); + const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() }); + await bridge.start(); + cleanups.push(async () => { + await bridge.close(); + await rm(paseoHome, { recursive: true, force: true }); + }); + const runtime = new TestOpenCodeHarness(); + const wrappedClient = new TestOpenCodeClient(); + const sharedClient = new TestOpenCodeClient(); + wrappedClient.sessionCreateResponse = { data: { id: "ses_wrapped" } }; + sharedClient.sessionCreateResponse = { data: { id: "ses_shared" } }; + runtime.enqueueClient(wrappedClient); + runtime.enqueueClient(sharedClient); + const client = new OpenCodeAgentClient(createTestLogger(), undefined, { + serverManager: runtime, + createClient: runtime.createClient, + bridge, + }); + + const wrapped = await client.createSession( + { provider: "opencode", cwd: "/workspace/one" }, + { env: { PASEO_AGENT_ID: "one" }, wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] }, + ); + const shared = await client.createSession( + { provider: "opencode", cwd: "/workspace/two" }, + { env: { PASEO_AGENT_ID: "two" } }, + ); + + expect(runtime.acquisitions.map(({ kind, wrap }) => ({ kind, wrap }))).toEqual([ + { kind: "dedicated", wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] }, + { kind: "current", wrap: undefined }, + ]); + await wrapped.close(); + await shared.close(); + }); }); async function readBridgeContext(bridge: OpenCodeBridge, sessionId: string): Promise { diff --git a/packages/server/src/server/agent/providers/opencode-server-manager.test.ts b/packages/server/src/server/agent/providers/opencode-server-manager.test.ts index 91eb9d3d88..b8ce07e8b2 100644 --- a/packages/server/src/server/agent/providers/opencode-server-manager.test.ts +++ b/packages/server/src/server/agent/providers/opencode-server-manager.test.ts @@ -296,7 +296,7 @@ describe("OpenCodeServerManager generations", () => { runtime.processForPort(4473).announceListening(); const currentAcquisition = await currentStart; - const dedicatedStart = manager.acquireDedicated({ TEST_ENV: "custom" }); + const dedicatedStart = manager.acquireDedicated({ env: { TEST_ENV: "custom" } }); await runtime.settle(); await currentAcquisition.release(); @@ -311,10 +311,29 @@ describe("OpenCodeServerManager generations", () => { expect(runtime.terminatedPorts).toEqual([4473, 4474]); }); + test("a dedicated server starts behind its session's wrap and the shared server does not", async () => { + const { manager, runtime } = createTestManager([4477, 4478]); + + const shared = await manager.acquireCurrent(); + const wrapped = await manager.acquireDedicated({ + env: { PASEO_AGENT_ID: "wrapped" }, + wrap: ["/opt/sandbox/bin/run", "--profile", "a b"], + }); + + expect(runtime.spawnCalls.map(({ args, options }) => ({ args, wrap: options.wrap }))).toEqual([ + { args: ["serve", "--port", "4477"], wrap: undefined }, + { args: ["serve", "--port", "4478"], wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] }, + ]); + await shared.release(); + await wrapped.release(); + }); + test("acquireExisting keeps a retired dedicated server alive until every reference releases", async () => { const { manager, runtime } = createTestManager([4475]); - const dedicatedAcquisition = await manager.acquireDedicated({ PASEO_AGENT_ID: "parent" }); + const dedicatedAcquisition = await manager.acquireDedicated({ + env: { PASEO_AGENT_ID: "parent" }, + }); const existingAcquisition = manager.acquireExisting(dedicatedAcquisition.server.url); expect(existingAcquisition?.server.url).toBe("http://127.0.0.1:4475"); @@ -329,7 +348,7 @@ describe("OpenCodeServerManager generations", () => { test("acquireExisting returns null for unknown or dead server urls", async () => { const { manager, runtime } = createTestManager([4476]); - const acquisition = await manager.acquireDedicated({ PASEO_AGENT_ID: "parent" }); + const acquisition = await manager.acquireDedicated({ env: { PASEO_AGENT_ID: "parent" } }); const url = acquisition.server.url; expect(manager.acquireExisting("http://127.0.0.1:9999")).toBe(null); diff --git a/packages/server/src/server/agent/providers/opencode/server-manager.ts b/packages/server/src/server/agent/providers/opencode/server-manager.ts index 9401ca889b..0fcb2c8d40 100644 --- a/packages/server/src/server/agent/providers/opencode/server-manager.ts +++ b/packages/server/src/server/agent/providers/opencode/server-manager.ts @@ -7,6 +7,7 @@ import path from "node:path"; import type { Logger } from "pino"; import { findExecutable } from "../../../../executable-resolution/executable-resolution.js"; +import type { LaunchWrap } from "../../../../utils/launch-wrap.js"; import { spawnProcess, type SpawnProcessOptions } from "../../../../utils/spawn.js"; import { terminateWithTreeKill, type ProcessTerminator } from "../../../../utils/tree-kill.js"; import type { ManagedProcessRegistry } from "../../../managed-processes/managed-processes.js"; @@ -36,10 +37,16 @@ export interface OpenCodeServerAcquisition { release: () => Promise; } +/** How a session's own server starts: the session's environment, behind the session's wrap. */ +export interface OpenCodeDedicatedLaunch { + env: Record; + wrap?: LaunchWrap; +} + export interface OpenCodeServerManagerLike { acquireCurrent(signal?: AbortSignal): Promise; acquireNew(signal?: AbortSignal): Promise; - acquireDedicated(env: Record): Promise; + acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise; acquireExisting(url: string): OpenCodeServerAcquisition | null; shutdown(): Promise; } @@ -180,8 +187,8 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike { return this.acquireServer(server); } - async acquireDedicated(env: Record): Promise { - const server = await this.startServer({ launchEnv: env, epoch: this.epoch }); + async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise { + const server = await this.startServer({ launch, epoch: this.epoch }); server.retired = true; this.retiredServers.add(server); const acquisition = this.acquireServer(server); @@ -325,7 +332,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike { } private startServer(options: { - launchEnv?: Record; + launch?: OpenCodeDedicatedLaunch; epoch: number; }): Promise { const start = this.spawnServer(options); @@ -336,10 +343,10 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike { } private async spawnServer(options: { - launchEnv?: Record; + launch?: OpenCodeDedicatedLaunch; epoch: number; }): Promise { - const { launchEnv } = options; + const launchEnv = options.launch?.env; const port = await this.portAllocator(); const url = `http://127.0.0.1:${port}`; const launchPrefix = await this.resolveCommandPrefix(); @@ -370,6 +377,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike { detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], baseEnv: environment, + wrap: options.launch?.wrap, }); const managedProcessRecord = this.recordManagedServerProcess({ process: serverProcess, @@ -404,7 +412,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike { managedProcessRecord, }; this.logger.info( - { ...generationLogContext(server), dedicated: launchEnv !== undefined }, + { ...generationLogContext(server), dedicated: options.launch !== undefined }, "OpenCode server generation started", ); void managedProcessRecord.then((record) => { diff --git a/packages/server/src/server/agent/providers/opencode/test-server-manager.ts b/packages/server/src/server/agent/providers/opencode/test-server-manager.ts index aa8e644a10..3f3ab7910c 100644 --- a/packages/server/src/server/agent/providers/opencode/test-server-manager.ts +++ b/packages/server/src/server/agent/providers/opencode/test-server-manager.ts @@ -1,4 +1,8 @@ -import type { OpenCodeServerAcquisition, OpenCodeServerManagerLike } from "./server-manager.js"; +import type { + OpenCodeDedicatedLaunch, + OpenCodeServerAcquisition, + OpenCodeServerManagerLike, +} from "./server-manager.js"; const events = { ready: async () => undefined, @@ -24,8 +28,8 @@ export class TestOpenCodeServerManager implements OpenCodeServerManagerLike { return this.recordAcquisition({ kind: "new" }); } - async acquireDedicated(env: Record): Promise { - return this.recordAcquisition({ kind: "dedicated", env }); + async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise { + return this.recordAcquisition({ kind: "dedicated", env: launch.env }); } acquireExisting(url: string): OpenCodeServerAcquisition | null { diff --git a/packages/server/src/server/agent/providers/opencode/test-utils/test-opencode-harness.ts b/packages/server/src/server/agent/providers/opencode/test-utils/test-opencode-harness.ts index f9c1683a48..82ab1b1a6f 100644 --- a/packages/server/src/server/agent/providers/opencode/test-utils/test-opencode-harness.ts +++ b/packages/server/src/server/agent/providers/opencode/test-utils/test-opencode-harness.ts @@ -1,7 +1,11 @@ import type { OpencodeClient } from "@opencode-ai/sdk/v2/client"; import type { OpenCodeEventSourceInput } from "../event-consumer.js"; -import type { OpenCodeServerAcquisition, OpenCodeServerManagerLike } from "../server-manager.js"; +import type { + OpenCodeDedicatedLaunch, + OpenCodeServerAcquisition, + OpenCodeServerManagerLike, +} from "../server-manager.js"; interface OpenCodeResponse { data?: unknown; @@ -13,6 +17,7 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike { readonly acquisitions: Array<{ kind: "current" | "new" | "dedicated" | "existing"; env?: Record; + wrap?: OpenCodeDedicatedLaunch["wrap"]; url?: string; releaseCount: number; }> = []; @@ -51,8 +56,8 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike { return this.recordAcquisition({ kind: "new" }); } - async acquireDedicated(env: Record): Promise { - return this.recordAcquisition({ kind: "dedicated", env }); + async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise { + return this.recordAcquisition({ kind: "dedicated", env: launch.env, wrap: launch.wrap }); } acquireExisting(url: string): OpenCodeServerAcquisition | null { @@ -62,12 +67,14 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike { private recordAcquisition(input: { kind: "current" | "new" | "dedicated" | "existing"; env?: Record; + wrap?: OpenCodeDedicatedLaunch["wrap"]; url?: string; }): OpenCodeServerAcquisition { const acquisition = { kind: input.kind, releaseCount: 0, ...(input.env ? { env: input.env } : {}), + ...(input.wrap ? { wrap: input.wrap } : {}), ...(input.url ? { url: input.url } : {}), }; this.acquisitions.push(acquisition); diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts index 895711907e..8094c8aa4b 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts @@ -6,6 +6,7 @@ import { describe, expect, test } from "vitest"; import { createTestLogger } from "../../../../../test-utils/test-logger.js"; import type { AgentStreamEvent } from "../../../agent-sdk-types.js"; import { ProviderSubagentStore } from "../../../provider-subagents/store.js"; +import type { V2RuntimeAcquireOptions } from "./runtime.js"; import { OpenCodeV2AgentClient } from "./agent.js"; import { V2Harness } from "../test-utils/v2-harness.js"; import type { V2Api } from "./api.js"; @@ -1270,6 +1271,72 @@ describe("OpenCode v2 session lifecycle", () => { } }); + test("asks the runtime for a server behind the wrap and the launch environment when creating and resuming", async () => { + const servers = [new V2Harness(), new V2Harness()]; + const requests: unknown[] = []; + const runtime = { + acquire: async (input?: V2RuntimeAcquireOptions) => { + requests.push(input?.dedicated); + const server = servers[requests.length - 1]; + if (!server) throw new Error("No OpenCode test server left"); + return server.connection; + }, + shutdown: async () => undefined, + }; + const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime }); + const wrap = ["/opt/sandbox/bin/run", "--profile", "a b"] as const; + const env = { SANDBOX_PROFILE: "agent" }; + const created = await client.createSession( + { provider: "opencode", cwd: "/tmp/project" }, + { agentId: "agent", wrap, env }, + ); + try { + // The created session's connection is live, and a wrapped resume still asks for its own. + const resumed = await client.resumeSession( + { + provider: "opencode", + sessionId: "session", + nativeHandle: "session", + metadata: { cwd: "/tmp/project" }, + }, + undefined, + { agentId: "agent", wrap, env }, + { purpose: "history" }, + ); + await resumed.close(); + expect(requests).toEqual([ + { wrap, env }, + { wrap, env }, + ]); + } finally { + await created.close(); + } + }); + + test("imports a wrapped session through one wrapped server, from the first session lookup", async () => { + const server = new V2Harness(); + // Import restores the session's agent. + server.api.session.switchAgent = async () => undefined; + const requests: unknown[] = []; + const runtime = { + acquire: async (input?: V2RuntimeAcquireOptions) => { + requests.push(input?.dedicated); + return server.connection; + }, + shutdown: async () => undefined, + }; + const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime }); + const wrap = ["/opt/sandbox/bin/run", "--profile", "import"] as const; + const env = { SANDBOX_PROFILE: "import" }; + const config = { provider: "opencode", cwd: "/tmp/project" } as const; + const imported = await client.importSession( + { providerHandleId: "session", cwd: "/tmp/project" }, + { config, storedConfig: config, launchContext: { agentId: "agent", wrap, env } }, + ); + await imported.session.close(); + expect(requests).toEqual([{ wrap, env }]); + }); + test("rejects MCP servers without the Paseo bridge before creating an OpenCode session", async () => { const harness = new V2Harness(); const client = new OpenCodeV2AgentClient({ diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.ts index 175c462a8e..53cb0c2837 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.ts @@ -36,10 +36,23 @@ import { importSessionFromPersistence } from "../../../provider-session-import.j import type { OpenCodeBridge } from "../bridge.js"; import { resolveOpenCodeHomeDir } from "../paths.js"; -import { V2Runtime, type V2Connection } from "./runtime.js"; +import { V2Runtime, type V2Connection, type V2DedicatedLaunch } from "./runtime.js"; import type { OpenCodeServiceSelection } from "./service-selection.js"; import { modelRef, modesFromV2, modelsFromV2 } from "./mapping.js"; +/** + * A wrapped launch gets a server of its own, started behind the wrap with the launch's environment, + * so it never shares a server that runs outside its wrap. + */ +function dedicatedLaunch(launch: AgentLaunchContext | undefined): V2DedicatedLaunch | undefined { + return launch?.wrap ? { wrap: launch.wrap, env: launch.env } : undefined; +} +interface ResumeTarget { + handle: AgentPersistenceHandle; + overrides: Partial | undefined; + launch: AgentLaunchContext | undefined; + historyOnly: boolean; +} interface PreparedLaunch { launch: AgentLaunchContext | undefined; /** The complete shell environment, when the launch sets one. */ @@ -116,7 +129,7 @@ export class OpenCodeV2AgentClient implements AgentClient { ): Promise { const prepared = await this.prepareLaunch(config, launch, false); try { - const connection = await this.runtime.acquire(); + const connection = await this.runtime.acquire({ dedicated: dedicatedLaunch(launch) }); try { const info = await connection.client.session.create({ location: { directory: config.cwd }, @@ -146,6 +159,21 @@ export class OpenCodeV2AgentClient implements AgentClient { overrides?: Partial, launch?: AgentLaunchContext, options?: AgentResumeSessionOptions, + ): Promise { + return this.resumeOn( + async () => { + // A live connection may run outside this launch's wrap, so a wrapped resume starts its own. + const live = launch?.wrap + ? undefined + : this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain(); + return live ?? (await this.runtime.acquire({ dedicated: dedicatedLaunch(launch) })); + }, + { handle, overrides, launch, historyOnly: options?.purpose === "history" }, + ); + } + private async resumeOn( + connect: () => Promise, + { handle, overrides, launch, historyOnly }: ResumeTarget, ): Promise { const cwd = overrides?.cwd ?? handle.metadata?.cwd; if (typeof cwd !== "string") @@ -156,12 +184,9 @@ export class OpenCodeV2AgentClient implements AgentClient { provider: "opencode", cwd, }; - const historyOnly = options?.purpose === "history"; const prepared = await this.prepareLaunch(config, launch, historyOnly); try { - const connection = - this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain() ?? - (await this.runtime.acquire()); + const connection = await connect(); try { const info = await connection.client.session.get({ sessionID: handle.nativeHandle ?? handle.sessionId, @@ -197,6 +222,7 @@ export class OpenCodeV2AgentClient implements AgentClient { servers, cwd: config.cwd, env: environment ?? createProviderEnv({ runtimeSettings: this.options.settings }), + wrap: launch?.wrap, }); return { launch, environment, mcp }; } @@ -257,7 +283,7 @@ export class OpenCodeV2AgentClient implements AgentClient { mcp, unbind: releaseBindings, bindChild, - acquire: () => this.runtime.acquire(), + acquire: () => this.runtime.acquire({ dedicated: dedicatedLaunch(launch) }), moved, historyOnly, }); @@ -312,14 +338,24 @@ export class OpenCodeV2AgentClient implements AgentClient { } } async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) { - const connection = await this.runtime.acquire(); + // The lookup and the resume share one connection, so a wrapped import never starts a server + // outside its wrap. + const connection = await this.runtime.acquire({ + dedicated: dedicatedLaunch(context.launchContext), + }); try { const info = await connection.client.session.get({ sessionID: input.providerHandleId }); return await importSessionFromPersistence({ provider: "opencode", request: input, context, - resumeSession: this.resumeSession.bind(this), + resumeSession: (handle, overrides, launch) => + this.resumeOn(async () => connection.retain(), { + handle, + overrides, + launch, + historyOnly: false, + }), config: { title: info.title, modeId: info.agent, diff --git a/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts b/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts index d60535889b..fdbdd9b3c8 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/owned-runtime.test.ts @@ -75,3 +75,76 @@ test("reports a bridge port change that has not been applied", async () => { await rm(root, { recursive: true, force: true }); } }); + +test("a wrapped caller gets its own helper behind the wrap, and other callers keep the shared one", async () => { + const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-wrap-")); + const script = path.join(root, "server.cjs"); + const launcher = path.join(root, "launcher.cjs"); + const record = path.join(root, "argv.json"); + await writeFile( + script, + ` + const http = require('node:http'); + const server = http.createServer((_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ version: '2.0.10', pid: process.pid, urls: [], paths: { tmp: '/tmp' } })); + }); + server.listen(0, '127.0.0.1', () => console.log('server listening on http://127.0.0.1:' + server.address().port)); + `, + ); + await writeFile( + launcher, + ` + const [, , ...argv] = process.argv; + // A launcher that needs its profile from the open hook's environment. + if (!process.env.SANDBOX_PROFILE) process.exit(17); + require('node:fs').writeFileSync(${JSON.stringify(record)}, JSON.stringify({ argv, profile: process.env.SANDBOX_PROFILE })); + const child = require('node:child_process').spawn(argv[1], argv.slice(2), { stdio: 'inherit' }); + child.on('exit', (code) => process.exit(code ?? 1)); + `, + ); + const runtime = new V2Runtime({ + logger: createTestLogger(), + selection: { kind: "owned" }, + settings: { command: { mode: "replace", argv: [process.execPath, script] } }, + }); + try { + const shared = await runtime.acquire(); + const wrapped = await runtime.acquire({ + dedicated: { + wrap: [process.execPath, launcher, "--profile"], + env: { SANDBOX_PROFILE: "agent" }, + }, + }); + const sharedAgain = await runtime.acquire(); + + const sharedPid = (await shared.client.server.info()).pid; + expect((await wrapped.client.server.info()).pid).not.toBe(sharedPid); + expect((await sharedAgain.client.server.info()).pid).toBe(sharedPid); + const launched = JSON.parse(await readFile(record, "utf8")); + expect(launched.profile).toBe("agent"); + expect(launched.argv.slice(0, 4)).toEqual(["--profile", process.execPath, script, "serve"]); + + await wrapped.release(); + await expect(wrapped.exited).resolves.toBeInstanceOf(Error); + await shared.release(); + await sharedAgain.release(); + } finally { + await runtime.shutdown(); + await rm(root, { recursive: true, force: true }); + } +}, 15_000); + +test("refuses to wrap a configured existing server", async () => { + const runtime = new V2Runtime({ + logger: createTestLogger(), + selection: { kind: "explicit", server: { url: "http://127.0.0.1:1" } }, + }); + try { + await expect( + runtime.acquire({ dedicated: { wrap: ["/opt/sandbox/bin/run"], env: {} } }), + ).rejects.toThrow("cannot start it behind a launch wrap"); + } finally { + await runtime.shutdown(); + } +}); diff --git a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts index 567d70f6a3..06f4ef45e2 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts @@ -5,6 +5,7 @@ import type { V2Api } from "./api.js"; import { randomBytes } from "node:crypto"; import { mkdir } from "node:fs/promises"; import type { Logger } from "pino"; +import type { LaunchWrap } from "../../../../../utils/launch-wrap.js"; import { spawnProcess } from "../../../../../utils/spawn.js"; import { terminateWithTreeKill } from "../../../../../utils/tree-kill.js"; import { @@ -59,9 +60,17 @@ export interface V2RuntimeOptions { bridge?: OpenCodeBridge; } +/** A server started for one caller alone, behind its wrap and with its launch environment. */ +export interface V2DedicatedLaunch { + wrap: LaunchWrap; + env: Record | undefined; +} + export interface V2RuntimeAcquireOptions { fresh?: boolean; signal?: AbortSignal; + /** Start a server for this caller alone. Other callers never share it. */ + dedicated?: V2DedicatedLaunch; } // The runtime owns a credential for each subprocess; sessions only receive its authenticated client. @@ -92,8 +101,9 @@ export class V2Runtime { this.assertBridgePort(); const selection = await raceProviderRefreshAbort(input.signal, this.selection); if (selection.kind === "explicit") this.assertExplicitConfiguration(); - this.current ??= this.startTracked(); - const pending = this.current; + const pending = input.dedicated + ? this.startTracked(input.dedicated) + : (this.current ??= this.startTracked()); let generation: Generation; try { generation = await raceProviderRefreshAbort(input.signal, pending); @@ -179,8 +189,8 @@ export class V2Runtime { this.current = null; } - private startTracked(): Promise { - const pending = this.start(); + private startTracked(dedicated?: V2DedicatedLaunch): Promise { + const pending = this.start(dedicated); this.starts.add(pending); void pending.then( (generation) => @@ -197,9 +207,14 @@ export class V2Runtime { return pending; } - private async start(): Promise { + private async start(dedicated: V2DedicatedLaunch | undefined): Promise { const selection = await this.selection; - if (selection.kind !== "owned") { + if (dedicated && selection.kind === "explicit") + throw new Error( + "OpenCode is configured to use an existing server, so Paseo cannot start it behind a launch wrap", + ); + // A discovered server is only a preference; a wrapped caller gets a server Paseo starts. + if (selection.kind !== "owned" && !dedicated) { const generation: Generation = { ...(await connectSharedService(selection, this.options)), users: 0, @@ -220,6 +235,7 @@ export class V2Runtime { const configured = { ...(inheritedConfig ? { OPENCODE_CONFIG_CONTENT: inheritedConfig } : {}), ...settings?.env, + ...dedicated?.env, }; const bridge = this.options.bridge; const plugin = bridge @@ -240,6 +256,7 @@ export class V2Runtime { cwd, detached: globalThis.process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], + wrap: dedicated?.wrap, ...createProviderEnvSpec({ runtimeSettings: settings, overlays: [{ ...decorated, OPENCODE_PASSWORD: password }], diff --git a/packages/server/src/server/agent/providers/opencode/v2/session-mcp.ts b/packages/server/src/server/agent/providers/opencode/v2/session-mcp.ts index 508d41f35f..3804721da3 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/session-mcp.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/session-mcp.ts @@ -1,5 +1,6 @@ import type { McpServerConfig } from "../../../agent-sdk-types.js"; import { connectMcpServer, type McpClientConnection } from "../../../mcp-client-connection.js"; +import type { LaunchWrap } from "../../../../../utils/launch-wrap.js"; import type { PaseoToolResult } from "../../../tools/types.js"; import type { OpenCodeBridgeMcpTool } from "../bridge.js"; @@ -22,6 +23,8 @@ interface ConnectSessionMcpInput { cwd: string; /** The agent's complete launch environment, which stdio servers inherit. */ env: NodeJS.ProcessEnv; + /** The agent's wrap, which stdio servers run behind. */ + wrap?: LaunchWrap; } /** @@ -44,6 +47,7 @@ export class SessionMcp { config, cwd: input.cwd, env: input.env, + wrap: input.wrap, clientName: "paseo-opencode", }); return { name, connection }; diff --git a/packages/server/src/server/agent/providers/pi/agent.ts b/packages/server/src/server/agent/providers/pi/agent.ts index b068ed106f..fab34f7063 100644 --- a/packages/server/src/server/agent/providers/pi/agent.ts +++ b/packages/server/src/server/agent/providers/pi/agent.ts @@ -498,6 +498,7 @@ function buildResumeStartInput(input: { return { cwd: input.processCwd, env: input.launchContext?.env, + wrap: input.launchContext?.wrap, session: input.sessionFile, thinkingOptionId: normalizePiThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined, mcpConfigPath: input.mcpConfigFile?.path, @@ -2660,11 +2661,13 @@ export class PiRpcAgentClient implements AgentClient { ): Promise { const providerOptions = PiProviderOptionsSchema.parse(config.providerOptions ?? {}); const runtime = this.resolveRuntime(providerOptions.rpcTimeoutMs); - const mcpEnv = { - ...this.runtimeSettings?.env, - ...launchContext?.env, - }; - const mcp = await this.prepareMcpInjection(config.cwd, config.mcpServers, mcpEnv, runtime); + const { env, wrap } = launchContext ?? {}; + const mcpEnv = { ...this.runtimeSettings?.env, ...env }; + const mcp = await this.prepareMcpInjection( + { cwd: config.cwd, env: mcpEnv, wrap }, + config.mcpServers, + runtime, + ); const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null; const paseoExtension = createPiPaseoExtensionFile({ systemPrompt: composeAgentSystemPrompt(config), @@ -2677,7 +2680,8 @@ export class PiRpcAgentClient implements AgentClient { model: config.model, thinkingOptionId: normalizePiThinkingOption(config.thinkingOptionId) ?? undefined, noSession: config.internal === true, - env: launchContext?.env, + env, + wrap, mcpConfigPath: mcpConfigFile?.path, extensionPaths: paseoExtension ? [paseoExtension.path] : undefined, }); @@ -2729,9 +2733,8 @@ export class PiRpcAgentClient implements AgentClient { ...launchContext?.env, }; const mcp = await this.prepareMcpInjection( - processCwd, + { cwd: processCwd, env: mcpEnv, wrap: launchContext?.wrap }, resumeConfig.config.mcpServers, - mcpEnv, runtime, ); const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null; @@ -2930,16 +2933,17 @@ export class PiRpcAgentClient implements AgentClient { return this.runtime ?? createRuntime(this.logger, this.runtimeSettings, rpcTimeoutMs); } + /** `probe` starts the Pi process that detects MCP support, as the agent's own process starts. */ private async prepareMcpInjection( - cwd: string, + probe: Pick, servers: Record | undefined, - env: Record | undefined, runtime: PiRuntime, ): Promise { if (!servers || Object.keys(servers).length === 0) { return null; } - const mcpSupport = await this.detectMcpSupport(cwd, env, runtime); + const { env } = probe; + const mcpSupport = await this.detectMcpSupport(probe, runtime); if (mcpSupport === "builtin") { return { kind: "builtin", servers: toPiBuiltinMcpServers(servers) }; } @@ -2953,12 +2957,11 @@ export class PiRpcAgentClient implements AgentClient { } private async detectMcpSupport( - cwd: string, - env: Record | undefined, + probe: Pick, runtime: PiRuntime, ): Promise { - const runtimeSession = await runtime.startSession({ cwd, env }).catch((error) => { - this.logger.debug({ err: error, cwd }, "Pi MCP probe failed to start"); + const runtimeSession = await runtime.startSession(probe).catch((error) => { + this.logger.debug({ err: error, cwd: probe.cwd }, "Pi MCP probe failed to start"); return null; }); if (!runtimeSession) { @@ -2971,7 +2974,7 @@ export class PiRpcAgentClient implements AgentClient { } return commands.some(isPiBuiltinMcpCommand) ? "builtin" : null; } catch (error) { - this.logger.debug({ err: error, cwd }, "Pi MCP probe failed"); + this.logger.debug({ err: error, cwd: probe.cwd }, "Pi MCP probe failed"); return null; } finally { await runtimeSession.close().catch(() => undefined); diff --git a/packages/server/src/server/agent/providers/pi/cli-runtime.test.ts b/packages/server/src/server/agent/providers/pi/cli-runtime.test.ts index 8a838d74d9..fabaf530ca 100644 --- a/packages/server/src/server/agent/providers/pi/cli-runtime.test.ts +++ b/packages/server/src/server/agent/providers/pi/cli-runtime.test.ts @@ -1,4 +1,5 @@ import { mkdir, mkdtemp, writeFile, readFile, rm } from "node:fs/promises"; +import os from "node:os"; import path from "node:path"; import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { EventEmitter } from "node:events"; @@ -167,6 +168,63 @@ describe("PiCliRuntime", () => { ]); }); + test("starts Pi behind the session's launch wrap and talks to it through the wrap", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "pi-launch-wrap-")); + try { + const fakePi = path.join(root, "fake-pi.mjs"); + await writeFile( + fakePi, + [ + 'import { createInterface } from "node:readline";', + 'createInterface({ input: process.stdin }).on("line", (line) => {', + " const command = JSON.parse(line);", + ' const data = { sessionId: "wrapped", argv: process.argv.slice(2) };', + ' process.stdout.write(JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data }) + "\\n");', + "});", + "", + ].join("\n"), + ); + const launcher = path.join(root, "launcher.mjs"); + await writeFile( + launcher, + [ + 'import { spawn } from "node:child_process";', + 'import { writeFileSync } from "node:fs";', + "const [command, ...args] = process.argv.slice(2);", + 'writeFileSync(new URL("./wrapped.json", import.meta.url), JSON.stringify([command, ...args]));', + 'const child = spawn(command, args, { stdio: "inherit" });', + 'child.on("exit", (code) => process.exit(code ?? 1));', + "", + ].join("\n"), + ); + const runtime = new PiCliRuntime({ + logger: pino({ level: "silent" }), + command: [process.execPath, fakePi], + }); + + const session = await runtime.startSession({ + cwd: root, + wrap: [process.execPath, launcher], + }); + try { + await expect(session.getState()).resolves.toMatchObject({ + sessionId: "wrapped", + argv: ["--mode", "rpc"], + }); + expect(JSON.parse(await readFile(path.join(root, "wrapped.json"), "utf8"))).toEqual([ + process.execPath, + fakePi, + "--mode", + "rpc", + ]); + } finally { + await session.close(); + } + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + test("passes an MCP config path to Pi", async () => { const child = createPiChild(); replyToCommands(child, () => ({})); diff --git a/packages/server/src/server/agent/providers/pi/cli-runtime.ts b/packages/server/src/server/agent/providers/pi/cli-runtime.ts index 78c1fc7cf6..6cb7e34e6f 100644 --- a/packages/server/src/server/agent/providers/pi/cli-runtime.ts +++ b/packages/server/src/server/agent/providers/pi/cli-runtime.ts @@ -65,6 +65,7 @@ export class PiCliRuntime implements PiRuntime { args, cwd: launch.cwd, env: launch.env, + wrap: launch.wrap, }; const spawn = this.spawnProcess; const processOptions = { diff --git a/packages/server/src/server/agent/providers/pi/runtime.ts b/packages/server/src/server/agent/providers/pi/runtime.ts index 42399d3275..872afd915c 100644 --- a/packages/server/src/server/agent/providers/pi/runtime.ts +++ b/packages/server/src/server/agent/providers/pi/runtime.ts @@ -13,6 +13,8 @@ export interface PiRuntimeLaunch { cwd: string; argv: string[]; env?: Record; + /** Start Pi as `[...wrap, ...argv]`. */ + wrap?: readonly [string, ...string[]]; protocolMode?: "rpc" | "rpc-ui"; model?: string; thinkingOptionId?: string; @@ -28,6 +30,8 @@ export interface PiStartSessionInput { cwd: string; signal?: AbortSignal; env?: Record; + /** The agent's launch wrap; every Pi process started for the agent runs behind it. */ + wrap?: readonly [string, ...string[]]; protocolMode?: "rpc" | "rpc-ui"; model?: string; thinkingOptionId?: string; @@ -102,6 +106,7 @@ export function buildPiLaunch(input: { ...input.session.env, } : undefined, + wrap: input.session.wrap, model: input.session.model, thinkingOptionId: input.session.thinkingOptionId, protocolMode, diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 46cf744d6e..ace06720da 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -161,6 +161,7 @@ export interface PaseoToolHostDependencies { workspaceScripts?: Pick; markWorkspaceArchiving?: ArchiveDependencies["markWorkspaceArchiving"]; clearWorkspaceArchiving?: ArchiveDependencies["clearWorkspaceArchiving"]; + lifecycle?: ArchiveDependencies["lifecycle"]; createPaseoWorktree?: CreatePaseoWorktreeWorkflowFn; // Mints a fresh directory workspace for a cwd and returns its id. ensureWorkspaceForCreate?: ( @@ -2565,6 +2566,7 @@ function createToolCatalog( const workspaceId = await resolveTerminalWorkspaceId(resolvedCwd); const terminal = await terminalManager.createTerminal({ + origin: { source: "agent" }, cwd: resolvedCwd, workspaceId, ...(name?.trim() ? { name: name.trim() } : {}), @@ -3463,6 +3465,7 @@ function archiveWorktreeDependencies( throw new Error("Checkout trust lookup is required to archive worktrees"); } return { + lifecycle: options.lifecycle ?? null, paseoHome: options.paseoHome, paseoWorktreesBaseRoot: options.worktreesRoot, worktreeManagers: options.worktreeManagers, diff --git a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts index ae2d2c141d..ab28a357fe 100644 --- a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts +++ b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts @@ -1,3 +1,4 @@ +import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import type { Logger } from "pino"; import type { AgentManager } from "../agent/agent-manager.js"; @@ -44,6 +45,7 @@ export interface AutoArchiveArchiveOptions { markWorkspaceArchiving: (workspaceIds: Iterable, archivingAt: string) => void; clearWorkspaceArchiving: (workspaceIds: Iterable) => void; emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds: Iterable) => Promise; + lifecycle: Pick | null; } export interface ArchiveIfSafeDependencies { @@ -104,6 +106,7 @@ export async function archiveIfSafe(input: { await deps.archiveByScope( { + lifecycle: options.lifecycle, paseoHome: options.paseoHome, paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot, worktreeManagers: options.worktreeManagers, diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index a3e93a7e1c..ac1ac49e28 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -192,6 +192,7 @@ import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js"; import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js"; import type { TerminalManager } from "../terminal/terminal-manager.js"; import { startWorkerTerminalManager } from "../terminal/worker-terminal-manager.js"; +import { withTerminalCreateHook } from "../terminal/terminal-create-hook.js"; import { applyTerminalAgentHookSetting } from "../terminal/agent-hooks/terminal-agent-hook-setting.js"; import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js"; import { createRelayRuntime, type RelayRuntime } from "./relay-runtime.js"; @@ -739,13 +740,16 @@ export async function createPaseoDaemon( }); let boundListenTarget: ListenTarget | null = null; let workspaceRegistry: FileBackedWorkspaceRegistry | null = null; - const terminalManager = await startWorkerTerminalManager({ - paseoHome: config.paseoHome, - paseoVersion: daemonVersion, - logger, - getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget), - eagerLaunch: !dependencies.lazyTerminalWorker, - }); + const terminalManager = withTerminalCreateHook( + await startWorkerTerminalManager({ + paseoHome: config.paseoHome, + paseoVersion: daemonVersion, + logger, + getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget), + eagerLaunch: !dependencies.lazyTerminalWorker, + }), + pluginRuntime, + ); applyTerminalAgentHookSetting({ store: daemonConfigStore, logger }); const serviceProxyPublicBaseUrl = config.serviceProxy?.publicBaseUrl @@ -1235,6 +1239,7 @@ export async function createPaseoDaemon( }); setupAutoArchiveOnMerge({ + lifecycle: pluginRuntime, paseoHome: config.paseoHome, paseoWorktreesBaseRoot: config.worktreesRoot, worktreeManagers: pluginRuntime, @@ -1266,6 +1271,7 @@ export async function createPaseoDaemon( ) => { return createPaseoWorktreeWorkflow( { + lifecycle: pluginRuntime, paseoHome: config.paseoHome, worktreesRoot: config.worktreesRoot, createPaseoWorktree: async (workflowInput, workflowOptions) => { @@ -1330,6 +1336,7 @@ export async function createPaseoDaemon( const archiveWorkspaceByIdExternal = (workspaceId: string, requestId: string) => archiveByScope( { + lifecycle: pluginRuntime, paseoHome: config.paseoHome, paseoWorktreesBaseRoot: config.worktreesRoot, worktreeManagers: pluginRuntime, @@ -1357,6 +1364,7 @@ export async function createPaseoDaemon( { scope: { kind: "workspace", workspaceId }, requestId }, ); const hubAgentLifecycle = new CreateAgentLifecycleDispatch({ + lifecycle: pluginRuntime, paseoHome: config.paseoHome, worktreesRoot: config.worktreesRoot, worktreeManagers: pluginRuntime, @@ -1461,6 +1469,7 @@ export async function createPaseoDaemon( const archiveScheduleWorkspaceExternal = async (workspaceId: string) => { await archiveByScope( { + lifecycle: pluginRuntime, paseoHome: config.paseoHome, paseoWorktreesBaseRoot: config.worktreesRoot, worktreeManagers: pluginRuntime, @@ -1624,6 +1633,7 @@ export async function createPaseoDaemon( listActiveWorkspaces: listActiveWorkspacesExternal, archiveWorkspaceRecord: (workspaceId, archivedAt) => archiveWorkspaceRecordExternal(workspaceId, undefined, archivedAt), + lifecycle: pluginRuntime, emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal, workspaceRegistry, projectRegistry, diff --git a/packages/server/src/server/command-run-hook.ts b/packages/server/src/server/command-run-hook.ts new file mode 100644 index 0000000000..8b6bd2ef48 --- /dev/null +++ b/packages/server/src/server/command-run-hook.ts @@ -0,0 +1,14 @@ +import type { PrepareWorktreeLifecycleCommand } from "../utils/worktree.js"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; + +/** Runs plugins' `command.run.before` hooks for each setup or teardown command. */ +export function commandRunHook( + lifecycle: Pick | null, + scope: { workspaceId: string | null; cwd: string; purpose: "setup" | "teardown" }, +): PrepareWorktreeLifecycleCommand | undefined { + if (!lifecycle) return undefined; + return async ({ command, env }) => { + const request = await lifecycle.before("command.run.before", { ...scope, command, env }); + return { env: request.env, ...(request.wrap ? { wrap: request.wrap } : {}) }; + }; +} diff --git a/packages/server/src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts index b0c38bc985..ebad71827a 100644 --- a/packages/server/src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts +++ b/packages/server/src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts @@ -364,13 +364,20 @@ test("terminal collection reports workspace script ownership after runtime regis }, }); try { - expect((await client.startWorkspaceScript(workspaceId, "sleeper")).error).toBeNull(); + const started = await client.startWorkspaceScript(workspaceId, "sleeper"); + expect(started.error).toBeNull(); + const terminalId = started.terminalId; await expect - .poll(() => - terminals.some((terminal) => terminal.workspaceId === workspaceId && terminal.isScript), + .poll( + () => + terminals.map((terminal) => ({ + id: terminal.id, + workspaceId: terminal.workspaceId, + isScript: terminal.isScript, + })), + { timeout: 10_000 }, ) - .toBe(true); - const terminalId = terminals.find((terminal) => terminal.workspaceId === workspaceId)!.id; + .toContainEqual({ id: terminalId, workspaceId, isScript: true }); const pidFile = path.join(cwd, "sleeper.pid"); await expect .poll(async () => Number(await readFile(pidFile, "utf8")), { timeout: 10_000 }) diff --git a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts index a3e4e273a4..8e20491fe8 100644 --- a/packages/server/src/server/plugins/agent-configuration.e2e.test.ts +++ b/packages/server/src/server/plugins/agent-configuration.e2e.test.ts @@ -140,3 +140,52 @@ export default function contribute(server) { await rm(directory, { recursive: true, force: true }); } }, 60_000); + +test("a create hook reads launch-wrap support for a plugin provider that never connected", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "paseo-launch-wrap-snapshot-")); + const daemon = await createTestPaseoDaemon({ + daemonVersion: "0.14.0-beta.2", + agentClients: { codex: createTestAgentClient("codex") }, + mcpEnabled: false, + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.14.0-beta.2", + }); + try { + await writeFile( + path.join(directory, "paseo-plugin.json"), + JSON.stringify({ id: "launch-wrap-snapshot", requirements: { paseo: ">=0.14.0-beta.2" } }), + ); + // connect() always fails, so nothing negotiated over a connection can reach the snapshot. + await writeFile( + path.join(directory, "index.server.ts"), + `import { runAcpProvider } from "@getpaseo/plugin/server/acp"; +let connects = 0; +export default function contribute(server) { + const acp = runAcpProvider({ id: "wrap-acp", label: "Wrap ACP", command: [process.execPath, "--version"] }); + server.registerProvider({ ...acp, connect() { connects += 1; throw new Error("not connected in this test"); } }); + return server.before("agent.create", async ({ request }, { paseo }) => { + const snapshot = await paseo.providers.snapshot(); + const entry = snapshot.entries.find((candidate) => candidate.provider === "wrap-acp"); + return { ...request, metadata: { ...request.metadata, launchWrapProbe: { launchWrap: entry?.launchWrap ?? null, status: entry?.status ?? null, connects } } }; + }); +} +`, + ); + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + await client.patchDaemonConfig({ pluginsEnabled: true }); + await client.installDirectoryPlugin(directory); + const agent = await client.createAgent({ provider: "codex", cwd: directory }); + expect(daemon.daemon.agentManager.getAgent(agent.id)?.metadata.launchWrapProbe).toMatchObject({ + launchWrap: true, + connects: 0, + }); + await client.archiveAgent(agent.id); + } finally { + await client.close(); + await daemon.close(); + await rm(directory, { recursive: true, force: true }); + } +}, 60_000); diff --git a/packages/server/src/server/plugins/agent-tools.e2e.test.ts b/packages/server/src/server/plugins/agent-tools.e2e.test.ts index 0ad42627fe..4571d1b993 100644 --- a/packages/server/src/server/plugins/agent-tools.e2e.test.ts +++ b/packages/server/src/server/plugins/agent-tools.e2e.test.ts @@ -46,6 +46,7 @@ function recordingProvider(native: boolean, callbacks: TestAgentClientOptions = const provider: AgentClient = { provider: inner.provider, capabilities: { ...inner.capabilities, supportsNativePaseoTools: native }, + supportsLaunchWrap: true, createSession: async (config, context, options) => { launches.push({ config, context }); return inner.createSession(config, context, options); @@ -587,6 +588,44 @@ test("an idle agent reopens once before its next prompt after a session-hook plu } }, 60_000); +function wrapPluginSource(profile: string) { + return ` +export default function contribute(server) { + server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: [${JSON.stringify(process.execPath)}, "--sandbox-profile", ${JSON.stringify(profile)}], + })); + return () => {}; +} +`; +} + +test("a plugin reload that changes the launch wrap reopens the idle session with the new wrap", async () => { + const h = await setup(false, wrapPluginSource("first")); + try { + const a = await h.create(); + expect(h.launches.at(-1)!.context?.wrap).toEqual([ + process.execPath, + "--sandbox-profile", + "first", + ]); + await writeFile( + path.join(h.directory, "tools-test", "index.server.ts"), + wrapPluginSource("second"), + ); + await h.client.reloadPlugin("tools-test"); + await sendAndFinish(h, a.id, "after reload"); + expect(h.launches).toHaveLength(2); + expect(h.launches.at(-1)!.context?.wrap).toEqual([ + process.execPath, + "--sandbox-profile", + "second", + ]); + } finally { + await h.close(); + } +}, 60_000); + test("a busy agent is steered after plugin reload and reopens only at its next idle prompt", async () => { let release!: () => void; const blocked = new Promise((resolve) => { diff --git a/packages/server/src/server/plugins/index.posix.test.ts b/packages/server/src/server/plugins/index.posix.test.ts index 87296ddacb..c846227102 100644 --- a/packages/server/src/server/plugins/index.posix.test.ts +++ b/packages/server/src/server/plugins/index.posix.test.ts @@ -19,6 +19,7 @@ import pino from "pino"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { DaemonConfigStore } from "../daemon-config-store.js"; import { PluginService } from "./index.js"; +import { PluginAgentClientRegistry } from "../agent/plugin-provider.js"; import { BuiltinPluginLoader } from "./builtin/index.js"; import { ManagedPluginSources } from "./managed-source.js"; import type { PluginProviderMetadata } from "./plugin-process-protocol.js"; @@ -583,6 +584,35 @@ describe("PluginService", () => { await service.stopAllPlugins(); }); + it("carries a provider's launch-wrap declaration from the plugin process to its definition", async () => { + const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); + roots.push(home); + const directory = await createPlugin( + "provider-launch-wrap", + `import { runAcpProvider } from "@getpaseo/plugin/server/acp"; +export default function contribute(server) { + server.registerProvider(runAcpProvider({ id: "wrapped-agent", label: "Wrapped", command: ["agent", "acp"] })); + server.registerProvider(runAcpProvider({ id: "connector-agent", label: "Connector", connector() { throw new Error("not opened by this test"); } })); + return () => {}; +}`, + ); + const service = createService(home); + + await service.start(); + try { + await service.installDirectory({ path: directory }); + const registrations = service.getProviderRegistrations(); + expect(registrations.find(({ id }) => id === "wrapped-agent")?.launchWrap).toBe(true); + expect(registrations.find(({ id }) => id === "connector-agent")?.launchWrap).toBeUndefined(); + const registry = new PluginAgentClientRegistry(pino({ level: "silent" })); + registry.replace(registrations); + expect(registry.definitions()["wrapped-agent"]?.supportsLaunchWrap).toBe(true); + expect(registry.definitions()["connector-agent"]?.supportsLaunchWrap).toBe(false); + } finally { + await service.stopAllPlugins(); + } + }); + it("publishes provider registrations only while their plugin is running", async () => { const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-")); roots.push(home); diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 8e699e51c5..f60edc7bc9 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -793,6 +793,7 @@ export class PluginService { description: provider.description, docsUrl: provider.docsUrl, command: provider.command, + launchWrap: provider.launchWrap, requiresConfiguration: provider.requiresConfiguration, status: provider.hasStatus ? (request) => { diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index aab2a9bd15..97d3243934 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { expect, onTestFinished, test } from "vitest"; +import { createPaseoClient } from "@getpaseo/client"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; import { resolveDaemonVersion } from "../daemon-version.js"; @@ -523,6 +524,7 @@ test("agent creation hooks change the provider and environment before the sessio acknowledgeClose: true, hooks: ` server.addHook("agent.create.before", async ({ request }) => { + console.log(JSON.stringify({ hook: "agent.create.before", workspaceId: request.workspaceId })); return { ...request, config: { ...request.config, provider: "${PROVIDER_ID}", model: "shutdown-model" }, env: { ...request.env, HOOK_CREATE: "created" } }; }); server.addHook("agent.open.before", async ({ request }) => { @@ -554,9 +556,14 @@ test("agent creation hooks change the provider and environment before the sessio await client.patchDaemonConfig({ pluginsEnabled: true }); await client.installDirectoryPlugin(pluginDirectory); await client.installDirectoryPlugin(extraPlugin); + const workspace = await client.createWorkspace({ + source: { kind: "directory", path: directory }, + }); + const workspaceId = workspace.workspace!.id; const agent = await client.createAgent({ provider: "claude", cwd: directory, + workspaceId, title: "Hook test", systemPrompt: "Saved instructions", }); @@ -577,6 +584,7 @@ test("agent creation hooks change the provider and environment before the sessio }); }) .toMatchObject([ + { hook: "agent.create.before", workspaceId }, { hook: "agent.open.before", request: { agentId: agent.id, env: { HOOK_CREATE: "created" } }, @@ -617,6 +625,226 @@ test("agent creation hooks change the provider and environment before the sessio } }, 60_000); +test("plugins wrap or refuse terminals and worktree setup and teardown commands", async () => { + const root = await realpath(await mkdtemp(path.join(tmpdir(), "paseo-terminal-hooks-"))); + const repository = path.join(root, "repository"); + const pluginDirectory = path.join(root, "plugin"); + const hookLog = path.join(root, "hooks.jsonl"); + // Spaces and cmd.exe syntax in the sandbox's install path, as in `C:\Program Files (x86)`. + const sandboxDirectory = path.join(root, "sandbox launcher (x86)"); + await mkdir(sandboxDirectory); + const launchLog = path.join(sandboxDirectory, "launches.jsonl"); + const launcher = path.join(sandboxDirectory, "launcher.cjs"); + // The sandbox stand-in: records the argv after its own two, marks the environment, runs the rest. + await writeFile( + launcher, + `const { appendFileSync } = require("node:fs"); +const { spawn } = require("node:child_process"); +const [log, tag, command, ...args] = process.argv.slice(2); +appendFileSync(log, JSON.stringify({ tag, command, args }) + "\\n"); +const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED: tag } }); +for (const signal of ["SIGTERM", "SIGHUP", "SIGINT"]) process.on(signal, () => child.kill(signal)); +child.on("exit", (code) => process.exit(code ?? 1)); +`, + ); + // Windows sandboxes ship a `.cmd` entry point, which runs through cmd.exe and forwards `%*`. + const commandScript = path.join(sandboxDirectory, "sandbox run.cmd"); + await writeFile(commandScript, `@"${process.execPath}" "${launcher}" %*\r\n`); + const wrapPrefix = process.platform === "win32" ? [commandScript] : [process.execPath, launcher]; + // Node one-liners read the environment the same way under bash, PowerShell, and cmd.exe. + const setupCommand = `node -e "require('fs').writeFileSync('setup.txt', 'setup:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`; + const teardownCommand = `node -e "require('fs').writeFileSync(require('path').join(process.env.PASEO_SOURCE_CHECKOUT_PATH, '..', 'teardown.txt'), 'teardown:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`; + const scriptCommand = `node -e "console.log('script:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`; + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + await writeFile( + path.join(repository, "paseo.json"), + JSON.stringify({ + worktree: { setup: setupCommand, teardown: teardownCommand }, + scripts: { greet: { command: scriptCommand } }, + }), + ); + execFileSync("git", ["add", "paseo.json"], { cwd: repository, stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + ].concat(["commit", "-m", "initial"]), + { cwd: repository, stdio: "pipe" }, + ); + await mkdir(pluginDirectory); + await writeFile( + path.join(pluginDirectory, "paseo-plugin.json"), + JSON.stringify({ id: "terminal-hooks", requirements: { paseo: ">=0.8.0" } }), + ); + await writeFile( + path.join(pluginDirectory, "index.server.ts"), + ` +import { appendFile } from "node:fs/promises"; +const log = (entry) => appendFile(${JSON.stringify(hookLog)}, JSON.stringify(entry) + "\\n"); +const wrap = (tag) => [...${JSON.stringify(wrapPrefix)}, ${JSON.stringify(launchLog)}, tag]; +export default function contribute(server) { + server.addHook("terminal.create.before", async ({ request }) => { + await log({ hook: "terminal", request }); + if (request.name === "Refused") throw new Error("terminals named Refused stay closed"); + return { + ...request, + env: { ...request.env, HOOK_MARK: request.source + ":" + request.workspaceId }, + wrap: wrap("terminal"), + }; + }); + server.addHook("command.run.before", async ({ request }) => { + await log({ hook: "command", request }); + return { + ...request, + env: { ...request.env, HOOK_MARK: request.purpose + "-hooked" }, + wrap: wrap(request.purpose), + }; + }); + return () => {}; +} +`, + ); + const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); + const sdk = createPaseoClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + await client.patchDaemonConfig({ pluginsEnabled: true }); + expect((await client.installDirectoryPlugin(pluginDirectory)).status).toBe("running"); + await sdk.connect(); + const created = await client.createWorkspace({ + source: { kind: "worktree", cwd: repository, branchName: "hooks", worktreeSlug: "hooks" }, + }); + expect(created.error).toBeNull(); + const workspaceId = created.workspace!.id; + const worktree = created.workspace!.workspaceDirectory; + + // Setup runs after creation, behind the wrap, with the hook's environment. + await expect + .poll(() => readFile(path.join(worktree, "setup.txt"), "utf8").catch(() => ""), { + timeout: 30_000, + }) + .toBe("setup:setup-hooked:setup"); + + const program = [ + "-e", + "console.log('program:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED); setInterval(() => {}, 1000)", + ]; + const wrapped = await sdk.terminals.create({ + workspaceId, + name: "Wrapped", + command: process.execPath, + args: program, + }); + await expect + .poll(async () => (await wrapped.capture({ stripAnsi: true })).lines.join("\n")) + .toContain(`program:client:${workspaceId}:terminal`); + + await expect(sdk.terminals.create({ workspaceId, name: "Refused" })).rejects.toThrow( + "Plugin terminal-hooks terminal.create.before failed: terminals named Refused stay closed", + ); + + // A script's command is typed into a default shell, and that shell runs behind the wrap. + await client.startWorkspaceScript(workspaceId, "greet"); + await expect + .poll(async () => { + const script = (await sdk.terminals.list({ workspaceId })).entries.find( + (entry) => entry.name === "greet", + ); + if (!script) return ""; + return (await sdk.terminals.ref(script.id).capture({ stripAnsi: true })).lines.join("\n"); + }) + .toContain(`script:script:${workspaceId}:terminal`); + + await client.archiveWorkspace(workspaceId); + await expect + .poll(() => readFile(path.join(root, "teardown.txt"), "utf8").catch(() => ""), { + timeout: 30_000, + }) + .toBe("teardown:teardown-hooked:teardown"); + + const readJsonLines = async (file: string) => + (await readFile(file, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + const entries = await readJsonLines(hookLog); + expect(entries.filter((entry) => entry.hook === "command")).toEqual([ + { + hook: "command", + request: { + workspaceId, + cwd: worktree, + purpose: "setup", + command: setupCommand, + env: expect.any(Object), + }, + }, + { + hook: "command", + request: { + workspaceId, + cwd: worktree, + purpose: "teardown", + command: teardownCommand, + env: expect.any(Object), + }, + }, + ]); + expect(entries.filter((entry) => entry.hook === "terminal")).toEqual([ + { + hook: "terminal", + request: { + workspaceId, + cwd: worktree, + source: "client", + name: "Wrapped", + command: process.execPath, + args: program, + input: null, + env: {}, + }, + }, + { + hook: "terminal", + request: expect.objectContaining({ source: "client", name: "Refused" }), + }, + { + hook: "terminal", + request: expect.objectContaining({ + workspaceId, + source: "script", + name: "greet", + command: null, + input: scriptCommand, + }), + }, + ]); + // Paseo appended what it would have run: the shell for a command, the program, the default shell. + const launches = await readJsonLines(launchLog); + expect(launches.map(({ tag, command }) => ({ tag, command }))).toEqual([ + { tag: "setup", command: expect.any(String) }, + { tag: "terminal", command: process.execPath }, + { tag: "terminal", command: expect.any(String) }, + { tag: "teardown", command: expect.any(String) }, + ]); + expect(launches[0].args.at(-1)).toBe(setupCommand); + expect(launches[1].args).toEqual(program); + expect(launches[3].args.at(-1)).toBe(teardownCommand); + } finally { + await sdk.close(); + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true }); + } +}, 120_000); + test("invalid output from an untyped plugin rejects creation before later callbacks run", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-invalid-hook-")); const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index 6ff3361f22..916967057d 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -229,7 +229,7 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }, { background: paseo, ), ).rejects.toThrow( - "agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt", + "agent.open.before hooks can only change env, tools, mcpServers, appendSystemPrompt, and wrap", ); }, ); @@ -398,3 +398,209 @@ test("session-open instructions compose, survive old hooks, and are ignored for ); expect(history).not.toHaveProperty("appendSystemPrompt"); }); + +const openInput = { + agentId: "agent", + workspaceId: null, + provider: "codex", + cwd: "/project", + reason: "resume", + purpose: "interactive", + env: {}, + title: null, + labels: {}, + metadata: {}, + tools: [], + mcpServers: {}, +}; + +type OpenHookResult = (request: Record) => Record; + +/** Runs `results` as successive `agent.open.before` hooks of one plugin. */ +async function invokeOpen(results: OpenHookResult[], input: Record = openInput) { + const hooks = new PluginHookHandlers(() => {}); + for (const result of results) { + hooks.addHook("agent.open.before", async ({ request }) => result(request) as never); + } + return await hooks.invoke("open", "agent.open.before", input, paseo); +} + +const withWrap = + (...wrap: string[]): OpenHookResult => + (request) => ({ ...request, wrap }); + +test("a session-open hook can select a launch wrap", async () => { + expect(await invokeOpen([withWrap("/usr/local/bin/sandbox", "--profile", "a b")])).toMatchObject({ + wrap: ["/usr/local/bin/sandbox", "--profile", "a b"], + }); +}); + +test("a session-open hook result with an unknown key fails the open", async () => { + await expect(invokeOpen([(request) => ({ ...request, notAHookField: true })])).rejects.toThrow( + /notAHookField/, + ); +}); + +test.each<[string, OpenHookResult, Record]>([ + [ + "omits it", + ({ wrap: _wrap, ...request }) => ({ ...request, env: { LATER: "1" } }), + { wrap: ["/usr/local/bin/sandbox"], env: { LATER: "1" } }, + ], + ["repeats it", withWrap("/usr/local/bin/sandbox"), { wrap: ["/usr/local/bin/sandbox"] }], +])("an earlier wrap stays when a later session-open hook %s", async (_case, later, expected) => { + expect(await invokeOpen([withWrap("/usr/local/bin/sandbox"), later])).toMatchObject(expected); +}); + +test.each<[string, OpenHookResult[], string]>([ + [ + "a later hook returns a different wrap", + [withWrap("/usr/local/bin/sandbox"), withWrap("/usr/local/bin/other")], + "cannot change a wrap", + ], + ["the executable is relative", [withWrap("sandbox")], "must be an absolute path"], + ["the executable is empty", [withWrap("")], "must be an absolute path"], +])("a session-open wrap fails the open when %s", async (_case, results, message) => { + await expect(invokeOpen(results)).rejects.toThrow(message); +}); + +test("a history open keeps the wrap while tools and MCP servers are stripped", async () => { + const history = await invokeOpen( + [ + (request) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox"], + mcpServers: { extra: { type: "stdio", command: "/bin/server" } }, + appendSystemPrompt: ["history"], + }), + ], + { ...openInput, purpose: "history" }, + ); + expect(history).toMatchObject({ wrap: ["/usr/local/bin/sandbox"], tools: [], mcpServers: {} }); + expect(history).not.toHaveProperty("appendSystemPrompt"); +}); + +const terminalRequest = { + workspaceId: "wks_a", + cwd: "/work/a", + source: "client" as const, + name: "Shell", + command: null, + args: [], + input: null, + env: {}, +}; +const commandRequest = { + workspaceId: null, + cwd: "/work/a", + purpose: "teardown" as const, + command: "make clean && rm -rf build", + env: {}, +}; + +test("terminal and command hooks can change env and wrap", async () => { + await expect( + validateBeforeResult("terminal.create.before", terminalRequest, { + ...terminalRequest, + env: { WRAPPED: "1" }, + wrap: ["/usr/bin/sandbox", "--workspace", "wks_a"], + }), + ).resolves.toEqual({ + ...terminalRequest, + env: { WRAPPED: "1" }, + wrap: ["/usr/bin/sandbox", "--workspace", "wks_a"], + }); + await expect( + validateBeforeResult("command.run.before", commandRequest, { + ...commandRequest, + wrap: ["/usr/bin/sandbox"], + }), + ).resolves.toMatchObject({ command: "make clean && rm -rf build", wrap: ["/usr/bin/sandbox"] }); +}); + +test.each<[string, "terminal.create.before" | "command.run.before", object, object, string]>([ + [ + "a terminal's directory", + "terminal.create.before", + terminalRequest, + { cwd: "/elsewhere" }, + "terminal.create.before hooks can only change env and wrap", + ], + [ + "a terminal's program", + "terminal.create.before", + terminalRequest, + { command: "/usr/bin/sandbox" }, + "terminal.create.before hooks can only change env and wrap", + ], + [ + "a command's text", + "command.run.before", + commandRequest, + { command: "sandbox make clean" }, + "command.run.before hooks can only change env and wrap", + ], + [ + "a command's purpose", + "command.run.before", + commandRequest, + { purpose: "setup" }, + "command.run.before hooks can only change env and wrap", + ], + [ + "a relative wrap", + "command.run.before", + commandRequest, + { wrap: ["sandbox"] }, + "wrap executable must be an absolute path", + ], +])("a hook cannot change %s", async (_case, name, request, change, message) => { + await expect( + validateBeforeResult(name, request as never, { ...request, ...change }), + ).rejects.toThrow(message); +}); + +test.each(["terminal.create.before", "command.run.before"] as const)( + "%s keeps the first wrap and rejects a different one", + async (name) => { + const initial = name === "terminal.create.before" ? terminalRequest : commandRequest; + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook( + name, + async ({ request }) => ({ ...request, wrap: ["/usr/bin/sandbox"] }) as never, + ); + hooks.addHook(name, async ({ request }) => { + const { wrap: _omitted, ...rest } = request as typeof request & { wrap?: unknown }; + return { ...rest, env: { LATER: "1" } } as never; + }); + await expect(hooks.invoke("first", name, initial, paseo)).resolves.toMatchObject({ + wrap: ["/usr/bin/sandbox"], + env: { LATER: "1" }, + }); + hooks.addHook(name, async ({ request }) => ({ ...request, wrap: ["/usr/bin/other"] }) as never); + await expect(hooks.invoke("second", name, initial, paseo)).rejects.toThrow( + `${name} hooks cannot change a wrap an earlier hook selected`, + ); + }, +); + +test("agent creation hooks keep the workspace, including from plugins that omit it", async () => { + const request = { + config: { provider: "claude", cwd: "/work/a" }, + metadata: { "issues.id": "ENG-1" }, + workspaceId: "wks_a", + }; + // A result built before either field existed keeps both. + await expect( + validateBeforeResult("agent.create.before", request, { config: request.config }), + ).resolves.toEqual(request); + await expect( + validateBeforeResult("agent.create.before", request, { + config: request.config, + metadata: { "issues.id": "ENG-2" }, + }), + ).resolves.toEqual({ ...request, metadata: { "issues.id": "ENG-2" } }); + await expect( + validateBeforeResult("agent.create.before", request, { ...request, workspaceId: "wks_b" }), + ).rejects.toThrow("agent.create.before hooks cannot change the workspace"); +}); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 9b138335b3..af4cf3b3cd 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -3,6 +3,7 @@ import { createLifecycleRegistration, pluginHookRegistry, } from "@getpaseo/plugin/internal/lifecycle"; +import { isAbsolute } from "node:path"; import { isDeepStrictEqual } from "node:util"; import { serializeAgentTool, @@ -93,13 +94,20 @@ const worktreeRequestSchema = z.discriminatedUnion("kind", [ .strict(), ]); +const launchWrapSchema = z + .tuple([z.string().refine(isAbsolute, "wrap executable must be an absolute path")], z.string()) + .optional(); + const beforeSchemas = { "worktree.create.before": worktreeRequestSchema, "agent.create.before": CreateAgentRequestMessageSchema.pick({ config: true, env: true, metadata: true, - }).strict(), + }) + // A plugin built before the field may omit it from its result; it can't change it. + .extend({ workspaceId: z.string().nullable().optional() }) + .strict(), "agent.open.before": z .object({ agentId: z.string(), @@ -118,14 +126,77 @@ const beforeSchemas = { tools: z.array(agentToolMetadataSchema), env: z.record(z.string(), z.string()), mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(), + wrap: launchWrapSchema, }) .strict(), "workspace.create.before": WorkspaceCreateRequestSchema.omit({ type: true, requestId: true, }).strict(), + "terminal.create.before": z + .object({ + workspaceId: z.string(), + cwd: z.string(), + source: z.enum(["client", "agent", "script", "worktree"]), + name: z.string().nullable(), + command: z.string().nullable(), + args: z.array(z.string()), + input: z.string().nullable(), + env: z.record(z.string(), z.string()), + wrap: launchWrapSchema, + }) + .strict(), + "command.run.before": z + .object({ + workspaceId: z.string().nullable(), + cwd: z.string(), + purpose: z.enum(["setup", "teardown"]), + command: z.string(), + env: z.record(z.string(), z.string()), + wrap: launchWrapSchema, + }) + .strict(), }; +// Request fields a hook reads but can't change, with the error a changed one gets. +const readOnlyRequestFields = { + "terminal.create.before": { + fields: ["workspaceId", "cwd", "source", "name", "command", "args", "input"], + message: "terminal.create.before hooks can only change env and wrap", + }, + "command.run.before": { + fields: ["workspaceId", "cwd", "purpose", "command"], + message: "command.run.before hooks can only change env and wrap", + }, +} as const; + +function assertReadOnlyFields(name: string, input: unknown, result: unknown): void { + if (!Object.hasOwn(readOnlyRequestFields, name)) return; + const { fields, message } = readOnlyRequestFields[name as keyof typeof readOnlyRequestFields]; + const previous = input as Record; + const next = result as Record; + if (fields.some((field) => !isDeepStrictEqual(previous[field], next[field]))) + throw new Error(message); +} + +type LaunchWrap = z.infer; + +/** + * One wrap per operation: the first hook that selects a wrap owns it. A later hook may omit it or + * repeat it; a different wrap fails, so two sandboxes never silently stack or replace each other. + */ +function keepSelectedWrap(name: string, previous: LaunchWrap, next: LaunchWrap): LaunchWrap { + if (previous && next && !isDeepStrictEqual(previous, next)) { + throw new Error(`${name} hooks cannot change a wrap an earlier hook selected`); + } + return previous ?? next; +} + +function withWrap(result: Result, wrap: LaunchWrap): Result { + const { wrap: _replaced, ...rest } = result as Result & { wrap?: LaunchWrap }; + return (wrap ? { ...rest, wrap } : rest) as Result; +} + const sessionOpenLocalResultSchema = beforeSchemas["agent.open.before"].extend({ tools: z.array( z.custom( @@ -278,11 +349,11 @@ export async function validateBeforeResult { + type OpenInput = Record & { wrap?: string[] }; + + function createHookChild(name: string, hooks: string[], onHook: (input: OpenInput) => unknown) { + const child = createReloadChild(name, []); + const send = child.send.bind(child); + child.send = (message, callback) => { + if (message.type === "initialize") { + callback?.(null); + queueMicrotask(() => + child.emitMessage({ type: "ready", methods: [], providers: [], hooks }), + ); + return true; + } + if (message.type === "hook") { + callback?.(null); + const { requestId, input } = message as unknown as { requestId: string; input: OpenInput }; + queueMicrotask(() => + child.emitMessage({ type: "result", requestId, output: onHook(input) }), + ); + return true; + } + return send(message, callback); + }; + return child; + } + + const request = { + agentId: "agent", + workspaceId: null, + provider: "codex", + cwd: "/project", + reason: "resume" as const, + purpose: "interactive" as const, + env: {}, + title: null, + background: false, + labels: {}, + metadata: {}, + tools: [], + mcpServers: {}, + }; + + // Ids sort like paseo-safehouse before zerosub, so the sandbox plugin runs first. + async function openWith(later: (input: OpenInput) => unknown) { + const calls: string[] = []; + // Started in the opposite order to their ids: the runtime orders hooks by id, not start order. + const children = [ + createHookChild("zerosub", ["agent.open.before"], (input) => { + calls.push("zerosub"); + return later(input); + }), + createHookChild("paseo-safehouse", ["agent.open.before"], (input) => { + calls.push("paseo-safehouse"); + return { ...input, wrap: ["/opt/safehouse/bin/safehouse", "--profile", "a b"] }; + }), + ]; + const runtime = createTestRuntime({ spawnChild: () => children.shift()! as never }); + await runtime.startPlugin("zerosub", await createPlugin("zerosub", "export default {}")); + await runtime.startPlugin( + "paseo-safehouse", + await createPlugin("paseo-safehouse", "export default {}"), + ); + try { + return await runtime.before("agent.open.before", request); + } finally { + expect(calls).toEqual(["paseo-safehouse", "zerosub"]); + await runtime.stopAll(); + } + } + + it("keeps the first plugin's wrap when a later plugin omits it", async () => { + const result = await openWith(({ wrap: _wrap, ...input }) => ({ + ...input, + env: { LATER: "1" }, + })); + expect(result).toMatchObject({ + wrap: ["/opt/safehouse/bin/safehouse", "--profile", "a b"], + env: { LATER: "1" }, + }); + }); + + it("passes when a later plugin returns the same wrap", async () => { + const result = await openWith((input) => input); + expect(result.wrap).toEqual(["/opt/safehouse/bin/safehouse", "--profile", "a b"]); + }); + + it("fails the open when a later plugin returns a different wrap", async () => { + await expect( + openWith((input) => ({ ...input, wrap: ["/usr/bin/other-sandbox"] })), + ).rejects.toThrow(/Plugin zerosub agent.open.before failed: .*cannot change a wrap/u); + }); +}); diff --git a/packages/server/src/server/plugins/session-attachments.ts b/packages/server/src/server/plugins/session-attachments.ts index 39a7620944..eb3c79b45b 100644 --- a/packages/server/src/server/plugins/session-attachments.ts +++ b/packages/server/src/server/plugins/session-attachments.ts @@ -358,9 +358,16 @@ function isReusable( ); } -/** The fields one plugin's callback passes on to the next. Tools and MCP servers are collected per plugin instead. */ +/** + * The fields one plugin's callback passes on to the next, including the launch wrap an earlier plugin selected. Tools + * and MCP servers are collected per plugin instead. + */ function chainedFields(request: SessionOpenWireRequest) { - return { env: request.env, appendSystemPrompt: request.appendSystemPrompt ?? [] }; + return { + env: request.env, + appendSystemPrompt: request.appendSystemPrompt ?? [], + wrap: request.wrap ?? null, + }; } /** diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index f11eea9e58..105a1885fc 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -837,6 +837,10 @@ export class Session { private readonly daemonConfigStore: DaemonConfigStore; private readonly pushNotifications: PushNotifications; private readonly pluginRuntime: SessionOptions["pluginRuntime"]; + // What worktree setup and teardown commands run through: the plugins' hooks, or none. + private get commandLifecycle(): NonNullable | null { + return this.pluginRuntime ?? null; + } private readonly orchestrationSkills: SessionOptions["orchestrationSkills"]; private unsubscribeAgentEvents: (() => void) | null = null; private unsubscribeProjectMutations: (() => void) | null = null; @@ -1296,6 +1300,7 @@ export class Session { }); this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations); this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({ + lifecycle: this.commandLifecycle, paseoHome: this.paseoHome, worktreesRoot: this.worktreesRoot, worktreeManagers: this.pluginRuntime, @@ -5832,6 +5837,7 @@ export class Session { ): Promise { return handleWorktreeArchiveRequest( { + lifecycle: this.commandLifecycle, paseoHome: this.paseoHome, paseoWorktreesBaseRoot: this.worktreesRoot, worktreeManagers: this.pluginRuntime, @@ -8161,6 +8167,7 @@ export class Session { ): Promise { return createWorktreeWorkflow( { + lifecycle: this.commandLifecycle, paseoHome: this.paseoHome, worktreesRoot: this.worktreesRoot, createPaseoWorktree: (workflowInput, serviceOptions) => @@ -8214,6 +8221,7 @@ export class Session { ): Promise { return handleWorkspaceSetupRunRequestMessage( { + lifecycle: this.commandLifecycle, getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId), clearAutomationBlock: (workspaceId) => this.withWorkspaceCheckout(workspaceId, async (checkoutPath) => { @@ -8263,6 +8271,7 @@ export class Session { } return archiveByScope( { + lifecycle: this.commandLifecycle, paseoHome: this.paseoHome, paseoWorktreesBaseRoot: this.worktreesRoot, worktreeManagers: this.pluginRuntime, diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index ad8c4773d4..ec22bc04ab 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -1,3 +1,5 @@ +import { commandRunHook } from "./command-run-hook.js"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; import { resolve } from "node:path"; import type { Logger } from "pino"; @@ -69,6 +71,8 @@ export interface ArchiveDependencies { assertWorkspaceAutomationAllowed: (workspaceId: string) => Promise; isCheckoutUntrusted: (checkoutPath: string) => Promise; sessionLogger?: Logger; + /** Plugins' lifecycle, for `command.run.before` on teardown commands. */ + lifecycle: Pick | null; } export interface KillTerminalsForWorkspaceDependencies { @@ -593,6 +597,11 @@ async function maybeRemoveDirectory( worktreePath: backing.path, teardownCwd: teardownTarget.cwd, repoRootPath: backing.mainRepoRoot ?? undefined, + prepareCommand: commandRunHook(dependencies.lifecycle, { + workspaceId: teardownTarget.workspaceId, + cwd: teardownTarget.cwd, + purpose: "teardown", + }), }); } } catch (error) { diff --git a/packages/server/src/server/worktree-bootstrap.ts b/packages/server/src/server/worktree-bootstrap.ts index 1e1ba58f8e..b6caefe805 100644 --- a/packages/server/src/server/worktree-bootstrap.ts +++ b/packages/server/src/server/worktree-bootstrap.ts @@ -327,6 +327,7 @@ export async function runWorktreeAutoTerminals(options: { (await getWorktreeTerminalSpecs(options.workspaceCwd)).map(async (spec) => { try { const terminal = await terminalManager.createTerminal({ + origin: { source: "worktree", input: spec.command }, cwd: options.workspaceCwd, name: spec.name, env: options.runtimeEnv, @@ -488,6 +489,7 @@ async function acquireWorkspaceScriptTerminal(params: { repoRoot: string; workspaceId: string; scriptName: string; + command: string; env: Record | undefined; }): Promise<{ terminal: TerminalSession; reusableTerminal: TerminalSession | null }> { const { @@ -497,6 +499,7 @@ async function acquireWorkspaceScriptTerminal(params: { repoRoot, workspaceId, scriptName, + command, env, } = params; let reusableTerminal: TerminalSession | null = null; @@ -506,6 +509,7 @@ async function acquireWorkspaceScriptTerminal(params: { const terminal = reusableTerminal ?? (await terminalManager.createTerminal({ + origin: { source: "script", input: command }, cwd: repoRoot, workspaceId, name: scriptName, @@ -588,6 +592,7 @@ export async function spawnWorkspaceScript( repoRoot, workspaceId, scriptName, + command: config.command, env, }); diff --git a/packages/server/src/server/worktree-session.ts b/packages/server/src/server/worktree-session.ts index 1cbad931eb..72b6323fbf 100644 --- a/packages/server/src/server/worktree-session.ts +++ b/packages/server/src/server/worktree-session.ts @@ -1,3 +1,5 @@ +import { commandRunHook } from "./command-run-hook.js"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; import type { Logger } from "pino"; import { basename } from "node:path"; import { @@ -63,6 +65,8 @@ interface CreatePaseoWorktreeInBackgroundDependencies { getDaemonTcpHost: (() => string | null) | null; serviceProxyPublicBaseUrl?: string | null; onScriptsChanged: ((workspaceId: string, workspaceDirectory: string) => void) | null; + /** Plugins' lifecycle, for `command.run.before` on setup commands. */ + lifecycle: Pick | null; } interface CreatePaseoWorktreeWorkflowDependencies extends CreatePaseoWorktreeInBackgroundDependencies { @@ -577,6 +581,11 @@ export async function runWorktreeSetupInBackground( applyWorktreeSetupProgressEvent(progressAccumulator, event); emitSetupProgress("running", null); }, + prepareCommand: commandRunHook(dependencies.lifecycle, { + workspaceId, + cwd: workspaceCwd, + purpose: "setup", + }), }); emitSetupProgress("completed", null); } diff --git a/packages/server/src/terminal/default-terminal-shell.ts b/packages/server/src/terminal/default-terminal-shell.ts new file mode 100644 index 0000000000..ceb7351212 --- /dev/null +++ b/packages/server/src/terminal/default-terminal-shell.ts @@ -0,0 +1,13 @@ +// Kept apart from terminal.ts so the daemon can resolve the shell without loading node-pty. +export function resolveDefaultTerminalShell( + options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {}, +): string { + const platform = options.platform ?? process.platform; + const env = options.env ?? process.env; + + if (platform === "win32") { + return env.ComSpec || env.COMSPEC || "C:\\Windows\\System32\\cmd.exe"; + } + + return env.SHELL || "/bin/sh"; +} diff --git a/packages/server/src/terminal/terminal-create-hook.ts b/packages/server/src/terminal/terminal-create-hook.ts new file mode 100644 index 0000000000..ed7b63ee43 --- /dev/null +++ b/packages/server/src/terminal/terminal-create-hook.ts @@ -0,0 +1,36 @@ +import type { PluginLifecycle } from "../server/plugins/lifecycle/index.js"; +import { applyLaunchWrap } from "../utils/launch-wrap.js"; +import { resolveDefaultTerminalShell } from "./default-terminal-shell.js"; +import type { DaemonTerminalManager } from "./worker-terminal-manager.js"; + +/** + * Runs plugins' `terminal.create.before` hooks for every terminal the daemon creates, before the + * worker starts it. A selected wrap becomes the terminal's program here, so the worker protocol + * does not change. Terminals adopted after a daemon restart aren't created again, so the hook + * doesn't run for them. + */ +export function withTerminalCreateHook( + manager: DaemonTerminalManager, + lifecycle: Pick, +): DaemonTerminalManager { + return { + ...manager, + async createTerminal({ origin, ...options }) { + const args = options.args ?? []; + const request = await lifecycle.before("terminal.create.before", { + workspaceId: options.workspaceId, + cwd: options.cwd, + source: origin?.source ?? "client", + name: options.name ?? null, + command: options.command ?? null, + args, + input: origin?.input ?? null, + env: options.env ?? {}, + }); + if (!request.wrap) return manager.createTerminal({ ...options, env: request.env }); + const command = options.command ?? resolveDefaultTerminalShell({ env: options.baseEnv }); + const launch = applyLaunchWrap({ command, args }, request.wrap); + return manager.createTerminal({ ...options, env: request.env, ...launch }); + }, + }; +} diff --git a/packages/server/src/terminal/terminal-manager.ts b/packages/server/src/terminal/terminal-manager.ts index f8ba1851fa..6d16622460 100644 --- a/packages/server/src/terminal/terminal-manager.ts +++ b/packages/server/src/terminal/terminal-manager.ts @@ -54,6 +54,16 @@ export type TerminalWorkspaceContributionChangedListener = ( event: TerminalWorkspaceContributionChangedEvent, ) => void; +/** + * Who asked for a terminal: an agent's Paseo tool, a `paseo.json` script or service, or a + * `paseo.json` worktree terminal; anything else is a client. `input` is the command Paseo types + * into the shell once it starts. + */ +export interface TerminalOrigin { + source: "client" | "agent" | "script" | "worktree"; + input?: string; +} + export interface TerminalManager { /** * Set when this host's terminals cannot be served at all (a worker from a newer Paseo holds @@ -62,6 +72,8 @@ export interface TerminalManager { getUnavailableError?(): Error | null; getTerminals(cwd: string, options?: { workspaceId?: string }): Promise; createTerminal(options: { + /** Where the terminal comes from, for plugins' `terminal.create.before` hooks. */ + origin?: TerminalOrigin; id?: string; cwd: string; workspaceId: string; diff --git a/packages/server/src/terminal/terminal-session-controller.test.ts b/packages/server/src/terminal/terminal-session-controller.test.ts index c81cd2fbb5..e7c74cccd6 100644 --- a/packages/server/src/terminal/terminal-session-controller.test.ts +++ b/packages/server/src/terminal/terminal-session-controller.test.ts @@ -728,6 +728,74 @@ describe("terminal-session-controller workspace-scoped subscriptions", () => { }); }); +describe("terminal-session-controller script ownership", () => { + test("reports a terminal as a script when its runtime registers right after the creation snapshot", async () => { + const cwd = "/work/repo"; + const terminal = listSession({ id: "script", name: "sleeper", cwd, workspaceId: "ws-a" }); + const scriptTerminalIds = new Set(); + let changedListener: ((event: TerminalsChangedEvent) => void) | null = null; + let metadataListener: (() => void) | null = null; + const terminalManager: TerminalManager = { + getTerminals: vi.fn(async () => [terminal]), + createTerminal: vi.fn(), + registerCwdEnv: vi.fn(), + validateTerminalActivityToken: vi.fn(() => "unknown"), + getTerminal: vi.fn(), + replayTerminal: async () => null, + setTerminalTitle: vi.fn(), + setTerminalActivity: vi.fn(), + killTerminal: vi.fn(), + killTerminalAndWait: vi.fn(), + captureTerminal: vi.fn(), + listDirectories: vi.fn(() => [cwd]), + killAll: vi.fn(), + subscribeTerminalsChanged: vi.fn((listener) => { + changedListener = listener; + return vi.fn(); + }), + subscribeTerminalActivity: vi.fn(() => vi.fn()), + subscribeTerminalWorkspaceContributionChanged: vi.fn(() => vi.fn()), + }; + const reported: boolean[] = []; + let registerAfterNextSnapshot = false; + const controller = createController({ + terminalManager, + emit: (message) => { + if (message.type !== "terminals_changed") return; + reported.push(message.payload.terminals.some((item) => item.isScript)); + if (!registerAfterNextSnapshot) return; + registerAfterNextSnapshot = false; + // The script service registers its runtime in a continuation that runs right after the + // snapshot for the new terminal goes out, before that snapshot's refresh has settled. + queueMicrotask(() => { + scriptTerminalIds.add(terminal.id); + metadataListener?.(); + }); + }, + emitBinary: vi.fn(), + hasBinaryChannel: () => true, + isPathWithinRoot: isSameOrDescendantPath, + sessionLogger: createLogger(), + isScriptTerminal: (item) => scriptTerminalIds.has(item.id), + subscribeTerminalMetadata: (listener) => { + metadataListener = listener; + return () => { + metadataListener = null; + }; + }, + }); + controller.dispatch({ type: "subscribe_terminals_request", cwd, workspaceId: "ws-a" }); + await flushMicrotasks(); + reported.length = 0; + + registerAfterNextSnapshot = true; + changedListener?.({ cwd, terminals: [{ id: terminal.id, name: terminal.name, cwd }] }); + await flushMicrotasks(); + + expect(reported.at(-1)).toBe(true); + }); +}); + describe("terminal-session-controller backpressure snapshot fallback", () => { async function setup( getClientBufferedAmount: () => number | null, diff --git a/packages/server/src/terminal/terminal-session-controller.ts b/packages/server/src/terminal/terminal-session-controller.ts index d047ee0c20..0dd46ac6be 100644 --- a/packages/server/src/terminal/terminal-session-controller.ts +++ b/packages/server/src/terminal/terminal-session-controller.ts @@ -390,39 +390,41 @@ export class TerminalSessionController { return subscription.refresh; } const refresh = (async () => { - do { - subscription.pending = false; - const terminals = - subscription.cwd === undefined - ? (await this.getAllTerminalSessions()).filter( - (terminal) => - subscription.workspaceId === undefined || - terminal.workspaceId === subscription.workspaceId, - ) - : await this.getTerminalsForWorkspaceRoot(subscription.cwd, subscription.workspaceId); - if (subscription.owner.signal.aborted) return; - subscription.owner.emit({ - type: "terminals_changed", - payload: { - cwd: subscription.cwd, - workspaceId: subscription.workspaceId, - terminals: terminals.map((terminal) => - Object.assign( - this.toTerminalInfo(terminal), - subscription.cwd === undefined ? { cwd: terminal.cwd } : {}, + try { + do { + subscription.pending = false; + const terminals = + subscription.cwd === undefined + ? (await this.getAllTerminalSessions()).filter( + (terminal) => + subscription.workspaceId === undefined || + terminal.workspaceId === subscription.workspaceId, + ) + : await this.getTerminalsForWorkspaceRoot(subscription.cwd, subscription.workspaceId); + if (subscription.owner.signal.aborted) return; + subscription.owner.emit({ + type: "terminals_changed", + payload: { + cwd: subscription.cwd, + workspaceId: subscription.workspaceId, + terminals: terminals.map((terminal) => + Object.assign( + this.toTerminalInfo(terminal), + subscription.cwd === undefined ? { cwd: terminal.cwd } : {}, + ), ), - ), - ...(requestId ? { requestId } : {}), - }, - }); - requestId = undefined; - } while (subscription.pending); + ...(requestId ? { requestId } : {}), + }, + }); + requestId = undefined; + } while (subscription.pending); + } finally { + // Clear in the same step as the last pending check. A change that lands after it then + // starts a new refresh instead of setting a pending flag that nothing reads again. + subscription.refresh = null; + } })(); subscription.refresh = refresh; - const settled = () => { - subscription.refresh = null; - }; - void refresh.then(settled, settled); return refresh; } diff --git a/packages/server/src/terminal/terminal.test.ts b/packages/server/src/terminal/terminal.test.ts index d36e86d732..488c6fcefd 100644 --- a/packages/server/src/terminal/terminal.test.ts +++ b/packages/server/src/terminal/terminal.test.ts @@ -1,3 +1,4 @@ +import { resolveDefaultTerminalShell } from "./default-terminal-shell.js"; import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; import { createTerminalSerializer } from "./terminal-serializer.js"; import { readTerminalState } from "./test-utils/terminal-state.js"; @@ -9,7 +10,6 @@ import { assertTerminalCommandCanStart, createTerminal, ensureNodePtySpawnHelperExecutableForCurrentPlatform, - resolveDefaultTerminalShell, resolveTerminalSpawnCommand, humanizeProcessTitle, normalizeProcessTitle, @@ -308,16 +308,18 @@ describe("createTerminal", () => { resolveExecutable: async () => "C:\\npm\\claude.cmd", }); - // The `.cmd` branch now hands node-pty a single pre-escaped command line - // (string) instead of an argv array, so that node-pty's own - // MSVCRT-style array quoting never runs a second time over an already - // cmd.exe-escaped argument. See escapeCmdExeArgument in terminal.ts. + // The `.cmd` branch hands node-pty one cmd.exe command line (a string) instead of an argv + // array, so node-pty's own array quoting never runs over it. An argument without a cmd.exe + // metacharacter stays as given. expect(resolved).toEqual({ command: "C:\\Windows\\System32\\cmd.exe", - args: '/d /s /c "C:\\npm\\claude.cmd ^^^"--foo^^^""', + args: '/d /s /c "C:\\npm\\claude.cmd --foo"', }); }); + // The escaping itself is the SDK's shared cmd.exe dialect, tested in + // packages/plugin/src/server/process-internal/windows-command.test.ts. These cases pin what a + // terminal adds: a prompt line break becomes a space, and a `.cmd` shim counts as a batch script. describe(".cmd shim argument escaping on Windows", () => { async function resolveCmdShimArgs(promptArg: string): Promise { const resolved = await resolveTerminalSpawnCommand("claude", [promptArg], { @@ -325,10 +327,6 @@ describe("createTerminal", () => { env: { ComSpec: "C:\\Windows\\System32\\cmd.exe" }, resolveExecutable: async () => "C:\\npm\\claude.cmd", }); - // A real narrow rather than a cast: the `.cmd` branch is the one case - // that returns a pre-escaped command line instead of argv, so if that - // contract ever changes these tests should fail loudly here rather than - // assert against a stringified array. const { args } = resolved; if (typeof args !== "string") { throw new Error(`expected a cmd.exe command line, got ${JSON.stringify(args)}`); @@ -336,21 +334,20 @@ describe("createTerminal", () => { return args; } - // Each expected string is the exact cmd.exe command line the escaping - // must produce so a real `cmd.exe /c` invocation reconstructs the - // original prompt as a single argv element for the target process - // (modulo the documented newline-to-space normalization below). - it("neutralizes cmd.exe's own metacharacters instead of letting them execute", async () => { + it("escapes cmd.exe metacharacters so they reach the shim as text", async () => { expect(await resolveCmdShimArgs("a & b | c")).toBe( - '/d /s /c "C:\\npm\\claude.cmd ^^^"a^^^ ^^^&^^^ b^^^ ^^^|^^^ c^^^""', + '/d /s /c "C:\\npm\\claude.cmd ^"a^ ^&^ b^ ^|^ c^""', ); + // A caret before each `%` keeps cmd.exe from expanding %PATH%. expect(await resolveCmdShimArgs("100% done %PATH%")).toBe( - '/d /s /c "C:\\npm\\claude.cmd ^^^"100^^^%^^^ done^^^ ^^^%PATH^^^%^^^""', + '/d /s /c "C:\\npm\\claude.cmd ^"100^%^ done^ ^%PATH^%^""', ); - expect(await resolveCmdShimArgs("a^b")).toBe('/d /s /c "C:\\npm\\claude.cmd ^^^"a^^^^b^^^""'); + expect(await resolveCmdShimArgs("a^b")).toBe('/d /s /c "C:\\npm\\claude.cmd ^"a^^b^""'); }); - it("escapes embedded double quotes and backslash runs preceding them", async () => { + // The shim reads its arguments again when it forwards `%*`, so an argument with a quote is + // escaped twice; its quotes would otherwise leave the rest of the line outside a quoted region. + it("escapes an argument with a double quote twice for the shim", async () => { expect(await resolveCmdShimArgs('say "hello" now')).toBe( '/d /s /c "C:\\npm\\claude.cmd ^^^"say^^^ \\^^^"hello\\^^^"^^^ now^^^""', ); @@ -359,18 +356,14 @@ describe("createTerminal", () => { ); }); - // cmd.exe has no way to escape a literal CR/LF inside one command line - // -- its parser treats newlines as command separators regardless of - // quoting -- so a raw newline is normalized to a space before escaping. - // This is a deliberate choice, not an oversight: it avoids the prompt - // ever splitting into a second, attacker-controlled cmd.exe command, at - // the cost of losing the original line breaks. - it("normalizes embedded newlines to spaces instead of letting them split the command", async () => { + // cmd.exe ends a command at a line break whatever the quoting. A terminal prompt often has + // several lines, so the terminal starts with each line break as a space instead of refusing. + it("joins the lines of a prompt with spaces", async () => { expect(await resolveCmdShimArgs("line one\nline two")).toBe( - '/d /s /c "C:\\npm\\claude.cmd ^^^"line^^^ one^^^ line^^^ two^^^""', + '/d /s /c "C:\\npm\\claude.cmd ^"line^ one^ line^ two^""', ); expect(await resolveCmdShimArgs("line one\r\nline two")).toBe( - '/d /s /c "C:\\npm\\claude.cmd ^^^"line^^^ one^^^ line^^^ two^^^""', + '/d /s /c "C:\\npm\\claude.cmd ^"line^ one^ line^ two^""', ); }); diff --git a/packages/server/src/terminal/terminal.ts b/packages/server/src/terminal/terminal.ts index 183be5e8bf..a58d3ab917 100644 --- a/packages/server/src/terminal/terminal.ts +++ b/packages/server/src/terminal/terminal.ts @@ -11,9 +11,14 @@ import { statSync, } from "node:fs"; import { tmpdir, userInfo } from "node:os"; -import { basename, delimiter, dirname, extname, join, resolve as resolvePath } from "node:path"; +import { basename, delimiter, dirname, join, resolve as resolvePath } from "node:path"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; +import { + isWindowsCommandScript, + windowsCommandLine, + windowsCommandShell, +} from "@getpaseo/plugin/internal/windows-command"; import { createExternalProcessEnv } from "../server/paseo-env.js"; import { resolveExternalProcessPath, @@ -35,6 +40,7 @@ import { import type { TerminalReplayOptions, TerminalReplayMetadata } from "./terminal-replay.js"; import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode"; import { TerminalActivityTracker } from "./activity/terminal-activity-tracker.js"; +import { resolveDefaultTerminalShell } from "./default-terminal-shell.js"; import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity"; const require = createRequire(import.meta.url); @@ -263,19 +269,6 @@ export function ensureNodePtySpawnHelperExecutableForCurrentPlatform( } } -export function resolveDefaultTerminalShell( - options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {}, -): string { - const platform = options.platform ?? process.platform; - const env = options.env ?? process.env; - - if (platform === "win32") { - return env.ComSpec || env.COMSPEC || "C:\\Windows\\System32\\cmd.exe"; - } - - return env.SHELL || "/bin/sh"; -} - export interface ResolvedTerminalCommand { command: string; // `.cmd`/`.bat` targets resolve to a single pre-escaped `cmd.exe` command @@ -295,64 +288,11 @@ export interface ResolveTerminalSpawnCommandOptions { resolveExecutable?: (name: string) => Promise; } -// cmd.exe treats these characters specially even inside a double-quoted -// argument, unlike a POSIX shell — quoting alone does not neutralize them. -// Prefixing each with `^`, cmd.exe's own escape character, does. Mirrors the -// `escape.command` metachar list in the `cross-spawn` npm package (already a -// dependency of this repo), which solves this exact `.cmd`/`.bat` spawning -// problem — see http://www.robvanderwoude.com/escapechars.php. -const CMD_EXE_METACHAR_PATTERN = /([()%!^"`<>&|;, *?])/g; - -function escapeCmdExeMetaChars(text: string): string { - return text.replace(CMD_EXE_METACHAR_PATTERN, "^$1"); -} - -/** - * Escape one argument for safe inclusion in a `cmd.exe /c "..."` command - * line that is about to invoke a `.cmd`/`.bat` shim. - * - * node-pty builds an MSVCRT/`CommandLineToArgvW`-style quoted command line - * for whatever `command` it is given (double-quote wrap on whitespace, - * backslash-escape only backslash runs immediately before a quote). That - * quoting is correct for a normal executable, which parses its own argv via - * that same convention. It is not correct here: the `command` node-pty - * launches for a `.cmd`/`.bat` target is `cmd.exe` itself, and cmd.exe - * re-parses the whole line with its *own* tokenizer before ever handing - * arguments to the batch script — a tokenizer that treats `&`, `|`, `^`, - * `%` (environment-variable expansion), `<`, `>` etc. as live syntax even - * inside double quotes. A prompt containing any of those characters would - * therefore be interpreted by cmd.exe, not passed through as text — the - * same class of hazard tracked upstream as Node's CVE-2024-27980 - * ("batBadBadging"). - * - * The escaping below is the "qntm" algorithm (https://qntm.org/cmd): double - * every backslash run that immediately precedes a quote (or the end of the - * argument, since a closing quote is appended next) and escape that quote, - * wrap the whole argument in quotes, then caret-escape cmd.exe's - * metacharacters — including the quotes just added, because cmd.exe's own - * tokenizer runs first and would otherwise treat them as toggling a quoted - * region. It is the same algorithm `cross-spawn` uses for its `.cmd`/`.bat` - * auto-shell path (`lib/util/escape.js`). Command shims forward `%*`, which - * adds a second cmd.exe parse, so metacharacters need a second escape pass to - * survive as literal argv in the Node process behind an npm-generated shim. - * - * cmd.exe has no escape for a literal CR or LF inside a single command - * line — its parser treats them as command separators regardless of - * quoting, so passing one through verbatim would let a crafted prompt - * inject a second, attacker-chosen command after the newline. There is no - * fidelity-preserving option for that case, so newlines are normalized to - * spaces before quoting: the target process still receives the full text, - * just without the original line breaks, instead of cmd.exe splitting the - * prompt into multiple commands. - */ -function escapeCmdExeArgument(rawArg: string): string { - const arg = rawArg.replace(/\r\n|\r|\n/g, " "); - - let escaped = arg.replace(/(\\*)"/g, '$1$1\\"'); - escaped = escaped.replace(/(\\*)$/, "$1$1"); - escaped = `"${escaped}"`; - - return escapeCmdExeMetaChars(escapeCmdExeMetaChars(escaped)); +// cmd.exe ends a command at a line break whatever the quoting, so the shared line builder refuses +// one. A terminal agent's initial prompt arrives as an argument and often spans lines; it still +// starts, with each line break as a space. +function joinPromptLines(argument: string): string { + return argument.replace(/\r\n|\r|\n/g, " "); } /** @@ -389,28 +329,15 @@ export async function resolveTerminalSpawnCommand( // `.cmd`/`.bat` shims are batch scripts that conpty's CreateProcess cannot // launch directly; they must run through cmd.exe (node-pty has no `shell` - // option, so build the `cmd /c` invocation ourselves). Checked by extension - // rather than isWindowsCommandScript() because that helper gates on the live - // process.platform, which is wrong once we're already on the win32 branch. - const extension = extname(resolved).toLowerCase(); - if (extension === ".cmd" || extension === ".bat") { - const env = options.env ?? process.env; - const comSpec = env.ComSpec || env.COMSPEC || "C:\\Windows\\System32\\cmd.exe"; - // Build the `/c` command line ourselves — as a single pre-escaped - // string, not an argv array — so node-pty's own array quoting never - // runs over these values; see escapeCmdExeArgument for why that - // quoting alone is not safe once cmd.exe re-parses the line. `resolved` - // gets the same metachar (not quote-wrap) treatment as the args: it - // isn't attacker-controlled, but it now sits inside the same joined - // command line and needs to survive cmd.exe's tokenizer too (e.g. a - // space in the install path). - const commandLine = [ - "/d", - "/s", - "/c", - `"${[escapeCmdExeMetaChars(resolved), ...args.map(escapeCmdExeArgument)].join(" ")}"`, - ].join(" "); - return { command: comSpec, args: commandLine }; + // option, so build the `cmd /c` invocation ourselves). + if (isWindowsCommandScript(resolved, platform)) { + // node-pty quotes an argv array for a program's own parser, which cmd.exe does not use, so the + // `/c` line goes to it as one string that the shared cmd.exe dialect has already quoted. + const line = windowsCommandLine(resolved, args.map(joinPromptLines), { commandScript: true }); + return { + command: windowsCommandShell(options.env ?? process.env), + args: `/d /s /c ${line}`, + }; } return { command: resolved, args }; diff --git a/packages/server/src/utils/git-repository-discovery.ts b/packages/server/src/utils/git-repository-discovery.ts index f56c2c1239..70aa3c91b0 100644 --- a/packages/server/src/utils/git-repository-discovery.ts +++ b/packages/server/src/utils/git-repository-discovery.ts @@ -113,7 +113,8 @@ let safeBareRepositorySupport: Promise | null = null; /** Reads `git --version` once per process. */ export function readSafeBareRepositorySupport(): Promise { - safeBareRepositorySupport ??= execCommand("git", ["--version"]).then( + // Started like every daemon git command, directly and without a PATH lookup in Node. + safeBareRepositorySupport ??= execCommand("git", ["--version"], { shell: false }).then( ({ stdout }) => parseSafeBareRepositorySupport(stdout), () => false, ); diff --git a/packages/server/src/utils/launch-wrap.ts b/packages/server/src/utils/launch-wrap.ts new file mode 100644 index 0000000000..805a6ca962 --- /dev/null +++ b/packages/server/src/utils/launch-wrap.ts @@ -0,0 +1,20 @@ +/** A plugin's launch wrap: an absolute executable and its arguments. */ +export type LaunchWrap = readonly [string, ...string[]]; + +export interface CommandLaunch { + command: string; + args: string[]; +} + +/** + * The launch that starts `launch` behind `wrap`: `[...wrap, command, ...args]`. Use it where the + * process is not started by `spawnProcess`, which takes the wrap as an option. + */ +export function applyLaunchWrap( + launch: CommandLaunch, + wrap: LaunchWrap | undefined, +): CommandLaunch { + if (!wrap) return launch; + const [executable, ...wrapArgs] = wrap; + return { command: executable, args: [...wrapArgs, launch.command, ...launch.args] }; +} diff --git a/packages/server/src/utils/spawn.launch-regression.test.ts b/packages/server/src/utils/spawn.launch-regression.test.ts index 4943e68990..2ffe92f88c 100644 --- a/packages/server/src/utils/spawn.launch-regression.test.ts +++ b/packages/server/src/utils/spawn.launch-regression.test.ts @@ -127,6 +127,7 @@ async function runFixture(params: { args: string[]; shell?: boolean; env?: NodeJS.ProcessEnv; + expectedArgs?: string[]; }): Promise { const child = spawnProcess(params.command, params.args, { env: { @@ -135,7 +136,7 @@ async function runFixture(params: { // Terminal color settings must not add Node warnings to the argv fixture's stderr. NO_COLOR: undefined, FORCE_COLOR: undefined, - PASEO_EXPECTED_ARGV_JSON: JSON.stringify(["--config", JSON_ARG]), + PASEO_EXPECTED_ARGV_JSON: JSON.stringify(params.expectedArgs ?? ["--config", JSON_ARG]), }, stdio: ["ignore", "pipe", "pipe"], ...(params.shell === undefined ? {} : { shell: params.shell }), @@ -278,6 +279,18 @@ describe.runIf(isPlatform("win32"))("Windows spawn launch regression", () => { expect(result.stdout.trim()).toBe("ARGV_OK"); }); + // A plugin launch wrap can pass an empty argument to a .cmd launcher; cmd.exe must keep its slot. + test("launches a cmd shim with an empty argument in its position", async () => { + const fixture = makeFixture(); + const args = ["--profile", "", "--config", JSON_ARG]; + + const result = await runFixture({ command: fixture.shim, args, expectedArgs: args }); + + expect(result.stderr).toBe(""); + expect(result.stdout.trim()).toBe("ARGV_OK"); + expect(result.code).toBe(0); + }); + test("direct launch with a space-containing executable preserves JSON args", async () => { const fixture = makeFixture(); diff --git a/packages/server/src/utils/spawn.percent-escape.test.ts b/packages/server/src/utils/spawn.percent-escape.test.ts index 3f9eb20eea..728fed7de4 100644 --- a/packages/server/src/utils/spawn.percent-escape.test.ts +++ b/packages/server/src/utils/spawn.percent-escape.test.ts @@ -21,11 +21,8 @@ function writeEchoArgScript(): string { return scriptPath; } -// Use the bare command name "node" (no extension, no path separator) so -// `shouldUseWindowsShell` resolves to true on Windows. That routes the spawn -// through cmd.exe and exercises `quoteWindowsArgument`, which is where the -// %-doubling bug lives. Using `process.execPath` here would skip the shell -// path entirely and silently pass the test. +// Use the bare command name "node" (no extension, no path separator), the way callers name +// tools, so the launch goes through the Windows PATH lookup before it starts. const COMMAND = "node"; describe("spawn argument escaping for % characters", () => { diff --git a/packages/server/src/utils/spawn.ts b/packages/server/src/utils/spawn.ts index b26104c63e..f1f9f77a2c 100644 --- a/packages/server/src/utils/spawn.ts +++ b/packages/server/src/utils/spawn.ts @@ -1,5 +1,9 @@ -import type { ChildProcess, SpawnOptions } from "node:child_process"; -import { spawnProcess as spawnCli, execCommand as execCli } from "@getpaseo/plugin/server"; +import type { ChildProcess } from "node:child_process"; +import { + spawnProcess as spawnCli, + execCommand as execCli, + type SpawnProcessOptions as CliSpawnOptions, +} from "@getpaseo/plugin/server"; import { createExternalCommandProcessEnv, type ProcessEnvRecord } from "../server/paseo-env.js"; interface ExternalEnvOptions { @@ -9,7 +13,7 @@ interface ExternalEnvOptions { envOverlay?: ProcessEnvRecord; } -export type SpawnProcessOptions = Omit & ExternalEnvOptions; +export type SpawnProcessOptions = Omit & ExternalEnvOptions; interface ExecCommandOptions extends ExternalEnvOptions { cwd?: string; diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index 46f2519763..862b832ddd 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -882,6 +882,100 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { expect(portValue).toBeGreaterThan(0); }); + it("runs each setup command behind a plugin's wrap and stops at a refused one", async () => { + // The launcher records the argv it was given, marks the environment, then runs the rest. + const launcher = join(repoDir, "launcher.sh"); + writeFileSync( + launcher, + '#!/bin/sh\nprintf "%s\\n" "$@" > "$(dirname "$0")/launch-argv.log"\nshift 2\nexport INSIDE=wrapped\nexec "$@"\n', + { mode: 0o755 }, + ); + writeFileSync( + join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { + setup: [ + 'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log', + "echo refused > refused.log", + ], + }, + }), + ); + const seen: string[] = []; + const setup = runWorktreeSetupCommands({ + worktreePath: repoDir, + branchName: "main", + runtimeEnv: { + PASEO_SOURCE_CHECKOUT_PATH: repoDir, + PASEO_ROOT_PATH: repoDir, + PASEO_WORKTREE_PATH: repoDir, + PASEO_BRANCH_NAME: "main", + PASEO_WORKTREE_PORT: "12345", + }, + prepareCommand: async ({ command, env }) => { + seen.push(`${command} ${env.PASEO_BRANCH_NAME}`); + if (command.startsWith("echo refused")) throw new Error("not in this workspace"); + return { env: { ...env, HOOK_MARK: "prepared" }, wrap: [launcher, "--profile", "a b"] }; + }, + }); + + await expect(setup).rejects.toMatchObject({ + name: "WorktreeSetupError", + message: + "Worktree setup command refused: echo refused > refused.log\nnot in this workspace", + results: [expect.objectContaining({ exitCode: 0 })], + }); + expect(seen).toEqual([ + 'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log main', + "echo refused > refused.log main", + ]); + expect(readFileSync(join(repoDir, "launch-argv.log"), "utf8").trim().split("\n")).toEqual([ + "--profile", + "a b", + "bash", + "-c", + 'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log', + ]); + expect(readFileSync(join(repoDir, "first.log"), "utf8").trim()).toBe("prepared"); + // The part after `&&` ran inside the launcher too. + expect(readFileSync(join(repoDir, "second-part.log"), "utf8").trim()).toBe("wrapped"); + expect(existsSync(join(repoDir, "refused.log"))).toBe(false); + }); + + it("reports a streamed setup command that cannot start as a failed command", async () => { + // Node refuses a null byte in an argument before it starts the process, as the SDK refuses a + // line break for a Windows cmd.exe launch. + writeFileSync( + join(repoDir, "paseo.json"), + JSON.stringify({ worktree: { setup: "echo a\0b" } }), + ); + const events: string[] = []; + const setup = runWorktreeSetupCommands({ + worktreePath: repoDir, + branchName: "main", + runtimeEnv: { + PASEO_SOURCE_CHECKOUT_PATH: repoDir, + PASEO_ROOT_PATH: repoDir, + PASEO_WORKTREE_PATH: repoDir, + PASEO_BRANCH_NAME: "main", + PASEO_WORKTREE_PORT: "12345", + }, + signal: new AbortController().signal, + onEvent: (event) => events.push(event.type), + }); + + await expect(setup).rejects.toMatchObject({ + name: "WorktreeSetupError", + results: [ + expect.objectContaining({ + exitCode: null, + stderr: expect.stringContaining("null bytes"), + }), + ], + }); + expect(events).toEqual(["command_started", "output", "command_completed"]); + }); + it("runs string setup scripts from paseo.json as a single shell command", async () => { const paseoConfig = { worktree: { diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index a3ce36d170..58bd50cbb1 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -223,6 +223,45 @@ describe("paseo worktree manager", () => { }).toEqual({ exitCode: 0, stdoutLength: limit, stderrLength: limit }); }); + it("stops teardown at its deadline while a plugin hook is pending, without starting the command", async () => { + writeFileSync( + join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { + teardown: `node -e "require('fs').writeFileSync('ran.txt', 'ran')"`, + teardownTimeoutMs: 100, + }, + }), + ); + let hookDone!: () => void; + const hookSettled = new Promise((resolve) => { + hookDone = resolve; + }); + + const startedAt = Date.now(); + await expect( + runWorktreeTeardownCommands({ + worktreePath: repoDir, + repoRootPath: repoDir, + branchName: "main", + prepareCommand: async ({ env }) => { + await new Promise((resolve) => setTimeout(resolve, 1000)); + hookDone(); + return { env }; + }, + }), + ).rejects.toMatchObject({ + name: "WorktreeTeardownError", + message: `Worktree teardown command failed: node -e "require('fs').writeFileSync('ran.txt', 'ran')"\nTimed out after 0.1s`, + results: [], + }); + expect(Date.now() - startedAt).toBeLessThan(900); + // The hook answering after the deadline does not start the command. + await hookSettled; + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(existsSync(join(repoDir, "ran.txt"))).toBe(false); + }); + it("rejects paths that are not under the paseo worktrees root", async () => { const outsidePath = join(tempDir, "outside-paseo-home"); mkdirSync(outsidePath, { recursive: true }); diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index ee587f14ef..d7b5d42270 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -1,4 +1,3 @@ -import { execFile } from "child_process"; import { promisify } from "util"; import { constants as fsConstants, type Dirent, realpath } from "fs"; import { copyFile, mkdir, readdir, rm, stat } from "fs/promises"; @@ -7,9 +6,11 @@ import net from "node:net"; import { createHash } from "node:crypto"; import stripAnsi from "strip-ansi"; import pLimit from "p-limit"; +import { execCommand } from "@getpaseo/plugin/server"; import { buildStringCommandShellInvocation, createStringCommandShellEnv, + type StringCommandShellInvocation, } from "./string-command-shell.js"; import { readPaseoConfig } from "./paseo-config-file.js"; export { @@ -38,6 +39,7 @@ import { runWithRepositoryRoot } from "./git-repository-discovery.js"; import { runGitCommand } from "./run-git-command.js"; import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js"; import { spawnProcess } from "./spawn.js"; +import { applyLaunchWrap } from "./launch-wrap.js"; import { resolvePaseoHome } from "../server/paseo-home.js"; import { createExternalProcessEnv } from "../server/paseo-env.js"; import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js"; @@ -55,7 +57,6 @@ import type { PluginWorktreeManagerRuntime } from "../server/plugins/runtime.js" export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug"; -const execFileAsync = promisify(execFile); const READ_ONLY_GIT_ENV = { GIT_OPTIONAL_LOCKS: "0", } as const; @@ -140,6 +141,64 @@ export function isServiceScript(config: ScriptConfig): config is ServiceScriptCo return "type" in config && config.type === "service"; } +/** A lifecycle command, and the environment Paseo adds to the daemon's for it. */ +export interface WorktreeLifecycleCommand { + command: string; + env: Record; +} + +/** How a lifecycle command runs after plugins saw it: its environment and an optional wrap. */ +export interface PreparedWorktreeLifecycleCommand { + env: Record; + wrap?: readonly [string, ...string[]]; +} + +/** Lets plugins wrap or refuse a lifecycle command before it runs; see `command.run.before`. */ +export type PrepareWorktreeLifecycleCommand = ( + command: WorktreeLifecycleCommand, +) => Promise; + +/** + * Asks the hooks how to run `command`. Resolves to `null` when `signal` aborts first, such as at the + * teardown deadline or when archive cancels setup; the command must then not start. + */ +async function prepareLifecycleCommand(options: { + prepare: PrepareWorktreeLifecycleCommand | undefined; + command: WorktreeLifecycleCommand; + signal: AbortSignal | undefined; + fail: (message: string) => Error; +}): Promise { + const { prepare, command, signal } = options; + if (signal?.aborted) return null; + if (!prepare) return { env: command.env }; + let stopWaiting = () => {}; + const aborted = new Promise((settle) => { + const onAbort = () => settle(null); + signal?.addEventListener("abort", onAbort, { once: true }); + stopWaiting = () => signal?.removeEventListener("abort", onAbort); + }); + const prepared = prepare(command).catch((error: unknown) => { + throw options.fail(error instanceof Error ? error.message : String(error)); + }); + // A hook that settles after the abort no longer matters; keep its rejection handled. + prepared.catch(() => {}); + try { + return await Promise.race([prepared, aborted]); + } finally { + stopWaiting(); + } +} + +/** The shell invocation for a `paseo.json` command, started behind a plugin's wrap when set. */ +function lifecycleCommandInvocation( + command: string, + wrap: PreparedWorktreeLifecycleCommand["wrap"], +): StringCommandShellInvocation { + const invocation = buildStringCommandShellInvocation({ command }); + const launch = applyLaunchWrap({ command: invocation.shell, args: invocation.args }, wrap); + return { shell: launch.command, args: launch.args }; +} + export class WorktreeSetupError extends Error { readonly results: WorktreeSetupCommandResult[]; @@ -445,14 +504,16 @@ export function processCarriageReturns(text: string): string { async function execSetupCommand( command: string, - options: { cwd: string; env: NodeJS.ProcessEnv }, + options: { cwd: string; env: NodeJS.ProcessEnv; wrap: PreparedWorktreeLifecycleCommand["wrap"] }, ): Promise { const startedAt = Date.now(); - const shellInvocation = buildStringCommandShellInvocation({ command }); + const shellInvocation = lifecycleCommandInvocation(command, options.wrap); try { - const { stdout, stderr } = await execFileAsync(shellInvocation.shell, shellInvocation.args, { + // execCommand starts a Windows `.cmd` or `.bat` wrap through cmd.exe; anything else has no shell. + const { stdout, stderr } = await execCommand(shellInvocation.shell, shellInvocation.args, { cwd: options.cwd, env: options.env, + shell: false, }); return { command, @@ -477,6 +538,7 @@ async function execSetupCommand( async function execSetupCommandStreamed(options: { command: string; + wrap: PreparedWorktreeLifecycleCommand["wrap"]; cwd: string; env: NodeJS.ProcessEnv; index: number; @@ -556,21 +618,29 @@ async function execSetupCommandStreamed(options: { cwd: options.cwd, }); - const shellInvocation = buildStringCommandShellInvocation({ command: options.command }); - const child = spawnProcess(shellInvocation.shell, shellInvocation.args, { - cwd: options.cwd, - env: options.env, - shell: false, - stdio: ["ignore", "pipe", "pipe"], - }); + const shellInvocation = lifecycleCommandInvocation(options.command, options.wrap); + let child: ReturnType; + try { + child = spawnProcess(shellInvocation.shell, shellInvocation.args, { + cwd: options.cwd, + env: options.env, + shell: false, + stdio: ["ignore", "pipe", "pipe"], + }); + } catch (error) { + // A command that cannot start fails like one whose process reports a spawn error. + emitOutput("stderr", error instanceof Error ? error.message : String(error)); + void finish(null); + return; + } - const abort = () => { + function abort(): void { termination ??= terminateWithTreeKill(child, { gracefulTimeoutMs: 1000, forceTimeoutMs: 1000, }); void finish(null); - }; + } if (options.signal?.aborted) { abort(); } else { @@ -678,6 +748,7 @@ export async function runWorktreeSetupCommands(options: { runtimeEnv?: WorktreeRuntimeEnv; signal?: AbortSignal; onEvent?: (event: WorktreeSetupCommandProgressEvent) => void; + prepareCommand?: PrepareWorktreeLifecycleCommand; }): Promise { // Read paseo.json from the worktree (it will have the same content as the source repo) const setupCommands = await getWorktreeSetupCommands(options.worktreePath); @@ -692,13 +763,26 @@ export async function runWorktreeSetupCommands(options: { branchName: options.branchName, ...(options.repoRootPath ? { repoRootPath: options.repoRootPath } : {}), })); - const setupEnv = createStringCommandShellEnv(createExternalProcessEnv(process.env, runtimeEnv)); const results: WorktreeSetupCommandResult[] = []; for (const [index, cmd] of setupCommands.entries()) { + const prepared = await prepareLifecycleCommand({ + prepare: options.prepareCommand, + command: { command: cmd, env: { ...runtimeEnv } }, + signal: options.signal, + fail: (message) => + new WorktreeSetupError(`Worktree setup command refused: ${cmd}\n${message}`, results), + }); + if (!prepared) { + throw new WorktreeSetupError(`Worktree setup canceled before: ${cmd}`, results); + } + const setupEnv = createStringCommandShellEnv( + createExternalProcessEnv(process.env, prepared.env), + ); const result = options.onEvent ? await execSetupCommandStreamed({ command: cmd, + wrap: prepared.wrap, cwd: options.worktreePath, env: setupEnv, index: index + 1, @@ -709,6 +793,7 @@ export async function runWorktreeSetupCommands(options: { : await execSetupCommand(cmd, { cwd: options.worktreePath, env: setupEnv, + wrap: prepared.wrap, }); results.push(result); @@ -779,6 +864,7 @@ export async function runWorktreeTeardownCommands(options: { teardownCwd?: string; branchName?: string; repoRootPath?: string; + prepareCommand?: PrepareWorktreeLifecycleCommand; }): Promise { const teardownCwd = options.teardownCwd ?? options.worktreePath; if ((await getOwnershipRelativePath(options.worktreePath, teardownCwd)) === null) { @@ -795,29 +881,41 @@ export async function runWorktreeTeardownCommands(options: { options.branchName ?? (await resolveBranchNameForWorktreePath(options.worktreePath)); const worktreePort = await readPaseoWorktreeRuntimePort(options.worktreePath); - const teardownEnv: NodeJS.ProcessEnv = createStringCommandShellEnv( - createExternalProcessEnv(process.env, { - // Source checkout path is the original git repo root (shared across worktrees), not the - // worktree itself. This allows lifecycle scripts to copy or clean resources using paths - // from the source checkout. - PASEO_SOURCE_CHECKOUT_PATH: repoRootPath, - // Backward-compatible alias. - PASEO_ROOT_PATH: repoRootPath, - PASEO_WORKTREE_PATH: options.worktreePath, - PASEO_BRANCH_NAME: branchName, - ...(worktreePort !== null ? { PASEO_WORKTREE_PORT: String(worktreePort) } : {}), - }), - ); + const runtimeEnv: Record = { + // Source checkout path is the original git repo root (shared across worktrees), not the + // worktree itself. This allows lifecycle scripts to copy or clean resources using paths + // from the source checkout. + PASEO_SOURCE_CHECKOUT_PATH: repoRootPath, + // Backward-compatible alias. + PASEO_ROOT_PATH: repoRootPath, + PASEO_WORKTREE_PATH: options.worktreePath, + PASEO_BRANCH_NAME: branchName, + ...(worktreePort !== null ? { PASEO_WORKTREE_PORT: String(worktreePort) } : {}), + }; // One deadline covers every command. Reaching it counts as failure and keeps the worktree. const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd); const deadline = AbortSignal.timeout(timeoutMs); const results: WorktreeTeardownCommandResult[] = []; for (const [index, cmd] of teardownCommands.entries()) { + const prepared = await prepareLifecycleCommand({ + prepare: options.prepareCommand, + command: { command: cmd, env: { ...runtimeEnv } }, + signal: deadline, + fail: (message) => + new WorktreeTeardownError(`Worktree teardown command refused: ${cmd}\n${message}`, results), + }); + if (!prepared) { + throw new WorktreeTeardownError( + `Worktree teardown command failed: ${cmd}\nTimed out after ${timeoutMs / 1000}s`, + results, + ); + } const result = await execSetupCommandStreamed({ command: cmd, + wrap: prepared.wrap, cwd: teardownCwd, - env: teardownEnv, + env: createStringCommandShellEnv(createExternalProcessEnv(process.env, prepared.env)), index: index + 1, total: teardownCommands.length, signal: deadline, diff --git a/plugin-examples/lifecycle-logger/README.md b/plugin-examples/lifecycle-logger/README.md index 60259d34c7..6c08d5beaf 100644 --- a/plugin-examples/lifecycle-logger/README.md +++ b/plugin-examples/lifecycle-logger/README.md @@ -1,7 +1,8 @@ # Lifecycle logger -Registers agent, workspace, and worktree hooks and logs their data as JSON. It observes agent creation, -session opening, turns, permissions, archive, and workspace creation/archive. Before hooks return +Registers agent, workspace, worktree, terminal, and command hooks and logs their data as JSON. It +observes agent creation, session opening, turns, permissions, archive, workspace creation/archive, +terminal creation, and worktree setup and teardown commands. Before hooks return the request unchanged. Environment values are redacted; prompts and timeline content are logged. Install it on a daemon where plugins are enabled: diff --git a/plugin-examples/lifecycle-logger/index.server.ts b/plugin-examples/lifecycle-logger/index.server.ts index e87be2c2f6..ef7ce3caff 100644 --- a/plugin-examples/lifecycle-logger/index.server.ts +++ b/plugin-examples/lifecycle-logger/index.server.ts @@ -57,5 +57,15 @@ export default function contribute(server: PluginServerContext) { logHook("agent.archive.after", event); }); + server.addHook("terminal.create.before", async ({ request }) => { + logHook("terminal.create.before", { request }); + return request; + }); + + server.addHook("command.run.before", async ({ request }) => { + logHook("command.run.before", { request }); + return request; + }); + return () => {}; } diff --git a/plugins/antigravity-provider/server/provider.test.ts b/plugins/antigravity-provider/server/provider.test.ts index 6e8bbd1ba9..9faa3b470f 100644 --- a/plugins/antigravity-provider/server/provider.test.ts +++ b/plugins/antigravity-provider/server/provider.test.ts @@ -886,3 +886,75 @@ it("keeps a turn open for backgrounded run_command calls but not IsDaemon comman await connection.close(); } }); + +it("runs a wrapped session as [...wrap, agy, acp, --disable-telemetry] with the session env", async () => { + const { directory, launch: fixture } = await launchAgent(` + const { createInterface } = require("node:readline"); + const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); + createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method } = JSON.parse(line); + if (method === "initialize") send({ id, result: { protocolVersion: 1 } }); + if (method === "session/new") { + send({ id, result: { sessionId: "native", configOptions: [{ id: "mode", name: "Mode", category: "mode", type: "select", currentValue: "default", options: [{ value: "default", name: "Default" }] }] } }); + send({ method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "available_commands_update", availableCommands: [] } } }); + } + }); + `); + // Records what it was started with, then runs the rest: the provider's own launch. + const launcher = path.join(directory, "launcher.cjs"); + const record = path.join(directory, "launch.json"); + await writeFile( + launcher, + `const { writeFileSync } = require("node:fs"); +const { spawn } = require("node:child_process"); +const [log, command, ...args] = process.argv.slice(2); +writeFileSync(log, JSON.stringify({ argv: process.argv.slice(2), hook: process.env.HOOK_ENV ?? null })); +const child = spawn(command, args, { stdio: "inherit" }); +process.on("SIGTERM", () => child.kill("SIGTERM")); +child.on("exit", (code) => process.exit(code ?? 1)); +`, + ); + const provider = createAntigravityProvider(); + expect(provider.launchWrap).toBe(true); + // The daemon resolves the registration's executable and passes its arguments as declared; + // Node running the fake agent stands in for the resolved `agy`. + const [executable, ...declaredArgs] = provider.command!; + expect(executable).toBe("agy"); + const agentScript = fixture.args[0]!; + const launch = { ...fixture, args: [agentScript, ...declaredArgs] }; + const connection = await provider.connect({ + launch, + versions: [1], + capabilities: ["prompt.message", "session.launch_wrap"], + }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + type: "session.open", + requestId: "new", + sessionId: "test", + history: "skip", + config: { + cwd: directory, + env: { HOOK_ENV: "final" }, + mcpServers: {}, + settings: {}, + persist: false, + wrap: [process.execPath, launcher, record], + }, + }); + await expect + .poll(() => + events.find((event) => event.type === "session.ready" || event.type === "request.failed"), + ) + .toMatchObject({ type: "session.ready" }); + const launched = JSON.parse(await readFile(record, "utf8")); + expect(launched).toEqual({ + argv: [record, process.execPath, agentScript, "acp", "--disable-telemetry"], + hook: "final", + }); + } finally { + await connection.close(); + } +}); diff --git a/plugins/muse-provider/server/connection.ts b/plugins/muse-provider/server/connection.ts index 3fca09ef5e..35feda5d8b 100644 --- a/plugins/muse-provider/server/connection.ts +++ b/plugins/muse-provider/server/connection.ts @@ -41,6 +41,8 @@ export class MspConnection { constructor( private readonly options: { launch: ProviderLaunch; + /** Start `muse serve` as `[...wrap, command, ...args]`. */ + wrap?: readonly [string, ...string[]]; cwd?: string; timeoutMs?: number; startupTimeoutMs?: number; @@ -52,6 +54,7 @@ export class MspConnection { launch.command, [...launch.args, "serve", ...(options.serveArgs ?? [])], { + wrap: options.wrap, env: launch.env, cwd, stdio: "pipe", diff --git a/plugins/muse-provider/server/provider.ts b/plugins/muse-provider/server/provider.ts index 00732f2740..3521a14cfb 100644 --- a/plugins/muse-provider/server/provider.ts +++ b/plugins/muse-provider/server/provider.ts @@ -29,6 +29,7 @@ const capabilities = [ "prompt.image", "prompt.steer", "session.configure", + "session.launch_wrap", "session.persistence", "permission", "session.list", @@ -48,6 +49,8 @@ export function createMuseProvider( label: "Muse Code", icon: "icon.svg", command: ["muse"], + // Each session starts its own `muse serve`, so it can run behind that session's wrap. + launchWrap: true, docsUrl: "https://paseo.sh/docs/supported-providers/muse-code", installation: { installUrl: "https://paseo.sh/docs/muse-code", diff --git a/plugins/muse-provider/server/session.ts b/plugins/muse-provider/server/session.ts index 31066c5b04..48055951dc 100644 --- a/plugins/muse-provider/server/session.ts +++ b/plugins/muse-provider/server/session.ts @@ -87,6 +87,7 @@ export class Session { this.config = options.config; this.host = new MspConnection({ launch: { ...options.launch, env: { ...options.launch.env, ...options.config.env } }, + wrap: options.config.wrap, cwd: options.config.cwd, serveArgs: options.serveArgs, }); diff --git a/plugins/muse-provider/test/provider.test.ts b/plugins/muse-provider/test/provider.test.ts index 1dd61778ad..c82e94acfb 100644 --- a/plugins/muse-provider/test/provider.test.ts +++ b/plugins/muse-provider/test/provider.test.ts @@ -162,6 +162,52 @@ test("registration exposes Muse with a daemon-resolved command", () => { icon: "icon.svg", }); }); +test("a session's launch wrap starts Muse serve and the session runs through it", async () => { + const h = await harness(); + const launcher = path.join(h.root, "launcher.mjs"); + const marker = path.join(h.root, "wrapped.json"); + await writeFile( + launcher, + [ + 'import { spawn } from "node:child_process";', + 'import { writeFileSync } from "node:fs";', + "const [command, ...args] = process.argv.slice(2);", + "writeFileSync(process.env.MUSE_TEST_WRAP_MARKER, JSON.stringify([command, ...args]));", + 'const child = spawn(command, args, { stdio: "inherit" });', + 'child.on("exit", (code) => process.exit(code ?? 1));', + "", + ].join("\n"), + ); + const from = await h.send({ + type: "session.open", + requestId: "open", + sessionId: "paseo-session", + config: { + cwd: h.root, + env: { MUSE_TEST_WRAP_MARKER: marker }, + settings: {}, + mcpServers: {}, + persist: true, + mode: "onRequest", + model: "meta/muse-spark-1.3", + systemPrompt: "Test instructions", + wrap: [process.execPath, launcher], + }, + history: "replay", + }); + expect( + await h.wait( + (event) => event.type === "session.ready" || event.type === "request.failed", + from, + ), + ).toMatchObject({ type: "session.ready" }); + const wrapped = JSON.parse(await readFile(marker, "utf8")) as string[]; + expect(wrapped.slice(0, h.launch.args.length + 2)).toEqual([ + h.launch.command, + ...h.launch.args, + "serve", + ]); +}); test("installation links to the Muse guide and reports the installed version", async () => { const provider = registration(); const launch = { diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md index d62cb9e542..488665d3e1 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -24,14 +24,14 @@ export default function contribute(server: PluginServerContext) { ## Naming and timing -Names follow `subject.operation.position`: the subject, the operation, then `before` or `after`. The name identifies a lifecycle position. Whether Paseo waits is a per-hook property shown in the table below. `workspace` covers every workspace; `worktree` covers only git worktrees. +Names follow `subject.operation.position`: the subject, the operation, then `before` or `after`. The name identifies a lifecycle position. Whether Paseo waits is a per-hook property shown in the table below. `workspace` covers every workspace; `worktree` covers only git worktrees. `terminal` covers every terminal Paseo starts in a workspace; `command` covers worktree setup and teardown commands. - Waiting hooks finish before Paseo continues. Throwing, returning invalid data, or exceeding 30 seconds fails the operation with `Plugin failed: …`. Request-changing hooks receive `{ request }` and may return a complete replacement request or `undefined`. - Notifications receive the event object and return `Promise`. Paseo does not wait; errors are logged against the plugin and the operation continues. `agent.turn.before` and `agent.permission.before` are notifications fired when a turn starts or a permission becomes pending. All handlers must be async. Turn completion includes success, failure, and cancellation; inspect `outcome`. Permission completion includes every resolution; inspect `resolution`. -Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, instructions, tools, and MCP servers each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action. +Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, instructions, tools, MCP servers, and a launch wrap each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action. `worktree.create.after` runs before the workspace is registered. It precedes `workspace.create.after`, and both precede the first agent's `agent.create.before` / `agent.open.before`. @@ -49,22 +49,24 @@ Paseo only sees the returned promise, so detached work gets no error reporting a ## Hooks -| Hook | Waits | Payload | Handler may change | -| ------------------------- | ----- | ----------------------------------------- | -------------------------------------------------------------- | -| `workspace.create.before` | yes | `{ request }` | Entire create request | -| `workspace.create.after` | no | `{ workspace }` | | -| `workspace.archive.after` | no | `{ workspace }` | | -| `worktree.create.before` | yes | `{ request }` | Creation options and destination | -| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | -| `agent.create.before` | yes | `{ request: { config, env?, metadata } }` | Saved config except `cwd`; `env`; `metadata` | -| `agent.create.after` | no | `{ agent }` | | -| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `appendSystemPrompt`, `tools`, `mcpServers` | -| `agent.close.after` | no | `{ agent }` | | -| `agent.archive.after` | no | `{ agent, archivedAt }` | | -| `agent.turn.before` | no | `{ agent, turnId }` | | -| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | -| `agent.permission.before` | no | `{ agent, request }` | | -| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | +| Hook | Waits | Payload | Handler may change | +| ------------------------- | ----- | ------------------------------------------------------ | ---------------------------------------------------------------------- | +| `workspace.create.before` | yes | `{ request }` | Entire create request | +| `workspace.create.after` | no | `{ workspace }` | | +| `workspace.archive.after` | no | `{ workspace }` | | +| `worktree.create.before` | yes | `{ request }` | Creation options and destination | +| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | +| `agent.create.before` | yes | `{ request: { config, env?, metadata, workspaceId } }` | Saved config except `cwd`; `env`; `metadata` | +| `agent.create.after` | no | `{ agent }` | | +| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `appendSystemPrompt`, `tools`, `mcpServers`, `wrap` | +| `agent.close.after` | no | `{ agent }` | | +| `agent.archive.after` | no | `{ agent, archivedAt }` | | +| `agent.turn.before` | no | `{ agent, turnId }` | | +| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | no | `{ agent, request }` | | +| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | +| `terminal.create.before` | yes | `{ request }` | `env`, `wrap`; throw to refuse | +| `command.run.before` | yes | `{ request }` | `env`, `wrap`; throw to refuse | ## Shared payloads @@ -124,6 +126,23 @@ await paseo.workspaces.ref(workspaceId).setMetadata({ "linear.issue": { id: "ENG Metadata survives a daemon restart. Every hook payload carries it: `workspace.create.before` and `agent.create.before` receive the metadata the caller sent, and the `after` hooks and `agent.open.before` receive what is stored. Against a host that predates metadata, these calls throw "Update the host to use metadata." +## Launch wraps {#launch-wraps} + +`agent.open.before`, `terminal.create.before`, and `command.run.before` can return `wrap: [executable, ...args]`, a `PluginLaunchWrap`. Paseo then starts the process as `[...wrap, command, ...args]`, for example under a sandbox: + +```ts +import type { PluginLaunchWrap } from "@getpaseo/plugin/server"; + +const sandbox: PluginLaunchWrap = ["/usr/local/bin/sandbox-run", "--profile", "agent"]; +``` + +- The executable must be an absolute path on the daemon host. Paseo runs it without a shell, except Windows `.cmd` and `.bat` launchers, which go through cmd.exe. Each element stays one argument. +- The first hook that returns a wrap selects it. A later hook, in the same plugin or a later one, may omit `wrap` or return the same value. A different value fails the operation. +- A wrap is never saved. Every launch asks the hooks again. +- A host that predates `wrap` rejects the field, so the operation fails instead of running unwrapped. + +Each hook section below lists what its wrap covers. + ## workspace.create.before Receives `{ request }` with `source`, optional `title`, optional `metadata`, and `firstAgentContext`. You may replace the entire explicit create request; a throw, invalid result, or timeout fails creation. Existing workspaces and directory lookup/import are unaffected. @@ -224,9 +243,63 @@ server.addHook("worktree.create.after", async ({ worktree }) => { }); ``` +## terminal.create.before {#terminalcreatebefore} + +Paseo waits for this hook before it starts a terminal in a workspace: + +- **New terminal** and terminal profiles in the app, and terminals created through the CLI, SDK, and plugins +- terminals agents open with Paseo tools +- the terminals `paseo.json` scripts, services, and worktree terminals run in + +Receives `{ request }`; return a replacement request or `undefined`. Only `env` and `wrap` may change. Throwing refuses the terminal, and whoever asked for it gets `Plugin terminal.create.before failed: …`. + +```ts +server.addHook("terminal.create.before", async ({ request }) => { + if (!sandboxed.has(request.workspaceId)) return; + return { ...request, wrap: ["/usr/local/bin/sandbox-run", "--profile", "terminal"] }; +}); +``` + +| Request field | Meaning | +| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | Read-only; the terminal's workspace | +| `cwd` | Read-only; where the terminal starts | +| `source` | Read-only. `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a `paseo.json` worktree terminal. `client`: the app, CLI, SDK, or a plugin | +| `name` | Read-only; the tab name, or null | +| `input` | Read-only. For `script` and `worktree`, the command Paseo types into the shell once it starts; otherwise null | +| `command`, `args` | Read-only; the program and its arguments. `command` is null for the default shell | +| `env` | Variables Paseo adds to the terminal's environment | +| `wrap` | Optional [launch wrap](#launch-wraps). Paseo starts `[...wrap, command, ...args]`; with no `command`, it puts the default shell after the wrap | + +Scripts, services, and worktree terminals start the default shell and then type their command into it, so a wrap on the shell also covers what they run. A wrapped shell starts without Paseo's shell integration, so a wrapped `paseo.json` script does not report when its command finishes. A terminal that survives a daemon restart is adopted, not created again, and doesn't run the hook again. A plugin that creates a terminal from inside this hook runs the hook for that terminal too. + +## command.run.before {#commandrunbefore} + +Paseo waits for this hook before each `paseo.json` worktree `setup` and `teardown` command. Receives `{ request }`; return a replacement request or `undefined`. Only `env` and `wrap` may change. Throwing refuses the command: setup stops and reports the plugin's error, and teardown stops and keeps the worktree directory, as a failing command does. + +```ts +server.addHook("command.run.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox-run", "--profile", request.purpose], +})); +``` + +| Request field | Meaning | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | Read-only; the workspace, or null when a worktree is archived by path and no workspace record remains | +| `cwd` | Read-only; where the command runs | +| `purpose` | Read-only; `setup` or `teardown` | +| `command` | Read-only; the command as written in `paseo.json`. Paseo runs it with `bash -c` on macOS and Linux, and with PowerShell or `cmd.exe` on Windows | +| `env` | Variables Paseo adds to the daemon's environment: `PASEO_SOURCE_CHECKOUT_PATH`, `PASEO_WORKTREE_PATH`, `PASEO_BRANCH_NAME`, and the rest | +| `wrap` | Optional [launch wrap](#launch-wraps). Paseo starts the shell behind it: `[...wrap, "bash", "-c", command]` on macOS and Linux | + +Setup starts after the workspace is registered and `workspace.create.after` is emitted, and runs alongside the first agent. When setup runs again, such as from **Run setup** on a worktree whose setup was blocked, each command runs the hook again. Teardown runs when the last workspace on a worktree is archived, before Paseo removes the directory. + ## agent.create.before -Receives `{ request: { config, env?, metadata } }`. Config and `metadata` changes are saved and remain after the plugin is disabled or removed; `env` applies to the initial launch and is not saved. You cannot change `config.cwd`. A throw, invalid result, or timeout fails creation. +Receives `{ request: { config, env?, metadata, workspaceId } }`. Config and `metadata` changes are saved and remain after the plugin is disabled or removed; `env` applies to the initial launch and is not saved. You cannot change `config.cwd` or `workspaceId`. A throw, invalid result, or timeout fails creation. + +`workspaceId` is the workspace the agent is created in, or null. Use it rather than `config.cwd` to find the workspace: several workspaces can share a directory, and an agent can be created in one workspace with a directory inside another. **`agent.create.before.config`** uses `AgentSessionConfig`: @@ -283,7 +356,7 @@ server.addHook("agent.create.after", async ({ agent }) => { ## agent.open.before -Receives `{ request }`; only `env`, `appendSystemPrompt`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open. +Receives `{ request }`; only `env`, `appendSystemPrompt`, `tools`, `mcpServers`, and `wrap` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open. Do not await a write to the agent being opened: `setMetadata`, `setLabels`, or an option, model, thinking or mode change. The write waits for the open to finish, the open waits for your hook, so the hook times out and the open fails. Start the write without awaiting it; it runs right after the open: @@ -316,18 +389,37 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { } ``` -| Field | Values | -| ------------- | ----------------------------------------------------------------------------------------------------------------------- | -| `workspaceId` | String or `null` | -| `title` | Read-only string or `null`; creation title on create, stored title on resume. | -| `background` | Read-only `true` for a [background agent](#background-agents). Fixed at creation. | -| `labels` | Read-only string map; creation labels on create, stored labels on resume. | -| `metadata` | Read-only JSON map; the [metadata](#metadata) stored on the agent. | -| `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | -| `mcpServers` | Editable launch-only server map, local to this plugin. See [Inject MCP servers](#inject-mcp-servers). | -| `reason` | `create`, `resume`, `refresh`, `import` | -| `purpose` | `interactive`, `history` | -| `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | +| Field | Values | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | String or `null` | +| `title` | Read-only string or `null`; creation title on create, stored title on resume. | +| `background` | Read-only `true` for a [background agent](#background-agents). Fixed at creation. | +| `labels` | Read-only string map; creation labels on create, stored labels on resume. | +| `metadata` | Read-only JSON map; the [metadata](#metadata) stored on the agent. | +| `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | +| `mcpServers` | Editable launch-only server map, local to this plugin. See [Inject MCP servers](#inject-mcp-servers). | +| `reason` | `create`, `resume`, `refresh`, `import` | +| `purpose` | `interactive`, `history` | +| `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | +| `wrap` | Optional [launch wrap](#launch-wraps) to start the harness behind. See [Run the harness behind a launch wrap](#run-the-harness-behind-a-launch-wrap). | + +### Run the harness behind a launch wrap + +Return a [launch wrap](#launch-wraps) to start the provider's harness as `[...wrap, command, ...args]`: + +```ts +server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox-run", "--profile", "agent"], +})); +``` + +- A provider applies a wrap when its provider snapshot entry has `launchWrap: true`. Every built-in provider and every custom ACP provider does. A plugin provider does when it declares support, as Muse Code and the ACP plugin providers such as Antigravity do. Read the field with `paseo.providers.snapshot()` in `agent.create.before` and choose a provider there. A wrap for any other provider fails the open; it is never dropped. +- History opens keep the wrap. +- A wrapped OpenCode session gets its own OpenCode server, which starts behind the wrap. An OpenCode provider configured to use an existing server cannot start one, so a wrapped open fails. +- The harness does not always start in the agent's directory. Codex starts it in the daemon's directory, and OpenCode starts its server in the `opencode-home` directory under the Paseo home. Both send the session directory over their protocol. If your launcher needs the directory, put `request.cwd` in the wrap's arguments. +- Keep the system temp directory visible inside the wrap. Paseo writes the Pi extension there before it starts Pi, and Claude Code writes its tool output there. A launcher that hides it behind an empty private directory breaks those sessions. +- The wrap covers the processes that Paseo starts for the session: the harness, the stdio MCP servers that Paseo hosts for the agent, and the terminals that an ACP agent asks Paseo to run. Paseo's host terminal tools, provider availability and catalog probes, and draft discovery run outside it. ### Append instructions on every session opening @@ -724,13 +816,13 @@ replaces that scope's prior value. ## Complete examples -| Plugin | Includes | -| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | -| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent, workspace, and worktree hooks; JSON logs with environment values redacted | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | -| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | Worktree manager (`create`, `remove`, `restore`) and agent activity markers | +| Plugin | Includes | +| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | +| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent, workspace, worktree, terminal, and command hooks; JSON logs with environment values redacted | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | +| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | Worktree manager (`create`, `remove`, `restore`) and agent activity markers | Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`. diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index 7bffe7150a..30ee45209a 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -22,14 +22,14 @@ export default function contribute(server: PluginServerContext) { ## 命名与等待 {#naming-and-timing} -名称遵循 `subject.operation.position`:主体、操作、`before` 或 `after`。名称标识生命周期中的位置;Paseo 是否等待由每个钩子决定,见下表。`workspace` 包括所有工作区,`worktree` 仅包括 git worktree。 +名称遵循 `subject.operation.position`:主体、操作、`before` 或 `after`。名称标识生命周期中的位置;Paseo 是否等待由每个钩子决定,见下表。`workspace` 包括所有工作区,`worktree` 仅包括 git worktree。`terminal` 包括 Paseo 在工作区中启动的所有终端,`command` 包括 worktree 的 setup 和 teardown 命令。 - 等待型钩子结束后 Paseo 才继续。抛出错误、返回无效数据或超过 30 秒会让操作失败,错误包含 `Plugin failed: …`。修改请求的钩子收到 `{ request }`,可以返回完整的替换请求或 `undefined`。 - 通知收到事件对象,返回 `Promise`。Paseo 不等待;错误会记录在插件名下,原操作继续。`agent.turn.before` 和 `agent.permission.before` 分别在轮次开始或权限进入待处理状态时发出通知。 所有处理函数都必须为异步函数。轮次完成包括成功、失败和取消,请查看 `outcome`。权限完成包括所有处理结果,请查看 `resolution`。 -创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、指令、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 +创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、指令、工具、MCP 服务器和启动包装。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 `worktree.create.after` 在工作区注册前运行,随后是 `workspace.create.after`,两者都早于第一个 Agent 的 `agent.create.before` / `agent.open.before`。 @@ -47,22 +47,24 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 ## 钩子一览 {#hooks} -| 钩子 | 等待 | 载荷 | 可修改 | -| ------------------------- | ---- | ----------------------------------------- | --------------------------------------------------------------- | -| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | -| `workspace.create.after` | 否 | `{ workspace }` | | -| `workspace.archive.after` | 否 | `{ workspace }` | | -| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | -| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | -| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | -| `agent.create.after` | 否 | `{ agent }` | | -| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`appendSystemPrompt`、`tools`、`mcpServers` | -| `agent.close.after` | 否 | `{ agent }` | | -| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | -| `agent.turn.before` | 否 | `{ agent, turnId }` | | -| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | -| `agent.permission.before` | 否 | `{ agent, request }` | | -| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | +| 钩子 | 等待 | 载荷 | 可修改 | +| ------------------------- | ---- | ------------------------------------------------------ | ----------------------------------------------------------------------- | +| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | +| `workspace.create.after` | 否 | `{ workspace }` | | +| `workspace.archive.after` | 否 | `{ workspace }` | | +| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | +| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | +| `agent.create.before` | 是 | `{ request: { config, env?, metadata, workspaceId } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | +| `agent.create.after` | 否 | `{ agent }` | | +| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`appendSystemPrompt`、`tools`、`mcpServers`、`wrap` | +| `agent.close.after` | 否 | `{ agent }` | | +| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | +| `agent.turn.before` | 否 | `{ agent, turnId }` | | +| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | 否 | `{ agent, request }` | | +| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | +| `terminal.create.before` | 是 | `{ request }` | `env`、`wrap`;抛出错误则拒绝 | +| `command.run.before` | 是 | `{ request }` | `env`、`wrap`;抛出错误则拒绝 | ## 共享载荷 {#shared-payloads} @@ -122,6 +124,23 @@ await paseo.workspaces.ref(workspaceId).setMetadata({ "linear.issue": { id: "ENG 元数据在 daemon 重启后仍然保留。所有钩子载荷都带有元数据:`workspace.create.before` 和 `agent.create.before` 收到调用方发送的元数据,`after` 钩子和 `agent.open.before` 收到已保存的元数据。主机版本过旧时,这些调用会抛出 “Update the host to use metadata.”。 +## 启动包装 {#launch-wraps} + +`agent.open.before`、`terminal.create.before` 和 `command.run.before` 可以返回 `wrap: [executable, ...args]`,即 `PluginLaunchWrap`。Paseo 随后以 `[...wrap, command, ...args]` 启动进程,例如在沙盒中运行: + +```ts +import type { PluginLaunchWrap } from "@getpaseo/plugin/server"; + +const sandbox: PluginLaunchWrap = ["/usr/local/bin/sandbox-run", "--profile", "agent"]; +``` + +- 可执行文件必须是 daemon 主机上的绝对路径。Paseo 不经过 shell 运行它;Windows 的 `.cmd` 和 `.bat` 启动器例外,它们通过 cmd.exe 运行。每个元素保持为一个参数。 +- 第一个返回包装的钩子选定包装。后面的钩子,无论属于同一插件还是之后的插件,可以省略 `wrap` 或返回相同的值。返回不同的值会让操作失败。 +- 包装不会被保存。每次启动都会重新询问钩子。 +- 不支持 `wrap` 的旧主机会拒绝该字段,操作失败,而不是不加包装地运行。 + +下面各钩子的章节说明其包装覆盖的范围。 + ## workspace.create.before {#workspacecreatebefore} 收到 `{ request }`,其中包含 `source`、可选的 `title`、可选的 `metadata` 和 `firstAgentContext`。可替换整个显式创建请求;抛出错误、无效返回或超时会让创建失败。已有工作区和目录查找、导入不受影响。 @@ -221,9 +240,63 @@ server.addHook("worktree.create.after", async ({ worktree }) => { }); ``` +## terminal.create.before {#terminalcreatebefore} + +Paseo 在工作区中启动终端之前等待此钩子: + +- 应用中的 **新建终端** 和终端配置,以及通过 CLI、SDK 和插件创建的终端 +- Agent 通过 Paseo 工具打开的终端 +- 运行 `paseo.json` 脚本、服务和 worktree 终端的终端 + +钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。只能修改 `env` 和 `wrap`。抛出错误会拒绝创建终端,请求方收到 `Plugin terminal.create.before failed: …`。 + +```ts +server.addHook("terminal.create.before", async ({ request }) => { + if (!sandboxed.has(request.workspaceId)) return; + return { ...request, wrap: ["/usr/local/bin/sandbox-run", "--profile", "terminal"] }; +}); +``` + +| 请求字段 | 含义 | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 只读,终端所属的工作区 | +| `cwd` | 只读,终端的起始目录 | +| `source` | 只读。`agent`:Agent 的 Paseo 工具。`script`:`paseo.json` 脚本或服务。`worktree`:`paseo.json` worktree 终端。`client`:应用、CLI、SDK 或插件 | +| `name` | 只读,标签页名称,没有时为 null | +| `input` | 只读。对于 `script` 和 `worktree`,是 shell 启动后 Paseo 输入的命令;其他情况为 null | +| `command`、`args` | 只读,要运行的程序及其参数。启动默认 shell 时 `command` 为 null | +| `env` | Paseo 添加到终端环境中的变量 | +| `wrap` | 可选的[启动包装](#launch-wraps)。Paseo 启动 `[...wrap, command, ...args]`;没有 `command` 时,把默认 shell 放在包装之后 | + +脚本、服务和 worktree 终端先启动默认 shell,再向其中输入命令,所以 shell 的包装也覆盖它们运行的命令。被包装的 shell 启动时没有 Paseo 的 shell 集成,所以被包装的 `paseo.json` 脚本不会报告其命令何时结束。daemon 重启后仍在运行的终端会被接管,不会重新创建,也不会再次触发此钩子。插件在此钩子中创建终端时,该终端同样会触发此钩子。 + +## command.run.before {#commandrunbefore} + +Paseo 在运行每条 `paseo.json` worktree `setup` 和 `teardown` 命令之前等待此钩子。钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。只能修改 `env` 和 `wrap`。抛出错误会拒绝该命令:setup 停止并报告插件的错误,teardown 停止并保留 worktree 目录,与命令失败时相同。 + +```ts +server.addHook("command.run.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox-run", "--profile", request.purpose], +})); +``` + +| 请求字段 | 含义 | +| ------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 只读,所属工作区;按路径归档 worktree 且没有工作区记录时为 null | +| `cwd` | 只读,命令的运行目录 | +| `purpose` | 只读,`setup` 或 `teardown` | +| `command` | 只读,`paseo.json` 中写的命令:在 macOS 和 Linux 上用 `bash -c` 运行,在 Windows 上用 PowerShell 或 `cmd.exe` 运行 | +| `env` | Paseo 在 daemon 环境之上添加的变量:`PASEO_SOURCE_CHECKOUT_PATH`、`PASEO_WORKTREE_PATH`、`PASEO_BRANCH_NAME` 等 | +| `wrap` | 可选的[启动包装](#launch-wraps)。Paseo 在包装之后启动 shell:在 macOS 和 Linux 上是 `[...wrap, "bash", "-c", command]` | + +setup 在工作区注册并发出 `workspace.create.after` 之后开始,与第一个 Agent 同时运行。setup 再次运行时,例如在 setup 被阻止的 worktree 上点击 **运行设置**,每条命令都会再次触发此钩子。teardown 在 worktree 上最后一个工作区归档时运行,在 Paseo 删除目录之前。 + ## agent.create.before {#agentcreatebefore} -收到 `{ request: { config, env?, metadata } }`。配置和 `metadata` 的修改会保存,即使插件以后被停用或移除;`env` 只用于首次启动,不会保存。不能修改 `config.cwd`。抛出错误、无效返回或超时会让创建失败。 +收到 `{ request: { config, env?, metadata, workspaceId } }`。配置和 `metadata` 的修改会保存,即使插件以后被停用或移除;`env` 只用于首次启动,不会保存。不能修改 `config.cwd` 和 `workspaceId`。抛出错误、无效返回或超时会让创建失败。 + +`workspaceId` 是创建 Agent 的工作区,没有时为 null。请用它而不是 `config.cwd` 来确定工作区:多个工作区可以共用一个目录,Agent 也可能在一个工作区中创建,而目录位于另一个工作区内。 **`agent.create.before.config`** 使用 `AgentSessionConfig`: @@ -279,7 +352,7 @@ server.addHook("agent.create.after", async ({ agent }) => { ## agent.open.before {#agentopenbefore} -收到 `{ request }`,只能修改 `env`、`appendSystemPrompt`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。 +收到 `{ request }`,只能修改 `env`、`appendSystemPrompt`、`tools`、`mcpServers` 和 `wrap`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。 不要 await 对正在打开的 Agent 的写入,例如 `setMetadata`。该写入要等打开完成,而打开在等你的钩子,结果钩子超时,打开失败。启动写入但不要 await,它会在打开完成后立即执行: @@ -312,18 +385,37 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { } ``` -| 字段 | 取值 | -| ------------- | -------------------------------------------------------------------------------------------------------- | -| `workspaceId` | 字符串或 `null` | -| `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | -| `background` | 只读;[后台 Agent](#background-agents) 为 `true`。在创建时确定。 | -| `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | -| `metadata` | 只读的 JSON 映射;Agent 上已保存的[元数据](#metadata)。 | -| `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | -| `mcpServers` | 可编辑的服务器映射,仅用于启动且仅包含本插件的条目。参阅[注入 MCP 服务器](#inject-mcp-servers)。 | -| `reason` | `create`、`resume`、`refresh`、`import` | -| `purpose` | `interactive`、`history` | -| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | +| 字段 | 取值 | +| ------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 字符串或 `null` | +| `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | +| `background` | 只读;[后台 Agent](#background-agents) 为 `true`。在创建时确定。 | +| `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | +| `metadata` | 只读的 JSON 映射;Agent 上已保存的[元数据](#metadata)。 | +| `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | +| `mcpServers` | 可编辑的服务器映射,仅用于启动且仅包含本插件的条目。参阅[注入 MCP 服务器](#inject-mcp-servers)。 | +| `reason` | `create`、`resume`、`refresh`、`import` | +| `purpose` | `interactive`、`history` | +| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | +| `wrap` | 可选的[启动包装](#launch-wraps),用它启动 harness。参阅[通过启动包装运行 harness](#run-the-harness-behind-a-launch-wrap)。 | + +### 通过启动包装运行 harness {#run-the-harness-behind-a-launch-wrap} + +返回[启动包装](#launch-wraps),让 Provider 的 harness 以 `[...wrap, command, ...args]` 启动: + +```ts +server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox-run", "--profile", "agent"], +})); +``` + +- Provider 快照条目中 `launchWrap: true` 的 Provider 会应用包装。所有内置 Provider 和所有自定义 ACP Provider 都支持。插件 Provider 声明支持后也会应用包装,例如 Muse Code 和 Antigravity 等 ACP 插件 Provider。在 `agent.create.before` 中用 `paseo.providers.snapshot()` 读取该字段,并在那里选择 Provider。为其他 Provider 返回包装会让打开失败,包装绝不会被丢弃。 +- 读取历史的打开也保留包装。 +- 带包装的 OpenCode 会话会获得自己的 OpenCode 服务器,该服务器在包装之后启动。配置为使用现有服务器的 OpenCode Provider 无法启动服务器,因此带包装的打开会失败。 +- harness 不一定在 Agent 的目录中启动。Codex 在 daemon 的目录中启动它,OpenCode 在 Paseo 主目录下的 `opencode-home` 目录中启动其服务器。两者都通过各自的协议发送会话目录。如果启动器需要该目录,把 `request.cwd` 放进包装的参数中。 +- 在包装内保持系统临时目录可见。Paseo 在启动 Pi 之前把 Pi 扩展写入该目录,Claude Code 也把工具输出写入该目录。如果启动器用一个空的私有目录遮住它,这些会话就会失败。 +- 包装覆盖 Paseo 为会话启动的进程:harness、Paseo 为 Agent 托管的 stdio MCP 服务器,以及 ACP Agent 请求 Paseo 运行的终端。Paseo 的主机终端工具、Provider 可用性和目录探测以及草稿发现都在包装之外运行。 ### 在每次打开会话时追加指令 {#append-instructions-on-every-session-opening} @@ -677,13 +769,13 @@ Creation request ## 完整示例 {#complete-examples} -| 插件 | 包含 | -| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | -| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | -| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | worktree 管理器(`create`、`remove`、`restore`)与 Agent 活动标记 | +| 插件 | 包含 | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | +| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区、worktree、终端和命令钩子;隐去环境变量值的 JSON 日志 | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | +| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | worktree 管理器(`create`、`remove`、`restore`)与 Agent 活动标记 | 用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。 diff --git a/public-docs/plugins/providers.md b/public-docs/plugins/providers.md index 48bce6059e..a229e8274b 100644 --- a/public-docs/plugins/providers.md +++ b/public-docs/plugins/providers.md @@ -99,6 +99,31 @@ const { stdout } = await execCommand(launch.command, [...launch.args, "--version }); ``` +### Run sessions behind a launch wrap + +A [launch wrap](./hooks.md#launch-wraps) from `agent.open.before` reaches your provider as +`session.open`'s `config.wrap`. To support it: + +1. Set `launchWrap: true` on the registration. Paseo publishes `launchWrap: true` in the provider + snapshot, so plugins can choose your provider before it connects. +2. Add `session.launch_wrap` to the connection's supported capabilities. Paseo sends `config.wrap` + only to a connection that negotiated it, and fails a wrapped open on any other connection. +3. Start the session's process with the `wrap` option. `spawnProcess` then starts + `[...wrap, command, ...args]` and handles Windows launchers for the wrap's executable: + +```ts +const child = spawnProcess(launch.command, [...launch.args, "serve"], { + wrap: input.config.wrap, + env: launch.env, + cwd: input.config.cwd, + stdio: "pipe", +}); +``` + +Start every process that does the session's work behind the wrap. If one process serves several +sessions, start a separate one for a wrapped session. `runAcpProvider({ command })` does all of this +for an ACP agent. + ## Return models, modes, and thinking options Paseo requests the catalog before creating a session. Return the choices needed by the agent form: diff --git a/public-docs/plugins/providers.zh-CN.md b/public-docs/plugins/providers.zh-CN.md index 7df6e4cf17..1317600010 100644 --- a/public-docs/plugins/providers.zh-CN.md +++ b/public-docs/plugins/providers.zh-CN.md @@ -89,6 +89,25 @@ const { stdout } = await execCommand(launch.command, [...launch.args, "--version }); ``` +### 在启动包装之后运行会话 {#run-sessions-behind-a-launch-wrap} + +来自 `agent.open.before` 的[启动包装](./hooks.zh-CN.md#launch-wraps)会作为 `session.open` 的 `config.wrap` 传给你的 Provider。要支持它: + +1. 在注册信息上设置 `launchWrap: true`。Paseo 会在 Provider 快照中发布 `launchWrap: true`,这样插件可以在你的 Provider 连接之前选择它。 +2. 把 `session.launch_wrap` 加入连接支持的能力。Paseo 只把 `config.wrap` 发给协商了该能力的连接,在其他连接上带包装的打开会失败。 +3. 用 `wrap` 选项启动会话的进程。`spawnProcess` 随后启动 `[...wrap, command, ...args]`,并为包装的可执行文件处理 Windows 启动器: + +```ts +const child = spawnProcess(launch.command, [...launch.args, "serve"], { + wrap: input.config.wrap, + env: launch.env, + cwd: input.config.cwd, + stdio: "pipe", +}); +``` + +在包装之后启动所有为会话工作的进程。如果一个进程服务多个会话,就为带包装的会话单独启动一个。`runAcpProvider({ command })` 会为 ACP Agent 完成以上所有工作。 + ## 返回模型、模式和思考选项 {#return-models-modes-and-thinking-options} Paseo 在创建会话之前会请求目录。返回 Agent 表单需要的选项: diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 7b2a3baa94..9ff87b3c35 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -19,6 +19,7 @@ const desktopPackagePath = new URL("packages/desktop/package.json", repoRoot); const gatedCiJobs = new Map([ ["quality", { name: "quality", contracts: ["format", "quality", "relay", "sdk"] }], + ["sdk-tests-windows", { name: "sdk-tests (windows-latest)", contract: "sdk" }], ["typecheck", { name: "typecheck", contract: "quality" }], ["server-tests-ubuntu", { name: "server-tests (ubuntu-latest)", contracts: ["server", "hub"] }], ["server-tests-windows", { name: "server-tests (windows-latest)", contracts: ["server", "hub"] }], @@ -437,7 +438,7 @@ test("stable iOS releases upload once and distribute to external testers before test("eight Playwright shards share two-worker coverage", () => { const source = readFileSync(ciWorkflowPath, "utf8"); const jobs = jobBlocks(source); - assert.equal(jobs.size, 21); + assert.equal(jobs.size, 22); for (let shard = 1; shard <= 8; shard++) { const job = jobs.get(`playwright-${shard}`).join("\n"); assert.match(job, new RegExp(`PLAYWRIGHT_SHARD: "${shard}/8"`)); @@ -517,6 +518,13 @@ test("quality preserves commands and routes each domain independently after fail assert.equal(accepts(jobCondition, {}, { cancelled: true }), false); }); +test("plugin SDK tests run on real Windows", () => { + const sdk = jobBlocks(readFileSync(ciWorkflowPath, "utf8")).get("sdk-tests-windows").join("\n"); + assert.match(sdk, /^ runs-on: windows-latest$/m); + assert.match(sdk, /run: npm run test --workspace=@getpaseo\/plugin$/m); + assert.doesNotMatch(sdk, /continue-on-error/); +}); + test("Windows units and integration run independently with complete routed coverage", () => { const source = readFileSync(ciWorkflowPath, "utf8"); const jobs = jobBlocks(source); @@ -568,7 +576,7 @@ test("Windows units and integration run independently with complete routed cover assert.doesNotMatch(invocations[0], / -t /); assert.equal( invocations[1], - '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 -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"', + '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"', ); const serverConfig = readFileSync(new URL("packages/server/vitest.config.ts", repoRoot), "utf8"); assert.doesNotMatch(serverConfig, /maxWorkers:\s*1\b/);