@herbertgao/pi-extensions 2026.11.0 → 2026.11.2

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +768 -0
  2. package/README.md +7 -7
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/extensions/clef.mjs +1 -1
  5. package/node_modules/@herbertgao/pi-agency/CHANGELOG.md +19 -0
  6. package/node_modules/@herbertgao/pi-agency/package.json +4 -2
  7. package/node_modules/@herbertgao/pi-agency/src/index.ts +1 -1
  8. package/node_modules/@herbertgao/pi-bark/CHANGELOG.md +52 -0
  9. package/node_modules/@herbertgao/pi-bark/package.json +2 -1
  10. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +207 -0
  11. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +7 -5
  12. package/node_modules/@herbertgao/pi-cc-extensions/README.md +10 -7
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +20 -0
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +61 -6
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/agent-summary/core.ts +11 -16
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/agent-summary/index.ts +60 -11
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/compact-thinking.ts +29 -11
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer-layout.ts +54 -6
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +23 -5
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/session-tokens.ts +52 -0
  21. package/node_modules/@herbertgao/pi-cc-extensions/package.json +5 -4
  22. package/node_modules/@herbertgao/pi-impeccable/CHANGELOG.md +13 -0
  23. package/node_modules/@herbertgao/pi-impeccable/package.json +2 -1
  24. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  25. package/node_modules/@herbertgao/pi-subagents/README.md +43 -33
  26. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +1 -1
  27. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +2 -0
  28. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  29. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +9 -8
  30. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +70 -9
  31. package/node_modules/@herbertgao/pi-subagents/src/agent-record-entry.ts +167 -0
  32. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +156 -13
  33. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +52 -8
  34. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +3 -4
  35. package/node_modules/@herbertgao/pi-subagents/src/index.ts +153 -56
  36. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +3 -2
  37. package/node_modules/@herbertgao/pi-subagents/src/status-note.ts +3 -1
  38. package/node_modules/@herbertgao/pi-subagents/src/types.ts +5 -0
  39. package/node_modules/@herbertgao/pi-subagents/src/workflow/host.ts +88 -6
  40. package/node_modules/@herbertgao/pi-subagents/src/workflow/progress.ts +3 -2
  41. package/node_modules/@herbertgao/sol-pi/CHANGELOG.md +84 -0
  42. package/node_modules/@herbertgao/sol-pi/README.md +3 -3
  43. package/node_modules/@herbertgao/sol-pi/THIRD_PARTY_NOTICES.md +4 -4
  44. package/node_modules/@herbertgao/sol-pi/agents-install.md +3 -3
  45. package/node_modules/@herbertgao/sol-pi/docs/compatibility.md +1 -1
  46. package/node_modules/@herbertgao/sol-pi/package.json +2 -1
  47. package/node_modules/pi-provider-qoder/README.md +40 -0
  48. package/node_modules/pi-provider-qoder/dist/index.js +69 -1
  49. package/node_modules/pi-provider-qoder/package.json +4 -3
  50. package/node_modules/pi-typesafe/README.md +3 -3
  51. package/node_modules/pi-typesafe/dist/auth.d.ts +21 -4
  52. package/node_modules/pi-typesafe/dist/auth.js +32 -7
  53. package/node_modules/pi-typesafe/dist/backends.d.ts +2 -2
  54. package/node_modules/pi-typesafe/dist/backends.js +9 -0
  55. package/node_modules/pi-typesafe/dist/client.js +7 -12
  56. package/node_modules/pi-typesafe/dist/errors.d.ts +3 -2
  57. package/node_modules/pi-typesafe/dist/errors.js +12 -10
  58. package/node_modules/pi-typesafe/dist/extension.js +14 -10
  59. package/node_modules/pi-typesafe/package.json +1 -1
  60. package/package.json +10 -9
