@deathbeam/pi-delegate 0.0.29 → 0.0.31

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
@@ -277,7 +277,12 @@ export function reportText(report: DelegateReport): string {
277
277
  const head = `Delegate "${report.agent}" (job ${report.id}, ${usageStats(report, report.elapsedMs)})`;
278
278
  if (report.error) return `${head} failed: ${report.error}\n${reviveHint(report.id)}`;
279
279
  const output = (report.output ?? "").trim();
280
- return `${head} finished.${output ? `\n\n${output}` : ""}`;
280
+ // The apply hint is for the model only: the transcript renders `output`, so users never see it.
281
+ const hint =
282
+ report.isolation && !report.cloneClosed
283
+ ? `\n\nCall delegate_apply with job ${report.id} to land its changes, or delegate_discard to drop them.`
284
+ : "";
285
+ return `${head} finished.${output ? `\n\n${output}` : ""}${hint}`;
281
286
  }
282
287
 
283
288
  export function jobLine(info: { description?: string } & UsageInfo, elapsedMs: number): string {
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.
@@ -233,14 +275,15 @@ export default function (pi: ExtensionAPI) {
233
275
  shell: false,
234
276
  stdio: "pipe",
235
277
  });
236
- store.launch(job, details.background);
278
+ store.launch(job);
237
279
  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.`
280
+ ? `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. \`git diff main-snapshot\` shows all changes made in this clone.`
239
281
  : "";
240
282
  const run = runChild(
241
283
  child,
242
284
  isolatedPrompt ? `${isolatedPrompt}\n\n${prompt}` : prompt,
243
- details.background ? job.controller.signal : signal,
285
+ // Foreground runs also stop on the tool's own abort (Esc); delegate_cancel and shutdown use the controller.
286
+ details.background || !signal ? job.controller.signal : AbortSignal.any([signal, job.controller.signal]),
244
287
  (update) => store.record(job, update),
245
288
  Boolean(prior),
246
289
  );
@@ -363,7 +406,10 @@ export default function (pi: ExtensionAPI) {
363
406
  new Text(resultHeader(theme, report, jobSummary(report), report.error ? "failed" : "done"), 0, 0),
364
407
  );
365
408
  if (report.error) container.addChild(new Text(theme.fg("error", report.error), 0, 0));
366
- else if (report.output) appendOutput(container, report.output, expanded, theme);
409
+ else if (report.output) {
410
+ container.addChild(new Spacer(1));
411
+ appendOutput(container, report.output, expanded, theme);
412
+ }
367
413
  return container;
368
414
  });
369
415
 
@@ -386,7 +432,9 @@ export default function (pi: ExtensionAPI) {
386
432
  "",
387
433
  "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).",
388
434
  "",
389
- "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.",
435
+ "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, delegate_discard drops them.",
436
+ "",
437
+ "To run another delegate in an isolated job's clone, pass that job id as `clone`. Every job id that ran in a clone is a handle on it: delegate_apply or delegate_discard with any of them acts on the whole clone, and only one of them can run at a time.",
390
438
  "",
391
439
  "To follow up on or redirect an existing job, see delegate_steer.",
392
440
  ].join("\n"),
@@ -413,16 +461,24 @@ export default function (pi: ExtensionAPI) {
413
461
  }),
414
462
  ),
415
463
  isolated: Type.Optional(
416
- Type.Boolean({ description: "Run in an isolated git clone; apply results with delegate_apply." }),
464
+ Type.Boolean({ description: "Run in a new isolated git clone; apply results with delegate_apply." }),
465
+ ),
466
+ clone: Type.Optional(
467
+ Type.String({
468
+ description: "Job id of an isolated delegate; run in its clone instead of the main tree.",
469
+ }),
417
470
  ),
418
471
  }),
419
472
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
420
473
  const params = dropNulls(rawParams);
421
474
  const { agent: agentName, description, task, model, isolated } = params;
422
475
  if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
476
+ const cloneId = jobId(params.clone);
477
+ if (cloneId && isolated === false) throw new Error("clone always runs isolated; omit isolated: false.");
478
+ const clone = cloneId ? clonedJob(cloneId).isolation : undefined;
423
479
  const agent = agentByName(ctx.cwd, agentName);
424
- const effective = isolated ?? agent.isolated;
425
- return runDelegate(ctx, agent, undefined, { description, model, isolated: effective }, task, signal);
480
+ const effective = clone ? true : (isolated ?? agent.isolated);
481
+ return runDelegate(ctx, agent, undefined, { description, model, isolated: effective, clone }, task, signal);
426
482
  },
427
483
 
