From 2547edefccf02e7418f5f039cc4766ce370924ff Mon Sep 17 00:00:00 2001 From: CL Kao Date: Sat, 21 Nov 2026 12:18:16 -0800 Subject: [PATCH] feat(plugins): let an open hook wrap the provider's launch command An agent.open.before result can carry `wrap: [executable, ...args]`. A supporting provider starts that session's harness as `[...wrap, command, ...args]`, one direct argv exec with the final hook env. This lets one sandbox plugin confine every provider that supports wrapping, instead of one wrapper provider per real provider. Support is a static provider property, published as optional `launchWrap` on the provider snapshot entry so an agent.create.before hook can read it with paseo.providers.snapshot(). Codex and providers that extend it declare it in the provider contract; plugin providers declare ProviderRegistration.launchWrap, which runAcpProvider sets for a command. The declaration travels in the registration metadata, so a provider reports it before its first connection. The open fails closed: - buildLaunchContext rejects a wrapped open with LaunchWrapUnsupportedError (code launch_wrap_unsupported) before anything starts when the provider does not declare support, when a plugin connection lacks session.launch_wrap, or for a Windows command-script wrapper; - a later hook may omit or repeat the wrap, a different one fails the open; - the wrap executable must be absolute; - a missing launcher fails the spawn and is never retried bare; - a host without this change rejects the unknown `wrap` key. The wrap is launch-only: history opens keep it, plugin session reopens reuse it, and it is never stored on the agent. Co-Authored-By: Claude Opus 5.5 --- docs/plugins.md | 36 ++++ .../src/server/acp-internal/connection.ts | 10 +- packages/plugin/src/server/acp.test.ts | 179 +++++++++++++++++- packages/plugin/src/server/acp.ts | 2 + packages/plugin/src/server/index.ts | 2 +- packages/plugin/src/server/lifecycle.ts | 7 + packages/plugin/src/server/process.ts | 16 ++ packages/plugin/src/server/provider.test.ts | 36 ++++ packages/plugin/src/server/provider.ts | 11 ++ packages/protocol/src/agent-types.ts | 2 + .../src/messages.providers-snapshot.test.ts | 6 + packages/protocol/src/messages.ts | 1 + .../src/server/agent/agent-manager.test.ts | 153 +++++++++++++++ .../server/src/server/agent/agent-manager.ts | 25 ++- .../src/server/agent/agent-sdk-types.ts | 7 + .../src/server/agent/plugin-provider.test.ts | 86 +++++++++ .../src/server/agent/plugin-provider.ts | 17 ++ .../src/server/agent/provider-options.ts | 12 ++ .../server/agent/provider-registry.test.ts | 20 ++ .../src/server/agent/provider-registry.ts | 13 +- .../agent/provider-snapshot-manager.test.ts | 17 ++ .../server/agent/provider-snapshot-manager.ts | 1 + ...codex-app-server-agent.spawn-error.test.ts | 31 +++ .../providers/codex-app-server-agent.test.ts | 53 ++++++ .../agent/providers/codex-app-server-agent.ts | 21 +- .../plugins/agent-configuration.e2e.test.ts | 49 +++++ .../src/server/plugins/index.posix.test.ts | 30 +++ packages/server/src/server/plugins/index.ts | 1 + .../server/plugins/lifecycle/handlers.test.ts | 106 +++++++++++ .../src/server/plugins/lifecycle/index.ts | 13 ++ .../server/plugins/plugin-process-protocol.ts | 2 + .../src/server/plugins/plugin-process.ts | 1 + .../src/server/plugins/runtime.posix.test.ts | 94 +++++++++ .../server/provider.test.ts | 73 ++++++- 34 files changed, 1119 insertions(+), 14 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index d2a4adecff..c7bb0ebb06 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -469,6 +469,42 @@ each live session. A plugin start, stop, or reload reruns only that plugin's cal 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]`: one direct argv exec with `shell: false` and the +final hook env, so 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` (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 + 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 anything starts. It throws + `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not declare + support, when a plugin provider's live connection lacks `session.launch_wrap`, or on Windows when the + wrap executable or provider command is a command script, which would need a shell. 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. The guarantee covers the harness process only: + +1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap. A + sandbox that relies on the wrap must also keep the agent's daemon access off. +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, diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index bc7c73cd83..5915810289 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -1,5 +1,5 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process"; -import { spawnProcess, terminateProcess } from "../process.js"; +import { applyLaunchWrap, spawnProcess, terminateProcess } from "../process.js"; import { Readable, Writable } from "node:stream"; import { ClientSideConnection, @@ -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; } @@ -497,7 +501,8 @@ class AcpRuntime { args: options.options.command.slice(1), env: process.env, }; - child = spawnProcess(launch.command, launch.args, { + const spawned = options.wrap ? applyLaunchWrap(options.wrap, launch) : launch; + child = spawnProcess(spawned.command, spawned.args, { 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..f90bc06ea9 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { @@ -7125,3 +7125,180 @@ describe("ACP tool call rows", () => { } }); }); + +describe("runAcpProvider launch wrap", () => { + async function wrapFixture(): Promise<{ + launcher: string; + agent: string; + launchLog: 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, + `#!${process.execPath} +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", + ); + await chmod(launcher, 0o755); + 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 { + launcher, + agent, + launchLog, + 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.launcher, launchLog, "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.launcher, launchLog, "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.launcher, launchLog, "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 { connection, events } = await connectWrapped([process.execPath, fixture.agent]); + try { + await connection.send( + wrappedOpen("one", [path.join(path.dirname(fixture.agent), "missing-launcher")]), + ); + expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({ + requestId: "open-one", + error: { message: expect.stringMatching(/ENOENT/u) }, + }); + // The only start is the connection's capability probe. + expect(await fixture.agentStarts()).toEqual(["init:bare"]); + expect(events.some((event) => event.type === "session.opened")).toBe(false); + } finally { + 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..ffdc88cde1 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -31,7 +31,7 @@ export type { PluginLifecycleRegistration, } from "./lifecycle.js"; -export { spawnProcess, execCommand, terminateProcess } from "./process.js"; +export { applyLaunchWrap, spawnProcess, execCommand, terminateProcess } 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..e3bf3304e6 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -98,6 +98,13 @@ export interface PluginSessionOpenRequest { tools: AgentToolDefinition[]; env: Record; mcpServers: NonNullable; + /** + * Run the provider's harness as `[...wrap, command, ...args]`. The executable must be an absolute + * path. Set it only for a provider whose snapshot entry has `launchWrap: true`: any other provider + * fails the open. A later hook may omit it or return the same value; a different value fails the + * open. Not saved on the agent. + */ + wrap?: readonly [executable: string, ...args: string[]]; } export type PluginTurnOutcome = diff --git a/packages/plugin/src/server/process.ts b/packages/plugin/src/server/process.ts index b2ba70ac12..c4bb1692fb 100644 --- a/packages/plugin/src/server/process.ts +++ b/packages/plugin/src/server/process.ts @@ -44,6 +44,22 @@ function shouldUseWindowsShell( return process.platform === "win32" && !hasPathSeparator(command) && !extname(command); } +/** + * Put `wrap` in front of a launch as one direct argv exec. A Windows command script on either side + * would need a shell to start, so it is rejected instead of being quoted into one. + */ +export function applyLaunchWrap( + wrap: readonly [string, ...string[]], + launch: { command: string; args: readonly string[] }, +): { command: string; args: string[] } { + for (const executable of [wrap[0], launch.command]) { + if (isWindowsCommandScript(executable)) { + throw new Error(`A launch wrap cannot start ${executable}: a command script needs a shell`); + } + } + return { command: wrap[0], args: [...wrap.slice(1), launch.command, ...launch.args] }; +} + /** Launch a CLI with Windows command-script handling and argv quoting. The caller owns env. */ export function spawnProcess( command: string, 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..2e3d03a509 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()], z.string()).optional(), }) .strict(); const externalResourceSchema = z 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/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index d2bc28c18b..dc1e8b1c3c 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -16268,3 +16268,156 @@ 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: [], + }; + } +} + +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 detached: string[] = []; + const hook: { wrap: [string, ...string[]] | undefined } = { wrap: undefined }; + const manager = new AgentManager({ + clients: { codex: client }, + registry: storage, + logger, + pluginAgentTools: { + isToolPluginAvailable: () => true, + detachTools: (agentId) => detached.push(agentId), + callTool: async () => { + throw new Error("unused"); + }, + }, + pluginLifecycle: { + emit: () => {}, + before: async (name, request) => + name === "agent.open.before" && hook.wrap + ? { + ...request, + wrap: hook.wrap, + tools: [ + { + name: "sandbox_status", + description: "Report the sandbox", + inputSchema: {}, + pluginId: "sandbox", + pluginInstanceId: "sandbox-1", + }, + ], + } + : request, + }, + }); + return { manager, storage, workdir, detached, 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, detached, 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); + // The hook attached a tool for this open; the rejection takes it away again. + expect(manager.getPluginTools(created.id)).toEqual([]); + expect(detached.filter((id) => id === created.id).length).toBeGreaterThanOrEqual(2); + 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); +}); + +test("a supporting provider rejects a Windows command-script wrap before it starts", async () => { + const client = new LaunchWrapRecordingClient(true); + const { manager, workdir, hook } = createLaunchWrapManager(client); + hook.wrap = ["C:\\tools\\sandbox.cmd"]; + const platform = Object.getOwnPropertyDescriptor(process, "platform")!; + Object.defineProperty(process, "platform", { ...platform, value: "win32" }); + try { + await expect( + manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }), + ).rejects.toMatchObject({ code: "launch_wrap_unsupported" }); + } finally { + Object.defineProperty(process, "platform", platform); + } + expect(client.calls.create).toBe(0); +}); diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index a422cc4977..cc5f97f5a7 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"; @@ -18,7 +18,7 @@ import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/inde import { applyRecordPatch } from "../record-patch.js"; import type { PluginSessionOpenRequest } from "@getpaseo/plugin/server"; import { randomUUID } from "node:crypto"; -import { basename, resolve } from "node:path"; +import { basename, extname, resolve } from "node:path"; import { stat } from "node:fs/promises"; import { AGENT_LIFECYCLE_STATUSES, @@ -6644,6 +6644,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 +6662,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, wrap); } const context: AgentLaunchContext = { agentId, + wrap, ...pluginPromptContext(appendSystemPrompt), mcpServers, mcpServerOwners, @@ -6855,3 +6860,19 @@ function pluginPromptContext( ): Pick { return appendSystemPrompt?.length ? { appendSystemPrompt } : {}; } + +async function requireLaunchWrap( + client: AgentClient, + wrap: NonNullable, +): Promise { + if (client.supportsLaunchWrap !== true) throw new LaunchWrapUnsupportedError(client.provider); + // The wrap is one direct exec; a Windows command script would need a shell to start. + const extension = extname(wrap[0]).toLowerCase(); + if (process.platform === "win32" && (extension === ".cmd" || extension === ".bat")) { + throw new LaunchWrapUnsupportedError( + client.provider, + `A launch wrap cannot start ${wrap[0]} on Windows: a command script needs a shell`, + ); + } + 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/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index 334d0be0cb..dd18785395 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,86 @@ 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]!; + + 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); +}); + +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(); +}); + +test("an ACP connector provider neither declares nor offers launch wrap", async () => { + const registration = runAcpProvider({ + id: "connector-acp", + label: "Connector ACP", + connector() { + let controller!: ReadableStreamDefaultController; + const readable = new ReadableStream({ + start(ctrl) { + controller = ctrl; + }, + }); + const writable = new WritableStream({ + write(message) { + if ("method" in message && "id" in message && message.method === "initialize") { + controller.enqueue({ + jsonrpc: "2.0", + id: message.id, + result: { protocolVersion: 1, agentCapabilities: {} }, + }); + } + }, + }); + return { readable, writable }; + }, + }); + const registry = new PluginAgentClientRegistry(createTestLogger()); + registry.replace([registration]); + expect(registry.definitions()[registration.id]?.supportsLaunchWrap).toBe(false); + await expect(registry.clients()[registration.id]!.requireLaunchWrap?.()).rejects.toMatchObject({ + code: "launch_wrap_unsupported", + }); + 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..93c2051d2a 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, }; } @@ -1101,6 +1108,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 +2159,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..9512ade07f 100644 --- a/packages/server/src/server/agent/provider-registry.test.ts +++ b/packages/server/src/server/agent/provider-registry.test.ts @@ -645,6 +645,26 @@ 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" } }, + }); + + 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); +}); + 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..7d68205fe9 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,12 +150,14 @@ interface ResolvedProvider { interface ProviderContract { supportsExactMcpPreapproval: boolean; + /** Sessions spawn their harness behind an `agent.open.before` wrap. */ + supportsLaunchWrap?: boolean; applyToolPolicy?: (provider: string, toolPolicy: ToolPolicy) => ToolPolicy; } const PROVIDER_CONTRACTS: Record = { claude: { supportsExactMcpPreapproval: true }, - codex: { supportsExactMcpPreapproval: true }, + codex: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true }, opencode: { supportsExactMcpPreapproval: true }, }; @@ -626,6 +630,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 +675,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); @@ -740,7 +746,7 @@ function createResolvedProviderClient( const inner = resolved.createBaseClient(logger); const profileModels = resolveConfiguredModels(provider, inner, resolved.profileModels); const additionalModels = resolveConfiguredModels(provider, inner, resolved.additionalModels); - return wrapClientProvider( + const client = wrapClientProvider( provider, inner, profileModels, @@ -748,6 +754,8 @@ function createResolvedProviderClient( resolved.profileModelsAreAdditive, resolved.providerOptions, ); + client.supportsLaunchWrap = resolved.contract.supportsLaunchWrap === true; + return client; } interface RegisteredProvider { @@ -962,6 +970,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..efcde9a643 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")).not.toHaveProperty("launchWrap"); + } 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/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..226a25c26a 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 { spawn } from "node:child_process"; import { describe, expect, test, vi } from "vitest"; import { CodexAppServerAgentClient } from "./codex-app-server-agent.js"; @@ -80,4 +81,34 @@ 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[] }> = []; + 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"] }); + }, + }, + }); + // 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: "/nonexistent/launch-wrap-that-does-not-exist", + args: ["--flag", process.execPath, "codex.js", "app-server"], + }, + ]); + }); }); 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..85d17c9b3c 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,59 @@ 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[] }> = []; + 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 }) => { + spawned.push({ command, args }); + 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/sandbox/bin/run", + args: ["--profile", "a b", "/opt/codex/bin/codex", "--profile", "x", "app-server"], + }); + } + 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..62144b0cb2 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 @@ -1,3 +1,4 @@ +import { applyLaunchWrap } from "@getpaseo/plugin/server"; import type { ProviderOptions } from "@getpaseo/protocol/agent-types"; import { applyProviderOptionsPatch } from "../option-controls.js"; import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js"; @@ -8272,25 +8273,33 @@ 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 }); - const args = [...launchPrefix.args, "app-server"]; + const resolvedPrefix = await processPort.resolvePrefix({ + runtimeSettings: this.runtimeSettings, + }); + const appServerArgs = [...resolvedPrefix.args, "app-server"]; if (options.goalsEnabled) { - args.push("--enable", "goals"); + appServerArgs.push("--enable", "goals"); } + // Every spawn from this closure, including reconnects and startup retries, carries the wrap. + const { command, args } = options.wrap + ? applyLaunchWrap(options.wrap, { command: resolvedPrefix.command, args: appServerArgs }) + : { command: resolvedPrefix.command, args: appServerArgs }; return () => { this.logger.trace( { agentId: options.agentId, provider: CODEX_PROVIDER, - launchPrefix, + command, + args, goalsEnabled: options.goalsEnabled === true, }, "provider.codex.spawn", ); const child = processPort.spawn({ - command: launchPrefix.command, + command, args, options: { detached: process.platform !== "win32", @@ -8339,6 +8348,7 @@ export class CodexAppServerAgentClient implements AgentClient { environment, goalsEnabled, agentId: launchContext?.agentId, + wrap: launchContext?.wrap, }); const session = new CodexAppServerAgentSession( sessionConfig, @@ -8376,6 +8386,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/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/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/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index 6ff3361f22..72542f016b 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -398,3 +398,109 @@ 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: {}, +}; + +test("a session-open hook can select a launch wrap", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox", "--profile", "a b"], + })); + const output = await hooks.invoke("open", "agent.open.before", openInput, paseo); + expect(output).toMatchObject({ wrap: ["/usr/local/bin/sandbox", "--profile", "a b"] }); +}); + +test("a session-open hook result with an unknown key fails the open", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + notAHookField: true, + })); + await expect(hooks.invoke("open", "agent.open.before", openInput, paseo)).rejects.toThrow( + /notAHookField/, + ); +}); + +test("a later session-open hook that omits the wrap keeps the earlier one", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox"], + })); + hooks.addHook("agent.open.before", async ({ request }) => { + const { wrap: _wrap, ...rest } = request; + return { ...rest, env: { ...rest.env, LATER: "1" } }; + }); + expect(await hooks.invoke("open", "agent.open.before", openInput, paseo)).toMatchObject({ + wrap: ["/usr/local/bin/sandbox"], + env: { LATER: "1" }, + }); +}); + +test("a later session-open hook may repeat the same wrap", async () => { + const hooks = new PluginHookHandlers(() => {}); + for (let index = 0; index < 2; index++) { + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox", "--profile", "a b"], + })); + } + expect(await hooks.invoke("open", "agent.open.before", openInput, paseo)).toMatchObject({ + wrap: ["/usr/local/bin/sandbox", "--profile", "a b"], + }); +}); + +test("a later session-open hook that returns a different wrap fails the open", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox"], + })); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/other"], + })); + await expect(hooks.invoke("open", "agent.open.before", openInput, paseo)).rejects.toThrow( + "cannot change a wrap", + ); +}); + +test("a session-open wrap needs an absolute executable", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ ...request, wrap: ["sandbox"] })); + await expect(hooks.invoke("open", "agent.open.before", openInput, paseo)).rejects.toThrow( + "must be absolute", + ); +}); + +test("a history open keeps the wrap while tools and MCP servers are stripped", async () => { + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox"], + mcpServers: { extra: { type: "stdio", command: "/bin/server" } }, + appendSystemPrompt: ["history"], + })); + const history = await hooks.invoke( + "history", + "agent.open.before", + { ...openInput, purpose: "history" }, + paseo, + ); + expect(history).toMatchObject({ wrap: ["/usr/local/bin/sandbox"], tools: [], mcpServers: {} }); + expect(history).not.toHaveProperty("appendSystemPrompt"); +}); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 9b138335b3..ee11ee9d00 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, @@ -118,6 +119,12 @@ const beforeSchemas = { tools: z.array(agentToolMetadataSchema), env: z.record(z.string(), z.string()), mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(), + wrap: z + .tuple( + [z.string().refine(isAbsolute, "agent.open.before wrap executable must be absolute")], + z.string(), + ) + .optional(), }) .strict(), "workspace.create.before": WorkspaceCreateRequestSchema.omit({ @@ -281,8 +288,14 @@ 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/plugins/antigravity-provider/server/provider.test.ts b/plugins/antigravity-provider/server/provider.test.ts index 6e8bbd1ba9..e949b07dbf 100644 --- a/plugins/antigravity-provider/server/provider.test.ts +++ b/plugins/antigravity-provider/server/provider.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpdir } from "node:os"; import type { ProviderEvent } from "@getpaseo/plugin/server/provider"; @@ -886,3 +886,74 @@ 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 = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-wrap-")); + directories.push(directory); + const agy = path.join(directory, "agy"); + await writeFile( + agy, + `#!${process.execPath} +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" }] }] } }); + if (method === "session/new") send({ method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "available_commands_update", availableCommands: [] } } }); +}); +`, + ); + const launcher = path.join(directory, "launcher"); + const record = path.join(directory, "launch.json"); + await writeFile( + launcher, + `#!${process.execPath} +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)); +`, + ); + await Promise.all([chmod(agy, 0o755), chmod(launcher, 0o755)]); + const provider = createAntigravityProvider(); + expect(provider.launchWrap).toBe(true); + const connection = await provider.connect({ + launch: { command: agy, args: ["acp", "--disable-telemetry"], env: {} }, + 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: [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, agy, "acp", "--disable-telemetry"], + hook: "final", + }); + } finally { + await connection.close(); + } +});