feat(plugins): hooks for terminal creation and worktree commands, with the workspace id

Applied from getpaseo/paseo#8691 (head 416d70614) onto main.
This commit is contained in:
Josh Bendavid
2026-11-25 17:37:32 +01:00
committed by Mohamed Boudra
parent 3153f6f94a
commit b4e4803df2
25 changed files with 724 additions and 38 deletions
+2
View File
@@ -523,6 +523,8 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
`plugin-examples/worktrunk`.
`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.
+24
View File
@@ -427,6 +427,30 @@ 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";
});
// Results built before workspaceId existed still typecheck; the daemon keeps the id.
server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env }));
server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env }));
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;
+2
View File
@@ -23,6 +23,8 @@ export type {
PluginHookWorkspace,
PluginHookWorktree,
PluginWorktreeCreateRequest,
PluginTerminalCreateRequest,
PluginCommandRunRequest,
PluginHookAgent,
PluginSessionOpenRequest,
PluginTurnOutcome,
+44 -2
View File
@@ -68,6 +68,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<string, string>;
}
/** 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<string, string>;
}
export interface PluginHookAgent {
id: string;
workspaceId: string | null;
@@ -145,18 +175,28 @@ export interface PluginHookRequests {
env?: Record<string, string>;
/** Stored on the new agent. Always present in the payload; return it changed to change it. */
metadata?: Record<string, JsonValue>;
/** 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<WorkspaceCreateRequest, "type" | "requestId">;
"terminal.create.before": PluginTerminalCreateRequest;
"command.run.before": PluginCommandRunRequest;
}
/** What a hook may return. An omitted `metadata` stays as it was. */
type PluginHookRequestResults = Omit<PluginHookRequests, "agent.open.before"> & {
/** What a hook may return. An omitted `metadata` or `workspaceId` stays as it was. */
type PluginHookRequestResults = Omit<
PluginHookRequests,
"agent.open.before" | "agent.create.before"
> & {
// Read-only fields added after the first SDK stay optional in a result; omitted means unchanged.
"agent.open.before": Omit<PluginSessionOpenRequest, "metadata" | "background"> & {
readonly background?: boolean;
metadata?: Readonly<Record<string, JsonValue>>;
};
"agent.create.before": Omit<PluginHookRequests["agent.create.before"], "workspaceId"> & {
readonly workspaceId?: string | null;
};
};
export type PluginHooks = {
@@ -224,6 +264,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<keyof PluginHooks, { waits: boolean }>;
// COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30
@@ -1721,6 +1721,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`.
@@ -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";
@@ -47,6 +48,7 @@ interface CreateAgentLifecycleDispatchDependencies {
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
logger: pino.Logger;
lifecycle: Pick<PluginLifecycle, "before"> | null;
}
export interface LifecycleRegistration {
@@ -192,6 +194,7 @@ export class CreateAgentLifecycleDispatch {
await archiveByScope(
{
lifecycle: this.dependencies.lifecycle,
paseoHome: this.dependencies.paseoHome,
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
worktreeManagers: this.dependencies.worktreeManagers,
@@ -161,6 +161,7 @@ export interface PaseoToolHostDependencies {
workspaceScripts?: Pick<WorkspaceScriptsService, "list" | "launch" | "stop">;
markWorkspaceArchiving?: ArchiveDependencies["markWorkspaceArchiving"];
clearWorkspaceArchiving?: ArchiveDependencies["clearWorkspaceArchiving"];
lifecycle?: ArchiveDependencies["lifecycle"];
createPaseoWorktree?: CreatePaseoWorktreeWorkflowFn;
// Mints a fresh directory workspace for a cwd and returns its id.
ensureWorkspaceForCreate?: (
@@ -2565,6 +2566,7 @@ function createToolCatalog(
const workspaceId = await resolveTerminalWorkspaceId(resolvedCwd);
const terminal = await terminalManager.createTerminal({
origin: { source: "agent" },
cwd: resolvedCwd,
workspaceId,
...(name?.trim() ? { name: name.trim() } : {}),
@@ -3463,6 +3465,7 @@ function archiveWorktreeDependencies(
throw new Error("Checkout trust lookup is required to archive worktrees");
}
return {
lifecycle: options.lifecycle ?? null,
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
@@ -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";
@@ -44,6 +45,7 @@ export interface AutoArchiveArchiveOptions {
markWorkspaceArchiving: (workspaceIds: Iterable<string>, archivingAt: string) => void;
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds: Iterable<string>) => Promise<void>;
lifecycle: Pick<PluginLifecycle, "before"> | null;
}
export interface ArchiveIfSafeDependencies {
@@ -104,6 +106,7 @@ export async function archiveIfSafe(input: {
await deps.archiveByScope(
{
lifecycle: options.lifecycle,
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
worktreeManagers: options.worktreeManagers,
+17 -7
View File
@@ -192,6 +192,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";
@@ -739,13 +740,16 @@ 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),
eagerLaunch: !dependencies.lazyTerminalWorker,
});
const terminalManager = withTerminalCreateHook(
await startWorkerTerminalManager({
paseoHome: config.paseoHome,
paseoVersion: daemonVersion,
logger,
getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget),
eagerLaunch: !dependencies.lazyTerminalWorker,
}),
pluginRuntime,
);
applyTerminalAgentHookSetting({ store: daemonConfigStore, logger });
const serviceProxyPublicBaseUrl = config.serviceProxy?.publicBaseUrl
@@ -1235,6 +1239,7 @@ export async function createPaseoDaemon(
});
setupAutoArchiveOnMerge({
lifecycle: pluginRuntime,
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
@@ -1266,6 +1271,7 @@ export async function createPaseoDaemon(
) => {
return createPaseoWorktreeWorkflow(
{
lifecycle: pluginRuntime,
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
createPaseoWorktree: async (workflowInput, workflowOptions) => {
@@ -1330,6 +1336,7 @@ export async function createPaseoDaemon(
const archiveWorkspaceByIdExternal = (workspaceId: string, requestId: string) =>
archiveByScope(
{
lifecycle: pluginRuntime,
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
@@ -1357,6 +1364,7 @@ export async function createPaseoDaemon(
{ scope: { kind: "workspace", workspaceId }, requestId },
);
const hubAgentLifecycle = new CreateAgentLifecycleDispatch({
lifecycle: pluginRuntime,
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
@@ -1461,6 +1469,7 @@ export async function createPaseoDaemon(
const archiveScheduleWorkspaceExternal = async (workspaceId: string) => {
await archiveByScope(
{
lifecycle: pluginRuntime,
paseoHome: config.paseoHome,
paseoWorktreesBaseRoot: config.worktreesRoot,
worktreeManagers: pluginRuntime,
@@ -1624,6 +1633,7 @@ export async function createPaseoDaemon(
listActiveWorkspaces: listActiveWorkspacesExternal,
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
archiveWorkspaceRecordExternal(workspaceId, undefined, archivedAt),
lifecycle: pluginRuntime,
emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal,
workspaceRegistry,
projectRegistry,
@@ -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<PluginLifecycle, "before"> | 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 };
};
}
@@ -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 }) => {
@@ -554,9 +556,14 @@ test("agent creation hooks change the provider and environment before the sessio
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(pluginDirectory);
await client.installDirectoryPlugin(extraPlugin);
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",
systemPrompt: "Saved instructions",
});
@@ -577,6 +584,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" } },
@@ -617,6 +625,176 @@ 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");
// 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)"`;
execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" });
await writeFile(
path.join(repository, "paseo.json"),
JSON.stringify({
worktree: { setup: setupCommand, teardown: teardownCommand },
scripts: { greet: { command: scriptCommand } },
}),
);
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");
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");
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: setupCommand,
}),
},
{
hook: "command",
request: expect.objectContaining({
workspaceId,
cwd: worktree,
purpose: "teardown",
command: teardownCommand,
}),
},
]);
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: scriptCommand,
}),
},
]);
} 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" });
@@ -479,3 +479,66 @@ test("a history open keeps the wrap while tools and MCP servers are stripped", a
expect(history).toMatchObject({ wrap: ["/usr/local/bin/sandbox"], tools: [], mcpServers: {} });
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: {},
};
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" },
metadata: { "issues.id": "ENG-1" },
workspaceId: "wks_a",
};
// A result built before either field existed keeps both.
await expect(
validateBeforeResult("agent.create.before", request, { config: request.config }),
).resolves.toEqual(request);
await expect(
validateBeforeResult("agent.create.before", request, {
config: request.config,
metadata: { "issues.id": "ENG-2" },
}),
).resolves.toEqual({ ...request, metadata: { "issues.id": "ENG-2" } });
await expect(
validateBeforeResult("agent.create.before", request, { ...request, workspaceId: "wks_b" }),
).rejects.toThrow("agent.create.before hooks cannot change the workspace");
});
@@ -100,7 +100,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(),
@@ -131,8 +134,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<string, unknown>;
const next = result as Record<string, unknown>;
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<AgentToolDefinition>(
@@ -309,8 +354,15 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
if (previous.config.cwd !== next.config.cwd) {
throw new Error("agent.create.before hooks cannot change the workspace directory");
}
if ((next.workspaceId ?? previous.workspaceId ?? null) !== (previous.workspaceId ?? null)) {
throw new Error("agent.create.before hooks cannot change the workspace");
}
// Omitted means unchanged: the next hook sees what this one was handed.
return { ...result, metadata: next.metadata ?? previous.metadata };
return {
...result,
metadata: next.metadata ?? previous.metadata,
workspaceId: previous.workspaceId ?? null,
};
}
if (name === "workspace.create.before") {
const previous = beforeSchemas["workspace.create.before"].parse(input);
@@ -318,6 +370,7 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
// Omitted means unchanged; an explicit {} still replaces.
return { ...result, metadata: next.metadata ?? previous.metadata };
}
assertReadOnlyFields(name, input, result);
if (name === "worktree.create.before") {
const previous = beforeSchemas["worktree.create.before"].parse(input);
const next = beforeSchemas["worktree.create.before"].parse(result);
+9
View File
@@ -837,6 +837,10 @@ export class Session {
private readonly daemonConfigStore: DaemonConfigStore;
private readonly pushNotifications: PushNotifications;
private readonly pluginRuntime: SessionOptions["pluginRuntime"];
// What worktree setup and teardown commands run through: the plugins' hooks, or none.
private get commandLifecycle(): NonNullable<SessionOptions["pluginRuntime"]> | null {
return this.pluginRuntime ?? null;
}
private readonly orchestrationSkills: SessionOptions["orchestrationSkills"];
private unsubscribeAgentEvents: (() => void) | null = null;
private unsubscribeProjectMutations: (() => void) | null = null;
@@ -1296,6 +1300,7 @@ export class Session {
});
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({
lifecycle: this.commandLifecycle,
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
@@ -5832,6 +5837,7 @@ export class Session {
): Promise<void> {
return handleWorktreeArchiveRequest(
{
lifecycle: this.commandLifecycle,
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
@@ -8161,6 +8167,7 @@ export class Session {
): Promise<CreatePaseoWorktreeWorkflowResult> {
return createWorktreeWorkflow(
{
lifecycle: this.commandLifecycle,
paseoHome: this.paseoHome,
worktreesRoot: this.worktreesRoot,
createPaseoWorktree: (workflowInput, serviceOptions) =>
@@ -8214,6 +8221,7 @@ export class Session {
): Promise<void> {
return handleWorkspaceSetupRunRequestMessage(
{
lifecycle: this.commandLifecycle,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
clearAutomationBlock: (workspaceId) =>
this.withWorkspaceCheckout(workspaceId, async (checkoutPath) => {
@@ -8263,6 +8271,7 @@ export class Session {
}
return archiveByScope(
{
lifecycle: this.commandLifecycle,
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
worktreeManagers: this.pluginRuntime,
@@ -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";
@@ -69,6 +71,8 @@ export interface ArchiveDependencies {
assertWorkspaceAutomationAllowed: (workspaceId: string) => Promise<void>;
isCheckoutUntrusted: (checkoutPath: string) => Promise<boolean>;
sessionLogger?: Logger;
/** Plugins' lifecycle, for `command.run.before` on teardown commands. */
lifecycle: Pick<PluginLifecycle, "before"> | null;
}
export interface KillTerminalsForWorkspaceDependencies {
@@ -593,6 +597,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) {
@@ -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<string, string> | 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,
});
@@ -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<PluginLifecycle, "before"> | 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);
}
@@ -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<PluginLifecycle, "before">,
): 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,
});
},
};
}
@@ -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<TerminalSession[]>;
createTerminal(options: {
/** Where the terminal comes from, for plugins' `terminal.create.before` hooks. */
origin?: TerminalOrigin;
id?: string;
cwd: string;
workspaceId: string;
@@ -882,6 +882,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: {
+63 -17
View File
@@ -140,6 +140,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<string, string>;
}
/** Lets plugins wrap or refuse a lifecycle command before it runs; see `command.run.before`. */
export type PrepareWorktreeLifecycleCommand = (
command: WorktreeLifecycleCommand,
) => Promise<WorktreeLifecycleCommand>;
async function prepareLifecycleCommand(
prepare: PrepareWorktreeLifecycleCommand | undefined,
command: WorktreeLifecycleCommand,
fail: (message: string) => Error,
): Promise<WorktreeLifecycleCommand> {
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[];
@@ -678,6 +702,7 @@ export async function runWorktreeSetupCommands(options: {
runtimeEnv?: WorktreeRuntimeEnv;
signal?: AbortSignal;
onEvent?: (event: WorktreeSetupCommandProgressEvent) => void;
prepareCommand?: PrepareWorktreeLifecycleCommand;
}): Promise<WorktreeSetupCommandResult[]> {
// Read paseo.json from the worktree (it will have the same content as the source repo)
const setupCommands = await getWorktreeSetupCommands(options.worktreePath);
@@ -692,10 +717,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,
@@ -779,6 +816,7 @@ export async function runWorktreeTeardownCommands(options: {
teardownCwd?: string;
branchName?: string;
repoRootPath?: string;
prepareCommand?: PrepareWorktreeLifecycleCommand;
}): Promise<WorktreeTeardownCommandResult[]> {
const teardownCwd = options.teardownCwd ?? options.worktreePath;
if ((await getOwnershipRelativePath(options.worktreePath, teardownCwd)) === null) {
@@ -795,29 +833,37 @@ 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<string, string> = {
// 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) } : {}),
};
// One deadline covers every command. Reaching it counts as failure and keeps the worktree.
const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd);
const deadline = AbortSignal.timeout(timeoutMs);
const results: WorktreeTeardownCommandResult[] = [];
for (const [index, cmd] of teardownCommands.entries()) {
for (const [index, configured] of teardownCommands.entries()) {
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 execSetupCommandStreamed({
command: cmd,
cwd: teardownCwd,
env: teardownEnv,
env: createStringCommandShellEnv(createExternalProcessEnv(process.env, prepared.env)),
index: index + 1,
total: teardownCommands.length,
signal: deadline,
+3 -2
View File
@@ -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:
@@ -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 () => {};
}
+63 -4
View File
@@ -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 <id> <hook> failed: …`. Request-changing hooks receive `{ request }` and may return a complete replacement request or `undefined`.
- Notifications receive the event object and return `Promise<void>`. 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.
@@ -56,7 +56,7 @@ Paseo only sees the returned promise, so detached work gets no error reporting a
| `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.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 }` | |
@@ -65,6 +65,8 @@ Paseo only sees the returned promise, so detached work gets no error reporting a
| `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 <id> 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`:
@@ -744,7 +803,7 @@ replaces that scope's prior value.
| 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-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 |
+63 -4
View File
@@ -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 <id> <hook> failed: …`。修改请求的钩子收到 `{ request }`,可以返回完整的替换请求或 `undefined`。
- 通知收到事件对象,返回 `Promise<void>`。Paseo 不等待;错误会记录在插件名下,原操作继续。`agent.turn.before` 和 `agent.permission.before` 分别在轮次开始或权限进入待处理状态时发出通知。
@@ -54,7 +54,7 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没
| `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.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 }` | |
@@ -63,6 +63,8 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没
| `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 <id> 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`:
@@ -697,7 +756,7 @@ Creation request
| 插件 | 包含 |
| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 |
| [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,并在插件进程中执行文件操作的工具 |