@deathbeam/pi-delegate 0.0.22 → 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
@@ -1,4 +1,6 @@
1
1
  import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
2
4
  import { limitOutput, resultPreview, toolCallDetail } from "./format.ts";
3
5
 
4
6
  type Child = ChildProcessWithoutNullStreams;
@@ -27,6 +29,7 @@ type ChildUpdateHandler = (update: ChildUpdate) => void;
27
29
  type ChildRun = {
28
30
  done: Promise<string>;
29
31
  steer: (message: string) => Promise<void>;
32
+ swapModel: (provider: string, modelId: string, level?: string, onModelSet?: () => void) => Promise<void>;
30
33
  };
31
34
 
32
35
  /** Run one RPC child, keeping its writer serialized so backpressure and EPIPE reach the caller. */
@@ -35,7 +38,7 @@ export function runChild(
35
38
  task: string,
36
39
  signal: AbortSignal | undefined,
37
40
  onUpdate?: ChildUpdateHandler,
38
- resume?: boolean,
41
+ revive?: boolean,
39
42
  ): ChildRun {
40
43
  let buffer = "";
41
44
  let liveText = "";
@@ -270,21 +273,21 @@ export function runChild(
270
273
  if (!settled) fail(error);
271
274
  });
272
275
  };
273
- if (resume) {
276
+ if (revive) {
274
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.
275
278
  void send({ type: "get_state" })
276
279
  .then((data) => {
277
280
  if (!settled && !aborted && !data?.messageCount) {
278
281
  fail(
279
282
  new Error(
280
- "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.",
281
284
  ),
282
285
  );
283
286
  return;
284
287
  }
285
288
  prompt();
286
289
  })
287
- // 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.
288
291
  .catch((error) => {
289
292
  if (!settled && !aborted) fail(error);
290
293
  });
@@ -297,5 +300,89 @@ export function runChild(
297
300
  return {
298
301
  done,
299
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
+ },
300
309
  };
301
310
  }
311
+
312
+ /** Text content of a persisted transcript message, in part order. */
313
+ function transcriptText(content: unknown): string[] {
314
+ if (typeof content === "string") return [content];
315
+ if (!Array.isArray(content)) return [];
316
+ return content
317
+ .map((part) => (part && typeof part === "object" ? (part as { type?: string; text?: string }) : {}))
318
+ .filter((part) => part.type === "text" && typeof part.text === "string")
319
+ .map((part) => part.text!);
320
+ }
321
+
322
+ /**
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
325
+ * itself still works.
326
+ */
327
+ export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
328
+ let sessionFile: string | undefined;
329
+ try {
330
+ // Sessions are <timestamp>_<sessionId>.jsonl; a recreated pinned session is the newest one.
331
+ sessionFile = readdirSync(sessionDir)
332
+ .filter((name) => name.endsWith(`_delegate-${id}.jsonl`))
333
+ .sort()
334
+ .at(-1);
335
+ } catch {
336
+ return [];
337
+ }
338
+ if (!sessionFile) return [];
339
+ let lines: string[] = [];
340
+ try {
341
+ lines = readFileSync(join(sessionDir, sessionFile), "utf8").split("\n");
342
+ } catch {
343
+ return [];
344
+ }
345
+ const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
346
+ const activity: ChildActivity[] = [];
347
+ for (const line of lines) {
348
+ if (!line.trim()) continue;
349
+ let entry: { type?: string; message?: unknown };
350
+ try {
351
+ entry = JSON.parse(line);
352
+ } catch {
353
+ continue; // Same tolerance pi's session reader has for malformed lines.
354
+ }
355
+ const message =
356
+ entry?.type === "message"
357
+ ? (entry.message as {
358
+ role?: "assistant" | "user" | "toolResult";
359
+ content?: unknown;
360
+ toolName?: string;
361
+ })
362
+ : undefined;
363
+ if (!message?.role) continue;
364
+ if (message.role === "toolResult") {
365
+ const preview = resultPreview({ content: message.content });
366
+ activity.push({
367
+ kind: "result",
368
+ text: normalize(`↳ ${message.toolName ?? "tool"}: ${preview ?? "(no text output)"}`),
369
+ });
370
+ continue;
371
+ }
372
+ // Assistant text lands before its tool calls, matching the live event order.
373
+ const text = transcriptText(message.content).join("");
374
+ if (text) activity.push({ kind: message.role, text });
375
+ if (message.role !== "assistant") continue;
376
+ for (const part of Array.isArray(message.content) ? message.content : []) {
377
+ const call =
378
+ part && typeof part === "object" ? (part as { type?: string; name?: string; arguments?: unknown }) : {};
379
+ if (call.type !== "toolCall" || !call.name) continue;
380
+ activity.push({
381
+ kind: "tool",
382
+ text: normalize(call.name),
383
+ detail: normalize(toolCallDetail(call.name, call.arguments)) || undefined,
384
+ });
385
+ }
386
+ }
387
+ return activity;
388
+ }
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,
@@ -29,10 +29,10 @@ import {
29
29
  usageStats,
30
30
  widgetJobs,
31
31
  } from "./format.ts";
