@deathbeam/pi-delegate 0.0.17 → 0.0.19

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/index.ts CHANGED
@@ -1,57 +1,36 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { existsSync, readdirSync, readFileSync } from "node:fs";
4
- import { homedir } from "node:os";
5
- import { join, resolve } from "node:path";
6
- import { fileURLToPath } from "node:url";
3
+ import { join } from "node:path";
7
4
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
8
- import {
9
- CONFIG_DIR_NAME,
10
- getAgentDir,
11
- getMarkdownTheme,
12
- keyHint,
13
- parseFrontmatter,
14
- rawKeyHint,
15
- } from "@earendil-works/pi-coding-agent";
5
+ import { getAgentDir, getMarkdownTheme, keyHint } from "@earendil-works/pi-coding-agent";
16
6
  import {
17
7
  type Component,
18
8
  Container,
19
- HStack,
20
9
  Markdown,
21
10
  Spacer,
22
11
  Text,
23
12
  TruncatedText,
24
- matchesKey,
25
13
  truncateToWidth,
26
- wrapTextWithAnsi,
27
14
  } from "@earendil-works/pi-tui";
28
15
  import { Type } from "typebox";
29
16
  import {
30
17
  COLLAPSED_OUTPUT_LINES,
31
18
  type DelegateReport,
32
- formatTools,
33
19
  jobIdentity,
34
20
  jobLine,
35
- type JobStatus,
36
21
  launchDetails,
37
22
  outputPreview,
38
23
  reportText,
24
+ resumeHint,
39
25
  SPINNER_INTERVAL_MS,
40
- STATUS_COLORS,
41
26
  statusText,
42
27
  usageStats,
43
28
  widgetJobs,
44
29
  } from "./format.ts";
45
- import { type ChildActivity, runChild } from "./child.ts";
46
-
47
- type AgentFile = {
48
- name: string;
49
- description: string;
50
- tools?: string[];
51
- model?: string;
52
- thinking?: string;
53
- prompt: string;
54
- };
30
+ import { runChild } from "./child.ts";
31
+ import { createJobStore, resumeDecision, type DelegateJob } from "./store.ts";
32
+ import { registerInspector } from "./inspector.ts";
33
+ import { configFor, contextWindowFor, discoverAgents, resolveModel } from "./agents.ts";
55
34
 
56
35
  type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "description" | "task" | "model" | "tools"> & {
57
36
  background: boolean;
@@ -65,130 +44,15 @@ type SteerDetails = Pick<
65
44
  elapsedMs: number;
66
45
  };
67
46
 
68
- type InspectJob = {
69
- id: string;
70
- agent: string;
71
- description: string;
72
- task: string;
73
- model: string;
74
- tools: string[];
75
- toolCalls: number;
76
- contextTokens?: number;
77
- contextWindow?: number;
78
- startedAt: number;
79
- endedAt?: number;
80
- status: JobStatus;
81
- activity: ChildActivity[];
82
- };
83
-
84
- type DelegateJob = InspectJob & {
85
- lastTool?: string;
86
- lastDetail?: string;
87
- lastResult?: string;
88
- controller: AbortController;
89
- steer?: (message: string) => Promise<void>;
90
- };
91
-
92
- type DelegateConfig = {
93
- agentDirs?: unknown;
94
- models?: Record<string, unknown>;
95
- };
96
-
97
- const DEFAULT_AGENT_DIR = "~/.agents/agents";
98
- const BUNDLED_AGENT_DIR = fileURLToPath(new URL("./agents", import.meta.url));
99
47
  const DELEGATION_TOOLS = new Set(["delegate", "delegate_list", "delegate_steer", "delegate_cancel"]);
100
- const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
101
48
  const WIDGET_KEY = "delegate";
102
49
  const RESULT_MESSAGE = "delegate-result";
103
50
  const REMINDER_MESSAGE = "delegate-reminder";
104
- const JOB_ENTRY = "delegate-job";
105
51
  const EXPLORATION_TOOLS = new Set(["read", "grep", "find", "ls", "bash", "powershell", "web_search", "web_fetch"]);
