@herbertgao/pi-extensions 2026.11.1 → 2026.11.3

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 (76) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +14 -14
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +1 -1
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +1 -1
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +109 -16
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/write-execution.ts +5 -1
  9. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  10. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +12 -0
  11. package/node_modules/@herbertgao/pi-subagents/README.md +54 -42
  12. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +1 -1
  13. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +2 -0
  14. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  15. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +9 -8
  16. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +70 -9
  17. package/node_modules/@herbertgao/pi-subagents/src/agent-record-entry.ts +183 -0
  18. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +156 -13
  19. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +52 -8
  20. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +3 -4
  21. package/node_modules/@herbertgao/pi-subagents/src/index.ts +158 -56
  22. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +3 -2
  23. package/node_modules/@herbertgao/pi-subagents/src/status-note.ts +3 -1
  24. package/node_modules/@herbertgao/pi-subagents/src/types.ts +5 -0
  25. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +167 -7
  26. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +8 -4
  27. package/node_modules/@herbertgao/pi-subagents/src/workflow/host.ts +88 -6
  28. package/node_modules/@herbertgao/pi-subagents/src/workflow/progress.ts +3 -2
  29. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +259 -0
  30. package/node_modules/@narumitw/pi-btw/package.json +6 -5
  31. package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +70 -0
  32. package/node_modules/@narumitw/pi-caffeinate/package.json +5 -4
  33. package/node_modules/pi-commandcode-provider/CHANGELOG.md +21 -0
  34. package/node_modules/pi-commandcode-provider/README.md +18 -6
  35. package/node_modules/pi-commandcode-provider/index.ts +11 -5
  36. package/node_modules/pi-commandcode-provider/package.json +1 -1
  37. package/node_modules/pi-commandcode-provider/src/api-key.ts +26 -10
  38. package/node_modules/pi-commandcode-provider/src/auth-server.ts +33 -24
  39. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +2 -2
  40. package/node_modules/pi-commandcode-provider/src/converters.ts +3 -61
  41. package/node_modules/pi-commandcode-provider/src/core.ts +29 -4
  42. package/node_modules/pi-commandcode-provider/src/cost.ts +32 -12
  43. package/node_modules/pi-commandcode-provider/src/oauth.ts +40 -6
  44. package/node_modules/pi-commandcode-provider/src/pricing.ts +5 -3
  45. package/node_modules/pi-commandcode-provider/src/runtime.ts +14 -7
  46. package/node_modules/pi-commandcode-provider/src/transport.ts +6 -3
  47. package/node_modules/pi-provider-qoder/README.md +40 -0
  48. package/node_modules/pi-provider-qoder/dist/index.js +64 -0
  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/node_modules/pi-web-access/CHANGELOG.md +22 -0
  61. package/node_modules/pi-web-access/README.md +31 -12
  62. package/node_modules/pi-web-access/curator-page.ts +5 -1
  63. package/node_modules/pi-web-access/curator-server.ts +2 -0
  64. package/node_modules/pi-web-access/dist/index.js +673 -308
  65. package/node_modules/pi-web-access/dist/mcp-cli.js +666 -309
  66. package/node_modules/pi-web-access/gemini-search.ts +12 -4
  67. package/node_modules/pi-web-access/github-api.ts +1 -1
  68. package/node_modules/pi-web-access/github-extract.ts +3 -2
  69. package/node_modules/pi-web-access/index.ts +7 -3
  70. package/node_modules/pi-web-access/mcp-tool-definitions.ts +1 -1
  71. package/node_modules/pi-web-access/outcrawl.ts +204 -0
  72. package/node_modules/pi-web-access/package.json +2 -2
  73. package/node_modules/pi-web-access/sofya.ts +201 -0
  74. package/node_modules/pi-web-access/utils.ts +16 -6
  75. package/node_modules/pi-web-access/web-tool-core.ts +4 -0
  76. package/package.json +11 -11
