@deathbeam/pi-delegate 0.0.50 → 0.0.51

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.
Files changed (3) hide show
  1. package/index.ts +28 -13
  2. package/package.json +1 -1
  3. package/src/isolation.ts +78 -59
package/index.ts CHANGED
@@ -100,8 +100,12 @@ function resultText(result: { content: unknown }): string {
100
100
  }
101
101
 
102
102
  /** Isolated jobs append the clone location and a change stat so the orchestrator can apply the work. */
103
- function withIsolation(output: string, isolation: IsolationState | undefined): string {
104
- return isolation ? [output, isolationSummary(isolation)].filter(Boolean).join("\n\n") : output;
103
+ async function withIsolation(
104
+ output: string,
105
+ isolation: IsolationState | undefined,
106
+ signal?: AbortSignal,
107
+ ): Promise<string> {
108
+ return isolation ? [output, await isolationSummary(isolation, signal)].filter(Boolean).join("\n\n") : output;
105
109
  }
106
110
 
107
111
  /** Status icon, identity, and the muted detail line: the row the widget and delegate_list both show. */
@@ -174,8 +178,8 @@ export default function (pi: ExtensionAPI) {
174
178
  }
175
179
 
176
180
  /** Closing a clone is a clone-wide operation: every job id that ran in it stops pointing at it. */
177
- function closeClone(isolation: IsolationState) {
178
- removeClone(isolation);
181
+ async function closeClone(isolation: IsolationState) {
182
+ await removeClone(isolation);
179
183
  for (const shared of jobsInClone(isolation.clone)) {
180
184
  shared.isolation = undefined;
181
185
  shared.cloneClosed = true;
@@ -192,12 +196,19 @@ export default function (pi: ExtensionAPI) {
192
196
  for (const job of jobsInClone(isolation.clone)) await waitForExit(job.id);
193
197
  }
194
198
 
199
+ /** The refusal for a clone an apply or discard owns. */
200
+ function closingError(clone: string) {
201
+ return new Error(`The clone at ${clone} is being applied or discarded; wait for it to finish.`);
202
+ }
203
+
195
204
  /** Claims the clone before waiting; on success the mark stays as the tombstone a waiting revive checks. */
196
- async function claimClone<T>(isolation: IsolationState, run: () => T): Promise<T> {
205
+ async function claimClone<T>(isolation: IsolationState, run: () => Promise<T>): Promise<T> {
206
+ // The claim must be exclusive, or a second apply or discard runs git in a clone the first is rewriting.
207
+ if (closing.has(isolation.clone)) throw closingError(isolation.clone);
197
208
  closing.add(isolation.clone);
198
209
  try {
199
210
  await requireIdleClone(isolation);
200
- return run();
211
+ return await run();
201
212
  } catch (error) {
202
213
  // A failed operation keeps the clone, so children may still spawn in it.
203
214
  closing.delete(isolation.clone);
@@ -245,7 +256,7 @@ export default function (pi: ExtensionAPI) {
245
256
  }
246
257
  }
247
258
 
248
- function finishJob(ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) {
259
+ async function finishJob(ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) {
249
260
  if (!store.finish(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined)) return;
250
261
  syncTicker(ctx);
251
262
  refreshWidget(ctx);
@@ -257,7 +268,7 @@ export default function (pi: ExtensionAPI) {
257
268
  contextTokens: job.contextTokens,
258
269
  contextWindow: job.contextWindow,
259
270
  elapsedMs: elapsedMs(job),
260
- output: withIsolation(output ?? "", job.isolation),
271
+ output: await withIsolation(output ?? "", job.isolation),
261
272
  error,
262
273
  isolation: job.isolation,
263
274
  };
@@ -294,7 +305,9 @@ export default function (pi: ExtensionAPI) {
294
305
  const displayModel = thinking ? `${model}:${thinking}` : model;
295
306
  const id = prior?.id ?? randomUUID().slice(0, 8);
296
307
  const isolation =
297
- prior?.isolation ?? fields.clone ?? (fields.isolated ? createIsolation(ctx.cwd, id) : undefined);
308
+ prior?.isolation ??
309
+ fields.clone ??
310
+ (fields.isolated ? await createIsolation(ctx.cwd, id, signal) : undefined);
298
311
  if (isolation) await requireIdleClone(isolation);
299
312
 
300
313
  const job: DelegateJob = {
@@ -341,8 +354,10 @@ export default function (pi: ExtensionAPI) {
341
354
  `You are working in an isolated git clone at ${isolation.clone}. Your working directory is ${cwd}; run every command from it with relative paths. Any path under ${ctx.cwd} means the same file under ${cwd}. Your edits stay in this clone until the orchestrator applies them.${tools.includes("bash") ? " Git commands that write, such as commit and rebase, work here and change only this clone. `git diff main-snapshot` shows every change made in it." : ""}`,
342
355
  );
343
356
  // Same tick as the spawn: a claim that landed while we waited would delete the clone under a fresh child.
344
- if (isolation && closing.has(isolation.clone))
345
- throw new Error(`The clone at ${isolation.clone} is being applied or discarded; wait for it to finish.`);
357
+ if (isolation && closing.has(isolation.clone)) throw closingError(isolation.clone);
358
+ // Two revives of one finished job both pass requireIdleClone, so only the first may spawn on that id.
359
+ if (store.liveJob(id))
360
+ throw new Error(`Delegate job "${id}" is already running; wait for it or cancel it first.`);
346
361
  const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
347
362
  cwd,
348
363
  shell: false,
@@ -369,7 +384,7 @@ export default function (pi: ExtensionAPI) {
369
384
  const output = await run.done;
370
385
  store.finish(job, "done");
371
386
  return {
372
- content: [{ type: "text" as const, text: withIsolation(output, job.isolation) }],
387
+ content: [{ type: "text" as const, text: await withIsolation(output, job.isolation, signal) }],
373
388
  details,
374
389
  };
375
390
  } catch (error) {
@@ -745,7 +760,7 @@ export default function (pi: ExtensionAPI) {
745
760
  }
746
761
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
747
762
  const capped = result.kind === "applied" ? capDiff(result.diff) : { diff: undefined, note: undefined };
748
- closeClone(isolation);
763
+ await closeClone(isolation);
749
764
  return {
750
765
  content: [
751
766
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.50",
3
+ "version": "0.0.51",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/isolation.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { execFileSync } from "node:child_process";
2
- import { readFileSync, rmSync, writeFileSync } from "node:fs";
1
+ import { execFile } from "node:child_process";
2
+ import { readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { join, relative, resolve } from "node:path";
4
+ import { promisify } from "node:util";
4
5
 
5
6
  /** Persisted with the job: where the clone lives and which main-tree snapshot it started from. */
6
7
  export type IsolationState = { clone: string; base: string };
@@ -12,29 +13,41 @@ type ApplyResult =
12
13
 
13
14
  const IDENTITY = ["-c", "user.name=pi-delegate", "-c", "user.email=pi-delegate@localhost"];
14
15
  const SNAPSHOT_BRANCH = "main-snapshot";
16
+ const execFileAsync = promisify(execFile);
15
17
 
16
18
  /** One git invocation; `indexFile` swaps in a scratch index and `input` feeds stdin (patches). */
17
- function git(
19
+ async function git(
18
20
  args: string[],
19
- options: { cwd?: string; gitDir?: string; workTree?: string; input?: string; indexFile?: string } = {},
20
- ): string {
21
+ options: {
22
+ cwd?: string;
23
+ gitDir?: string;
24
+ workTree?: string;
25
+ input?: string;
26
+ indexFile?: string;
27
+ signal?: AbortSignal;
28
+ } = {},
29
+ ): Promise<string> {
21
30
  const command = [
22
31
  ...(options.gitDir ? ["--git-dir", options.gitDir] : []),
23
32
  ...(options.workTree ? ["--work-tree", options.workTree] : []),
24
33
  ...args,
25
34
  ];
35
+ const pending = execFileAsync("git", command, {
36
+ cwd: options.cwd,
37
+ encoding: "utf8",
38
+ // Binary diffs of real repositories blow past execFile's 1 MiB default.
39
+ maxBuffer: 1024 ** 3,
40
+ signal: options.signal,
41
+ env: options.indexFile ? { ...process.env, GIT_INDEX_FILE: options.indexFile } : process.env,
42
+ });
43
+ // The promisified form has no `input` option, so the patch rides stdin; closing it is also EOF for `git apply -`.
44
+ // A git that exits before reading it (e.g. a rejected patch) would otherwise raise an uncaught EPIPE.
45
+ pending.child.stdin?.on("error", () => {}).end(options.input);
26
46
  try {
27
- return execFileSync("git", command, {
28
- cwd: options.cwd,
29
- input: options.input,
30
- encoding: "utf8",
31
- // Without this, git's stderr (rebase hints etc.) leaks onto the TUI.
32
- stdio: "pipe",
33
- // Binary diffs of real repositories blow past execFileSync's 1 MiB default.
34
- maxBuffer: 1024 ** 3,
35
- env: options.indexFile ? { ...process.env, GIT_INDEX_FILE: options.indexFile } : process.env,
36
- });
47
+ return (await pending).stdout;
37
48
  } catch (error) {
49
+ // An aborted turn is not a git failure; pi marks the cancelled tool call itself.
50
+ if (options.signal?.aborted) throw error;
38
51
  const failure = error as { stderr?: string };
39
52
  const detail = (failure.stderr ?? "").trim();
40
53
  throw new Error(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`);
@@ -47,58 +60,63 @@ function rootOf(iso: IsolationState): string {
47
60
  }
48
61
 
49
62
  /** Commits the main tree's current content through a scratch index, so the clone's own checkout and index stay untouched. */
50
- function snapshotMainTree(iso: IsolationState, root: string): string {
63
+ async function snapshotMainTree(iso: IsolationState, root: string, signal?: AbortSignal): Promise<string> {
51
64
  const gitDir = join(iso.clone, ".git");
52
65
  const indexFile = join(gitDir, "pi-delegate-snapshot-index");
53
66
  try {
54
- git(["read-tree", iso.base], { gitDir, indexFile });
55
- git(["add", "-A"], { gitDir, workTree: root, indexFile });
56
- const tree = git(["write-tree"], { gitDir, indexFile }).trim();
57
- const snapshot = git([...IDENTITY, "commit-tree", tree, "-p", iso.base, "-m", "main tree snapshot"], {
58
- gitDir,
59
- }).trim();
60
- git(["branch", "-f", SNAPSHOT_BRANCH, snapshot], { gitDir });
67
+ await git(["read-tree", iso.base], { gitDir, indexFile, signal });
68
+ await git(["add", "-A"], { gitDir, workTree: root, indexFile, signal });
69
+ const tree = (await git(["write-tree"], { gitDir, indexFile, signal })).trim();
70
+ const snapshot = (
71
+ await git([...IDENTITY, "commit-tree", tree, "-p", iso.base, "-m", "main tree snapshot"], {
72
+ gitDir,
73
+ signal,
74
+ })
75
+ ).trim();
76
+ await git(["branch", "-f", SNAPSHOT_BRANCH, snapshot], { gitDir, signal });
61
77
  return snapshot;
62
78
  } finally {
63
- rmSync(indexFile, { force: true });
79
+ await rm(indexFile, { force: true });
64
80
  }
65
81
  }
66
82
 
67
83
  /** Creates the isolated clone and the base commit capturing the main tree as the user sees it now. */
68
- export function createIsolation(cwd: string, jobId: string): IsolationState {
84
+ export async function createIsolation(cwd: string, jobId: string, signal?: AbortSignal): Promise<IsolationState> {
69
85
  let root: string;
70
86
  try {
71
- root = git(["rev-parse", "--show-toplevel"], { cwd }).trim();
72
- } catch {
87
+ root = (await git(["rev-parse", "--show-toplevel"], { cwd, signal })).trim();
88
+ } catch (error) {
89
+ if (signal?.aborted) throw error;
73
90
  throw new Error("isolated: true requires the session to run inside a git repository.");
74
91
  }
75
92
  const clone = join(root, ".pi", "worktrees", jobId);
76
- rmSync(clone, { recursive: true, force: true });
77
- git(["clone", "--shared", "--quiet", root, clone]);
93
+ await rm(clone, { recursive: true, force: true });
78
94
  try {
95
+ await git(["clone", "--shared", "--quiet", root, clone], { signal });
79
96
  // Snapshots use --work-tree=<root>, so the clones themselves must never be picked up; the
80
97
  // main repo's local excludes must carry over too, or locally-ignored files land in clones.
81
98
  let exclude = "\n.pi/worktrees/\n";
82
99
  try {
83
- const mainExclude = git(["rev-parse", "--git-path", "info/exclude"], { cwd: root }).trim();
84
- exclude = `${readFileSync(resolve(root, mainExclude), "utf8")}${exclude}`;
100
+ const mainExclude = (await git(["rev-parse", "--git-path", "info/exclude"], { cwd: root, signal })).trim();
101
+ exclude = `${await readFile(resolve(root, mainExclude), "utf8")}${exclude}`;
85
102
  } catch {
86
103
  // No local exclude file; .gitignore still applies.
87
104
  }
88
- writeFileSync(join(clone, ".git", "info", "exclude"), exclude);
105
+ await writeFile(join(clone, ".git", "info", "exclude"), exclude);
89
106
  let head: string;
90
107
  try {
91
- head = git(["rev-parse", "HEAD"], { cwd: clone }).trim();
92
- } catch {
108
+ head = (await git(["rev-parse", "HEAD"], { cwd: clone, signal })).trim();
109
+ } catch (error) {
110
+ if (signal?.aborted) throw error;
93
111
  throw new Error("cannot isolate a repository with no commits.");
94
112
  }
95
113
  const iso: IsolationState = { clone, base: head };
96
- iso.base = snapshotMainTree(iso, root);
114
+ iso.base = await snapshotMainTree(iso, root, signal);
97
115
  // The clone's checkout still matches the upstream tip; make it match the snapshot instead.
98
- git(["reset", "--hard", "--quiet", iso.base], { cwd: clone });
116
+ await git(["reset", "--hard", "--quiet", iso.base], { cwd: clone, signal });
99
117
  return iso;
100
118
  } catch (error) {
101
- rmSync(clone, { recursive: true, force: true });
119
+ await rm(clone, { recursive: true, force: true });
102
120
  throw error;
103
121
  }
104
122
  }
@@ -110,53 +128,54 @@ export function cloneCwd(iso: IsolationState, cwd: string): string {
110
128
  }
111
129
 
112
130
  /** Clone location plus a stat of everything the delegate changed, for the job's report. */
113
- export function isolationSummary(iso: IsolationState): string {
131
+ export async function isolationSummary(iso: IsolationState, signal?: AbortSignal): Promise<string> {
114
132
  const lines = [`Isolated clone: ${iso.clone}`];
115
133
  const indexFile = join(iso.clone, ".git", "pi-delegate-summary-index");
116
134
  try {
117
135
  // A scratch index stages uncommitted and untracked changes for the stat without touching the clone's own index.
118
- git(["read-tree", "HEAD"], { cwd: iso.clone, indexFile });
119
- git(["add", "-A"], { cwd: iso.clone, indexFile });
120
- const stat = git(["diff", "--stat", iso.base], { cwd: iso.clone, indexFile }).trimEnd();
136
+ await git(["read-tree", "HEAD"], { cwd: iso.clone, indexFile, signal });
137
+ await git(["add", "-A"], { cwd: iso.clone, indexFile, signal });
138
+ const stat = (await git(["diff", "--stat", iso.base], { cwd: iso.clone, indexFile, signal })).trimEnd();
121
139
  if (stat) lines.push(`Changes in this clone:\n${stat}`);
122
140
  } catch {
123
141
  // The clone may already be applied or gone; the path alone still says where the work lives.
124
142
  } finally {
125
- rmSync(indexFile, { force: true });
143
+ await rm(indexFile, { force: true });
126
144
  }
127
145
  return lines.join("\n");
128
146
  }
129
147
 
130
- export function removeClone(iso: IsolationState): void {
131
- rmSync(iso.clone, { recursive: true, force: true });
148
+ export async function removeClone(iso: IsolationState): Promise<void> {
149
+ await rm(iso.clone, { recursive: true, force: true });
132
150
  }
133
151
 
134
152
  /**
135
153
  * Merges the clone into the main working tree. Base rule: `base` tracks the newest `main-snapshot`, so a
136
154
  * repeat apply is correct whether or not the delegate rebased onto it yet. Only the main tree is written.
137
155
  */
138
- export function applyClone(iso: IsolationState): ApplyResult {
156
+ export async function applyClone(iso: IsolationState): Promise<ApplyResult> {
139
157
  const root = rootOf(iso);
140
- function run(args: string[]): string {
158
+ function run(args: string[]): Promise<string> {
141
159
  return git(args, { cwd: iso.clone });
142
160
  }
143
161
  // Commit uncommitted delegate work so the rebase carries it.
144
- run(["add", "-A"]);
145
- if (run(["status", "--porcelain"]).trim()) run([...IDENTITY, "commit", "--no-verify", "-m", "delegate work"]);
146
- const branch = run(["rev-parse", "--abbrev-ref", "HEAD"]).trim();
162
+ await run(["add", "-A"]);
163
+ if ((await run(["status", "--porcelain"])).trim())
164
+ await run([...IDENTITY, "commit", "--no-verify", "-m", "delegate work"]);
165
+ const branch = (await run(["rev-parse", "--abbrev-ref", "HEAD"])).trim();
147
166
  if (branch === SNAPSHOT_BRANCH)
148
167
  throw new Error(
149
168
  `the clone is checked out on ${SNAPSHOT_BRANCH}; steer the delegate to move its work onto its own branch, then apply again`,
150
169
  );
151
170
  // Snapshot the current main tree, then replay the delegate's commits onto it with a real 3-way
152
171
  // merge: git tolerates nearby, non-overlapping edits that raw patch context matching rejects.
153
- const snapshot = snapshotMainTree(iso, root);
172
+ const snapshot = await snapshotMainTree(iso, root);
154
173
  try {
155
- run([...IDENTITY, "rebase", "--empty=drop", SNAPSHOT_BRANCH]);
174
+ await run([...IDENTITY, "rebase", "--empty=drop", SNAPSHOT_BRANCH]);
156
175
  } catch (error) {
157
- const files = run(["diff", "--name-only", "--diff-filter=U"]).trim();
176
+ const files = (await run(["diff", "--name-only", "--diff-filter=U"])).trim();
158
177
  try {
159
- run(["rebase", "--abort"]);
178
+ await run(["rebase", "--abort"]);
160
179
  } catch {
161
180
  // The rebase failed before starting; there is nothing to abort.
162
181
  }
@@ -165,24 +184,24 @@ export function applyClone(iso: IsolationState): ApplyResult {
165
184
  return { kind: "conflict", files: files.split("\n"), snapshot };
166
185
  }
167
186
  // After the rebase this diff is exactly the delegate's work on the current main state.
168
- const patch = run(["diff", "--binary", SNAPSHOT_BRANCH, "HEAD"]);
187
+ const patch = await run(["diff", "--binary", SNAPSHOT_BRANCH, "HEAD"]);
169
188
  if (!patch.trim()) return { kind: "empty" };
170
189
  // A changed submodule serializes as a "Subproject commit" hunk that git apply rejects outright.
171
- if (run(["diff", "--raw", SNAPSHOT_BRANCH, "HEAD"]).match(/^:160000 160000 /m))
190
+ if ((await run(["diff", "--raw", SNAPSHOT_BRANCH, "HEAD"])).match(/^:160000 160000 /m))
172
191
  throw new Error("the delegate changed a submodule (gitlink), which git apply cannot carry; apply it manually");
173
192
  try {
174
- git(["apply", "--check", "-"], { cwd: root, input: patch });
193
+ await git(["apply", "--check", "-"], { cwd: root, input: patch });
175
194
  } catch (error) {
176
195
  // The patch was built on the exact snapshot, so a rejection means the tree moved after it.
177
196
  throw new Error(
178
197
  `${(error as Error).message} — the main tree changed since the snapshot; call delegate_apply again`,
179
198
  );
180
199
  }
181
- git(["apply", "-"], { cwd: root, input: patch });
200
+ await git(["apply", "-"], { cwd: root, input: patch });
182
201
  // Without --binary, binary files render as a name-only "Binary files differ" line.
183
202
  return {
184
203
  kind: "applied",
185
- stat: run(["diff", "--stat", SNAPSHOT_BRANCH, "HEAD"]).trimEnd(),
186
- diff: run(["diff", SNAPSHOT_BRANCH, "HEAD"]),
204
+ stat: (await run(["diff", "--stat", SNAPSHOT_BRANCH, "HEAD"])).trimEnd(),
205
+ diff: await run(["diff", SNAPSHOT_BRANCH, "HEAD"]),
187
206
  };
188
207
  }