@deathbeam/pi-delegate 0.0.30 → 0.0.32

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,7 @@
1
1
  # [@deathbeam/pi-delegate](https://www.npmjs.com/package/@deathbeam/pi-delegate)
2
2
 
3
- Run subagents with `delegate`, `delegate_list`, `delegate_steer`, `delegate_cancel`, and `delegate_apply`.
3
+ Run subagents with `delegate`, `delegate_list`, `delegate_steer`, `delegate_cancel`, `delegate_apply`, and
4
+ `delegate_discard`.
4
5
  Use `/delegate` command to inspect jobs in a full-screen TUI.
5
6
 
6
7
  ## Installation
@@ -51,10 +52,12 @@ Explore the codebase and report relevant paths.
51
52
  ## Isolation
52
53
 
53
54
  `isolated: true` (on a `delegate` call or in agent frontmatter) runs the delegate in its own git clone at
54
- `.pi/worktrees/<id>`, starting from your current working tree including uncommitted changes. Add `.pi/worktrees/` to
55
- `.gitignore`.
55
+ `.pi/worktrees/<id>`, starting from your current working tree including uncommitted changes.
56
56
 
57
57
  `delegate_apply` merges the result into your working tree as uncommitted changes.
58
+ `delegate_discard` discards the clone and its changes.
59
+
60
+ Any later delegate can share that clone with `clone: <job id>`, for review, tests, or follow-up work.
58
61
 
59
62
  ## Development
60
63
 
package/format.ts CHANGED
@@ -280,7 +280,7 @@ export function reportText(report: DelegateReport): string {
280
280
  // The apply hint is for the model only: the transcript renders `output`, so users never see it.
281
281
  const hint =
282
282
  report.isolation && !report.cloneClosed
283
- ? `\n\nCall delegate_apply with job ${report.id} to land its changes.`
283
+ ? `\n\nCall delegate_apply with job ${report.id} to land its changes, or delegate_discard to drop them.`
284
284
  : "";
285
285
  return `${head} finished.${output ? `\n\n${output}` : ""}${hint}`;
286
286
  }
package/index.ts CHANGED
@@ -50,7 +50,14 @@ type SteerDetails = Pick<
50
50
  elapsedMs: number;
51
51
  };
52
52
 
53
- const DELEGATION_TOOLS = new Set(["delegate", "delegate_apply", "delegate_list", "delegate_steer", "delegate_cancel"]);
53
+ const DELEGATION_TOOLS = new Set([
54
+ "delegate",
55
+ "delegate_apply",
56
+ "delegate_discard",
57
+ "delegate_list",
58
+ "delegate_steer",
59
+ "delegate_cancel",
60
+ ]);
54
61
  const WIDGET_KEY = "delegate";
55
62
  const RESULT_MESSAGE = "delegate-result";
56
63
  const REMINDER_MESSAGE = "delegate-reminder";
@@ -102,6 +109,39 @@ export default function (pi: ExtensionAPI) {
102
109
  return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
103
110
  };
104
111
 