32
- import { runChild } from "./child.ts";
33
- import { createJobStore, resumeDecision, type DelegateJob } from "./store.ts";
32
+ import { priorActivity, runChild } from "./child.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;
@@ -53,7 +53,6 @@ const REMINDER_MESSAGE = "delegate-reminder";
53
53
  const EXPLORATION_TOOLS = new Set(["read", "grep", "find", "ls", "bash", "powershell", "web_search", "web_fetch"]);
54
54
  const FIRST_REMINDER_AT = 5;
55
55
  const DELEGATE_SESSION_DIR = join(getAgentDir(), "sessions", "delegates");
56
- const RESUME_PROMPT = "Continue the task above from where you left off.";
57
56
  const INTERRUPTED_MESSAGE = "delegate-interrupted";
58
57
 
59
58
  function argText(value: unknown): string {
@@ -65,13 +64,25 @@ function jobId(value: unknown): string {
65
64
  .trim()
66
65
  .replace(/^job\s+/i, "");
67
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
+ }
68
71
 
69
72
  function resultText(result: { content: readonly { type: string; text?: string }[] }): string {
70
73
  return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n");
71
74
  }
72
75
 
73
76
  function resultFallback(body: string, theme: Theme, isError: boolean): Text {
74
- 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));
75
86
  }
76
87
 
77
88
  /** Shared collapsed-output note so all three preview sites phrase it identically. */
@@ -79,6 +90,13 @@ function moreLines(theme: Theme, hidden: number): string {
79
90
  return theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand");
80
91
  }
81
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
+
82
100
  /** Shared tool layout: an optional identity header, then a width-aware payload preview. */