106
52
  const FIRST_REMINDER_AT = 5;
107
-
108
- function expandPath(value: string, cwd: string): string {
109
- return resolve(cwd, value.replace(/^~(?=\/|$)/, homedir()));
110
- }
111
-
112
- function stringList(value: unknown): string[] {
113
- const values = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : [];
114
- return values
115
- .filter((item): item is string => typeof item === "string")
116
- .map((item) => item.trim())
117
- .filter(Boolean);
118
- }
119
-
120
- function readConfig(path: string): DelegateConfig {
121
- try {
122
- const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
123
- if (!parsed || typeof parsed !== "object") return {};
124
- const delegate = (parsed as { delegate?: unknown }).delegate;
125
- return delegate && typeof delegate === "object" ? (delegate as DelegateConfig) : {};
126
- } catch {
127
- return {};
128
- }
129
- }
130
-
131
- function configFor(cwd: string): DelegateConfig {
132
- const global = readConfig(join(getAgentDir(), "settings.json"));
133
- const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
134
- return {
135
- agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
136
- models: { ...(global.models ?? {}), ...(project.models ?? {}) },
137
- };
138
- }
139
-
140
- function loadAgents(dir: string): AgentFile[] {
141
- if (!existsSync(dir)) return [];
142
- const agents: AgentFile[] = [];
143
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
144
- if (!entry.name.endsWith(".md") || (!entry.isFile() && !entry.isSymbolicLink())) continue;
145
- try {
146
- const { frontmatter, body } = parseFrontmatter<Record<string, unknown>>(
147
- readFileSync(join(dir, entry.name), "utf8"),
148
- );
149
- if (typeof frontmatter.name !== "string" || typeof frontmatter.description !== "string") continue;
150
- agents.push({
151
- name: frontmatter.name,
152
- description: frontmatter.description,
153
- tools: stringList(frontmatter.tools),
154
- model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
155
- thinking: typeof frontmatter.thinking === "string" ? frontmatter.thinking : undefined,
156
- prompt: body.trim(),
157
- });
158
- } catch {
159
- // One malformed agent file should not disable delegation.
160
- }
161
- }
162
- return agents;
163
- }
164
-
165
- function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
166
- const dirs = [BUNDLED_AGENT_DIR, DEFAULT_AGENT_DIR, ...stringList(configuredDirs)].map((dir) =>
167
- expandPath(dir, cwd),
168
- );
169
- const agents = new Map<string, AgentFile>();
170
- for (const dir of [...new Set(dirs)]) {
171
- for (const agent of loadAgents(dir)) agents.set(agent.name, agent);
172
- }
173
- return [...agents.values()];
174
- }
175
-
176
- function resolveModel(
177
- value: string | undefined,
178
- models: Record<string, unknown>,
179
- current: ExtensionContext["model"],
180
- ): string | undefined {
181
- if (value && !MODEL_TIERS.has(value)) return value;
182
- const configured = value ? models[value] : undefined;
183
- if (typeof configured === "string" && configured) return configured;
184
- return current ? `${current.provider}/${current.id}` : undefined;
185
- }
186
-
187
- function contextWindowFor(ctx: ExtensionContext, model: string | undefined): number | undefined {
188
- const separator = model?.indexOf("/") ?? -1;
189
- if (!model || separator < 0) return undefined;
190
- return ctx.modelRegistry.find(model.slice(0, separator), model.slice(separator + 1))?.contextWindow;
191
- }
53
+ const DELEGATE_SESSION_DIR = join(getAgentDir(), "sessions", "delegates");
54
+ const RESUME_PROMPT = "Continue the task above from where you left off.";
55
+ const INTERRUPTED_MESSAGE = "delegate-interrupted";
192
56
 