112
+ /** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
113
+ const jobsInClone = (clone: string) => store.all().filter((job) => job.isolation?.clone === clone);
114
+
115
+ /** A job that still has a clone; any job id that ran in a clone is a handle on it. */
116
+ const clonedJob = (id: string) => {
117
+ const job = store.findOrThrow(id);
118
+ const isolation = job.isolation;
119
+ if (!isolation)
120
+ throw new Error(
121
+ job.cloneClosed
122
+ ? `The clone of delegate job "${id}" was already applied or discarded.`
123
+ : `Delegate job "${id}" did not run in an isolated clone.`,
124
+ );
125
+ return { job, isolation };
126
+ };
127
+
128
+ /** Closing a clone is a clone-wide operation: every job id that ran in it stops pointing at it. */
129
+ const closeClone = (isolation: IsolationState) => {
130
+ removeClone(isolation);
131
+ for (const shared of jobsInClone(isolation.clone)) {
132
+ shared.isolation = undefined;
133
+ shared.cloneClosed = true;
134
+ store.save(shared);
135
+ }
136
+ };
137
+
138
+ /** One job at a time per clone: a shared clone is a shared working directory. */
139
+ const requireIdleClone = (isolation: IsolationState) => {
140
+ const busy = store.live().find((job) => job.isolation?.clone === isolation.clone);
141
+ if (busy)
142
+ throw new Error(`Delegate job "${busy.id}" is running in this clone; wait for it or cancel it first.`);
143
+ };
144
+
105
145
  const refreshWidget = (ctx: ExtensionContext) => {
106
146
  if (!ctx.hasUI) return;
107
147
  store.notify();
@@ -173,7 +213,7 @@ export default function (pi: ExtensionAPI) {
173
213
  ctx: ExtensionContext,
174
214
  agent: AgentFile,
175
215
  prior: InspectJob | undefined,
176
- fields: { description: string; model?: string; isolated?: boolean },
216
+ fields: { description: string; model?: string; isolated?: boolean; clone?: IsolationState },
177
217
  task: string,
178
218
  signal: AbortSignal | undefined,
179
219
  prompt = task,
@@ -184,7 +224,9 @@ export default function (pi: ExtensionAPI) {
184
224
  );
185
225
  const displayModel = thinking ? `${model}:${thinking}` : model;
186
226
  const id = prior?.id ?? randomUUID().slice(0, 8);
187
- const isolation = fields.isolated ? (prior?.isolation ?? createIsolation(ctx.cwd, id)) : undefined;
227
+ const isolation =
228
+ prior?.isolation ?? fields.clone ?? (fields.isolated ? createIsolation(ctx.cwd, id) : undefined);
229
+ if (isolation) requireIdleClone(isolation);
188
230
 
189
231
  const job: DelegateJob = {
190
232
  // A revived job keeps its id: the pinned child session id reopens the old transcript.
@@ -228,19 +270,22 @@ export default function (pi: ExtensionAPI) {
228
270
  if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
229
271
  const entrypoint = process.argv[1];
230
272
  if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
273
+ const cwd = isolation ? cloneCwd(isolation, ctx.cwd) : ctx.cwd;
231
274
  const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
232
- cwd: isolation ? cloneCwd(isolation, ctx.cwd) : ctx.cwd,
275
+ cwd,
233
276
  shell: false,
234
277
  stdio: "pipe",
235
278
  });
236
- store.launch(job, details.background);
279
+ store.launch(job);
280
+ // The brief was written against the main tree, so its absolute paths need mapping to the clone.
237
281
  const isolatedPrompt = isolation
238
- ? `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.`
282
+ ? `You are working in an isolated git clone at ${isolation.clone}. Your working directory ${cwd} is already inside it, so use relative paths and do not cd into it. Paths under ${ctx.cwd} in the task refer to the same files under ${cwd}. The main working tree is untouched; any edits or commits you make stay in this clone until the orchestrator applies them.${tools.includes("bash") ? " `git diff main-snapshot` shows all changes made in this clone." : ""}`
239
283
  : "";
240
284
  const run = runChild(
241
285
  child,
242
286
  isolatedPrompt ? `${isolatedPrompt}\n\n${prompt}` : prompt,
243
- details.background ? job.controller.signal : signal,
287
+ // Foreground runs also stop on the tool's own abort (Esc); delegate_cancel and shutdown use the controller.
288
+ details.background || !signal ? job.controller.signal : AbortSignal.any([signal, job.controller.signal]),
244
289
  (update) => store.record(job, update),
245
290
  Boolean(prior),
246
291
  );
@@ -389,7 +434,9 @@ export default function (pi: ExtensionAPI) {
389
434
  "",
390
435
  "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).",
391
436
  "",
392
- "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.",
437
+ "With isolated: true, the delegate runs in an isolated git clone at .pi/worktrees/<job id>, 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, delegate_discard drops them.",
438
+ "",
439
+ "To run another delegate in an isolated job's clone, pass that job id as `clone`. delegate_apply or delegate_discard with any job id from that clone acts on the whole clone, and only one job can run in a clone at a time.",
393
440
  "",
394
441
  "To follow up on or redirect an existing job, see delegate_steer.",
395
442
  ].join("\n"),
@@ -416,16 +463,24 @@ export default function (pi: ExtensionAPI) {
416
463
  }),
417
464
  ),
