@deathbeam/pi-delegate 0.0.44 → 0.0.46

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
@@ -70,6 +70,7 @@ const EXPLORATION_TOOLS = new Set(["read", "grep", "find", "ls", "bash", "powers
70
70
  const FIRST_REMINDER_AT = 5;
71
71
  const DELEGATE_SESSION_DIR = join(getAgentDir(), "sessions", "delegates");
72
72
  const INTERRUPTED_MESSAGE = "delegate-interrupted";
73
+ const SKILL_PROMPT = "If your task names a skill, read its SKILL.md before starting and follow it.";
73
74
 
74
75
  function argText(value: unknown): string {
75
76
  return typeof value === "string" ? value : "";
@@ -89,13 +90,6 @@ function resultText(result: { content: unknown }): string {
89
90
  return textParts(result.content).join("\n");
90
91
  }
91
92
 
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
93
  /** Isolated jobs append the clone location and a change stat so the orchestrator can apply the work. */
100
94
  function withIsolation(output: string, isolation: IsolationState | undefined): string {
101
95
  return isolation ? [output, isolationSummary(isolation)].filter(Boolean).join("\n\n") : output;
@@ -110,8 +104,10 @@ export default function (pi: ExtensionAPI) {
110
104
  const store = createJobStore(pi.appendEntry);
111
105
  // A cancelled child can outlive its job row; a revive waits for it so two children never share a pinned session.
112
106
  const exiting = new Map<string, Promise<void>>();
107
+ // A clone an apply or discard owns: a revive that waited on the same exiting child must not spawn into it.
108
+ const closing = new Set<string>();
113
109
 
114
- /** Waits for a cancelled child to exit; a child that never closes must not block steering forever. */
110
+ /** Waits for a cancelled child to exit; a child that never closes must not block its successor forever. */
115
111
  async function waitForExit(id: string) {
116
112
  const closed = exiting.get(id);
117
113
  if (!closed) return;
@@ -122,7 +118,7 @@ export default function (pi: ExtensionAPI) {
122
118
  });
123
119
  const result = await Promise.race([closed.then(() => "closed" as const), timeout]);
124
120
  clearTimeout(timer);
125
- if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; call delegate_steer again.`);
121
+ if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; try again.`);
126
122
  }
127
123
 
128
124
  let ticker: ReturnType<typeof setInterval> | undefined;
@@ -179,10 +175,25 @@ export default function (pi: ExtensionAPI) {
179
175
  }
180
176
 
181
177
  /** One job at a time per clone: a shared clone is a shared working directory. */
182
- function requireIdleClone(isolation: IsolationState) {
178
+ async function requireIdleClone(isolation: IsolationState) {
183
179
  const busy = store.live().find((job) => job.isolation?.clone === isolation.clone);
184
180
  if (busy)
185
181
  throw new Error(`Delegate job "${busy.id}" is running in this clone; wait for it or cancel it first.`);
182
+ // A cancelled child leaves the live set at once but can keep writing in its clone until SIGKILL.
183
+ for (const job of jobsInClone(isolation.clone)) await waitForExit(job.id);
184
+ }
185
+
186
+ /** Claims the clone before waiting; on success the mark stays as the tombstone a waiting revive checks. */
187
+ async function claimClone<T>(isolation: IsolationState, run: () => T): Promise<T> {
188
+ closing.add(isolation.clone);
189
+ try {
190
+ await requireIdleClone(isolation);
191
+ return run();
192
+ } catch (error) {
193
+ // A failed operation keeps the clone, so children may still spawn in it.
194
+ closing.delete(isolation.clone);
195
+ throw error;
196
+ }
186
197
  }
187
198
 
188
199
  function refreshWidget(ctx: ExtensionContext) {
@@ -261,7 +272,9 @@ export default function (pi: ExtensionAPI) {
261
272
  ) {
262
273
  const entrypoint = process.argv[1];
263
274
  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);
275
+ const requested = fields.model ?? agent.model;
276
+ const { model, thinking } = resolveModel(requested, configFor(ctx.cwd).models ?? {}, ctx);
277
+ if (!model) throw new Error(`No model found for "${requested}".`);
265
278
  const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
266
279
  (tool) => !DELEGATION_TOOLS.has(tool),
267
280
  );
@@ -269,7 +282,7 @@ export default function (pi: ExtensionAPI) {
269
282
  const id = prior?.id ?? randomUUID().slice(0, 8);
270
283
  const isolation =
271
284
  prior?.isolation ?? fields.clone ?? (fields.isolated ? createIsolation(ctx.cwd, id) : undefined);
272
- if (isolation) requireIdleClone(isolation);
285
+ if (isolation) await requireIdleClone(isolation);
273
286
 
274
287
  const job: DelegateJob = {
275
288
  // A revived job keeps its id: the pinned child session id reopens the old transcript.
@@ -307,12 +320,16 @@ export default function (pi: ExtensionAPI) {
307
320
  ];
308
321
  if (thinking) args.push("--thinking", thinking);
309
322
  if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
323
+ args.push("--append-system-prompt", SKILL_PROMPT);
310
324
  const cwd = isolation ? cloneCwd(isolation, ctx.cwd) : ctx.cwd;
311
325
  if (isolation)
312
326
  args.push(
313
327
  "--append-system-prompt",
314
328
  `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
329
  );
330
+ // Same tick as the spawn: a claim that landed while we waited would delete the clone under a fresh child.
331
+ if (isolation && closing.has(isolation.clone))
332
+ throw new Error(`The clone at ${isolation.clone} is being applied or discarded; wait for it to finish.`);
316
333
  const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
317
334
  cwd,
318
335
  shell: false,
@@ -374,11 +391,11 @@ export default function (pi: ExtensionAPI) {
374
391
  /** Swaps a running child's model over the RPC; the child confirms or rejects it, and never restarts. */
375
392
  async function swapModel(job: DelegateJob, request: string, ctx: ExtensionContext) {
376
393
  if (!job.swapModel) throw new Error(`Delegate job "${job.id}" cannot switch models.`);
377
- const { model } = mustResolveModel(request, ctx);
394
+ const { model, explicit: level } = resolveModel(request, configFor(ctx.cwd).models ?? {}, ctx);
395
+ if (!model) throw new Error(`No model found for "${request}".`);
378
396
  const [provider, ...rest] = model.split("/");
379
397
  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];
398
+ // Only an explicit :thinking suffix, on the request or its tier, changes the level; an inherited one must not silently reset it.
382
399
  // The display lands on the set_model ack, so a thinking-level failure cannot leave it stale.
383
400
  await job.swapModel(provider, rest.join("/"), level, () => {
384
401
  job.model = model;
@@ -475,7 +492,7 @@ export default function (pi: ExtensionAPI) {
475
492
  "Available agents:",
476
493
  ...agentList,
477
494
  "",
478
- "A delegate gets the project instructions but not this conversation. Write `task` as a self-contained brief: the goal and why it matters, what you know (paths, symbols, errors), scope and constraints, whether to edit or only report, and what to return (format, length, path:line evidence).",
495
+ 'A delegate gets the project instructions but not this conversation. Write `task` as a self-contained brief: the goal and why it matters, what you know (paths, symbols, errors), scope and constraints, whether to edit or only report, and what to return (format, length, path:line evidence). When a listed skill fits the work, name it in the brief ("load the <name> skill first"); the delegate sees the same skill list but not the request that matched it.',
479
496
  "",
480
497
  "With isolated: true, the delegate runs in a git clone at .pi/worktrees/<job id>, starting from the main tree 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.",
481
498
  "",
@@ -695,9 +712,9 @@ export default function (pi: ExtensionAPI) {
695
712
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
696
713
  const id = jobId(rawParams.id);
697
714
  const { job, isolation } = clonedJob(id);
698
- requireIdleClone(isolation);
699
- const result = applyClone(isolation);
715
+ const result = await claimClone(isolation, () => applyClone(isolation));
700
716
  if (result.kind === "conflict") {
717
+ closing.delete(isolation.clone);
701
718
  // Base rule: base tracks the newest snapshot, so the next apply works whether or not the delegate rebased yet.
702
719
  for (const shared of jobsInClone(isolation.clone)) {
703
720
  shared.isolation = { ...isolation, base: result.snapshot };
@@ -757,8 +774,7 @@ export default function (pi: ExtensionAPI) {
757
774
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
758
775
  const id = jobId(rawParams.id);
759
776
  const { job, isolation } = clonedJob(id);
760
- requireIdleClone(isolation);
761
- closeClone(isolation);
777
+ await claimClone(isolation, () => closeClone(isolation));
762
778
  return {
763
779
  content: [
764
780
  {
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.46",
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 {