From 6b0fbfc640c079003aa067c24548bcd0fd1916ab Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 25 Nov 2026 10:39:18 +0100 Subject: [PATCH] refactor(plugins): one launch wrap for agents, terminals, and worktree commands terminal.create.before and command.run.before now change only env and a launch wrap, the same PluginLaunchWrap agent.open.before returns. Paseo starts the terminal as [...wrap, command, ...args] (the default shell when there is no command) and a setup or teardown command's shell as [...wrap, shell, ...shellArgs]. The first hook's wrap wins; a different one fails the operation. command, args, and the command text are read-only, so a plugin cannot rewrite what runs. The terminal wrap is applied in the daemon before the worker, so the terminal worker protocol is unchanged. resolveDefaultTerminalShell moves to its own module so the daemon does not load node-pty. Co-authored-by: CL Kao Co-authored-by: Josh Bendavid --- docs/plugins.md | 9 ++ packages/plugin/src/boundaries.test.ts | 18 ++- packages/plugin/src/server/index.ts | 1 + packages/plugin/src/server/lifecycle.ts | 34 +++-- .../server/src/server/command-run-hook.ts | 2 +- .../src/server/plugins/lifecycle.e2e.test.ts | 89 +++++++++--- .../server/plugins/lifecycle/handlers.test.ts | 132 +++++++++++++----- .../src/server/plugins/lifecycle/index.ts | 61 +++++--- .../src/terminal/default-terminal-shell.ts | 13 ++ .../src/terminal/terminal-create-hook.ts | 16 ++- packages/server/src/terminal/terminal.test.ts | 2 +- packages/server/src/terminal/terminal.ts | 14 +- .../server/src/utils/worktree.posix.test.ts | 39 +++++- packages/server/src/utils/worktree.ts | 61 +++++--- public-docs/plugins/hooks.md | 130 +++++++++-------- public-docs/plugins/hooks.zh-CN.md | 130 +++++++++-------- 16 files changed, 488 insertions(+), 263 deletions(-) create mode 100644 packages/server/src/terminal/default-terminal-shell.ts diff --git a/docs/plugins.md b/docs/plugins.md index d986c600f9..bf6775bcb0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -525,6 +525,15 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi `terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run. +Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle +module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's +`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and +no previous-version adapter is needed. A default-shell terminal resolves the shell there through +`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty. +The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not +report command completion. A setup or teardown wrap goes in front of the +`buildStringCommandShellInvocation` argv. + Emit from the operation owner, not a client subscription. Provider history replay must not trigger live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt or answer a permission through its own daemon session. Awaiting it there deadlocks that command. diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 020002f093..be221d49b9 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -392,7 +392,7 @@ describe("lifecycle hook SDK types", () => { it("infers payloads and replacement requests and requires async handlers and new names", () => { expect( typeErrors(` - import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server"; + import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server"; import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types"; export default function contribute(server: PluginServerContext) { server.addHook("worktree.create.before", async ({ request }) => { @@ -438,19 +438,27 @@ describe("lifecycle hook SDK types", () => { server.addHook("terminal.create.before", async ({ request }) => { const source: "client" | "agent" | "script" | "worktree" = request.source; const input: string | null = request.input; + const program: string | null = request.command; // @ts-expect-error The terminal's workspace is read-only. request.workspaceId = "wks_other"; - // @ts-expect-error The terminal's directory is read-only. - request.cwd = "/other"; - return { ...request, command: "/usr/bin/wrapper", args: [request.command ?? "sh"], env: { A: "1" } }; + // @ts-expect-error The terminal's program is read-only; return a wrap instead. + request.command = "/usr/bin/other"; + const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId]; + return { ...request, env: { A: "1" }, wrap }; }); server.addHook("command.run.before", async ({ request }) => { const workspace: string | null = request.workspaceId; const purpose: "setup" | "teardown" = request.purpose; // @ts-expect-error A command's purpose is read-only. request.purpose = "setup"; - return { ...request, command: "wrapper " + request.command }; + // @ts-expect-error The configured command is read-only; return a wrap instead. + request.command = "wrapper " + request.command; + return { ...request, wrap: ["/usr/bin/sandbox"] }; }); + server.addHook("agent.open.before", async ({ request }) => ({ + ...request, + wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"], + })); server.addHook("agent.turn.after", async (event, { paseo, signal }) => { const { agent, outcome } = event; const kind: "completed" | "failed" | "canceled" = outcome.kind; diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index 298e145675..d64a22b17c 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -23,6 +23,7 @@ export type { PluginHookWorkspace, PluginHookWorktree, PluginWorktreeCreateRequest, + PluginLaunchWrap, PluginTerminalCreateRequest, PluginCommandRunRequest, PluginHookAgent, diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index 75e88d48bf..585de1b2fb 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -69,9 +69,14 @@ export type PluginWorktreeCreateRequest = { ); /** - * A terminal Paseo is about to create in a workspace. `command` is absent for the default shell. - * Paseo types `input` into a `script` or `worktree` terminal once its shell starts. + * A launcher Paseo starts a process behind: the process runs as `[...wrap, command, ...args]`. + * The executable is an absolute path on the daemon host. Each element is one argument; no shell + * parses them, except that Windows runs a `.cmd` or `.bat` executable through cmd.exe. A later + * hook may omit the wrap or return the same one; a different wrap fails the operation. */ +export type PluginLaunchWrap = readonly [executable: string, ...args: string[]]; + +/** A terminal Paseo is about to create in a workspace. */ export interface PluginTerminalCreateRequest { readonly workspaceId: string; readonly cwd: string; @@ -81,10 +86,15 @@ export interface PluginTerminalCreateRequest { */ readonly source: "client" | "agent" | "script" | "worktree"; readonly name: string | null; + /** The program the terminal starts, or `null` for the user's default shell. */ + readonly command: string | null; + readonly args: readonly string[]; + /** What Paseo types into the shell once it starts: the command of a script or worktree terminal. */ readonly input: string | null; - command?: string; - args: string[]; + /** Environment overrides for the terminal; excludes the daemon's inherited environment. */ env: Record; + /** Start the terminal as `[...wrap, command, ...args]`; with no `command`, the default shell. */ + wrap?: PluginLaunchWrap; } /** A `paseo.json` worktree setup or teardown command Paseo is about to run. */ @@ -93,9 +103,12 @@ export interface PluginCommandRunRequest { readonly workspaceId: string | null; readonly cwd: string; readonly purpose: "setup" | "teardown"; - /** A shell command: Paseo runs it with `bash -c`, or PowerShell or `cmd.exe` on Windows. */ - command: string; + /** The command as written in `paseo.json`. Paseo runs it through a shell. */ + readonly command: string; + /** Environment overrides for the command; excludes the daemon's inherited environment. */ env: Record; + /** Start the command's shell as `[...wrap, shell, ...shellArgs]`. */ + wrap?: PluginLaunchWrap; } export interface PluginHookAgent { @@ -129,12 +142,11 @@ export interface PluginSessionOpenRequest { 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. + * Start the provider's harness as `[...wrap, command, ...args]`. Only a provider whose snapshot + * entry has `launchWrap: true` applies it; any other provider fails the open. Not saved on the + * agent. */ - wrap?: readonly [executable: string, ...args: string[]]; + wrap?: PluginLaunchWrap; } export type PluginTurnOutcome = diff --git a/packages/server/src/server/command-run-hook.ts b/packages/server/src/server/command-run-hook.ts index 2db304fc98..8b6bd2ef48 100644 --- a/packages/server/src/server/command-run-hook.ts +++ b/packages/server/src/server/command-run-hook.ts @@ -9,6 +9,6 @@ export function commandRunHook( if (!lifecycle) return undefined; return async ({ command, env }) => { const request = await lifecycle.before("command.run.before", { ...scope, command, env }); - return { command: request.command, env: request.env }; + return { env: request.env, ...(request.wrap ? { wrap: request.wrap } : {}) }; }; } diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index 7ef66d7ef2..c2a15b694c 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -630,10 +630,24 @@ test("plugins wrap or refuse terminals and worktree setup and teardown commands" const repository = path.join(root, "repository"); const pluginDirectory = path.join(root, "plugin"); const hookLog = path.join(root, "hooks.jsonl"); + const launchLog = path.join(root, "launches.jsonl"); + const launcher = path.join(root, "launcher.cjs"); + // The sandbox stand-in: records the argv after its own two, marks the environment, runs the rest. + await writeFile( + launcher, + `const { appendFileSync } = require("node:fs"); +const { spawn } = require("node:child_process"); +const [log, tag, command, ...args] = process.argv.slice(2); +appendFileSync(log, JSON.stringify({ tag, command, args }) + "\\n"); +const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED: tag } }); +for (const signal of ["SIGTERM", "SIGHUP", "SIGINT"]) process.on(signal, () => child.kill(signal)); +child.on("exit", (code) => process.exit(code ?? 1)); +`, + ); // Node one-liners read the environment the same way under bash, PowerShell, and cmd.exe. - const setupCommand = `node -e "require('fs').writeFileSync('setup.txt', 'setup:' + process.env.HOOK_MARK)"`; - const teardownCommand = `node -e "require('fs').writeFileSync(require('path').join(process.env.PASEO_SOURCE_CHECKOUT_PATH, '..', 'teardown.txt'), 'teardown:' + process.env.HOOK_MARK)"`; - const scriptCommand = `node -e "console.log('script:' + process.env.HOOK_MARK)"`; + const setupCommand = `node -e "require('fs').writeFileSync('setup.txt', 'setup:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`; + const teardownCommand = `node -e "require('fs').writeFileSync(require('path').join(process.env.PASEO_SOURCE_CHECKOUT_PATH, '..', 'teardown.txt'), 'teardown:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`; + const scriptCommand = `node -e "console.log('script:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`; execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); await writeFile( path.join(repository, "paseo.json"), @@ -665,21 +679,24 @@ test("plugins wrap or refuse terminals and worktree setup and teardown commands" ` import { appendFile } from "node:fs/promises"; const log = (entry) => appendFile(${JSON.stringify(hookLog)}, JSON.stringify(entry) + "\\n"); +const wrap = (tag) => [${JSON.stringify(process.execPath)}, ${JSON.stringify(launcher)}, ${JSON.stringify(launchLog)}, tag]; export default function contribute(server) { server.addHook("terminal.create.before", async ({ request }) => { await log({ hook: "terminal", request }); if (request.name === "Refused") throw new Error("terminals named Refused stay closed"); - if (request.source === "script") return { ...request, env: { ...request.env, HOOK_MARK: "hooked" } }; return { ...request, - command: process.execPath, - args: ["-e", "console.log('wrapped:' + process.env.HOOK_MARK); setInterval(() => {}, 1000)"], env: { ...request.env, HOOK_MARK: request.source + ":" + request.workspaceId }, + wrap: wrap("terminal"), }; }); server.addHook("command.run.before", async ({ request }) => { await log({ hook: "command", request }); - return { ...request, env: { ...request.env, HOOK_MARK: request.purpose + "-hooked" } }; + return { + ...request, + env: { ...request.env, HOOK_MARK: request.purpose + "-hooked" }, + wrap: wrap(request.purpose), + }; }); return () => {}; } @@ -701,23 +718,32 @@ export default function contribute(server) { const workspaceId = created.workspace!.id; const worktree = created.workspace!.workspaceDirectory; - // Setup runs after creation, with the hook's environment. + // Setup runs after creation, behind the wrap, with the hook's environment. await expect .poll(() => readFile(path.join(worktree, "setup.txt"), "utf8").catch(() => ""), { timeout: 30_000, }) - .toBe("setup:setup-hooked"); + .toBe("setup:setup-hooked:setup"); - const wrapped = await sdk.terminals.create({ workspaceId, name: "Wrapped" }); + const program = [ + "-e", + "console.log('program:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED); setInterval(() => {}, 1000)", + ]; + const wrapped = await sdk.terminals.create({ + workspaceId, + name: "Wrapped", + command: process.execPath, + args: program, + }); await expect .poll(async () => (await wrapped.capture({ stripAnsi: true })).lines.join("\n")) - .toContain(`wrapped:client:${workspaceId}`); + .toContain(`program:client:${workspaceId}:terminal`); await expect(sdk.terminals.create({ workspaceId, name: "Refused" })).rejects.toThrow( "Plugin terminal-hooks terminal.create.before failed: terminals named Refused stay closed", ); - // A script's command is typed into a default shell, which the hook gave its environment. + // A script's command is typed into a default shell, and that shell runs behind the wrap. await client.startWorkspaceScript(workspaceId, "greet"); await expect .poll(async () => { @@ -727,37 +753,41 @@ export default function contribute(server) { if (!script) return ""; return (await sdk.terminals.ref(script.id).capture({ stripAnsi: true })).lines.join("\n"); }) - .toContain("script:hooked"); + .toContain(`script:script:${workspaceId}:terminal`); await client.archiveWorkspace(workspaceId); await expect .poll(() => readFile(path.join(root, "teardown.txt"), "utf8").catch(() => ""), { timeout: 30_000, }) - .toBe("teardown:teardown-hooked"); + .toBe("teardown:teardown-hooked:teardown"); - const entries = (await readFile(hookLog, "utf8")) - .trim() - .split("\n") - .map((line) => JSON.parse(line)); + const readJsonLines = async (file: string) => + (await readFile(file, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + const entries = await readJsonLines(hookLog); expect(entries.filter((entry) => entry.hook === "command")).toEqual([ { hook: "command", - request: expect.objectContaining({ + request: { workspaceId, cwd: worktree, purpose: "setup", command: setupCommand, - }), + env: expect.any(Object), + }, }, { hook: "command", - request: expect.objectContaining({ + request: { workspaceId, cwd: worktree, purpose: "teardown", command: teardownCommand, - }), + env: expect.any(Object), + }, }, ]); expect(entries.filter((entry) => entry.hook === "terminal")).toEqual([ @@ -768,8 +798,9 @@ export default function contribute(server) { cwd: worktree, source: "client", name: "Wrapped", + command: process.execPath, + args: program, input: null, - args: [], env: {}, }, }, @@ -783,10 +814,22 @@ export default function contribute(server) { workspaceId, source: "script", name: "greet", + command: null, input: scriptCommand, }), }, ]); + // Paseo appended what it would have run: the shell for a command, the program, the default shell. + const launches = await readJsonLines(launchLog); + expect(launches.map(({ tag, command }) => ({ tag, command }))).toEqual([ + { tag: "setup", command: expect.any(String) }, + { tag: "terminal", command: process.execPath }, + { tag: "terminal", command: expect.any(String) }, + { tag: "teardown", command: expect.any(String) }, + ]); + expect(launches[0].args.at(-1)).toBe(setupCommand); + expect(launches[1].args).toEqual(program); + expect(launches[3].args.at(-1)).toBe(teardownCommand); } finally { await sdk.close(); await client.close(); diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index 921ac03ad9..916967057d 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -458,8 +458,8 @@ test.each<[string, OpenHookResult[], string]>([ [withWrap("/usr/local/bin/sandbox"), withWrap("/usr/local/bin/other")], "cannot change a wrap", ], - ["the executable is relative", [withWrap("sandbox")], "must be absolute"], - ["the executable is empty", [withWrap("")], "must be absolute"], + ["the executable is relative", [withWrap("sandbox")], "must be an absolute path"], + ["the executable is empty", [withWrap("")], "must be an absolute path"], ])("a session-open wrap fails the open when %s", async (_case, results, message) => { await expect(invokeOpen(results)).rejects.toThrow(message); }); @@ -480,48 +480,110 @@ test("a history open keeps the wrap while tools and MCP servers are stripped", a expect(history).not.toHaveProperty("appendSystemPrompt"); }); -test("terminal and command hooks can change only what Paseo runs", async () => { - const terminal = { - workspaceId: "wks_a", - cwd: "/work/a", - source: "client" as const, - name: "Shell", - input: null, - args: [], - env: {}, - }; +const terminalRequest = { + workspaceId: "wks_a", + cwd: "/work/a", + source: "client" as const, + name: "Shell", + command: null, + args: [], + input: null, + env: {}, +}; +const commandRequest = { + workspaceId: null, + cwd: "/work/a", + purpose: "teardown" as const, + command: "make clean && rm -rf build", + env: {}, +}; + +test("terminal and command hooks can change env and wrap", async () => { await expect( - validateBeforeResult("terminal.create.before", terminal, { - ...terminal, - command: "/usr/bin/wrapper", - args: ["--workspace", "wks_a"], + validateBeforeResult("terminal.create.before", terminalRequest, { + ...terminalRequest, env: { WRAPPED: "1" }, + wrap: ["/usr/bin/sandbox", "--workspace", "wks_a"], }), ).resolves.toEqual({ - ...terminal, - command: "/usr/bin/wrapper", - args: ["--workspace", "wks_a"], + ...terminalRequest, env: { WRAPPED: "1" }, + wrap: ["/usr/bin/sandbox", "--workspace", "wks_a"], }); await expect( - validateBeforeResult("terminal.create.before", terminal, { ...terminal, cwd: "/elsewhere" }), - ).rejects.toThrow("terminal.create.before hooks can only change command, args, and env"); - - const command = { - workspaceId: null, - cwd: "/work/a", - purpose: "teardown" as const, - command: "make clean", - env: {}, - }; - await expect( - validateBeforeResult("command.run.before", command, { ...command, command: "wrap make clean" }), - ).resolves.toMatchObject({ command: "wrap make clean" }); - await expect( - validateBeforeResult("command.run.before", command, { ...command, purpose: "setup" }), - ).rejects.toThrow("command.run.before hooks can only change command and env"); + validateBeforeResult("command.run.before", commandRequest, { + ...commandRequest, + wrap: ["/usr/bin/sandbox"], + }), + ).resolves.toMatchObject({ command: "make clean && rm -rf build", wrap: ["/usr/bin/sandbox"] }); }); +test.each<[string, "terminal.create.before" | "command.run.before", object, object, string]>([ + [ + "a terminal's directory", + "terminal.create.before", + terminalRequest, + { cwd: "/elsewhere" }, + "terminal.create.before hooks can only change env and wrap", + ], + [ + "a terminal's program", + "terminal.create.before", + terminalRequest, + { command: "/usr/bin/sandbox" }, + "terminal.create.before hooks can only change env and wrap", + ], + [ + "a command's text", + "command.run.before", + commandRequest, + { command: "sandbox make clean" }, + "command.run.before hooks can only change env and wrap", + ], + [ + "a command's purpose", + "command.run.before", + commandRequest, + { purpose: "setup" }, + "command.run.before hooks can only change env and wrap", + ], + [ + "a relative wrap", + "command.run.before", + commandRequest, + { wrap: ["sandbox"] }, + "wrap executable must be an absolute path", + ], +])("a hook cannot change %s", async (_case, name, request, change, message) => { + await expect( + validateBeforeResult(name, request as never, { ...request, ...change }), + ).rejects.toThrow(message); +}); + +test.each(["terminal.create.before", "command.run.before"] as const)( + "%s keeps the first wrap and rejects a different one", + async (name) => { + const initial = name === "terminal.create.before" ? terminalRequest : commandRequest; + const hooks = new PluginHookHandlers(() => {}); + hooks.addHook( + name, + async ({ request }) => ({ ...request, wrap: ["/usr/bin/sandbox"] }) as never, + ); + hooks.addHook(name, async ({ request }) => { + const { wrap: _omitted, ...rest } = request as typeof request & { wrap?: unknown }; + return { ...rest, env: { LATER: "1" } } as never; + }); + await expect(hooks.invoke("first", name, initial, paseo)).resolves.toMatchObject({ + wrap: ["/usr/bin/sandbox"], + env: { LATER: "1" }, + }); + hooks.addHook(name, async ({ request }) => ({ ...request, wrap: ["/usr/bin/other"] }) as never); + await expect(hooks.invoke("second", name, initial, paseo)).rejects.toThrow( + `${name} hooks cannot change a wrap an earlier hook selected`, + ); + }, +); + test("agent creation hooks keep the workspace, including from plugins that omit it", async () => { const request = { config: { provider: "claude", cwd: "/work/a" }, diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index 7c2c8ae982..af4cf3b3cd 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -94,6 +94,10 @@ const worktreeRequestSchema = z.discriminatedUnion("kind", [ .strict(), ]); +const launchWrapSchema = z + .tuple([z.string().refine(isAbsolute, "wrap executable must be an absolute path")], z.string()) + .optional(); + const beforeSchemas = { "worktree.create.before": worktreeRequestSchema, "agent.create.before": CreateAgentRequestMessageSchema.pick({ @@ -122,12 +126,7 @@ 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(), + wrap: launchWrapSchema, }) .strict(), "workspace.create.before": WorkspaceCreateRequestSchema.omit({ @@ -140,10 +139,11 @@ const beforeSchemas = { cwd: z.string(), source: z.enum(["client", "agent", "script", "worktree"]), name: z.string().nullable(), - input: z.string().nullable(), - command: z.string().min(1).optional(), + command: z.string().nullable(), args: z.array(z.string()), + input: z.string().nullable(), env: z.record(z.string(), z.string()), + wrap: launchWrapSchema, }) .strict(), "command.run.before": z @@ -151,8 +151,9 @@ const beforeSchemas = { workspaceId: z.string().nullable(), cwd: z.string(), purpose: z.enum(["setup", "teardown"]), - command: z.string().min(1), + command: z.string(), env: z.record(z.string(), z.string()), + wrap: launchWrapSchema, }) .strict(), }; @@ -160,12 +161,12 @@ const beforeSchemas = { // Request fields a hook reads but can't change, with the error a changed one gets. const readOnlyRequestFields = { "terminal.create.before": { - fields: ["workspaceId", "cwd", "source", "name", "input"], - message: "terminal.create.before hooks can only change command, args, and env", + fields: ["workspaceId", "cwd", "source", "name", "command", "args", "input"], + message: "terminal.create.before hooks can only change env and wrap", }, "command.run.before": { - fields: ["workspaceId", "cwd", "purpose"], - message: "command.run.before hooks can only change command and env", + fields: ["workspaceId", "cwd", "purpose", "command"], + message: "command.run.before hooks can only change env and wrap", }, } as const; @@ -178,6 +179,24 @@ function assertReadOnlyFields(name: string, input: unknown, result: unknown): vo throw new Error(message); } +type LaunchWrap = z.infer; + +/** + * One wrap per operation: the first hook that selects a wrap owns it. A later hook may omit it or + * repeat it; a different wrap fails, so two sandboxes never silently stack or replace each other. + */ +function keepSelectedWrap(name: string, previous: LaunchWrap, next: LaunchWrap): LaunchWrap { + if (previous && next && !isDeepStrictEqual(previous, next)) { + throw new Error(`${name} hooks cannot change a wrap an earlier hook selected`); + } + return previous ?? next; +} + +function withWrap(result: Result, wrap: LaunchWrap): Result { + const { wrap: _replaced, ...rest } = result as Result & { wrap?: LaunchWrap }; + return (wrap ? { ...rest, wrap } : rest) as Result; +} + const sessionOpenLocalResultSchema = beforeSchemas["agent.open.before"].extend({ tools: z.array( z.custom( @@ -333,14 +352,8 @@ export async function validateBeforeResult { expect(portValue).toBeGreaterThan(0); }); - it("runs setup commands as a plugin prepares them and stops at a refused one", async () => { + it("runs each setup command behind a plugin's wrap and stops at a refused one", async () => { + // The launcher records the argv it was given, marks the environment, then runs the rest. + const launcher = join(repoDir, "launcher.sh"); + writeFileSync( + launcher, + '#!/bin/sh\nprintf "%s\\n" "$@" > "$(dirname "$0")/launch-argv.log"\nshift 2\nexport INSIDE=wrapped\nexec "$@"\n', + { mode: 0o755 }, + ); writeFileSync( join(repoDir, "paseo.json"), JSON.stringify({ - worktree: { setup: ['echo "$HOOK_MARK" > first.log', "echo second > second.log"] }, + worktree: { + setup: [ + 'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log', + "echo refused > refused.log", + ], + }, }), ); const seen: string[] = []; @@ -902,19 +914,32 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { }, prepareCommand: async ({ command, env }) => { seen.push(`${command} ${env.PASEO_BRANCH_NAME}`); - if (command.startsWith("echo second")) throw new Error("not in this workspace"); - return { command, env: { ...env, HOOK_MARK: "prepared" } }; + if (command.startsWith("echo refused")) throw new Error("not in this workspace"); + return { env: { ...env, HOOK_MARK: "prepared" }, wrap: [launcher, "--profile", "a b"] }; }, }); await expect(setup).rejects.toMatchObject({ name: "WorktreeSetupError", - message: "Worktree setup command refused: echo second > second.log\nnot in this workspace", + message: + "Worktree setup command refused: echo refused > refused.log\nnot in this workspace", results: [expect.objectContaining({ exitCode: 0 })], }); - expect(seen).toEqual(['echo "$HOOK_MARK" > first.log main', "echo second > second.log main"]); + expect(seen).toEqual([ + 'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log main', + "echo refused > refused.log main", + ]); + expect(readFileSync(join(repoDir, "launch-argv.log"), "utf8").trim().split("\n")).toEqual([ + "--profile", + "a b", + "bash", + "-c", + 'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log', + ]); expect(readFileSync(join(repoDir, "first.log"), "utf8").trim()).toBe("prepared"); - expect(existsSync(join(repoDir, "second.log"))).toBe(false); + // The part after `&&` ran inside the launcher too. + expect(readFileSync(join(repoDir, "second-part.log"), "utf8").trim()).toBe("wrapped"); + expect(existsSync(join(repoDir, "refused.log"))).toBe(false); }); it("runs string setup scripts from paseo.json as a single shell command", async () => { diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 0dbac109bb..3a8cd3a041 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -1,4 +1,3 @@ -import { execFile } from "child_process"; import { promisify } from "util"; import { constants as fsConstants, type Dirent, realpath } from "fs"; import { copyFile, mkdir, readdir, rm, stat } from "fs/promises"; @@ -7,9 +6,11 @@ import net from "node:net"; import { createHash } from "node:crypto"; import stripAnsi from "strip-ansi"; import pLimit from "p-limit"; +import { execCommand } from "@getpaseo/plugin/server"; import { buildStringCommandShellInvocation, createStringCommandShellEnv, + type StringCommandShellInvocation, } from "./string-command-shell.js"; import { readPaseoConfig } from "./paseo-config-file.js"; export { @@ -55,7 +56,6 @@ import type { PluginWorktreeManagerRuntime } from "../server/plugins/runtime.js" export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug"; -const execFileAsync = promisify(execFile); const READ_ONLY_GIT_ENV = { GIT_OPTIONAL_LOCKS: "0", } as const; @@ -146,17 +146,23 @@ export interface WorktreeLifecycleCommand { env: Record; } +/** How a lifecycle command runs after plugins saw it: its environment and an optional wrap. */ +export interface PreparedWorktreeLifecycleCommand { + env: Record; + wrap?: readonly [string, ...string[]]; +} + /** Lets plugins wrap or refuse a lifecycle command before it runs; see `command.run.before`. */ export type PrepareWorktreeLifecycleCommand = ( command: WorktreeLifecycleCommand, -) => Promise; +) => Promise; async function prepareLifecycleCommand( prepare: PrepareWorktreeLifecycleCommand | undefined, command: WorktreeLifecycleCommand, fail: (message: string) => Error, -): Promise { - if (!prepare) return command; +): Promise { + if (!prepare) return { env: command.env }; try { return await prepare(command); } catch (error) { @@ -164,6 +170,17 @@ async function prepareLifecycleCommand( } } +/** The shell invocation for a `paseo.json` command, started behind a plugin's wrap when set. */ +function lifecycleCommandInvocation( + command: string, + wrap: PreparedWorktreeLifecycleCommand["wrap"], +): StringCommandShellInvocation { + const invocation = buildStringCommandShellInvocation({ command }); + if (!wrap) return invocation; + const [executable, ...wrapArgs] = wrap; + return { shell: executable, args: [...wrapArgs, invocation.shell, ...invocation.args] }; +} + export class WorktreeSetupError extends Error { readonly results: WorktreeSetupCommandResult[]; @@ -469,14 +486,16 @@ export function processCarriageReturns(text: string): string { async function execSetupCommand( command: string, - options: { cwd: string; env: NodeJS.ProcessEnv }, + options: { cwd: string; env: NodeJS.ProcessEnv; wrap: PreparedWorktreeLifecycleCommand["wrap"] }, ): Promise { const startedAt = Date.now(); - const shellInvocation = buildStringCommandShellInvocation({ command }); + const shellInvocation = lifecycleCommandInvocation(command, options.wrap); try { - const { stdout, stderr } = await execFileAsync(shellInvocation.shell, shellInvocation.args, { + // execCommand starts a Windows `.cmd` or `.bat` wrap through cmd.exe; anything else has no shell. + const { stdout, stderr } = await execCommand(shellInvocation.shell, shellInvocation.args, { cwd: options.cwd, env: options.env, + shell: false, }); return { command, @@ -501,6 +520,7 @@ async function execSetupCommand( async function execSetupCommandStreamed(options: { command: string; + wrap: PreparedWorktreeLifecycleCommand["wrap"]; cwd: string; env: NodeJS.ProcessEnv; index: number; @@ -580,7 +600,7 @@ async function execSetupCommandStreamed(options: { cwd: options.cwd, }); - const shellInvocation = buildStringCommandShellInvocation({ command: options.command }); + const shellInvocation = lifecycleCommandInvocation(options.command, options.wrap); const child = spawnProcess(shellInvocation.shell, shellInvocation.args, { cwd: options.cwd, env: options.env, @@ -719,23 +739,20 @@ export async function runWorktreeSetupCommands(options: { })); const results: WorktreeSetupCommandResult[] = []; - for (const [index, configured] of setupCommands.entries()) { + for (const [index, cmd] of setupCommands.entries()) { const prepared = await prepareLifecycleCommand( options.prepareCommand, - { command: configured, env: { ...runtimeEnv } }, + { command: cmd, env: { ...runtimeEnv } }, (message) => - new WorktreeSetupError( - `Worktree setup command refused: ${configured}\n${message}`, - results, - ), + new WorktreeSetupError(`Worktree setup command refused: ${cmd}\n${message}`, results), ); - const cmd = prepared.command; const setupEnv = createStringCommandShellEnv( createExternalProcessEnv(process.env, prepared.env), ); const result = options.onEvent ? await execSetupCommandStreamed({ command: cmd, + wrap: prepared.wrap, cwd: options.worktreePath, env: setupEnv, index: index + 1, @@ -746,6 +763,7 @@ export async function runWorktreeSetupCommands(options: { : await execSetupCommand(cmd, { cwd: options.worktreePath, env: setupEnv, + wrap: prepared.wrap, }); results.push(result); @@ -849,19 +867,16 @@ export async function runWorktreeTeardownCommands(options: { const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd); const deadline = AbortSignal.timeout(timeoutMs); const results: WorktreeTeardownCommandResult[] = []; - for (const [index, configured] of teardownCommands.entries()) { + for (const [index, cmd] of teardownCommands.entries()) { const prepared = await prepareLifecycleCommand( options.prepareCommand, - { command: configured, env: { ...runtimeEnv } }, + { command: cmd, env: { ...runtimeEnv } }, (message) => - new WorktreeTeardownError( - `Worktree teardown command refused: ${configured}\n${message}`, - results, - ), + new WorktreeTeardownError(`Worktree teardown command refused: ${cmd}\n${message}`, results), ); - const cmd = prepared.command; const result = await execSetupCommandStreamed({ command: cmd, + wrap: prepared.wrap, cwd: teardownCwd, env: createStringCommandShellEnv(createExternalProcessEnv(process.env, prepared.env)), index: index + 1, diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md index 905b4e159d..be7c3f5031 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -49,24 +49,24 @@ Paseo only sees the returned promise, so detached work gets no error reporting a ## Hooks -| Hook | Waits | Payload | Handler may change | -| ------------------------- | ----- | ----------------------------------------- | ---------------------------------------------------------------------- | -| `workspace.create.before` | yes | `{ request }` | Entire create request | -| `workspace.create.after` | no | `{ workspace }` | | -| `workspace.archive.after` | no | `{ workspace }` | | -| `worktree.create.before` | yes | `{ request }` | Creation options and destination | -| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | +| Hook | Waits | Payload | Handler may change | +| ------------------------- | ----- | ------------------------------------------------------ | ---------------------------------------------------------------------- | +| `workspace.create.before` | yes | `{ request }` | Entire create request | +| `workspace.create.after` | no | `{ workspace }` | | +| `workspace.archive.after` | no | `{ workspace }` | | +| `worktree.create.before` | yes | `{ request }` | Creation options and destination | +| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | | `agent.create.before` | yes | `{ request: { config, env?, metadata, workspaceId } }` | Saved config except `cwd`; `env`; `metadata` | -| `agent.create.after` | no | `{ agent }` | | -| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `appendSystemPrompt`, `tools`, `mcpServers`, `wrap` | -| `agent.close.after` | no | `{ agent }` | | -| `agent.archive.after` | no | `{ agent, archivedAt }` | | -| `agent.turn.before` | no | `{ agent, turnId }` | | -| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | -| `agent.permission.before` | no | `{ agent, request }` | | -| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | -| `terminal.create.before` | yes | `{ request }` | `command`, `args`, `env`; throw to refuse | -| `command.run.before` | yes | `{ request }` | `command`, `env`; throw to refuse | +| `agent.create.after` | no | `{ agent }` | | +| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `appendSystemPrompt`, `tools`, `mcpServers`, `wrap` | +| `agent.close.after` | no | `{ agent }` | | +| `agent.archive.after` | no | `{ agent, archivedAt }` | | +| `agent.turn.before` | no | `{ agent, turnId }` | | +| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | no | `{ agent, request }` | | +| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | +| `terminal.create.before` | yes | `{ request }` | `env`, `wrap`; throw to refuse | +| `command.run.before` | yes | `{ request }` | `env`, `wrap`; throw to refuse | ## Shared payloads @@ -126,6 +126,23 @@ await paseo.workspaces.ref(workspaceId).setMetadata({ "linear.issue": { id: "ENG Metadata survives a daemon restart. Every hook payload carries it: `workspace.create.before` and `agent.create.before` receive the metadata the caller sent, and the `after` hooks and `agent.open.before` receive what is stored. Against a host that predates metadata, these calls throw "Update the host to use metadata." +## Launch wraps {#launch-wraps} + +`agent.open.before`, `terminal.create.before`, and `command.run.before` can return `wrap: [executable, ...args]`, a `PluginLaunchWrap`. Paseo then starts the process as `[...wrap, command, ...args]`, for example under a sandbox: + +```ts +import type { PluginLaunchWrap } from "@getpaseo/plugin/server"; + +const sandbox: PluginLaunchWrap = ["/usr/local/bin/sandbox-run", "--profile", "agent"]; +``` + +- The executable must be an absolute path on the daemon host. Paseo runs it without a shell, except Windows `.cmd` and `.bat` launchers, which go through cmd.exe. Each element stays one argument. +- The first hook that returns a wrap selects it. A later hook, in the same plugin or a later one, may omit `wrap` or return the same value. A different value fails the operation. +- A wrap is never saved. Every launch asks the hooks again. +- A host that predates `wrap` rejects the field, so the operation fails instead of running unwrapped. + +Each hook section below lists what its wrap covers. + ## workspace.create.before Receives `{ request }` with `source`, optional `title`, optional `metadata`, and `firstAgentContext`. You may replace the entire explicit create request; a throw, invalid result, or timeout fails creation. Existing workspaces and directory lookup/import are unaffected. @@ -234,16 +251,12 @@ Paseo waits for this hook before it starts a terminal in a workspace: - terminals agents open with Paseo tools - the terminals `paseo.json` scripts, services, and worktree terminals run in -Receives `{ request }`; return a replacement request or `undefined`. Throwing refuses the terminal, and whoever asked for it gets `Plugin terminal.create.before failed: …`. +Receives `{ request }`; return a replacement request or `undefined`. Only `env` and `wrap` may change. Throwing refuses the terminal, and whoever asked for it gets `Plugin terminal.create.before failed: …`. ```ts server.addHook("terminal.create.before", async ({ request }) => { if (!sandboxed.has(request.workspaceId)) return; - return { - ...request, - command: "/usr/local/bin/sandbox-run", - args: request.command ? [request.command, ...request.args] : [], - }; + return { ...request, wrap: ["/usr/local/bin/sandbox-run", "--profile", "terminal"] }; }); ``` @@ -254,30 +267,31 @@ server.addHook("terminal.create.before", async ({ request }) => { | `source` | Read-only. `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a `paseo.json` worktree terminal. `client`: the app, CLI, SDK, or a plugin | | `name` | Read-only; the tab name, or null | | `input` | Read-only. For `script` and `worktree`, the command Paseo types into the shell once it starts; otherwise null | -| `command`, `args` | The program and its arguments. Without `command`, Paseo starts the default shell | +| `command`, `args` | Read-only; the program and its arguments. `command` is null for the default shell | | `env` | Variables Paseo adds to the terminal's environment | +| `wrap` | Optional [launch wrap](#launch-wraps). Paseo starts `[...wrap, command, ...args]`; with no `command`, it puts the default shell after the wrap | -Scripts, services, and worktree terminals start the default shell and then type their command into it, so a hook that wraps the shell also wraps what they run. A terminal that survives a daemon restart is adopted, not created again, and doesn't run the hook again. A plugin that creates a terminal from inside this hook runs the hook for that terminal too. +Scripts, services, and worktree terminals start the default shell and then type their command into it, so a wrap on the shell also covers what they run. A wrapped shell starts without Paseo's shell integration, so a wrapped `paseo.json` script does not report when its command finishes. A terminal that survives a daemon restart is adopted, not created again, and doesn't run the hook again. A plugin that creates a terminal from inside this hook runs the hook for that terminal too. ## command.run.before {#commandrunbefore} -Paseo waits for this hook before each `paseo.json` worktree `setup` and `teardown` command. Receives `{ request }`; return a replacement request or `undefined`. Throwing refuses the command: setup stops and reports the plugin's error, and teardown stops and keeps the worktree directory, as a failing command does. +Paseo waits for this hook before each `paseo.json` worktree `setup` and `teardown` command. Receives `{ request }`; return a replacement request or `undefined`. Only `env` and `wrap` may change. Throwing refuses the command: setup stops and reports the plugin's error, and teardown stops and keeps the worktree directory, as a failing command does. ```ts server.addHook("command.run.before", async ({ request }) => ({ ...request, - command: 'sandbox-run sh -c "$SANDBOXED_COMMAND"', - env: { ...request.env, SANDBOXED_COMMAND: request.command }, + wrap: ["/usr/local/bin/sandbox-run", "--profile", request.purpose], })); ``` -| Request field | Meaning | -| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| `workspaceId` | Read-only; the workspace, or null when a worktree is archived by path and no workspace record remains | -| `cwd` | Read-only; where the command runs | -| `purpose` | Read-only; `setup` or `teardown` | -| `command` | A shell command: Paseo runs it with `bash -c` on macOS and Linux, and with PowerShell or `cmd.exe` on Windows | -| `env` | Variables Paseo adds to the daemon's environment: `PASEO_SOURCE_CHECKOUT_PATH`, `PASEO_WORKTREE_PATH`, `PASEO_BRANCH_NAME`, and the rest | +| Request field | Meaning | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | Read-only; the workspace, or null when a worktree is archived by path and no workspace record remains | +| `cwd` | Read-only; where the command runs | +| `purpose` | Read-only; `setup` or `teardown` | +| `command` | Read-only; the command as written in `paseo.json`. Paseo runs it with `bash -c` on macOS and Linux, and with PowerShell or `cmd.exe` on Windows | +| `env` | Variables Paseo adds to the daemon's environment: `PASEO_SOURCE_CHECKOUT_PATH`, `PASEO_WORKTREE_PATH`, `PASEO_BRANCH_NAME`, and the rest | +| `wrap` | Optional [launch wrap](#launch-wraps). Paseo starts the shell behind it: `[...wrap, "bash", "-c", command]` on macOS and Linux | Setup starts after the workspace is registered and `workspace.create.after` is emitted, and runs alongside the first agent. When setup runs again, such as from **Run setup** on a worktree whose setup was blocked, each command runs the hook again. Teardown runs when the last workspace on a worktree is archived, before Paseo removes the directory. @@ -375,23 +389,23 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { } ``` -| Field | Values | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| `workspaceId` | String or `null` | -| `title` | Read-only string or `null`; creation title on create, stored title on resume. | -| `background` | Read-only `true` for a [background agent](#background-agents). Fixed at creation. | -| `labels` | Read-only string map; creation labels on create, stored labels on resume. | -| `metadata` | Read-only JSON map; the [metadata](#metadata) stored on the agent. | -| `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | -| `mcpServers` | Editable launch-only server map, local to this plugin. See [Inject MCP servers](#inject-mcp-servers). | -| `reason` | `create`, `resume`, `refresh`, `import` | -| `purpose` | `interactive`, `history` | -| `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | -| `wrap` | Optional `[executable, ...args]` to start the harness behind. See [Run the harness behind a launch wrap](#run-the-harness-behind-a-launch-wrap). | +| Field | Values | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | String or `null` | +| `title` | Read-only string or `null`; creation title on create, stored title on resume. | +| `background` | Read-only `true` for a [background agent](#background-agents). Fixed at creation. | +| `labels` | Read-only string map; creation labels on create, stored labels on resume. | +| `metadata` | Read-only JSON map; the [metadata](#metadata) stored on the agent. | +| `tools` | Editable `AgentToolDefinition[]`, local to this plugin. See [Attach tools to agents](#attach-tools-to-agents). | +| `mcpServers` | Editable launch-only server map, local to this plugin. See [Inject MCP servers](#inject-mcp-servers). | +| `reason` | `create`, `resume`, `refresh`, `import` | +| `purpose` | `interactive`, `history` | +| `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. | +| `wrap` | Optional [launch wrap](#launch-wraps) to start the harness behind. See [Run the harness behind a launch wrap](#run-the-harness-behind-a-launch-wrap). | ### Run the harness behind a launch wrap -Return `wrap` to start the provider's harness as `[...wrap, command, ...args]`, for example under a sandbox: +Return a [launch wrap](#launch-wraps) to start the provider's harness as `[...wrap, command, ...args]`: ```ts server.addHook("agent.open.before", async ({ request }) => ({ @@ -400,10 +414,8 @@ server.addHook("agent.open.before", async ({ request }) => ({ })); ``` -- The executable must be an absolute path. Paseo runs it without a shell, except Windows script launchers, which go through cmd.exe like any provider launcher. Each element stays one argument. -- Only a provider whose provider snapshot entry has `launchWrap: true` applies a wrap. Read it with `paseo.providers.snapshot()` in `agent.create.before` and choose a provider there. A wrap for any other provider fails the open; it is never dropped. A host without wrap support rejects the field and fails the open too. -- A later hook may omit `wrap` or return the same value. A different value fails the open. -- History opens keep the wrap. It is not saved on the agent; every open asks the hooks again. +- Only a provider whose provider snapshot entry has `launchWrap: true` applies a wrap: Codex and command-based ACP providers such as Antigravity. Read it with `paseo.providers.snapshot()` in `agent.create.before` and choose a provider there. A wrap for any other provider fails the open; it is never dropped. +- History opens keep the wrap. - The wrap covers the session's harness process only. Paseo's host terminal tools, provider availability and catalog probes, and draft discovery run outside it. ### Append instructions on every session opening @@ -801,13 +813,13 @@ replaces that scope's prior value. ## Complete examples -| Plugin | Includes | -| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | +| Plugin | Includes | +| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent, workspace, worktree, terminal, and command hooks; JSON logs with environment values redacted | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | -| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | Worktree manager (`create`, `remove`, `restore`) and agent activity markers | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | +| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | Worktree manager (`create`, `remove`, `restore`) and agent activity markers | Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`. diff --git a/public-docs/plugins/hooks.zh-CN.md b/public-docs/plugins/hooks.zh-CN.md index 07a04cb1cd..e2b56018b3 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -47,24 +47,24 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 ## 钩子一览 {#hooks} -| 钩子 | 等待 | 载荷 | 可修改 | -| ------------------------- | ---- | ----------------------------------------- | ----------------------------------------------------------------------- | -| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | -| `workspace.create.after` | 否 | `{ workspace }` | | -| `workspace.archive.after` | 否 | `{ workspace }` | | -| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | -| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | +| 钩子 | 等待 | 载荷 | 可修改 | +| ------------------------- | ---- | ------------------------------------------------------ | ----------------------------------------------------------------------- | +| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | +| `workspace.create.after` | 否 | `{ workspace }` | | +| `workspace.archive.after` | 否 | `{ workspace }` | | +| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | +| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | | `agent.create.before` | 是 | `{ request: { config, env?, metadata, workspaceId } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | -| `agent.create.after` | 否 | `{ agent }` | | -| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`appendSystemPrompt`、`tools`、`mcpServers`、`wrap` | -| `agent.close.after` | 否 | `{ agent }` | | -| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | -| `agent.turn.before` | 否 | `{ agent, turnId }` | | -| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | -| `agent.permission.before` | 否 | `{ agent, request }` | | -| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | -| `terminal.create.before` | 是 | `{ request }` | `command`、`args`、`env`;抛出错误则拒绝 | -| `command.run.before` | 是 | `{ request }` | `command`、`env`;抛出错误则拒绝 | +| `agent.create.after` | 否 | `{ agent }` | | +| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`appendSystemPrompt`、`tools`、`mcpServers`、`wrap` | +| `agent.close.after` | 否 | `{ agent }` | | +| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | +| `agent.turn.before` | 否 | `{ agent, turnId }` | | +| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | 否 | `{ agent, request }` | | +| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | +| `terminal.create.before` | 是 | `{ request }` | `env`、`wrap`;抛出错误则拒绝 | +| `command.run.before` | 是 | `{ request }` | `env`、`wrap`;抛出错误则拒绝 | ## 共享载荷 {#shared-payloads} @@ -124,6 +124,23 @@ await paseo.workspaces.ref(workspaceId).setMetadata({ "linear.issue": { id: "ENG 元数据在 daemon 重启后仍然保留。所有钩子载荷都带有元数据:`workspace.create.before` 和 `agent.create.before` 收到调用方发送的元数据,`after` 钩子和 `agent.open.before` 收到已保存的元数据。主机版本过旧时,这些调用会抛出 “Update the host to use metadata.”。 +## 启动包装 {#launch-wraps} + +`agent.open.before`、`terminal.create.before` 和 `command.run.before` 可以返回 `wrap: [executable, ...args]`,即 `PluginLaunchWrap`。Paseo 随后以 `[...wrap, command, ...args]` 启动进程,例如在沙盒中运行: + +```ts +import type { PluginLaunchWrap } from "@getpaseo/plugin/server"; + +const sandbox: PluginLaunchWrap = ["/usr/local/bin/sandbox-run", "--profile", "agent"]; +``` + +- 可执行文件必须是 daemon 主机上的绝对路径。Paseo 不经过 shell 运行它;Windows 的 `.cmd` 和 `.bat` 启动器例外,它们通过 cmd.exe 运行。每个元素保持为一个参数。 +- 第一个返回包装的钩子选定包装。后面的钩子,无论属于同一插件还是之后的插件,可以省略 `wrap` 或返回相同的值。返回不同的值会让操作失败。 +- 包装不会被保存。每次启动都会重新询问钩子。 +- 不支持 `wrap` 的旧主机会拒绝该字段,操作失败,而不是不加包装地运行。 + +下面各钩子的章节说明其包装覆盖的范围。 + ## workspace.create.before {#workspacecreatebefore} 收到 `{ request }`,其中包含 `source`、可选的 `title`、可选的 `metadata` 和 `firstAgentContext`。可替换整个显式创建请求;抛出错误、无效返回或超时会让创建失败。已有工作区和目录查找、导入不受影响。 @@ -231,16 +248,12 @@ Paseo 在工作区中启动终端之前等待此钩子: - Agent 通过 Paseo 工具打开的终端 - 运行 `paseo.json` 脚本、服务和 worktree 终端的终端 -钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。抛出错误会拒绝创建终端,请求方收到 `Plugin terminal.create.before failed: …`。 +钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。只能修改 `env` 和 `wrap`。抛出错误会拒绝创建终端,请求方收到 `Plugin terminal.create.before failed: …`。 ```ts server.addHook("terminal.create.before", async ({ request }) => { if (!sandboxed.has(request.workspaceId)) return; - return { - ...request, - command: "/usr/local/bin/sandbox-run", - args: request.command ? [request.command, ...request.args] : [], - }; + return { ...request, wrap: ["/usr/local/bin/sandbox-run", "--profile", "terminal"] }; }); ``` @@ -251,30 +264,31 @@ server.addHook("terminal.create.before", async ({ request }) => { | `source` | 只读。`agent`:Agent 的 Paseo 工具。`script`:`paseo.json` 脚本或服务。`worktree`:`paseo.json` worktree 终端。`client`:应用、CLI、SDK 或插件 | | `name` | 只读,标签页名称,没有时为 null | | `input` | 只读。对于 `script` 和 `worktree`,是 shell 启动后 Paseo 输入的命令;其他情况为 null | -| `command`、`args` | 要运行的程序及其参数。没有 `command` 时,Paseo 启动默认 shell | +| `command`、`args` | 只读,要运行的程序及其参数。启动默认 shell 时 `command` 为 null | | `env` | Paseo 添加到终端环境中的变量 | +| `wrap` | 可选的[启动包装](#launch-wraps)。Paseo 启动 `[...wrap, command, ...args]`;没有 `command` 时,把默认 shell 放在包装之后 | -脚本、服务和 worktree 终端先启动默认 shell,再向其中输入命令,所以包装 shell 的钩子也会包装它们运行的命令。daemon 重启后仍在运行的终端会被接管,不会重新创建,也不会再次触发此钩子。插件在此钩子中创建终端时,该终端同样会触发此钩子。 +脚本、服务和 worktree 终端先启动默认 shell,再向其中输入命令,所以 shell 的包装也覆盖它们运行的命令。被包装的 shell 启动时没有 Paseo 的 shell 集成,所以被包装的 `paseo.json` 脚本不会报告其命令何时结束。daemon 重启后仍在运行的终端会被接管,不会重新创建,也不会再次触发此钩子。插件在此钩子中创建终端时,该终端同样会触发此钩子。 ## command.run.before {#commandrunbefore} -Paseo 在运行每条 `paseo.json` worktree `setup` 和 `teardown` 命令之前等待此钩子。钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。抛出错误会拒绝该命令:setup 停止并报告插件的错误,teardown 停止并保留 worktree 目录,与命令失败时相同。 +Paseo 在运行每条 `paseo.json` worktree `setup` 和 `teardown` 命令之前等待此钩子。钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。只能修改 `env` 和 `wrap`。抛出错误会拒绝该命令:setup 停止并报告插件的错误,teardown 停止并保留 worktree 目录,与命令失败时相同。 ```ts server.addHook("command.run.before", async ({ request }) => ({ ...request, - command: 'sandbox-run sh -c "$SANDBOXED_COMMAND"', - env: { ...request.env, SANDBOXED_COMMAND: request.command }, + wrap: ["/usr/local/bin/sandbox-run", "--profile", request.purpose], })); ``` -| 请求字段 | 含义 | -| ------------- | --------------------------------------------------------------------------------------------------------------- | -| `workspaceId` | 只读,所属工作区;按路径归档 worktree 且没有工作区记录时为 null | -| `cwd` | 只读,命令的运行目录 | -| `purpose` | 只读,`setup` 或 `teardown` | -| `command` | shell 命令:在 macOS 和 Linux 上用 `bash -c` 运行,在 Windows 上用 PowerShell 或 `cmd.exe` 运行 | -| `env` | Paseo 在 daemon 环境之上添加的变量:`PASEO_SOURCE_CHECKOUT_PATH`、`PASEO_WORKTREE_PATH`、`PASEO_BRANCH_NAME` 等 | +| 请求字段 | 含义 | +| ------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 只读,所属工作区;按路径归档 worktree 且没有工作区记录时为 null | +| `cwd` | 只读,命令的运行目录 | +| `purpose` | 只读,`setup` 或 `teardown` | +| `command` | 只读,`paseo.json` 中写的命令:在 macOS 和 Linux 上用 `bash -c` 运行,在 Windows 上用 PowerShell 或 `cmd.exe` 运行 | +| `env` | Paseo 在 daemon 环境之上添加的变量:`PASEO_SOURCE_CHECKOUT_PATH`、`PASEO_WORKTREE_PATH`、`PASEO_BRANCH_NAME` 等 | +| `wrap` | 可选的[启动包装](#launch-wraps)。Paseo 在包装之后启动 shell:在 macOS 和 Linux 上是 `[...wrap, "bash", "-c", command]` | setup 在工作区注册并发出 `workspace.create.after` 之后开始,与第一个 Agent 同时运行。setup 再次运行时,例如在 setup 被阻止的 worktree 上点击 **运行设置**,每条命令都会再次触发此钩子。teardown 在 worktree 上最后一个工作区归档时运行,在 Paseo 删除目录之前。 @@ -371,23 +385,23 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => { } ``` -| 字段 | 取值 | -| ------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `workspaceId` | 字符串或 `null` | -| `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | -| `background` | 只读;[后台 Agent](#background-agents) 为 `true`。在创建时确定。 | -| `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | -| `metadata` | 只读的 JSON 映射;Agent 上已保存的[元数据](#metadata)。 | -| `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | -| `mcpServers` | 可编辑的服务器映射,仅用于启动且仅包含本插件的条目。参阅[注入 MCP 服务器](#inject-mcp-servers)。 | -| `reason` | `create`、`resume`、`refresh`、`import` | -| `purpose` | `interactive`、`history` | -| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | -| `wrap` | 可选的 `[executable, ...args]`,用它启动 harness。参阅[通过启动包装运行 harness](#run-the-harness-behind-a-launch-wrap)。 | +| 字段 | 取值 | +| ------------- | -------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 字符串或 `null` | +| `title` | 只读字符串或 `null`;创建时使用创建请求的标题,恢复时使用已保存的标题。 | +| `background` | 只读;[后台 Agent](#background-agents) 为 `true`。在创建时确定。 | +| `labels` | 只读的字符串映射;创建时使用创建请求的标签,恢复时使用已保存的标签。 | +| `metadata` | 只读的 JSON 映射;Agent 上已保存的[元数据](#metadata)。 | +| `tools` | 可编辑的 `AgentToolDefinition[]`,仅包含此插件的工具。参阅[为 Agent 附加工具](#attach-tools-to-agents)。 | +| `mcpServers` | 可编辑的服务器映射,仅用于启动且仅包含本插件的条目。参阅[注入 MCP 服务器](#inject-mcp-servers)。 | +| `reason` | `create`、`resume`、`refresh`、`import` | +| `purpose` | `interactive`、`history` | +| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 | +| `wrap` | 可选的[启动包装](#launch-wraps),用它启动 harness。参阅[通过启动包装运行 harness](#run-the-harness-behind-a-launch-wrap)。 | ### 通过启动包装运行 harness {#run-the-harness-behind-a-launch-wrap} -返回 `wrap`,让 Provider 的 harness 以 `[...wrap, command, ...args]` 启动,例如在沙盒中运行: +返回[启动包装](#launch-wraps),让 Provider 的 harness 以 `[...wrap, command, ...args]` 启动: ```ts server.addHook("agent.open.before", async ({ request }) => ({ @@ -396,10 +410,8 @@ server.addHook("agent.open.before", async ({ request }) => ({ })); ``` -- 可执行文件必须是绝对路径。Paseo 不经过 shell 运行它;Windows 脚本启动器例外,它和其他 Provider 启动器一样通过 cmd.exe 运行。每个元素保持为一个参数。 -- 只有 Provider 快照条目中 `launchWrap: true` 的 Provider 才会应用包装。在 `agent.create.before` 中用 `paseo.providers.snapshot()` 读取它,并在那里选择 Provider。为其他 Provider 返回包装会让打开失败,包装绝不会被丢弃。不支持包装的主机会拒绝该字段,同样让打开失败。 -- 后面的钩子可以省略 `wrap` 或返回相同的值。返回不同的值会让打开失败。 -- 读取历史的打开也保留包装。包装不会保存在 Agent 上,每次打开都会重新询问钩子。 +- 只有 Provider 快照条目中 `launchWrap: true` 的 Provider 才会应用包装:Codex,以及 Antigravity 等基于命令的 ACP Provider。在 `agent.create.before` 中用 `paseo.providers.snapshot()` 读取它,并在那里选择 Provider。为其他 Provider 返回包装会让打开失败,包装绝不会被丢弃。 +- 读取历史的打开也保留包装。 - 包装只覆盖会话的 harness 进程。Paseo 的主机终端工具、Provider 可用性和目录探测以及草稿发现都在包装之外运行。 ### 在每次打开会话时追加指令 {#append-instructions-on-every-session-opening} @@ -754,13 +766,13 @@ Creation request ## 完整示例 {#complete-examples} -| 插件 | 包含 | -| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | +| 插件 | 包含 | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区、worktree、终端和命令钩子;隐去环境变量值的 JSON 日志 | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | -| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | worktree 管理器(`create`、`remove`、`restore`)与 Agent 活动标记 | +| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree | +| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 | +| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 | +| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | worktree 管理器(`create`、`remove`、`restore`)与 Agent 活动标记 | 用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。