418
465
  isolated: Type.Optional(
419
- Type.Boolean({ description: "Run in an isolated git clone; apply results with delegate_apply." }),
466
+ Type.Boolean({ description: "Run in a new isolated git clone; apply results with delegate_apply." }),
467
+ ),
468
+ clone: Type.Optional(
469
+ Type.String({
470
+ description: "Job id of an isolated delegate; run in its clone instead of the main tree.",
471
+ }),
420
472
  ),
421
473
  }),
422
474
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
423
475
  const params = dropNulls(rawParams);
424
476
  const { agent: agentName, description, task, model, isolated } = params;
425
477
  if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
478
+ const cloneId = jobId(params.clone);
479
+ if (cloneId && isolated === false) throw new Error("clone always runs isolated; omit isolated: false.");
480
+ const clone = cloneId ? clonedJob(cloneId).isolation : undefined;
426
481
  const agent = agentByName(ctx.cwd, agentName);
427
- const effective = isolated ?? agent.isolated;
428
- return runDelegate(ctx, agent, undefined, { description, model, isolated: effective }, task, signal);
482
+ const effective = clone ? true : (isolated ?? agent.isolated);
483
+ return runDelegate(ctx, agent, undefined, { description, model, isolated: effective, clone }, task, signal);
429
484
  },
430
485
 
