@tintinweb/pi-subagents 0.4.0 → 0.4.3

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.
package/src/index.ts CHANGED
@@ -204,8 +204,44 @@ export default function (pi: ExtensionAPI) {
204
204
  30_000,
205
205
  );
206
206
 
207
+ /** Helper: build event data for lifecycle events from an AgentRecord. */
208
+ function buildEventData(record: AgentRecord) {
209
+ const durationMs = record.completedAt ? record.completedAt - record.startedAt : Date.now() - record.startedAt;
210
+ let tokens: { input: number; output: number; total: number } | undefined;
211
+ try {
212
+ if (record.session) {
213
+ const stats = record.session.getSessionStats();
214
+ tokens = {
215
+ input: stats.tokens?.input ?? 0,
216
+ output: stats.tokens?.output ?? 0,
217
+ total: stats.tokens?.total ?? 0,
218
+ };
219
+ }
220
+ } catch { /* session stats unavailable */ }
221
+ return {
222
+ id: record.id,
223
+ type: record.type,
224
+ description: record.description,
225
+ result: record.result,
226
+ error: record.error,
227
+ status: record.status,
228
+ toolUses: record.toolUses,
229
+ durationMs,
230
+ tokens,
231
+ };
232
+ }
233
+
207
234
  // Background completion: route through group join or send individual nudge
