diff --git a/docs/plugins.md b/docs/plugins.md index bf6775bcb0..bef8f5e6af 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -482,9 +482,10 @@ 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` (Codex and providers - that extend it). A plugin provider declares `ProviderRegistration.launchWrap`; - `runAcpProvider({ command })` sets it, a connector does not. The declaration travels with the + 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. @@ -495,7 +496,13 @@ reuses the wrap it opened with. 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. The guarantee covers the harness process only: +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 diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index c9d436ac75..39d52102b5 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -501,14 +501,8 @@ class AcpRuntime { args: options.options.command.slice(1), env: process.env, }; - // spawnProcess starts a Windows script wrapper through cmd.exe, as for any launcher. - const spawned = options.wrap - ? { - command: options.wrap[0], - args: [...options.wrap.slice(1), launch.command, ...launch.args], - } - : launch; - child = spawnProcess(spawned.command, spawned.args, { + child = spawnProcess(launch.command, launch.args, { + wrap: options.wrap, cwd: options.cwd, env: { ...launch.env, ...options.env }, stdio: "pipe", diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index d64a22b17c..50ff559783 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -35,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/process.test.ts b/packages/plugin/src/server/process.test.ts index de3ea276d9..d4d612786b 100644 --- a/packages/plugin/src/server/process.test.ts +++ b/packages/plugin/src/server/process.test.ts @@ -75,3 +75,32 @@ test("a Windows script launch wrap starts through cmd.exe with each argument quo shell: false, }); }); + +// 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, + ]); +}); diff --git a/packages/plugin/src/server/process.ts b/packages/plugin/src/server/process.ts index f5527945b1..84e6b0082d 100644 --- a/packages/plugin/src/server/process.ts +++ b/packages/plugin/src/server/process.ts @@ -12,6 +12,7 @@ import { quoteWindowsArgument, quoteWindowsCommand, } from "./process-internal/windows-command.js"; +import type { PluginLaunchWrap } from "./lifecycle.js"; const execFileAsync = promisify(execFile); export interface ExecCommandOptions { env?: NodeJS.ProcessEnv; @@ -70,20 +71,34 @@ export function resolveSpawnInvocation( }; } +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 invocation = resolveSpawnInvocation(command, args, spawnOptions.shell); + const { wrap, ...spawnOptions } = options ?? {}; + const invocation = wrap + ? resolveSpawnInvocation(wrap[0], [...wrap.slice(1), command, ...args], false) + : resolveSpawnInvocation(command, args, spawnOptions.shell); return spawn(invocation.command, invocation.args, { ...spawnOptions, 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/provider-registry.test.ts b/packages/server/src/server/agent/provider-registry.test.ts index 9512ade07f..005d062ada 100644 --- a/packages/server/src/server/agent/provider-registry.test.ts +++ b/packages/server/src/server/agent/provider-registry.test.ts @@ -647,22 +647,28 @@ 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, { - providerOverrides: { "my-codex": { extends: "codex", label: "My Codex" } }, + isDev: true, + providerOverrides: { + "my-claude": { extends: "claude", label: "My Claude" }, + "my-acp": { extends: "acp", label: "My ACP", command: ["my-acp", "--acp"] }, + }, }); - for (const provider of ["codex", "my-codex"]) { - expect(registry[provider].supportsLaunchWrap).toBe(true); - expect(registry[provider].createClient(logger).supportsLaunchWrap).toBe(true); - } - for (const provider of Object.keys(registry).filter( - (id) => id !== "codex" && id !== "my-codex", - )) { - expect({ provider, supportsLaunchWrap: registry[provider].supportsLaunchWrap }).toEqual({ - provider, - supportsLaunchWrap: false, - }); - } - expect(registry.claude.createClient(logger).supportsLaunchWrap).toBe(false); + 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 () => { diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index 6d46c354e8..88ca55ed5c 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -155,22 +155,33 @@ interface ProviderContract { 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 }, + claude: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true }, codex: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true }, - opencode: { supportsExactMcpPreapproval: 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) { @@ -889,7 +900,7 @@ function addDerivedProviders( contract: providerId === HUB_E2E_PROVIDER_ID ? HUB_E2E_PROVIDER_CONTRACT - : UNSUPPORTED_PROVIDER_CONTRACT, + : CUSTOM_ACP_PROVIDER_CONTRACT, }); continue; } 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 efcde9a643..60698125bd 100644 --- a/packages/server/src/server/agent/provider-snapshot-manager.test.ts +++ b/packages/server/src/server/agent/provider-snapshot-manager.test.ts @@ -553,7 +553,7 @@ describe("ProviderSnapshotManager public surface", () => { 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")).not.toHaveProperty("launchWrap"); + expect(byProvider("claude")).toMatchObject({ status: "loading", launchWrap: true }); } finally { manager.destroy(); } 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 226a25c26a..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,4 +1,4 @@ -import { spawn } from "node:child_process"; +import { spawnProcess } from "../../../utils/spawn.js"; import { describe, expect, test, vi } from "vitest"; import { CodexAppServerAgentClient } from "./codex-app-server-agent.js"; @@ -82,13 +82,13 @@ describe("CodexAppServerAgentClient spawn error handling", () => { } }); test("a missing launch wrap fails the open and never starts the bare codex command", async () => { - const spawned: Array<{ command: string; args: string[] }> = []; + 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 }) => { - spawned.push({ command, args }); - return spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] }); + spawn: ({ command, args, options }) => { + spawned.push({ command, args, wrap: options.wrap }); + return spawnProcess(command, args, options); }, }, }); @@ -106,8 +106,9 @@ describe("CodexAppServerAgentClient spawn error handling", () => { ).rejects.toThrow(/ENOENT/u); expect(spawned).toEqual([ { - command: "/nonexistent/launch-wrap-that-does-not-exist", - args: ["--flag", process.execPath, "codex.js", "app-server"], + 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 85d17c9b3c..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 @@ -2495,7 +2495,7 @@ describe("Codex app-server provider", () => { test.each(["interactive", "history"] as const)( "spawns a wrapped %s resume through the launch wrap", async (purpose) => { - const spawned: Array<{ command: string; args: string[] }> = []; + 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({ @@ -2513,8 +2513,8 @@ describe("Codex app-server provider", () => { command: "/opt/codex/bin/codex", args: ["--profile", "x"], }), - spawn: ({ command, args }) => { - spawned.push({ command, args }); + spawn: ({ command, args, options }) => { + spawned.push({ command, args, wrap: options.wrap }); return appServer.child; }, }, @@ -2536,8 +2536,9 @@ describe("Codex app-server provider", () => { expect(spawned.length).toBeGreaterThan(0); for (const input of spawned) { expect(input).toEqual({ - command: "/opt/sandbox/bin/run", - args: ["--profile", "a b", "/opt/codex/bin/codex", "--profile", "x", "app-server"], + command: "/opt/codex/bin/codex", + args: ["--profile", "x", "app-server"], + wrap: ["/opt/sandbox/bin/run", "--profile", "a b"], }); } await session.close(); 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 5f85174bef..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 @@ -8275,35 +8275,28 @@ export class CodexAppServerAgentClient implements AgentClient { wrap?: AgentLaunchContext["wrap"]; }): Promise<() => ChildProcessWithoutNullStreams> { const processPort = this.deps.appServerProcess ?? defaultCodexAppServerProcess; - const resolvedPrefix = await processPort.resolvePrefix({ - runtimeSettings: this.runtimeSettings, - }); - const appServerArgs = [...resolvedPrefix.args, "app-server"]; + const launchPrefix = await processPort.resolvePrefix({ runtimeSettings: this.runtimeSettings }); + const args = [...launchPrefix.args, "app-server"]; if (options.goalsEnabled) { - appServerArgs.push("--enable", "goals"); + args.push("--enable", "goals"); } - // Every spawn from this closure, including reconnects and startup retries, carries the wrap. - const { command, args } = options.wrap - ? { - command: options.wrap[0], - args: [...options.wrap.slice(1), resolvedPrefix.command, ...appServerArgs], - } - : { command: resolvedPrefix.command, args: appServerArgs }; return () => { this.logger.trace( { agentId: options.agentId, provider: CODEX_PROVIDER, - command, - args, + 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, + command: launchPrefix.command, args, options: { + wrap: options.wrap, detached: process.platform !== "win32", stdio: ["pipe", "pipe", "pipe"], baseEnv: options.environment, 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.ts b/packages/server/src/server/agent/providers/opencode-agent.ts index daf3156e30..dc30f5918e 100644 --- a/packages/server/src/server/agent/providers/opencode-agent.ts +++ b/packages/server/src/server/agent/providers/opencode-agent.ts @@ -1617,10 +1617,18 @@ 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(); + // A wrapped session gets its own server, so it never shares a server that runs outside its wrap. + if (launchContext?.wrap) { + return this.serverManager.acquireDedicated({ + env: launchContext.env ?? {}, + wrap: launchContext.wrap, + }); + } + if ( + launchContext?.env && + (!this.bridge || requiresDedicatedOpenCodeServer(config, launchContext)) + ) { + return this.serverManager.acquireDedicated({ env: launchContext.env }); } return this.serverManager.acquireCurrent(); } 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..dee705c9f8 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 @@ -1270,6 +1270,44 @@ describe("OpenCode v2 session lifecycle", () => { } }); + test("asks the runtime for a wrapped server when creating and resuming a wrapped session", async () => { + const servers = [new V2Harness(), new V2Harness()]; + const requests: unknown[] = []; + const runtime = { + acquire: async (input?: { wrap?: readonly [string, ...string[]] }) => { + requests.push(input?.wrap); + 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 created = await client.createSession( + { provider: "opencode", cwd: "/tmp/project" }, + { agentId: "agent", wrap }, + ); + 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 }, + { purpose: "history" }, + ); + await resumed.close(); + expect(requests).toEqual([wrap, wrap]); + } finally { + await created.close(); + } + }); + 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..365a73c93a 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.ts @@ -116,7 +116,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({ wrap: launch?.wrap }); try { const info = await connection.client.session.create({ location: { directory: config.cwd }, @@ -159,9 +159,11 @@ export class OpenCodeV2AgentClient implements AgentClient { 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()); + // 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(); + const connection = live ?? (await this.runtime.acquire({ wrap: launch?.wrap })); try { const info = await connection.client.session.get({ sessionID: handle.nativeHandle ?? handle.sessionId, @@ -197,6 +199,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 +260,7 @@ export class OpenCodeV2AgentClient implements AgentClient { mcp, unbind: releaseBindings, bindChild, - acquire: () => this.runtime.acquire(), + acquire: () => this.runtime.acquire({ wrap: launch?.wrap }), moved, historyOnly, }); 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..554995059c 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,72 @@ 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; + require('node:fs').writeFileSync(${JSON.stringify(record)}, JSON.stringify(argv)); + 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({ wrap: [process.execPath, launcher, "--profile"] }); + 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); + expect(JSON.parse(await readFile(record, "utf8")).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({ wrap: ["/opt/sandbox/bin/run"] })).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..956087b90e 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 { @@ -62,6 +63,8 @@ export interface V2RuntimeOptions { export interface V2RuntimeAcquireOptions { fresh?: boolean; signal?: AbortSignal; + /** Start a server for this caller alone, behind the wrap. Other callers never share it. */ + wrap?: LaunchWrap; } // The runtime owns a credential for each subprocess; sessions only receive its authenticated client. @@ -92,8 +95,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.wrap + ? this.startTracked(input.wrap) + : (this.current ??= this.startTracked()); let generation: Generation; try { generation = await raceProviderRefreshAbort(input.signal, pending); @@ -179,8 +183,8 @@ export class V2Runtime { this.current = null; } - private startTracked(): Promise { - const pending = this.start(); + private startTracked(wrap?: LaunchWrap): Promise { + const pending = this.start(wrap); this.starts.add(pending); void pending.then( (generation) => @@ -197,9 +201,14 @@ export class V2Runtime { return pending; } - private async start(): Promise { + private async start(wrap: LaunchWrap | undefined): Promise { const selection = await this.selection; - if (selection.kind !== "owned") { + if (wrap && 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" && !wrap) { const generation: Generation = { ...(await connectSharedService(selection, this.options)), users: 0, @@ -240,6 +249,7 @@ export class V2Runtime { cwd, detached: globalThis.process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], + 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/daemon-e2e/terminal-workspace-sdk.e2e.test.ts b/packages/server/src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts index 7fd77e4479..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,18 +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.map((terminal) => ({ + id: terminal.id, workspaceId: terminal.workspaceId, isScript: terminal.isScript, })), { timeout: 10_000 }, ) - .toContainEqual({ workspaceId, isScript: 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/terminal/terminal-create-hook.ts b/packages/server/src/terminal/terminal-create-hook.ts index 6abf23f89e..ed7b63ee43 100644 --- a/packages/server/src/terminal/terminal-create-hook.ts +++ b/packages/server/src/terminal/terminal-create-hook.ts @@ -1,4 +1,5 @@ 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"; @@ -27,14 +28,9 @@ export function withTerminalCreateHook( env: options.env ?? {}, }); if (!request.wrap) return manager.createTerminal({ ...options, env: request.env }); - const [executable, ...wrapArgs] = request.wrap; const command = options.command ?? resolveDefaultTerminalShell({ env: options.baseEnv }); - return manager.createTerminal({ - ...options, - env: request.env, - command: executable, - args: [...wrapArgs, command, ...args], - }); + const launch = applyLaunchWrap({ command, args }, request.wrap); + return manager.createTerminal({ ...options, env: request.env, ...launch }); }, }; } 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.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.ts b/packages/server/src/utils/worktree.ts index 134499243d..71e9b51a3f 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -39,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"; @@ -194,9 +195,8 @@ function lifecycleCommandInvocation( wrap: PreparedWorktreeLifecycleCommand["wrap"], ): StringCommandShellInvocation { const invocation = buildStringCommandShellInvocation({ command }); - if (!wrap) return invocation; - const [executable, ...wrapArgs] = wrap; - return { shell: executable, args: [...wrapArgs, invocation.shell, ...invocation.args] }; + const launch = applyLaunchWrap({ command: invocation.shell, args: invocation.args }, wrap); + return { shell: launch.command, args: launch.args }; } export class WorktreeSetupError extends Error { 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 cdef154a39..488665d3e1 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -414,10 +414,12 @@ server.addHook("agent.open.before", async ({ request }) => ({ })); ``` -- Only a provider whose provider snapshot entry has `launchWrap: true` applies a wrap: Codex and command-based ACP providers such as Antigravity. Read it 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. +- 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. -- The harness does not always start in the agent's directory. Codex starts it in the daemon's directory and sends the session directory over its protocol. If your launcher needs the directory, put `request.cwd` in the wrap's arguments. -- The wrap covers the session's harness process only. Paseo's host terminal tools, provider availability and catalog probes, and draft discovery run outside it. +- 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 diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index 54ffeaffb2..30ee45209a 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -410,10 +410,12 @@ server.addHook("agent.open.before", async ({ request }) => ({ })); ``` -- 只有 Provider 快照条目中 `launchWrap: true` 的 Provider 才会应用包装:Codex,以及 Antigravity 等基于命令的 ACP Provider。在 `agent.create.before` 中用 `paseo.providers.snapshot()` 读取它,并在那里选择 Provider。为其他 Provider 返回包装会让打开失败,包装绝不会被丢弃。 +- Provider 快照条目中 `launchWrap: true` 的 Provider 会应用包装。所有内置 Provider 和所有自定义 ACP Provider 都支持。插件 Provider 声明支持后也会应用包装,例如 Muse Code 和 Antigravity 等 ACP 插件 Provider。在 `agent.create.before` 中用 `paseo.providers.snapshot()` 读取该字段,并在那里选择 Provider。为其他 Provider 返回包装会让打开失败,包装绝不会被丢弃。 - 读取历史的打开也保留包装。 -- harness 不一定在 Agent 的目录中启动。Codex 在 daemon 的目录中启动它,并通过其协议发送会话目录。如果启动器需要该目录,把 `request.cwd` 放进包装的参数中。 -- 包装只覆盖会话的 harness 进程。Paseo 的主机终端工具、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} 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 表单需要的选项: