@agentproto/worktree 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { connectDaemonAgentSessionHost, worktreeAgentWorkflow } from '../chunk-6EV7WP2U.mjs';
2
+ import { connectDaemonAgentSessionHost, worktreeAgentWorkflow } from '../chunk-5SDH2V6M.mjs';
3
3
  import '../chunk-E3EM24BS.mjs';
4
- import '../chunk-KRQFVJPK.mjs';
5
- import '../chunk-IKCBL2UN.mjs';
4
+ import '../chunk-EVHLUKC7.mjs';
5
+ import '../chunk-EK5BH2YL.mjs';
6
6
  import { runWorkflow } from '@agentproto/workflow-runtime';
7
7
  import { resolve } from 'path';
8
8
  import { openSync, closeSync, createReadStream, createWriteStream } from 'fs';
@@ -1,5 +1,5 @@
1
- import { worktreeProvider } from './chunk-KRQFVJPK.mjs';
2
- import { provisionWorktreeTool, runGateTool, cleanupWorktreeTool } from './chunk-IKCBL2UN.mjs';
1
+ import { worktreeProvider } from './chunk-EVHLUKC7.mjs';
2
+ import { provisionWorktreeTool, runGateTool, cleanupWorktreeTool } from './chunk-EK5BH2YL.mjs';
3
3
  import { z } from 'zod';
4
4
  import { resolveMcpUrl, HarnessClient } from '@agentproto/harness';
5
5
 
@@ -196,5 +196,5 @@ async function waitForSettled(client, sessionId, since) {
196
196
  }
197
197
 
198
198
  export { connectDaemonAgentSessionHost, makeDaemonAgentSessionHost, worktreeAgentInputSchema, worktreeAgentWorkflow };
199
- //# sourceMappingURL=chunk-6EV7WP2U.mjs.map
200
- //# sourceMappingURL=chunk-6EV7WP2U.mjs.map
199
+ //# sourceMappingURL=chunk-5SDH2V6M.mjs.map
200
+ //# sourceMappingURL=chunk-5SDH2V6M.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/workflow.ts","../src/agent-session-host.ts"],"names":[],"mappings":";;;;;;;;;AASO,IAAM,wBAAA,G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AW,KAAA,EAAwB;AAC9C,MAAA,OAAO,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,KAAK,CAAA;AAAA,IACvC,CAAA;AAAA,IAEA,MAAM,KAAK,SAAA,EAA0B;AACnC,MAAA,MAAM,MAAA,CAAO,KAAK,SAAS,CAAA;AAAA,IAC7B,CAAA;AAAA,IAEA,MAAM,UAAA,CAAW,UAAA,EAAY,IAAA,EAA2B;AACtD,MAAA,OAAO,MAAA,CAAO,UAAA,CAAW,UAAA,EAAY,IAAI,CAAA;AAAA,IAC3C,CAAA;AAAA,IAEA,MAAM,mBAAA,GAAuC;AAC3C,MAAA,OAAO,OAAO,mBAAA,EAAoB;AAAA,IACpC,CAAA;AAAA,IAEA,GAAI,OAAO,MAAA,CAAO,KAAA,KAAU,UAAA,GACxB;AAAA,MACE,MAAM,MAAM,SAAA,EAAkD;AAC5D,QAAA,OAAO,MAAA,CAAO,MAAO,SAAS,CAAA;AAAA,MAChC;AAAA,QAEF,EAAC;AAAA,IAEL,MAAM,KAAA,GAAuB;AAC3B,MAAA,MAAM,OAAO,KAAA,EAAM;AAAA,IACrB;AAAA,GACF;AACF;AAWA,eAAe,cAAA,CAAe,MAAA,EAAsB,SAAA,EAAmB,KAAA,EAA8B;AACnG,EAAA,WAAS;AACP,IAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,UAAA,CAAW,CAAC,SAAS,CAAA,EAAG,EAAE,KAAA,EAAO,KAAA,EAAO,SAAA,EAAW,WAAA,EAAa,OAAO,CAAA;AACnG,IAAA,IAAI,CAAC,OAAO,QAAA,EAAU;AAAA,EACxB;AACF","file":"chunk-6EV7WP2U.mjs","sourcesContent":["import { z } from \"zod\"\nimport type { Bindings, RuntimeWorkflow } from \"@agentproto/workflow-runtime\"\nimport { provisionWorktreeTool, cleanupWorktreeTool, runGateTool } from \"./tools/index.js\"\nimport { worktreeProvider } from \"./provider/index.js\"\n\n/**\n * Input to the worktree-agent workflow: launch a coding agent inside a\n * fresh git worktree, gate its work, and — on approval — clean up.\n */\nexport const worktreeAgentInputSchema = z.object({\n repoRoot: z.string().describe(\"Absolute path to the git repository root.\"),\n slug: z.string().describe(\"Worktree/branch identifier, e.g. 'fix-flaky-test'.\"),\n base: z.string().optional().describe(\"Ref to cut the worktree branch from. Default 'origin/main'.\"),\n depsCmd: z.string().optional().describe(\"Command to install deps inside the worktree, e.g. 'pnpm install --prefer-offline'.\"),\n copyGlobs: z.array(z.string()).optional().describe(\"Gitignored files to copy into the worktree, e.g. secrets.\"),\n linkPaths: z.array(z.string()).optional().describe(\"Gitignored dirs/files symlinked from the host repo into the worktree before depsCmd (node_modules, sibling workspace repos) so the graph resolves without a full reinstall.\"),\n writeFiles: z\n .array(\n z.object({\n path: z.string().describe(\"Path relative to the worktree root.\"),\n content: z.string().describe(\"File content, written or appended verbatim.\"),\n mode: z\n .enum([\"create\", \"append\"])\n .optional()\n .describe(\"'create' (default): write only if path doesn't already exist. 'append': always append (creating if missing); if git tracks the path, it's marked skip-worktree afterwards.\"),\n }),\n )\n .optional()\n .describe(\"Files written into the worktree before depsCmd runs, e.g. a package-manager config generated for this specific worktree.\"),\n task: z.string().describe(\"The prompt sent to the coding agent.\"),\n adapter: z.string().optional().describe(\"Agent adapter slug. Default 'claude-code'.\"),\n gateCmd: z.string().describe(\"Command run inside the worktree to check the agent's work, e.g. 'pnpm test'.\"),\n deleteBranch: z.boolean().optional().describe(\"Delete the worktree's branch on cleanup. Default true.\"),\n})\n\nexport type WorktreeAgentInput = z.infer<typeof worktreeAgentInputSchema>\n\nconst candidates = [worktreeProvider]\n\nfunction input(b: { input: unknown }): WorktreeAgentInput {\n return b.input as WorktreeAgentInput\n}\n\n/**\n * provision (tool) → code (AgentStep, cwd bound to provision's output) →\n * gate (tool) → on pass: approval → cleanup (tool); on fail: leave the\n * worktree in place for inspection.\n */\nexport const worktreeAgentWorkflow: RuntimeWorkflow = {\n id: \"worktree-agent\",\n description:\n \"Launch a coding agent inside a fresh git worktree, gate its work with a \" +\n \"check command, get a human ack, then clean up. On gate failure the \" +\n \"worktree is left in place for inspection instead of being cleaned up.\",\n steps: [\n {\n kind: \"tool\",\n id: \"provision\",\n tool: provisionWorktreeTool,\n candidates,\n input: (b: Bindings) => {\n const i = input(b)\n return {\n repoRoot: i.repoRoot,\n slug: i.slug,\n base: i.base,\n depsCmd: i.depsCmd,\n copyGlobs: i.copyGlobs,\n linkPaths: i.linkPaths,\n writeFiles: i.writeFiles,\n }\n },\n },\n {\n kind: \"agent\",\n id: \"code\",\n adapter: (b: Bindings) => input(b).adapter ?? \"claude-code\",\n cwd: (b: Bindings) => (b.steps.provision as { cwd: string }).cwd,\n prompt: (b: Bindings) => input(b).task,\n },\n {\n kind: \"tool\",\n id: \"gate\",\n tool: runGateTool,\n candidates,\n input: (b: Bindings) => ({\n cwd: (b.steps.provision as { cwd: string }).cwd,\n cmd: input(b).gateCmd,\n }),\n },\n {\n kind: \"branch\",\n id: \"route\",\n cond: (b: Bindings) => (b.steps.gate as { passed: boolean }).passed,\n then: [\n {\n kind: \"approval\",\n id: \"approval\",\n prompt: () => \"Gate passed. Approve worktree cleanup?\",\n onApprove: [\n {\n kind: \"tool\",\n id: \"cleanup\",\n tool: cleanupWorktreeTool,\n candidates,\n // discardUntracked/discardModified: worktree.cleanup refuses a\n // dirty tree by default (PLAN.md §5.2 layer 3). This workflow's\n // own approval step, just above, is that guard already — a\n // human explicitly approved tearing this worktree down, so\n // both flags are granted here rather than surfacing a second,\n // redundant refusal.\n input: (b: Bindings) => ({\n repoRoot: input(b).repoRoot,\n cwd: (b.steps.provision as { cwd: string }).cwd,\n branch: (b.steps.provision as { branch: string }).branch,\n deleteBranch: input(b).deleteBranch ?? true,\n discardUntracked: true,\n discardModified: true,\n }),\n },\n ],\n onReject: [\n {\n kind: \"transform\",\n id: \"held\",\n compute: () => ({ removed: false, reason: \"cleanup_rejected\" as const }),\n },\n ],\n },\n ],\n otherwise: [\n {\n kind: \"transform\",\n id: \"gate-failed\",\n compute: () => ({ removed: false, reason: \"gate_failed\" as const }),\n },\n ],\n },\n ],\n output: (b: Bindings) => ({\n cwd: (b.steps.provision as { cwd: string }).cwd,\n branch: (b.steps.provision as { branch: string }).branch,\n gate: b.steps.gate,\n cleanup: b.steps.cleanup ?? b.steps.held ?? b.steps[\"gate-failed\"],\n }),\n}\n","import {\n HarnessClient,\n resolveMcpUrl,\n type ConnectHarnessOptions,\n type SessionDescriptor,\n type SessionUsageSnapshot,\n type StartAgentArgs,\n type TurnEvent,\n type TurnResult,\n} from \"@agentproto/harness\"\nimport type { AgentSessionHost } from \"@agentproto/workflow-runtime\"\n\n/** `session_monitor`'s max accepted long-poll window (`orchestration-tools.ts`). */\nconst MAX_POLL_MS = 49_000\n\n/** The subset of `HarnessClient` the host drives — narrowed for fake-client tests. */\nexport type DaemonClient = Pick<\n HarnessClient,\n \"start\" | \"prompt\" | \"output\" | \"kill\" | \"waitForAny\" | \"currentEventsCursor\" | \"close\"\n> & {\n /** `session_usage` — optional so pre-existing fakes/clients without it still\n * satisfy the type; the host simply exposes no `usage` then. */\n usage?: HarnessClient[\"usage\"]\n}\n\nexport interface DaemonAgentSessionHost extends AgentSessionHost {\n close(): Promise<void>\n /** Full `agent_start`, returning the raw descriptor and forwarding every\n * `StartAgentArgs` field (`mcpServers`, `model`, `effort`, `label`, …) —\n * unlike `spawn()` above (the narrow AgentStep-shaped convenience\n * wrapper), which only takes `cwd`/`workspaceSlug`/`stepId`. Consumers\n * that need finer per-turn control than the AgentStep contract provides\n * (e.g. `@agentproto/sandbox`'s sandbox agent-session proxy) use this\n * plus `prompt`/`output`/`kill`/`waitForAny` directly instead of\n * `spawn`/`sendPromptAndWait`. */\n start(args: StartAgentArgs): Promise<SessionDescriptor>\n /** Send a follow-up turn — `opts.interrupt` cancels an in-flight turn and\n * redirects the session onto this prompt (mirrors `agent_prompt`). */\n prompt(sessionId: string, prompt: string, opts?: { interrupt?: boolean }): Promise<void>\n /** Tail the ring buffer (`agent_output`). */\n output(sessionId: string, lastN?: number): Promise<string>\n /** SIGTERM the session (`agent_kill`). */\n kill(sessionId: string): Promise<void>\n /** Multiplexed long-poll (`session_monitor`) — see `HarnessClient.waitForAny`. */\n waitForAny(\n sessionIds: string[],\n opts?: { timeoutMs?: number; event?: TurnEvent; since?: number },\n ): Promise<TurnResult>\n /** Race-free cursor for a subsequent `waitForAny({ since })` — see\n * `HarnessClient.currentEventsCursor`. */\n currentEventsCursor(): Promise<number>\n /** Usage accounting for a session on this daemon (`session_usage`) — present\n * when the underlying client can answer it. `@agentproto/sandbox`'s host\n * inherits it, which is how a sandboxed session's cost/tokens/model reach\n * the HOST daemon's descriptor (the proxy's text stream carries none). */\n usage?(sessionId: string): Promise<SessionUsageSnapshot>\n}\n\n/**\n * Connect to the agentproto daemon's MCP endpoint and return a real,\n * supervisable `AgentSessionHost` — every `AgentStep` becomes an `agent_start`\n * daemon session rather than a bare subprocess. Fails loudly (no silent\n * fallback) if the daemon isn't reachable.\n */\nexport async function connectDaemonAgentSessionHost(\n opts?: ConnectHarnessOptions,\n): Promise<DaemonAgentSessionHost> {\n const url = resolveMcpUrl(opts)\n let client: HarnessClient\n try {\n client = await HarnessClient.connect({ url })\n } catch (err) {\n throw new Error(\n `worktree-agent: could not reach the agentproto daemon's MCP endpoint at ${url}. ` +\n \"Start the daemon (`agentproto daemon start`), or point at a running one via \" +\n `AGENTPROTO_MCP_URL, before running this command.\\n` +\n `(${err instanceof Error ? err.message : String(err)})`,\n )\n }\n return makeDaemonAgentSessionHost(client)\n}\n\n/** Build the host over an already-connected client (exported for tests with a fake client). */\nexport function makeDaemonAgentSessionHost(client: DaemonClient): DaemonAgentSessionHost {\n const sessionByStepId = new Map<string, string>()\n\n return {\n async spawn(adapter, opts): Promise<string> {\n const desc = await client.start({\n adapter,\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n ...(opts.workspaceSlug !== undefined ? { workspaceSlug: opts.workspaceSlug } : {}),\n ...(opts.stepId !== undefined ? { label: opts.stepId } : {}),\n })\n if (opts.stepId) sessionByStepId.set(opts.stepId, desc.id)\n return desc.id\n },\n\n async sendPromptAndWait(sessionId, prompt): Promise<void> {\n // Capture a race-free cursor BEFORE sending: an extremely fast turn\n // can settle before a live bus subscription even starts — a real\n // race over the network round-trip to `prompt`/`waitForAny`, not\n // just in-process call ordering (see `HarnessClient\n // .currentEventsCursor`'s doc). The awaited cursor fetch completes\n // strictly before `prompt` is sent, so the daemon's ring-replay\n // branch can always find the matching turn-end regardless of how\n // late the long-poll's own subscription lands.\n const since = await client.currentEventsCursor()\n await client.prompt(sessionId, prompt)\n await waitForSettled(client, sessionId, since)\n },\n\n resolveByLabel(stepId): string | undefined {\n return sessionByStepId.get(stepId)\n },\n\n async start(args): Promise<SessionDescriptor> {\n return client.start(args)\n },\n\n async prompt(sessionId, prompt, opts): Promise<void> {\n await client.prompt(sessionId, prompt, opts)\n },\n\n async output(sessionId, lastN): Promise<string> {\n return client.output(sessionId, lastN)\n },\n\n async kill(sessionId): Promise<void> {\n await client.kill(sessionId)\n },\n\n async waitForAny(sessionIds, opts): Promise<TurnResult> {\n return client.waitForAny(sessionIds, opts)\n },\n\n async currentEventsCursor(): Promise<number> {\n return client.currentEventsCursor()\n },\n\n ...(typeof client.usage === \"function\"\n ? {\n async usage(sessionId: string): Promise<SessionUsageSnapshot> {\n return client.usage!(sessionId)\n },\n }\n : {}),\n\n async close(): Promise<void> {\n await client.close()\n },\n }\n}\n\n/**\n * `session_monitor` long-polls cap at 49s; loop past timeouts for longer\n * turns. A clean timeout comes back as `{ timedOut: true, sessionIds }` —\n * there is no `event: \"timeout\"` on the wire, `event` is only ever set on a\n * real match. Keep polling while `timedOut` is true; stop once it's\n * falsy/absent (a real turn-end/awaiting-input/exited match). `since` is\n * reused unchanged across retries — a timeout means nothing has matched\n * since that cursor yet, so there is nothing to advance.\n */\nasync function waitForSettled(client: DaemonClient, sessionId: string, since: number): Promise<void> {\n for (;;) {\n const result = await client.waitForAny([sessionId], { event: \"any\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-runtime\"\nimport { provisionWorktreeTool, cleanupWorktreeTool, runGateTool } from \"./tools/index.js\"\nimport { worktreeProvider } from \"./provider/index.js\"\n\n/**\n * Input to the worktree-agent workflow: launch a coding agent inside a\n * fresh git worktree, gate its work, and — on approval — clean up.\n */\nexport const worktreeAgentInputSchema = z.object({\n repoRoot: z.string().describe(\"Absolute path to the git repository root.\"),\n slug: z.string().describe(\"Worktree/branch identifier, e.g. 'fix-flaky-test'.\"),\n base: z.string().optional().describe(\"Ref to cut the worktree branch from. Default 'origin/main'.\"),\n depsCmd: z.string().optional().describe(\"Command to install deps inside the worktree, e.g. 'pnpm install --prefer-offline'.\"),\n copyGlobs: z.array(z.string()).optional().describe(\"Gitignored files to copy into the worktree, e.g. secrets.\"),\n linkPaths: z.array(z.string()).optional().describe(\"Gitignored dirs/files symlinked from the host repo into the worktree before depsCmd (node_modules, sibling workspace repos) so the graph resolves without a full reinstall.\"),\n writeFiles: z\n .array(\n z.object({\n path: z.string().describe(\"Path relative to the worktree root.\"),\n content: z.string().describe(\"File content, written or appended verbatim.\"),\n mode: z\n .enum([\"create\", \"append\"])\n .optional()\n .describe(\"'create' (default): write only if path doesn't already exist. 'append': always append (creating if missing); if git tracks the path, it's marked skip-worktree afterwards.\"),\n }),\n )\n .optional()\n .describe(\"Files written into the worktree before depsCmd runs, e.g. a package-manager config generated for this specific worktree.\"),\n task: z.string().describe(\"The prompt sent to the coding agent.\"),\n adapter: z.string().optional().describe(\"Agent adapter slug. Default 'claude-code'.\"),\n gateCmd: z.string().describe(\"Command run inside the worktree to check the agent's work, e.g. 'pnpm test'.\"),\n deleteBranch: z.boolean().optional().describe(\"Delete the worktree's branch on cleanup. Default true.\"),\n})\n\nexport type WorktreeAgentInput = z.infer<typeof worktreeAgentInputSchema>\n\nconst candidates = [worktreeProvider]\n\nfunction input(b: { input: unknown }): WorktreeAgentInput {\n return b.input as WorktreeAgentInput\n}\n\n/**\n * provision (tool) → code (AgentStep, cwd bound to provision's output) →\n * gate (tool) → on pass: approval → cleanup (tool); on fail: leave the\n * worktree in place for inspection.\n */\nexport const worktreeAgentWorkflow: RuntimeWorkflow = {\n id: \"worktree-agent\",\n description:\n \"Launch a coding agent inside a fresh git worktree, gate its work with a \" +\n \"check command, get a human ack, then clean up. On gate failure the \" +\n \"worktree is left in place for inspection instead of being cleaned up.\",\n steps: [\n {\n kind: \"tool\",\n id: \"provision\",\n tool: provisionWorktreeTool,\n candidates,\n input: (b: Bindings) => {\n const i = input(b)\n return {\n repoRoot: i.repoRoot,\n slug: i.slug,\n base: i.base,\n depsCmd: i.depsCmd,\n copyGlobs: i.copyGlobs,\n linkPaths: i.linkPaths,\n writeFiles: i.writeFiles,\n }\n },\n },\n {\n kind: \"agent\",\n id: \"code\",\n adapter: (b: Bindings) => input(b).adapter ?? \"claude-code\",\n cwd: (b: Bindings) => (b.steps.provision as { cwd: string }).cwd,\n prompt: (b: Bindings) => input(b).task,\n },\n {\n kind: \"tool\",\n id: \"gate\",\n tool: runGateTool,\n candidates,\n input: (b: Bindings) => ({\n cwd: (b.steps.provision as { cwd: string }).cwd,\n cmd: input(b).gateCmd,\n }),\n },\n {\n kind: \"branch\",\n id: \"route\",\n cond: (b: Bindings) => (b.steps.gate as { passed: boolean }).passed,\n then: [\n {\n kind: \"approval\",\n id: \"approval\",\n prompt: () => \"Gate passed. Approve worktree cleanup?\",\n onApprove: [\n {\n kind: \"tool\",\n id: \"cleanup\",\n tool: cleanupWorktreeTool,\n candidates,\n // discardUntracked/discardModified: worktree.cleanup refuses a\n // dirty tree by default (PLAN.md §5.2 layer 3). This workflow's\n // own approval step, just above, is that guard already — a\n // human explicitly approved tearing this worktree down, so\n // both flags are granted here rather than surfacing a second,\n // redundant refusal.\n input: (b: Bindings) => ({\n repoRoot: input(b).repoRoot,\n cwd: (b.steps.provision as { cwd: string }).cwd,\n branch: (b.steps.provision as { branch: string }).branch,\n deleteBranch: input(b).deleteBranch ?? true,\n discardUntracked: true,\n discardModified: true,\n }),\n },\n ],\n onReject: [\n {\n kind: \"transform\",\n id: \"held\",\n compute: () => ({ removed: false, reason: \"cleanup_rejected\" as const }),\n },\n ],\n },\n ],\n otherwise: [\n {\n kind: \"transform\",\n id: \"gate-failed\",\n compute: () => ({ removed: false, reason: \"gate_failed\" as const }),\n },\n ],\n },\n ],\n output: (b: Bindings) => ({\n cwd: (b.steps.provision as { cwd: string }).cwd,\n branch: (b.steps.provision as { branch: string }).branch,\n gate: b.steps.gate,\n cleanup: b.steps.cleanup ?? b.steps.held ?? b.steps[\"gate-failed\"],\n }),\n}\n","import {\n HarnessClient,\n resolveMcpUrl,\n type ConnectHarnessOptions,\n type SessionDescriptor,\n type SessionUsageSnapshot,\n type StartAgentArgs,\n type TurnEvent,\n type TurnResult,\n} from \"@agentproto/harness\"\nimport type { AgentSessionHost } from \"@agentproto/workflow-runtime\"\n\n/** `session_monitor`'s max accepted long-poll window (`orchestration-tools.ts`). */\nconst MAX_POLL_MS = 49_000\n\n/** The subset of `HarnessClient` the host drives — narrowed for fake-client tests. */\nexport type DaemonClient = Pick<\n HarnessClient,\n \"start\" | \"prompt\" | \"output\" | \"kill\" | \"waitForAny\" | \"currentEventsCursor\" | \"close\"\n> & {\n /** `session_usage` — optional so pre-existing fakes/clients without it still\n * satisfy the type; the host simply exposes no `usage` then. */\n usage?: HarnessClient[\"usage\"]\n}\n\nexport interface DaemonAgentSessionHost extends AgentSessionHost {\n close(): Promise<void>\n /** Full `agent_start`, returning the raw descriptor and forwarding every\n * `StartAgentArgs` field (`mcpServers`, `model`, `effort`, `label`, …) —\n * unlike `spawn()` above (the narrow AgentStep-shaped convenience\n * wrapper), which only takes `cwd`/`workspaceSlug`/`stepId`. Consumers\n * that need finer per-turn control than the AgentStep contract provides\n * (e.g. `@agentproto/sandbox`'s sandbox agent-session proxy) use this\n * plus `prompt`/`output`/`kill`/`waitForAny` directly instead of\n * `spawn`/`sendPromptAndWait`. */\n start(args: StartAgentArgs): Promise<SessionDescriptor>\n /** Send a follow-up turn — `opts.interrupt` cancels an in-flight turn and\n * redirects the session onto this prompt (mirrors `agent_prompt`). */\n prompt(sessionId: string, prompt: string, opts?: { interrupt?: boolean }): Promise<void>\n /** Tail the ring buffer (`agent_output`). */\n output(sessionId: string, lastN?: number): Promise<string>\n /** SIGTERM the session (`agent_kill`). */\n kill(sessionId: string): Promise<void>\n /** Multiplexed long-poll (`session_monitor`) — see `HarnessClient.waitForAny`. */\n waitForAny(\n sessionIds: string[],\n opts?: { timeoutMs?: number; event?: TurnEvent; since?: number },\n ): Promise<TurnResult>\n /** Race-free cursor for a subsequent `waitForAny({ since })` — see\n * `HarnessClient.currentEventsCursor`. */\n currentEventsCursor(): Promise<number>\n /** Usage accounting for a session on this daemon (`session_usage`) — present\n * when the underlying client can answer it. `@agentproto/sandbox`'s host\n * inherits it, which is how a sandboxed session's cost/tokens/model reach\n * the HOST daemon's descriptor (the proxy's text stream carries none). */\n usage?(sessionId: string): Promise<SessionUsageSnapshot>\n}\n\n/**\n * Connect to the agentproto daemon's MCP endpoint and return a real,\n * supervisable `AgentSessionHost` — every `AgentStep` becomes an `agent_start`\n * daemon session rather than a bare subprocess. Fails loudly (no silent\n * fallback) if the daemon isn't reachable.\n */\nexport async function connectDaemonAgentSessionHost(\n opts?: ConnectHarnessOptions,\n): Promise<DaemonAgentSessionHost> {\n const url = resolveMcpUrl(opts)\n let client: HarnessClient\n try {\n client = await HarnessClient.connect({ url })\n } catch (err) {\n throw new Error(\n `worktree-agent: could not reach the agentproto daemon's MCP endpoint at ${url}. ` +\n \"Start the daemon (`agentproto daemon start`), or point at a running one via \" +\n `AGENTPROTO_MCP_URL, before running this command.\\n` +\n `(${err instanceof Error ? err.message : String(err)})`,\n )\n }\n return makeDaemonAgentSessionHost(client)\n}\n\n/** Build the host over an already-connected client (exported for tests with a fake client). */\nexport function makeDaemonAgentSessionHost(client: DaemonClient): DaemonAgentSessionHost {\n const sessionByStepId = new Map<string, string>()\n\n return {\n async spawn(adapter, opts): Promise<string> {\n const desc = await client.start({\n adapter,\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n ...(opts.workspaceSlug !== undefined ? { workspaceSlug: opts.workspaceSlug } : {}),\n ...(opts.stepId !== undefined ? { label: opts.stepId } : {}),\n })\n if (opts.stepId) sessionByStepId.set(opts.stepId, desc.id)\n return desc.id\n },\n\n async sendPromptAndWait(sessionId, prompt): Promise<void> {\n // Capture a race-free cursor BEFORE sending: an extremely fast turn\n // can settle before a live bus subscription even starts — a real\n // race over the network round-trip to `prompt`/`waitForAny`, not\n // just in-process call ordering (see `HarnessClient\n // .currentEventsCursor`'s doc). The awaited cursor fetch completes\n // strictly before `prompt` is sent, so the daemon's ring-replay\n // branch can always find the matching turn-end regardless of how\n // late the long-poll's own subscription lands.\n const since = await client.currentEventsCursor()\n await client.prompt(sessionId, prompt)\n await waitForSettled(client, sessionId, since)\n },\n\n resolveByLabel(stepId): string | undefined {\n return sessionByStepId.get(stepId)\n },\n\n async start(args): Promise<SessionDescriptor> {\n return client.start(args)\n },\n\n async prompt(sessionId, prompt, opts): Promise<void> {\n await client.prompt(sessionId, prompt, opts)\n },\n\n async output(sessionId, lastN): Promise<string> {\n return client.output(sessionId, lastN)\n },\n\n async kill(sessionId): Promise<void> {\n await client.kill(sessionId)\n },\n\n async waitForAny(sessionIds, opts): Promise<TurnResult> {\n return client.waitForAny(sessionIds, opts)\n },\n\n async currentEventsCursor(): Promise<number> {\n return client.currentEventsCursor()\n },\n\n ...(typeof client.usage === \"function\"\n ? {\n async usage(sessionId: string): Promise<SessionUsageSnapshot> {\n return client.usage!(sessionId)\n },\n }\n : {}),\n\n async close(): Promise<void> {\n await client.close()\n },\n }\n}\n\n/**\n * `session_monitor` long-polls cap at 49s; loop past timeouts for longer\n * turns. A clean timeout comes back as `{ timedOut: true, sessionIds }` —\n * there is no `event: \"timeout\"` on the wire, `event` is only ever set on a\n * real match. Keep polling while `timedOut` is true; stop once it's\n * falsy/absent (a real turn-end/awaiting-input/exited match). `since` is\n * reused unchanged across retries — a timeout means nothing has matched\n * since that cursor yet, so there is nothing to advance.\n */\nasync function waitForSettled(client: DaemonClient, sessionId: string, since: number): Promise<void> {\n for (;;) {\n const result = await client.waitForAny([sessionId], { event: \"any\", timeoutMs: MAX_POLL_MS, since })\n if (!result.timedOut) return\n }\n}\n"]}
@@ -26,7 +26,9 @@ var provisionWorktreeTool = defineTool({
26
26
  mode: z.enum(["create", "append"]).optional().describe("'create' (default): write only if path doesn't already exist. 'append': always append (creating if missing); if git tracks the path, it's marked skip-worktree afterwards so the change never shows as a local modification.")
27
27
  })
