@deathbeam/pi-delegate 0.0.44 → 0.0.45

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,8 +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`, `delegate_apply`, and
4
- `delegate_discard`.
5
- Use `/delegate` command to inspect jobs in a full-screen TUI.
3
+ Run subagents in the background with `delegate`, and manage them with `delegate_list`, `delegate_steer`, `delegate_cancel`, `delegate_apply`, and `delegate_discard`.
4
+ `/delegate` opens a fullscreen inspector for live and recent jobs.
6
5
 
7
6
  ## Installation
8
7
 
@@ -29,7 +28,10 @@ Optional `delegate` settings live in `~/.pi/agent/settings.json` or `.pi/setting
29
28
  }
30
29
  ```
31
30
 
32
- Agents are Markdown files with frontmatter, the body becomes the child's system prompt:
31
+ - `agentDirs` adds directories to search for agents. The bundled agents and `~/.agents/agents` are always loaded.
32
+ - `models` maps the `cheap`, `balanced`, and `strong` tiers to a `provider/model-id` with an optional `:<thinking>` suffix. A tier without an entry uses the session model.
33
+
34
+ Agents are Markdown files with frontmatter. The body becomes the delegate's system prompt.
33
35
 
34
36
  ```markdown
35
37
  ---
@@ -43,16 +45,16 @@ isolated: false
43
45
  Explore the codebase and report relevant paths.
44
46
  ```
45
47
 
46
- - `name` is required and must be unique
47
- - `description` is required
48
+ - `name` is required and must be unique.
49
+ - `description` is required.
48
50
  - `tools` is optional, a comma-separated list of tool names. Defaults to the session tools.
49
51
  - `model` is optional, a tier name or `provider/model[:thinking]`. Defaults to the session model.
50
- - `isolated` is optional, defaults to `false`. See [Isolation](#isolation).
52
+ - `isolated` is optional and defaults to `false`. See [Isolation](#isolation).
51
53
 
52
54
  ## Isolation
53
55
 
54
56
  `isolated: true` (on a `delegate` call or in agent frontmatter) runs the delegate in its own git clone at
55
- `.pi/worktrees/<id>`, starting from your current working tree including uncommitted changes.
57
+ `.pi/worktrees/<job id>`, starting from your current working tree including uncommitted changes.
56
58
 
57
59
  `delegate_apply` merges the result into your working tree as uncommitted changes.
58
60
  `delegate_discard` discards the clone and its changes.
@@ -61,10 +63,10 @@ Any later delegate can share that clone with `clone: <job id>`, for review, test
61
63
 
62
64
  ## Development
63
65
 
64
- From this package directory:
66
+ From the repo root:
65
67
 
66
68
  ```sh
67
69
  npm install
