@agentproto/worktree 0.12.0 → 0.13.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 +1 @@
1
- {"version":3,"sources":["../src/workflow.ts","../src/agent-session-host.ts"],"names":[],"mappings":";;;;;;;;;AASO,IAAM,wBAAA,GAA2B,EAAE,MAAA,CAAO;AAAA,EAC/C,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,2CAA2C,CAAA;AAAA,EACzE,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,oDAAoD,CAAA;AAAA,EAC9E,MAAM,CAAA,CAAE,MAAA,GAAS,QAAA,EAAS,CAAE,SAAS,6DAA6D,CAAA;AAAA,EAClG,SAAS,CAAA,CAAE,MAAA,GAAS,QAAA,EAAS,CAAE,SAAS,oFAAoF,CAAA;AAAA,EAC5H,SAAA,EAAW,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,QAAA,EAAS,CAAE,QAAA,CAAS,2DAA2D,CAAA;AAAA,EAC9G,SAAA,EAAW,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,QAAA,EAAS,CAAE,QAAA,CAAS,6KAA6K,CAAA;AAAA,EAChO,YAAY,CAAA,CACT,KAAA;AAAA,IACC,EAAE,MAAA,CAAO;AAAA,MACP,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,qCAAqC,CAAA;AAAA,MAC/D,OAAA,EAAS,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,6CAA6C,CAAA;AAAA,MAC1E,IAAA,EAAM,CAAA,CACH,IAAA,CAAK,CAAC,QAAA,EAAU,QAAQ,CAAC,CAAA,CACzB,QAAA,EAAS,CACT,QAAA,CAAS,4KAA4K;AAAA,KACzL;AAAA,GACH,CACC,QAAA,EAAS,CACT,QAAA,CAAS,0HAA0H,CAAA;AAAA,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.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\", timeoutMs: MAX_POLL_MS, since })\n if (!result.timedOut) return\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/workflow.ts","../src/agent-session-host.ts"],"names":[],"mappings":";;;;;;;;;AASO,IAAM,wBAAA,GAA2B,EAAE,MAAA,CAAO;AAAA,EAC/C,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,2CAA2C,CAAA;AAAA,EACzE,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,oDAAoD,CAAA;AAAA,EAC9E,MAAM,CAAA,CAAE,MAAA,GAAS,QAAA,EAAS,CAAE,SAAS,6DAA6D,CAAA;AAAA,EAClG,SAAS,CAAA,CAAE,MAAA,GAAS,QAAA,EAAS,CAAE,SAAS,oFAAoF,CAAA;AAAA,EAC5H,SAAA,EAAW,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,QAAA,EAAS,CAAE,QAAA,CAAS,2DAA2D,CAAA;AAAA,EAC9G,SAAA,EAAW,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,QAAA,EAAS,CAAE,QAAA,CAAS,6KAA6K,CAAA;AAAA,EAChO,YAAY,CAAA,CACT,KAAA;AAAA,IACC,EAAE,MAAA,CAAO;AAAA,MACP,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,qCAAqC,CAAA;AAAA,MAC/D,OAAA,EAAS,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,6CAA6C,CAAA;AAAA,MAC1E,IAAA,EAAM,CAAA,CACH,IAAA,CAAK,CAAC,QAAA,E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,EAAE,KAAA,EAAO,KAAA,EAAO,SAAA,EAAW,WAAA,EAAa,OAAO,CAAA;AACnG,IAAA,IAAI,CAAC,OAAO,QAAA,EAAU;AAAA,EACxB;AACF","file":"chunk-YMDOSMMD.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\", timeoutMs: MAX_POLL_MS, since })\n if (!result.timedOut) return\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -329,6 +329,37 @@ declare function sweepWorktreeTrash(root: string, options?: {
329
329
  declare function globToRegExp(pattern: string): RegExp;
330
330
  /** Expand a glob against `root`, returning root-relative posix paths of matching files. */
331
331
  declare function expandGlob(root: string, pattern: string): Promise<string[]>;