28
28
  ).optional().describe("Files written into the worktree before depsCmd runs, e.g. a package-manager config generated for this specific worktree."),
29
- runSetup: z.boolean().optional().describe("Read the base tree's agentproto.json and apply its declarative worktree lifecycle: `worktree.depsCmd`/`worktree.linkPaths` as fallbacks for the inputs above, then the `worktree.setup` hooks after creation. Default true; a failing setup hook fails provisioning.")
29
+ runSetup: z.boolean().optional().describe("Read the base tree's agentproto.json and apply its declarative worktree lifecycle: `worktree.depsCmd`/`worktree.linkPaths` as fallbacks for the inputs above, then the `worktree.setup` hooks after creation. Default true; a failing setup hook fails provisioning."),
30
+ setupLogPath: z.string().optional().describe("Absolute path to append the FULL, unfiltered stdout+stderr of every `worktree.setup` hook command to (success or failure). Caller-provided \u2014 typically a path under the spawning session's own directory, so the full output outlives a subsequently-reclaimed worktree. Best-effort: a write failure never fails provisioning. When omitted, only a short, noise-filtered tail survives in a failing hook's own error message."),
31
+ retrySetupOnFailure: z.boolean().optional().describe("Re-run a failing `worktree.setup` command exactly once before giving up \u2014 a complement to (never a substitute for) a real root-cause fix, meant for unattended callers with no way to retry themselves short of provisioning an entirely new worktree. Default false: an interactive caller (e.g. `agentproto worktree new`) sees a genuine failure on the first try rather than waiting through an identical rerun.")
30
32
  }),
