@deathbeam/pi-delegate 0.0.25 → 0.0.27

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # [@deathbeam/pi-delegate](https://www.npmjs.com/package/@deathbeam/pi-delegate)
2
2
 
3
- Run subagents with `delegate`, `delegate_list`, `delegate_steer`, and `delegate_cancel`.
3
+ Run subagents with `delegate`, `delegate_list`, `delegate_steer`, `delegate_cancel`, and `delegate_apply`.
4
4
  Use `/delegate` command to inspect jobs in a full-screen TUI.
5
5
 
6
6
  ## Installation
@@ -53,6 +53,15 @@ The main session is prompted to act as an orchestrator. When it makes 5, 10, 20,
53
53
  `grep`, `find`, `ls`, shell, web tools) without delegating, a hidden reminder nudges it to delegate the rest. The count
54
54
  resets on each prompt and each `delegate` call.
55
55
 
56
+ ## Isolation
57
+
58
+ `isolated: true` (on a `delegate` call or in agent frontmatter) runs the delegate in its own git clone at
59
+ `.pi/worktrees/<id>`, starting from your current working tree including uncommitted changes. Add `.pi/worktrees/` to
60
+ `.gitignore`.
61
+
62
+ `delegate_apply` merges the result into your working tree as uncommitted changes. On conflict the clone is kept so you
63
+ can steer the delegate to resolve it. `discard: true` drops the clone instead.
64
+
56
65
  ## Development
57
66
 
58
67
  From this package directory:
package/agents/explore.md CHANGED
@@ -7,7 +7,7 @@ model: cheap
7
7
 
8
8
  You are a read-only codebase exploration agent with an isolated context.
9
9
 
10
- Trace the flow relevant to the assigned task. Find entry points, callers, important files, existing helpers, and likely risks. Do not modify files.
10
+ Trace the flow relevant to the assigned task. Find entry points, callers, important files, existing helpers, and likely risks.
11
11
 
12
12
  Return a concise report with relevant paths, the data or control flow, findings, and unresolved questions. Prefer evidence from the repository over guesses.
13
13
 
package/agents/general.md CHANGED
@@ -11,4 +11,4 @@ Complete the assigned task directly. Inspect the repository before changing it,
11
11
 
12
12
  The task is authoritative; do not assume you can see the parent conversation. Report what you changed, what you checked, and any remaining uncertainty.
13
13
 
14
- If the task expected code or file edits and you made none, do not report success: make the edits or say plainly what blocked you. Do not end your response with a question you could have answered yourself.
14
+ If the task expected code or file edits and you made none, do not report success: make the edits or say plainly what blocked you. Answer your own open questions before finishing; end with statements, not questions.
package/agents.ts CHANGED
@@ -10,6 +10,7 @@ export type AgentFile = {
10
10
  description: string;
11
11
  tools?: string[];
12
12
  model?: string;
13
+ isolated?: boolean;
13
14
  prompt: string;
14
15
  };
15
16
 
@@ -69,6 +70,7 @@ function loadAgents(dir: string): AgentFile[] {
69
70
  description: frontmatter.description,
70
71
  tools: stringList(frontmatter.tools),
71
72
  model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
73
+ isolated: typeof frontmatter.isolated === "boolean" ? frontmatter.isolated : undefined,
72
74
  prompt: body.trim(),
73
75
  });
