From ecf8c812cda4df005f1f6e7de798138731ba142c Mon Sep 17 00:00:00 2001 From: CL Kao Date: Sat, 21 Nov 2026 17:04:27 -0800 Subject: [PATCH] fix(plugins): keep the wrap prepend internal and test Windows launchers through a seam - Inline the wrap prepend in the ACP shim and Codex instead of exporting applyLaunchWrap from @getpaseo/plugin/server; the author surface and boundaries.test.ts stay as upstream. - spawnProcess and execCommand now share resolveSpawnInvocation, which takes the platform. A unit test proves a Windows script wrapper runs through cmd.exe with each argument quoted whole, without mocking child_process or patching process.platform. - A wrapped Codex refresh whose provider command is a Windows script spawns through the production spawnProcess, with the provider command passed to the wrapper as an argument. - The wrap fixtures in the ACP and Antigravity tests run as Node through process.execPath, so they also run on Windows. - The provider protocol rejects an empty wrap executable. - The provider registry and plugin clients set supportsLaunchWrap where they build the client. - Docs name the launch wrap in the hook summaries and point provider authors at ProviderRegistration.launchWrap. Co-Authored-By: Claude Opus 5.5 --- docs/plugins.md | 8 +- .../src/server/acp-internal/connection.ts | 10 +- packages/plugin/src/server/acp.test.ts | 17 ++- packages/plugin/src/server/index.ts | 2 +- .../process-internal/windows-command.ts | 25 ++-- packages/plugin/src/server/process.test.ts | 62 +++------- packages/plugin/src/server/process.ts | 56 +++++---- packages/plugin/src/server/provider.ts | 2 +- .../src/server/agent/agent-manager.test.ts | 85 ++++++++++++- .../src/server/agent/plugin-provider.test.ts | 36 +----- .../src/server/agent/plugin-provider.ts | 2 + .../src/server/agent/provider-registry.ts | 7 +- .../agent/providers/codex-app-server-agent.ts | 6 +- .../server/plugins/lifecycle/handlers.test.ts | 115 +++++++----------- .../server/provider.test.ts | 47 +++---- public-docs/plugins/hooks.md | 4 +- public-docs/plugins/hooks.zh-CN.md | 4 +- 17 files changed, 256 insertions(+), 232 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index a31471d098..91f51763ed 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -462,8 +462,8 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md) owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved -configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on -every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary. +configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a +[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary. `packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to each live session. A plugin start, stop, or reload reruns only that plugin's callback per session, swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes @@ -623,6 +623,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is no provider reload input. +Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can +run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See +[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both. + For an ACP command, register `runAcpProvider({ id, label, command })` from `@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind` (`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index 5915810289..c9d436ac75 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 { applyLaunchWrap, spawnProcess, terminateProcess } from "../process.js"; +import { spawnProcess, terminateProcess } from "../process.js"; import { Readable, Writable } from "node:stream"; import { ClientSideConnection, @@ -501,7 +501,13 @@ class AcpRuntime { args: options.options.command.slice(1), env: process.env, }; - const spawned = options.wrap ? applyLaunchWrap(options.wrap, launch) : launch; + // 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, { cwd: options.cwd, env: { ...launch.env, ...options.env }, diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index f90bc06ea9..7094fd7e6e 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -1,4 +1,4 @@ -import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { @@ -7128,9 +7128,10 @@ describe("ACP tool call rows", () => { describe("runAcpProvider launch wrap", () => { async function wrapFixture(): Promise<{ - launcher: string; agent: string; launchLog: string; + /** The wrap that runs the recording launcher as Node, tagged so the agent can tell. */ + wrap: (tag: string) => [string, ...string[]]; launches: () => Promise>; agentStarts: () => Promise; }> { @@ -7142,8 +7143,7 @@ describe("runAcpProvider launch wrap", () => { // 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 { 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"); @@ -7153,7 +7153,6 @@ child.on("exit", (code) => process.exit(code ?? 1)); `, "utf8", ); - await chmod(launcher, 0o755); const agent = path.join(directory, "agent.cjs"); await writeFile( agent, @@ -7172,9 +7171,9 @@ lines.on("line", (line) => { const readLines = async (file: string) => (await readFile(file, "utf8").catch(() => "")).split("\n").filter(Boolean); return { - launcher, agent, launchLog, + wrap: (tag) => [process.execPath, launcher, launchLog, tag], launches: async () => (await readLines(launchLog)).map((line) => JSON.parse(line)), agentStarts: async () => await readLines(agentLog), }; @@ -7211,7 +7210,7 @@ lines.on("line", (line) => { 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 connection.send(wrappedOpen("one", fixture.wrap("sandbox"))); await waitForEvent(events, (event) => event.type === "session.ready"); expect(await fixture.launches()).toEqual([ { argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "one" }, @@ -7231,7 +7230,7 @@ lines.on("line", (line) => { "--profile name with spaces", ]); try { - await connection.send(wrappedOpen("one", [fixture.launcher, launchLog, "tag with spaces"])); + await connection.send(wrappedOpen("one", fixture.wrap("tag with spaces"))); await waitForEvent(events, (event) => event.type === "session.ready"); expect((await fixture.launches())[0]?.argv).toEqual([ launchLog, @@ -7250,7 +7249,7 @@ lines.on("line", (line) => { 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("wrapped", fixture.wrap("sandbox"))); await connection.send(wrappedOpen("bare", undefined)); await waitForEvent( events, diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index ffdc88cde1..fe41fac10c 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 { applyLaunchWrap, spawnProcess, execCommand, terminateProcess } from "./process.js"; +export { 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/process-internal/windows-command.ts b/packages/plugin/src/server/process-internal/windows-command.ts index 44b9362ad8..188209437e 100644 --- a/packages/plugin/src/server/process-internal/windows-command.ts +++ b/packages/plugin/src/server/process-internal/windows-command.ts @@ -1,12 +1,15 @@ import { extname } from "node:path"; -export function isWindowsCommandScript(executablePath: string): boolean { +export function isWindowsCommandScript( + executablePath: string, + platform: NodeJS.Platform = process.platform, +): boolean { const extension = extname(executablePath).toLowerCase(); - return process.platform === "win32" && (extension === ".cmd" || extension === ".bat"); + return platform === "win32" && (extension === ".cmd" || extension === ".bat"); } -function escapeWindowsCmdValue(value: string): string { - if (process.platform !== "win32") return value; +function escapeWindowsCmdValue(value: string, platform: NodeJS.Platform): string { + if (platform !== "win32") return value; const isQuoted = value.startsWith('"') && value.endsWith('"'); const unquoted = isQuoted ? value.slice(1, -1) : value; @@ -32,8 +35,11 @@ function escapeWindowsCmdValue(value: string): string { * command path with spaces (e.g. `C:\Program Files\...`) is split at the * space. Wrapping it in quotes produces the correct `"C:\Program Files\..." args`. */ -export function quoteWindowsCommand(command: string): string { - return escapeWindowsCmdValue(command); +export function quoteWindowsCommand( + command: string, + platform: NodeJS.Platform = process.platform, +): string { + return escapeWindowsCmdValue(command, platform); } /** @@ -41,6 +47,9 @@ export function quoteWindowsCommand(command: string): string { * Any argument containing spaces must be quoted or it will be split before the * child process sees it. */ -export function quoteWindowsArgument(argument: string): string { - return escapeWindowsCmdValue(argument); +export function quoteWindowsArgument( + argument: string, + platform: NodeJS.Platform = process.platform, +): string { + return escapeWindowsCmdValue(argument, platform); } diff --git a/packages/plugin/src/server/process.test.ts b/packages/plugin/src/server/process.test.ts index ba42f1a4d6..9e7eeb707a 100644 --- a/packages/plugin/src/server/process.test.ts +++ b/packages/plugin/src/server/process.test.ts @@ -1,22 +1,9 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import type * as ChildProcess from "node:child_process"; -import { afterEach, expect, test, vi } from "vitest"; -import { applyLaunchWrap, execCommand, spawnProcess } from "./index.js"; - -// Delegates to the real spawn; a test can capture one call instead of starting a process. -const spawnSpy = vi.hoisted(() => ({ - current: undefined as undefined | ((...args: unknown[]) => unknown), -})); -vi.mock("node:child_process", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - spawn: (...args: Parameters) => - spawnSpy.current ? spawnSpy.current(...args) : actual.spawn(...args), - }; -}); +import { afterEach, expect, test } from "vitest"; +import { execCommand, spawnProcess } from "./index.js"; +import { resolveSpawnInvocation } from "./process.js"; const roots: string[] = []; afterEach(async () => { @@ -66,33 +53,24 @@ test("spawnProcess delivers shell arguments to the real child unchanged", async expect(JSON.parse(stdout)).toEqual(argumentsToPreserve); }); -test("a Windows command-script wrapper starts through cmd.exe with each argument quoted whole", () => { - const platform = Object.getOwnPropertyDescriptor(process, "platform")!; - const calls: unknown[][] = []; - spawnSpy.current = (...args) => { - calls.push(args); - return {}; - }; - Object.defineProperty(process, "platform", { ...platform, value: "win32" }); - try { - const { command, args } = applyLaunchWrap( - ["C:\\Program Files\\Sandbox\\run.cmd", "--profile", "work profile"], - { command: "C:\\tools\\agy.cmd", args: ["acp", "--disable-telemetry"] }, - ); - spawnProcess(command, args, { stdio: "pipe" }); - } finally { - Object.defineProperty(process, "platform", platform); - spawnSpy.current = undefined; - } - expect(calls).toHaveLength(1); - const [command, args, options] = calls[0] as [string, string[], { shell: unknown }]; - expect(options.shell).toBe(true); - expect(command).toBe('"C:\\Program Files\\Sandbox\\run.cmd"'); - expect(args).toEqual([ +// A launch wrap prepends a Windows script wrapper to the provider launch; spawnProcess must run it +// through cmd.exe with every argument quoted whole, as it does for any provider launcher. +test("a Windows script launch wrap starts through cmd.exe with each argument quoted", () => { + const wrapped = [ + "C:\\Program Files\\Sandbox\\run.cmd", "--profile", - '"work profile"', + "work profile", "C:\\tools\\agy.cmd", "acp", - "--disable-telemetry", - ]); + ]; + expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "win32")).toEqual({ + command: '"C:\\Program Files\\Sandbox\\run.cmd"', + args: ["--profile", '"work profile"', "C:\\tools\\agy.cmd", "acp"], + shell: true, + }); + expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "linux")).toEqual({ + command: wrapped[0], + args: wrapped.slice(1), + shell: false, + }); }); diff --git a/packages/plugin/src/server/process.ts b/packages/plugin/src/server/process.ts index 80c14838a4..f5527945b1 100644 --- a/packages/plugin/src/server/process.ts +++ b/packages/plugin/src/server/process.ts @@ -33,26 +33,41 @@ function hasPathSeparator(value: string): boolean { function shouldUseWindowsShell( command: string, - requestedShell?: boolean | string, + requestedShell: boolean | string | undefined, + platform: NodeJS.Platform, ): boolean | string { - if (isWindowsCommandScript(command)) { + if (isWindowsCommandScript(command, platform)) { return true; } if (requestedShell !== undefined) { return requestedShell; } - return process.platform === "win32" && !hasPathSeparator(command) && !extname(command); + return platform === "win32" && !hasPathSeparator(command) && !extname(command); +} + +export interface SpawnInvocation { + command: string; + args: string[]; + shell: boolean | string; } /** - * Put `wrap` in front of a launch. Spawn the result with `spawnProcess`, which runs a Windows - * command-script wrapper through cmd.exe with quoted arguments, as for any provider launcher. + * How `spawnProcess` and `execCommand` start `command` on `platform`. On Windows a command script + * or a bare name runs through cmd.exe, so the command and every argument are quoted for it. */ -export function applyLaunchWrap( - wrap: readonly [string, ...string[]], - launch: { command: string; args: readonly string[] }, -): { command: string; args: string[] } { - return { command: wrap[0], args: [...wrap.slice(1), launch.command, ...launch.args] }; +export function resolveSpawnInvocation( + command: string, + args: readonly string[], + requestedShell: boolean | string | undefined, + platform: NodeJS.Platform = process.platform, +): SpawnInvocation { + const shell = shouldUseWindowsShell(command, requestedShell, platform); + if (platform !== "win32" || shell === false) return { command, args: [...args], shell }; + return { + command: quoteWindowsCommand(command, platform), + args: args.map((argument) => quoteWindowsArgument(argument, platform)), + shell, + }; } /** Launch a CLI with Windows command-script handling and argv quoting. The caller owns env. */ @@ -68,17 +83,12 @@ export function spawnProcess( options?: SpawnOptions, ): ChildProcess { const spawnOptions = options ?? {}; - const isWindows = process.platform === "win32"; - const shell = shouldUseWindowsShell(command, spawnOptions.shell); + const invocation = resolveSpawnInvocation(command, args, spawnOptions.shell); - const shouldQuoteForShell = isWindows && shell !== false; - const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command; - const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args; - - return spawn(resolvedCommand, resolvedArgs, { + return spawn(invocation.command, invocation.args, { ...spawnOptions, env: options?.env, - shell, + shell: invocation.shell, signal: options?.signal, windowsHide: true, }); @@ -89,13 +99,9 @@ export async function execCommand( args: string[], options?: ExecCommandOptions, ): Promise { - const isWindows = process.platform === "win32"; - const shell = shouldUseWindowsShell(command, options?.shell); - const shouldQuoteForShell = isWindows && shell !== false; - const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command; - const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args; + const invocation = resolveSpawnInvocation(command, args, options?.shell); - return execFileAsync(resolvedCommand, resolvedArgs, { + return execFileAsync(invocation.command, invocation.args, { cwd: options?.cwd, env: options?.env, encoding: options?.encoding ?? "utf8", @@ -103,7 +109,7 @@ export async function execCommand( killSignal: options?.killSignal, timeout: options?.timeout, maxBuffer: options?.maxBuffer, - shell, + shell: invocation.shell, windowsHide: true, }) as Promise; } diff --git a/packages/plugin/src/server/provider.ts b/packages/plugin/src/server/provider.ts index 2e3d03a509..26ee02a2c0 100644 --- a/packages/plugin/src/server/provider.ts +++ b/packages/plugin/src/server/provider.ts @@ -917,7 +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(), + wrap: z.tuple([z.string().min(1)], z.string()).optional(), }) .strict(); const externalResourceSchema = z diff --git a/packages/server/src/server/agent/agent-manager.test.ts b/packages/server/src/server/agent/agent-manager.test.ts index 08995d5078..e6d374999c 100644 --- a/packages/server/src/server/agent/agent-manager.test.ts +++ b/packages/server/src/server/agent/agent-manager.test.ts @@ -7,7 +7,7 @@ import { } from "./agent-messages/index.js"; import { expect, test, vi, onTestFinished } from "vitest"; import { spawn } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { randomUUID } from "node:crypto"; @@ -23,7 +23,11 @@ import { import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js"; import { AgentTurnStartCanceledError } from "./agent-sdk-types.js"; import { ForegroundPromptStart } from "./agent-run-state.js"; -import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js"; +import { + CodexAppServerAgentClient, + CodexAppServerAgentSession, +} from "./providers/codex-app-server-agent.js"; +import { spawnProcess } from "../../utils/spawn.js"; import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; @@ -16403,3 +16407,80 @@ test("a supporting provider receives the wrap at launch and the record never sto expect(JSON.stringify(await storage.get(created.id))).not.toContain("/opt/sandbox"); await manager.closeAgent(created.id); }); + +// Records its argv, then answers as the Codex app server, so the provider command is only an +// argument: a Windows script name there must reach the wrapper as is. +const RECORDING_CODEX_APP_SERVER = ` +const { appendFileSync } = require("node:fs"); +const [log, ...rest] = process.argv.slice(2); +appendFileSync(log, JSON.stringify(rest) + "\\n"); +const results = { + "collaborationMode/list": { data: [] }, + "config/read": { config: {} }, + getUserSavedConfig: { config: {} }, + "model/list": { data: [{ id: "gpt-5.4", isDefault: true, defaultReasoningEffort: "medium" }] }, + "skills/list": { data: [] }, + "thread/start": { thread: { id: "thread-1" } }, + "thread/resume": { thread: { id: "thread-1" } }, + "thread/loaded/list": { data: [] }, + "thread/backgroundTerminals/list": { data: [], nextCursor: null }, +}; +let buffer = ""; +process.stdin.on("data", (chunk) => { + buffer += chunk.toString(); + for (let index = buffer.indexOf("\\n"); index !== -1; index = buffer.indexOf("\\n")) { + const line = buffer.slice(0, index).trim(); + buffer = buffer.slice(index + 1); + if (!line) continue; + const message = JSON.parse(line); + if (message.id === undefined || !message.method) continue; + process.stdout.write(JSON.stringify({ id: message.id, result: results[message.method] ?? {} }) + "\\n"); + } +}); +`; + +test("a wrapped refresh passes a Windows script provider command to the wrapper through the real spawn", async () => { + const workdir = mkdtempSync(join(tmpdir(), "agent-launch-wrap-refresh-")); + onTestFinished(() => rmSync(workdir, { recursive: true, force: true })); + const launcher = join(workdir, "recording-app-server.cjs"); + const launches = join(workdir, "launches.jsonl"); + writeFileSync(launcher, RECORDING_CODEX_APP_SERVER); + // The version probes run `node --version`; sessions spawn through the production spawnProcess. + const codex = new CodexAppServerAgentClient( + logger, + { command: { mode: "replace", argv: [process.execPath] } }, + { + appServerProcess: { + resolvePrefix: async () => ({ command: "C:\\codex\\codex.cmd", args: [] }), + spawn: ({ command, args, options }) => spawnProcess(command, args, options), + }, + }, + ); + const client: AgentClient = Object.assign(codex, { supportsLaunchWrap: true }); + const manager = new AgentManager({ + clients: { codex: client }, + logger, + pluginLifecycle: { + emit: () => {}, + before: async (name, request) => + name === "agent.open.before" + ? { ...request, wrap: [process.execPath, launcher, launches] } + : request, + }, + }); + const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { + workspaceId: undefined, + }); + + await manager.reloadAgentSession(created.id); + + const argv = readFileSync(launches, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as string[]); + expect(argv).toHaveLength(2); + for (const launched of argv) + expect(launched.slice(0, 2)).toEqual(["C:\\codex\\codex.cmd", "app-server"]); + expect(manager.getAgent(created.id)?.lifecycle).not.toBe("error"); + await manager.closeAgent(created.id); +}); diff --git a/packages/server/src/server/agent/plugin-provider.test.ts b/packages/server/src/server/agent/plugin-provider.test.ts index dd18785395..4f22f1f3ab 100644 --- a/packages/server/src/server/agent/plugin-provider.test.ts +++ b/packages/server/src/server/agent/plugin-provider.test.ts @@ -3690,6 +3690,7 @@ test("a declared launch wrap still needs session.launch_wrap on the live connect registry.replace([{ ...harness.registration, launchWrap: true }]); expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(true); const client = registry.clients()[harness.registration.id]!; + expect(client.supportsLaunchWrap).toBe(true); await expect(client.requireLaunchWrap?.()).rejects.toMatchObject({ code: "launch_wrap_unsupported", @@ -3709,6 +3710,7 @@ test("a provider that declares no launch wrap is not marked as supporting it", ( const registry = new PluginAgentClientRegistry(createTestLogger()); registry.replace([harness.registration]); expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(false); + expect(registry.clients()[harness.registration.id]!.supportsLaunchWrap).toBe(false); }); test("a plugin session reopen sends the wrap the session opened with", async () => { @@ -3732,37 +3734,3 @@ test("a plugin session reopen sends the wrap the session opened with", async () 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 93c2051d2a..22c33870a2 100644 --- a/packages/server/src/server/agent/plugin-provider.ts +++ b/packages/server/src/server/agent/plugin-provider.ts @@ -1077,10 +1077,12 @@ class PluginAgentClient implements AgentClient { readonly getCatalogCacheKey?: AgentClient["getCatalogCacheKey"]; readonly installation?: AgentClientInstallation; + readonly supportsLaunchWrap: boolean; constructor(registration: ProviderRegistration, runtimeSettings?: ProviderRuntimeSettings) { this.provider = registration.id; this.label = registration.label; + this.supportsLaunchWrap = registration.launchWrap === true; this.runtime = new ProviderRuntime(registration, runtimeSettings); if (registration.getCatalogCacheKey) this.getCatalogCacheKey = (options) => this.runtime.catalogCacheKey(options); diff --git a/packages/server/src/server/agent/provider-registry.ts b/packages/server/src/server/agent/provider-registry.ts index 7d68205fe9..6d46c354e8 100644 --- a/packages/server/src/server/agent/provider-registry.ts +++ b/packages/server/src/server/agent/provider-registry.ts @@ -502,6 +502,7 @@ function wrapClientProvider( additionalModels: ProviderProfileModel[], profileModelsAreAdditive: boolean, configuredOptions: ProviderOptions | undefined, + supportsLaunchWrap: boolean, ): AgentClient { const listImportableSessions = inner.listImportableSessions?.bind(inner); const importSession = inner.importSession?.bind(inner); @@ -521,6 +522,7 @@ function wrapClientProvider( get capabilities() { return inner.capabilities; }, + supportsLaunchWrap, shutdown: inner.shutdown?.bind(inner), createSession: async (config, launchContext, options) => wrapSessionProvider( @@ -746,16 +748,15 @@ function createResolvedProviderClient( const inner = resolved.createBaseClient(logger); const profileModels = resolveConfiguredModels(provider, inner, resolved.profileModels); const additionalModels = resolveConfiguredModels(provider, inner, resolved.additionalModels); - const client = wrapClientProvider( + return wrapClientProvider( provider, inner, profileModels, additionalModels, resolved.profileModelsAreAdditive, resolved.providerOptions, + resolved.contract.supportsLaunchWrap === true, ); - client.supportsLaunchWrap = resolved.contract.supportsLaunchWrap === true; - return client; } interface RegisteredProvider { 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 62144b0cb2..5f85174bef 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,4 +1,3 @@ -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"; @@ -8285,7 +8284,10 @@ export class CodexAppServerAgentClient implements AgentClient { } // 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: options.wrap[0], + args: [...options.wrap.slice(1), resolvedPrefix.command, ...appServerArgs], + } : { command: resolvedPrefix.command, args: appServerArgs }; return () => { this.logger.trace( diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index 74611c900b..f51e8fc988 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -414,92 +414,67 @@ const openInput = { mcpServers: {}, }; -test("a session-open hook can select a launch wrap", async () => { +type OpenHookResult = (request: Record) => Record; + +/** Runs `results` as successive `agent.open.before` hooks of one plugin. */ +async function invokeOpen(results: OpenHookResult[], input: Record = openInput) { const hooks = new PluginHookHandlers(() => {}); - hooks.addHook("agent.open.before", async ({ request }) => ({ - ...request, + for (const result of results) { + hooks.addHook("agent.open.before", async ({ request }) => result(request) as never); + } + return await hooks.invoke("open", "agent.open.before", input, paseo); +} + +const withWrap = + (...wrap: string[]): OpenHookResult => + (request) => ({ ...request, wrap }); + +test("a session-open hook can select a launch wrap", async () => { + expect(await invokeOpen([withWrap("/usr/local/bin/sandbox", "--profile", "a b")])).toMatchObject({ wrap: ["/usr/local/bin/sandbox", "--profile", "a b"], - })); - 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( + await expect(invokeOpen([(request) => ({ ...request, notAHookField: true })])).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.each<[string, OpenHookResult, Record]>([ + [ + "omits it", + ({ wrap: _wrap, ...request }) => ({ ...request, env: { LATER: "1" } }), + { wrap: ["/usr/local/bin/sandbox"], env: { LATER: "1" } }, + ], + ["repeats it", withWrap("/usr/local/bin/sandbox"), { wrap: ["/usr/local/bin/sandbox"] }], +])("an earlier wrap stays when a later session-open hook %s", async (_case, later, expected) => { + expect(await invokeOpen([withWrap("/usr/local/bin/sandbox"), later])).toMatchObject(expected); }); -test("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( +test.each<[string, OpenHookResult[], string]>([ + [ + "a later hook returns a different wrap", + [withWrap("/usr/local/bin/sandbox"), withWrap("/usr/local/bin/other")], "cannot change a wrap", - ); -}); - -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", - ); + ], + ["the executable is relative", [withWrap("sandbox")], "must be absolute"], + ["the executable is empty", [withWrap("")], "must be absolute"], +])("a session-open wrap fails the open when %s", async (_case, results, message) => { + await expect(invokeOpen(results)).rejects.toThrow(message); }); test("a history open keeps the wrap while tools and MCP servers are stripped", async () => { - const 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", + const history = await invokeOpen( + [ + (request) => ({ + ...request, + wrap: ["/usr/local/bin/sandbox"], + mcpServers: { extra: { type: "stdio", command: "/bin/server" } }, + appendSystemPrompt: ["history"], + }), + ], { ...openInput, purpose: "history" }, - paseo, ); expect(history).toMatchObject({ wrap: ["/usr/local/bin/sandbox"], tools: [], mcpServers: {} }); expect(history).not.toHaveProperty("appendSystemPrompt"); diff --git a/plugins/antigravity-provider/server/provider.test.ts b/plugins/antigravity-provider/server/provider.test.ts index e949b07dbf..721bf04c7a 100644 --- a/plugins/antigravity-provider/server/provider.test.ts +++ b/plugins/antigravity-provider/server/provider.test.ts @@ -1,4 +1,4 @@ -import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { 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"; @@ -888,28 +888,24 @@ it("keeps a turn open for backgrounded run_command calls but not IsDaemon comman }); 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 { directory, launch } = await launchAgent(` + const { createInterface } = require("node:readline"); + const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); + createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method } = JSON.parse(line); + if (method === "initialize") send({ id, result: { protocolVersion: 1 } }); + if (method === "session/new") { + send({ id, result: { sessionId: "native", configOptions: [{ id: "mode", name: "Mode", category: "mode", type: "select", currentValue: "default", options: [{ value: "default", name: "Default" }] }] } }); + send({ method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "available_commands_update", availableCommands: [] } } }); + } + }); + `); + // Records what it was started with, then runs the rest: the provider's own launch. + const launcher = path.join(directory, "launcher.cjs"); const record = path.join(directory, "launch.json"); await writeFile( launcher, - `#!${process.execPath} -const { writeFileSync } = require("node:fs"); + `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 })); @@ -918,11 +914,10 @@ 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: {} }, + launch, versions: [1], capabilities: ["prompt.message", "session.launch_wrap"], }); @@ -940,7 +935,7 @@ child.on("exit", (code) => process.exit(code ?? 1)); mcpServers: {}, settings: {}, persist: false, - wrap: [launcher, record], + wrap: [process.execPath, launcher, record], }, }); await expect @@ -949,10 +944,8 @@ child.on("exit", (code) => process.exit(code ?? 1)); ) .toMatchObject({ type: "session.ready" }); const launched = JSON.parse(await readFile(record, "utf8")); - expect(launched).toEqual({ - argv: [record, agy, "acp", "--disable-telemetry"], - hook: "final", - }); + expect(launched).toEqual({ argv: [record, launch.command, ...launch.args], hook: "final" }); + expect(launched.argv.slice(-2)).toEqual(["acp", "--disable-telemetry"]); } finally { await connection.close(); } diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md index f62606642e..8baa6361f1 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -31,7 +31,7 @@ Names follow `subject.operation.position`: the subject, the operation, then `bef All handlers must be async. Turn completion includes success, failure, and cancellation; inspect `outcome`. Permission completion includes every resolution; inspect `resolution`. -Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, instructions, tools, and MCP servers each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action. +Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, instructions, tools, MCP servers, and a launch wrap each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action. `worktree.create.after` runs before the workspace is registered. It precedes `workspace.create.after`, and both precede the first agent's `agent.create.before` / `agent.open.before`. @@ -50,7 +50,7 @@ Paseo only sees the returned promise, so detached work gets no error reporting a ## Hooks | Hook | Waits | Payload | Handler may change | -|---------------------------|-------|-------------------------------------------|------------------------------------------------------------------------| +| ------------------------- | ----- | ----------------------------------------- | ---------------------------------------------------------------------- | | `workspace.create.before` | yes | `{ request }` | Entire create request | | `workspace.create.after` | no | `{ workspace }` | | | `workspace.archive.after` | no | `{ workspace }` | | diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index b8cfdee915..719ea73279 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -29,7 +29,7 @@ export default function contribute(server: PluginServerContext) { 所有处理函数都必须为异步函数。轮次完成包括成功、失败和取消,请查看 `outcome`。权限完成包括所有处理结果,请查看 `resolution`。 -创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、指令、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 +创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、指令、工具、MCP 服务器和启动包装。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。 `worktree.create.after` 在工作区注册前运行,随后是 `workspace.create.after`,两者都早于第一个 Agent 的 `agent.create.before` / `agent.open.before`。 @@ -48,7 +48,7 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 ## 钩子一览 {#hooks} | 钩子 | 等待 | 载荷 | 可修改 | -|---------------------------|------|-------------------------------------------|-------------------------------------------------------------------------| +| ------------------------- | ---- | ----------------------------------------- | ----------------------------------------------------------------------- | | `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | | `workspace.create.after` | 否 | `{ workspace }` | | | `workspace.archive.after` | 否 | `{ workspace }` | |