31
33
  outputSchema: z.object({
32
34
  cwd: z.string().describe("Absolute path to the created worktree."),
@@ -158,5 +160,5 @@ var listServicesTool = defineTool({
158
160
  });
159
161
 
160
162
  export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool };
161
- //# sourceMappingURL=chunk-IKCBL2UN.mjs.map
162
- //# sourceMappingURL=chunk-IKCBL2UN.mjs.map
163
+ //# sourceMappingURL=chunk-EK5BH2YL.mjs.map
164
+ //# sourceMappingURL=chunk-EK5BH2YL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/provision-worktree.tool.ts","../src/tools/cleanup-worktree.tool.ts","../src/tools/run-gate.tool.ts","../src/tools/run-script.tool.ts","../src/tools/service.schema.ts","../src/tools/start-service.tool.ts","../src/tools/stop-service.tool.ts","../src/tools/list-services.tool.ts"],"names":["defineTool","z"],"mappings":";;;;;;;;AAQO,IAAM,wBAAwB,UAAA,CAAW;AAAA,EAC9C,EAAA,EAAI,oBAAA;AAAA,EACJ,WAAA,EACE,q6DAAA;AAAA,EA6BF,OAAA,EAAS,OAAA;AAAA,EACT,WAAA,EAAa,EAAE,MAAA,CAAO;AAAA,IACpB,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,2CAA2C,CAAA;AAAA,IACzE,MAAM,CAAA,CACH,MAAA,GACA,QAAA,EAAS,CACT,SAAS,wDAAwD,CAAA;AAAA,IACpE,IAAA,EAAM,EACH,MAAA,EAAO,CACP,MAAM,sBAAA,EAAwB,mCAAmC,CAAA,CACjE,QAAA,CAAS,2EAAsE,CAAA;AAAA,IAClF,QAAQ,CAAA,CACL,MAAA,GACA,QAAA,EAAS,CACT,SAAS,wDAAwD,CAAA;AAAA,IACpE,KAAK,CAAA,CACF,MAAA,GACA,QAAA,EAAS,CACT,SAAS,gFAAgF,CAAA;AAAA,IAC5F,SAAS,CAAA,CACN,MAAA,GACA,QAAA,EAAS,CACT,SAAS,6FAA6F,CAAA;AAAA,IACzG,SAAA,EAAW,CAAA,CACR,KAAA,CAAM,CAAA,CAAE,MAAA,EAAQ,CAAA,CAChB,QA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EACT,WAAA,EAAaC,EAAE,MAAA,CAAO;AAAA,IACpB,QAAA,EAAUA,CAAAA,CAAE,MAAA,EAAO,CAAE,SAAS,kDAAkD,CAAA;AAAA,IAChF,YAAA,EAAcA,CAAAA,CAAE,MAAA,EAAO,CAAE,SAAS,gCAAgC,CAAA;AAAA,IAClE,MAAA,EAAQA,CAAAA,CAAE,MAAA,EAAO,CAAE,SAAS,6BAA6B,CAAA;AAAA,IACzD,MAAMA,CAAAA,CAAE,MAAA,GAAS,QAAA,EAAS,CAAE,SAAS,qEAAqE,CAAA;AAAA,IAC1G,SAAA,EAAWA,CAAAA,CAAE,MAAA,EAAO,CAAE,KAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,QAAA,EAAS,CAAE,SAAS,gDAAgD;AAAA,GACnH,CAAA;AAAA,EACD,YAAA,EAAcA,EAAE,MAAA,CAAO;AAAA,IACrB,QAAA,EAAUA,CAAAA,CAAE,KAAA,CAAM,mBAAmB;AAAA,GACtC,CAAA;AAAA,EACD,SAAS,EAAC;AAAA,EACV,QAAA,EAAU,MAAA;AAAA,EACV,SAAA,EAAW;AACb,CAAC","file":"chunk-EK5BH2YL.mjs","sourcesContent":["import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: create a git worktree off a base ref, on its own branch,\n * optionally installing deps and copying gitignored files (secrets) into it.\n * Agnostic — no hardcoded package manager or env layout; both are inputs.\n */\nexport const provisionWorktreeTool = defineTool({\n id: \"worktree.provision\",\n description:\n \"Create a git worktree for `repoRoot` at a sibling '_worktrees/<slug>' \" +\n \"directory (or `dir`, when given), on a new branch 'wt/<slug>' (or \" +\n \"`branch`, when given) cut from `base`. If `depsCmd` is given, it runs \" +\n \"inside the new worktree afterwards (e.g. install deps). If `copyGlobs` \" +\n \"is given, matching files under `repoRoot` (including gitignored ones, \" +\n \"e.g. local secrets) are copied into the worktree at the same relative \" +\n \"path. If `linkPaths` is given, each is symlinked from `repoRoot` into \" +\n \"the worktree before `depsCmd` runs — for gitignored, expensive-to-\" +\n \"recreate trees a fresh worktree lacks (node_modules, sibling workspace \" +\n \"repos) so the workspace graph resolves without a full reinstall. When \" +\n \"`depsCmd`/`linkPaths` are omitted, they fall back to `worktree.depsCmd`/\" +\n \"`worktree.linkPaths` declared in the base tree's agentproto.json (same \" +\n \"`runSetup` gate as the setup hooks below) — an explicit input always \" +\n \"wins over the declarative default. If \" +\n \"`writeFiles` is given, each entry's `content` is written into the \" +\n \"worktree at `path` before `depsCmd` runs — for generated, worktree-\" +\n \"specific config a tool invoked by `depsCmd` needs to see (e.g. a \" +\n \"package-manager config pointing a cache/store dir outside the \" +\n \"worktree, so it isn't shared with — or clobbered by — a sibling \" +\n \"worktree). `mode: \\\"create\\\"` (default) skips an entry whose path \" +\n \"already exists, matching `linkPaths`' never-clobber rule; \" +\n \"`mode: \\\"append\\\"` always appends (creating the file if missing) and, \" +\n \"if git already tracks that path, marks it `skip-worktree` afterwards \" +\n \"so the tweak never shows up as a local modification the caller could \" +\n \"accidentally commit — callers are responsible for making the content \" +\n \"itself idempotent (e.g. checking `repoRoot`'s copy of the file for the \" +\n \"line before including the entry, since a fresh worktree's tracked \" +\n \"files start as a byte-identical checkout). Also writes a creation-\" +\n \"provenance marker into the worktree's private gitdir.\",\n version: \"0.2.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the git repository root.\"),\n base: z\n .string()\n .optional()\n .describe(\"Ref the new branch is cut from. Default 'origin/main'.\"),\n slug: z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"slug must be lowercase kebab-case\")\n .describe(\"Short identifier — names both the worktree directory and its branch.\"),\n branch: z\n .string()\n .optional()\n .describe(\"Branch name for the new worktree. Default 'wt/<slug>'.\"),\n dir: z\n .string()\n .optional()\n .describe(\"Absolute path for the new worktree. Default '<repoRoot>/../_worktrees/<slug>'.\"),\n depsCmd: z\n .string()\n .optional()\n .describe(\"Shell command run inside the worktree after creation, e.g. 'pnpm install --prefer-offline'.\"),\n copyGlobs: z\n .array(z.string())\n .optional()\n .describe(\"Glob patterns (relative to repoRoot) of gitignored files to copy into the worktree, e.g. 'envs/**/.env.local'.\"),\n linkPaths: z\n .array(z.string())\n .optional()\n .describe(\"Relative paths (dirs or files) symlinked from repoRoot into the worktree before depsCmd, e.g. 'node_modules' or a gitignored sibling workspace repo. Lets the workspace graph resolve without a full reinstall.\"),\n writeFiles: z\n .array(\n z.object({\n path: z.string().describe(\"Path relative to the worktree root.\"),\n content: z.string().describe(\"File content, written or appended verbatim.\"),\n mode: z\n .enum([\"create\", \"append\"])\n .optional()\n .describe(\"'create' (default): write only if path doesn't already exist. 'append': always append (creating if missing); if git tracks the path, it's marked skip-worktree afterwards so the change never shows as a local modification.\"),\n }),\n )\n .optional()\n .describe(\"Files written into the worktree before depsCmd runs, e.g. a package-manager config generated for this specific worktree.\"),\n runSetup: z\n .boolean()\n .optional()\n .describe(\"Read the base tree's agentproto.json and apply its declarative worktree lifecycle: `worktree.depsCmd`/`worktree.linkPaths` as fallbacks for the inputs above, then the `worktree.setup` hooks after creation. Default true; a failing setup hook fails provisioning.\"),\n setupLogPath: z\n .string()\n .optional()\n .describe(\"Absolute path to append the FULL, unfiltered stdout+stderr of every `worktree.setup` hook command to (success or failure). Caller-provided — typically a path under the spawning session's own directory, so the full output outlives a subsequently-reclaimed worktree. Best-effort: a write failure never fails provisioning. When omitted, only a short, noise-filtered tail survives in a failing hook's own error message.\"),\n retrySetupOnFailure: z\n .boolean()\n .optional()\n .describe(\"Re-run a failing `worktree.setup` command exactly once before giving up — a complement to (never a substitute for) a real root-cause fix, meant for unattended callers with no way to retry themselves short of provisioning an entirely new worktree. Default false: an interactive caller (e.g. `agentproto worktree new`) sees a genuine failure on the first try rather than waiting through an identical rerun.\"),\n }),\n outputSchema: z.object({\n cwd: z.string().describe(\"Absolute path to the created worktree.\"),\n branch: z.string().describe(\"The branch the worktree was created on.\"),\n }),\n mutates: [\"fs:write\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: remove a git worktree, optionally deleting its branch.\n *\n * Guarded by default (PLAN.md §5.2 layer 3): with neither discard flag set,\n * this runs a plain `git worktree remove` — git itself is the final arbiter\n * and refuses on modified or unignored-untracked files, tolerating gitignored\n * trees like `node_modules/`. `discardUntracked` / `discardModified` each\n * authorize exactly one class of destruction git otherwise refuses; only\n * when the flags cover everything actually dirty does `--force` get passed\n * through. This replaces an unconditional `--force` that used to destroy\n * real edits indiscriminately (the incident this contract change exists to\n * prevent) — hence `riskLevel: 2`, up from the old unconditional-force `1`.\n */\nexport const cleanupWorktreeTool = defineTool({\n id: \"worktree.cleanup\",\n description:\n \"Remove a git worktree created by 'worktree.provision'. Refuses if the \" +\n \"worktree has modified tracked files or unignored untracked files, \" +\n \"unless the matching `discardModified` / `discardUntracked` flag is \" +\n \"set — a clean or gitignore-only tree (e.g. installed deps) always \" +\n \"removes with no flags. If `deleteBranch` is true and `branch` is \" +\n \"given, also force-delete that branch (only ever called for merged \" +\n \"branches by this package's own callers).\",\n version: \"0.2.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the git repository root.\"),\n cwd: z.string().describe(\"Absolute path to the worktree to remove.\"),\n branch: z.string().optional().describe(\"The worktree's branch, for deleteBranch.\"),\n deleteBranch: z.boolean().optional().describe(\"Also force-delete `branch` after removing the worktree.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json supplies teardown hooks. Default 'origin/main'.\"),\n runTeardown: z.boolean().optional().describe(\"Run the `worktree.teardown` hooks before removal. Default true; teardown failures are logged, never blocking.\"),\n discardUntracked: z.boolean().optional().describe(\"Authorize discarding unignored untracked files. Default false: refuse if any are present.\"),\n discardModified: z.boolean().optional().describe(\"Authorize discarding modified tracked files (staged or unstaged). Default false: refuse if any are present.\"),\n }),\n outputSchema: z.object({\n removed: z.literal(true),\n }),\n mutates: [\"fs:write\"],\n approval: \"auto\",\n riskLevel: 2,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: run a caller-provided gate/check command inside a\n * directory (typically a provisioned worktree) and report pass/fail.\n * `cmd` is a trusted, developer-authored config value (same trust model as\n * a CI job's `script:` line), run through a shell so it may include flags.\n */\nexport const runGateTool = defineTool({\n id: \"worktree.run-gate\",\n description:\n \"Run a gate command (e.g. 'pnpm test') inside `cwd` and report pass/fail \" +\n \"from its exit code, along with captured stdout/stderr.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n cwd: z.string().describe(\"Directory to run the command in.\"),\n cmd: z.string().describe(\"Shell command to run, e.g. 'pnpm test'.\"),\n }),\n outputSchema: z.object({\n passed: z.boolean(),\n exitCode: z.number().int(),\n stdout: z.string(),\n stderr: z.string(),\n }),\n mutates: [],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/**\n * AIP-14 contract: run a one-shot named `scripts.<name>` command from the\n * repo's committed `agentproto.json` inside a worktree, with the\n * `AGENTPROTO_*` context env injected. For long-running services use\n * `worktree.start-service` instead.\n */\nexport const runScriptTool = defineTool({\n id: \"worktree.run-script\",\n description:\n \"Run a declared `scripts.<name>` command (from the base tree's \" +\n \"agentproto.json) inside `worktreePath`, injecting AGENTPROTO_* env, and \" +\n \"report pass/fail with captured stdout/stderr. For a `type: \\\"service\\\"` \" +\n \"script prefer `worktree.start-service`.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the source git repository root.\"),\n worktreePath: z.string().describe(\"Absolute path to the worktree to run in.\"),\n branch: z.string().describe(\"The worktree's branch name (for AGENTPROTO_BRANCH_NAME).\"),\n script: z.string().describe(\"Name of the script under `scripts` to run.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json is read. Default 'origin/main'.\"),\n }),\n outputSchema: z.object({\n passed: z.boolean(),\n exitCode: z.number().int(),\n stdout: z.string(),\n stderr: z.string(),\n }),\n mutates: [\"fs:write\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\n\n/** Shared shape of a supervised service's status across the service tools. */\nexport const serviceStatusSchema = z.object({\n name: z.string().describe(\"The declared script name.\"),\n hostname: z.string().describe(\"The *.localhost host the reverse proxy routes to this service.\"),\n port: z.number().int().describe(\"The port the service listens on.\"),\n url: z.string().describe(\"The service's reverse-proxy URL.\"),\n pid: z.number().int().nullable().describe(\"Child process id while running, else null.\"),\n status: z.enum([\"running\", \"exited\"]).describe(\"Whether the service process is up.\"),\n exitCode: z.number().int().nullable().describe(\"Exit code once it has exited, else null.\"),\n startedAt: z.string().nullable().describe(\"ISO timestamp of the last start, else null.\"),\n})\n\nexport type ServiceStatusOutput = z.infer<typeof serviceStatusSchema>\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\nimport { serviceStatusSchema } from \"./service.schema.js\"\n\n/**\n * AIP-14 contract: start a declared `type: \"service\"` script for a worktree.\n * Allocates the service's port (declared port if free, else ephemeral),\n * injects AGENTPROTO_PORT/URL + peer env, and registers its hostname with the\n * reverse proxy. Idempotent per worktree+name.\n */\nexport const startServiceTool = defineTool({\n id: \"worktree.start-service\",\n description:\n \"Start a declared `scripts.<name>` service for a worktree as a supervised \" +\n \"long-running child process. Allocates a port, injects AGENTPROTO_PORT / \" +\n \"AGENTPROTO_URL and AGENTPROTO_SERVICE_<PEER>_PORT|URL for siblings, and \" +\n \"registers a `<script>--<branch>--<repo>.localhost` proxy route.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the source git repository root.\"),\n worktreePath: z.string().describe(\"Absolute path to the worktree.\"),\n branch: z.string().describe(\"The worktree's branch name.\"),\n script: z.string().describe(\"Name of the `type: \\\"service\\\"` script to start.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json is read. Default 'origin/main'.\"),\n proxyPort: z.number().int().min(1).max(65535).optional().describe(\"Reverse-proxy port used to build the service URL.\"),\n }),\n outputSchema: serviceStatusSchema,\n mutates: [\"process:spawn\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\n\n/** AIP-14 contract: stop a running supervised service for a worktree. */\nexport const stopServiceTool = defineTool({\n id: \"worktree.stop-service\",\n description:\n \"Stop a supervised service (SIGTERM) for a worktree and drop its reverse-\" +\n \"proxy route. A no-op (stopped: false) if the service isn't running.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n worktreePath: z.string().describe(\"Absolute path to the worktree.\"),\n script: z.string().describe(\"Name of the service to stop.\"),\n }),\n outputSchema: z.object({\n stopped: z.boolean().describe(\"Whether a running service was actually stopped.\"),\n }),\n mutates: [\"process:spawn\"],\n approval: \"auto\",\n riskLevel: 1,\n})\n","import { z } from \"zod\"\nimport { defineTool } from \"@agentproto/tool\"\nimport { serviceStatusSchema } from \"./service.schema.js\"\n\n/**\n * AIP-14 contract: list every declared service for a worktree with its\n * resolved port / proxy URL and current run status. Resolves (allocating\n * ports for) the worktree's services on first call so declared-but-unstarted\n * services still appear.\n */\nexport const listServicesTool = defineTool({\n id: \"worktree.list-services\",\n description:\n \"List the declared services for a worktree — each with its allocated \" +\n \"port, `*.localhost` proxy URL, and running/exited status.\",\n version: \"0.1.0\",\n inputSchema: z.object({\n repoRoot: z.string().describe(\"Absolute path to the source git repository root.\"),\n worktreePath: z.string().describe(\"Absolute path to the worktree.\"),\n branch: z.string().describe(\"The worktree's branch name.\"),\n base: z.string().optional().describe(\"Ref whose committed agentproto.json is read. Default 'origin/main'.\"),\n proxyPort: z.number().int().min(1).max(65535).optional().describe(\"Reverse-proxy port used to build service URLs.\"),\n }),\n outputSchema: z.object({\n services: z.array(serviceStatusSchema),\n }),\n mutates: [],\n approval: \"auto\",\n riskLevel: 0,\n})\n"]}
@@ -1,12 +1,13 @@
1
- import { provisionWorktreeTool, cleanupWorktreeTool, runGateTool, runScriptTool, startServiceTool, stopServiceTool, listServicesTool } from './chunk-IKCBL2UN.mjs';
1
+ import { provisionWorktreeTool, cleanupWorktreeTool, runGateTool, runScriptTool, startServiceTool, stopServiceTool, listServicesTool } from './chunk-EK5BH2YL.mjs';
2
2
  import { implementTool, defineDriver } from '@agentproto/driver';
3
3
  import { randomUUID } from 'crypto';
4
- import { lstat, mkdir, symlink, appendFile, writeFile, copyFile, readdir, stat, readFile } from 'fs/promises';
5
- import { resolve, join, dirname, posix, basename, sep } from 'path';
4
+ import { lstat, mkdir, symlink, appendFile, writeFile, copyFile, rename, readdir, stat, readFile } from 'fs/promises';
5
+ import { resolve, join, dirname, basename, posix, sep } from 'path';
6
6
  import { ToolError } from '@agentproto/tool';
7
7
  import { spawn } from 'child_process';
8
8
  import { z } from 'zod';
9
9
  import { homedir } from 'os';
10
+ import { existsSync, mkdirSync, realpathSync, readdirSync } from 'fs';
10
11
  import { createServer } from 'net';
11
12
 
12
13
  /**
@@ -232,38 +233,78 @@ function resolveWorktreesTurboCacheDir() {
232
233
  }
233
234
 
234
235
  // src/lifecycle.ts
236
+ var NOISE_LINE_RES = [
237
+ /Failed to replace env in config: \$\{NODE_AUTH_TOKEN\}/,
238
+ /^\s*WARN\s+Issue while reading ".*\.npmrc"\.?\s*$/
239
+ ];
240
+ function filteredTail(result) {
241
+ const combined = [result.stdout, result.stderr].filter(Boolean).join("\n");
242
+ const lines = combined.split("\n").filter((line) => !NOISE_LINE_RES.some((re) => re.test(line)));
243
+ const tail = lines.slice(-60).join("\n").trim();
244
+ return tail || "(no output captured)";
245
+ }
235
246
  var HookError = class extends Error {
236
247
  command;
237
248
  result;
238
- constructor(phase, run) {
249
+ /** Path to the full, unfiltered stdout+stderr log for this and every
250
+ * other hook command in the same run, when the caller asked for one to
251
+ * be persisted (see {@link runSetup}'s `opts.logPath`). */
252
+ logPath;
253
+ constructor(phase, run, logPath) {
239
254
  super(
240
255
  `worktree ${phase} hook failed (exit ${run.result.exitCode}): ${run.command}
241
- ` + (run.result.stderr || run.result.stdout).trim()
256
+ ` + filteredTail(run.result) + (logPath ? `
257
+
258
+ (full hook output: ${logPath})` : "")
242
259
  );
243
260
  this.name = "HookError";
244
261
  this.command = run.command;
245
262
  this.result = run.result;
263
+ if (logPath !== void 0) this.logPath = logPath;
246
264
  }
247
265
  };
248
- async function runSetup(config, ctx) {
266
+ async function appendHookLog(logPath, command, result) {
267
+ if (!logPath) return;
268
+ try {
269
+ await mkdir(dirname(logPath), { recursive: true });
270
+ const parts = [
271
+ `$ ${command}`,
272
+ result.stdout,
273
+ result.stderr,
274
+ `(exit ${result.exitCode})`,
275
+ ""
276
+ ].filter(Boolean);
277
+ await appendFile(logPath, parts.join("\n") + "\n", "utf8");
278
+ } catch {
279
+ }
280
+ }
281
+ async function runSetup(config, ctx, opts = {}) {
249
282
  const commands = normalizeHook(config.worktree?.setup);
250
283
  const runs = [];
251
284
  const env = { ...hookEnv(ctx), TURBO_CACHE_DIR: resolveWorktreesTurboCacheDir() };
252
285
  for (const command of commands) {
253
- const result = await execShell(command, ctx.worktreePath, { env });
254
- const run = { command, result };
286
+ let result = await execShell(command, ctx.worktreePath, { env });
287
+ let run = { command, result };
255
288
  runs.push(run);
256
- if (result.exitCode !== 0) throw new HookError("setup", run);
289
+ await appendHookLog(opts.logPath, command, result);
290
+ if (result.exitCode !== 0 && opts.retryOnFailure) {
291
+ result = await execShell(command, ctx.worktreePath, { env });
292
+ run = { command, result };
293
+ runs.push(run);
294
+ await appendHookLog(opts.logPath, `${command} (retry 1/1)`, result);
295
+ }
296
+ if (result.exitCode !== 0) throw new HookError("setup", run, opts.logPath);
257
297
  }
258
298
  return runs;
259
299
  }
260
- async function runTeardown(config, ctx) {
300
+ async function runTeardown(config, ctx, opts = {}) {
261
301
  const commands = normalizeHook(config.worktree?.teardown);
262
302
  const runs = [];
263
303
  const env = hookEnv(ctx);
264
304
  for (const command of commands) {
265
305
  const result = await execShell(command, ctx.worktreePath, { env });
266
306
  runs.push({ command, result });
307
+ await appendHookLog(opts.logPath, command, result);
267
308
  }
268
309
  return runs;
269
310
  }
@@ -456,11 +497,18 @@ var provisionWorktreeBuiltin = implementTool(
456
497
  }
457
498
  if (config) {
458
499
  try {
459
- await runSetup(config, {
460
- sourceCheckoutPath: input.repoRoot,
461
- worktreePath: cwd,
462
- branchName: branch
463
- });
500
+ await runSetup(
501
+ config,
502
+ {
503
+ sourceCheckoutPath: input.repoRoot,
504
+ worktreePath: cwd,
505
+ branchName: branch
506
+ },
507
+ {
508
+ ...input.setupLogPath ? { logPath: input.setupLogPath } : {},
509
+ ...input.retrySetupOnFailure ? { retryOnFailure: true } : {}
510
+ }
511
+ );
464
512
  } catch (err) {
465
513
  if (err instanceof HookError) {
466
514
  throw new ToolError({ code: "execution_failed", message: err.message });
@@ -471,6 +519,86 @@ var provisionWorktreeBuiltin = implementTool(
471
519
  return { cwd, branch };
472
520
  }
473
521
  );
522
+ var WORKTREE_TRASH_DIRNAME = ".trash";
523
+ function realOrResolved(path) {
524
+ try {
525
+ return realpathSync(path);
526
+ } catch {
527
+ return path;
528
+ }
529
+ }
530
+ async function removeWorktreeFast(repoRoot, path, options = {}) {
531
+ const force = options.force === true;
532
+ if (!force) {
533
+ const status = await execArgv(
534
+ "git",
535
+ ["-C", path, "status", "--porcelain=v2", "--ignored=matching"],
536
+ repoRoot
537
+ );
538
+ if (status.exitCode !== 0) {
539
+ throw new Error(
540
+ `git status failed in ${path} (exit ${status.exitCode}): ${status.stderr.trim() || status.stdout.trim()}`
541
+ );
542
+ }
543
+ if (status.stdout.trim().length > 0) {
544
+ const probe = await execArgv("git", ["-C", repoRoot, "worktree", "remove", path], repoRoot);
545
+ if (probe.exitCode !== 0) {
546
+ throw new Error(
547
+ `git worktree remove failed (exit ${probe.exitCode}): ${probe.stderr.trim() || probe.stdout.trim()}`
548
+ );
549
+ }
550
+ await execGit(repoRoot, ["worktree", "prune"]);
551
+ return;
552
+ }
553
+ }
554
+ const list = await execArgv("git", ["-C", repoRoot, "worktree", "list", "--porcelain"], repoRoot);
555
+ if (list.exitCode !== 0) {
556
+ throw new Error(
557
+ `git worktree list failed (exit ${list.exitCode}): ${list.stderr.trim() || list.stdout.trim()}`
558
+ );
559
+ }
560
+ const registered = new Set(
561
+ list.stdout.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length).trim())
562
+ );
563
+ const registeredReal = new Set([...registered].map(realOrResolved));
564
+ if (!registeredReal.has(realOrResolved(path))) {
565
+ throw new Error(`not a linked worktree of ${repoRoot}: ${path}`);
566
+ }
567
+ const poolDir = join(path, "..");
568
+ const stamp = (options.now ?? Date.now)();
569
+ const trashDir = join(poolDir, WORKTREE_TRASH_DIRNAME, `${basename(path)}-${stamp}`);
570
+ try {
571
+ if (!existsSync(join(poolDir, WORKTREE_TRASH_DIRNAME))) {
572
+ mkdirSync(join(poolDir, WORKTREE_TRASH_DIRNAME));
573
+ }
574
+ await rename(path, trashDir);
575
+ } catch {
576
+ await execGit(repoRoot, force ? ["worktree", "remove", "--force", path] : ["worktree", "remove", path]);
577
+ return;
578
+ }
579
+ await execGit(repoRoot, ["worktree", "prune"]);
580
+ if (options.spawnRemoval) {
581
+ options.spawnRemoval(trashDir);
582
+ } else {
583
+ spawn("rm", ["-rf", trashDir], { detached: true, stdio: "ignore" }).unref();
584
+ }
585
+ }
586
+ function sweepWorktreeTrash(root, options = {}) {
587
+ let names;
588
+ try {
589
+ names = readdirSync(join(root, WORKTREE_TRASH_DIRNAME));
590
+ } catch {
591
+ return;
592
+ }
593
+ for (const name of names) {
594
+ const trashDir = join(root, WORKTREE_TRASH_DIRNAME, name);
595
+ if (options.spawnRemoval) {
596
+ options.spawnRemoval(trashDir);
597
+ } else {
598
+ spawn("rm", ["-rf", trashDir], { detached: true, stdio: "ignore" }).unref();
599
+ }
600
+ }
601
+ }
474
602
  function isPortFree(port) {
475
603
  return new Promise((resolve5) => {
476
604
  const server = createServer();
@@ -769,6 +897,7 @@ async function computeTreeState(repoRoot, worktreePath, options = {}) {
769
897
  );
770
898
  }
771
899
  const noise = [];
900
+ const dirtyPaths = [];
772
901
  let modified = 0;
773
902
  let staged = 0;
774
903
  let untracked = 0;
@@ -779,6 +908,7 @@ async function computeTreeState(repoRoot, worktreePath, options = {}) {
779
908
  noise.push(path);
780
909
  continue;
781
910
  }
911
+ if (path !== null) dirtyPaths.push(path);
782
912
  if (line.startsWith("? ")) {
783
913
  untracked++;
784
914
  continue;
@@ -790,12 +920,14 @@ async function computeTreeState(repoRoot, worktreePath, options = {}) {
790
920
  }
791
921
  }
792
922
  if (modified === 0 && staged === 0 && untracked === 0) return noise.length > 0 ? { state: "clean", noise } : { state: "clean" };
923
+ const onlyUnder = dirtyPaths.length > 0 && dirtyPaths.every((p) => p.startsWith(".plans/")) ? ".plans/" : void 0;
793
924
  return {
794
925
  state: "dirty",
795
926
  modified,
796
927
  staged,
797
928
  untracked,
798
- newestMtimeMs: await newestDirtyMtimeMs(repoRoot, worktreePath)
929
+ newestMtimeMs: await newestDirtyMtimeMs(repoRoot, worktreePath),
930
+ ...onlyUnder ? { onlyUnder } : {}
799
931
  };
800
932
  }
801
933
  async function newestDirtyMtimeMs(repoRoot, worktreePath) {
@@ -1062,6 +1194,7 @@ function classify(tree, integration, liveness, nowMs = Date.now()) {
1062
1194
  const idleOrUnreachable = liveness.state === "idle" || liveness.state === "daemon-unreachable";
1063
1195
  if ((merged || fresh) && clean && idleOrUnreachable) return { reclaimable: true, class: "reclaim" };
1064
1196
  if (merged && !clean) {
1197
+ if (!idleOrUnreachable) return { reclaimable: false, class: "hold" };
1065
1198
  const writtenRecently = tree.state === "dirty" && typeof tree.newestMtimeMs === "number" && nowMs - tree.newestMtimeMs < RECENT_WRITE_HOLD_WINDOW_MS;
1066
1199
  if (writtenRecently) return { reclaimable: false, class: "hold" };
1067
1200
  return { reclaimable: false, class: "salvage" };
@@ -1189,13 +1322,13 @@ var cleanupWorktreeBuiltin = implementTool(
1189
1322
  if (tree.untracked > 0 && !discardUntracked) blocked.push("untracked");
1190
1323
  if ((tree.modified > 0 || tree.staged > 0) && !discardModified) blocked.push("modified");
1191
1324
  if (blocked.length > 0) throw new WorktreeNotRemovableError(input.cwd, blocked);
1192
- await execGit(input.repoRoot, ["worktree", "remove", "--force", input.cwd]);
1325
+ await removeWorktreeFast(input.repoRoot, input.cwd, { force: true });
1193
1326
  } else {
1194
- await execGit(input.repoRoot, ["worktree", "remove", input.cwd]);
1327
+ await removeWorktreeFast(input.repoRoot, input.cwd);
1195
1328
  }
1196
1329
  } else {
1197
1330
  try {
1198
- await execGit(input.repoRoot, ["worktree", "remove", input.cwd]);
1331
+ await removeWorktreeFast(input.repoRoot, input.cwd);
1199
1332
  } catch (err) {
1200
1333
  throw new WorktreeNotRemovableError(input.cwd, [], err instanceof Error ? err.message : String(err));
1201
1334
  }
@@ -1287,6 +1420,6 @@ var worktreeProvider = defineDriver({
1287
1420
  ]
1288
1421
  });
1289
1422
 
1290
- export { CONFIG_FILENAME, ConfigError, DEFAULT_PROXY_PORT, ENV_VARS, FileVerdictMemoStore, HookError, InMemoryVerdictMemoStore, ProxyTable, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, ServiceSupervisor, VERDICT_MEMO_PATH, WORKTREES_TURBO_CACHE_DIR_ENV, WorktreeNotRemovableError, allocatePort, classify, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, normalizeHook, parseConfig, peerEnv, peerEnvKey, readSessionsRegistry, readWorktreeMarker, reconcileIntegration, repoLabel, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, stripPort, worktreeProvider, writeWorktreeMarker };
1291
- //# sourceMappingURL=chunk-KRQFVJPK.mjs.map
1292
- //# sourceMappingURL=chunk-KRQFVJPK.mjs.map
1423
+ export { CONFIG_FILENAME, ConfigError, DEFAULT_PROXY_PORT, ENV_VARS, FileVerdictMemoStore, HookError, InMemoryVerdictMemoStore, ProxyTable, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, ServiceSupervisor, VERDICT_MEMO_PATH, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, WorktreeNotRemovableError, allocatePort, classify, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, normalizeHook, parseConfig, peerEnv, peerEnvKey, readSessionsRegistry, readWorktreeMarker, reconcileIntegration, removeWorktreeFast, repoLabel, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, stripPort, sweepWorktreeTrash, worktreeProvider, writeWorktreeMarker };
1424
+ //# sourceMappingURL=chunk-EVHLUKC7.mjs.map
1425
+ //# sourceMappingURL=chunk-EVHLUKC7.mjs.map