332
+ /** A `cloneGlobs`/`copyGlobs` pattern that could resolve outside its root — a
333
+ * leading `/`, or a literal `..` path segment. */
334
+ declare class GlobTraversalError extends Error {
335
+ constructor(pattern: string);
336
+ }
337
+ /**
338
+ * Expand a glob against `root` for CLONING a whole entry. Unlike
339
+ * {@link expandGlob} — which enumerates individual FILES and deliberately
340
+ * skips descending into `node_modules` — this matches whole entries (files
341
+ * OR directories) and never descends past a match: a matching directory is
342
+ * returned as a single unit for the caller to clone as a whole tree, so a
343
+ * pattern like `node_modules` costs one `readdir`, not a walk of everything
344
+ * inside it. `**` is not supported (a clone target must be a single named
345
+ * entry per level, not an arbitrary-depth wildcard) and throws.
346
+ *
347
+ * Throws {@link GlobTraversalError} on a pattern that could resolve outside
348
+ * `root` (a leading `/`, or any `..` segment) — checked before any
349
+ * filesystem access.
350
+ */
351
+ declare function expandCloneGlob(root: string, pattern: string): Promise<string[]>;
352
+
353
+ /**
354
+ * Clone every entry matched by `patterns` (see {@link expandCloneGlob}) from
355
+ * `repoRoot` into `cwd`, meant to run BEFORE `depsCmd` so a gitignored,
356
+ * expensive-to-recreate tree (e.g. `node_modules`) is already present when
357
+ * the package manager runs — turning `depsCmd` into a quick verify/repair
358
+ * instead of a full reinstall. Skips an entry whose destination already
359
+ * exists — same never-clobber rule `linkPaths`/`writeFiles` follow in
360
+ * `provision-worktree.body.ts`.
361
+ */
362
+ declare function cloneEntries(repoRoot: string, cwd: string, patterns: readonly string[]): Promise<void>;
332
363
 
333
364
  /**
334
365
  * `agentproto.json` — the declarative per-repo worktree lifecycle.
@@ -390,6 +421,71 @@ declare function getScript(config: AgentprotoConfig, name: string): NamedScript
390
421
  */
391
422
  declare function loadConfigFromBase(repoRoot: string, base?: string): Promise<AgentprotoConfig | null>;
392
423
 