@@ -195,7 +195,9 @@ function loadOneFile(
195
195
  // filename-derived one down with it.
196
196
  const name = declared || filenameType
197
197
 
198
- const { builtinToolNames, extSelectors } = parseToolsField(fm.tools)
198
+ const { builtinToolNames, extSelectors, mcpToolPatterns } = parseToolsField(
199
+ fm.tools,
200
+ )
199
201
 
200
202
  agents.set(name, {
201
203
  name,
@@ -207,7 +209,13 @@ function loadOneFile(
207
209
  description: str(fm.description) ?? name,
208
210
  builtinToolNames,
209
211
  extSelectors,
210
- disallowedTools: csvListOptional(fm.disallowed_tools),
212
+ mcpToolPatterns,
213
+ // `disallowedTools` is Claude Code's spelling of the key. Each entry denies the tool
214
+ // with exactly that name, as in Claude Code, and the pi built-in it maps to, so an
215
+ // extension tool named `glob` stays denied rather than becoming `find`.
216
+ disallowedTools: csvListOptional(
217
+ fm.disallowed_tools ?? fm.disallowedTools,
218
+ )?.flatMap((n) => [...new Set([n, normalizeToolName(n)])]),
211
219
  extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
212
220
  excludeExtensions: csvListOptional(fm.exclude_extensions),
213
221
  skills: inheritField(fm.skills ?? fm.inherit_skills),
@@ -388,27 +396,63 @@ function csvList(val: unknown, defaults: string[]): string[] {
388
396
  return parseCsvField(val) ?? []
389
397
  }
390
398
 
399
+ /** Claude Code tool names whose pi built-in is named differently. Keys are lowercase. */
400
+ const CLAUDE_CODE_TOOL_ALIASES: Record<string, string> = {
401
+ glob: "find",
402
+ multiedit: "edit",
403
+ }
404
+
391
405
  /**
392
- * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
393
- * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
394
- * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
395
- * selectors parsed later by the runner. omitted → all built-ins, no selectors.
396
- * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
406
+ * A tool name as pi spells it. Built-ins match case-insensitively, so Claude Code's
407
+ * `Read` and `LS` work, and a Claude Code name with a differently named pi built-in
408
+ * maps to it. Anything else comes back unchanged, so runAgent still warns about it.
409
+ */
410
+ function normalizeToolName(name: string): string {
411
+ const lower = name.toLowerCase()
412
+ return (
413
+ BUILTIN_TOOL_NAMES.find((b) => b === lower) ??
414
+ CLAUDE_CODE_TOOL_ALIASES[lower] ??
415
+ name
416
+ )
417
+ }
418
+
419
+ /**
420
+ * Partition the `tools:` CSV into the built-in tool allowlist, raw `ext:` selectors
421
+ * and bare `mcp__` entries. `*` (and the case-insensitive alias `all`, for
422
+ * `tools: all`) expands to all built-ins; plain entries are built-in names, in pi's
423
+ * or Claude Code's spelling; `ext:` entries are extension-tool selectors parsed
424
+ * later by the runner; `mcp__<server>__<tool>` entries (exact or `*` patterns)
425
+ * narrow MCP tools, as pi's `--tools` does. omitted → all built-ins, no selectors.
426
+ * `tools:` present with only `ext:` or `mcp__` entries → zero built-ins (use `*`).
397
427
  */
398
428
  function parseToolsField(val: unknown): {
399
429
  builtinToolNames: string[]
400
430
  extSelectors: string[] | undefined
431
+ mcpToolPatterns: string[] | undefined
401
432
  } {
402
433
  const entries = csvList(val, BUILTIN_TOOL_NAMES)
403
434
  const isWildcard = (e: string) => e === "*" || e.toLowerCase() === "all"
435
+ const isMcp = (e: string) => e.startsWith("mcp__")
404
436
  const hasWildcard = entries.some(isWildcard)
405
- const plain = entries.filter((e) => !isWildcard(e) && !e.startsWith("ext:"))
437
+ const plain = [
438
+ ...new Set(
439
+ entries
440
+ .filter((e) => !isWildcard(e) && !e.startsWith("ext:") && !isMcp(e))
441
+ .map(normalizeToolName),
442
+ ),
443
+ ]
406
444
  const extEntries = entries.filter((e) => e.startsWith("ext:"))
445
+ // A server-level `mcp__<server>` means every tool of that server, as in Claude Code.
446
+ const mcpEntries = entries.filter(isMcp).map((e) => {
447
+ const server = e.slice("mcp__".length)
448
+ return server && !server.includes("__") ? `${e}__*` : e
449
+ })
407
450
  return {
408
451
  builtinToolNames: hasWildcard
409
452
  ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])]
410
453
  : plain,
411
454
  extSelectors: extEntries.length > 0 ? extEntries : undefined,
455
+ mcpToolPatterns: mcpEntries.length > 0 ? mcpEntries : undefined,
412
456
  }
413
457
  }
414
458
 
@@ -36,10 +36,9 @@ export const DEFAULT_AGENTS: Map<string, AgentConfig> = new Map([
36
36
  builtinToolNames: READ_ONLY_TOOLS,
37
37
  extensions: true,
38
38
  skills: true,
39
- // Fast/cheap model for read-only search. Provider-preferred but resilient:
40
- // resolveModel matches this fuzzily (date-stamp optional) and falls back to
41
- // the same model under another provider if anthropic doesn't expose it.
42
- model: "anthropic/claude-haiku-4-5",
39
+ // No model: Explore inherits the session's, as in Claude Code. A pin here
40
+ // outranked the caller and resolved through any provider with a key
41
+ // (#175, #350); a same-named agent file can still pin one.
43
42
  systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
44
43
  You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
45
44
  Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
@@ -19,6 +19,7 @@ import {
19
19
  } from "node:fs"
20
20
  import { isAbsolute, join } from "node:path"
21
21
  import {
22
+ type AgentSession,
22
23
  defineTool,
23
24
  type ExtensionAPI,
24
25
  type ExtensionCommandContext,
@@ -51,6 +52,13 @@ import {
51
52
  serializeAgentFile,
52
53
  } from "./agent-file-toggle.js"
53
54
  import { AgentManager, isTopLevelAgent } from "./agent-manager.js"
55
+ import {
56
+ AGENT_RECORD_ENTRY_TYPE,
57
+ type AgentRecordEntryData,
58
+ agentRecordEntryData,
59
+ findAgentRecordEntry,
60
+ reopenTarget,
61
+ } from "./agent-record-entry.js"
54
62
  import {
55
63
  getAgentConversation,
56
64
  getDefaultMaxTurns,
@@ -899,17 +907,12 @@ export default function (pi: ExtensionAPI) {
899
907
  pi.events.emit("subagents:completed", eventData)
900
908
  }
901
909
 
902
- // Persist final record for cross-extension history reconstruction
903
- pi.appendEntry("subagents:record", {
904
- id: record.id,
905
- type: record.type,
906
- description: record.description,
907
- status: record.status,
908
- result: record.result,
909
- error: record.error,
910
- startedAt: record.startedAt,
911
- completedAt: record.completedAt,
912
- })
910
+ // Persist the final record: get_subagent_result answers from it once the
911
+ // live record is gone, and other extensions reconstruct history from it.
912
+ pi.appendEntry<AgentRecordEntryData>(
913
+ AGENT_RECORD_ENTRY_TYPE,
914
+ agentRecordEntryData(record),
915
+ )
913
916
 
914
917
  // Skip notification if result was already consumed via get_subagent_result
915
918
  if (record.resultConsumed) {
@@ -1127,6 +1130,16 @@ export default function (pi: ExtensionAPI) {
1127
1130
  return resolved?.kind === "live" ? resolved.record : undefined
1128
1131
  }
1129
1132
 
1133
+ /** get_subagent_result's answer from a persisted record, once the live record is gone. */
1134
+ const formatSavedAgentRecord = (saved: AgentRecordEntryData): string =>
1135
+ `Agent: ${saved.id}\n` +
1136
+ `Type: ${getDisplayName(saved.type)} | Status: ${saved.status}${getStatusNote(saved.status)} | Duration: ${formatDuration(saved.startedAt, saved.completedAt)}\n` +
1137
+ `Description: ${saved.description}\n` +
1138
+ `(From the session's saved record: the live record has been cleaned up, so its stats and conversation are gone.)\n\n` +
1139
+ (saved.status === "error"
1140
+ ? `Error: ${saved.error}${partialOutputSuffix(saved)}`
1141
+ : saved.result?.trim() || "No output.")
1142
+
1130
1143
  const registryEntry = {
1131
1144
  waitForAll: () => manager.waitForAll(),
1132
1145
  hasRunning: () => manager.hasRunning(),
@@ -1264,6 +1277,24 @@ export default function (pi: ExtensionAPI) {
1264
1277
  runWorkflowFlag(ctx)
1265
1278
  })
1266
1279
 
1280
+ // Start a mentioned agent the direct way. runAgent resolves model, thinking,
1281
+ // max turns and `isolated` from the agent's own config when the spawn omits
1282
+ // them, but not `inherit_context`: an RPC caller decides that one itself. A
1283
+ // mention is the user starting the agent from this session, so the file does —
1284
+ // reloaded first, as the spawn reloads it, so a mid-session edit is not missed.
1285
+ const startMentioned = (
1286
+ ctx: ExtensionContext,
1287
+ type: string,
1288
+ message: string,
1289
+ ) => {
1290
+ reloadCustomAgents()
1291
+ return spawnTopLevel(pi, ctx, type, message, {
1292
+ description: describeMention(message),
1293
+ isBackground: true,
1294
+ inheritContext: getAgentConfig(type)?.inheritContext,
1295
+ })
1296
+ }
1297
+
1267
1298
  /** Agent types `@` can start, in the shape the roster wants. */
1268
1299
  const mentionTypes = (): TypeInfo[] =>
1269
1300
  getAvailableTypes().map((name) => ({
@@ -1384,34 +1415,19 @@ export default function (pi: ExtensionAPI) {
1384
1415
  const entry = resolved.entry
1385
1416
  const target = `@${entry.alias ?? entry.handle}`
1386
1417
 
1387
- // Checked here rather than left to SessionManager.open: that runs inside
1388
- // runAgent, whose rejection lands on the record as an agent error, not in
1389
- // the catch below. A `/new` in another pi window or a manual delete makes
1390
- // the conversation unrecoverable (Claude Code's `not_reachable`), so drop
1391
- // the entry — a row that can only ever fail is worse than none — and say
1392
- // so rather than quietly sending this message to an unrelated agent.
1393
- if (!existsSync(entry.sessionFile)) {
1394
- manager.dropTombstone(entry.handle)
1395
- ctx.ui.notify(
1396
- `Could not resume ${target} — its session is gone.`,
1397
- "warning",
1398
- )
1399
- return { action: "handled" }
1400
- }
1401
-
1402
- // The Agent tool deliberately falls back to general-purpose for a type it
1403
- // cannot resolve (#183), which covers a deleted file AND a merely
1404
- // disabled one. A resume must not inherit that: reopening this
1405
- // conversation under a different agent's prompt and tools is not
1406
- // continuing it, and the new record would re-tombstone under the
1407
- // substitute, so the handle would never find its way back.
1408
1418
  reloadCustomAgents()
1409
- const dispatch = resolveSpawnType(entry.type)
1410
- if (!dispatch.ok || dispatch.fellBackFrom !== undefined) {
1411
- // The tombstone stays: re-enabling the agent makes the handle work
1412
- // again, which a drop would foreclose.
1419
+ const reopen = reopenTarget(
1420
+ entry.type,
1421
+ entry.sessionFile,
1422
+ entry.worktreeLost,
1423
+ )
1424
+ if (!reopen.ok) {
1425
+ // A session that is gone can only ever fail, so its row goes with it;
1426
+ // an unavailable agent stays, since re-enabling it makes the handle
1427
+ // work again.
1428
+ if (reopen.gone) manager.dropTombstone(entry.handle)
1413
1429
  ctx.ui.notify(
1414
- `Could not resume ${target} — the ${entry.type} agent is no longer available.`,
1430
+ `Could not resume ${target} — ${reopen.reason}.`,
1415
1431
  "warning",
1416
1432
  )
1417
1433
  return { action: "handled" }
@@ -1421,7 +1437,7 @@ export default function (pi: ExtensionAPI) {
1421
1437
  // spawnResolved, not spawnTopLevel: the latter strips
1422
1438
  // `resumeSessionFile` and `reclaim` as untrusted. This path is the
1423
1439
  // exception — both come from a tombstone this extension wrote.
1424
- const id = spawnResolved(pi, ctx, dispatch.type, mention.message, {
1440
+ const id = spawnResolved(pi, ctx, reopen.type, mention.message, {
1425
1441
  description: entry.description,
1426
1442
  reclaim: { handle: entry.handle, alias: entry.alias },
1427
1443
  resumeSessionFile: entry.sessionFile,
@@ -1490,10 +1506,7 @@ export default function (pi: ExtensionAPI) {
1490
1506
  // agent the direct way rather than leaving the user with a toast and
1491
1507
  // nothing running.
1492
1508
  try {
1493
- const id = spawnTopLevel(pi, ctx, type, mention.message, {
1494
- description: describeMention(mention.message),
1495
- isBackground: true,
1496
- })
1509
+ const id = startMentioned(ctx, type, mention.message)
1497
1510
  // Same reason as the direct path below: the agent may still be
1498
1511
  // starting, and a failure there must reach this catch.
1499
1512
  await manager.awaitStartup(id)
@@ -1512,15 +1525,10 @@ export default function (pi: ExtensionAPI) {
1512
1525
  }
1513
1526
 
1514
1527
  try {
1515
- // Nothing else to pass: runAgent resolves model, thinking, max turns and
1516
- // `isolated` from the agent's own config when the spawn omits them, and the
1517
- // manager's onStart/onComplete callbacks own the widget, the fleet list
1528
+ // The manager's onStart/onComplete callbacks own the widget, the fleet list
1518
1529
  // and the completion notification — the same contract the scheduler and
1519
1530
  // cross-extension RPC spawns run under.
1520
- const id = spawnTopLevel(pi, ctx, type, mention.message, {
1521
- description: describeMention(mention.message),
1522
- isBackground: true,
1523
- })
1531
+ const id = startMentioned(ctx, type, mention.message)
1524
1532
  // The agent may still be starting (a worktree copy is an awaited git
1525
1533
  // call) — report a failure that lands there as a failed start, not as a
1526
1534
  // "Started" toast for an agent that never ran.
@@ -2262,7 +2270,9 @@ Terse command-style prompts produce shallow, generic work.
2262
2270
  promptSnippet: "Launch autonomous sub-agents for complex multi-step tasks",
2263
2271
  promptGuidelines: [
2264
2272
  "Use Agent with specialized agents when the task matches an agent type's description. Subagents are valuable for parallelizing independent queries or for protecting the main context window from excessive results, but should not be used excessively when not needed. Importantly, avoid duplicating work that subagents are already doing — if you delegate research to a subagent, do not also perform the same searches yourself.",
2265
- "For broad codebase exploration or research, spawn Agent with an appropriate subagent_type (e.g. Explore). Otherwise use direct tools (read, grep, find) when the target is already known.",
2273
+ // Names Explore only when it can be spawned, as Claude Code does (#330).
2274
+ // Read at registration, like the type list in the description.
2275
+ `For broad codebase exploration or research, spawn Agent with an appropriate subagent_type${getAvailableTypes().includes("Explore") ? " (e.g. Explore)" : ""}. Otherwise use direct tools (read, grep, find) when the target is already known.`,
2266
2276
  "When an agent runs in the background, you will be notified on completion — do not poll or sleep waiting for it. Continue with other work instead.",
2267
2277
  "Trust but verify: an agent's summary describes intent, not outcome. When an agent writes or edits code, check the actual changes before reporting work as done.",
2268
2278
  ],
@@ -2505,13 +2515,64 @@ Terse command-style prompts produce shallow, generic work.
2505
2515
 
2506
2516
  // ---- Execute ----
2507
2517
 
2508
- execute: async (toolCallId, params, signal, onUpdate, ctx) => {
2518
+ execute: async (toolCallId, callParams, signal, onUpdate, ctx) => {
2509
2519
  // Ensure we have UI context for widget rendering
2510
2520
  widget.setUICtx(ctx.ui as UICtx)
2511
2521
 
2512
2522
  // Reload custom agents so new project/global .md files are picked up without restart
2513
2523
  reloadCustomAgents()
2514
2524
 
2525
+ // A resume whose record is gone — evicted ten minutes after it finished,
2526
+ // or lost to a reload or restart — reopens the agent from the session's
2527
+ // saved record of it, under the same id, as Claude Code resumes from the
2528
+ // transcript on disk. This is an ordinary spawn carrying a session file,
2529
+ // like the `@handle` path's, so it runs through the spawn branches below
2530
+ // and picks up the widget, fleet row, transcript, join batching and
2531
+ // completion notification unchanged. Only the prompt, the turn budget and
2532
+ // run_in_background carry over from the call: like a live resume, it
2533
+ // ignores `subagent_type`, model and the rest, and runs under the agent
2534
+ // type's current definition.
2535
+ // `schedule` is left to its own branch, which refuses the combination.
2536
+ const saved =
2537
+ callParams.resume !== undefined &&
2538
+ !callParams.schedule &&
2539
+ manager.getRecord(callParams.resume) === undefined
2540
+ ? findAgentRecordEntry(ctx, callParams.resume)
2541
+ : undefined
2542
+ let reopenOptions:
2543
+ | {
2544
+ resumeSessionFile: string
2545
+ reclaim: { id: string; handle?: string; alias?: string }
2546
+ }
2547
+ | undefined
2548
+ if (saved !== undefined) {
2549
+ const reopen = reopenTarget(
2550
+ saved.type,
2551
+ saved.sessionFile,
2552
+ saved.worktreeLost,
2553
+ )
2554
+ if (!reopen.ok)
2555
+ return textResult(
2556
+ `Agent "${saved.id}" cannot be resumed — ${reopen.reason}.`,
2557
+ )
2558
+ reopenOptions = {
2559
+ resumeSessionFile: reopen.sessionFile,
2560
+ reclaim: { id: saved.id, handle: saved.handle, alias: saved.alias },
2561
+ }
2562
+ }
2563
+ const params: typeof callParams =
2564
+ saved === undefined
2565
+ ? callParams
2566
+ : {
2567
+ prompt: callParams.prompt,
2568
+ description: saved.description,
2569
+ subagent_type: saved.type,
2570
+ run_in_background: callParams.run_in_background,
2571
+ max_turns: callParams.max_turns,
2572
+ isolation: undefined,
2573
+ schedule: undefined,
2574
+ }
2575
+
2515
2576
  const rawType = params.subagent_type as SubagentType
2516
2577
  // Single decision point for dispatch (#183): unknown, disabled and
2517
2578
  // case-ambiguous types are refused here, BEFORE anything spawns, so a
@@ -2606,8 +2667,16 @@ Terse command-style prompts produce shallow, generic work.
2606
2667
  agentId,
2607
2668
  ctx.sessionManager.getSessionId(),
2608
2669
  )
2609
- writeInitialEntry(rec.outputFile, agentId, params.prompt, ctx.cwd)
2670
+ // A reopened agent keeps its id, so this is the transcript its earlier
2671
+ // runs wrote: append to it, as a live resume does, never truncate it.
2672
+ if (reopenOptions) ensureOutputFile(rec.outputFile)
2673
+ else writeInitialEntry(rec.outputFile, agentId, params.prompt, ctx.cwd)
2610
2674
  }
2675
+ // Where a reopened agent's transcript stream starts: past the turns the
2676
+ // reopened session already holds, so its new prompt is written once and
2677
+ // the old turns are not written again. A spawn starts from its prompt.
2678
+ const transcriptAnchor = (session: AgentSession): number | undefined =>
2679
+ reopenOptions ? session.messages.length : undefined
2611
2680
 
2612
2681
  // Unconditional, not "only when it differs from the parent": a thinking
2613
2682
  // level reads as a property of a model, and an agent that inherited the
@@ -2646,9 +2715,11 @@ Terse command-style prompts produce shallow, generic work.
2646
2715
  // Normalize so `0` (unlimited) doesn't surface as a misleading "max turns: 0".
2647
2716
  maxTurns: normalizeMaxTurns(resolvedConfig.maxTurns),
2648
2717
  isolated,
2649
- inheritContext,
2718
+ // Neither is applied to a reopened conversation (runAgent, the
2719
+ // manager), so neither is shown.
2720
+ inheritContext: reopenOptions ? undefined : inheritContext,
2650
2721
  runInBackground,
2651
- isolation,
2722
+ isolation: reopenOptions ? undefined : isolation,
2652
2723
  }
2653
2724
  // Tool-result render shows the mode label too; viewer's header already does.
2654
2725
  const modeLabel = getPromptModeLabel(subagentType)
@@ -2846,6 +2917,13 @@ Terse command-style prompts produce shallow, generic work.
2846
2917
  if (!record) {
2847
2918
  return textResult(`Failed to resume agent "${params.resume}".`)
2848
2919
  }
2920
+ // A foreground resume settles inline, never through the completion
2921
+ // callback, so persist its outcome here: get_subagent_result must find
2922
+ // this run's result, not the earlier run's, once the live record is gone.
2923
+ pi.appendEntry<AgentRecordEntryData>(
2924
+ AGENT_RECORD_ENTRY_TYPE,
2925
+ agentRecordEntryData(record),
2926
+ )
2849
2927
  // A failed resume surfaces the error, plus any partial output THIS
2850
2928
  // resume produced (never the previous turn's answer, #144).
2851
2929
  if (record.status === "error") {
@@ -2869,7 +2947,7 @@ Terse command-style prompts produce shallow, generic work.
2869
2947
  ) => {
2870
2948
  const isQueued = record?.status === "queued"
2871
2949
  return textResult(
2872
- `${fallbackNote}Agent ${isQueued ? "queued" : "started"} in background.\n` +
2950
+ `${fallbackNote}Agent ${isQueued ? "queued" : reopenOptions ? "resumed from its saved session" : "started"} in background.\n` +
2873
2951
  `Agent ID: ${id}\n` +
2874
2952
  `Type: ${displayName}\n` +
2875
2953
  `Description: ${params.description}\n` +
@@ -2910,6 +2988,7 @@ Terse command-style prompts produce shallow, generic work.
2910
2988
  rec.outputFile,
2911
2989
  id,
2912
2990
  ctx.cwd,
2991
+ transcriptAnchor(session),
2913
2992
  )
2914
2993
  }
2915
2994
  }
@@ -2929,6 +3008,7 @@ Terse command-style prompts produce shallow, generic work.
2929
3008
  isolation,
2930
3009
  invocation: agentInvocation,
2931
3010
  rootSessionId: ctx.sessionManager.getSessionId(),
3011
+ ...reopenOptions,
2932
3012
  ...bgCallbacks,
2933
3013
  })
2934
3014
 
@@ -3057,6 +3137,7 @@ Terse command-style prompts produce shallow, generic work.
3057
3137
  rec.outputFile,
3058
3138
  fgId,
3059
3139
  ctx.cwd,
3140
+ transcriptAnchor(session),
3060
3141
  )
3061
3142
  }
3062
3143
  }
@@ -3100,6 +3181,7 @@ Terse command-style prompts produce shallow, generic work.
3100
3181
  invocation: agentInvocation,
3101
3182
  signal,
3102
3183
  rootSessionId: ctx.sessionManager.getSessionId(),
3184
+ ...reopenOptions,
3103
3185
  // Deliberately does NOT set fgId: that drives agentActivity, the
3104
3186
  // widget and the `finally` cleanup below, none of which should see an
3105
3187
  // agent that has no session and may never get one.
@@ -3728,8 +3810,23 @@ Terse command-style prompts produce shallow, generic work.
3728
3810
  }),
3729
3811
  ),
3730
3812
  }),
3731
- execute: async (_toolCallId, params, signal, _onUpdate, _ctx) => {
3813
+ execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
3732
3814
  const record = resolveAgentRef(params.agent_id)
3815
+ if (!record) {
3816
+ // Evicted, or lost to a reload: answer from the record the session saved.
3817
+ // An evicted handle still resolves to its id through its tombstone.
3818
+ const tombstone = manager.resolveMention(params.agent_id)
3819
+ const saved = findAgentRecordEntry(
3820
+ ctx,
3821
+ tombstone?.kind === "tombstone"
3822
+ ? tombstone.entry.id
3823
+ : params.agent_id,
3824
+ )
3825
+ if (saved) {
3826
+ outbox.cancel(saved.id)
3827
+ return textResult(formatSavedAgentRecord(saved))
3828
+ }
3829
+ }
3733
3830
  if (!record || !isTopLevelAgent(record)) {
3734
3831
  return textResult(
3735
3832
  `Agent not found: "${params.agent_id}". It may have been cleaned up.`,
@@ -148,8 +148,9 @@ export interface SubagentsSettings {
148
148
  */
149
149
  agentMentions?: AgentMentionMode
150
150
  /**
151
- * Whether subagents persist their pi session by default, so `@handle` can
152
- * reopen an agent's conversation long after its in-memory record is gone.
151
+ * Whether subagents persist their pi session by default, so `@handle`,
152
+ * `Agent({ resume })` and a workflow's `resume` can reopen an agent's
153
+ * conversation long after its in-memory record is gone.
153
154
  * Defaults to `true`. Per-agent `persist_session:` frontmatter overrides it
154
155
  * in both directions. Turning it off restores the previous behaviour, where
155
156
  * a handle stops resolving roughly ten minutes after the agent finishes and
@@ -84,7 +84,9 @@ export function getForegroundOutcomeNote(status: string): string {
84
84
  * surfaces (or "" if the run produced nothing). `record.result` is bounded to
85
85
  * the run's own turns, so this is never a stale earlier answer (#144).
86
86
  */
87
- export function partialOutputSuffix(record: AgentRecord): string {
87
+ export function partialOutputSuffix(
88
+ record: Pick<AgentRecord, "result">,
89
+ ): string {
88
90
  const partial = record.result?.trim()
89
91
  return partial ? `\n\nPartial output before the failure:\n${partial}` : ""
90
92
  }
@@ -46,6 +46,9 @@ export interface AgentConfig {
46
46
  /** Raw `ext:` selector entries from the `tools:` CSV, e.g. ["ext:foo", "ext:bar/x"].
47
47
  * Presence of any entry flips extension tools to an explicit allowlist. */
48
48
  extSelectors?: string[]
49
+ /** Bare `mcp__` entries from the `tools:` CSV (exact names or `*` patterns), as in
50
+ * pi's `--tools`: MCP tools are narrowed to the matching ones. */
51
+ mcpToolPatterns?: string[]
49
52
  /** Tool denylist — these tools are removed even if `builtinToolNames` or extensions include them. */
50
53
  disallowedTools?: string[]
51
54
  /** true = inherit all, string[] = only listed, false = none */
@@ -151,6 +154,8 @@ export interface AgentTombstone {
151
154
  /** Always set — a record with no session file is never tombstoned. */
152
155
  sessionFile: string
153
156
  completedAt: number
157
+ /** The agent's work lived in a worktree that is now gone; reopening is refused. */
158
+ worktreeLost?: boolean
154
159
  }
155
160
 
156
161
  /**
@@ -38,6 +38,7 @@ import type {
38
38
  ExtensionContext,
39
39
  } from "@earendil-works/pi-coding-agent"
40
40
  import type { AgentManager } from "../agent-manager.js"
41
+ import { reopenTarget, worktreeLost } from "../agent-record-entry.js"
41
42
  import { getAgentConfig, resolveSpawnType } from "../agent-types.js"
42
43
  import { resolveModel } from "../model-resolver.js"
43
44
  import { checkModelScope } from "../model-scope.js"
@@ -177,6 +178,27 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
177
178
  const { pi, ctx, manager } = deps
178
179
  /** Runtime agent id → the manager record it spawned. Never pruned mid-run. */
179
180
  const records = new Map<string, string>()
181
+ /**
182
+ * Manager record id → what reopening that child needs once the manager has
183
+ * evicted it, ten minutes after it finished. A long review or a merge queue
184
+ * outlasts that easily, and `resume` must still reach the child (#385).
185
+ * Lives exactly as long as the run, like `records`, so memory stays bounded
186
+ * by the run itself; the manager keeps no tombstone for an owned child.
187
+ */
188
+ const settled = new Map<
189
+ string,
190
+ Pick<AgentRecord, "type" | "description" | "sessionFile"> & {
191
+ worktreeLost: boolean
192
+ }
193
+ >()
194
+ const remember = (record: AgentRecord): void => {
195
+ settled.set(record.id, {
196
+ type: record.type,
197
+ description: record.description,
198
+ sessionFile: record.sessionFile,
199
+ worktreeLost: worktreeLost(record),
200
+ })
201
+ }
180
202
  /**
181
203
  * scopeModels warnings already toasted, so a fan-out that pins one
182
204
  * out-of-scope agent file raises one notification rather than one per child.
@@ -214,6 +236,66 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
214
236
  return { ok: result.code === 0, output }
215
237
  }
216
238
 
239
+ /**
240
+ * Resume a child the manager has evicted: reopen its saved session under the
241
+ * same id, still owned by this run, as `Agent({ resume })` does for a
242
+ * top-level agent. The continuation runs under the agent type's current
243
+ * definition, like every reopen — the script's model, schema and isolation
244
+ * for the first run are not replayed.
245
+ */
246
+ async function reopenAgent(
247
+ id: string,
248
+ prompt: string,
249
+ onResolved: Parameters<NonNullable<WorkflowHost["resumeAgent"]>>[2],
250
+ ): Promise<WorkflowSpawnResult> {
251
+ const kept = settled.get(id)
252
+ if (kept === undefined)
253
+ return {
254
+ ok: false,
255
+ error: `Agent ${id} cannot be resumed — it never finished a run to resume from.`,
256
+ }
257
+ const reopen = reopenTarget(kept.type, kept.sessionFile, kept.worktreeLost)
258
+ if (!reopen.ok)
259
+ return {
260
+ ok: false,
261
+ error: `Agent ${id} cannot be resumed — ${reopen.reason}.`,
262
+ }
263
+ const config = getAgentConfig(reopen.type)
264
+ try {
265
+ const { record } = await manager.spawnAndWait(
266
+ pi,
267
+ ctx,
268
+ reopen.type,
269
+ prompt,
270
+ {
271
+ description: kept.description,
272
+ resumeSessionFile: reopen.sessionFile,
273
+ reclaim: { id },
274
+ ...(config?.isolated !== undefined
275
+ ? { isolated: config.isolated }
276
+ : {}),
277
+ ...(deps.workflowId !== undefined
278
+ ? { workflowId: deps.workflowId }
279
+ : {}),
280
+ ...(deps.signal !== undefined ? { signal: deps.signal } : {}),
281
+ ...(deps.rootSessionId !== undefined
282
+ ? { rootSessionId: deps.rootSessionId }
283
+ : {}),
284
+ },
285
+ () => onResolved?.({ recordId: id }),
286
+ )
287
+ remember(record)
288
+ const info = resolvedInfo(record)
289
+ if (info !== undefined) onResolved?.(info)
290
+ return toSpawnResult(record)
291
+ } catch (error) {
292
+ return {
293
+ ok: false,
294
+ error: error instanceof Error ? error.message : String(error),
295
+ }
296
+ }
297
+ }
298
+
217
299
  return {
218
300
  async spawnAgent(request) {
219
301
  const dispatch = resolveSpawnType(request.agentType)
@@ -402,6 +484,7 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
402
484
  reportResolved()
403
485
  },
404
486
  )
487
+ remember(record)
405
488
  return {
406
489
  ...toSpawnResult(record),
407
490
  ...(gate !== undefined ? { gate } : {}),
@@ -433,12 +516,11 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
433
516
  }
434
517
  }
435
518
  const record = await manager.resume(id, prompt, deps.signal)
436
- if (record === undefined) {
437
- return {
438
- ok: false,
439
- error: `Agent ${id} has no session left to resume — records are dropped ten minutes after they finish.`,
440
- }
441
- }
519
+ // No live session: the manager evicted the child, or it never got as far
520
+ // as having one. `reopenAgent` refuses the second with the reason — and a
521
+ // record still in memory without a session is refused by the manager,
522
+ // which never reopens an id that is still live.
523
+ if (record === undefined) return reopenAgent(id, prompt, onResolved)
442
524
  // The resumed row is built from scratch, so it has to be told the same
443
525
  // thing the first one was — the child's session already exists, so this is
444
526
  // simply read back rather than waited for. The id goes first for the same
@@ -379,8 +379,9 @@ export function stats(
379
379
  let started = 0
380
380
  let anyLive = false
381
381
 
382
- for (const entry of progress) {
383
- if (entry.type !== "workflow_agent") continue
382
+ // The log holds an entry per transition (queued, started, progress, settled);
383
+ // only each agent's latest one describes it.
384
+ for (const entry of collapse(progress).agents) {
384
385
  seen++
385
386
  if (entry.state === "done") {
386
387
  done++