68
- npm test
69
- pi install .
70
+ npm test -- packages/pi-delegate
71
+ pi install ./packages/pi-delegate
70
72
  ```
package/index.ts CHANGED
@@ -89,13 +89,6 @@ function resultText(result: { content: unknown }): string {
89
89
  return textParts(result.content).join("\n");
90
90
  }
91
91
 
92
- /** One resolution path for launches and swaps; the error names the requested model. */
93
- function mustResolveModel(request: string | undefined, ctx: ExtensionContext, fallback?: string) {
94
- const { model, thinking } = resolveModel(request ?? fallback, configFor(ctx.cwd).models ?? {}, ctx);
95
- if (!model) throw new Error(`No model found for "${request ?? fallback}".`);
96
- return { model, thinking };
97
- }
98
-
99
92
  /** Isolated jobs append the clone location and a change stat so the orchestrator can apply the work. */
100
93
  function withIsolation(output: string, isolation: IsolationState | undefined): string {
101
94
  return isolation ? [output, isolationSummary(isolation)].filter(Boolean).join("\n\n") : output;
@@ -110,8 +103,10 @@ export default function (pi: ExtensionAPI) {
110
103
  const store = createJobStore(pi.appendEntry);
111
104
  // A cancelled child can outlive its job row; a revive waits for it so two children never share a pinned session.
112
105
  const exiting = new Map<string, Promise<void>>();
106
+ // A clone an apply or discard owns: a revive that waited on the same exiting child must not spawn into it.
107
+ const closing = new Set<string>();
113
108
 
114
- /** Waits for a cancelled child to exit; a child that never closes must not block steering forever. */
109
+ /** Waits for a cancelled child to exit; a child that never closes must not block its successor forever. */
115
110
  async function waitForExit(id: string) {
116
111
  const closed = exiting.get(id);
117
112
  if (!closed) return;
@@ -122,7 +117,7 @@ export default function (pi: ExtensionAPI) {
122
117
  });
123
118
  const result = await Promise.race([closed.then(() => "closed" as const), timeout]);
124
119
  clearTimeout(timer);
125
- if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; call delegate_steer again.`);
120
+ if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; try again.`);
126
121
  }
127
122
 
128
123
  let ticker: ReturnType<typeof setInterval> | undefined;
@@ -179,10 +174,25 @@ export default function (pi: ExtensionAPI) {
179
174
  }
180
175
 
181
176
  /** One job at a time per clone: a shared clone is a shared working directory. */
182
- function requireIdleClone(isolation: IsolationState) {
177
+ async function requireIdleClone(isolation: IsolationState) {
183
178
  const busy = store.live().find((job) => job.isolation?.clone === isolation.clone);
184
179
  if (busy)
185
180
  throw new Error(`Delegate job "${busy.id}" is running in this clone; wait for it or cancel it first.`);
181
+ // A cancelled child leaves the live set at once but can keep writing in its clone until SIGKILL.
182
+ for (const job of jobsInClone(isolation.clone)) await waitForExit(job.id);
183
+ }
184
+
185
+ /** Claims the clone before waiting; on success the mark stays as the tombstone a waiting revive checks. */
186
+ async function claimClone<T>(isolation: IsolationState, run: () => T): Promise<T> {
187
+ closing.add(isolation.clone);
188
+ try {
189
+ await requireIdleClone(isolation);
190
+ return run();
191
+ } catch (error) {
192
+ // A failed operation keeps the clone, so children may still spawn in it.
193
+ closing.delete(isolation.clone);
194
+ throw error;
195
+ }
186
196
  }
187
197
 
188
198
  function refreshWidget(ctx: ExtensionContext) {
@@ -261,7 +271,9 @@ export default function (pi: ExtensionAPI) {
261
271
  ) {
262
272
  const entrypoint = process.argv[1];
263
273
  if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
264
- const { model, thinking } = mustResolveModel(fields.model, ctx, agent.model);
274
+ const requested = fields.model ?? agent.model;
275
+ const { model, thinking } = resolveModel(requested, configFor(ctx.cwd).models ?? {}, ctx);
276
+ if (!model) throw new Error(`No model found for "${requested}".`);
265
277
  const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
266
278
  (tool) => !DELEGATION_TOOLS.has(tool),
267
279
  );
@@ -269,7 +281,7 @@ export default function (pi: ExtensionAPI) {
269
281
  const id = prior?.id ?? randomUUID().slice(0, 8);
270
282
  const isolation =
271
283
  prior?.isolation ?? fields.clone ?? (fields.isolated ? createIsolation(ctx.cwd, id) : undefined);
272
- if (isolation) requireIdleClone(isolation);
284
+ if (isolation) await requireIdleClone(isolation);
273
285
 
274
286
  const job: DelegateJob = {
275
287
  // A revived job keeps its id: the pinned child session id reopens the old transcript.
@@ -313,6 +325,9 @@ export default function (pi: ExtensionAPI) {
313
325
  "--append-system-prompt",
314
326
  `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." : ""}`,
315
327
  );
328
+ // Same tick as the spawn: a claim that landed while we waited would delete the clone under a fresh child.
329
+ if (isolation && closing.has(isolation.clone))
330
+ throw new Error(`The clone at ${isolation.clone} is being applied or discarded; wait for it to finish.`);
316
331
  const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
317
332
  cwd,
318
333
  shell: false,