424
+ /**
425
+ * `<workspace>/.agentproto/worktree.json` — a LOCAL, host-owned worktree
426
+ * lifecycle default, read straight off disk (never `git show`, never a
427
+ * worktree's own tree). Same idea as `<workspace>/.agentproto/allowed-
428
+ * commands.json` (`command-allowlist.ts`): a per-machine setting that lets
429
+ * one host declare what a fresh worktree needs (a `node_modules` clone, a
430
+ * per-worktree pnpm store) without committing that machine's paths into the
431
+ * repo. `.agentproto/` is gitignored repo-wide (see this repo's own
432
+ * `.gitignore`), so this file can never ride in on a branch — there is
433
+ * nothing here for `config.ts`'s "only what a reviewer merged" guarantee to
434
+ * defend against; the trust model is simply "whoever owns this machine's
435
+ * filesystem".
436
+ *
437
+ * `workspace` is the SOURCE checkout — the same directory passed as
438
+ * `provisionWorktreeTool`'s `repoRoot` — never the freshly created worktree
439
+ * (which starts with no `.agentproto/worktree.json` of its own, since the
440
+ * dir is gitignored and nothing copies it in).
441
+ */
442
+ declare const LOCAL_WORKTREE_CONFIG_REL = ".agentproto/worktree.json";
443
+ declare const localWriteFileEntrySchema: z.ZodObject<{
444
+ path: z.ZodString;
445
+ content: z.ZodString;
446
+ mode: z.ZodOptional<z.ZodEnum<{
447
+ create: "create";
448
+ append: "append";
449
+ }>>;
450
+ }, z.core.$strip>;
451
+ declare const localWorktreeConfigSchema: z.ZodObject<{
452
+ copyGlobs: z.ZodOptional<z.ZodArray<z.ZodString>>;
453
+ cloneGlobs: z.ZodOptional<z.ZodArray<z.ZodString>>;
454
+ writeFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
455
+ path: z.ZodString;
456
+ content: z.ZodString;
457
+ mode: z.ZodOptional<z.ZodEnum<{
458
+ create: "create";
459
+ append: "append";
460
+ }>>;
461
+ }, z.core.$strip>>>;
462
+ depsCmd: z.ZodOptional<z.ZodString>;
463
+ linkPaths: z.ZodOptional<z.ZodArray<z.ZodString>>;
464
+ }, z.core.$strip>;
465
+ type LocalWriteFileEntry = z.infer<typeof localWriteFileEntrySchema>;
466
+ type LocalWorktreeConfig = z.infer<typeof localWorktreeConfigSchema>;
467
+ /**
468
+ * Parse + validate raw `worktree.json` text. Throws {@link ConfigError} on
469
+ * malformed JSON or a schema violation — same failure shape as
470
+ * `config.ts`'s `parseConfig`, so callers can handle both uniformly.
471
+ */
472
+ declare function parseLocalWorktreeConfig(raw: string): LocalWorktreeConfig;
473
+ /**
474
+ * Load `<workspace>/.agentproto/worktree.json` straight off disk. Returns
475
+ * `null` when the file is absent (the common case — most workspaces don't
476
+ * opt in). Throws {@link ConfigError} on a present-but-invalid file.
477
+ */
478
+ declare function loadLocalWorktreeConfig(workspace: string): Promise<LocalWorktreeConfig | null>;
479
+ /** Substitute the literal `{slug}` token for `slug` in `text`. */
480
+ declare function applySlugPlaceholder(text: string, slug: string): string;
481
+ /**
482
+ * Resolve a local config's `writeFiles` for one concrete worktree: expands
483
+ * `{slug}` in `path`/`content` so a declarative entry (e.g. a pnpm
484
+ * `virtualStoreDir` pointed outside the worktree) can be written once and
485
+ * still land at a distinct, collision-free path per worktree.
486
+ */
487
+ declare function resolveLocalWriteFiles(files: readonly LocalWriteFileEntry[] | undefined, slug: string): LocalWriteFileEntry[];
488
+
393
489
  /**
394
490
  * Typed env surface for worktree lifecycle hooks, scripts, and services.
395
491
  *
@@ -2157,4 +2253,4 @@ declare function recordBranchVerdict(input: {
2157
2253
  now?: () => string;
2158
2254
  }): Promise<BranchVerdictRecord>;
2159
2255
 
2160
- export { type AgentprotoConfig, type ApplyBranchGcOptions, type ApplyGcOptions, BRANCH_GC_SCOPES, BRANCH_GC_STATE_DIR, BRANCH_TRIAGE_VERDICTS, BRANCH_VERDICTS_PATH, type BaseDivergence, type BranchCoverage, type BranchGcApplyOutcome, type BranchGcApplyResult, type BranchGcClass, type BranchGcHoldReason, type BranchGcPlan, type BranchGcPlanEntry, type BranchGcReclaimReason, type BranchGcRestoreEntry, type BranchGcRestoreLog, type BranchGcSummary, type BranchHistory, type BranchPushState, type BranchRef, type BranchRefKind, type BranchReviewCandidate, type BranchReviewQueue, type BranchStatus, type BranchTriageVerdict, type BranchVerdict, BranchVerdictError, type BranchVerdictRecord, type BranchVerdictStore, type BranchVerdictSummary, CONFIG_FILENAME, type Classification, type ClassifyForGcOptions, type ComputeProvenanceOptions, type ComputeTreeStateOptions, type ComputeWorktreeStatusInput, ConfigError, DEFAULT_BRANCH_GC_MIN_AGE_DAYS, DEFAULT_GC_NOISE_PATHS, DEFAULT_PROXY_PORT, type DaemonAgentSessionHost, type DaemonClient, ENV_VARS, type ExecOptions, type ExecResult, FileBranchVerdictStore, FileVerdictMemoStore, type ForgeClient, type ForgePullRequestRef, ForgeUnavailableError, type GateState, type GcApplyOutcome, type GcClass, type GcHoldReason, type GcPlanEntry, type GcReclaimReason, GhCliForgeClient, type GitWorktreeRef, HookError, type HookRun, type HostnameParts, type InBaseReclaimReason, InMemoryBranchVerdictStore, InMemoryVerdictMemoStore, type IntegrationState, type LadderContext, type ListWorktreeStatusesInput, type LivenessState, type NamedScript, type PeerService, type PlanBranchGcInput, type PlanGcInput, type ProvenanceConfidence, type ProvenanceInfo, ProxyTable, type ReconcileIntegrationInput, type RemoveWorktreeFastOptions, type ResolveGcClassOptions, type ResolveSupervisorInput, type ResolvedGcClass, type ResolvedWorktreeRuntime, RestForgeClient, type RunningProxy, SALVAGE_ROOT, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, type SalvageManifest, type SalvageResult, type SalvageWorktreeInput, type ScriptConfig, type ServiceRuntime, type ServiceStatus, ServiceSupervisor, type SessionRef, type SupervisorOptions, type TipClassification, type TreeIndex, type TreeState, UnreachableForgeClient, VERDICT_MEMO_PATH, type VerdictMemoRecord, type VerdictMemoStore, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, type WorktreeAgentInput, type WorktreeClass, type WorktreeEnvContext, type WorktreeMarker, WorktreeNotRemovableError, type WorktreeStatusEntry, allocatePort, applyBranchGc, applyGc, branchReviewQueue, branchVerdictSchema, classify, classifyForGc, classifyTip, classifyTipAgainstBase, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, connectDaemonAgentSessionHost, createForgeClient, createLadderContext, createProxyServer, detectAnchor, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isMechanicalDepBumpRange, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, makeDaemonAgentSessionHost, normalizeHook, parseConfig, parseGithubOwnerRepo, peerEnv, peerEnvKey, planBranchGc, planGc, readBranchGcRestoreLog, readSessionsRegistry, readWorktreeMarker, reclaimOneWorktree, reconcileIntegration, recordBranchVerdict, removeWorktreeFast, repoLabel, resolveGcClass, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, salvageWorktree, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, startProxy, stripPort, summarizeBranchGcPlan, sweepWorktreeTrash, worktreeAgentInputSchema, worktreeAgentWorkflow, writeWorktreeMarker };
2256
+ export { type AgentprotoConfig, type ApplyBranchGcOptions, type ApplyGcOptions, BRANCH_GC_SCOPES, BRANCH_GC_STATE_DIR, BRANCH_TRIAGE_VERDICTS, BRANCH_VERDICTS_PATH, type BaseDivergence, type BranchCoverage, type BranchGcApplyOutcome, type BranchGcApplyResult, type BranchGcClass, type BranchGcHoldReason, type BranchGcPlan, type BranchGcPlanEntry, type BranchGcReclaimReason, type BranchGcRestoreEntry, type BranchGcRestoreLog, type BranchGcSummary, type BranchHistory, type BranchPushState, type BranchRef, type BranchRefKind, type BranchReviewCandidate, type BranchReviewQueue, type BranchStatus, type BranchTriageVerdict, type BranchVerdict, BranchVerdictError, type BranchVerdictRecord, type BranchVerdictStore, type BranchVerdictSummary, CONFIG_FILENAME, type Classification, type ClassifyForGcOptions, type ComputeProvenanceOptions, type ComputeTreeStateOptions, type ComputeWorktreeStatusInput, ConfigError, DEFAULT_BRANCH_GC_MIN_AGE_DAYS, DEFAULT_GC_NOISE_PATHS, DEFAULT_PROXY_PORT, type DaemonAgentSessionHost, type DaemonClient, ENV_VARS, type ExecOptions, type ExecResult, FileBranchVerdictStore, FileVerdictMemoStore, type ForgeClient, type ForgePullRequestRef, ForgeUnavailableError, type GateState, type GcApplyOutcome, type GcClass, type GcHoldReason, type GcPlanEntry, type GcReclaimReason, GhCliForgeClient, type GitWorktreeRef, GlobTraversalError, HookError, type HookRun, type HostnameParts, type InBaseReclaimReason, InMemoryBranchVerdictStore, InMemoryVerdictMemoStore, type IntegrationState, LOCAL_WORKTREE_CONFIG_REL, type LadderContext, type ListWorktreeStatusesInput, type LivenessState, type LocalWorktreeConfig, type LocalWriteFileEntry, type NamedScript, type PeerService, type PlanBranchGcInput, type PlanGcInput, type ProvenanceConfidence, type ProvenanceInfo, ProxyTable, type ReconcileIntegrationInput, type RemoveWorktreeFastOptions, type ResolveGcClassOptions, type ResolveSupervisorInput, type ResolvedGcClass, type ResolvedWorktreeRuntime, RestForgeClient, type RunningProxy, SALVAGE_ROOT, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, type SalvageManifest, type SalvageResult, type SalvageWorktreeInput, type ScriptConfig, type ServiceRuntime, type ServiceStatus, ServiceSupervisor, type SessionRef, type SupervisorOptions, type TipClassification, type TreeIndex, type TreeState, UnreachableForgeClient, VERDICT_MEMO_PATH, type VerdictMemoRecord, type VerdictMemoStore, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, type WorktreeAgentInput, type WorktreeClass, type WorktreeEnvContext, type WorktreeMarker, WorktreeNotRemovableError, type WorktreeStatusEntry, allocatePort, applyBranchGc, applyGc, applySlugPlaceholder, branchReviewQueue, branchVerdictSchema, classify, classifyForGc, classifyTip, classifyTipAgainstBase, cloneEntries, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, connectDaemonAgentSessionHost, createForgeClient, createLadderContext, createProxyServer, detectAnchor, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandCloneGlob, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isMechanicalDepBumpRange, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, loadLocalWorktreeConfig, makeDaemonAgentSessionHost, normalizeHook, parseConfig, parseGithubOwnerRepo, parseLocalWorktreeConfig, peerEnv, peerEnvKey, planBranchGc, planGc, readBranchGcRestoreLog, readSessionsRegistry, readWorktreeMarker, reclaimOneWorktree, reconcileIntegration, recordBranchVerdict, removeWorktreeFast, repoLabel, resolveGcClass, resolveLocalWriteFiles, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, salvageWorktree, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, startProxy, stripPort, summarizeBranchGcPlan, sweepWorktreeTrash, worktreeAgentInputSchema, worktreeAgentWorkflow, writeWorktreeMarker };
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
- export { connectDaemonAgentSessionHost, makeDaemonAgentSessionHost, worktreeAgentInputSchema, worktreeAgentWorkflow } from './chunk-5SDH2V6M.mjs';
1
+ export { connectDaemonAgentSessionHost, makeDaemonAgentSessionHost, worktreeAgentInputSchema, worktreeAgentWorkflow } from './chunk-YMDOSMMD.mjs';
2
2
  import './chunk-E3EM24BS.mjs';
3
- import { computeProvenance, execArgv, classify, computeWorktreeStatus, sweepWorktreeTrash, listGitWorktrees, execGit, worktreeProvider } from './chunk-EVHLUKC7.mjs';
4
- 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 } from './chunk-EVHLUKC7.mjs';
5
- import { cleanupWorktreeTool } from './chunk-EK5BH2YL.mjs';
6
- export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from './chunk-EK5BH2YL.mjs';
3
+ import { computeProvenance, execArgv, classify, computeWorktreeStatus, sweepWorktreeTrash, listGitWorktrees, execGit, worktreeProvider } from './chunk-MYH5XOX6.mjs';
4
+ export { CONFIG_FILENAME, ConfigError, DEFAULT_PROXY_PORT, ENV_VARS, FileVerdictMemoStore, GlobTraversalError, HookError, InMemoryVerdictMemoStore, LOCAL_WORKTREE_CONFIG_REL, ProxyTable, SESSIONS_BUCKETS_ROOT, SESSIONS_FILE_PATH, ServiceSupervisor, VERDICT_MEMO_PATH, WORKTREES_TURBO_CACHE_DIR_ENV, WORKTREE_TRASH_DIRNAME, WorktreeNotRemovableError, allocatePort, applySlugPlaceholder, classify, cloneEntries, computeBaseDivergence, computeLiveness, computeProvenance, computeTreeState, computeWorktreeStatus, detectDefaultBranch, disposeSupervisor, ephemeralPort, execArgv, execGit, execShell, expandCloneGlob, expandGlob, getScript, getSupervisor, globToRegExp, hookEnv, isPortFree, listGitWorktrees, listScripts, listServices, listWorktreeStatuses, loadConfigFromBase, loadLocalWorktreeConfig, normalizeHook, parseConfig, parseLocalWorktreeConfig, peerEnv, peerEnvKey, readSessionsRegistry, readWorktreeMarker, reconcileIntegration, removeWorktreeFast, repoLabel, resolveLocalWriteFiles, resolveSupervisor, resolveWorktreesTurboCacheDir, runSetup, runTeardown, serviceEnv, serviceEnvToken, serviceHostname, serviceUrl, sessionInWorktree, sharedProxyTable, slugify, stripPort, sweepWorktreeTrash, worktreeProvider, writeWorktreeMarker } from './chunk-MYH5XOX6.mjs';
5
+ import { cleanupWorktreeTool } from './chunk-3FZWPMLF.mjs';
6
+ export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from './chunk-3FZWPMLF.mjs';
7
7
  import { mkdir, copyFile, readFile, writeFile, open, rename, readdir, realpath, rm, stat } from 'fs/promises';
8
8
  import { homedir } from 'os';
9
9
  import { resolve, join, dirname, basename, sep, relative, isAbsolute } from 'path';
@@ -1,4 +1,4 @@
1
- export { worktreeProvider } from '../chunk-EVHLUKC7.mjs';
2
- import '../chunk-EK5BH2YL.mjs';
1
+ export { worktreeProvider } from '../chunk-MYH5XOX6.mjs';
2
+ import '../chunk-3FZWPMLF.mjs';
3
3
  //# sourceMappingURL=index.mjs.map
4
4
  //# sourceMappingURL=index.mjs.map
@@ -14,6 +14,7 @@ declare const provisionWorktreeTool: _agentproto_tool.ToolHandle<{
14
14
  dir?: string | undefined;
15
15
  depsCmd?: string | undefined;
16
16
  copyGlobs?: string[] | undefined;
17
+ cloneGlobs?: string[] | undefined;
17
18
  linkPaths?: string[] | undefined;
18
19
  writeFiles?: {
19
20
  path: string;
@@ -1,4 +1,4 @@
1
1
  import '../chunk-E3EM24BS.mjs';
2
- export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from '../chunk-EK5BH2YL.mjs';
2
+ export { cleanupWorktreeTool, listServicesTool, provisionWorktreeTool, runGateTool, runScriptTool, serviceStatusSchema, startServiceTool, stopServiceTool } from '../chunk-3FZWPMLF.mjs';
3
3
  //# sourceMappingURL=index.mjs.map
4
4
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/worktree",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "AIP-14 TOOL contracts + builtin AIP-30 PROVIDER for provisioning, gating, and cleaning up a git worktree — the primitive an AgentStep binds its `cwd` to for a launch-agent-in-a-worktree workflow.",
5
5
  "keywords": [
6
6
  "agentproto",
@@ -1 +0,0 @@
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,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;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"]}