83
101
  function toolLayout(toolName: string, identity: string, payload: string, theme: Theme, expanded: boolean): Component {
84
102
  const container = new Container();
@@ -111,6 +129,29 @@ function toolLayout(toolName: string, identity: string, payload: string, theme:
111
129
  return container;
112
130
  }
113
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
+
114
155
  export default function (pi: ExtensionAPI) {
115
156
  const store = createJobStore(pi.appendEntry);
116
157
  let ticker: ReturnType<typeof setInterval> | undefined;
@@ -118,13 +159,15 @@ export default function (pi: ExtensionAPI) {
118
159
  let directCalls = 0;
119
160
  let nextReminder = FIRST_REMINDER_AT;
120
161
 
121
- const jobSnapshot = (job: DelegateJob) => ({
162
+ const jobSnapshot = (job: InspectJob) => ({
122
163
  id: job.id,
123
164
  agent: job.agent,
124
165
  description: job.description,
125
166
  contextTokens: job.contextTokens,
126
167
  contextWindow: job.contextWindow,
127
168
  startedAt: job.startedAt,
169
+ status: job.status,
170
+ endedAt: job.endedAt,
128
171
  });
129
172
 
130
173
  const jobTarget = (rawId: unknown, theme: Theme): string => {
@@ -196,6 +239,125 @@ export default function (pi: ExtensionAPI) {
196
239
  );
197
240
  };
198
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
+
199
361
  pi.on("session_shutdown", () => {
200
362
  if (ticker) clearInterval(ticker);
201
363
  for (const job of store.live()) job.controller.abort();
@@ -210,7 +372,7 @@ export default function (pi: ExtensionAPI) {
210
372
  pi.sendMessage(
211
373
  {
212
374
  customType: INTERRUPTED_MESSAGE,
213
- 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>`,
214
376
  display: false,
215
377
  },
216
378
  { deliverAs: "steer" },
@@ -260,11 +422,7 @@ export default function (pi: ExtensionAPI) {
260
422
  ),
261
423
  );
262
424
  if (report.error) container.addChild(new Text(theme.fg("error", report.error), 0, 0));
263
- else if (report.output) {
264
- const { shown, hidden } = outputPreview(report.output, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
265
- container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
266
- if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
267
- }
425
+ else if (report.output) appendOutput(container, report.output, expanded, theme);
268
426
  return container;
269
427
  });
270
428
 
@@ -286,7 +444,7 @@ export default function (pi: ExtensionAPI) {
286
444
  "",
287
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).",
288
446
  "",
289
- "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.",
290
448
  ].join("\n"),
291
449
  promptSnippet:
292
450
  "Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
@@ -299,138 +457,29 @@ export default function (pi: ExtensionAPI) {
299
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.",
300
458
  ],
301
459
  parameters: Type.Object({
302
- agent: Type.Optional(Type.String({ description: "Agent name from the list in this tool's description." })),
303
- description: Type.Optional(
304
- Type.String({ description: "Short 3-8 word summary of this delegation, shown in the transcript." }),
305
- ),
306
- task: Type.Optional(
307
- Type.String({ description: "Self-contained brief; the delegate cannot see this conversation." }),
308
- ),
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." }),
309
465
  model: Type.Optional(
310
466
  Type.String({
311
467
  description:
312
468
  "Model tier (cheap, balanced, strong) or an explicit provider/model, with an optional :<thinking> suffix.",
313
469
  }),
314
470
  ),
315
- resume: Type.Optional(
316
- Type.String({
317
- description:
318
- "Job id of an interrupted, failed, or cancelled delegate to continue; it reuses the original agent, description and task (model may be overridden).",
319
- }),
320
- ),
321
471
  }),
322
472
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
323
- // Strict models inject literal "null" for optional params they omit; drop it before reading any.
324
- const params = Object.fromEntries(
325
- Object.entries(rawParams).filter(([, value]) => value !== null && value !== "null"),
326
- ) as typeof rawParams;
327
- const config = configFor(ctx.cwd);
328
- const agents = discoverAgents(ctx.cwd, config.agentDirs);
329
- const resuming = params.resume
330
- ? resumeDecision(jobId(params.resume), store.all(), new Set(store.live().map((job) => job.id)))
331
- : undefined;
332
- if (resuming?.error) throw new Error(resuming.error);
333
- const prior = resuming?.job;
334
- if (!prior && (!params.agent || !params.description || !params.task))
335
- throw new Error(
336
- "agent, description and task are required unless resuming an interrupted, failed, or cancelled job.",
337
- );
338
- 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);
339
478
  if (!agent) {
340
479
  const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
341
- throw new Error(`Unknown agent "${prior?.agent ?? params.agent}". Available agents: ${names}.`);
342
- }
343
- const { model, thinking } = resolveModel(params.model ?? agent.model, config.models ?? {}, ctx);
344
- if (!model) throw new Error(`No model found for "${agent.name}".`);
345
- const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
346
- (tool) => !DELEGATION_TOOLS.has(tool),
347
- );
348
- const displayModel = thinking ? `${model}:${thinking}` : model;
349
- const job: DelegateJob = {
350
- // A resumed job keeps its id: the pinned child session id reopens the old transcript.
351
- id: prior?.id ?? randomUUID().slice(0, 8),
352
- agent: agent.name,
353
- description: (prior?.description ?? params.description ?? "").trim(),
354
- task: prior?.task ?? params.task ?? "",
355
- model: displayModel,
356
- status: "running",
357
- activity: [],
358
- tools,
359
- toolCalls: 0,
360
- startedAt: Date.now(),
361
- contextWindow: contextWindowFor(ctx, model),
362
- controller: new AbortController(),
363
- };
364
- const details: DelegateDetails = {
365
- id: job.id,
366
- agent: job.agent,
367
- description: job.description,
368
- task: job.task,
369
- model: displayModel,
370
- tools,
371
- background: ctx.hasUI,
372
- };
373
- const args = [
374
- "--session-id",
375
- `delegate-${job.id}`,
376
- "--session-dir",
377
- DELEGATE_SESSION_DIR,
378
- "--model",
379
- model,
380
- "--tools",
381
- tools.join(","),
382
- ];
383
- if (thinking) args.push("--thinking", thinking);
384
- if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
385
- const entrypoint = process.argv[1];
386
- if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
387
- const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
388
- cwd: ctx.cwd,
389
- shell: false,
390
- stdio: "pipe",
391
- });
392
- store.launch(job, details.background);
393
- const run = runChild(
394
- child,
395
- prior ? RESUME_PROMPT : job.task,
396
- details.background ? job.controller.signal : signal,
397
- (update) => store.record(job, update),
398
- Boolean(prior),
399
- );
400
- job.steer = run.steer;
401
-
402
- if (!details.background) {
403
- try {
404
- const output = await run.done;
405
- store.finish(job, "done");
406
- return { content: [{ type: "text", text: output }], details };
407
- } catch (error) {
408
- // Record the outcome so the launch entry cannot linger as "running".
409
- const cancelled = error instanceof Error && error.message === "Delegate was aborted";
410
- store.finish(job, cancelled ? "cancelled" : "failed");
411
- // Failed jobs are resumable; mirror the failed background report's hint on the thrown error.
412
- if (!cancelled && error instanceof Error) error.message += `\n${resumeHint(job.id)}`;
413
- throw error;
414
- }
480
+ throw new Error(`Unknown agent "${agentName}". Available agents: ${names}.`);
415
481
  }
416
-
417
- syncTicker(ctx);
418
- refreshWidget(ctx);
419
- void run.done
420
- .then(
421
- (output) => finishJob(ctx, job, output),
422
- (error) => finishJob(ctx, job, undefined, error instanceof Error ? error.message : String(error)),
423
- )
424
- .catch(() => {});
425
- return {
426
- content: [
427
- {
428
- type: "text",
429
- text: `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.`,
430
- },
431
- ],
432
- details,
433
- };
482
+ return runDelegate(ctx, agent, undefined, { description, model }, task, signal);
434
483
  },
435
484
 
436
485
  renderCall(args, theme, context) {
@@ -455,29 +504,13 @@ export default function (pi: ExtensionAPI) {
455
504
  const details = result.details as DelegateDetails | undefined;
456
505
  const body = resultText(result);
457
506
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
458
- const status = details.background ? "started in background" : "completed";
459
- // The done icon means actual completion; a background launch reports its status without it.
460
- const header = details.background
461
- ? `${jobIdentity(theme, details)} ${theme.fg("muted", status)}`
462
- : `${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", status)}`;
463
- const container = new Container();
464
- container.addChild(new Text(`\n${header}`, 0, 0));
465
- // The call body already carries the task; only the launch metadata is new here.
466
- if (expanded)
467
- container.addChild(
468
- new Text(
469
- theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")),
470
- 0,
471
- 0,
472
- ),
473
- );
474
- // Background results arrive as their own message; headless runs still show the output here.
475
- if (!details.background && body) {
476
- const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
477
- container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
478
- if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
479
- }
480
- return container;
507
+ return launchResult(
508
+ details,
509
+ body,
510
+ details.background ? "started in background" : "completed",
511
+ expanded,
512
+ theme,
513
+ );
481
514
  },
482
515
  });
483
516
 
@@ -485,35 +518,78 @@ export default function (pi: ExtensionAPI) {
485
518
  name: "delegate_steer",
486
519
  label: "Steer delegate",
487
520
  description:
488
- "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.",
489
- 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",
490
523
  parameters: Type.Object({
491
524
  id: Type.String({
492
525
  description: 'Job id from a delegate tool result or a delegate-result message, such as "38631a01".',
493
526
  }),
494
- 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
+ ),
495
537
  }),
496
- async execute(_toolCallId, params) {
538
+ async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
539
+ const params = dropNulls(rawParams);
497
540
  const id = jobId(params.id);
498
- const job = store.live().find((candidate) => candidate.id === id);
499
- if (!job?.steer) throw new Error(`No running delegate job "${id}".`);
500
- await job.steer(params.message);
501
- const details: SteerDetails = {
502
- id: job.id,
503
- agent: job.agent,
504
- description: job.description,
505
- message: params.message,
506
- toolCalls: job.toolCalls,
507
- contextTokens: job.contextTokens,
508
- contextWindow: job.contextWindow,
509
- elapsedMs: Date.now() - job.startedAt,
510
- };
511
- return {
512
- content: [
513
- { type: "text", text: `Steering message delivered to delegate "${job.agent}" (job ${job.id}).` },
514
- ],
515
- details,
516
- };
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
+ );
517
593
  },
518
594
 
519
595
  renderCall(args, theme, context) {
@@ -526,14 +602,22 @@ export default function (pi: ExtensionAPI) {
526
602
  );
527
603
  },
528
604
 
529
- renderResult(result, _options, theme, context) {
530
- const details = result.details as SteerDetails | undefined;
605
+ renderResult(result, { expanded }, theme, context) {
606
+ const details = result.details as SteerDetails | DelegateDetails | undefined;
531
607
  const body = resultText(result);
532
608
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
533
- return new Text(
534
- `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("muted", usageStats(details, details.elapsedMs))}`,
535
- 0,
536
- 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,
537
621
  );
538
622
  },
539
623
  });
@@ -542,7 +626,7 @@ export default function (pi: ExtensionAPI) {
542
626
  name: "delegate_cancel",
543
627
  label: "Cancel delegate",
544
628
  description:
545
- "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.",
546
630
  promptSnippet: "Cancel a running background delegate by job id",
547
631
  parameters: Type.Object({
548
632
  id: Type.String({ description: "Job id from delegate or delegate_list." }),
@@ -572,7 +656,8 @@ export default function (pi: ExtensionAPI) {
572
656
  const body = resultText(result);
573
657
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
574
658
  return new Text(
575
- `\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")}`,
576
661
  0,
577
662
  0,
578
663
  );
@@ -583,21 +668,28 @@ export default function (pi: ExtensionAPI) {
583
668
  name: "delegate_list",
584
669
  label: "List delegates",
585
670
  description:
586
- "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.",
587
- 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",
588
673
  parameters: Type.Object({}),
589
674
  async execute() {
590
675
  const now = Date.now();
591
- const jobs = store.live();
592
- if (!jobs.length)
593
- return { content: [{ type: "text", text: "No delegates are running." }], details: undefined };
594
- const lastActivity = (job: DelegateJob) =>
595
- 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
+ };
596
685
  const lines = jobs.map(
597
- (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)}`,
598
688
  );
599
689
  return {
600
- 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
+ ],
601
693
  details: { jobs: jobs.map(jobSnapshot) },
602
694
  };
603
695
  },
@@ -606,8 +698,11 @@ export default function (pi: ExtensionAPI) {
606
698
  if (!jobs?.length || context.isError) return resultFallback(resultText(result), theme, context.isError);
607
699
  const now = Date.now();
608
700
  return new Text(
609
- `\n${jobs
610
- .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
+ )
611
706
  .join("\n")}`,
612
707
  0,
613
708
  0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.22",
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
  };