@@ -374,11 +389,11 @@ export default function (pi: ExtensionAPI) {
374
389
  /** Swaps a running child's model over the RPC; the child confirms or rejects it, and never restarts. */
375
390
  async function swapModel(job: DelegateJob, request: string, ctx: ExtensionContext) {
376
391
  if (!job.swapModel) throw new Error(`Delegate job "${job.id}" cannot switch models.`);
377
- const { model } = mustResolveModel(request, ctx);
392
+ const { model, explicit: level } = resolveModel(request, configFor(ctx.cwd).models ?? {}, ctx);
393
+ if (!model) throw new Error(`No model found for "${request}".`);
378
394
  const [provider, ...rest] = model.split("/");
379
395
  if (!rest.length) throw new Error(`Model "${model}" has no provider prefix.`);
380
- // Only an explicit :thinking suffix changes the level; an inherited one must not silently reset it.
381
- const level = /:(off|minimal|low|medium|high|xhigh|max)$/.exec(request)?.[1];
396
+ // Only an explicit :thinking suffix, on the request or its tier, changes the level; an inherited one must not silently reset it.
382
397
  // The display lands on the set_model ack, so a thinking-level failure cannot leave it stale.
383
398
  await job.swapModel(provider, rest.join("/"), level, () => {
384
399
  job.model = model;
@@ -695,9 +710,9 @@ export default function (pi: ExtensionAPI) {
695
710
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
696
711
  const id = jobId(rawParams.id);
697
712
  const { job, isolation } = clonedJob(id);
698
- requireIdleClone(isolation);
699
- const result = applyClone(isolation);
713
+ const result = await claimClone(isolation, () => applyClone(isolation));
700
714
  if (result.kind === "conflict") {
715
+ closing.delete(isolation.clone);
701
716
  // Base rule: base tracks the newest snapshot, so the next apply works whether or not the delegate rebased yet.
702
717
  for (const shared of jobsInClone(isolation.clone)) {
703
718
  shared.isolation = { ...isolation, base: result.snapshot };
@@ -757,8 +772,7 @@ export default function (pi: ExtensionAPI) {
757
772
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
758
773
  const id = jobId(rawParams.id);
759
774
  const { job, isolation } = clonedJob(id);
760
- requireIdleClone(isolation);
761
- closeClone(isolation);
775
+ await claimClone(isolation, () => closeClone(isolation));
762
776
  return {
763
777
  content: [
764
778
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.44",
3
+ "version": "0.0.45",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,9 +28,6 @@
28
28
  "./index.ts"
29
29
  ]
30
30
  },
31
- "scripts": {
32
- "test": "node check.mjs"
33
- },
34
31
  "peerDependencies": {
35
32
  "@earendil-works/pi-coding-agent": "*",
36
33
  "@earendil-works/pi-tui": "*"
package/src/agents.ts CHANGED
@@ -112,20 +112,26 @@ function splitThinking(value: string): { model: string; thinking?: string } {
112
112
  }
113
113
 
114
114
  // Precedence: requested `:<thinking>` suffix, then the tier suffix, then the session level.
115
+ // `explicit` is the level the request names outright; undefined means it only inherits the session level.
115
116
  export function resolveModel(
116
117
  value: string | undefined,
117
118
  models: Record<string, unknown>,
118
119
  ctx: Pick<ExtensionContext, "model" | "thinkingLevel">,
119
- ): { model?: string; thinking?: string } {
120
+ ): { model?: string; thinking?: string; explicit?: string } {
120
121
  const split = splitThinking(value ?? "");
121
122
  const thinking = split.thinking ?? ctx.thinkingLevel;
122
- if (split.model && !MODEL_TIERS.has(split.model)) return { model: split.model, thinking };
123
+ if (split.model && !MODEL_TIERS.has(split.model)) return { model: split.model, thinking, explicit: split.thinking };
123
124
  const configured = models[split.model];
124
125
  if (typeof configured === "string" && configured) {
125
126
  const tier = splitThinking(configured);
126
- return { model: tier.model, thinking: split.thinking ?? tier.thinking ?? ctx.thinkingLevel };
127
+ const explicit = split.thinking ?? tier.thinking;
128
+ return { model: tier.model, thinking: explicit ?? ctx.thinkingLevel, explicit };
127
129
  }
128
- return { model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined, thinking };
130
+ return {
131
+ model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
132
+ thinking,
133
+ explicit: split.thinking,
134
+ };
129
135
  }
130
136
 
131
137
  export function contextWindowFor(ctx: ExtensionContext, model: string | undefined): number | undefined {