@deathbeam/pi-delegate 0.0.23 → 0.0.24

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/agents.ts CHANGED
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
6
  import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
7
7
 
8
- type AgentFile = {
8
+ export type AgentFile = {
9
9
  name: string;
10
10
  description: string;
11
11
  tools?: string[];
package/child.ts CHANGED
@@ -29,6 +29,7 @@ type ChildUpdateHandler = (update: ChildUpdate) => void;
29
29
  type ChildRun = {
30
30
  done: Promise<string>;
31
31
  steer: (message: string) => Promise<void>;
32
+ swapModel: (provider: string, modelId: string, level?: string, onModelSet?: () => void) => Promise<void>;
32
33
  };
33
34
 
34
35
  /** Run one RPC child, keeping its writer serialized so backpressure and EPIPE reach the caller. */
@@ -37,7 +38,7 @@ export function runChild(
37
38
  task: string,
38
39
  signal: AbortSignal | undefined,
39
40
  onUpdate?: ChildUpdateHandler,
40
- resume?: boolean,
41
+ revive?: boolean,
41
42
  ): ChildRun {
42
43
  let buffer = "";
43
44
  let liveText = "";
@@ -272,21 +273,21 @@ export function runChild(
272
273
  if (!settled) fail(error);
273
274
  });
274
275
  };
275
- if (resume) {
276
+ if (revive) {
276
277
  // An empty transcript means the pinned session was recreated (e.g. a different cwd) and the task is gone; fail rather than prompt into a blank session.
277
278
  void send({ type: "get_state" })
278
279
  .then((data) => {
279
280
  if (!settled && !aborted && !data?.messageCount) {
280
281
  fail(
281
282
  new Error(
282
- "Resumed delegate transcript is empty; the pinned session was recreated. Start a fresh delegate instead.",
283
+ "Revived delegate transcript is empty; the pinned session was recreated. Start a fresh delegate instead.",
283
284
  ),
284
285
  );
285
286
  return;
286
287
  }
287
288
  prompt();
288
289
  })
289
- // A resume we cannot verify must not prompt into an unknown transcript.
290
+ // A revive we cannot verify must not prompt into an unknown transcript.
290
291
  .catch((error) => {
291
292
  if (!settled && !aborted) fail(error);
292
293
  });
@@ -299,6 +300,12 @@ export function runChild(
299
300
  return {
300
301
  done,
301
302
  steer: (message) => send({ type: "steer", message }),
303
+ // The callback lands between the two acks, so a thinking-level failure cannot hide the applied model.
304
+ swapModel: async (provider, modelId, level, onModelSet) => {
305
+ await send({ type: "set_model", provider, modelId });
306
+ onModelSet?.();
307
+ if (level !== undefined) await send({ type: "set_thinking_level", level });
308
+ },
302
309
  };
303
310
  }
304
311
 
@@ -313,8 +320,8 @@ function transcriptText(content: unknown): string[] {
313
320
  }
314
321
 
315
322
  /**
316
- * Replays the child's persisted transcript as the activity a resumed job continues from, so the
317
- * inspector keeps the old history. A missing or unreadable transcript seeds nothing: the resume
323
+ * Replays the child's persisted transcript as the activity a revived job continues from, so the
324
+ * inspector keeps the old history. A missing or unreadable transcript seeds nothing: the revive
318
325
  * itself still works.
319
326
  */
320
327
  export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
package/format.ts CHANGED
@@ -156,14 +156,14 @@ export function resultPreview(result: unknown, maxChars = 120): string | undefin
156
156
  return line.length > maxChars ? `${line.slice(0, maxChars - 1)}…` : line;
157
157
  }
158
158
 
159
- /** Shared so failed reports and thrown errors phrase the resume hint identically. */
160
- export function resumeHint(id: string): string {
161
- return `To continue this job, call delegate with resume: ${id}.`;
159
+ /** Shared so failed reports and thrown errors phrase the revive hint identically. */
160
+ export function reviveHint(id: string): string {
161
+ return `To continue this job, call delegate_steer with id ${id} and a message.`;
162
162
  }
163
163
 
164
164
  export function reportText(report: DelegateReport): string {
165
165
  if (report.error)
166
- return `Delegate "${report.agent}" (job ${report.id}) failed: ${report.error}\n${resumeHint(report.id)}`;
166
+ return `Delegate "${report.agent}" (job ${report.id}) failed: ${report.error}\n${reviveHint(report.id)}`;
167
167
  const output = (report.output ?? "").trim();
168
168
  return `Delegate "${report.agent}" (job ${report.id}) finished.${output ? `\n\n${output}` : ""}`;
169
169
  }
package/index.ts CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  launchDetails,
22
22
  outputPreview,
23
23
  reportText,
24
- resumeHint,
24
+ reviveHint,
25
25
  SPINNER_INTERVAL_MS,
26
26
  formatDuration,
27
27
  statusText,
@@ -30,13 +30,12 @@ import {
30
30
  widgetJobs,
31
31
  } from "./format.ts";
32
32
  import { priorActivity, runChild } from "./child.ts";
33
- import { createJobStore, resumeDecision, type DelegateJob } from "./store.ts";
33
+ import { createJobStore, type DelegateJob, type InspectJob } from "./store.ts";
34
34
  import { registerInspector } from "./inspector.ts";
35
- import { configFor, contextWindowFor, discoverAgents, resolveModel } from "./agents.ts";
35
+ import { configFor, contextWindowFor, discoverAgents, resolveModel, type AgentFile } from "./agents.ts";
36
36
 
37
37
  type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "description" | "task" | "model" | "tools"> & {
38
38
  background: boolean;
39
- resumed: boolean;
40
39
  };
41
40
 
42
41
  type SteerDetails = Pick<
@@ -54,7 +53,6 @@ const REMINDER_MESSAGE = "delegate-reminder";
54
53
  const EXPLORATION_TOOLS = new Set(["read", "grep", "find", "ls", "bash", "powershell", "web_search", "web_fetch"]);
55
54
  const FIRST_REMINDER_AT = 5;
56
55
  const DELEGATE_SESSION_DIR = join(getAgentDir(), "sessions", "delegates");
57
- const RESUME_PROMPT = "Continue the task above from where you left off.";
58
56
  const INTERRUPTED_MESSAGE = "delegate-interrupted";
59
57
 
60
58
  function argText(value: unknown): string {
@@ -66,13 +64,25 @@ function jobId(value: unknown): string {
66
64
  .trim()
67
65
  .replace(/^job\s+/i, "");
68
66
  }
67
+ /** Strict models inject literal "null" for optional params they omit; drop it before reading any. */
68
+ function dropNulls<T extends Record<string, unknown>>(raw: T): T {
69
+ return Object.fromEntries(Object.entries(raw).filter(([, value]) => value !== null && value !== "null")) as T;
70
+ }
69
71
 
70
72
  function resultText(result: { content: readonly { type: string; text?: string }[] }): string {
71
73
  return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n");
72
74
  }
73
75
 
74
76
  function resultFallback(body: string, theme: Theme, isError: boolean): Text {
75
- return new Text(`\n${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
77
+ const mark = statusText(theme, isError ? "failed" : "done");
78
+ return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
79
+ }
80
+
81
+ /** Shared foreground output preview: delegate results, steer revives, and follow-up reports. */
82
+ function appendOutput(container: Container, body: string, expanded: boolean, theme: Theme): void {
83
+ const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
84
+ container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
85
+ if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
76
86
  }
77
87
 
78
88
  /** Shared collapsed-output note so all three preview sites phrase it identically. */
@@ -80,6 +90,13 @@ function moreLines(theme: Theme, hidden: number): string {
80
90
  return theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand");
81
91
  }
82
92
 
93
+ /** One resolution path for launches and swaps; the error names the requested model. */
94
+ function mustResolveModel(request: string | undefined, ctx: ExtensionContext, fallback?: string) {
95
+ const { model, thinking } = resolveModel(request ?? fallback, configFor(ctx.cwd).models ?? {}, ctx);
96
+ if (!model) throw new Error(`No model found for "${request ?? fallback}".`);
97
+ return { model, thinking };
98
+ }
99
+
83
100
  /** Shared tool layout: an optional identity header, then a width-aware payload preview. */
84
101
  function toolLayout(toolName: string, identity: string, payload: string, theme: Theme, expanded: boolean): Component {
85
102
  const container = new Container();
@@ -112,6 +129,29 @@ function toolLayout(toolName: string, identity: string, payload: string, theme:
112
129
  return container;
113
130
  }
114
131
 
132
+ /** Shared launch-result card: delegate launches and steer revives render identically. */
133
+ function launchResult(
134
+ details: DelegateDetails,
135
+ body: string,
136
+ status: string,
137
+ expanded: boolean,
138
+ theme: Theme,
139
+ ): Component {
140
+ const container = new Container();
141
+ // The mark is the call's outcome (launch succeeded); job progress stays in the widget and report.
142
+ container.addChild(
143
+ new Text(`\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", status)}`, 0, 0),
144
+ );
145
+ // The call body already carries the task; only the launch metadata is new here.
146
+ if (expanded)
147
+ container.addChild(
148
+ new Text(theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")), 0, 0),
149
+ );
150
+ // Background results arrive as their own message; headless runs still show the output here.
151
+ if (!details.background && body) appendOutput(container, body, expanded, theme);
152
+ return container;
153
+ }
154
+
115
155
  export default function (pi: ExtensionAPI) {
116
156
  const store = createJobStore(pi.appendEntry);
117
157
  let ticker: ReturnType<typeof setInterval> | undefined;
@@ -119,13 +159,15 @@ export default function (pi: ExtensionAPI) {
119
159
  let directCalls = 0;
120
160
  let nextReminder = FIRST_REMINDER_AT;
121
161
 
122
- const jobSnapshot = (job: DelegateJob) => ({
162
+ const jobSnapshot = (job: InspectJob) => ({
123
163
  id: job.id,
124
164
  agent: job.agent,
125
165
  description: job.description,
126
166
  contextTokens: job.contextTokens,
127
167
  contextWindow: job.contextWindow,
128
168
  startedAt: job.startedAt,
169
+ status: job.status,
170
+ endedAt: job.endedAt,
129
171
  });
130
172
 
131
173
  const jobTarget = (rawId: unknown, theme: Theme): string => {
@@ -197,6 +239,125 @@ export default function (pi: ExtensionAPI) {
197
239
  );
198
240
  };
199
241
 
242
+ /** Runs one delegate child: foreground runs return their output, background ones report on completion. */
243
+ const runDelegate = async (
244
+ ctx: ExtensionContext,
245
+ agent: AgentFile,
246
+ prior: InspectJob | undefined,
247
+ fields: { description: string; model?: string },
248
+ task: string,
249
+ signal: AbortSignal | undefined,
250
+ prompt = task,
251
+ ) => {
252
+ const { model, thinking } = mustResolveModel(fields.model, ctx, agent.model);
253
+ const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
254
+ (tool) => !DELEGATION_TOOLS.has(tool),
255
+ );
256
+ const displayModel = thinking ? `${model}:${thinking}` : model;
257
+ const job: DelegateJob = {
258
+ // A revived job keeps its id: the pinned child session id reopens the old transcript.
259
+ id: prior?.id ?? randomUUID().slice(0, 8),
260
+ agent: agent.name,
261
+ description: fields.description.trim(),
262
+ task,
263
+ model: displayModel,
264
+ status: "running",
265
+ // A revive continues the pinned transcript, so the inspector replays the child's own history.
266
+ activity: prior ? priorActivity(DELEGATE_SESSION_DIR, prior.id) : [],
267
+ tools,
268
+ toolCalls: 0,
269
+ startedAt: Date.now(),
270
+ contextWindow: contextWindowFor(ctx, model),
271
+ controller: new AbortController(),
272
+ };
273
+ const details: DelegateDetails = {
274
+ id: job.id,
275
+ agent: job.agent,
276
+ description: job.description,
277
+ task: job.task,
278
+ model: displayModel,
279
+ tools,
280
+ background: ctx.hasUI,
281
+ };
282
+ const args = [
283
+ "--session-id",
284
+ `delegate-${job.id}`,
285
+ "--session-dir",
286
+ DELEGATE_SESSION_DIR,
287
+ "--model",
288
+ model,
289
+ "--tools",
290
+ tools.join(","),
291
+ ];
292
+ if (thinking) args.push("--thinking", thinking);
293
+ if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
294
+ const entrypoint = process.argv[1];
295
+ if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
296
+ const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
297
+ cwd: ctx.cwd,
298
+ shell: false,
299
+ stdio: "pipe",
300
+ });
301
+ store.launch(job, details.background);
302
+ const run = runChild(
303
+ child,
304
+ prompt,
305
+ details.background ? job.controller.signal : signal,
306
+ (update) => store.record(job, update),
307
+ Boolean(prior),
308
+ );
309
+ job.steer = run.steer;
310
+ job.swapModel = run.swapModel;
311
+ if (!details.background) {
312
+ try {
313
+ const output = await run.done;
314
+ store.finish(job, "done");
315
+ return { content: [{ type: "text" as const, text: output }], details };
316
+ } catch (error) {
317
+ // Record the outcome so the launch entry cannot linger as "running".
318
+ const cancelled = error instanceof Error && error.message === "Delegate was aborted";
319
+ store.finish(job, cancelled ? "cancelled" : "failed");
320
+ // Failed jobs are revivable; mirror the failed background report's hint on the thrown error.
321
+ if (!cancelled && error instanceof Error) error.message += `\n${reviveHint(job.id)}`;
322
+ throw error;
323
+ }
324
+ }
325
+
326
+ syncTicker(ctx);
327
+ refreshWidget(ctx);
328
+ void run.done
329
+ .then(
330
+ (output) => finishJob(ctx, job, output),
331
+ (error) => finishJob(ctx, job, undefined, error instanceof Error ? error.message : String(error)),
332
+ )
333
+ .catch(() => {});
334
+ return {
335
+ content: [
336
+ {
337
+ type: "text" as const,
338
+ text: `${prior ? "Revived" : "Started"} delegate "${job.agent}" in the background (job ${job.id}). Steer it with delegate_steer or stop it with delegate_cancel. Do not call tools solely to wait, even no-op bash commands; when its report is your next dependency, end your turn and it will arrive automatically unless cancelled.`,
339
+ },
340
+ ],
341
+ details,
342
+ };
343
+ };
344
+
345
+ /** Swaps a running child's model over the RPC; the child confirms or rejects it, and never restarts. */
346
+ const swapModel = async (job: DelegateJob, request: string, ctx: ExtensionContext) => {
347
+ if (!job.swapModel) throw new Error(`Delegate job "${job.id}" cannot switch models.`);
348
+ const { model } = mustResolveModel(request, ctx);
349
+ const [provider, ...rest] = model.split("/");
350
+ if (!rest.length) throw new Error(`Model "${model}" has no provider prefix.`);
351
+ // Only an explicit :thinking suffix changes the level; an inherited one must not silently reset it.
352
+ const level = /:(off|minimal|low|medium|high|xhigh|max)$/.exec(request)?.[1];
353
+ // The display lands on the set_model ack, so a thinking-level failure cannot leave it stale.
354
+ await job.swapModel(provider, rest.join("/"), level, () => {
355
+ job.model = model;
356
+ job.contextWindow = contextWindowFor(ctx, model);
357
+ });
358
+ if (level) job.model = `${model}:${level}`;
359
+ };
360
+
200
361
  pi.on("session_shutdown", () => {
201
362
  if (ticker) clearInterval(ticker);
202
363
  for (const job of store.live()) job.controller.abort();
@@ -211,7 +372,7 @@ export default function (pi: ExtensionAPI) {
211
372
  pi.sendMessage(
212
373
  {
213
374
  customType: INTERRUPTED_MESSAGE,
214
- content: `<system-reminder>These delegate jobs were interrupted by a restart or crash; their transcripts survive. Resume each with the delegate tool's resume parameter (job id only):\n${interrupted.map((job) => `- ${job.id} ${job.agent}: ${job.description}`).join("\n")}</system-reminder>`,
375
+ content: `<system-reminder>These delegate jobs were interrupted by a restart or crash; their transcripts survive. Continue each with delegate_steer (job id plus your guidance):\n${interrupted.map((job) => `- ${job.id} ${job.agent}: ${job.description}`).join("\n")}</system-reminder>`,
215
376
  display: false,
216
377
  },
217
378
  { deliverAs: "steer" },
@@ -261,11 +422,7 @@ export default function (pi: ExtensionAPI) {
261
422
  ),
262
423
  );
263
424
  if (report.error) container.addChild(new Text(theme.fg("error", report.error), 0, 0));
264
- else if (report.output) {
265
- const { shown, hidden } = outputPreview(report.output, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
266
- container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
267
- if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
268
- }
425
+ else if (report.output) appendOutput(container, report.output, expanded, theme);
269
426
  return container;
270
427
  });
271
428
 
@@ -287,7 +444,7 @@ export default function (pi: ExtensionAPI) {
287
444
  "",
288
445
  "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).",
289
446
  "",
290
- "An interrupted, failed, or cancelled job can be continued by passing its job id as `resume`. The agent, task, and description come from the original job, and the model may be overridden. Done jobs need no resume: their reports are already in this session.",
447
+ "Use delegate_steer to continue or redirect any job by its id: a running job takes the guidance mid-run, and a finished job continues its own transcript with the message as its next instruction.",
291
448
  ].join("\n"),
292
449
  promptSnippet:
293
450
  "Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
@@ -300,158 +457,44 @@ export default function (pi: ExtensionAPI) {
300
457
  "Read every required delegate report before claiming the task is done. Never sleep, poll, or call any tool solely to wait (including `bash` with `true`, `echo`, or `sleep 0`). Use delegate_list only for a one-time status check.",
301
458
  ],
302
459
  parameters: Type.Object({
303
- agent: Type.Optional(Type.String({ description: "Agent name from the list in this tool's description." })),
304
- description: Type.Optional(
305
- Type.String({ description: "Short 3-8 word summary of this delegation, shown in the transcript." }),
306
- ),
307
- task: Type.Optional(
308
- Type.String({ description: "Self-contained brief; the delegate cannot see this conversation." }),
309
- ),
460
+ agent: Type.String({ description: "Agent name from the list in this tool's description." }),
461
+ description: Type.String({
462
+ description: "Short 3-8 word summary of this delegation, shown in the transcript.",
463
+ }),
464
+ task: Type.String({ description: "Self-contained brief; the delegate cannot see this conversation." }),
310
465
  model: Type.Optional(
311
466
  Type.String({
312
467
  description:
313
468
  "Model tier (cheap, balanced, strong) or an explicit provider/model, with an optional :<thinking> suffix.",
314
469
  }),
315
470
  ),
316
- resume: Type.Optional(
317
- Type.String({
318
- description:
319
- "Job id of an interrupted, failed, or cancelled delegate to continue; it reuses the original agent, description and task (model may be overridden).",
320
- }),
321
- ),
322
471
  }),
323
472
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
324
- // Strict models inject literal "null" for optional params they omit; drop it before reading any.
325
- const params = Object.fromEntries(
326
- Object.entries(rawParams).filter(([, value]) => value !== null && value !== "null"),
327
- ) as typeof rawParams;
328
- const config = configFor(ctx.cwd);
329
- const agents = discoverAgents(ctx.cwd, config.agentDirs);
330
- const resuming = params.resume
331
- ? resumeDecision(jobId(params.resume), store.all(), new Set(store.live().map((job) => job.id)))
332
- : undefined;
333
- if (resuming?.error) throw new Error(resuming.error);
334
- const prior = resuming?.job;
335
- if (!prior && (!params.agent || !params.description || !params.task))
336
- throw new Error(
337
- "agent, description and task are required unless resuming an interrupted, failed, or cancelled job.",
338
- );
339
- const agent = agents.find((candidate) => candidate.name === (prior?.agent ?? params.agent));
473
+ const params = dropNulls(rawParams);
474
+ const { agent: agentName, description, task, model } = params;
475
+ if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
476
+ const agents = discoverAgents(ctx.cwd, configFor(ctx.cwd).agentDirs);
477
+ const agent = agents.find((candidate) => candidate.name === agentName);
340
478
  if (!agent) {
341
479
  const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
342
- throw new Error(`Unknown agent "${prior?.agent ?? params.agent}". Available agents: ${names}.`);
343
- }
344
- const { model, thinking } = resolveModel(params.model ?? agent.model, config.models ?? {}, ctx);
345
- if (!model) throw new Error(`No model found for "${agent.name}".`);
346
- const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
347
- (tool) => !DELEGATION_TOOLS.has(tool),
348
- );
349
- const displayModel = thinking ? `${model}:${thinking}` : model;
350
- const job: DelegateJob = {
351
- // A resumed job keeps its id: the pinned child session id reopens the old transcript.
352
- id: prior?.id ?? randomUUID().slice(0, 8),
353
- agent: agent.name,
354
- description: (prior?.description ?? params.description ?? "").trim(),
355
- task: prior?.task ?? params.task ?? "",
356
- model: displayModel,
357
- status: "running",
358
- // A resume continues the pinned transcript, so the inspector replays the child's own history.
359
- activity: prior ? priorActivity(DELEGATE_SESSION_DIR, prior.id) : [],
360
- tools,
361
- toolCalls: 0,
362
- startedAt: Date.now(),
363
- contextWindow: contextWindowFor(ctx, model),
364
- controller: new AbortController(),
365
- };
366
- const details: DelegateDetails = {
367
- id: job.id,
368
- agent: job.agent,
369
- description: job.description,
370
- task: job.task,
371
- model: displayModel,
372
- tools,
373
- background: ctx.hasUI,
374
- resumed: Boolean(prior),
375
- };
376
- const args = [
377
- "--session-id",
378
- `delegate-${job.id}`,
379
- "--session-dir",
380
- DELEGATE_SESSION_DIR,
381
- "--model",
382
- model,
383
- "--tools",
384
- tools.join(","),
385
- ];
386
- if (thinking) args.push("--thinking", thinking);
387
- if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
388
- const entrypoint = process.argv[1];
389
- if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
390
- const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
391
- cwd: ctx.cwd,
392
- shell: false,
393
- stdio: "pipe",
394
- });
395
- store.launch(job, details.background);
396
- const run = runChild(
397
- child,
398
- prior ? RESUME_PROMPT : job.task,
399
- details.background ? job.controller.signal : signal,
400
- (update) => store.record(job, update),
401
- Boolean(prior),
402
- );
403
- job.steer = run.steer;
404
-
405
- if (!details.background) {
406
- try {
407
- const output = await run.done;
408
- store.finish(job, "done");
409
- return { content: [{ type: "text", text: output }], details };
410
- } catch (error) {
411
- // Record the outcome so the launch entry cannot linger as "running".
412
- const cancelled = error instanceof Error && error.message === "Delegate was aborted";
413
- store.finish(job, cancelled ? "cancelled" : "failed");
414
- // Failed jobs are resumable; mirror the failed background report's hint on the thrown error.
415
- if (!cancelled && error instanceof Error) error.message += `\n${resumeHint(job.id)}`;
416
- throw error;
417
- }
480
+ throw new Error(`Unknown agent "${agentName}". Available agents: ${names}.`);
418
481
  }
419
-
420
- syncTicker(ctx);
421
- refreshWidget(ctx);
422
- void run.done
423
- .then(
424
- (output) => finishJob(ctx, job, output),
425
- (error) => finishJob(ctx, job, undefined, error instanceof Error ? error.message : String(error)),
426
- )
427
- .catch(() => {});
428
- return {
429
- content: [
430
- {
431
- type: "text",
432
- text: `${prior ? "Resumed" : "Started"} delegate "${job.agent}" in the background (job ${job.id}). Steer it with delegate_steer or stop it with delegate_cancel. Do not call tools solely to wait, even no-op bash commands; when its report is your next dependency, end your turn and it will arrive automatically unless cancelled.`,
433
- },
434
- ],
435
- details,
436
- };
482
+ return runDelegate(ctx, agent, undefined, { description, model }, task, signal);
437
483
  },
438
484
 
439
485
  renderCall(args, theme, context) {
440
- // A resume passes only the job id; recover the identity and task from the stored job.
441
- const resumed = args?.resume ? store.find(jobId(args.resume)) : undefined;
442
- const agent = argText(args?.agent).trim() || resumed?.agent || "";
443
- const description = argText(args?.description).trim() || resumed?.description || "";
486
+ const agent = argText(args?.agent).trim();
487
+ const description = argText(args?.description).trim();
444
488
  const identity = [
445
489
  agent ? theme.fg("toolTitle", theme.bold(agent)) : "",
446
490
  description ? theme.fg("accent", description) : "",
447
- resumed ? theme.fg("muted", "(resumed)") : "",
448
491
  ]
449
492
  .filter(Boolean)
450
493
  .join(" ");
451
494
  return toolLayout(
452
495
  "delegate",
453
496
  identity || theme.fg("muted", "…"),
454
- argText(args?.task) || resumed?.task || "",
497
+ argText(args?.task),
455
498
  theme,
456
499
  context.expanded,
457
500
  );
@@ -461,31 +504,13 @@ export default function (pi: ExtensionAPI) {
461
504
  const details = result.details as DelegateDetails | undefined;
462
505
  const body = resultText(result);
463
506
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
464
- const status = details.background
465
- ? `${details.resumed ? "resumed" : "started"} in background`
466
- : "completed";
467
- // The done icon means actual completion; a background launch reports its status without it.
468
- const header = details.background
469
- ? `${jobIdentity(theme, details)} ${theme.fg("muted", status)}`
470
- : `${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", status)}`;
471
- const container = new Container();
472
- container.addChild(new Text(`\n${header}`, 0, 0));
473
- // The call body already carries the task; only the launch metadata is new here.
474
- if (expanded)
475
- container.addChild(
476
- new Text(
477
- theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")),
478
- 0,
479
- 0,
480
- ),
481
- );
482
- // Background results arrive as their own message; headless runs still show the output here.
483
- if (!details.background && body) {
484
- const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
485
- container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
486
- if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
487
- }
488
- return container;
507
+ return launchResult(
508
+ details,
509
+ body,
510
+ details.background ? "started in background" : "completed",
511
+ expanded,
512
+ theme,
513
+ );
489
514
  },
490
515
  });
491
516
 
@@ -493,35 +518,78 @@ export default function (pi: ExtensionAPI) {
493
518
  name: "delegate_steer",
494
519
  label: "Steer delegate",
495
520
  description:
496
- "Send guidance to a running background delegate. The child receives it after its current tool calls and before its next model request; it cannot revive a finished job. Use delegate_list for the ids of running jobs.",
497
- promptSnippet: "Send guidance to a running background delegate by job id",
521
+ "Send guidance to a delegate by job id. A running job receives it after its current tool calls, before its next model request. A finished job (done, failed, cancelled, or interrupted) continues its own transcript with the message as its next instruction and reports again as a follow-up.",
522
+ promptSnippet: "Send guidance to a delegate by job id, or continue a finished one",
498
523
  parameters: Type.Object({
499
524
  id: Type.String({
500
525
  description: 'Job id from a delegate tool result or a delegate-result message, such as "38631a01".',
501
526
  }),
502
- message: Type.String({ description: "The guidance to deliver to the running child." }),
527
+ message: Type.String({
528
+ description:
529
+ "The guidance to deliver: queued on a running child, or the next instruction when it revives a finished job.",
530
+ }),
531
+ model: Type.Optional(
532
+ Type.String({
533
+ description:
534
+ "Model tier (cheap, balanced, strong) or an explicit provider/model, with an optional :<thinking> suffix. Switches a running job's model live, without a restart.",
535
+ }),
536
+ ),
503
537
  }),
504
- async execute(_toolCallId, params) {
538
+ async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
539
+ const params = dropNulls(rawParams);
505
540
  const id = jobId(params.id);
506
- const job = store.live().find((candidate) => candidate.id === id);
507
- if (!job?.steer) throw new Error(`No running delegate job "${id}".`);
508
- await job.steer(params.message);
509
- const details: SteerDetails = {
510
- id: job.id,
511
- agent: job.agent,
512
- description: job.description,
513
- message: params.message,
514
- toolCalls: job.toolCalls,
515
- contextTokens: job.contextTokens,
516
- contextWindow: job.contextWindow,
517
- elapsedMs: Date.now() - job.startedAt,
518
- };
519
- return {
520
- content: [
521
- { type: "text", text: `Steering message delivered to delegate "${job.agent}" (job ${job.id}).` },
522
- ],
523
- details,
524
- };
541
+ const running = store.live().find((candidate) => candidate.id === id);
542
+ if (running) {
543
+ // A live job without steer would fall into the revive path and double-spawn its pinned session.
544
+ if (!running.steer) throw new Error(`No steerable delegate job "${id}".`);
545
+ try {
546
+ if (params.model) await swapModel(running, params.model, ctx);
547
+ await running.steer(params.message);
548
+ } catch (error) {
549
+ // The swap or steer await can outlast the job (a model ack waits up to 30s); raw child errors are cryptic.
550
+ if (!store.live().some((candidate) => candidate.id === id))
551
+ throw new Error(
552
+ `Delegate job "${id}" just finished; call delegate_steer again to continue it.`,
553
+ );
554
+ throw error;
555
+ }
556
+ const details: SteerDetails = {
557
+ id: running.id,
558
+ agent: running.agent,
559
+ description: running.description,
560
+ message: params.message,
561
+ toolCalls: running.toolCalls,
562
+ contextTokens: running.contextTokens,
563
+ contextWindow: running.contextWindow,
564
+ elapsedMs: Date.now() - running.startedAt,
565
+ };
566
+ return {
567
+ content: [
568
+ {
569
+ type: "text",
570
+ text: `Steering message delivered to delegate "${running.agent}" (job ${running.id}).`,
571
+ },
572
+ ],
573
+ details,
574
+ };
575
+ }
576
+ const prior = store.find(id);
577
+ if (!id || !prior) throw new Error(`Unknown delegate job "${id}".`);
578
+ const agents = discoverAgents(ctx.cwd, configFor(ctx.cwd).agentDirs);
579
+ const agent = agents.find((candidate) => candidate.name === prior.agent);
580
+ if (!agent) {
581
+ const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
582
+ throw new Error(`Unknown agent "${prior.agent}". Available agents: ${names}.`);
583
+ }
584
+ return runDelegate(
585
+ ctx,
586
+ agent,
587
+ prior,
588
+ { description: prior.description, model: params.model ?? prior.model },
589
+ prior.task,
590
+ signal,
591
+ params.message,
592
+ );
525
593
  },
526
594
 
527
595
  renderCall(args, theme, context) {
@@ -534,14 +602,22 @@ export default function (pi: ExtensionAPI) {
534
602
  );
535
603
  },
536
604
 
537
- renderResult(result, _options, theme, context) {
538
- const details = result.details as SteerDetails | undefined;
605
+ renderResult(result, { expanded }, theme, context) {
606
+ const details = result.details as SteerDetails | DelegateDetails | undefined;
539
607
  const body = resultText(result);
540
608
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
541
- return new Text(
542
- `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("muted", usageStats(details, details.elapsedMs))}`,
543
- 0,
544
- 0,
609
+ if ("message" in details)
610
+ return new Text(
611
+ `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("muted", usageStats(details, details.elapsedMs))}`,
612
+ 0,
613
+ 0,
614
+ );
615
+ return launchResult(
616
+ details,
617
+ body,
618
+ details.background ? "revived in background" : "revived",
619
+ expanded,
620
+ theme,
545
621
  );
546
622
  },
547
623
  });
@@ -550,7 +626,7 @@ export default function (pi: ExtensionAPI) {
550
626
  name: "delegate_cancel",
551
627
  label: "Cancel delegate",
552
628
  description:
553
- "Cancel a running background delegate by job id. Requests abort now and forcibly kills the child after five seconds if needed. Cancelled jobs send no follow-up report, but can be resumed later with the delegate tool's `resume` parameter.",
629
+ "Cancel a running background delegate by job id. Requests abort now and force-kills the child after five seconds if needed. A cancelled job sends no report; continue it later with delegate_steer.",
554
630
  promptSnippet: "Cancel a running background delegate by job id",
555
631
  parameters: Type.Object({
556
632
  id: Type.String({ description: "Job id from delegate or delegate_list." }),
@@ -580,7 +656,8 @@ export default function (pi: ExtensionAPI) {
580
656
  const body = resultText(result);
581
657
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
582
658
  return new Text(
583
- `\n${statusText(theme, "cancelled")} ${jobIdentity(theme, details)} ${theme.fg("muted", "cancellation requested")}`,
659
+ // The mark is the call's outcome (cancellation requested), not the job's cancelled status.
660
+ `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", "cancellation requested")}`,
584
661
  0,
585
662
  0,
586
663
  );
@@ -591,21 +668,28 @@ export default function (pi: ExtensionAPI) {
591
668
  name: "delegate_list",
592
669
  label: "List delegates",
593
670
  description:
594
- "List the background delegates still running, with their job ids and progress, for steering or checking. Finished delegates are not listed; their results arrive as follow-up messages.",
595
- promptSnippet: "List running background delegates and their job ids",
671
+ "List delegates with their job ids, status, and progress. Finished jobs stay listed; continue one with delegate_steer.",
672
+ promptSnippet: "List delegates and their job ids",
596
673
  parameters: Type.Object({}),
597
674
  async execute() {
598
675
  const now = Date.now();
599
- const jobs = store.live();
600
- if (!jobs.length)
601
- return { content: [{ type: "text", text: "No delegates are running." }], details: undefined };
602
- const lastActivity = (job: DelegateJob) =>
603
- job.lastTool ? ` · ${job.lastTool}${job.lastDetail ? ` ${job.lastDetail}` : ""}` : "";
676
+ const jobs = store.all();
677
+ if (!jobs.length) return { content: [{ type: "text", text: "No delegates yet." }], details: undefined };
678
+ const running = jobs.filter((job) => job.status === "running").length;
679
+ const lastActivity = (job: InspectJob) => {
680
+ const { lastTool, lastDetail } = job as DelegateJob;
681
+ return job.status === "running" && lastTool
682
+ ? ` · ${lastTool}${lastDetail ? ` ${lastDetail}` : ""}`
683
+ : "";
684
+ };
604
685
  const lines = jobs.map(
605
- (job) => `- ${job.id} ${job.agent} · ${jobLine(job, now - job.startedAt)}${lastActivity(job)}`,
686
+ (job) =>
687
+ `- ${job.id} ${job.agent} · ${job.status} · ${jobLine(job, (job.endedAt ?? now) - job.startedAt)}${lastActivity(job)}`,
606
688
  );
607
689
  return {
608
- content: [{ type: "text", text: `${jobs.length} running:\n${lines.join("\n")}` }],
690
+ content: [
691
+ { type: "text", text: `${jobs.length} delegates (${running} running):\n${lines.join("\n")}` },
692
+ ],
609
693
  details: { jobs: jobs.map(jobSnapshot) },
610
694
  };
611
695
  },
@@ -614,8 +698,11 @@ export default function (pi: ExtensionAPI) {
614
698
  if (!jobs?.length || context.isError) return resultFallback(resultText(result), theme, context.isError);
615
699
  const now = Date.now();
616
700
  return new Text(
617
- `\n${jobs
618
- .map((job) => `${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`)
701
+ `\n${statusText(theme, "done")} ${theme.fg("muted", `${jobs.length} delegates`)}\n${jobs
702
+ .map(
703
+ (job) =>
704
+ `${statusText(theme, job.status, now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, (job.endedAt ?? now) - job.startedAt))}`,
705
+ )
619
706
  .join("\n")}`,
620
707
  0,
621
708
  0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.23",
3
+ "version": "0.0.24",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/store.ts CHANGED
@@ -23,6 +23,7 @@ export type DelegateJob = InspectJob & {
23
23
  lastResult?: string;
24
24
  controller: AbortController;
25
25
  steer?: (message: string) => Promise<void>;
26
+ swapModel?: (provider: string, modelId: string, level?: string, onModelSet?: () => void) => Promise<void>;
26
27
  };
27
28
 
28
29
  const JOB_ENTRY = "delegate-job";
@@ -42,25 +43,6 @@ function restoredJobs(entries: readonly unknown[]): InspectJob[] {
42
43
  return jobs;
43
44
  }
44
45
 
45
- /** Whether and how a delegate call may resume an interrupted, failed, or cancelled job. */
46
- export function resumeDecision(
47
- id: string,
48
- jobs: readonly InspectJob[],
49
- live: ReadonlySet<string>,
50
- ): { job?: InspectJob; error?: string } {
51
- if (!id) return { error: "No job id given for resume." };
52
- if (live.has(id))
53
- return { error: `Delegate job "${id}" is still running; steer or cancel it instead of resuming.` };
54
- const job = jobs.find((candidate) => candidate.id === id);
55
- if (!job) return { error: `Unknown delegate job "${id}".` };
56
- if (job.status === "interrupted" || job.status === "failed" || job.status === "cancelled") return { job };
57
- if (job.status === "done")
58
- return { error: `Delegate job "${id}" is already done; its report is in this session, no resume needed.` };
59
- return {
60
- error: `Delegate job "${id}" is ${job.status}; only interrupted, failed or cancelled jobs can be resumed.`,
61
- };
62
- }
63
-
64
46
  /** One owner for live jobs, history, and the delegate-job session entries they write. */
65
47
  export function createJobStore(append: (customType: string, data: InspectJob) => void) {
66
48
  const running = new Map<string, DelegateJob>();
@@ -75,7 +57,7 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
75
57
  if (stale >= 0) history.splice(stale, 1);
76
58
  };
77
59
  const entryData = (job: DelegateJob): InspectJob => {
78
- const { controller, steer, lastTool, lastDetail, lastResult, ...snapshot } = job;
60
+ const { controller, steer, swapModel, lastTool, lastDetail, lastResult, ...snapshot } = job;
79
61
  // Copy activity: the live job keeps appending to its own array after the launch snapshot.
80
62
  return { ...snapshot, activity: [...snapshot.activity] };
81
63
  };