208
235
  const manager = new AgentManager((record) => {
236
+ // Emit lifecycle event based on terminal status
237
+ const isError = record.status === "error" || record.status === "stopped" || record.status === "aborted";
238
+ const eventData = buildEventData(record);
239
+ if (isError) {
240
+ pi.events.emit("subagents:failed", eventData);
241
+ } else {
242
+ pi.events.emit("subagents:completed", eventData);
243
+ }
244
+
209
245
  // Skip notification if result was already consumed via get_subagent_result
210
246
  if (record.resultConsumed) {
211
247
  agentActivity.delete(record.id);
@@ -228,6 +264,31 @@ export default function (pi: ExtensionAPI) {
228
264
  // 'held' → do nothing, group will fire later
229
265
  // 'delivered' → group callback already fired
230
266
  widget.update();
267
+ }, undefined, (record) => {
268
+ // Emit started event when agent transitions to running (including from queue)
269
+ pi.events.emit("subagents:started", {
270
+ id: record.id,
271
+ type: record.type,
272
+ description: record.description,
273
+ });
274
+ });
275
+
276
+ // Expose manager via Symbol.for() global registry for cross-package access.
277
+ // Standard Node.js pattern for cross-package singletons (used by OpenTelemetry, etc.).
278
+ const MANAGER_KEY = Symbol.for("pi-subagents:manager");
279
+ (globalThis as any)[MANAGER_KEY] = {
280
+ waitForAll: () => manager.waitForAll(),
281
+ hasRunning: () => manager.hasRunning(),
282
+ spawn: (piRef: any, ctx: any, type: string, prompt: string, options: any) =>
283
+ manager.spawn(piRef, ctx, type, prompt, options),
284
+ getRecord: (id: string) => manager.getRecord(id),
285
+ };
286
+
287
+ // Wait for all subagents on shutdown, then dispose the manager
288
+ pi.on("session_shutdown", async () => {
289
+ delete (globalThis as any)[MANAGER_KEY];
290
+ await manager.waitForAll();
291
+ manager.dispose();
231
292
  });
232
293
 
233
294
  // Live widget: show running agents above editor
@@ -347,6 +408,7 @@ Guidelines:
347
408
  - Use model to specify a different model (as "provider/modelId", or fuzzy e.g. "haiku", "sonnet").
348
409
  - Use thinking to control extended thinking level.
349
410
  - Use inherit_context if the agent needs the parent conversation history.
411
+ - Use isolation: "worktree" to run the agent in an isolated git worktree (safe parallel file modifications).
350
412
  - Use join_mode to control how background completion notifications are delivered. By default (smart), 2+ background agents spawned in the same turn are grouped into a single notification. Use "async" for individual notifications or "group" to force grouping.`,
351
413
  parameters: Type.Object({
352
414
  prompt: Type.String({
@@ -395,6 +457,11 @@ Guidelines:
395
457
  description: "If true, fork parent conversation into the agent. Default: false (fresh context).",
396
458
  }),
397
459
  ),
460
+ isolation: Type.Optional(
461
+ Type.Literal("worktree", {
462
+ description: 'Set to "worktree" to run the agent in a temporary git worktree (isolated copy of the repo). Changes are saved to a branch on completion.',
463
+ }),
464
+ ),
398
465
  join_mode: Type.Optional(
399
466
  Type.Union([
400
467
  Type.Literal("async"),
@@ -529,6 +596,7 @@ Guidelines:
529
596
  const inheritContext = params.inherit_context ?? customConfig?.inheritContext ?? false;
530
597
  const runInBackground = params.run_in_background ?? customConfig?.runInBackground ?? false;
531
598
  const isolated = params.isolated ?? customConfig?.isolated ?? false;
599
+ const isolation = params.isolation ?? customConfig?.isolation;
532
600
 
533
601
  // Build display tags for non-default config
534
602
  const parentModelId = ctx.model?.id;
@@ -541,6 +609,7 @@ Guidelines:
541
609
  if (modeLabel) agentTags.push(modeLabel);
542
610
  if (thinking) agentTags.push(`thinking: ${thinking}`);
543
611
  if (isolated) agentTags.push("isolated");
612
+ if (isolation === "worktree") agentTags.push("worktree");
544
613
  // Shared base fields for all AgentDetails in this call
545
614
  const detailBase = {
546
615
  displayName,
@@ -581,6 +650,7 @@ Guidelines:
581
650
  inheritContext,
582
651
  thinkingLevel: thinking,
583
652
  isBackground: true,
653
+ isolation,
584
654
  ...bgCallbacks,
585
655
  });
586
656
 
@@ -603,6 +673,15 @@ Guidelines:
603
673
  agentActivity.set(id, bgState);
604
674
  widget.ensureTimer();
605
675
  widget.update();
676
+
677
+ // Emit created event
678
+ pi.events.emit("subagents:created", {
679
+ id,
680
+ type: subagentType,
681
+ description: params.description,
682
+ isBackground: true,
683
+ });
684
+
606
685
  const isQueued = record?.status === "queued";
607
686
  return textResult(
608
687
  `Agent ${isQueued ? "queued" : "started"} in background.\n` +
@@ -669,6 +748,7 @@ Guidelines:
669
748
  isolated,
670
749
  inheritContext,
671
750
  thinkingLevel: thinking,
751
+ isolation,
672
752
  ...fgCallbacks,
673
753
  });
674
754
 
@@ -802,6 +882,7 @@ Guidelines:
802
882
 
803
883
  try {
804
884
  await steerAgent(record.session, params.message);
885
+ pi.events.emit("subagents:steered", { id: record.id, message: params.message });
805
886
  return textResult(`Steering message sent to agent ${record.id}. The agent will process it after its current tool execution.`);
806
887
  } catch (err) {
807
888
  return textResult(`Failed to steer agent: ${err instanceof Error ? err.message : String(err)}`);
@@ -1077,9 +1158,12 @@ Guidelines:
1077
1158
  else if (Array.isArray(cfg.extensions)) fmFields.push(`extensions: ${cfg.extensions.join(", ")}`);
1078
1159
  if (cfg.skills === false) fmFields.push("skills: false");
1079
1160
  else if (Array.isArray(cfg.skills)) fmFields.push(`skills: ${cfg.skills.join(", ")}`);
1161
+ if (cfg.disallowedTools?.length) fmFields.push(`disallowed_tools: ${cfg.disallowedTools.join(", ")}`);
1080
1162
  if (cfg.inheritContext) fmFields.push("inherit_context: true");
1081
1163
  if (cfg.runInBackground) fmFields.push("run_in_background: true");
1082
1164
  if (cfg.isolated) fmFields.push("isolated: true");
1165
+ if (cfg.memory) fmFields.push(`memory: ${cfg.memory}`);
1166
+ if (cfg.isolation) fmFields.push(`isolation: ${cfg.isolation}`);
1083
1167
 
1084
1168
  const content = `---\n${fmFields.join("\n")}\n---\n\n${cfg.systemPrompt}\n`;
1085
1169
 
@@ -1199,10 +1283,13 @@ thinking: <optional thinking level: off, minimal, low, medium, high, xhigh. Omit
1199
1283
  max_turns: <optional max agentic turns, default 50. Omit for default>
1200
1284
  prompt_mode: <"replace" (body IS the full system prompt) or "append" (body is appended to default prompt). Default: replace>
1201
1285
  extensions: <true (inherit all MCP/extension tools), false (none), or comma-separated names. Default: true>
1202
- skills: <true (inherit all), false (none). Default: true>
1286
+ skills: <true (inherit all), false (none), or comma-separated skill names to preload into prompt. Default: true>
1287
+ disallowed_tools: <comma-separated tool names to block, even if otherwise available. Omit for none>
1203
1288
  inherit_context: <true to fork parent conversation into agent so it sees chat history. Default: false>
1204
1289
  run_in_background: <true to run in background by default. Default: false>
1205
1290
  isolated: <true for no extension/MCP tools, only built-in tools. Default: false>
1291
+ memory: <"user" (global), "project" (per-project), or "local" (gitignored per-project) for persistent memory. Omit for none>
1292
+ isolation: <"worktree" to run in isolated git worktree. Omit for normal>
1206
1293
  ---
1207
1294
 
1208
1295
  <system prompt body — instructions for the agent>
package/src/memory.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
3
+ *
4
+ * Memory scopes:
5
+ * - "user" → ~/.pi/agent-memory/{agent-name}/
6
+ * - "project" → .pi/agent-memory/{agent-name}/
7
+ * - "local" → .pi/agent-memory-local/{agent-name}/
8
+ */
9
+
10
+ import { existsSync, readFileSync, mkdirSync, lstatSync } from "node:fs";
11
+ import { join, resolve } from "node:path";
12
+ import { homedir } from "node:os";
13
+ import type { MemoryScope } from "./types.js";
14
+
15
+ /** Maximum lines to read from MEMORY.md */
16
+ const MAX_MEMORY_LINES = 200;
17
+
18
+ /**
19
+ * Returns true if a name contains characters not allowed in agent/skill names.
20
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
21
+ */
22
+ export function isUnsafeName(name: string): boolean {
23
+ if (!name || name.length > 128) return true;
24
+ return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
25
+ }
26
+
27
+ /**
28
+ * Returns true if the given path is a symlink (defense against symlink attacks).
29
+ */
30
+ export function isSymlink(filePath: string): boolean {
31
+ try {
32
+ return lstatSync(filePath).isSymbolicLink();
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Safely read a file, rejecting symlinks.
40
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
41
+ */
42
+ export function safeReadFile(filePath: string): string | undefined {
43
+ if (!existsSync(filePath)) return undefined;
44
+ if (isSymlink(filePath)) return undefined;
45
+ try {
46
+ return readFileSync(filePath, "utf-8");
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Resolve the memory directory path for a given agent + scope + cwd.
54
+ * Throws if agentName contains path traversal characters.
55
+ */
56
+ export function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string {
57
+ if (isUnsafeName(agentName)) {
58
+ throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
59
+ }
60
+ switch (scope) {
61
+ case "user":
62
+ return join(homedir(), ".pi", "agent-memory", agentName);
63
+ case "project":
64
+ return join(cwd, ".pi", "agent-memory", agentName);
65
+ case "local":
66
+ return join(cwd, ".pi", "agent-memory-local", agentName);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Ensure the memory directory exists, creating it if needed.
72
+ * Refuses to create directories if any component in the path is a symlink
73
+ * to prevent symlink-based directory traversal attacks.
74
+ */
75
+ export function ensureMemoryDir(memoryDir: string): void {
76
+ // If the directory already exists, verify it's not a symlink
77
+ if (existsSync(memoryDir)) {
78
+ if (isSymlink(memoryDir)) {
79
+ throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
80
+ }
81
+ return;
82
+ }
83
+ mkdirSync(memoryDir, { recursive: true });
84
+ }
85
+
86
+ /**
87
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
88
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
89
+ */
90
+ export function readMemoryIndex(memoryDir: string): string | undefined {
91
+ // Reject symlinked memory directories
92
+ if (isSymlink(memoryDir)) return undefined;
93
+
94
+ const memoryFile = join(memoryDir, "MEMORY.md");
95
+ const content = safeReadFile(memoryFile);
96
+ if (content === undefined) return undefined;
97
+
98
+ const lines = content.split("\n");
99
+ if (lines.length > MAX_MEMORY_LINES) {
100
+ return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
101
+ }
102
+ return content;
103
+ }
104
+
105
+ /**
106
+ * Build the memory block to inject into the agent's system prompt.
107
+ * Also ensures the memory directory exists (creates it if needed).
108
+ */
109
+ export function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
110
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
111
+ // Create the memory directory so the agent can immediately write to it
112
+ ensureMemoryDir(memoryDir);
113
+
114
+ const existingMemory = readMemoryIndex(memoryDir);
115
+
116
+ const header = `# Agent Memory
117
+
118
+ You have a persistent memory directory at: ${memoryDir}/
119
+ Memory scope: ${scope}
120
+
121
+ This memory persists across sessions. Use it to build up knowledge over time.`;
122
+
123
+ const memoryContent = existingMemory
124
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
125
+ : `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
126
+
127
+ const instructions = `
128
+
129
+ ## Memory Instructions
130
+ - MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
131
+ - Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
132
+ - Each memory file should use this frontmatter format:
133
+ \`\`\`markdown
134
+ ---
135
+ name: <memory name>
136
+ description: <one-line description>
137
+ type: <user|feedback|project|reference>
138
+ ---
139
+ <memory content>
140
+ \`\`\`
141
+ - Update or remove memories that become outdated. Check for existing memories before creating duplicates.
142
+ - You have Read, Write, and Edit tools available for managing memory files.`;
143
+
144
+ return header + memoryContent + instructions;
145
+ }
146
+
147
+ /**
148
+ * Build a read-only memory block for agents that lack write/edit tools.
149
+ * Does NOT create the memory directory — agents can only consume existing memory.
150
+ */
151
+ export function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
152
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
153
+ const existingMemory = readMemoryIndex(memoryDir);
154
+
155
+ const header = `# Agent Memory (read-only)
156
+
157
+ Memory scope: ${scope}
158
+ You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
159
+
160
+ const memoryContent = existingMemory
161
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
162
+ : `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
163
+
164
+ return header + memoryContent;
165
+ }
package/src/prompts.ts CHANGED
@@ -4,6 +4,14 @@
4
4
 