193
57
  function argText(value: unknown): string {
194
58
  return typeof value === "string" ? value : "";
@@ -246,37 +110,12 @@ function toolLayout(toolName: string, identity: string, payload: string, theme:
246
110
  }
247
111
 
248
112
  export default function (pi: ExtensionAPI) {
249
- const running = new Map<string, DelegateJob>();
250
- const recent: InspectJob[] = [];
251
- let viewing: (() => void) | undefined;
113
+ const store = createJobStore(pi.appendEntry);
252
114
  let ticker: ReturnType<typeof setInterval> | undefined;
253
115
  // Prompts are read once; drift happens one quick search at a time, so count it and nudge at 5, 10, 20, ...
254
116
  let directCalls = 0;
255
117
  let nextReminder = FIRST_REMINDER_AT;
256
118
 
257
- const addActivity = (job: DelegateJob, activity: ChildActivity) => {
258
- const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
259
- job.activity.push(
260
- activity.kind === "assistant" || activity.kind === "user"
261
- ? activity
262
- : {
263
- ...activity,
264
- text: normalize(activity.text),
265
- detail: activity.detail && normalize(activity.detail),
266
- },
267
- );
268
- viewing?.();
269
- };
270
-
271
- const remember = (job: DelegateJob, status: JobStatus, detail?: string) => {
272
- job.status = status;
273
- if (detail) addActivity(job, { kind: "status", text: detail });
274
- const { controller, steer, lastTool, lastDetail, lastResult, ...snapshot } = job;
275
- const entry: InspectJob = { ...snapshot, endedAt: Date.now() };
276
- recent.unshift(entry);
277
- pi.appendEntry(JOB_ENTRY, entry);
278
- };
279
-
280
119
  const jobSnapshot = (job: DelegateJob) => ({
281
120
  id: job.id,
282
121
  agent: job.agent,
@@ -288,22 +127,23 @@ export default function (pi: ExtensionAPI) {
288
127
 
289
128
  const jobTarget = (rawId: unknown, theme: Theme): string => {
290
129
  const id = jobId(rawId);
291
- const job = running.get(id) ?? recent.find((item) => item.id === id);
130
+ const job = store.find(id);
292
131
  return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
293
132
  };
294
133
 
295
134
  const refreshWidget = (ctx: ExtensionContext) => {
296
135
  if (!ctx.hasUI) return;
297
- viewing?.();
298
- if (running.size === 0) {
136
+ store.notify();
137
+ const jobs = store.live();
138
+ if (jobs.length === 0) {
299
139
  ctx.ui.setWidget(WIDGET_KEY, undefined);
300
140
  return;
301
141
  }
302
142
  const theme = ctx.ui.theme;
303
143
  const now = Date.now();
304
- const { shown, hidden, detail } = widgetJobs([...running.values()]);
144
+ const { shown, hidden, detail } = widgetJobs(jobs);
305
145
  const lines: string[] = [];
306
- const counts = `${running.size} running · ${running.size + recent.length} total`;
146
+ const counts = `${jobs.length} running · ${store.all().length} total`;
307
147
  lines.push(`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`);
308
148
  for (const job of shown) {
309
149
  lines.push(
@@ -320,17 +160,18 @@ export default function (pi: ExtensionAPI) {
320
160
  ctx.ui.setWidget(WIDGET_KEY, lines);
321
161
  };
322
162
 
323
- const stopTicker = () => {
324
- if (ticker) clearInterval(ticker);
325
- ticker = undefined;
163
+ // The ticker animates spinners exactly while live jobs exist.
164
+ const syncTicker = (ctx: ExtensionContext) => {
165
+ if (store.live().length > 0) ticker ??= setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
166
+ else if (ticker) {
167
+ clearInterval(ticker);
168
+ ticker = undefined;
169
+ }
326
170
  };
327
171
 
328
172
  const finishJob = (ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) => {
329
- // Cancellation was already acknowledged; shutdown has no UI to report into.
330
- if (job.controller.signal.aborted) return;
331
- running.delete(job.id);
332
- remember(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined);
333
- if (running.size === 0) stopTicker();
173
+ if (!store.finish(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined)) return;
174
+ syncTicker(ctx);
334
175
  refreshWidget(ctx);
335
176
  const report: DelegateReport = {
336
177
  id: job.id,
@@ -353,23 +194,28 @@ export default function (pi: ExtensionAPI) {
353
194
  };
354
195
 
355
196
  pi.on("session_shutdown", () => {
356
- stopTicker();
357
- for (const job of running.values()) job.controller.abort();
358
- running.clear();
359
- recent.length = 0;
360
- viewing = undefined;
197
+ if (ticker) clearInterval(ticker);
198
+ for (const job of store.live()) job.controller.abort();
199
+ store.clear();
361
200
  });
362
201
 
363
202
  // Rebuilt from the active branch, like pi's todo example; abandoned branches are alternative histories.
364
- const restoreJobs = (ctx: ExtensionContext) => {
365
- recent.length = 0;
366
- for (const entry of ctx.sessionManager.getBranch()) {
367
- if (entry.type !== "custom" || entry.customType !== JOB_ENTRY || !entry.data) continue;
368
- recent.unshift(entry.data as InspectJob);
369
- }
203
+ const restoreSession = (ctx: ExtensionContext) => {
204
+ const interrupted = store.restore(ctx.sessionManager.getBranch());
205
+ // Custom entries never reach the model, so announce the interrupted jobs as a steered message.
206
+ if (interrupted.length)
207
+ pi.sendMessage(
208
+ {
209
+ customType: INTERRUPTED_MESSAGE,
210
+ 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>`,
211
+ display: false,
212
+ },
213
+ { deliverAs: "steer" },
214
+ );
370
215
  };
371
- pi.on("session_start", (_event, ctx) => restoreJobs(ctx));
372
- pi.on("session_tree", (_event, ctx) => restoreJobs(ctx));
216
+
217
+ pi.on("session_start", (_event, ctx) => restoreSession(ctx));
218
+ pi.on("session_tree", (_event, ctx) => restoreSession(ctx));
373
219
 
374
220
  pi.on("before_agent_start", () => {
375
221
  directCalls = 0;
@@ -419,225 +265,7 @@ export default function (pi: ExtensionAPI) {
419
265
  return container;
420
266
  });
421
267
 
422
- pi.registerCommand("delegate", {
423
- description: "Inspect live and recent delegate activity",
424
- handler: async (_args, ctx) => {
425
- if (ctx.mode !== "tui") return;
426
- if (!running.size && !recent.length) {
427
- ctx.ui.notify("No delegates in this session yet.", "info");
428
- return;
429
- }
430
- const screen = {
431
- overlay: true,
432
- overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
433
- } as const;
434
- try {
435
- await ctx.ui.custom((tui, theme, keys, done) => {
436
- let selectedId = running.keys().next().value ?? recent[0]!.id;
437
- let focus: "list" | "history" = "list";
438
- let top: number | undefined;
439
- let historyWidth = 1;
440
- let markdown = new WeakMap<ChildActivity, Markdown>();
441
- const jobs = () => [...running.values(), ...recent];
442
- // Fixed rows: title, top rule, bottom rule, footer.
443
- const bodyHeight = () => Math.max(0, tui.terminal.rows - 4);
444
- const toolsLines = (job: InspectJob, width: number) =>
445
- wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
446
- theme.fg("dim", line),
447
- );
448
- // Fixed rows: header, model, description, rule, counter.
449
- const historyHeight = (job: InspectJob, width: number) =>
450
- Math.max(0, bodyHeight() - 5 - toolsLines(job, width).length);
451
- // ScrollView needs fullscreen layout; window the history in regular TUI too.
452
- const renderJobs = (width: number, items: InspectJob[], selectedIndex: number): string[] => {
453
- const row = (text: string) =>
454
- truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│");
455
- const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 3));
456
- const start = Math.max(
457
- 0,
458
- Math.min(selectedIndex - Math.floor(visible / 2), items.length - visible),
459
- );
460
- const lines = items
461
- .slice(start, start + visible)
462
- .flatMap((item, index) => [
463
- row(
464
- `${theme.fg(start + index === selectedIndex && focus === "list" ? "accent" : "text", start + index === selectedIndex ? "›" : " ")} ${statusText(theme, item.status)} ${jobIdentity(theme, item)}`,
465
- ),
466
- row(theme.fg("muted", ` ${item.description}`)),
467
- row(
468
- theme.fg(
469
- "muted",
470
- ` ${usageStats(item, (item.endedAt ?? Date.now()) - item.startedAt)}`,
471
- ),
472
- ),
473
- ]);
474
- return [
475
- ...lines,
476
- ...Array(Math.max(0, bodyHeight() - 1 - lines.length)).fill(row("")),
477
- row(theme.fg("dim", `${selectedIndex + 1}/${items.length}`)),
478
- ].slice(0, bodyHeight());
479
- };
480
- const renderEntry = (entry: ChildActivity, width: number): string[] => {
481
- if (entry.kind === "assistant" || entry.kind === "user") {
482
- let md = markdown.get(entry);
483
- if (!md) {
484
- md = new Markdown(entry.text, 0, 0, getMarkdownTheme());
485
- markdown.set(entry, md);
486
- }
487
- return [theme.fg("accent", entry.kind), ...md.render(width), ""];
488
- }
489
- if (entry.kind === "tool")
490
- return [
491
- truncateToWidth(
492
- theme.fg("toolTitle", entry.text) +
493
- (entry.detail ? ` ${theme.fg("accent", entry.detail)}` : ""),
494
- width,
495
- ),
496
- ];
497
- if (entry.kind === "result") return [truncateToWidth(theme.fg("text", entry.text), width)];
498
- // Only failure detail still says anything; the header icon carries the status.
499
- if (!entry.text) return [];
500
- return [truncateToWidth(theme.fg(STATUS_COLORS.failed, entry.text), width)];
501
- };
502
- const renderHistory = (width: number, job: InspectJob): string[] => {
503
- historyWidth = width;
504
- const tools = toolsLines(job, width);
505
- const height = historyHeight(job, width);
506
- const history = job.activity.flatMap((entry) => renderEntry(entry, width));
507
- const maxTop = Math.max(0, history.length - height);
508
- const start = Math.min(top ?? maxTop, maxTop);
509
- const visible = history.slice(start, start + height);
510
- const shown = visible.length
511
- ? visible
512
- : height
513
- ? [theme.fg("muted", "Waiting for activity…")]
514
- : [];
515
- return [
516
- truncateToWidth(`${statusText(theme, job.status)} ${jobIdentity(theme, job)}`, width),
517
- truncateToWidth(theme.fg("dim", job.model), width),
518
- ...tools,
519
- truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
520
- theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
521
- ...shown,
522
- ...Array(Math.max(0, height - shown.length)).fill(""),
523
- truncateToWidth(
524
- theme.fg(
525
- "dim",
526
- `${visible.length ? `${start + 1}–${start + visible.length}` : "0"}/${history.length}`,
527
- ),
528
- width,
529
- ),
530
- ].slice(0, bodyHeight());
531
- };
532
- viewing = () => tui.requestRender();
533
- return {
534
- render(width: number) {
535
- const items = jobs();
536
- const selectedIndex = Math.max(
537
- 0,
538
- items.findIndex((item) => item.id === selectedId),
539
- );
540
- const selected = items[selectedIndex];
541
- const title = truncateToWidth(
542
- `${theme.fg(focus === "list" ? "accent" : "muted", focus === "list" ? "[Jobs]" : "Jobs")} ` +
543
- `${theme.fg(focus === "history" ? "accent" : "muted", focus === "history" ? "[Activity]" : "Activity")}` +
544
- theme.fg("dim", ` · ${running.size} running · ${items.length} total`),
545
- width,
546
- );
547
- const footer = truncateToWidth(
548
- theme.fg(
549
- "dim",
550
- `${keyHint("tui.select.up", "previous")} · ${keyHint("tui.select.down", "next")} · ${rawKeyHint("←/→", "switch pane")} · ${keyHint("tui.select.cancel", "close")}`,
551
- ),
552
- width,
553
- );
554
- if (!selected)
555
- return [
556
- title,
557
- theme.fg("muted", "No delegates in this session."),
558
- // Fixed rows: title, top rule, bottom rule, footer.
559
- ...Array(Math.max(0, tui.terminal.rows - 4)).fill(""),
560
- footer,
561
- ].slice(0, tui.terminal.rows);
562
- const sidebarWidth = Math.min(
563
- 40,
564
- Math.max(16, Math.floor(width * 0.35)),
565
- Math.max(1, width - 2),
566
- );
567
- const body = new HStack(
568
- [
569
- {
570
- component: {
571
- render: (w) => renderJobs(w, items, selectedIndex),
572
- invalidate() {},
573
- },
574
- basis: sidebarWidth,
575
- shrink: 0,
576
- },
577
- {
578
- component: { render: (w) => renderHistory(w, selected), invalidate() {} },
579
- basis: 0,
580
- grow: 1,
581
- },
582
- ],
583
- { gap: 1 },
584
- ).render(width);
585
- return [
586
- title,
587
- theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
588
- ...body,
589
- theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
590
- footer,
591
- ].slice(0, tui.terminal.rows);
592
- },
593
- invalidate() {
594
- markdown = new WeakMap();
595
- },
596
- handleInput(data: string) {
597
- if (keys.matches(data, "tui.select.cancel")) done(undefined);
598
- else if (matchesKey(data, "tab")) focus = focus === "list" ? "history" : "list";
599
- else if (matchesKey(data, "left")) focus = "list";
600
- else if (
601
- matchesKey(data, "right") ||
602
- (focus === "list" && keys.matches(data, "tui.select.confirm"))
603
- )
604
- focus = "history";
605
- else if (keys.matches(data, "tui.select.up") || keys.matches(data, "tui.select.down")) {
606
- const up = keys.matches(data, "tui.select.up");
607
- const items = jobs();
608
- if (focus === "list") {
609
- const index = Math.max(
610
- 0,
611
- items.findIndex((item) => item.id === selectedId),
612
- );
613
- selectedId =
614
- items[Math.max(0, Math.min(items.length - 1, index + (up ? -1 : 1)))]?.id ??
615
- selectedId;
616
- top = undefined;
617
- } else {
618
- const selected = items.find((item) => item.id === selectedId) ?? items[0];
619
- const length =
620
- selected?.activity.reduce(
621
- (sum, entry) => sum + renderEntry(entry, historyWidth).length,
622
- 0,
623
- ) ?? 0;
624
- const maxTop = Math.max(
625
- 0,
626
- length - (selected ? historyHeight(selected, historyWidth) : 0),
627
- );
628
- const position = Math.max(0, Math.min(maxTop, top ?? maxTop) + (up ? -1 : 1));
629
- top = position >= maxTop ? undefined : position;
630
- }
631
- }
632
- tui.requestRender();
633
- },
634
- };
635
- }, screen);
636
- } finally {
637
- viewing = undefined;
638
- }
639
- },
640
- });
268
+ registerInspector(pi, store);
641
269
 
642
270
  const cwd = process.cwd();
643
271
  const agentList = discoverAgents(cwd, configFor(cwd).agentDirs).map(
@@ -654,6 +282,8 @@ export default function (pi: ExtensionAPI) {
654
282
  ...agentList,
655
283
  "",
656
284
  "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).",
285
+ "",
286
+ "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.",
657
287
  ].join("\n"),
658
288
  promptSnippet:
659
289
  "Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
@@ -666,34 +296,58 @@ export default function (pi: ExtensionAPI) {
666
296
  "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.",
667
297
  ],
668
298
  parameters: Type.Object({
669
- agent: Type.String({ description: "Agent name from the list in this tool's description." }),
670
- description: Type.String({
671
- description: "Short 3-8 word summary of this delegation, shown in the transcript.",
672
- }),
673
- task: Type.String({ description: "Self-contained brief; the delegate cannot see this conversation." }),
299
+ agent: Type.Optional(Type.String({ description: "Agent name from the list in this tool's description." })),
300
+ description: Type.Optional(
301
+ Type.String({ description: "Short 3-8 word summary of this delegation, shown in the transcript." }),
302
+ ),
303
+ task: Type.Optional(
304
+ Type.String({ description: "Self-contained brief; the delegate cannot see this conversation." }),
305
+ ),
674
306
  model: Type.Optional(
675
307
  Type.String({ description: "Model tier (cheap, balanced, strong) or an explicit provider/model." }),
676
308
  ),
309
+ resume: Type.Optional(
310
+ Type.String({
311
+ description:
312
+ "Job id of an interrupted, failed, or cancelled delegate to continue; it reuses the original agent, description and task (model may be overridden).",
313
+ }),
314
+ ),
677
315
  }),
678
316
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
679
317
  const config = configFor(ctx.cwd);
680
318
  const agents = discoverAgents(ctx.cwd, config.agentDirs);
681
- const agent = agents.find((candidate) => candidate.name === params.agent);
319
+ const resuming = params.resume
320
+ ? resumeDecision(jobId(params.resume), store.all(), new Set(store.live().map((job) => job.id)))
321
+ : undefined;
322
+ if (resuming?.error) throw new Error(resuming.error);
323
+ const prior = resuming?.job;
324
+ if (!prior && (!params.agent || !params.description || !params.task))
325
+ throw new Error(
326
+ "agent, description and task are required unless resuming an interrupted, failed, or cancelled job.",
327
+ );
328
+ const agent = agents.find((candidate) => candidate.name === (prior?.agent ?? params.agent));
682
329
  if (!agent) {
683
330
  const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
684
- throw new Error(`Unknown agent "${params.agent}". Available agents: ${names}.`);
331
+ throw new Error(`Unknown agent "${prior?.agent ?? params.agent}". Available agents: ${names}.`);
685
332
  }
686
- const model = resolveModel(params.model ?? agent.model, config.models ?? {}, ctx.model);
687
- if (!model) throw new Error(`No model found for "${params.agent}".`);
333
+ const { model, thinking: tierThinking } = resolveModel(
334
+ params.model ?? agent.model,
335
+ config.models ?? {},
336
+ ctx.model,
337
+ );
338
+ if (!model) throw new Error(`No model found for "${agent.name}".`);
688
339
  const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
689
340
  (tool) => !DELEGATION_TOOLS.has(tool),
690
341
  );
342
+ const thinking = agent.thinking ?? tierThinking ?? ctx.thinkingLevel;
343
+ const displayModel = thinking ? `${model}:${thinking}` : model;
691
344
  const job: DelegateJob = {
692
- id: randomUUID().slice(0, 8),
345
+ // A resumed job keeps its id: the pinned child session id reopens the old transcript.
346
+ id: prior?.id ?? randomUUID().slice(0, 8),
693
347
  agent: agent.name,
694
- description: params.description.trim(),
695
- task: params.task,
696
- model,
348
+ description: (prior?.description ?? params.description ?? "").trim(),
349
+ task: prior?.task ?? params.task ?? "",
350
+ model: displayModel,
697
351
  status: "running",
698
352
  activity: [],
699
353
  tools,
@@ -707,42 +361,56 @@ export default function (pi: ExtensionAPI) {
707
361
  agent: job.agent,
708
362
  description: job.description,
709
363
  task: job.task,
710
- model,
364
+ model: displayModel,
711
365
  tools,
712
- // Only a UI can deliver a result that arrives after the tool returned; headless runs must block.
713
366
  background: ctx.hasUI,
714
367
  };
715
- const args = ["--model", model, "--tools", tools.join(",")];
716
- const thinking = agent.thinking ?? ctx.thinkingLevel;
368
+ const args = [
369
+ "--session-id",
370
+ `delegate-${job.id}`,
371
+ "--session-dir",
372
+ DELEGATE_SESSION_DIR,
373
+ "--model",
374
+ model,
375
+ "--tools",
376
+ tools.join(","),
377
+ ];
717
378
  if (thinking) args.push("--thinking", thinking);
718
379
  if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
719
380
  const entrypoint = process.argv[1];
720
381
  if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
721
- const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", "--no-session", ...args], {
382
+ const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
722
383
  cwd: ctx.cwd,
723
384
  shell: false,
724
385
  stdio: "pipe",
725
386
  });
726
- const run = runChild(child, params.task, details.background ? job.controller.signal : signal, (update) => {
727
- if (job.status !== "running") return;
728
- const { activity, ...progress } = update;
729
- for (const [key, value] of Object.entries(progress)) {
730
- if (value !== undefined) (job as Record<string, unknown>)[key] = value;
731
- }
732
- if (activity && details.background) addActivity(job, activity);
733
- });
387
+ store.launch(job, details.background);
388
+ const run = runChild(
389
+ child,
390
+ prior ? RESUME_PROMPT : job.task,
391
+ details.background ? job.controller.signal : signal,
392
+ (update) => store.record(job, update),
393
+ Boolean(prior),
394
+ );
734
395
  job.steer = run.steer;
735
396
 
736
397
  if (!details.background) {
737
- const output = await run.done;
738
- return { content: [{ type: "text", text: output }], details };
398
+ try {
399
+ const output = await run.done;
400
+ store.finish(job, "done");
401
+ return { content: [{ type: "text", text: output }], details };
402
+ } catch (error) {
403
+ // Record the outcome so the launch entry cannot linger as "running".
404
+ const cancelled = error instanceof Error && error.message === "Delegate was aborted";
405
+ store.finish(job, cancelled ? "cancelled" : "failed");
406
+ // Failed jobs are resumable; mirror the failed background report's hint on the thrown error.
407
+ if (!cancelled && error instanceof Error) error.message += `\n${resumeHint(job.id)}`;
408
+ throw error;
409
+ }
739
410
  }
740
411
 
741
- running.set(job.id, job);
742
- if (!ticker) ticker = setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
412
+ syncTicker(ctx);
743
413
  refreshWidget(ctx);
744
- // The only failure left here is reporting into a session that is being torn down,
745
- // and an unhandled rejection would crash pi.
746
414
  void run.done
747
415
  .then(
748
416
  (output) => finishJob(ctx, job, output),
@@ -822,7 +490,7 @@ export default function (pi: ExtensionAPI) {
822
490
  }),
823
491
  async execute(_toolCallId, params) {
824
492
  const id = jobId(params.id);
825
- const job = running.get(id);
493
+ const job = store.live().find((candidate) => candidate.id === id);
826
494
  if (!job?.steer) throw new Error(`No running delegate job "${id}".`);
827
495
  await job.steer(params.message);
828
496
  const details: SteerDetails = {
@@ -869,19 +537,18 @@ export default function (pi: ExtensionAPI) {
869
537
  name: "delegate_cancel",
870
538
  label: "Cancel delegate",
871
539
  description:
872
- "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.",
540
+ "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.",
873
541
  promptSnippet: "Cancel a running background delegate by job id",
874
542
  parameters: Type.Object({
875
543
  id: Type.String({ description: "Job id from delegate or delegate_list." }),
876
544
  }),
877
545
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
878
546
  const id = jobId(params.id);
879
- const job = running.get(id);
547
+ const job = store.live().find((candidate) => candidate.id === id);
880
548
  if (!job) throw new Error(`No running delegate job "${id}".`);
881
- running.delete(id);
882
- remember(job, "cancelled");
549
+ store.finish(job, "cancelled");
883
550
  job.controller.abort();
884
- if (running.size === 0) stopTicker();
551
+ syncTicker(ctx);
885
552
  refreshWidget(ctx);
886
553
  return {
887
554
  content: [
@@ -916,7 +583,7 @@ export default function (pi: ExtensionAPI) {
916
583
  parameters: Type.Object({}),
917
584
  async execute() {
918
585
  const now = Date.now();
919
- const jobs = [...running.values()];
586
+ const jobs = store.live();
920
587
  if (!jobs.length)
921
588
  return { content: [{ type: "text", text: "No delegates are running." }], details: undefined };
922
589
  const lastActivity = (job: DelegateJob) =>