431
486
  renderCall(args, theme, context) {
@@ -569,7 +624,7 @@ export default function (pi: ExtensionAPI) {
569
624
  name: "delegate_cancel",
570
625
  label: "Cancel delegate",
571
626
  description: "Cancel a running delegate by job id. It sends no report; delegate_steer can continue it later.",
572
- promptSnippet: "Cancel a running background delegate by job id",
627
+ promptSnippet: "Cancel a running delegate by job id",
573
628
  parameters: Type.Object({
574
629
  id: Type.String({ description: "Job id from delegate or delegate_list." }),
575
630
  }),
@@ -606,53 +661,29 @@ export default function (pi: ExtensionAPI) {
606
661
  name: "delegate_apply",
607
662
  label: "Apply delegate",
608
663
  description:
609
- "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.",
610
- promptSnippet: "Apply an isolated delegate's clone to the main tree, or discard it, by job id",
664
+ "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. No delegate may be running in its clone.",
665
+ promptSnippet: "Apply an isolated delegate's clone to the main tree by job id",
611
666
  parameters: Type.Object({
612
- id: Type.String({ description: "Job id of a finished isolated delegate." }),
613
- discard: Type.Optional(
614
- Type.Boolean({ description: "Remove the delegate's clone without applying its changes." }),
615
- ),
667
+ id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
616
668
  }),
617
669
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
618
670
  const params = dropNulls(rawParams);
619
671
  const id = jobId(params.id);
620
- const job = store.findOrThrow(id);
621
- if (job.status === "running")
622
- throw new Error(`Delegate job "${id}" is still running; steer it or cancel it first.`);
623
- if (!job.isolation)
624
- throw new Error(`Delegate job "${id}" is not isolated; its changes are already in the main tree.`);
625
-
626
- const isolation = job.isolation;
627
- const closeClone = () => {
628
- removeClone(isolation);
629
- job.isolation = undefined;
630
- job.cloneClosed = true;
631
- store.save(job);
632
- };
633
- if (params.discard === true) {
634
- closeClone();
635
- return {
636
- content: [
637
- {
638
- type: "text",
639
- text: `Discarded the isolated clone of delegate "${job.agent}" (job ${job.id}); nothing was applied.`,
640
- },
641
- ],
642
- details: { id: job.id, agent: job.agent, discarded: true },
643
- };
644
- }
645
- const result = applyClone(job.isolation);
672
+ const { job, isolation } = clonedJob(id);
673
+ requireIdleClone(isolation);
674
+ const result = applyClone(isolation);
646
675
  if (result.kind === "conflict") {
647
676
  // Base rule: base tracks the newest snapshot, so the next apply works whether or not the delegate rebased yet.
648
- job.isolation = { ...job.isolation, base: result.snapshot };
649
- store.save(job);
677
+ for (const shared of jobsInClone(isolation.clone)) {
678
+ shared.isolation = { ...isolation, base: result.snapshot };
679
+ store.save(shared);
680
+ }
650
681
  throw new Error(
651
- `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.`,
682
+ `Main tree changed under delegate job "${job.id}"; conflicting files: ${result.files.join(", ") || "(unknown)"}. The clone at ${isolation.clone} was kept. Steer job ${job.id} with: "The main tree changed under you. Run \`git rebase main-snapshot\`, resolve each conflict, then \`git add\` the files and run \`git rebase --continue\` until the rebase finishes." Then call delegate_apply again.`,
652
683
  );
653
684
  }
654
685
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
655
- closeClone();
686
+ closeClone(isolation);
656
687
  return {
657
688
  content: [
658
689
  {
@@ -668,22 +699,14 @@ export default function (pi: ExtensionAPI) {
668
699
  },
669
700
 
670
701
  renderCall(args, theme, context) {
671
- return toolLayout(
672
- "delegate_apply",
673
- jobTarget(args?.id, theme),
674
- argText(args?.discard) === "true" ? "discard" : "",
675
- theme,
676
- context.expanded,
677
- );
702
+ return toolLayout("delegate_apply", jobTarget(args?.id, theme), "", theme, context.expanded);
678
703
  },
679
704
 
680
705
  renderResult(result, { expanded }, theme, context) {
681
- const details = result.details as
682
- { id: string; agent: string; discarded?: boolean; diff?: string } | undefined;
706
+ const details = result.details as { id: string; agent: string; diff?: string } | undefined;
683
707
  const body = resultText(result);
684
708
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
685
- const status = details.discarded ? "clone discarded" : "changes applied";
686
- const header = `\n${resultHeader(theme, details, status)}`;
709
+ const header = `\n${resultHeader(theme, details, "changes applied")}`;
687
710
  const diff = details.diff?.trim() ? renderDiff(piDiff(details.diff)) : "";
688
711
  if (!diff) return new Text(header, 0, 0);
689
712
  // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
@@ -697,6 +720,43 @@ export default function (pi: ExtensionAPI) {
697
720
  },
698
721
  });
699
722
 
723
+ pi.registerTool({
724
+ name: "delegate_discard",
725
+ label: "Discard delegate clone",
726
+ description: "Remove an isolated delegate's clone without applying its changes.",
727
+ promptSnippet: "Discard an isolated delegate's clone by job id",
728
+ parameters: Type.Object({
729
+ id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
730
+ }),
731
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
732
+ const params = dropNulls(rawParams);
733
+ const id = jobId(params.id);
734
+ const { job, isolation } = clonedJob(id);
735
+ requireIdleClone(isolation);
736
+ closeClone(isolation);
737
+ return {
738
+ content: [
739
+ {
740
+ type: "text",
741
+ text: `Discarded the isolated clone of delegate "${job.agent}" (job ${job.id}); nothing was applied.`,
742
+ },
743
+ ],
744
+ details: { id: job.id, agent: job.agent, discarded: true },
745
+ };
746
+ },
747
+
748
+ renderCall(args, theme, context) {
749
+ return toolLayout("delegate_discard", jobTarget(args?.id, theme), "", theme, context.expanded);
750
+ },
751
+
752
+ renderResult(result, _options, theme, context) {
753
+ const details = result.details as { id: string; agent: string; discarded?: boolean } | undefined;
754
+ const body = resultText(result);
755
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
756
+ return new Text(`\n${resultHeader(theme, details, "clone discarded")}`, 0, 0);
757
+ },
758
+ });
759
+
700
760
  pi.registerTool({
701
761
  name: "delegate_list",
702
762
  label: "List delegates",
package/isolation.ts CHANGED
@@ -72,7 +72,7 @@ export function createIsolation(cwd: string, jobId: string): IsolationState {
72
72
  try {
73
73
  root = git(["rev-parse", "--show-toplevel"], { cwd }).trim();
74
74
  } catch {
75
- throw new Error('isolation: "clone" requires the session to run inside a git repository.');
75
+ throw new Error("isolated: true requires the session to run inside a git repository.");
76
76
  }
77
77
  const clone = join(root, ".pi", "worktrees", jobId);
78
78
  rmSync(clone, { recursive: true, force: true });
@@ -118,7 +118,7 @@ export function isolationSummary(iso: IsolationState): string {
118
118
  // Staging first pulls uncommitted and untracked changes into the stat.
119
119
  git(["add", "-A"], { cwd: iso.clone });
120
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}`);
121
+ if (stat) lines.push(`Changes in this clone:\n${stat}`);
122
122
  } catch {
123
123
  // The clone may already be applied or gone; the path alone still says where the work lives.
124
124
  }
@@ -142,7 +142,9 @@ export function applyClone(iso: IsolationState): ApplyResult {
142
142
  if (run(["status", "--porcelain"]).trim()) run([...IDENTITY, "commit", "--no-verify", "-m", "delegate work"]);
143
143
  const branch = run(["rev-parse", "--abbrev-ref", "HEAD"]).trim();
144
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`);
145
+ throw new Error(
146
+ `the clone is checked out on ${SNAPSHOT_BRANCH}; steer the delegate to move its work onto its own branch, then apply again`,
147
+ );
146
148
  // Snapshot the current main tree, then replay the delegate's commits onto it with a real 3-way
147
149
  // merge: git tolerates nearby, non-overlapping edits that raw patch context matching rejects.
148
150
  const snapshot = snapshotMainTree(iso, root);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.30",
3
+ "version": "0.0.32",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/store.ts CHANGED
@@ -95,11 +95,11 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
95
95
  return job;
96
96
  },
97
97
  liveJob: (id: string) => running.get(id),
98
- /** Writes the launch entry a restarted parent restores from; background jobs join the live set. */
99
- launch: (job: DelegateJob, background: boolean) => {
98
+ /** Writes the launch entry a restarted parent restores from; the job joins the live set until it finishes. */
99
+ launch: (job: DelegateJob) => {
100
100
  append(JOB_ENTRY, snapshot(job));
101
101
  drop(job.id);
102
- if (background) running.set(job.id, job);
102
+ running.set(job.id, job);
103
103
  },
104
104
  record: (job: DelegateJob, update: ChildUpdate) => {
105
105
  if (job.status !== "running") return;
@@ -108,8 +108,7 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
108
108
  if (update.lastDetail !== undefined) job.lastDetail = update.lastDetail;
109
109
  if (update.lastResult !== undefined) job.lastResult = update.lastResult;
110
110
  if (update.contextTokens !== undefined) job.contextTokens = update.contextTokens;
111
- // Activity feeds the live views; a foreground run reports through its tool result instead.
112
- if (update.activity && running.has(job.id)) addActivity(job, update.activity);
111
+ if (update.activity) addActivity(job, update.activity);
113
112
  },
114
113
  /** Leaves the live set and writes the completion entry; false when the job was cancelled. */
115
114
  finish: (job: DelegateJob, status: JobStatus, detail?: string): boolean => {