@@ -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,28 @@ 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. After
3818
+ // a reload there is no tombstone, so the saved entry's handle and alias
3819
+ // have to match on their own.
3820
+ const tombstone = manager.resolveMention(params.agent_id)
3821
+ const savedId =
3822
+ tombstone?.kind === "tombstone"
3823
+ ? tombstone.entry.id
3824
+ : params.agent_id
3825
+ const saved = findAgentRecordEntry(
3826
+ ctx,
3827
+ savedId,
3828
+ tombstone === undefined,
3829
+ )
3830
+ if (saved) {
3831
+ outbox.cancel(saved.id)
3832
+ return textResult(formatSavedAgentRecord(saved))
3833
+ }
3834
+ }
3733
3835
  if (!record || !isTopLevelAgent(record)) {
3734
3836
  return textResult(
3735
3837
  `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
  /**
@@ -8,6 +8,7 @@
8
8
  import {
9
9
  type AgentSession,
10
10
  getMarkdownTheme,
11
+ ToolExecutionComponent,
11
12
  } from "@earendil-works/pi-coding-agent"
12
13
  import {
13
14
  type Component,
@@ -53,6 +54,49 @@ import {
53
54
  type ViewerKeys,
54
55
  } from "./viewer-keys.js"
55
56
 
57
+ /** An assistant message's tool call, and the message that answers it. */
58
+ type AgentMessage = AgentSession["messages"][number]
59
+ type ToolCallPart = Extract<
60
+ Extract<AgentMessage, { role: "assistant" }>["content"][number],
61
+ { type: "toolCall" }
62
+ >
63
+ type ToolResultPart = Extract<AgentMessage, { role: "toolResult" }>
64
+
65
+ /** A rendered tool call, reused across renders so its component's caches survive. */
66
+ interface ToolBlock {
67
+ component: ToolExecutionComponent
68
+ /** The result already handed to the component, if any. */
69
+ result?: ToolResultPart
70
+ /**
71
+ * The block's rendered rows and the width they were produced at.
72
+ *
73
+ * `ToolExecutionComponent` re-wraps and re-paints its whole subtree on every
74
+ * `render()`, which costs ~0.4 ms per settled call — enough that a 500-message
75
+ * transcript re-wrapped every block on every keystroke. The rows only change
76
+ * when the inputs above do, so they are kept and reused until one does.
77
+ */
78
+ rows?: string[]
79
+ width?: number
80
+ }
81
+
82
+ /**
83
+ * Whether pi's global theme is initialized.
84
+ *
85
+ * `ToolExecutionComponent` draws with pi's theme rather than the instance this
86
+ * viewer is handed, and pi throws on the first color lookup when nothing called
87
+ * `initTheme()`. This viewer is constructed outside pi too — its own unit tests,
88
+ * an embedded session — so the tool path is gated on a probe, the same way
89
+ * `resolveMarkdownTheme` already treats pi's Markdown theme.
90
+ */
91
+ function piThemeAvailable(): boolean {
92
+ try {
93
+ getMarkdownTheme().heading("probe")
94
+ return true
95
+ } catch {
96
+ return false
97
+ }
98
+ }
99
+
56
100
  /** Base lines consumed by chrome: top border + header + header sep + footer sep + footer + bottom border. */
57
101
  const CHROME_LINES_BASE = 6
58
102
  const MIN_VIEWPORT = 3
@@ -238,6 +282,15 @@ export class ConversationViewer implements Component, Focusable {
238
282
  object,
239
283
  { md: Markdown; text: string; failed?: boolean }
240
284
  >()
285
+ /** One block per tool call id, so a redraw reuses the component's own caches. */
286
+ private readonly toolBlocks = new Map<string, ToolBlock>()
287
+ /**
288
+ * Whether calls render through pi's components. Probe-gated: without pi's
289
+ * theme the viewer keeps its own plain rendering rather than throwing.
290
+ */
291
+ private readonly toolRendering = piThemeAvailable()
292
+ /** Whether tool blocks show their full output; toggled with pi's expand key. */
293
+ private toolsExpanded = false
241
294
 
242
295
  constructor(
243
296
  private tui: TUI,
@@ -383,6 +436,18 @@ export class ConversationViewer implements Component, Focusable {
383
436
  }
384
437
  if (this.stopArmed) this.stopArmed = false
385
438
 
439
+ // Unfold tool output — the same key, and the same meaning, as in the main
440
+ // transcript. It is what the renderers' own elision notices refer to.
441
+ if (this.keys.expand(data)) {
442
+ this.toolsExpanded = !this.toolsExpanded
443
+ for (const block of this.toolBlocks.values()) {
444
+ block.component.setExpanded(this.toolsExpanded)
445
+ block.rows = undefined
446
+ }
447
+ this.tui.requestRender()
448
+ return
449
+ }
450
+
386
451
  const totalLines = this.buildContentLines(this.lastInnerW).length
387
452
  const viewportHeight = this.viewportHeight()
388
453
  if (this.fullscreen) {
@@ -946,6 +1011,14 @@ export class ConversationViewer implements Component, Focusable {
946
1011
  return lines
947
1012
  }
948
1013
 
1014
+ // A result is folded into the block of the call it answers, so every call
1015
+ // has to find its result before the loop reaches it.
1016
+ const results = new Map<string, ToolResultPart>()
1017
+ for (const msg of messages) {
1018
+ if (msg.role === "toolResult") results.set(msg.toolCallId, msg)
1019
+ }
1020
+ const foldedCalls = new Set<string>()
1021
+
949
1022
  const mode = this.markdownMode()
950
1023
  let needsSeparator = false
951
1024
  for (const msg of messages) {
@@ -962,12 +1035,10 @@ export class ConversationViewer implements Component, Focusable {
962
1035
  }
963
1036
  } else if (msg.role === "assistant") {
964
1037
  const textParts: string[] = []
965
- const toolCalls: string[] = []
1038
+ const toolCalls: ToolCallPart[] = []
966
1039
  for (const c of msg.content) {
967
1040
  if (c.type === "text" && c.text) textParts.push(c.text)
968
- else if (c.type === "toolCall") {
969
- toolCalls.push((c as any).name ?? (c as any).toolName ?? "unknown")
970
- }
1041
+ else if (c.type === "toolCall") toolCalls.push(c)
971
1042
  }
972
1043
  if (needsSeparator) lines.push(th.fg("dim", "───"))
973
1044
  lines.push(th.bold("[Assistant]"))
@@ -979,12 +1050,31 @@ export class ConversationViewer implements Component, Focusable {
979
1050
  : this.markdownLines(msg, text, width, false)),
980
1051
  )
981
1052
  }
982
- for (const name of toolCalls) {
1053
+ for (const call of toolCalls) {
1054
+ if (!this.toolRendering) {
1055
+ lines.push(
1056
+ truncateToWidth(th.fg("muted", ` [Tool: ${call.name}]`), width),
1057
+ )
1058
+ continue
1059
+ }
1060
+ foldedCalls.add(call.id)
1061
+ // An aborted or failed response never runs its calls, so no result
1062
+ // will arrive: say so, as pi's session replay does.
1063
+ const notRun =
1064
+ msg.stopReason === "aborted"
1065
+ ? "Operation aborted"
1066
+ : msg.stopReason === "error"
1067
+ ? msg.errorMessage || "Error"
1068
+ : undefined
983
1069
  lines.push(
984
- truncateToWidth(th.fg("muted", ` [Tool: ${name}]`), width),
1070
+ ...this.toolBlockLines(call, results.get(call.id), notRun, width),
985
1071
  )
986
1072
  }
987
1073
  } else if (msg.role === "toolResult") {
1074
+ // Rendered under its call above. A result whose call is not in the
1075
+ // transcript — a compacted prefix, a reopened session — keeps the plain
1076
+ // block, because there is no call row to fold it into.
1077
+ if (foldedCalls.has(msg.toolCallId)) continue
988
1078
  const { text, elided } = capResult(extractText(msg.content).trim())
989
1079
  if (!text) continue
990
1080
  if (needsSeparator) lines.push(th.fg("dim", "───"))
@@ -1032,6 +1122,76 @@ export class ConversationViewer implements Component, Focusable {
1032
1122
  )
1033
1123
  }
1034
1124
 
1035
- return lines.map((l) => truncateToWidth(l, width))
1125
+ // Only clamp what actually overflows: `truncateToWidth` takes a slow,
1126
+ // character-by-character path for any line carrying an escape sequence, and
1127
+ // a tool block's rows are already rendered at this width by its component.
1128
+ return lines.map((l) =>
1129
+ visibleWidth(l) > width ? truncateToWidth(l, width) : l,
1130
+ )
1131
+ }
1132
+
1133
+ /**
1134
+ * One tool call as pi draws it in the main transcript: the arguments on the
1135
+ * call, then the result in that tool's own format — a bash box, read line
1136
+ * numbers, an edit diff. Blocks are cached per call id because
1137
+ * `ToolExecutionComponent` rebuilds its renderer tree on every update.
1138
+ *
1139
+ * A tool without a renderer still renders: the component falls back to a
1140
+ * generic `name key=value` header plus a bounded preview that the expand key
1141
+ * unfolds.
1142
+ */
1143
+ private toolBlockLines(
1144
+ call: ToolCallPart,
1145
+ result: ToolResultPart | undefined,
1146
+ notRun: string | undefined,
1147
+ width: number,
1148
+ ): string[] {
1149
+ let block = this.toolBlocks.get(call.id)
1150
+ let changed = false
1151
+ if (!block) {
1152
+ // Built the way pi replays a saved session: `session.messages` only holds
1153
+ // finished messages, so the arguments are final. No setArgsComplete() or
1154
+ // markExecutionStarted() — both request a render, and this runs inside
1155
+ // one; the former also makes the edit renderer re-read the file.
1156
+ const component = new ToolExecutionComponent(
1157
+ call.name,
1158
+ call.id,
1159
+ call.arguments,
1160
+ // Text only: an image needs rows this line-based renderer cannot reserve.
1161
+ { showImages: false },
1162
+ // pi's resolution for the agent's own session: builtin and extension
1163
+ // renderers, and extension overrides. `{}` for a tool no registry knows,
1164
+ // so it gets the bounded, expandable fallback rather than a raw dump.
1165
+ this.session.extensionRunner.resolveToolRenderers(call.name, () =>
1166
+ this.session.getToolDefinition(call.name),
1167
+ ) ?? {},
1168
+ this.tui,
1169
+ this.session.sessionManager.getCwd(),
1170
+ )
1171
+ component.setExpanded(this.toolsExpanded)
1172
+ // The message is final, so this is decided once, when the block is built.
1173
+ if (notRun && !result)
1174
+ component.updateResult({
1175
+ content: [{ type: "text", text: notRun }],
1176
+ isError: true,
1177
+ })
1178
+ block = { component }
1179
+ this.toolBlocks.set(call.id, block)
1180
+ changed = true
1181
+ }
1182
+ if (result && block.result !== result) {
1183
+ block.result = result
1184
+ block.component.updateResult({
1185
+ content: result.content,
1186
+ details: result.details,
1187
+ isError: result.isError,
1188
+ durationMs: result.durationMs,
1189
+ })
1190
+ changed = true
1191
+ }
1192
+ if (!changed && block.rows && block.width === width) return block.rows
1193
+ block.rows = block.component.render(width)
1194
+ block.width = width
1195
+ return block.rows
1036
1196
  }
1037
1197
  }