428
484
  renderCall(args, theme, context) {
@@ -566,7 +622,7 @@ export default function (pi: ExtensionAPI) {
566
622
  name: "delegate_cancel",
567
623
  label: "Cancel delegate",
568
624
  description: "Cancel a running delegate by job id. It sends no report; delegate_steer can continue it later.",
569
- promptSnippet: "Cancel a running background delegate by job id",
625
+ promptSnippet: "Cancel a running delegate by job id",
570
626
  parameters: Type.Object({
571
627
  id: Type.String({ description: "Job id from delegate or delegate_list." }),
572
628
  }),
@@ -603,53 +659,29 @@ export default function (pi: ExtensionAPI) {
603
659
  name: "delegate_apply",
604
660
  label: "Apply delegate",
605
661
  description:
606
- "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.",
607
- promptSnippet: "Apply an isolated delegate's clone to the main tree, or discard it, by job id",
662
+ "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.",
663
+ promptSnippet: "Apply an isolated delegate's clone to the main tree by job id",
608
664
  parameters: Type.Object({
609
- id: Type.String({ description: "Job id of a finished isolated delegate." }),
610
- discard: Type.Optional(
611
- Type.Boolean({ description: "Remove the delegate's clone without applying its changes." }),
612
- ),
665
+ id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
613
666
  }),
614
667
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
615
668
  const params = dropNulls(rawParams);
616
669
  const id = jobId(params.id);
617
- const job = store.findOrThrow(id);
618
- if (job.status === "running")
619
- throw new Error(`Delegate job "${id}" is still running; steer it or cancel it first.`);
620
- if (!job.isolation)
621
- throw new Error(`Delegate job "${id}" is not isolated; its changes are already in the main tree.`);
622
-
623
- const isolation = job.isolation;
624
- const closeClone = () => {
625
- removeClone(isolation);
626
- job.isolation = undefined;
627
- job.cloneClosed = true;
628
- store.save(job);
629
- };
630
- if (params.discard === true) {
631
- closeClone();
632
- return {
633
- content: [
634
- {
635
- type: "text",
636
- text: `Discarded the isolated clone of delegate "${job.agent}" (job ${job.id}); nothing was applied.`,
637
- },
638
- ],
639
- details: { id: job.id, agent: job.agent, discarded: true },
640
- };
641
- }
642
- const result = applyClone(job.isolation);
670
+ const { job, isolation } = clonedJob(id);
671
+ requireIdleClone(isolation);
672
+ const result = applyClone(isolation);
643
673
  if (result.kind === "conflict") {
644
674
  // Base rule: base tracks the newest snapshot, so the next apply works whether or not the delegate rebased yet.
645
- job.isolation = { ...job.isolation, base: result.snapshot };
646
- store.save(job);
675
+ for (const shared of jobsInClone(isolation.clone)) {
676
+ shared.isolation = { ...isolation, base: result.snapshot };
677
+ store.save(shared);
678
+ }
647
679
  throw new Error(
648
- `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.`,
680
+ `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: "Main tree changed under you. In your clone run \`git rebase main-snapshot\` (or merge), resolve conflicts, commit." Then call delegate_apply again.`,
649
681
  );
650
682
  }
651
683
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
652
- closeClone();
684
+ closeClone(isolation);
653
685
  return {
654
686
  content: [
655
687
  {
@@ -665,22 +697,14 @@ export default function (pi: ExtensionAPI) {
665
697
  },
666
698
 
667
699
  renderCall(args, theme, context) {
668
- return toolLayout(
669
- "delegate_apply",
670
- jobTarget(args?.id, theme),
671
- argText(args?.discard) === "true" ? "discard" : "",
672
- theme,
673
- context.expanded,
674
- );
700
+ return toolLayout("delegate_apply", jobTarget(args?.id, theme), "", theme, context.expanded);
675
701
  },
676
702
 
677
703
  renderResult(result, { expanded }, theme, context) {
678
- const details = result.details as
679
- { id: string; agent: string; discarded?: boolean; diff?: string } | undefined;
704
+ const details = result.details as { id: string; agent: string; diff?: string } | undefined;
680
705
  const body = resultText(result);
681
706
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
682
- const status = details.discarded ? "clone discarded" : "changes applied";
683
- const header = `\n${resultHeader(theme, details, status)}`;
707
+ const header = `\n${resultHeader(theme, details, "changes applied")}`;
684
708
  const diff = details.diff?.trim() ? renderDiff(piDiff(details.diff)) : "";
685
709
  if (!diff) return new Text(header, 0, 0);
686
710
  // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
@@ -694,6 +718,43 @@ export default function (pi: ExtensionAPI) {
694
718
  },
695
719
  });
696
720
 
721
+ pi.registerTool({
722
+ name: "delegate_discard",
723
+ label: "Discard delegate clone",
724
+ description: "Remove an isolated delegate's clone without applying its changes.",
725
+ promptSnippet: "Discard an isolated delegate's clone by job id",
726
+ parameters: Type.Object({
727
+ id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
728
+ }),
729
+ async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
730
+ const params = dropNulls(rawParams);
731
+ const id = jobId(params.id);
732
+ const { job, isolation } = clonedJob(id);
733
+ requireIdleClone(isolation);
734
+ closeClone(isolation);
735
+ return {
736
+ content: [
737
+ {
738
+ type: "text",
739
+ text: `Discarded the isolated clone of delegate "${job.agent}" (job ${job.id}); nothing was applied.`,
740
+ },
741
+ ],
742
+ details: { id: job.id, agent: job.agent, discarded: true },
743
+ };
744
+ },
745
+
746
+ renderCall(args, theme, context) {
747
+ return toolLayout("delegate_discard", jobTarget(args?.id, theme), "", theme, context.expanded);
748
+ },
749
+
750
+ renderResult(result, _options, theme, context) {
751
+ const details = result.details as { id: string; agent: string; discarded?: boolean } | undefined;
752
+ const body = resultText(result);
753
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
754
+ return new Text(`\n${resultHeader(theme, details, "clone discarded")}`, 0, 0);
755
+ },
756
+ });
757
+
697
758
  pi.registerTool({
698
759
  name: "delegate_list",
699
760
  label: "List delegates",
package/isolation.ts CHANGED
@@ -122,7 +122,6 @@ export function isolationSummary(iso: IsolationState): string {
122
122
  } catch {
123
123
  // The clone may already be applied or gone; the path alone still says where the work lives.
124
124
  }
125
- lines.push("Apply with delegate_apply to land these changes in the main tree.");
126
125
  return lines.join("\n");
127
126
  }
128
127
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.29",
3
+ "version": "0.0.31",
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 => {