74
76
  } catch {
package/format.ts CHANGED
@@ -161,6 +161,68 @@ export function reviveHint(id: string): string {
161
161
  return `To continue this job, call delegate_steer with id ${id} and a message.`;
162
162
  }
163
163
 
164
+ /**
165
+ * Converts a git unified diff into pi's own diff format (`+12 content` / `-12 content` / ` 12 content`,
166
+ * prefix, padded line number, space, content), which is what pi's renderDiff colors; a raw unified
167
+ * diff renders as flat context. Line numbers come from the @@ headers (- uses the old side, + and
168
+ * context the new side); the file path heads each file and `...` separates its hunks.
169
+ */
170
+ export function piDiff(unified: string): string {
171
+ const out: string[] = [];
172
+ let path = "";
173
+ let pathShown = false;
174
+ let hunkSeen = false;
175
+ let oldNum = 0;
176
+ let newNum = 0;
177
+ let width = 1;
178
+ const header = () => {
179
+ if (!pathShown) {
180
+ out.push(path);
181
+ pathShown = true;
182
+ }
183
+ };
184
+ for (const line of unified.split("\n")) {
185
+ const file = /^diff --git a\/\S+ b\/(.+)$/.exec(line);
186
+ if (file) {
187
+ path = file[1]!;
188
+ pathShown = false;
189
+ hunkSeen = false;
190
+ continue;
191
+ }
192
+ const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
193
+ if (hunk) {
194
+ const [, oldStart, oldCount, newStart, newCount] = hunk;
195
+ // The width comes free from the hunk header's last line number on each side.
196
+ width = String(
197
+ Math.max(
198
+ Number(oldStart) + (Number(oldCount) || 1) - 1,
199
+ Number(newStart) + (Number(newCount) || 1) - 1,
200
+ ),
201
+ ).length;
202
+ header();
203
+ if (hunkSeen) out.push(` ${"".padStart(width, " ")} ...`);
204
+ hunkSeen = true;
205
+ oldNum = Number(oldStart);
206
+ newNum = Number(newStart);
207
+ continue;
208
+ }
209
+ // File-meta noise and the no-newline marker carry no content to render.
210
+ if (!hunkSeen || line.startsWith("\\")) {
211
+ if (/^Binary files .* differ$/.test(line)) header();
212
+ continue;
213
+ }
214
+ const content = line.slice(1);
215
+ const num = (prefix: string) => String(prefix === "-" ? oldNum++ : newNum++).padStart(width, " ");
216
+ if (line.startsWith("+")) out.push(`+${num("+")} ${content}`);
217
+ else if (line.startsWith("-")) out.push(`-${num("-")} ${content}`);
218
+ else {
219
+ out.push(` ${num(" ")} ${content}`);
220
+ oldNum++;
221
+ }
222
+ }
223
+ return out.join("\n");
224
+ }
225
+
164
226
  export function reportText(report: DelegateReport): string {
165
227
  // Context usage lets the parent judge whether to continue this job or start a fresh one.
166
228
  const head = `Delegate "${report.agent}" (job ${report.id}, ${usageStats(report, report.elapsedMs)})`;
package/index.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
+ import { Type } from "typebox";
4
5
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
5
- import { getAgentDir, getMarkdownTheme, keyHint } from "@earendil-works/pi-coding-agent";
6
+ import { getAgentDir, getMarkdownTheme, keyHint, renderDiff } from "@earendil-works/pi-coding-agent";
6
7
  import {
7
8
  type Component,
8
9
  Container,
@@ -12,7 +13,6 @@ import {
12
13
  TruncatedText,
13
14
  truncateToWidth,
14
15
  } from "@earendil-works/pi-tui";
15
- import { Type } from "typebox";
16
16
  import {
17
17
  COLLAPSED_OUTPUT_LINES,
18
18
  type DelegateReport,
@@ -20,6 +20,7 @@ import {
20
20
  jobLine,
21
21
  launchDetails,
22
22
  outputPreview,
23
+ piDiff,
23
24
  reportText,
24
25
  reviveHint,
25
26
  SPINNER_INTERVAL_MS,
@@ -31,6 +32,14 @@ import {
31
32
  } from "./format.ts";
32
33
  import { priorActivity, runChild } from "./child.ts";
33
34
  import { createJobStore, type DelegateJob, type InspectJob } from "./store.ts";
35
+ import {
36
+ applyClone,
37
+ cloneCwd,
38
+ createIsolation,
39
+ isolationSummary,
40
+ removeClone,
41
+ type IsolationState,
42
+ } from "./isolation.ts";
34
43
  import { registerInspector } from "./inspector.ts";
35
44
  import { configFor, contextWindowFor, discoverAgents, resolveModel, type AgentFile } from "./agents.ts";
36
45
 
@@ -46,7 +55,7 @@ type SteerDetails = Pick<
46
55
  elapsedMs: number;
47
56
  };
48
57
 
49
- const DELEGATION_TOOLS = new Set(["delegate", "delegate_list", "delegate_steer", "delegate_cancel"]);
58
+ const DELEGATION_TOOLS = new Set(["delegate", "delegate_apply", "delegate_list", "delegate_steer", "delegate_cancel"]);
50
59
  const WIDGET_KEY = "delegate";
51
60
  const RESULT_MESSAGE = "delegate-result";
52
61
  const REMINDER_MESSAGE = "delegate-reminder";
@@ -97,6 +106,11 @@ function mustResolveModel(request: string | undefined, ctx: ExtensionContext, fa
97
106
  return { model, thinking };
98
107
  }
99
108
 
109
+ /** Isolated jobs append the clone location and a change stat so the orchestrator can apply the work. */
110
+ function withIsolation(output: string, isolation: IsolationState | undefined): string {
111
+ return isolation ? [output, isolationSummary(isolation)].filter(Boolean).join("\n\n") : output;
112
+ }
113
+
100
114
  /** Shared tool layout: an optional identity header, then a width-aware payload preview. */
101
115
  function toolLayout(toolName: string, identity: string, payload: string, theme: Theme, expanded: boolean): Component {
102
116
  const container = new Container();
@@ -228,7 +242,7 @@ export default function (pi: ExtensionAPI) {
228
242
  contextTokens: job.contextTokens,
229
243
  contextWindow: job.contextWindow,
230
244
  elapsedMs: Date.now() - job.startedAt,
231
- output,
245
+ output: withIsolation(output ?? "", job.isolation),
232
246
  error,
233
247
  };
234
248
  // Idle: this starts a new turn. Streaming: steer the report in at the next turn boundary;
@@ -244,7 +258,7 @@ export default function (pi: ExtensionAPI) {
244
258
  ctx: ExtensionContext,
245
259
  agent: AgentFile,
246
260
  prior: InspectJob | undefined,
247
- fields: { description: string; model?: string },
261
+ fields: { description: string; model?: string; isolated?: boolean },
248
262
  task: string,
249
263
  signal: AbortSignal | undefined,
250
264
  prompt = task,
@@ -254,20 +268,23 @@ export default function (pi: ExtensionAPI) {
254
268
  (tool) => !DELEGATION_TOOLS.has(tool),
255
269
  );
256
270
  const displayModel = thinking ? `${model}:${thinking}` : model;
271
+ const id = prior?.id ?? randomUUID().slice(0, 8);
272
+ const isolation = fields.isolated ? (prior?.isolation ?? createIsolation(ctx.cwd, id)) : undefined;
273
+
257
274
  const job: DelegateJob = {
258
275
  // A revived job keeps its id: the pinned child session id reopens the old transcript.
259
- id: prior?.id ?? randomUUID().slice(0, 8),
276
+ id,
260
277
  agent: agent.name,
261
278
  description: fields.description.trim(),
262
279
  task,
263
280
  model: displayModel,
264
281
  status: "running",
265
- // A revive continues the pinned transcript, so the inspector replays the child's own history.
266
282
  activity: prior ? priorActivity(DELEGATE_SESSION_DIR, prior.id) : [],
267
283
  tools,
268
284
  toolCalls: 0,
269
285
  startedAt: Date.now(),
270
286
  contextWindow: contextWindowFor(ctx, model),
287
+ isolation,
271
288
  controller: new AbortController(),
272
289
  };
273
290
  const details: DelegateDetails = {
@@ -294,14 +311,17 @@ export default function (pi: ExtensionAPI) {
294
311
  const entrypoint = process.argv[1];
295
312
  if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
296
313
  const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
297
- cwd: ctx.cwd,
314
+ cwd: isolation ? cloneCwd(isolation, ctx.cwd) : ctx.cwd,
298
315
  shell: false,
299
316
  stdio: "pipe",
300
317
  });
301
318
  store.launch(job, details.background);
319
+ const isolatedPrompt = isolation
320
+ ? `You are working in an isolated git clone at ${isolation.clone}; the main working tree is untouched. Commit freely here; the orchestrator applies your changes to the main tree.`
321
+ : "";
302
322
  const run = runChild(
303
323
  child,
304
- prompt,
324
+ isolatedPrompt ? `${isolatedPrompt}\n\n${prompt}` : prompt,
305
325
  details.background ? job.controller.signal : signal,
306
326
  (update) => store.record(job, update),
307
327
  Boolean(prior),
@@ -312,7 +332,10 @@ export default function (pi: ExtensionAPI) {
312
332
  try {
313
333
  const output = await run.done;
314
334
  store.finish(job, "done");
315
- return { content: [{ type: "text" as const, text: output }], details };
335
+ return {
336
+ content: [{ type: "text" as const, text: withIsolation(output, job.isolation) }],
337
+ details,
338
+ };
316
339
  } catch (error) {
317
340
  // Record the outcome so the launch entry cannot linger as "running".
318
341
  const cancelled = error instanceof Error && error.message === "Delegate was aborted";
@@ -335,7 +358,7 @@ export default function (pi: ExtensionAPI) {
335
358
  content: [
336
359
  {
337
360
  type: "text" as const,
338
- text: `${prior ? "Revived" : "Started"} delegate "${job.agent}" in the background (job ${job.id}). Steer it with delegate_steer or stop it with delegate_cancel. Do not call tools solely to wait, even no-op bash commands; when its report is your next dependency, end your turn and it will arrive automatically unless cancelled.`,
361
+ text: `${prior ? "Revived" : "Started"} delegate "${job.agent}" in the background (job ${job.id}). Do not call tools solely to wait, even no-op bash commands; when its report is your next dependency, end your turn and it will arrive automatically unless cancelled.`,
339
362
  },
340
363
  ],
341
364
  details,
@@ -402,7 +425,7 @@ export default function (pi: ExtensionAPI) {
402
425
  pi.sendMessage(
403
426
  {
404
427
  customType: REMINDER_MESSAGE,
405
- content: `<system-reminder>You have made ${directCalls} direct exploration calls since your last delegation. If what remains is exploration, research, or a build/test/debug loop, delegate it now, in parallel for independent scopes, instead of continuing yourself.</system-reminder>`,
428
+ content: `<system-reminder>You have made ${directCalls} direct exploration calls since your last delegation. If what remains is exploration, research, or a build/test/debug loop, delegate it now, in parallel for independent scopes.</system-reminder>`,
406
429
  display: false,
407
430
  },
408
431
  { deliverAs: "steer" },
@@ -429,9 +452,10 @@ export default function (pi: ExtensionAPI) {
429
452
  registerInspector(pi, store);
430
453
 
431
454
  const cwd = process.cwd();
432
- const agentList = discoverAgents(cwd, configFor(cwd).agentDirs).map(
433
- (agent) => `- ${agent.name}${agent.model ? ` (${agent.model})` : ""}: ${agent.description}`,
434
- );
455
+ const agentList = discoverAgents(cwd, configFor(cwd).agentDirs).map((agent) => {
456
+ const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
457
+ return `- ${agent.name}${qualifiers ? ` (${qualifiers})` : ""}: ${agent.description}`;
458
+ });
435
459
 
436
460
  pi.registerTool({
437
461
  name: "delegate",
@@ -439,17 +463,19 @@ export default function (pi: ExtensionAPI) {
439
463
  description: [
440
464
  "Start a delegate: a background run of one of the agents below on one focused task. Returns a job id immediately; the report arrives later as a follow-up message.",
441
465
  "",
442
- "Available agents (default model in parentheses):",
466
+ "Available agents:",
443
467
  ...agentList,
444
468
  "",
445
469
  "A delegate gets the project instructions but not this conversation: it cannot see the user's request, the files you read, or your decisions. Write `task` as a self-contained brief: the goal and why, what you already know (paths, symbols, errors), scope and constraints, whether to edit files or only report, and what to return (format, length, path:line evidence).",
446
470
  "",
471
+ "With isolated: true, the delegate runs in an isolated git clone at .pi/worktrees/<job id> (gitignore that path), starting from the main tree exactly as it is now, uncommitted and untracked files included. It never touches the main tree and may commit freely; delegate_apply brings its changes back.",
472
+ "",
447
473
  "To follow up on or redirect an existing job, see delegate_steer.",
448
474
  ].join("\n"),
449
475
  promptSnippet:
450
476
  "Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
451
477
  promptGuidelines: [
452
- "You are the orchestrator, and delegating is your default: plan, split the work, brief delegates, and integrate their reports. Delegation is authorized; do not wait for the user to ask. Your context is the scarce resource: everything you read stays in it, is re-sent with every later request, and brings compaction closer. A delegate works in a fresh context, often on a cheaper model, and returns only its report.",
478
+ "You are the orchestrator, and delegating is your default: plan, split the work, brief delegates, and integrate their reports. Delegate on your own initiative. Your context is the scarce resource: everything you read stays in it, is re-sent with every later request, and brings compaction closer. A delegate works in a fresh context, often on a cheaper model, and returns only its report.",
453
479
  "Delegate exploration, research, implementation beyond a small edit, build/test/debug loops, and reviews. Work directly only for reading one known file or the lines you are about to edit, one targeted search, a small edit (about 30 lines in one file), a quick verification (one test run or one cited line), or a command the user asked you to run. Shell one-liners and scripts that search or read code count as exploration, not quick commands.",
454
480
  "Your failure mode is drifting into doing the work yourself, one quick search at a time. Decide what to delegate before your first exploratory call; if one targeted search does not settle it, delegate the rest.",
455
481
  "Start every independent delegate before waiting on any, ideally in one message. Trust reports instead of repeating their searches; check only what you act on. If a report falls short, delegate a follow-up that names the gap instead of redoing the work yourself.",
@@ -468,10 +494,13 @@ export default function (pi: ExtensionAPI) {
468
494
  "Model tier (cheap, balanced, strong) or an explicit provider/model, with an optional :<thinking> suffix.",
469
495
  }),
470
496
  ),
497
+ isolated: Type.Optional(
498
+ Type.Boolean({ description: "Run in an isolated git clone; apply results with delegate_apply." }),
499
+ ),
471
500
  }),
472
501
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
473
502
  const params = dropNulls(rawParams);
474
- const { agent: agentName, description, task, model } = params;
503
+ const { agent: agentName, description, task, model, isolated } = params;
475
504
  if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
476
505
  const agents = discoverAgents(ctx.cwd, configFor(ctx.cwd).agentDirs);
477
506
  const agent = agents.find((candidate) => candidate.name === agentName);
@@ -479,7 +508,8 @@ export default function (pi: ExtensionAPI) {
479
508
  const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
480
509
  throw new Error(`Unknown agent "${agentName}". Available agents: ${names}.`);
481
510
  }
482
- return runDelegate(ctx, agent, undefined, { description, model }, task, signal);
511
+ const effective = isolated ?? agent.isolated;
512
+ return runDelegate(ctx, agent, undefined, { description, model, isolated: effective }, task, signal);
483
513
  },
484
514
 
485
515
  renderCall(args, theme, context) {
@@ -518,7 +548,7 @@ export default function (pi: ExtensionAPI) {
518
548
  name: "delegate_steer",
519
549
  label: "Steer delegate",
520
550
  description:
521
- "Send a message to a delegate job. A running job reads it before its next model request. A finished job, whatever its status, continues its own transcript with the message as its next instruction and reports again. Continue a job for follow-up on the same work. For a new task, or a job past half its context window (shown in its report), start a fresh delegate with a condensed brief of what the old job found.",
551
+ "Send a message to a delegate job. A running job reads it before its next model request. A finished job, whatever its status, continues its own transcript (its brief, its work, prior steers) with the message as its next instruction and reports again, so send only what is new. Continue a job for follow-up on the same work. For a new task, or a job past half its context window (shown in its report), start a fresh delegate with a condensed brief of what the old job found.",
522
552
  promptSnippet: "Send guidance to a delegate by job id, or continue a finished one",
523
553
  parameters: Type.Object({
524
554
  id: Type.String({
@@ -574,6 +604,11 @@ export default function (pi: ExtensionAPI) {
574
604
  }
575
605
  const prior = store.find(id);
576
606
  if (!id || !prior) throw new Error(`Unknown delegate job "${id}".`);
607
+ // An applied or discarded clone cannot be continued; a revive would run in the main tree.
608
+ if (prior.cloneClosed)
609
+ throw new Error(
610
+ `The isolated clone of delegate job "${id}" was already applied or discarded; delegate_steer cannot continue it. Start a fresh delegate with a condensed brief instead.`,
611
+ );
577
612
  const agents = discoverAgents(ctx.cwd, configFor(ctx.cwd).agentDirs);
578
613
  const agent = agents.find((candidate) => candidate.name === prior.agent);
579
614
  if (!agent) {
@@ -584,7 +619,11 @@ export default function (pi: ExtensionAPI) {
584
619
  ctx,
585
620
  agent,
586
621
  prior,
587
- { description: prior.description, model: params.model ?? prior.model },
622
+ {
623
+ description: prior.description,
624
+ model: params.model ?? prior.model,
625
+ isolated: Boolean(prior.isolation),
626
+ },
588
627
  prior.task,
589
628
  signal,
590
629
  params.message,
@@ -662,6 +701,106 @@ export default function (pi: ExtensionAPI) {
662
701
  },
663
702
  });
664
703
 
704
+ pi.registerTool({
705
+ name: "delegate_apply",
706
+ label: "Apply delegate",
707
+ description:
708
+ "Apply an isolated delegate's changes to the main working tree by job id. The delegate's commits and uncommitted changes are 3-way merged onto a fresh snapshot of the main tree, so nearby but non-overlapping edits apply cleanly; only a true conflict fails. On conflict the clone is kept and the error explains the recovery. The job must be finished, not running.",
709
+ promptSnippet: "Apply an isolated delegate's clone to the main tree, or discard it, by job id",
710
+ parameters: Type.Object({
711
+ id: Type.String({ description: "Job id of a finished isolated delegate." }),
712
+ discard: Type.Optional(
713
+ Type.Boolean({ description: "Remove the delegate's clone without applying its changes." }),
714
+ ),
715
+ }),
716
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
717
+ const params = dropNulls(rawParams);
718
+ const id = jobId(params.id);
719
+ const job = store.find(id);
720
+ if (!id || !job) throw new Error(`Unknown delegate job "${id}".`);
721
+ if (job.status === "running")
722
+ throw new Error(`Delegate job "${id}" is still running; steer it or cancel it first.`);
723
+ if (!job.isolation)
724
+ throw new Error(`Delegate job "${id}" is not isolated; its changes are already in the main tree.`);
725
+ if (params.discard === true) {
726
+ removeClone(job.isolation);
727
+ job.isolation = undefined;
728
+ job.cloneClosed = true;
729
+ store.save(job);
730
+ return {
731
+ content: [
732
+ {
733
+ type: "text",
734
+ text: `Discarded the isolated clone of delegate "${job.agent}" (job ${job.id}); nothing was applied.`,
735
+ },
736
+ ],
737
+ details: { id: job.id, agent: job.agent, discarded: true },
738
+ };
739
+ }
740
+ const result = applyClone(job.isolation);
741
+ if (result.kind === "conflict") {
742
+ // Base rule: base tracks the newest snapshot, so the next apply works whether or not the delegate rebased yet.
743
+ job.isolation = { ...job.isolation, base: result.snapshot };
744
+ store.save(job);
745
+ throw new Error(
746
+ `Main tree changed under delegate job "${job.id}"; conflicting files: ${result.files.join(", ") || "(unknown)"}. The clone at ${job.isolation.clone} was kept. Steer job ${job.id} with: "Main tree changed under you. In your clone run \`git rebase main-snapshot\` (or merge), resolve conflicts, commit." Then call delegate_apply again.`,
747
+ );
748
+ }
749
+ const stat = result.kind === "applied" ? `\n${result.stat}` : "";
750
+ removeClone(job.isolation);
751
+ job.isolation = undefined;
752
+ job.cloneClosed = true;
753
+ store.save(job);
754
+ return {
755
+ content: [
756
+ {
757
+ type: "text",
758
+ text:
759
+ result.kind === "empty"
760
+ ? `Delegate "${job.agent}" (job ${job.id}) made no changes; its clone was removed.`
761
+ : `Applied the changes of delegate "${job.agent}" (job ${job.id}) to the main tree:${stat}\n(clone removed)`,
762
+ },
763
+ ],
764
+ details: { id: job.id, agent: job.agent, diff: result.kind === "applied" ? result.diff : undefined },
765
+ };
766
+ },
767
+
768
+ renderCall(args, theme, context) {
769
+ return toolLayout(
770
+ "delegate_apply",
771
+ jobTarget(args?.id, theme),
772
+ argText(args?.discard) === "true" ? "discard" : "",
773
+ theme,
774
+ context.expanded,
775
+ );
776
+ },
777
+
778
+ renderResult(result, { expanded }, theme, context) {
779
+ const details = result.details as
780
+ { id: string; agent: string; discarded?: boolean; diff?: string } | undefined;
781
+ const body = resultText(result);
782
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
783
+ const status = details.discarded ? "clone discarded" : "changes applied";
784
+ const header = `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", status)}`;
785
+ const diff = details.diff?.trim() ? renderDiff(piDiff(details.diff)) : "";
786
+ if (!diff) return new Text(header, 0, 0);
787
+ const lines = diff.split("\n");
788
+ // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
789
+ const shown =
790
+ expanded || lines.length <= COLLAPSED_OUTPUT_LINES
791
+ ? lines
792
+ : [
793
+ ...lines.slice(0, COLLAPSED_OUTPUT_LINES),
794
+ moreLines(theme, lines.length - COLLAPSED_OUTPUT_LINES),
795
+ ];
796
+ const container = new Container();
797
+ container.addChild(new Text(header, 0, 0));
798
+ container.addChild(new Spacer(1));
799
+ container.addChild(new Text(shown.join("\n"), 0, 0));
800
+ return container;
801
+ },
802
+ });
803
+
665
804
  pi.registerTool({
666
805
  name: "delegate_list",
667
806
  label: "List delegates",
package/isolation.ts ADDED
@@ -0,0 +1,183 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join, relative, resolve } from "node:path";
4
+
5
+ /** Persisted with the job: where the clone lives and which main-tree snapshot it started from. */
6
+ export type IsolationState = { clone: string; base: string };
7
+
8
+ export type ApplyResult =
9
+ | { kind: "applied"; stat: string; diff: string }
10
+ | { kind: "empty" }
11
+ | { kind: "conflict"; files: string[]; snapshot: string };
12
+
13
+ const IDENTITY = ["-c", "user.name=pi-delegate", "-c", "user.email=pi-delegate@localhost"];
14
+ const SNAPSHOT_BRANCH = "main-snapshot";
15
+
16
+ /** One git invocation; `indexFile` swaps in a scratch index and `input` feeds stdin (patches). */
17
+ function git(
18
+ args: string[],
19
+ options: { cwd?: string; gitDir?: string; workTree?: string; input?: string; indexFile?: string } = {},
20
+ ): string {
21
+ const command = [
22
+ ...(options.gitDir ? ["--git-dir", options.gitDir] : []),
23
+ ...(options.workTree ? ["--work-tree", options.workTree] : []),
24
+ ...args,
25
+ ];
26
+ try {
27
+ return execFileSync("git", command, {
28
+ cwd: options.cwd,
29
+ input: options.input,
30
+ encoding: "utf8",
31
+ // Binary diffs of real repositories blow past execFileSync's 1 MiB default.
32
+ maxBuffer: 1024 ** 3,
33
+ env: options.indexFile ? { ...process.env, GIT_INDEX_FILE: options.indexFile } : process.env,
34
+ });
35
+ } catch (error) {
36
+ const failure = error as { stderr?: string };
37
+ const detail = (failure.stderr ?? "").trim();
38
+ throw new Error(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`);
39
+ }
40
+ }
41
+
42
+ /** Clones live at <repoRoot>/.pi/worktrees/<jobId>, so the root sits three directories up. */
43
+ function rootOf(iso: IsolationState): string {
44
+ return resolve(iso.clone, "..", "..", "..");
45
+ }
46
+
47
+ /**
48
+ * Commits the main tree's current content (committed, uncommitted, and untracked files, honoring
49
+ * .gitignore) with the recorded base as parent, through a scratch index so the clone's own checkout
50
+ * and index stay untouched. Updates and returns the `main-snapshot` branch.
51
+ */
52
+ function snapshotMainTree(iso: IsolationState, root: string): string {
53
+ const gitDir = join(iso.clone, ".git");
54
+ const indexFile = join(gitDir, "pi-delegate-snapshot-index");
55
+ try {
56
+ git(["read-tree", iso.base], { gitDir, indexFile });
57
+ git(["add", "-A"], { gitDir, workTree: root, indexFile });
58
+ const tree = git(["write-tree"], { gitDir, indexFile }).trim();
59
+ const snapshot = git([...IDENTITY, "commit-tree", tree, "-p", iso.base, "-m", "main tree snapshot"], {
60
+ gitDir,
61
+ }).trim();
62
+ git(["branch", "-f", SNAPSHOT_BRANCH, snapshot], { gitDir });
63
+ return snapshot;
64
+ } finally {
65
+ rmSync(indexFile, { force: true });
66
+ }
67
+ }
68
+
69
+ /** Creates the isolated clone and the base commit capturing the main tree as the user sees it now. */
70
+ export function createIsolation(cwd: string, jobId: string): IsolationState {
71
+ let root: string;
72
+ try {
73
+ root = git(["rev-parse", "--show-toplevel"], { cwd }).trim();
74
+ } catch {
75
+ throw new Error('isolation: "clone" requires the session to run inside a git repository.');
76
+ }
77
+ const clone = join(root, ".pi", "worktrees", jobId);
78
+ rmSync(clone, { recursive: true, force: true });
79
+ git(["clone", "--shared", "--quiet", root, clone]);
80
+ try {
81
+ // Snapshots use --work-tree=<root>, so the clones themselves must never be picked up; the
82
+ // main repo's local excludes must carry over too, or locally-ignored files land in clones.
83
+ let exclude = "\n.pi/worktrees/\n";
84
+ try {
85
+ const mainExclude = git(["rev-parse", "--git-path", "info/exclude"], { cwd: root }).trim();
86
+ exclude = `${readFileSync(resolve(root, mainExclude), "utf8")}${exclude}`;
87
+ } catch {
88
+ // No local exclude file; .gitignore still applies.
89
+ }
90
+ writeFileSync(join(clone, ".git", "info", "exclude"), exclude);
91
+ let head: string;
92
+ try {
93
+ head = git(["rev-parse", "HEAD"], { cwd: clone }).trim();
94
+ } catch {
95
+ throw new Error("cannot isolate a repository with no commits.");
96
+ }
97
+ const iso: IsolationState = { clone, base: head };
98
+ iso.base = snapshotMainTree(iso, root);
99
+ // The clone's checkout still matches the upstream tip; make it match the snapshot instead.
100
+ git(["reset", "--hard", "--quiet", iso.base], { cwd: clone });
101
+ return iso;
102
+ } catch (error) {
103
+ rmSync(clone, { recursive: true, force: true });
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ /** The clone path matching the session cwd's position inside the repository. */
109
+ export function cloneCwd(iso: IsolationState, cwd: string): string {
110
+ const rel = relative(rootOf(iso), cwd);
111
+ return rel.startsWith("..") ? iso.clone : join(iso.clone, rel);
112
+ }
113
+
114
+ /** Clone location plus a stat of everything the delegate changed, for the job's report. */
115
+ export function isolationSummary(iso: IsolationState): string {
116
+ const lines = [`Isolated clone: ${iso.clone}`];
117
+ try {
118
+ // Staging first pulls uncommitted and untracked changes into the stat.
119
+ git(["add", "-A"], { cwd: iso.clone });
120
+ const stat = git(["diff", "--stat", iso.base], { cwd: iso.clone }).trimEnd();
121
+ if (stat) lines.push(`Changes vs the main tree at launch:\n${stat}`);
122
+ } catch {
123
+ // The clone may already be applied or gone; the path alone still says where the work lives.
124
+ }
125
+ return lines.join("\n");
126
+ }
127
+
128
+ export function removeClone(iso: IsolationState): void {
129
+ rmSync(iso.clone, { recursive: true, force: true });
130
+ }
131
+
132
+ /**
133
+ * Merges the delegate's clone into the main working tree. Base rule: `base` always tracks the newest
134
+ * `main-snapshot`, so a repeat apply is correct whether or not the delegate rebased onto it yet.
135
+ * The main repository's .git is never written to; only its working tree receives the final patch.
136
+ */
137
+ export function applyClone(iso: IsolationState): ApplyResult {
138
+ const root = rootOf(iso);
139
+ const run = (args: string[]) => git(args, { cwd: iso.clone });
140
+ // Commit uncommitted delegate work so the rebase carries it.
141
+ run(["add", "-A"]);
142
+ if (run(["status", "--porcelain"]).trim()) run([...IDENTITY, "commit", "--no-verify", "-m", "delegate work"]);
143
+ const branch = run(["rev-parse", "--abbrev-ref", "HEAD"]).trim();
144
+ if (branch === SNAPSHOT_BRANCH)
145
+ throw new Error(`the clone is on ${SNAPSHOT_BRANCH}; the delegate must keep its work on its own branch`);
146
+ // Snapshot the current main tree, then replay the delegate's commits onto it with a real 3-way
147
+ // merge: git tolerates nearby, non-overlapping edits that raw patch context matching rejects.
148
+ const snapshot = snapshotMainTree(iso, root);
149
+ try {
150
+ run([...IDENTITY, "rebase", "--empty=drop", SNAPSHOT_BRANCH]);
151
+ } catch (error) {
152
+ const files = run(["diff", "--name-only", "--diff-filter=U"]).trim();
153
+ try {
154
+ run(["rebase", "--abort"]);
155
+ } catch {
156
+ // The rebase failed before starting; there is nothing to abort.
157
+ }
158
+ // A real conflict leaves unmerged files; anything else (e.g. a missing git identity) surfaces as-is.
159
+ if (!files) throw error;
160
+ return { kind: "conflict", files: files.split("\n"), snapshot };
161
+ }
162
+ // After the rebase this diff is exactly the delegate's work on the current main state.
163
+ const patch = run(["diff", "--binary", SNAPSHOT_BRANCH, "HEAD"]);
164
+ if (!patch.trim()) return { kind: "empty" };
165
+ // A changed submodule serializes as a "Subproject commit" hunk that git apply rejects outright.
166
+ if (run(["diff", "--raw", SNAPSHOT_BRANCH, "HEAD"]).match(/^:160000 160000 /m))
167
+ throw new Error("the delegate changed a submodule (gitlink), which git apply cannot carry; apply it manually");
168
+ try {
169
+ git(["apply", "--check", "-"], { cwd: root, input: patch });
170
+ } catch (error) {
171
+ // The patch was built on the exact snapshot, so a rejection means the tree moved after it.
172
+ throw new Error(
173
+ `${(error as Error).message} — the main tree changed since the snapshot; call delegate_apply again`,
174
+ );
175
+ }
176
+ git(["apply", "-"], { cwd: root, input: patch });
177
+ // Without --binary, binary files render as a name-only "Binary files differ" line.
178
+ return {
179
+ kind: "applied",
180
+ stat: run(["diff", "--stat", SNAPSHOT_BRANCH, "HEAD"]).trimEnd(),
181
+ diff: run(["diff", SNAPSHOT_BRANCH, "HEAD"]),
182
+ };
183
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.25",
3
+ "version": "0.0.27",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,6 +23,7 @@
23
23
  "agents.ts",
24
24
  "child.ts",
25
25
  "format.ts",
26
+ "isolation.ts",
26
27
  "agents",
27
28
  "README.md",
28
29
  "LICENSE"
package/store.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ChildActivity, ChildUpdate } from "./child.ts";
2
+ import type { IsolationState } from "./isolation.ts";
2
3
 
3
4
  export type JobStatus = "running" | "done" | "failed" | "cancelled" | "interrupted";
4
5
  export type InspectJob = {
@@ -15,6 +16,9 @@ export type InspectJob = {
15
16
  endedAt?: number;
16
17
  status: JobStatus;
17
18
  activity: ChildActivity[];
19
+ isolation?: IsolationState;
20
+ /** Set once an isolated job's clone was applied or discarded, so a steer revive refuses instead of rerunning in the main tree. */
21
+ cloneClosed?: boolean;
18
22
  };
19
23
 
20
24
  export type DelegateJob = InspectJob & {
@@ -110,6 +114,13 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
110
114
  notify();
111
115
  return true;
112
116
  },
117
+ /** Appends a corrected entry for a finished job changed after completion (isolation applied, discarded, or re-based). */
118
+ save: (job: InspectJob) => {
119
+ drop(job.id);
120
+ history.unshift(job);
121
+ append(JOB_ENTRY, { ...job, activity: [...job.activity] });
122
+ notify();
123
+ },
113
124
  /** Rebuilds history from the branch and returns the jobs it marked interrupted. */
114
125
  restore: (branch: readonly unknown[]): InspectJob[] => {
115
126
  history.length = 0;