diff --git a/docs/plugins.md b/docs/plugins.md index 61f21cd61c..a30f5e01b2 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -471,6 +471,8 @@ Workspace records decide ownership, including explicit non-ownership after recov ownership checks prefer the marker-verified worktree root over the legacy path shape: a plugin can place a worktree several directories below the default worktrees root. +`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. + 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 8b8cae6630..01b6f1af7c 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -427,6 +427,27 @@ describe("lifecycle hook SDK types", () => { const { metadata, ...withoutMetadata } = request; return withoutMetadata; }); + server.addHook("agent.create.before", async ({ request }) => { + const workspace: string | null = request.workspaceId; + // @ts-expect-error The agent's workspace is read-only. + request.workspaceId = "wks_other"; + }); + server.addHook("terminal.create.before", async ({ request }) => { + const source: "client" | "agent" | "script" | "worktree" = request.source; + const input: string | null = request.input; + // @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" } }; + }); + 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 }; + }); 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 4ff70ae74d..8897c0ce4a 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -23,6 +23,8 @@ export type { PluginHookWorkspace, PluginHookWorktree, PluginWorktreeCreateRequest, + PluginTerminalCreateRequest, + PluginCommandRunRequest, PluginHookAgent, PluginSessionOpenRequest, PluginTurnOutcome, diff --git a/packages/plugin/src/server/lifecycle.ts b/packages/plugin/src/server/lifecycle.ts index f1ee1a9790..650c0745d8 100644 --- a/packages/plugin/src/server/lifecycle.ts +++ b/packages/plugin/src/server/lifecycle.ts @@ -63,6 +63,36 @@ 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. + */ +export interface PluginTerminalCreateRequest { + readonly workspaceId: string; + readonly cwd: string; + /** + * `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a + * `paseo.json` worktree terminal. `client`: everything else (the app, CLI, SDK, plugins). + */ + readonly source: "client" | "agent" | "script" | "worktree"; + readonly name: string | null; + readonly input: string | null; + command?: string; + args: string[]; + env: Record; +} + +/** A `paseo.json` worktree setup or teardown command Paseo is about to run. */ +export interface PluginCommandRunRequest { + /** Null when a worktree is archived by path and no workspace record remains. */ + readonly workspaceId: string | null; + readonly cwd: string; + readonly purpose: "setup" | "teardown"; + /** A shell command: Paseo runs it with `bash -c`, or PowerShell or `cmd.exe` on Windows. */ + command: string; + env: Record; +} + export interface PluginHookAgent { id: string; workspaceId: string | null; @@ -131,9 +161,13 @@ export interface PluginHookRequests { env?: Record; /** Stored on the new agent. Always present in the payload; return it changed to change it. */ metadata?: Record; + /** The workspace the agent is created in, which `config.cwd` alone does not identify. */ + readonly workspaceId: string | null; }; "agent.open.before": PluginSessionOpenRequest; "workspace.create.before": Omit; + "terminal.create.before": PluginTerminalCreateRequest; + "command.run.before": PluginCommandRunRequest; } /** What a hook may return. An omitted `metadata` stays as it was. */ @@ -210,6 +244,8 @@ export const pluginHookRegistry = { "agent.turn.after": { waits: false }, "agent.permission.before": { waits: false }, "agent.permission.after": { waits: false }, + "terminal.create.before": { waits: true }, + "command.run.before": { waits: true }, } as const satisfies Record; // COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30 diff --git a/packages/server/src/server/agent/agent-manager.ts b/packages/server/src/server/agent/agent-manager.ts index 81d25be675..dca228d846 100644 --- a/packages/server/src/server/agent/agent-manager.ts +++ b/packages/server/src/server/agent/agent-manager.ts @@ -1535,6 +1535,7 @@ export class AgentManager { config: sent, env: options.env, metadata: options.metadata ?? {}, + workspaceId: options.workspaceId ?? null, }); // COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. A plugin written // against the previous SDK edits `config.featureValues`. diff --git a/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts b/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts index 2cbf71313b..10db1b8780 100644 --- a/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts +++ b/packages/server/src/server/agent/create-agent-lifecycle-dispatch.ts @@ -1,3 +1,4 @@ +import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import type { CreatePaseoWorktreeInput } from "../paseo-worktree-service.js"; import { randomUUID } from "node:crypto"; import type pino from "pino"; @@ -37,6 +38,7 @@ interface CreateAgentLifecycleDispatchDependencies { clearWorkspaceArchiving: (workspaceIds: Iterable) => void; killTerminalsForWorkspace: (workspaceId: string) => Promise; logger: pino.Logger; + lifecycle: Pick | null; } export interface LifecycleRegistration { @@ -182,6 +184,7 @@ export class CreateAgentLifecycleDispatch { await archiveByScope( { + lifecycle: this.dependencies.lifecycle, paseoHome: this.dependencies.paseoHome, paseoWorktreesBaseRoot: this.dependencies.worktreesRoot, github: this.dependencies.github, diff --git a/packages/server/src/server/agent/tools/paseo-tools.ts b/packages/server/src/server/agent/tools/paseo-tools.ts index 1107ad5e9d..a3791e0dfd 100644 --- a/packages/server/src/server/agent/tools/paseo-tools.ts +++ b/packages/server/src/server/agent/tools/paseo-tools.ts @@ -150,6 +150,7 @@ export interface PaseoToolHostDependencies { workspaceScripts?: Pick; markWorkspaceArchiving?: ArchiveDependencies["markWorkspaceArchiving"]; clearWorkspaceArchiving?: ArchiveDependencies["clearWorkspaceArchiving"]; + lifecycle?: ArchiveDependencies["lifecycle"]; createPaseoWorktree?: CreatePaseoWorktreeWorkflowFn; // Mints a fresh directory workspace for a cwd and returns its id. ensureWorkspaceForCreate?: ( @@ -2534,6 +2535,7 @@ function createToolCatalog( const workspaceId = await resolveTerminalWorkspaceId(resolvedCwd); const terminal = await terminalManager.createTerminal({ + origin: { source: "agent" }, cwd: resolvedCwd, workspaceId, ...(name?.trim() ? { name: name.trim() } : {}), @@ -3344,6 +3346,7 @@ function archiveWorktreeDependencies( throw new Error("Workspace archiving clearer is required to archive worktrees"); } return { + lifecycle: options.lifecycle ?? null, paseoHome: options.paseoHome, paseoWorktreesBaseRoot: options.worktreesRoot, github: options.github, diff --git a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts index 7ea7604b3e..ab0d795699 100644 --- a/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts +++ b/packages/server/src/server/auto-archive-on-merge/archive-if-safe.ts @@ -1,3 +1,4 @@ +import type { PluginLifecycle } from "../plugins/lifecycle/index.js"; import type { Logger } from "pino"; import type { AgentManager } from "../agent/agent-manager.js"; @@ -37,6 +38,7 @@ export interface AutoArchiveArchiveOptions { markWorkspaceArchiving: (workspaceIds: Iterable, archivingAt: string) => void; clearWorkspaceArchiving: (workspaceIds: Iterable) => void; emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds: Iterable) => Promise; + lifecycle: Pick | null; } export interface ArchiveIfSafeDependencies { @@ -97,6 +99,7 @@ export async function archiveIfSafe(input: { await deps.archiveByScope( { + lifecycle: options.lifecycle, paseoHome: options.paseoHome, paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot, github: options.github, diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index df4dd21c10..f5191a6edc 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -184,6 +184,7 @@ import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js"; import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js"; import type { TerminalManager } from "../terminal/terminal-manager.js"; import { startWorkerTerminalManager } from "../terminal/worker-terminal-manager.js"; +import { withTerminalCreateHook } from "../terminal/terminal-create-hook.js"; import { applyTerminalAgentHookSetting } from "../terminal/agent-hooks/terminal-agent-hook-setting.js"; import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js"; import { createRelayRuntime, type RelayRuntime } from "./relay-runtime.js"; @@ -721,12 +722,15 @@ export async function createPaseoDaemon( }); let boundListenTarget: ListenTarget | null = null; let workspaceRegistry: FileBackedWorkspaceRegistry | null = null; - const terminalManager = await startWorkerTerminalManager({ - paseoHome: config.paseoHome, - paseoVersion: daemonVersion, - logger, - getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget), - }); + const terminalManager = withTerminalCreateHook( + await startWorkerTerminalManager({ + paseoHome: config.paseoHome, + paseoVersion: daemonVersion, + logger, + getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget), + }), + pluginRuntime, + ); applyTerminalAgentHookSetting({ store: daemonConfigStore, logger }); const serviceProxyPublicBaseUrl = config.serviceProxy?.publicBaseUrl @@ -1214,6 +1218,7 @@ export async function createPaseoDaemon( }); setupAutoArchiveOnMerge({ + lifecycle: pluginRuntime, paseoHome: config.paseoHome, paseoWorktreesBaseRoot: config.worktreesRoot, daemonConfigStore, @@ -1239,6 +1244,7 @@ export async function createPaseoDaemon( ) => { return createPaseoWorktreeWorkflow( { + lifecycle: pluginRuntime, paseoHome: config.paseoHome, worktreesRoot: config.worktreesRoot, createPaseoWorktree: async (workflowInput, workflowOptions) => { @@ -1302,6 +1308,7 @@ export async function createPaseoDaemon( const archiveWorkspaceByIdExternal = (workspaceId: string, requestId: string) => archiveByScope( { + lifecycle: pluginRuntime, paseoHome: config.paseoHome, paseoWorktreesBaseRoot: config.worktreesRoot, github, @@ -1326,6 +1333,7 @@ export async function createPaseoDaemon( { scope: { kind: "workspace", workspaceId }, requestId }, ); const hubAgentLifecycle = new CreateAgentLifecycleDispatch({ + lifecycle: pluginRuntime, paseoHome: config.paseoHome, worktreesRoot: config.worktreesRoot, agentManager, @@ -1424,6 +1432,7 @@ export async function createPaseoDaemon( const archiveScheduleWorkspaceExternal = async (workspaceId: string) => { await archiveByScope( { + lifecycle: pluginRuntime, paseoHome: config.paseoHome, paseoWorktreesBaseRoot: config.worktreesRoot, github, @@ -1558,6 +1567,7 @@ export async function createPaseoDaemon( listActiveWorkspaces: listActiveWorkspacesExternal, archiveWorkspaceRecord: (workspaceId, archivedAt) => archiveWorkspaceRecordExternal(workspaceId, undefined, archivedAt), + lifecycle: pluginRuntime, emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal, workspaceRegistry, projectRegistry, diff --git a/packages/server/src/server/command-run-hook.ts b/packages/server/src/server/command-run-hook.ts new file mode 100644 index 0000000000..2db304fc98 --- /dev/null +++ b/packages/server/src/server/command-run-hook.ts @@ -0,0 +1,14 @@ +import type { PrepareWorktreeLifecycleCommand } from "../utils/worktree.js"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; + +/** Runs plugins' `command.run.before` hooks for each setup or teardown command. */ +export function commandRunHook( + lifecycle: Pick | null, + scope: { workspaceId: string | null; cwd: string; purpose: "setup" | "teardown" }, +): PrepareWorktreeLifecycleCommand | undefined { + if (!lifecycle) return undefined; + return async ({ command, env }) => { + const request = await lifecycle.before("command.run.before", { ...scope, command, env }); + return { command: request.command, env: request.env }; + }; +} diff --git a/packages/server/src/server/plugins/lifecycle.e2e.test.ts b/packages/server/src/server/plugins/lifecycle.e2e.test.ts index d08089ad3d..7eabcdc63a 100644 --- a/packages/server/src/server/plugins/lifecycle.e2e.test.ts +++ b/packages/server/src/server/plugins/lifecycle.e2e.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { expect, onTestFinished, test } from "vitest"; +import { createPaseoClient } from "@getpaseo/client"; import { DaemonClient } from "../test-utils/daemon-client.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; import { resolveDaemonVersion } from "../daemon-version.js"; @@ -523,6 +524,7 @@ test("agent creation hooks change the provider and environment before the sessio acknowledgeClose: true, hooks: ` server.addHook("agent.create.before", async ({ request }) => { + console.log(JSON.stringify({ hook: "agent.create.before", workspaceId: request.workspaceId })); return { ...request, config: { ...request.config, provider: "${PROVIDER_ID}", model: "shutdown-model" }, env: { ...request.env, HOOK_CREATE: "created" } }; }); server.addHook("agent.open.before", async ({ request }) => { @@ -541,9 +543,14 @@ test("agent creation hooks change the provider and environment before the sessio await client.fetchAgents({ subscribe: {} }); await client.patchDaemonConfig({ pluginsEnabled: true }); await client.installDirectoryPlugin(pluginDirectory); + const workspace = await client.createWorkspace({ + source: { kind: "directory", path: directory }, + }); + const workspaceId = workspace.workspace!.id; const agent = await client.createAgent({ provider: "claude", cwd: directory, + workspaceId, title: "Hook test", }); expect(agent.provider).toBe(PROVIDER_ID); @@ -563,6 +570,7 @@ test("agent creation hooks change the provider and environment before the sessio }); }) .toMatchObject([ + { hook: "agent.create.before", workspaceId }, { hook: "agent.open.before", request: { agentId: agent.id, env: { HOOK_CREATE: "created" } }, @@ -584,6 +592,170 @@ test("agent creation hooks change the provider and environment before the sessio } }, 60_000); +test("plugins wrap or refuse terminals and worktree setup and teardown commands", async () => { + const root = await realpath(await mkdtemp(path.join(tmpdir(), "paseo-terminal-hooks-"))); + const repository = path.join(root, "repository"); + const pluginDirectory = path.join(root, "plugin"); + const hookLog = path.join(root, "hooks.jsonl"); + execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" }); + await writeFile( + path.join(repository, "paseo.json"), + JSON.stringify({ + worktree: { + setup: 'echo "setup:$HOOK_MARK" > setup.txt', + teardown: 'echo "teardown:$HOOK_MARK" > "$PASEO_SOURCE_CHECKOUT_PATH/../teardown.txt"', + }, + scripts: { greet: { command: 'echo "script:$HOOK_MARK"' } }, + }), + ); + execFileSync("git", ["add", "paseo.json"], { cwd: repository, stdio: "pipe" }); + execFileSync( + "git", + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + ].concat(["commit", "-m", "initial"]), + { cwd: repository, stdio: "pipe" }, + ); + await mkdir(pluginDirectory); + await writeFile( + path.join(pluginDirectory, "paseo-plugin.json"), + JSON.stringify({ id: "terminal-hooks", requirements: { paseo: ">=0.8.0" } }), + ); + await writeFile( + path.join(pluginDirectory, "index.server.ts"), + ` +import { appendFile } from "node:fs/promises"; +const log = (entry) => appendFile(${JSON.stringify(hookLog)}, JSON.stringify(entry) + "\\n"); +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 }, + }; + }); + server.addHook("command.run.before", async ({ request }) => { + await log({ hook: "command", request }); + return { ...request, env: { ...request.env, HOOK_MARK: request.purpose + "-hooked" } }; + }); + return () => {}; +} +`, + ); + const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" }); + const sdk = createPaseoClient({ url: `ws://127.0.0.1:${daemon.port}/ws` }); + try { + await client.connect(); + await client.fetchAgents({ subscribe: {} }); + await client.patchDaemonConfig({ pluginsEnabled: true }); + expect((await client.installDirectoryPlugin(pluginDirectory)).status).toBe("running"); + await sdk.connect(); + const created = await client.createWorkspace({ + source: { kind: "worktree", cwd: repository, branchName: "hooks", worktreeSlug: "hooks" }, + }); + expect(created.error).toBeNull(); + const workspaceId = created.workspace!.id; + const worktree = created.workspace!.workspaceDirectory; + + // Setup runs after creation, with the hook's environment. + await expect + .poll(() => readFile(path.join(worktree, "setup.txt"), "utf8").catch(() => ""), { + timeout: 30_000, + }) + .toBe("setup:setup-hooked\n"); + + const wrapped = await sdk.terminals.create({ workspaceId, name: "Wrapped" }); + await expect + .poll(async () => (await wrapped.capture({ stripAnsi: true })).lines.join("\n")) + .toContain(`wrapped:client:${workspaceId}`); + + 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. + await client.startWorkspaceScript(workspaceId, "greet"); + await expect + .poll(async () => { + const script = (await sdk.terminals.list({ workspaceId })).entries.find( + (entry) => entry.name === "greet", + ); + if (!script) return ""; + return (await sdk.terminals.ref(script.id).capture({ stripAnsi: true })).lines.join("\n"); + }) + .toContain("script:hooked"); + + await client.archiveWorkspace(workspaceId); + await expect + .poll(() => readFile(path.join(root, "teardown.txt"), "utf8").catch(() => ""), { + timeout: 30_000, + }) + .toBe("teardown:teardown-hooked\n"); + + const entries = (await readFile(hookLog, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(entries.filter((entry) => entry.hook === "command")).toEqual([ + { + hook: "command", + request: expect.objectContaining({ + workspaceId, + cwd: worktree, + purpose: "setup", + command: 'echo "setup:$HOOK_MARK" > setup.txt', + }), + }, + { + hook: "command", + request: expect.objectContaining({ workspaceId, cwd: worktree, purpose: "teardown" }), + }, + ]); + expect(entries.filter((entry) => entry.hook === "terminal")).toEqual([ + { + hook: "terminal", + request: { + workspaceId, + cwd: worktree, + source: "client", + name: "Wrapped", + input: null, + args: [], + env: {}, + }, + }, + { + hook: "terminal", + request: expect.objectContaining({ source: "client", name: "Refused" }), + }, + { + hook: "terminal", + request: expect.objectContaining({ + workspaceId, + source: "script", + name: "greet", + input: 'echo "script:$HOOK_MARK"', + }), + }, + ]); + } finally { + await sdk.close(); + await client.close(); + await daemon.close(); + await rm(root, { recursive: true, force: true }); + } +}, 120_000); + test("invalid output from an untyped plugin rejects creation before later callbacks run", async () => { const directory = await mkdtemp(path.join(tmpdir(), "paseo-invalid-hook-")); const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" }); diff --git a/packages/server/src/server/plugins/lifecycle/handlers.test.ts b/packages/server/src/server/plugins/lifecycle/handlers.test.ts index bf7526ba1d..a9110ff0d2 100644 --- a/packages/server/src/server/plugins/lifecycle/handlers.test.ts +++ b/packages/server/src/server/plugins/lifecycle/handlers.test.ts @@ -357,3 +357,58 @@ test("checkout-branch hooks reject a branch-off baseRef", async () => { validateBeforeResult("worktree.create.before", request, { ...request, baseRef: "main" }), ).rejects.toThrow(/baseRef/); }); + +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: {}, + }; + await expect( + validateBeforeResult("terminal.create.before", terminal, { + ...terminal, + command: "/usr/bin/wrapper", + args: ["--workspace", "wks_a"], + env: { WRAPPED: "1" }, + }), + ).resolves.toEqual({ + ...terminal, + command: "/usr/bin/wrapper", + args: ["--workspace", "wks_a"], + env: { WRAPPED: "1" }, + }); + 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"); +}); + +test("agent creation hooks keep the workspace, including from plugins that omit it", async () => { + const request = { + config: { provider: "claude", cwd: "/work/a" }, + workspaceId: "wks_a", + }; + await expect( + validateBeforeResult("agent.create.before", request, { config: request.config }), + ).resolves.toEqual(request); + await expect( + validateBeforeResult("agent.create.before", request, { ...request, workspaceId: "wks_b" }), + ).rejects.toThrow("agent.create.before hooks cannot change the workspace"); +}); diff --git a/packages/server/src/server/plugins/lifecycle/index.ts b/packages/server/src/server/plugins/lifecycle/index.ts index b291bf3723..299ccfce53 100644 --- a/packages/server/src/server/plugins/lifecycle/index.ts +++ b/packages/server/src/server/plugins/lifecycle/index.ts @@ -93,7 +93,10 @@ const beforeSchemas = { config: true, env: true, metadata: true, - }).strict(), + }) + // A plugin built before the field may omit it from its result; it can't change it. + .extend({ workspaceId: z.string().nullable().optional() }) + .strict(), "agent.open.before": z .object({ agentId: z.string(), @@ -117,8 +120,50 @@ const beforeSchemas = { type: true, requestId: true, }).strict(), + "terminal.create.before": z + .object({ + workspaceId: z.string(), + cwd: z.string(), + source: z.enum(["client", "agent", "script", "worktree"]), + name: z.string().nullable(), + input: z.string().nullable(), + command: z.string().min(1).optional(), + args: z.array(z.string()), + env: z.record(z.string(), z.string()), + }) + .strict(), + "command.run.before": z + .object({ + workspaceId: z.string().nullable(), + cwd: z.string(), + purpose: z.enum(["setup", "teardown"]), + command: z.string().min(1), + env: z.record(z.string(), z.string()), + }) + .strict(), }; +// Request fields a hook reads but can't change, with the error a changed one gets. +const readOnlyRequestFields = { + "terminal.create.before": { + fields: ["workspaceId", "cwd", "source", "name", "input"], + message: "terminal.create.before hooks can only change command, args, and env", + }, + "command.run.before": { + fields: ["workspaceId", "cwd", "purpose"], + message: "command.run.before hooks can only change command and env", + }, +} as const; + +function assertReadOnlyFields(name: string, input: unknown, result: unknown): void { + if (!Object.hasOwn(readOnlyRequestFields, name)) return; + const { fields, message } = readOnlyRequestFields[name as keyof typeof readOnlyRequestFields]; + const previous = input as Record; + const next = result as Record; + if (fields.some((field) => !isDeepStrictEqual(previous[field], next[field]))) + throw new Error(message); +} + const sessionOpenLocalResultSchema = beforeSchemas["agent.open.before"].extend({ tools: z.array( z.custom( @@ -258,8 +303,15 @@ export async function validateBeforeResult { return handleWorktreeArchiveRequest( { + lifecycle: this.pluginRuntime ?? null, paseoHome: this.paseoHome, paseoWorktreesBaseRoot: this.worktreesRoot, github: this.github, @@ -7962,6 +7964,7 @@ export class Session { ): Promise { return createWorktreeWorkflow( { + lifecycle: this.pluginRuntime ?? null, paseoHome: this.paseoHome, worktreesRoot: this.worktreesRoot, createPaseoWorktree: (workflowInput, serviceOptions) => @@ -8015,6 +8018,7 @@ export class Session { ): Promise { return handleWorkspaceSetupRunRequestMessage( { + lifecycle: this.pluginRuntime ?? null, getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId), clearAutomationBlock: (workspaceId) => clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId), @@ -8056,6 +8060,7 @@ export class Session { } return archiveByScope( { + lifecycle: this.pluginRuntime ?? null, paseoHome: this.paseoHome, paseoWorktreesBaseRoot: this.worktreesRoot, github: this.github, diff --git a/packages/server/src/server/workspace-archive-service.ts b/packages/server/src/server/workspace-archive-service.ts index 7a71b4682b..75f5b27f3a 100644 --- a/packages/server/src/server/workspace-archive-service.ts +++ b/packages/server/src/server/workspace-archive-service.ts @@ -1,3 +1,5 @@ +import { commandRunHook } from "./command-run-hook.js"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; import { resolve } from "node:path"; import type { Logger } from "pino"; @@ -53,6 +55,8 @@ export interface ArchiveDependencies { stopWorkspaceSetup?: (workspaceId: string) => Promise; assertWorkspaceAutomationAllowed?: (workspaceId: string) => Promise; sessionLogger?: Logger; + /** Plugins' lifecycle, for `command.run.before` on teardown commands. */ + lifecycle: Pick | null; } export interface KillTerminalsForWorkspaceDependencies { @@ -463,6 +467,11 @@ async function maybeRemoveDirectory( worktreePath: backing.path, teardownCwd: teardownTarget.cwd, repoRootPath: backing.mainRepoRoot ?? undefined, + prepareCommand: commandRunHook(dependencies.lifecycle, { + workspaceId: teardownTarget.workspaceId, + cwd: teardownTarget.cwd, + purpose: "teardown", + }), }); } } catch (error) { diff --git a/packages/server/src/server/worktree-bootstrap.ts b/packages/server/src/server/worktree-bootstrap.ts index 1e1ba58f8e..b6caefe805 100644 --- a/packages/server/src/server/worktree-bootstrap.ts +++ b/packages/server/src/server/worktree-bootstrap.ts @@ -327,6 +327,7 @@ export async function runWorktreeAutoTerminals(options: { (await getWorktreeTerminalSpecs(options.workspaceCwd)).map(async (spec) => { try { const terminal = await terminalManager.createTerminal({ + origin: { source: "worktree", input: spec.command }, cwd: options.workspaceCwd, name: spec.name, env: options.runtimeEnv, @@ -488,6 +489,7 @@ async function acquireWorkspaceScriptTerminal(params: { repoRoot: string; workspaceId: string; scriptName: string; + command: string; env: Record | undefined; }): Promise<{ terminal: TerminalSession; reusableTerminal: TerminalSession | null }> { const { @@ -497,6 +499,7 @@ async function acquireWorkspaceScriptTerminal(params: { repoRoot, workspaceId, scriptName, + command, env, } = params; let reusableTerminal: TerminalSession | null = null; @@ -506,6 +509,7 @@ async function acquireWorkspaceScriptTerminal(params: { const terminal = reusableTerminal ?? (await terminalManager.createTerminal({ + origin: { source: "script", input: command }, cwd: repoRoot, workspaceId, name: scriptName, @@ -588,6 +592,7 @@ export async function spawnWorkspaceScript( repoRoot, workspaceId, scriptName, + command: config.command, env, }); diff --git a/packages/server/src/server/worktree-session.ts b/packages/server/src/server/worktree-session.ts index 1cbad931eb..72b6323fbf 100644 --- a/packages/server/src/server/worktree-session.ts +++ b/packages/server/src/server/worktree-session.ts @@ -1,3 +1,5 @@ +import { commandRunHook } from "./command-run-hook.js"; +import type { PluginLifecycle } from "./plugins/lifecycle/index.js"; import type { Logger } from "pino"; import { basename } from "node:path"; import { @@ -63,6 +65,8 @@ interface CreatePaseoWorktreeInBackgroundDependencies { getDaemonTcpHost: (() => string | null) | null; serviceProxyPublicBaseUrl?: string | null; onScriptsChanged: ((workspaceId: string, workspaceDirectory: string) => void) | null; + /** Plugins' lifecycle, for `command.run.before` on setup commands. */ + lifecycle: Pick | null; } interface CreatePaseoWorktreeWorkflowDependencies extends CreatePaseoWorktreeInBackgroundDependencies { @@ -577,6 +581,11 @@ export async function runWorktreeSetupInBackground( applyWorktreeSetupProgressEvent(progressAccumulator, event); emitSetupProgress("running", null); }, + prepareCommand: commandRunHook(dependencies.lifecycle, { + workspaceId, + cwd: workspaceCwd, + purpose: "setup", + }), }); emitSetupProgress("completed", null); } diff --git a/packages/server/src/terminal/terminal-create-hook.ts b/packages/server/src/terminal/terminal-create-hook.ts new file mode 100644 index 0000000000..640e078769 --- /dev/null +++ b/packages/server/src/terminal/terminal-create-hook.ts @@ -0,0 +1,34 @@ +import type { PluginLifecycle } from "../server/plugins/lifecycle/index.js"; +import type { DaemonTerminalManager } from "./worker-terminal-manager.js"; + +/** + * Runs plugins' `terminal.create.before` hooks for every terminal the daemon creates, before the + * worker starts it. Terminals adopted after a daemon restart aren't created again, so the hook + * doesn't run for them. + */ +export function withTerminalCreateHook( + manager: DaemonTerminalManager, + lifecycle: Pick, +): DaemonTerminalManager { + return { + ...manager, + async createTerminal({ origin, ...options }) { + const request = await lifecycle.before("terminal.create.before", { + workspaceId: options.workspaceId, + cwd: options.cwd, + source: origin?.source ?? "client", + name: options.name ?? null, + input: origin?.input ?? null, + ...(options.command ? { command: options.command } : {}), + args: options.args ?? [], + env: options.env ?? {}, + }); + return manager.createTerminal({ + ...options, + command: request.command, + args: request.args, + env: request.env, + }); + }, + }; +} diff --git a/packages/server/src/terminal/terminal-manager.ts b/packages/server/src/terminal/terminal-manager.ts index f8ba1851fa..6d16622460 100644 --- a/packages/server/src/terminal/terminal-manager.ts +++ b/packages/server/src/terminal/terminal-manager.ts @@ -54,6 +54,16 @@ export type TerminalWorkspaceContributionChangedListener = ( event: TerminalWorkspaceContributionChangedEvent, ) => void; +/** + * Who asked for a terminal: an agent's Paseo tool, a `paseo.json` script or service, or a + * `paseo.json` worktree terminal; anything else is a client. `input` is the command Paseo types + * into the shell once it starts. + */ +export interface TerminalOrigin { + source: "client" | "agent" | "script" | "worktree"; + input?: string; +} + export interface TerminalManager { /** * Set when this host's terminals cannot be served at all (a worker from a newer Paseo holds @@ -62,6 +72,8 @@ export interface TerminalManager { getUnavailableError?(): Error | null; getTerminals(cwd: string, options?: { workspaceId?: string }): Promise; createTerminal(options: { + /** Where the terminal comes from, for plugins' `terminal.create.before` hooks. */ + origin?: TerminalOrigin; id?: string; cwd: string; workspaceId: string; diff --git a/packages/server/src/utils/worktree.posix.test.ts b/packages/server/src/utils/worktree.posix.test.ts index 35d59cce3f..2ad5b1bb15 100644 --- a/packages/server/src/utils/worktree.posix.test.ts +++ b/packages/server/src/utils/worktree.posix.test.ts @@ -881,6 +881,41 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => { expect(portValue).toBeGreaterThan(0); }); + it("runs setup commands as a plugin prepares them and stops at a refused one", async () => { + writeFileSync( + join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { setup: ['echo "$HOOK_MARK" > first.log', "echo second > second.log"] }, + }), + ); + const seen: string[] = []; + const setup = runWorktreeSetupCommands({ + worktreePath: repoDir, + branchName: "main", + runtimeEnv: { + PASEO_SOURCE_CHECKOUT_PATH: repoDir, + PASEO_ROOT_PATH: repoDir, + PASEO_WORKTREE_PATH: repoDir, + PASEO_BRANCH_NAME: "main", + PASEO_WORKTREE_PORT: "12345", + }, + prepareCommand: async ({ command, env }) => { + seen.push(`${command} ${env.PASEO_BRANCH_NAME}`); + if (command.startsWith("echo second")) throw new Error("not in this workspace"); + return { command, env: { ...env, HOOK_MARK: "prepared" } }; + }, + }); + + await expect(setup).rejects.toMatchObject({ + name: "WorktreeSetupError", + message: "Worktree setup command refused: echo second > second.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(readFileSync(join(repoDir, "first.log"), "utf8").trim()).toBe("prepared"); + expect(existsSync(join(repoDir, "second.log"))).toBe(false); + }); + it("runs string setup scripts from paseo.json as a single shell command", async () => { const paseoConfig = { worktree: { diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 2fc8bc05db..b11b1558a8 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -134,6 +134,30 @@ export function isServiceScript(config: ScriptConfig): config is ServiceScriptCo return "type" in config && config.type === "service"; } +/** A lifecycle command, and the environment Paseo adds to the daemon's for it. */ +export interface WorktreeLifecycleCommand { + command: string; + env: Record; +} + +/** Lets plugins wrap or refuse a lifecycle command before it runs; see `command.run.before`. */ +export type PrepareWorktreeLifecycleCommand = ( + command: WorktreeLifecycleCommand, +) => Promise; + +async function prepareLifecycleCommand( + prepare: PrepareWorktreeLifecycleCommand | undefined, + command: WorktreeLifecycleCommand, + fail: (message: string) => Error, +): Promise { + if (!prepare) return command; + try { + return await prepare(command); + } catch (error) { + throw fail(error instanceof Error ? error.message : String(error)); + } +} + export class WorktreeSetupError extends Error { readonly results: WorktreeSetupCommandResult[]; @@ -636,6 +660,7 @@ export async function runWorktreeSetupCommands(options: { runtimeEnv?: WorktreeRuntimeEnv; signal?: AbortSignal; onEvent?: (event: WorktreeSetupCommandProgressEvent) => void; + prepareCommand?: PrepareWorktreeLifecycleCommand; }): Promise { // Read paseo.json from the worktree (it will have the same content as the source repo) const setupCommands = await getWorktreeSetupCommands(options.worktreePath); @@ -650,10 +675,22 @@ export async function runWorktreeSetupCommands(options: { branchName: options.branchName, ...(options.repoRootPath ? { repoRootPath: options.repoRootPath } : {}), })); - const setupEnv = createStringCommandShellEnv(createExternalProcessEnv(process.env, runtimeEnv)); const results: WorktreeSetupCommandResult[] = []; - for (const [index, cmd] of setupCommands.entries()) { + for (const [index, configured] of setupCommands.entries()) { + const prepared = await prepareLifecycleCommand( + options.prepareCommand, + { command: configured, env: { ...runtimeEnv } }, + (message) => + new WorktreeSetupError( + `Worktree setup command refused: ${configured}\n${message}`, + results, + ), + ); + const cmd = prepared.command; + const setupEnv = createStringCommandShellEnv( + createExternalProcessEnv(process.env, prepared.env), + ); const result = options.onEvent ? await execSetupCommandStreamed({ command: cmd, @@ -737,6 +774,7 @@ export async function runWorktreeTeardownCommands(options: { teardownCwd?: string; branchName?: string; repoRootPath?: string; + prepareCommand?: PrepareWorktreeLifecycleCommand; }): Promise { const teardownCwd = options.teardownCwd ?? options.worktreePath; if ((await getOwnershipRelativePath(options.worktreePath, teardownCwd)) === null) { @@ -753,25 +791,33 @@ export async function runWorktreeTeardownCommands(options: { options.branchName ?? (await resolveBranchNameForWorktreePath(options.worktreePath)); const worktreePort = await readPaseoWorktreeRuntimePort(options.worktreePath); - const teardownEnv: NodeJS.ProcessEnv = createStringCommandShellEnv( - createExternalProcessEnv(process.env, { - // Source checkout path is the original git repo root (shared across worktrees), not the - // worktree itself. This allows lifecycle scripts to copy or clean resources using paths - // from the source checkout. - PASEO_SOURCE_CHECKOUT_PATH: repoRootPath, - // Backward-compatible alias. - PASEO_ROOT_PATH: repoRootPath, - PASEO_WORKTREE_PATH: options.worktreePath, - PASEO_BRANCH_NAME: branchName, - ...(worktreePort !== null ? { PASEO_WORKTREE_PORT: String(worktreePort) } : {}), - }), - ); + const runtimeEnv: Record = { + // Source checkout path is the original git repo root (shared across worktrees), not the + // worktree itself. This allows lifecycle scripts to copy or clean resources using paths + // from the source checkout. + PASEO_SOURCE_CHECKOUT_PATH: repoRootPath, + // Backward-compatible alias. + PASEO_ROOT_PATH: repoRootPath, + PASEO_WORKTREE_PATH: options.worktreePath, + PASEO_BRANCH_NAME: branchName, + ...(worktreePort !== null ? { PASEO_WORKTREE_PORT: String(worktreePort) } : {}), + }; const results: WorktreeTeardownCommandResult[] = []; - for (const cmd of teardownCommands) { + for (const configured of teardownCommands) { + const prepared = await prepareLifecycleCommand( + options.prepareCommand, + { command: configured, env: { ...runtimeEnv } }, + (message) => + new WorktreeTeardownError( + `Worktree teardown command refused: ${configured}\n${message}`, + results, + ), + ); + const cmd = prepared.command; const result = await execSetupCommand(cmd, { cwd: teardownCwd, - env: teardownEnv, + env: createStringCommandShellEnv(createExternalProcessEnv(process.env, prepared.env)), }); results.push(result); diff --git a/plugin-examples/lifecycle-logger/README.md b/plugin-examples/lifecycle-logger/README.md index 60259d34c7..6c08d5beaf 100644 --- a/plugin-examples/lifecycle-logger/README.md +++ b/plugin-examples/lifecycle-logger/README.md @@ -1,7 +1,8 @@ # Lifecycle logger -Registers agent, workspace, and worktree hooks and logs their data as JSON. It observes agent creation, -session opening, turns, permissions, archive, and workspace creation/archive. Before hooks return +Registers agent, workspace, worktree, terminal, and command hooks and logs their data as JSON. It +observes agent creation, session opening, turns, permissions, archive, workspace creation/archive, +terminal creation, and worktree setup and teardown commands. Before hooks return the request unchanged. Environment values are redacted; prompts and timeline content are logged. Install it on a daemon where plugins are enabled: diff --git a/plugin-examples/lifecycle-logger/index.server.ts b/plugin-examples/lifecycle-logger/index.server.ts index e87be2c2f6..ef7ce3caff 100644 --- a/plugin-examples/lifecycle-logger/index.server.ts +++ b/plugin-examples/lifecycle-logger/index.server.ts @@ -57,5 +57,15 @@ export default function contribute(server: PluginServerContext) { logHook("agent.archive.after", event); }); + server.addHook("terminal.create.before", async ({ request }) => { + logHook("terminal.create.before", { request }); + return request; + }); + + server.addHook("command.run.before", async ({ request }) => { + logHook("command.run.before", { request }); + return request; + }); + return () => {}; } diff --git a/public-docs/plugins/hooks.md b/public-docs/plugins/hooks.md index 29be2ce0de..1428725a83 100644 --- a/public-docs/plugins/hooks.md +++ b/public-docs/plugins/hooks.md @@ -24,7 +24,7 @@ export default function contribute(server: PluginServerContext) { ## Naming and timing -Names follow `subject.operation.position`: the subject, the operation, then `before` or `after`. The name identifies a lifecycle position. Whether Paseo waits is a per-hook property shown in the table below. `workspace` covers every workspace; `worktree` covers only git worktrees. +Names follow `subject.operation.position`: the subject, the operation, then `before` or `after`. The name identifies a lifecycle position. Whether Paseo waits is a per-hook property shown in the table below. `workspace` covers every workspace; `worktree` covers only git worktrees. `terminal` covers every terminal Paseo starts in a workspace; `command` covers worktree setup and teardown commands. - Waiting hooks finish before Paseo continues. Throwing, returning invalid data, or exceeding 30 seconds fails the operation with `Plugin failed: …`. Request-changing hooks receive `{ request }` and may return a complete replacement request or `undefined`. - Notifications receive the event object and return `Promise`. Paseo does not wait; errors are logged against the plugin and the operation continues. `agent.turn.before` and `agent.permission.before` are notifications fired when a turn starts or a permission becomes pending. @@ -49,22 +49,24 @@ Paseo only sees the returned promise, so detached work gets no error reporting a ## Hooks -| Hook | Waits | Payload | Handler may change | -| ------------------------- | ----- | ----------------------------------------- | ---------------------------------------------- | -| `workspace.create.before` | yes | `{ request }` | Entire create request | -| `workspace.create.after` | no | `{ workspace }` | | -| `workspace.archive.after` | no | `{ workspace }` | | -| `worktree.create.before` | yes | `{ request }` | Creation options and destination | -| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | -| `agent.create.before` | yes | `{ request: { config, env?, metadata } }` | Saved config except `cwd`; `env`; `metadata` | -| `agent.create.after` | no | `{ agent }` | | -| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `tools`, `mcpServers` | -| `agent.close.after` | no | `{ agent }` | | -| `agent.archive.after` | no | `{ agent, archivedAt }` | | -| `agent.turn.before` | no | `{ agent, turnId }` | | -| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | -| `agent.permission.before` | no | `{ agent, request }` | | -| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | +| Hook | Waits | Payload | Handler may change | +| ------------------------- | ----- | ------------------------------------------------------ | ---------------------------------------------- | +| `workspace.create.before` | yes | `{ request }` | Entire create request | +| `workspace.create.after` | no | `{ workspace }` | | +| `workspace.archive.after` | no | `{ workspace }` | | +| `worktree.create.before` | yes | `{ request }` | Creation options and destination | +| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation | +| `agent.create.before` | yes | `{ request: { config, env?, metadata, workspaceId } }` | Saved config except `cwd`; `env`; `metadata` | +| `agent.create.after` | no | `{ agent }` | | +| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `tools`, `mcpServers` | +| `agent.close.after` | no | `{ agent }` | | +| `agent.archive.after` | no | `{ agent, archivedAt }` | | +| `agent.turn.before` | no | `{ agent, turnId }` | | +| `agent.turn.after` | no | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | no | `{ agent, request }` | | +| `agent.permission.after` | no | `{ agent, requestId, resolution }` | | +| `terminal.create.before` | yes | `{ request }` | `command`, `args`, `env`; throw to refuse | +| `command.run.before` | yes | `{ request }` | `command`, `env`; throw to refuse | ## Shared payloads @@ -224,9 +226,66 @@ server.addHook("worktree.create.after", async ({ worktree }) => { }); ``` +## terminal.create.before {#terminalcreatebefore} + +Paseo waits for this hook before it starts a terminal in a workspace: + +- **New terminal** and terminal profiles in the app, and terminals created through the CLI, SDK, and plugins +- terminals agents open with Paseo tools +- the terminals `paseo.json` scripts, services, and worktree terminals run in + +Receives `{ request }`; return a replacement request or `undefined`. 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] : [], + }; +}); +``` + +| Request field | Meaning | +| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | Read-only; the terminal's workspace | +| `cwd` | Read-only; where the terminal starts | +| `source` | Read-only. `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a `paseo.json` worktree terminal. `client`: the app, CLI, SDK, or a plugin | +| `name` | Read-only; the tab name, or null | +| `input` | Read-only. For `script` and `worktree`, the command Paseo types into the shell once it starts; otherwise null | +| `command`, `args` | The program and its arguments. Without `command`, Paseo starts the default shell | +| `env` | Variables Paseo adds to the terminal's environment | + +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. + +## 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. + +```ts +server.addHook("command.run.before", async ({ request }) => ({ + ...request, + command: 'sandbox-run sh -c "$SANDBOXED_COMMAND"', + env: { ...request.env, SANDBOXED_COMMAND: request.command }, +})); +``` + +| 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 | + +Setup starts after the workspace is registered and `workspace.create.after` is emitted, and runs alongside the first agent. When setup runs again, such as from **Run setup** on a worktree whose setup was blocked, each command runs the hook again. Teardown runs when the last workspace on a worktree is archived, before Paseo removes the directory. + ## agent.create.before -Receives `{ request: { config, env?, metadata } }`. Config and `metadata` changes are saved and remain after the plugin is disabled or removed; `env` applies to the initial launch and is not saved. You cannot change `config.cwd`. A throw, invalid result, or timeout fails creation. +Receives `{ request: { config, env?, metadata, workspaceId } }`. Config and `metadata` changes are saved and remain after the plugin is disabled or removed; `env` applies to the initial launch and is not saved. You cannot change `config.cwd` or `workspaceId`. A throw, invalid result, or timeout fails creation. + +`workspaceId` is the workspace the agent is created in, or null. Use it rather than `config.cwd` to find the workspace: several workspaces can share a directory, and an agent can be created in one workspace with a directory inside another. **`agent.create.before.config`** uses `AgentSessionConfig`: @@ -681,12 +740,12 @@ replaces that scope's prior value. ## Complete examples -| Plugin | Includes | -| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | -| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent, workspace, and worktree hooks; JSON logs with environment values redacted | -| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection | -| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options | -| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process | +| 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 | 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 af6c66bd7b..c728c53214 100644 --- a/public-docs/plugins/hooks.zh-CN.md +++ b/public-docs/plugins/hooks.zh-CN.md @@ -22,7 +22,7 @@ export default function contribute(server: PluginServerContext) { ## 命名与等待 {#naming-and-timing} -名称遵循 `subject.operation.position`:主体、操作、`before` 或 `after`。名称标识生命周期中的位置;Paseo 是否等待由每个钩子决定,见下表。`workspace` 包括所有工作区,`worktree` 仅包括 git worktree。 +名称遵循 `subject.operation.position`:主体、操作、`before` 或 `after`。名称标识生命周期中的位置;Paseo 是否等待由每个钩子决定,见下表。`workspace` 包括所有工作区,`worktree` 仅包括 git worktree。`terminal` 包括 Paseo 在工作区中启动的所有终端,`command` 包括 worktree 的 setup 和 teardown 命令。 - 等待型钩子结束后 Paseo 才继续。抛出错误、返回无效数据或超过 30 秒会让操作失败,错误包含 `Plugin failed: …`。修改请求的钩子收到 `{ request }`,可以返回完整的替换请求或 `undefined`。 - 通知收到事件对象,返回 `Promise`。Paseo 不等待;错误会记录在插件名下,原操作继续。`agent.turn.before` 和 `agent.permission.before` 分别在轮次开始或权限进入待处理状态时发出通知。 @@ -47,22 +47,24 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没 ## 钩子一览 {#hooks} -| 钩子 | 等待 | 载荷 | 可修改 | -| ------------------------- | ---- | ----------------------------------------- | ------------------------------------------ | -| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | -| `workspace.create.after` | 否 | `{ workspace }` | | -| `workspace.archive.after` | 否 | `{ workspace }` | | -| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | -| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | -| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | -| `agent.create.after` | 否 | `{ agent }` | | -| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`tools`、`mcpServers` | -| `agent.close.after` | 否 | `{ agent }` | | -| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | -| `agent.turn.before` | 否 | `{ agent, turnId }` | | -| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | -| `agent.permission.before` | 否 | `{ agent, request }` | | -| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | +| 钩子 | 等待 | 载荷 | 可修改 | +| ------------------------- | ---- | ------------------------------------------------------ | ------------------------------------------ | +| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 | +| `workspace.create.after` | 否 | `{ workspace }` | | +| `workspace.archive.after` | 否 | `{ workspace }` | | +| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 | +| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 | +| `agent.create.before` | 是 | `{ request: { config, env?, metadata, workspaceId } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` | +| `agent.create.after` | 否 | `{ agent }` | | +| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`tools`、`mcpServers` | +| `agent.close.after` | 否 | `{ agent }` | | +| `agent.archive.after` | 否 | `{ agent, archivedAt }` | | +| `agent.turn.before` | 否 | `{ agent, turnId }` | | +| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | | +| `agent.permission.before` | 否 | `{ agent, request }` | | +| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | | +| `terminal.create.before` | 是 | `{ request }` | `command`、`args`、`env`;抛出错误则拒绝 | +| `command.run.before` | 是 | `{ request }` | `command`、`env`;抛出错误则拒绝 | ## 共享载荷 {#shared-payloads} @@ -221,9 +223,66 @@ server.addHook("worktree.create.after", async ({ worktree }) => { }); ``` +## terminal.create.before {#terminalcreatebefore} + +Paseo 在工作区中启动终端之前等待此钩子: + +- 应用中的 **新建终端** 和终端配置,以及通过 CLI、SDK 和插件创建的终端 +- Agent 通过 Paseo 工具打开的终端 +- 运行 `paseo.json` 脚本、服务和 worktree 终端的终端 + +钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。抛出错误会拒绝创建终端,请求方收到 `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] : [], + }; +}); +``` + +| 请求字段 | 含义 | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `workspaceId` | 只读,终端所属的工作区 | +| `cwd` | 只读,终端的起始目录 | +| `source` | 只读。`agent`:Agent 的 Paseo 工具。`script`:`paseo.json` 脚本或服务。`worktree`:`paseo.json` worktree 终端。`client`:应用、CLI、SDK 或插件 | +| `name` | 只读,标签页名称,没有时为 null | +| `input` | 只读。对于 `script` 和 `worktree`,是 shell 启动后 Paseo 输入的命令;其他情况为 null | +| `command`、`args` | 要运行的程序及其参数。没有 `command` 时,Paseo 启动默认 shell | +| `env` | Paseo 添加到终端环境中的变量 | + +脚本、服务和 worktree 终端先启动默认 shell,再向其中输入命令,所以包装 shell 的钩子也会包装它们运行的命令。daemon 重启后仍在运行的终端会被接管,不会重新创建,也不会再次触发此钩子。插件在此钩子中创建终端时,该终端同样会触发此钩子。 + +## command.run.before {#commandrunbefore} + +Paseo 在运行每条 `paseo.json` worktree `setup` 和 `teardown` 命令之前等待此钩子。钩子收到 `{ request }`,返回替换请求,或返回 `undefined` 保持原值。抛出错误会拒绝该命令: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 }, +})); +``` + +| 请求字段 | 含义 | +| ------------- | --------------------------------------------------------------------------------------------------------------- | +| `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` 等 | + +setup 在工作区注册并发出 `workspace.create.after` 之后开始,与第一个 Agent 同时运行。setup 再次运行时,例如在 setup 被阻止的 worktree 上点击 **运行设置**,每条命令都会再次触发此钩子。teardown 在 worktree 上最后一个工作区归档时运行,在 Paseo 删除目录之前。 + ## agent.create.before {#agentcreatebefore} -收到 `{ request: { config, env?, metadata } }`。配置和 `metadata` 的修改会保存,即使插件以后被停用或移除;`env` 只用于首次启动,不会保存。不能修改 `config.cwd`。抛出错误、无效返回或超时会让创建失败。 +收到 `{ request: { config, env?, metadata, workspaceId } }`。配置和 `metadata` 的修改会保存,即使插件以后被停用或移除;`env` 只用于首次启动,不会保存。不能修改 `config.cwd` 和 `workspaceId`。抛出错误、无效返回或超时会让创建失败。 + +`workspaceId` 是创建 Agent 的工作区,没有时为 null。请用它而不是 `config.cwd` 来确定工作区:多个工作区可以共用一个目录,Agent 也可能在一个工作区中创建,而目录位于另一个工作区内。 **`agent.create.before.config`** 使用 `AgentSessionConfig`: @@ -664,12 +723,12 @@ 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,并在插件进程中执行文件操作的工具 | +| 插件 | 包含 | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | +| [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,并在插件进程中执行文件操作的工具 | 用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。