5
5
  import type { AgentConfig, EnvInfo } from "./types.js";
6
6
 
7
+ /** Extra sections to inject into the system prompt (memory, skills, etc.). */
8
+ export interface PromptExtras {
9
+ /** Persistent memory content to inject (first 200 lines of MEMORY.md + instructions). */
10
+ memoryBlock?: string;
11
+ /** Preloaded skill contents to inject. */
12
+ skillBlocks?: { name: string; content: string }[];
13
+ }
14
+
7
15
  /**
8
16
  * Build the system prompt for an agent from its config.
9
17
  *
@@ -12,18 +20,32 @@ import type { AgentConfig, EnvInfo } from "./types.js";
12
20
  * - "append" with empty systemPrompt: pure parent clone
13
21
  *
14
22
  * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
23
+ * @param extras Optional extra sections to inject (memory, preloaded skills).
15
24
  */
16
25
  export function buildAgentPrompt(
17
26
  config: AgentConfig,
18
27
  cwd: string,
19
28
  env: EnvInfo,
20
29
  parentSystemPrompt?: string,
30
+ extras?: PromptExtras,
21
31
  ): string {
22
32
  const envBlock = `# Environment
23
33
  Working directory: ${cwd}
24
34
  ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
25
35
  Platform: ${env.platform}`;
26
36
 
37
+ // Build optional extras suffix
38
+ const extraSections: string[] = [];
39
+ if (extras?.memoryBlock) {
40
+ extraSections.push(extras.memoryBlock);
41
+ }
42
+ if (extras?.skillBlocks?.length) {
43
+ for (const skill of extras.skillBlocks) {
44
+ extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
45
+ }
46
+ }
47
+ const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
48
+
27
49
  if (config.promptMode === "append") {
28
50
  const identity = parentSystemPrompt || genericBase;
29
51
 
@@ -44,7 +66,7 @@ You are operating as a sub-agent invoked to handle a specific task.
44
66
  ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
45
67
  : "";
46
68
 
47
- return envBlock + "\n\n<inherited_system_prompt>\n" + identity + "\n</inherited_system_prompt>\n\n" + bridge + customSection;
69
+ return envBlock + "\n\n<inherited_system_prompt>\n" + identity + "\n</inherited_system_prompt>\n\n" + bridge + customSection + extrasSuffix;
48
70
  }
49
71
 
50
72
  // "replace" mode — env header + the config's full system prompt
@@ -53,7 +75,7 @@ You have been invoked to handle a specific task autonomously.
53
75
 
54
76
  ${envBlock}`;
55
77
 
56
- return replaceHeader + "\n\n" + config.systemPrompt;
78
+ return replaceHeader + "\n\n" + config.systemPrompt + extrasSuffix;
57
79
  }
58
80
 
59
81
  /** Fallback base prompt when parent system prompt is unavailable in append mode. */
@@ -0,0 +1,79 @@
1
+ /**
2
+ * skill-loader.ts — Preload specific skill files and inject their content into the system prompt.
3
+ *
4
+ * When skills is a string[], reads each named skill from .pi/skills/ or ~/.pi/skills/
5
+ * and returns their content for injection into the agent's system prompt.
6
+ */
7
+
8
+ import { join } from "node:path";
9
+ import { homedir } from "node:os";
10
+ import { isUnsafeName, safeReadFile } from "./memory.js";
11
+
12
+ export interface PreloadedSkill {
13
+ name: string;
14
+ content: string;
15
+ }
16
+
17
+ /**
18
+ * Attempt to load named skills from project and global skill directories.
19
+ * Looks for: <dir>/<name>.md, <dir>/<name>.txt, <dir>/<name>
20
+ *
21
+ * @param skillNames List of skill names to preload.
22
+ * @param cwd Working directory for project-level skills.
23
+ * @returns Array of loaded skills (missing skills are skipped with a warning comment).
24
+ */
25
+ export function preloadSkills(skillNames: string[], cwd: string): PreloadedSkill[] {
26
+ const results: PreloadedSkill[] = [];
27
+
28
+ for (const name of skillNames) {
29
+ // Unlike memory (which throws on unsafe names because it's part of agent setup),
30
+ // skills are optional — skip gracefully to avoid blocking agent startup.
31
+ if (isUnsafeName(name)) {
32
+ results.push({ name, content: `(Skill "${name}" skipped: name contains path traversal characters)` });
33
+ continue;
34
+ }
35
+ const content = findAndReadSkill(name, cwd);
36
+ if (content !== undefined) {
37
+ results.push({ name, content });
38
+ } else {
39
+ // Include a note about missing skills so the agent knows it was requested but not found
40
+ results.push({ name, content: `(Skill "${name}" not found in .pi/skills/ or ~/.pi/skills/)` });
41
+ }
42
+ }
43
+
44
+ return results;
45
+ }
46
+
47
+ /**
48
+ * Search for a skill file in project and global directories.
49
+ * Project-level takes priority over global.
50
+ */
51
+ function findAndReadSkill(name: string, cwd: string): string | undefined {
52
+ const projectDir = join(cwd, ".pi", "skills");
53
+ const globalDir = join(homedir(), ".pi", "skills");
54
+
55
+ // Try project first, then global
56
+ for (const dir of [projectDir, globalDir]) {
57
+ const content = tryReadSkillFile(dir, name);
58
+ if (content !== undefined) return content;
59
+ }
60
+
61
+ return undefined;
62
+ }
63
+
64
+ /**
65
+ * Try to read a skill file from a directory.
66
+ * Tries extensions in order: .md, .txt, (no extension)
67
+ */
68
+ function tryReadSkillFile(dir: string, name: string): string | undefined {
69
+ const extensions = [".md", ".txt", ""];
70
+
71
+ for (const ext of extensions) {
72
+ const path = join(dir, name + ext);
73
+ // safeReadFile rejects symlinks to prevent reading arbitrary files
74
+ const content = safeReadFile(path);
75
+ if (content !== undefined) return content.trim();
76
+ }
77
+
78
+ return undefined;
79
+ }
package/src/types.ts CHANGED
@@ -13,12 +13,20 @@ export type SubagentType = string;
13
13
  /** Names of the three embedded default agents. */
14
14
  export const DEFAULT_AGENT_NAMES = ["general-purpose", "Explore", "Plan"] as const;
15
15
 
16
+ /** Memory scope for persistent agent memory. */
17
+ export type MemoryScope = "user" | "project" | "local";
18
+
19
+ /** Isolation mode for agent execution. */
20
+ export type IsolationMode = "worktree";
21
+
16
22
  /** Unified agent configuration — used for both default and user-defined agents. */
17
23
  export interface AgentConfig {
18
24
  name: string;
19
25
  displayName?: string;
20
26
  description: string;
21
27
  builtinToolNames?: string[];
28
+ /** Tool denylist — these tools are removed even if `builtinToolNames` or extensions include them. */
29
+ disallowedTools?: string[];
22
30
  /** true = inherit all, string[] = only listed, false = none */
23
31
  extensions: true | string[] | false;
24
32
  /** true = inherit all, string[] = only listed, false = none */
@@ -34,6 +42,10 @@ export interface AgentConfig {
34
42
  runInBackground: boolean;
35
43
  /** Default for spawn: no extension tools */
36
44
  isolated: boolean;
45
+ /** Persistent memory scope — agents with memory get a persistent directory and MEMORY.md */
46
+ memory?: MemoryScope;
47
+ /** Isolation mode — "worktree" runs the agent in a temporary git worktree */
48
+ isolation?: IsolationMode;
37
49
  /** true = this is an embedded default agent (informational) */
38
50
  isDefault?: boolean;
39
51
  /** false = agent is hidden from the registry */
@@ -61,6 +73,10 @@ export interface AgentRecord {
61
73
  joinMode?: JoinMode;
62
74
  /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
63
75
  resultConsumed?: boolean;
76
+ /** Worktree info if the agent is running in an isolated worktree. */
77
+ worktree?: { path: string; branch: string };
78
+ /** Worktree cleanup result after agent completion. */
79
+ worktreeResult?: { hasChanges: boolean; branch?: string };
64
80
  }
65
81
 
66
82
  export interface EnvInfo {
@@ -0,0 +1,162 @@
1
+ /**
2
+ * worktree.ts — Git worktree isolation for agents.
3
+ *
4
+ * Creates a temporary git worktree so the agent works on an isolated copy of the repo.
5
+ * On completion, if no changes were made, the worktree is cleaned up.
6
+ * If changes exist, a branch is created and returned in the result.
7
+ */
8
+
9
+ import { execFileSync } from "node:child_process";
10
+ import { existsSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { tmpdir } from "node:os";
13
+ import { randomUUID } from "node:crypto";
14
+
15
+ export interface WorktreeInfo {
16
+ /** Absolute path to the worktree directory. */
17
+ path: string;
18
+ /** Branch name created for this worktree (if changes exist). */
19
+ branch: string;
20
+ }
21
+
22
+ export interface WorktreeCleanupResult {
23
+ /** Whether changes were found in the worktree. */
24
+ hasChanges: boolean;
25
+ /** Branch name if changes were committed. */
26
+ branch?: string;
27
+ /** Worktree path if it was kept. */
28
+ path?: string;
29
+ }
30
+
31
+ /**
32
+ * Create a temporary git worktree for an agent.
33
+ * Returns the worktree path, or undefined if not in a git repo.
34
+ */
35
+ export function createWorktree(cwd: string, agentId: string): WorktreeInfo | undefined {
36
+ // Verify we're in a git repo with at least one commit (HEAD must exist)
37
+ try {
38
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd, stdio: "pipe", timeout: 5000 });
39
+ execFileSync("git", ["rev-parse", "HEAD"], { cwd, stdio: "pipe", timeout: 5000 });
40
+ } catch {
41
+ return undefined;
42
+ }
43
+
44
+ const branch = `pi-agent-${agentId}`;
45
+ const suffix = randomUUID().slice(0, 8);
46
+ const worktreePath = join(tmpdir(), `pi-agent-${agentId}-${suffix}`);
47
+
48
+ try {
49
+ // Create detached worktree at HEAD
50
+ execFileSync("git", ["worktree", "add", "--detach", worktreePath, "HEAD"], {
51
+ cwd,
52
+ stdio: "pipe",
53
+ timeout: 30000,
54
+ });
55
+ return { path: worktreePath, branch };
56
+ } catch {
57
+ // If worktree creation fails, return undefined (agent runs in normal cwd)
58
+ return undefined;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Clean up a worktree after agent completion.
64
+ * - If no changes: remove worktree entirely.
65
+ * - If changes exist: create a branch, commit changes, return branch info.
66
+ */
67
+ export function cleanupWorktree(
68
+ cwd: string,
69
+ worktree: WorktreeInfo,
70
+ agentDescription: string,
71
+ ): WorktreeCleanupResult {
72
+ if (!existsSync(worktree.path)) {
73
+ return { hasChanges: false };
74
+ }
75
+
76
+ try {
77
+ // Check for uncommitted changes in the worktree
78
+ const status = execFileSync("git", ["status", "--porcelain"], {
79
+ cwd: worktree.path,
80
+ stdio: "pipe",
81
+ timeout: 10000,
82
+ }).toString().trim();
83
+
84
+ if (!status) {
85
+ // No changes — remove worktree
86
+ removeWorktree(cwd, worktree.path);
87
+ return { hasChanges: false };
88
+ }
89
+
90
+ // Changes exist — stage, commit, and create a branch
91
+ execFileSync("git", ["add", "-A"], { cwd: worktree.path, stdio: "pipe", timeout: 10000 });
92
+ // Truncate description for commit message (no shell sanitization needed — execFileSync uses argv)
93
+ const safeDesc = agentDescription.slice(0, 200);
94
+ const commitMsg = `pi-agent: ${safeDesc}`;
95
+ execFileSync("git", ["commit", "-m", commitMsg], {
96
+ cwd: worktree.path,
97
+ stdio: "pipe",
98
+ timeout: 10000,
99
+ });
100
+
101
+ // Create a branch pointing to the worktree's HEAD.
102
+ // If the branch already exists, append a suffix to avoid overwriting previous work.
103
+ let branchName = worktree.branch;
104
+ try {
105
+ execFileSync("git", ["branch", branchName], {
106
+ cwd: worktree.path,
107
+ stdio: "pipe",
108
+ timeout: 5000,
109
+ });
110
+ } catch {
111
+ // Branch already exists — use a unique suffix
112
+ branchName = `${worktree.branch}-${Date.now()}`;
113
+ execFileSync("git", ["branch", branchName], {
114
+ cwd: worktree.path,
115
+ stdio: "pipe",
116
+ timeout: 5000,
117
+ });
118
+ }
119
+ // Update branch name in worktree info for the caller
120
+ worktree.branch = branchName;
121
+
122
+ // Remove the worktree (branch persists in main repo)
123
+ removeWorktree(cwd, worktree.path);
124
+
125
+ return {
126
+ hasChanges: true,
127
+ branch: worktree.branch,
128
+ path: worktree.path,
129
+ };
130
+ } catch {
131
+ // Best effort cleanup on error
132
+ try { removeWorktree(cwd, worktree.path); } catch { /* ignore */ }
133
+ return { hasChanges: false };
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Force-remove a worktree.
139
+ */
140
+ function removeWorktree(cwd: string, worktreePath: string): void {
141
+ try {
142
+ execFileSync("git", ["worktree", "remove", "--force", worktreePath], {
143
+ cwd,
144
+ stdio: "pipe",
145
+ timeout: 10000,
146
+ });
147
+ } catch {
148
+ // If git worktree remove fails, try pruning
149
+ try {
150
+ execFileSync("git", ["worktree", "prune"], { cwd, stdio: "pipe", timeout: 5000 });
151
+ } catch { /* ignore */ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Prune any orphaned worktrees (crash recovery).
157
+ */
158
+ export function pruneWorktrees(cwd: string): void {
159
+ try {
160
+ execFileSync("git", ["worktree", "prune"], { cwd, stdio: "pipe", timeout: 5000 });
161
+ } catch { /* ignore */ }
162
+ }