@herbertgao/pi-extensions 2026.11.18 → 2026.11.20

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 (177) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -5
  3. package/THIRD_PARTY_NOTICES.md +3 -24
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  64. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
  65. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  66. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
  67. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  68. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  69. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  70. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  71. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  72. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  73. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
  74. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  75. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  76. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
  77. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  78. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
  80. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  82. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  84. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  85. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  86. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  87. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  88. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  89. package/node_modules/pi-commandcode-provider/README.md +3 -2
  90. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  91. package/node_modules/pi-commandcode-provider/package.json +4 -3
  92. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  93. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  94. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  95. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  96. package/node_modules/pi-typesafe/README.md +1 -1
  97. package/node_modules/pi-typesafe/dist/ask.js +6 -3
  98. package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
  99. package/node_modules/pi-typesafe/dist/auth.js +159 -55
  100. package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
  101. package/node_modules/pi-typesafe/dist/batch.js +62 -22
  102. package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
  103. package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
  104. package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
  105. package/node_modules/pi-typesafe/dist/client.js +67 -27
  106. package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
  107. package/node_modules/pi-typesafe/dist/errors.js +105 -2
  108. package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
  109. package/node_modules/pi-typesafe/dist/extension.js +206 -106
  110. package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
  111. package/node_modules/pi-typesafe/dist/index.js +3 -3
  112. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
  113. package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
  114. package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
  115. package/node_modules/pi-typesafe/dist/login.js +167 -13
  116. package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
  117. package/node_modules/pi-typesafe/dist/schema.js +47 -13
  118. package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
  119. package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
  120. package/node_modules/pi-typesafe/dist/usage.js +79 -40
  121. package/node_modules/pi-typesafe/package.json +3 -3
  122. package/package.json +12 -15
  123. package/node_modules/pi-antigravity/README.md +0 -298
  124. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  125. package/node_modules/pi-antigravity/package.json +0 -87
  126. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  127. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  128. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  129. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  130. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  131. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  132. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  133. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  134. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  135. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  136. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  137. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  138. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  139. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  140. package/node_modules/pi-antigravity/src/index.ts +0 -547
  141. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  142. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  143. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  144. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  145. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  146. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  147. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  148. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  149. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  150. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  151. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  152. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  153. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  154. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  155. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  156. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  157. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  158. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  159. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  160. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  161. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  162. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  163. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  164. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  165. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  166. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  167. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  168. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  169. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  170. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  171. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  172. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  173. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  174. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  175. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  176. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  177. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -71,6 +71,7 @@ import {
71
71
  setFallbackSubagent,
72
72
  setToolDescriptionMode,
73
73
  } from "./agent-types.js"
74
+ import { getCacheRetention, setCacheRetention } from "./cache-retention.js"
74
75
  import { inChildSessionContext } from "./child-context.js"
75
76
  import { CompletionOutbox, NOTIFICATION_HOLD_MS } from "./completion-outbox.js"
76
77
  import { type RpcHandle, registerRpcHandlers } from "./cross-extension-rpc.js"
@@ -143,10 +144,12 @@ import {
143
144
  getStatusNote,
144
145
  partialOutputSuffix,
145
146
  } from "./status-note.js"
147
+ import { toSubagentInfo } from "./subagent-info.js"
146
148
  import {
147
149
  type AgentInvocation,
148
150
  type AgentMentionMode,
149
151
  type AgentRecord,
152
+ type CacheRetentionSetting,
150
153
  type JoinMode,
151
154
  type NotificationDetails,
152
155
  type SubagentType,
@@ -245,6 +248,12 @@ import {
245
248
  workflowRunId,
246
249
  } from "./workflow/task.js"
247
250
  import { workflowToolDescription } from "./workflow/tool-description.js"
251
+ import {
252
+ toWorkflowDetail,
253
+ toWorkflowInfo,
254
+ workflowArgs,
255
+ workflowResult,
256
+ } from "./workflow-info.js"
248
257
  import {
249
258
  isWorktreeIsolationEnabled,
250
259
  setWorktreeIsolationEnabled,
@@ -617,31 +626,9 @@ export default function (pi: ExtensionAPI) {
617
626
  seedProjectTrust(process.cwd())
618
627
 
619
628
  /** Reload agents from package/global/project agent dirs and merge with defaults (called on init and each Agent invocation). */
620
- /** Current session context; undefined outside a session (also gates the
621
- * agents-changed emit above to active sessions). */
622
- let currentCtx: ExtensionContext | undefined
623
-
624
629
  const reloadCustomAgents = (strict = false) => {
625
- // The before/after comparison feeds subagents:agents-changed, so badge
626
- // holders re-pull exactly when the spawnable set actually changed. Gated
627
- // on an active session: the factory-time first load always "changes" the
628
- // set (defaults → defaults+files) and would fire a pull nobody can answer
629
- // yet; session_start's own reload runs after currentCtx is set and still
630
- // announces anything that changed since.
631
- // Signature covers name, displayName and color: a color-only edit to a
632
- // file-backed agent is a real change for badge holders, not just a rename.
633
- const signature = () =>
634
- getAvailableTypes()
635
- .map((type) => {
636
- const config = getConfig(type)
637
- return `${type}|${config.displayName}|${config.color ?? ""}`
638
- })
639
- .join(",")
640
- const before = signature()
641
630
  const userAgents = loadCustomAgents(process.cwd(), strict)
642
631
  registerAgents(userAgents)
643
- if (currentCtx !== undefined && signature() !== before)
644
- pi.events.emit("subagents:agents-changed", {})
645
632
  }
646
633
 
647
634
  // Initial load — the only strict one. A bad edit mid-session must not kill the
@@ -808,65 +795,26 @@ export default function (pi: ExtensionAPI) {
808
795
  widget.update()
809
796
  }, 30_000)
810
797
 
811
- /** Helper: build event data for lifecycle events from an AgentRecord. */
812
- function buildEventData(record: AgentRecord) {
813
- const durationMs = record.completedAt
814
- ? record.completedAt - record.startedAt
815
- : Date.now() - record.startedAt
816
- // All three fields are lifetime-accumulated (Σ over every assistant message_end),
817
- // so they survive compaction together — input + output ≤ total always.
818
- // tokens is omitted when nothing was ever produced (e.g. agent errored before
819
- // any message_end fired), preserving prior payload shape.
820
- const u = record.lifetimeUsage
821
- const total = getLifetimeTotal(u)
822
- const tokens =
823
- total > 0 ? { input: u.input, output: u.output, total } : undefined
824
- // The whole run's spend as a pi `Usage` — pi's convention for handing spend
825
- // to a consumer, so `usage.cost.total` and `usage.cacheRead` are where a
826
- // listener already expects them and anything pi adds to `Usage` arrives
827
- // without a change here. Omitted when nothing was spent, so "spent nothing"
828
- // and "never ran" stay distinguishable. Ungated by `showCost`: that setting
829
- // governs what a human is shown, not what the event carries.
830
- //
831
- // `tokens` above is the other convention, kept as it shipped: a flat view
832
- // model like pi's own `SessionStats`, carrying the DISPLAY total, which
833
- // excludes cacheRead (#38). The two answer different questions and neither
834
- // derives from the other.
835
- const usage = toReportedUsage(u)
836
- return {
837
- id: record.id,
838
- type: record.type,
839
- description: record.description,
840
- result: record.result,
841
- error: record.error,
842
- status: record.status,
843
- toolUses: record.toolUses,
844
- durationMs,
845
- tokens,
846
- usage,
847
- }
848
- }
849
-
850
798
  // Background completion: route through group join or send individual nudge
851
799
  const manager = new AgentManager(
852
800
  (record) => {
853
- // Owned children — nested, or a workflow's — report only through their
854
- // owner: the parent's scoped tools, or the workflow's card, notification
855
- // and dialog. Keep them out of top-level lifecycle, transcript,
856
- // notification, and UI channels.
857
- if (!isTopLevelAgent(record)) return
858
-
859
- // Emit lifecycle event based on terminal status
801
+ // The lifecycle events cover every agent, owned ones included: they carry
802
+ // `parentAgentId` / `workflowId`, so a listener that wants only the
803
+ // session's own agents filters on those (#442).
860
804
  const isError =
861
805
  record.status === "error" ||
862
806
  record.status === "stopped" ||
863
807
  record.status === "aborted"
864
- const eventData = buildEventData(record)
865
- if (isError) {
866
- pi.events.emit("subagents:failed", eventData)
867
- } else {
868
- pi.events.emit("subagents:completed", eventData)
869
- }
808
+ pi.events.emit(
809
+ isError ? "subagents:failed" : "subagents:completed",
810
+ toSubagentInfo(record),
811
+ )
812
+
813
+ // Everything below is for the session's own agents only. Owned children —
814
+ // nested, or a workflow's — report to the model through their owner: the
815
+ // parent's scoped tools, or the workflow's card, notification and dialog.
816
+ // Keep them out of the transcript, notification, and UI channels.
817
+ if (!isTopLevelAgent(record)) return
870
818
 
871
819
  // Persist the final record: get_subagent_result answers from it once the
872
820
  // live record is gone, and other extensions reconstruct history from it.
@@ -901,7 +849,17 @@ export default function (pi: ExtensionAPI) {
901
849
  },
902
850
  undefined,
903
851
  (record) => {
904
- if (!isTopLevelAgent(record)) return
852
+ if (!isTopLevelAgent(record)) {
853
+ // An owned agent never queues (it takes no pool slot) and has no
854
+ // `subagents:created` emit site of its own, so it is announced here, the
855
+ // moment it starts: a startup that fails first leaves no record and so
856
+ // announces nothing. A resume re-announces the id, as a detached
857
+ // top-level resume does.
858
+ const info = toSubagentInfo(record)
859
+ pi.events.emit("subagents:created", info)
860
+ pi.events.emit("subagents:started", info)
861
+ return
862
+ }
905
863
  // Agent-tool spawns refresh these surfaces in their tool handler, but RPC
906
864
  // and scheduler spawns enter through the manager directly.
907
865
  if (currentCtx?.hasUI) {
@@ -911,19 +869,12 @@ export default function (pi: ExtensionAPI) {
911
869
  fleet.update()
912
870
  }
913
871
  // Emit started event when agent transitions to running (including from queue)
914
- pi.events.emit("subagents:started", {
915
- id: record.id,
916
- type: record.type,
917
- description: record.description,
918
- })
872
+ pi.events.emit("subagents:started", toSubagentInfo(record))
919
873
  },
920
874
  (record, info) => {
921
- if (!isTopLevelAgent(record)) return
922
875
  // Emit compacted event when agent's session compacts (preserves count on record).
923
876
  pi.events.emit("subagents:compacted", {
924
- id: record.id,
925
- type: record.type,
926
- description: record.description,
877
+ ...toSubagentInfo(record),
927
878
  reason: info.reason,
928
879
  tokensBefore: info.tokensBefore,
929
880
  compactionCount: record.compactionCount,
@@ -938,10 +889,9 @@ export default function (pi: ExtensionAPI) {
938
889
  // The same message, live, for anyone keeping their own ledger — a footer
939
890
  // that breaks spend down by agent type and thinking level, say. This is the
940
891
  // one place every agent's spend passes through, which is why it is emitted
941
- // here and not from the lifecycle events: those fire for top-level agents
942
- // only, once, at the end, so a workflow's children and nested agents would
943
- // never be counted, and a running agent would read as free until it
944
- // stopped. Deliberately ungated by `reportUsage` — that decides whether the
892
+ // here and not from the lifecycle events: those carry spend once, at the
893
+ // end, so a running agent would read as free until it stopped.
894
+ // Deliberately ungated by `reportUsage` — that decides whether the
945
895
  // parent session's own totals include this spend, not whether it happened.
946
896
  //
947
897
  // `model` and `thinking` are read off the record per message, not captured
@@ -980,8 +930,10 @@ export default function (pi: ExtensionAPI) {
980
930
  })
981
931
  },
982
932
  (record, message) => {
983
- if (!isTopLevelAgent(record)) return
984
- pi.events.emit("subagents:steered", { id: record.id, message })
933
+ pi.events.emit("subagents:steered", {
934
+ ...toSubagentInfo(record),
935
+ message,
936
+ })
985
937
  },
986
938
  )
987
939
 
@@ -1125,6 +1077,7 @@ export default function (pi: ExtensionAPI) {
1125
1077
  }
1126
1078
 
1127
1079
  // --- Cross-extension RPC via pi.events ---
1080
+ let currentCtx: ExtensionContext | undefined
1128
1081
  // RPC handlers + the `subagents:ready` broadcast are wired on `session_start`
1129
1082
  // (a bound lifecycle event), not at factory time. pi runs every extension
1130
1083
  // factory before the `extensions:` filter and only fires lifecycle events for
@@ -1196,10 +1149,30 @@ export default function (pi: ExtensionAPI) {
1196
1149
  spawn: spawnTopLevel,
1197
1150
  awaitStartup: (id) => manager.awaitStartup(id),
1198
1151
  getRecord: (id) => manager.getRecord(id),
1152
+ listAgents: () => manager.listAgents(),
1153
+ isNotificationPending: (id) => {
1154
+ const record = manager.getRecord(id)
1155
+ // Owned agents are never notified, and a read result never will be.
1156
+ if (!record || !isTopLevelAgent(record) || record.resultConsumed)
1157
+ return false
1158
+ if (record.status === "running" || record.status === "queued")
1159
+ return false
1160
+ // The three places a settled agent's completion waits: the outbox,
1161
+ // a `group` holding it for its siblings, and a `group` spawn whose
1162
+ // turn has not ended yet (see the manager's onComplete).
1163
+ return (
1164
+ outbox.has(id) ||
1165
+ groupJoin.isHolding(id) ||
1166
+ turnGroupSpawns.includes(id)
1167
+ )
1168
+ },
1199
1169
  // Unguarded on purpose: the stop handler now runs the top-level check
1200
1170
  // itself off `getRecord`, and reports the refusal instead of the
1201
1171
  // "Agent not found" a false from here used to be read as.
1202
1172
  abort: (id) => manager.abort(id),
1173
+ waitForSettled: (id, timeoutMs) =>
1174
+ manager.waitForSettled(id, timeoutMs),
1175
+ isSettling: (id) => manager.isSettling(id),
1203
1176
  consumeResult: (id) => {
1204
1177
  const record = resolveAgentRef(id)
1205
1178
  // Same guard as get_subagent_result: a running agent has no result
@@ -1214,6 +1187,17 @@ export default function (pi: ExtensionAPI) {
1214
1187
  },
1215
1188
  steer: (id, message) => manager.steer(id, message),
1216
1189
  },
1190
+ // Read-only snapshots of workflow runs, for `workflow_get` / `workflow_list`.
1191
+ // A run is top-level, so there is no ownership to guard. `get` carries the
1192
+ // live per-agent detail; `list` is summaries only.
1193
+ workflows: {
1194
+ get: (id) => {
1195
+ const task = workflowTasks.get(id)
1196
+ return task ? toWorkflowDetail(task) : undefined
1197
+ },
1198
+ list: () =>
1199
+ [...workflowTasks.values()].map((task) => toWorkflowInfo(task)),
1200
+ },
1217
1201
  })
1218
1202
  // Broadcast readiness so extensions loaded alongside us can discover us.
1219
1203
  // Emitting after all factories have run (rather than at factory time)
@@ -1528,9 +1512,10 @@ export default function (pi: ExtensionAPI) {
1528
1512
  rpcHandle?.unsubPing()
1529
1513
  rpcHandle?.unsubConsume()
1530
1514
  rpcHandle?.unsubSteer()
1531
- rpcHandle?.unsubRegisterAgents()
1532
- rpcHandle?.unsubUnregisterAgents()
1533
- rpcHandle?.unsubListAgents()
1515
+ rpcHandle?.unsubGet()
1516
+ rpcHandle?.unsubList()
1517
+ rpcHandle?.unsubWorkflowGet()
1518
+ rpcHandle?.unsubWorkflowList()
1534
1519
  rpcHandle = undefined
1535
1520
  currentCtx = undefined
1536
1521
  // Only release the global slot if this activation claimed it — a child
@@ -1618,9 +1603,7 @@ export default function (pi: ExtensionAPI) {
1618
1603
  const record = manager.getRecord(id)
1619
1604
  if (record) {
1620
1605
  pi.events.emit("subagents:created", {
1621
- id,
1622
- type: record.type,
1623
- description: record.description,
1606
+ ...toSubagentInfo(record),
1624
1607
  isBackground: true,
1625
1608
  })
1626
1609
  }
@@ -1702,8 +1685,6 @@ export default function (pi: ExtensionAPI) {
1702
1685
  (mode) =>
1703
1686
  chooseViewerMarkdown(
1704
1687
  mode,
1705
- // SAFETY: FleetList keeps the live ExtensionContext; this cast only
1706
- // narrows its structural UI surface to the optional warning context.
1707
1688
  currentCtx as unknown as ExtensionCommandContext | undefined,
1708
1689
  ),
1709
1690
  getFullscreenScrollbar,
@@ -1972,9 +1953,7 @@ export default function (pi: ExtensionAPI) {
1972
1953
  // event carrying the caller's type would re-register the agent under
1973
1954
  // the wrong one in cross-extension mirrors keyed by id.
1974
1955
  pi.events.emit("subagents:created", {
1975
- id,
1976
- type: existing.type,
1977
- description: existing.description,
1956
+ ...toSubagentInfo(existing),
1978
1957
  isBackground: true,
1979
1958
  })
1980
1959
 
@@ -1984,8 +1963,6 @@ export default function (pi: ExtensionAPI) {
1984
1963
  // Grab UI context from first tool execution + clear lingering widget on new turn
1985
1964
  pi.on("tool_execution_start", async (_event, ctx) => {
1986
1965
  widget.setUICtx(ctx.ui as UICtx)
1987
- // SAFETY: Pi's UI context implements the FleetUICtx structural subset;
1988
- // this assertion exposes only the methods FleetList calls.
1989
1966
  fleet.setUICtx(ctx.ui as unknown as FleetUICtx)
1990
1967
  watchHandoffKey(ctx.ui)
1991
1968
  widget.onTurnStart()
@@ -2032,6 +2009,7 @@ export default function (pi: ExtensionAPI) {
2032
2009
  setFleetView: setFleetViewEnabled,
2033
2010
  setAgentMentions: setAgentMentionMode,
2034
2011
  setRememberAgents,
2012
+ setCacheRetention,
2035
2013
  setWidgetMode: setWidgetMode,
2036
2014
  setOutputTranscript: setOutputTranscriptDefault,
2037
2015
  setWorktreeIsolation: setWorktreeIsolationEnabled,
@@ -2081,11 +2059,11 @@ export default function (pi: ExtensionAPI) {
2081
2059
  // With no per-result note by design, the model would have every reason to go
2082
2060
  // on reporting a `pi-agent-*` branch that was never created.
2083
2061
  const isolationGuideline = isWorktreeIsolationEnabled()
2084
- ? `\n- Use isolation: "worktree" to give the agent its own git worktree (safe parallel file modifications); leave it unset, or pass "off", for none. The worktree is normally removed when the agent finishes and changes land on a named branch. If preservation fails, the worktree is kept and its recovery path is reported.`
2062
+ ? `\n- Use isolation: "worktree" to give the agent its own git worktree (safe parallel file modifications); leave it unset, or pass "off", for none. The worktree is removed when the agent finishes; if it made changes, they are committed to a branch and the branch is named in the result.`
2085
2063
  : ""
2086
2064
 
2087
2065
  const isolationCompactGuideline = isWorktreeIsolationEnabled()
2088
- ? `\n- isolation: "worktree" uses a temporary git worktree. Changes land on a branch; a preservation failure keeps the worktree and reports its path.`
2066
+ ? `\n- isolation: "worktree" gives the agent its own git worktree (removed on completion); changes land on a branch named in the result.`
2089
2067
  : ""
2090
2068
 
2091
2069
  // Compact Agent tool description (#91, `toolDescriptionMode: "compact"`) —
@@ -2227,11 +2205,11 @@ Terse command-style prompts produce shallow, generic work.
2227
2205
  name: Type.Optional(
2228
2206
  Type.String({
2229
2207
  description:
2230
- 'Optional memorable name for this agent, e.g. "auth-audit", so it can be addressed as `@name` at the prompt and by steer_subagent / get_subagent_result. Any characters are accepted; the `@handle` is slugged from it (lowercase letters, digits, `_`, `-`) while UI labels show it as given, spaces included. Worth setting when several agents of the same type run at once; omit for one-off work. The agent stays reachable by its type either way.',
2208
+ 'Optional memorable name for this agent, e.g. "auth-audit", so it can be addressed as `@name` at the prompt and by steer_subagent / get_subagent_result. Letters, digits, `_` and `-`. Worth setting when several agents of the same type run at once; omit for one-off work. The agent stays reachable by its type either way.',
2231
2209
  }),
2232
2210
  ),
2233
2211
  subagent_type: Type.String({
2234
- description: `The type of specialized agent to use. Available types: ${getAvailableTypes().join(", ")}. Custom agents from .pi/agents/*.md (project) or ${getAgentDir()}/agents/*.md (global) are also available, as are types another tool registered for this session — a list outside this description is usable, not invalid.`,
2212
+ description: `The type of specialized agent to use. Available types: ${getAvailableTypes().join(", ")}. Custom agents from .pi/agents/*.md (project) or ${getAgentDir()}/agents/*.md (global) are also available.`,
2235
2213
  }),
2236
2214
  model: Type.Optional(
2237
2215
  Type.String({
@@ -2980,13 +2958,11 @@ Terse command-style prompts produce shallow, generic work.
2980
2958
  fleet.ensureTimer()
2981
2959
  fleet.update()
2982
2960
 
2983
- // Emit created event
2984
- pi.events.emit("subagents:created", {
2985
- id,
2986
- type: subagentType,
2987
- description: params.description,
2988
- isBackground: true,
2989
- })
2961
+ if (record)
2962
+ pi.events.emit("subagents:created", {
2963
+ ...toSubagentInfo(record),
2964
+ isBackground: true,
2965
+ })
2990
2966
 
2991
2967
  return backgroundResult(id, record)
2992
2968
  }
@@ -3307,6 +3283,24 @@ Terse command-style prompts produce shallow, generic work.
3307
3283
  ctx: ExtensionContext,
3308
3284
  task: WorkflowTask,
3309
3285
  ): Promise<void> {
3286
+ // This function must never reject (both callers are detached). The payload
3287
+ // is built inside the guard as well as emitted there: a stale `pi` throws
3288
+ // on emit after a session replacement, and either throw would otherwise
3289
+ // surface as an unhandled rejection.
3290
+ const announce = (event: string, build: () => unknown) => {
3291
+ try {
3292
+ pi.events.emit(event, build())
3293
+ } catch {
3294
+ /* stale `pi`, or a payload that could not be built */
3295
+ }
3296
+ }
3297
+ // Bracket the run on the bus. The per-agent detail between these is pulled
3298
+ // on demand via `subagents:rpc:workflow_get`, not pushed — `onProgress`
3299
+ // fires per tool call and message per agent, too hot for the bus.
3300
+ announce("subagents:workflow_started", () => ({
3301
+ ...toWorkflowInfo(task),
3302
+ ...workflowArgs(task),
3303
+ }))
3310
3304
  try {
3311
3305
  const result = await runWorkflow({
3312
3306
  script: task.script,
@@ -3344,6 +3338,10 @@ Terse command-style prompts produce shallow, generic work.
3344
3338
  } catch (err) {
3345
3339
  failWorkflowTask(task, err instanceof Error ? err.message : String(err))
3346
3340
  }
3341
+ announce("subagents:workflow_settled", () => ({
3342
+ ...toWorkflowInfo(task),
3343
+ ...workflowResult(task),
3344
+ }))
3347
3345
  }
3348
3346
 
3349
3347
  /**
@@ -4099,6 +4097,7 @@ Terse command-style prompts produce shallow, generic work.
4099
4097
  fleetView: isFleetViewEnabled(),
4100
4098
  agentMentions: getAgentMentionMode(),
4101
4099
  rememberAgents: getRememberAgents(),
4100
+ cacheRetention: getCacheRetention(),
4102
4101
  widgetMode: getWidgetMode(),
4103
4102
  outputTranscript: getOutputTranscriptDefault(),
4104
4103
  worktreeIsolation: isWorktreeIsolationEnabled(),
@@ -4394,6 +4393,16 @@ Terse command-style prompts produce shallow, generic work.
4394
4393
  currentValue: getRememberAgents() ? "on" : "off",
4395
4394
  values: ["on", "off"],
4396
4395
  },
4396
+ {
4397
+ id: "cacheRetention",
4398
+ label: "Prompt cache retention",
4399
+ description:
4400
+ "Prompt cache lifetime for subagent model calls: short (5 min on Anthropic), long (1 hour), none, " +
4401
+ "or inherit (pi's default, incl. PI_CACHE_RETENTION). An agent's cache_retention frontmatter overrides it; " +
4402
+ "the main session is unaffected. Applies to agents started after the change",
4403
+ currentValue: getCacheRetention(),
4404
+ values: ["inherit", "short", "long", "none"],
4405
+ },
4397
4406
  {
4398
4407
  id: "packageAgents",
4399
4408
  label: "Package agents",
@@ -4748,6 +4757,9 @@ Terse command-style prompts produce shallow, generic work.
4748
4757
  target,
4749
4758
  `Remember agents ${enabled ? "enabled" : "disabled"}`,
4750
4759
  )
4760
+ } else if (id === "cacheRetention") {
4761
+ setCacheRetention(value as CacheRetentionSetting)
4762
+ notifyApplied(ctx, target, `Prompt cache retention set to ${value}`)
4751
4763
  } else if (id === "widgetMode") {
4752
4764
  setWidgetMode(value as WidgetMode)
4753
4765
  notifyApplied(ctx, target, `Widget set to ${value}`)
@@ -4866,8 +4878,6 @@ Terse command-style prompts produce shallow, generic work.
4866
4878
  viewAgentConversation,
4867
4879
  // Read lazily: `currentCtx` is rebound on every session_start, and the
4868
4880
  // fleet list may act between sessions, when there is none.
4869
- // SAFETY: ExtensionContext and ExtensionCommandContext share the runtime
4870
- // UI/session fields used by persistSettings; the value can also be absent.
4871
4881
  getCtx: () => currentCtx as unknown as ExtensionCommandContext | undefined,
4872
4882
  onTaskChange: (task) => workflowCards.request(task.id),
4873
4883
  }
@@ -62,6 +62,7 @@ import {
62
62
  SessionManager,
63
63
  type ToolDefinition,
64
64
  } from "@earendil-works/pi-coding-agent"
65
+ import { getCacheRetention, installCacheRetention } from "./cache-retention.js"
65
66
  import { runInChildSessionContext } from "./child-context.js"
66
67
  import { agentMentionReminder } from "./mention.js"
67
68
  import { withoutCwdSection } from "./prompts.js"
@@ -142,8 +143,6 @@ export async function runMentionClone(
142
143
  // Pi 0.80.8 moved createAgentSession from modelRegistry to modelRuntime;
143
144
  // agent-runner.ts carries the same shim for the same reason — pass both so
144
145
  // the clone keeps the parent's providers across the supported range.
145
- // SAFETY: The supported Pi versions expose runtime through this facade at
146
- // runtime; the optional property keeps the pre-modelRuntime fallback safe.
147
146
  const parentModelRuntime = (
148
147
  ctx.modelRegistry as unknown as { runtime?: unknown }
149
148
  ).runtime
@@ -203,6 +202,8 @@ export async function runMentionClone(
203
202
  } as Parameters<typeof createAgentSession>[0]),
204
203
  )
205
204
  session = created.session
205
+ // No agent config here — the clone is a copy of the conversation, so only the setting applies.
206
+ installCacheRetention(session, getCacheRetention())
206
207
 
207
208
  // User text first, reminder after — the order Claude Code's attachment
208
209
  // renderer produces, where the reminder trails the message it is about.
@@ -15,6 +15,7 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent"
15
15
  import { NO_FALLBACK } from "./agent-types.js"
16
16
  import type {
17
17
  AgentMentionMode,
18
+ CacheRetentionSetting,
18
19
  JoinMode,
19
20
  ViewerMarkdownMode,
20
21
  WidgetMode,
@@ -184,6 +185,15 @@ export interface SubagentsSettings {
184
185
  * nested under the spawning session in pi's `/resume`.
185
186
  */
186
187
  rememberAgents?: boolean
188
+ /**
189
+ * Prompt-cache retention for subagent model calls: `none`, `short` (5 min on
190
+ * Anthropic) or `long` (1 hour). Defaults to `inherit`, which leaves pi's
191
+ * default — and its `PI_CACHE_RETENTION` environment variable — in charge.
192
+ * Per-agent `cache_retention:` frontmatter overrides it, and a request that
193
+ * sets its own retention (compaction passes `none`) keeps it. The parent
194
+ * session is never affected. Read at spawn.
195
+ */
196
+ cacheRetention?: CacheRetentionSetting
187
197
  /**
188
198
  * Display mode for the persistent above-editor agent widget:
189
199
  * - `all`: show every agent (foreground + background).
@@ -392,6 +402,7 @@ export interface SettingsAppliers {
392
402
  setFleetView: (b: boolean) => void
393
403
  setAgentMentions: (mode: AgentMentionMode) => void
394
404
  setRememberAgents: (b: boolean) => void
405
+ setCacheRetention: (v: CacheRetentionSetting) => void
395
406
  setWidgetMode: (mode: WidgetMode) => void
396
407
  setOutputTranscript: (b: boolean) => void
397
408
  setWorktreeIsolation: (b: boolean) => void
@@ -427,6 +438,8 @@ const VALID_VIEWER_MARKDOWN_MODES: ReadonlySet<string> =
427
438
  new Set<ViewerMarkdownMode>(["off", "assistant", "all"])
428
439
  const VALID_AGENT_MENTION_MODES: ReadonlySet<string> =
429
440
  new Set<AgentMentionMode>(["model", "direct", "off"])
441
+ const VALID_CACHE_RETENTIONS: ReadonlySet<string> =
442
+ new Set<CacheRetentionSetting>(["inherit", "none", "short", "long"])
430
443
 
431
444
  // Sanity ceilings — prevent hand-edited configs from asking for values that
432
445
  // make no operational sense (e.g. 1e6 concurrent subagents). Permissive enough
@@ -498,6 +511,7 @@ export const SETTING_DEFAULTS: {
498
511
  fleetView: true,
499
512
  agentMentions: "model",
500
513
  rememberAgents: true,
514
+ cacheRetention: "inherit",
501
515
  widgetMode: "background",
502
516
  outputTranscript: true,
503
517
  worktreeIsolation: true,
@@ -597,6 +611,12 @@ function sanitize(raw: unknown): SubagentsSettings {
597
611
  if (typeof r.rememberAgents === "boolean") {
598
612
  out.rememberAgents = r.rememberAgents
599
613
  }
614
+ if (
615
+ typeof r.cacheRetention === "string" &&
616
+ VALID_CACHE_RETENTIONS.has(r.cacheRetention)
617
+ ) {
618
+ out.cacheRetention = r.cacheRetention as CacheRetentionSetting
619
+ }
600
620
  if (
601
621
  typeof r.widgetMode === "string" &&
602
622
  VALID_WIDGET_MODES.has(r.widgetMode)
@@ -822,6 +842,7 @@ export function applySettings(
822
842
  if (s.agentMentions) appliers.setAgentMentions(s.agentMentions)
823
843
  if (typeof s.rememberAgents === "boolean")
824
844
  appliers.setRememberAgents(s.rememberAgents)
845
+ if (s.cacheRetention) appliers.setCacheRetention(s.cacheRetention)
825
846
  if (s.widgetMode) appliers.setWidgetMode(s.widgetMode)
826
847
  if (typeof s.outputTranscript === "boolean")
827
848
  appliers.setOutputTranscript(s.outputTranscript)
@@ -0,0 +1,115 @@
1
+ /**
2
+ * subagent-info.ts — The one agent shape other extensions read off `pi.events`.
3
+ *
4
+ * Every `subagents:*` lifecycle event carries it, plus whatever that event
5
+ * adds of its own. It is a public contract, so it is built from a whitelist:
6
+ * a field reaches listeners only by being named here, never because it was
7
+ * added to `AgentRecord`. Documented in docs/rpc.md.
8
+ *
9
+ * Two rules keep the events one shape. A payload is flat: these fields, with
10
+ * the event's own spread beside them, because existing listeners read
11
+ * `payload.id`. And an event's own field never reuses a name from here, or a
12
+ * listener reading it off any `subagents:*` event gets two meanings.
13
+ * (`subagents:usage`'s per-message `usage` predates this rule.)
14
+ */
15
+ import type { AgentRecord } from "./types.js"
16
+ import {
17
+ getLifetimeTotal,
18
+ type ReportedUsage,
19
+ toReportedUsage,
20
+ } from "./usage.js"
21
+
22
+ export interface SubagentInfo {
23
+ id: string
24
+ type: string
25
+ description: string
26
+ status: AgentRecord["status"]
27
+ /** Nesting depth: a top-level agent is 1. */
28
+ depth: number
29
+ /** The agent that spawned this one through its scoped `Agent` tool. */
30
+ parentAgentId?: string
31
+ /** The workflow run that spawned this one. */
32
+ workflowId?: string
33
+ startedAt: number
34
+ completedAt?: number
35
+ /** Until `completedAt`, the time elapsed so far. */
36
+ durationMs: number
37
+ toolUses: number
38
+ result?: string
39
+ error?: string
40
+ /**
41
+ * The validated `StructuredOutput` payload as canonical JSON. Set only when
42
+ * the spawn asked for a schema and the agent produced a valid report.
43
+ */
44
+ structuredJson?: string
45
+ /** The agent's pi session file, when the session is persisted. */
46
+ sessionFile?: string
47
+ /**
48
+ * Display token totals: excludes cacheRead (#38). Omitted when nothing was
49
+ * produced.
50
+ */
51
+ tokens?: { input: number; output: number; total: number }
52
+ /**
53
+ * The run's spend as a pi `Usage`, its descendants' spend included, so
54
+ * summing it across a tree double-counts. Omitted when nothing was spent.
55
+ */
56
+ usage?: ReportedUsage
57
+ /**
58
+ * This agent's own spend, descendants excluded: the figure to sum across a
59
+ * tree. Omitted when the agent itself spent nothing.
60
+ */
61
+ ownUsage?: ReportedUsage
62
+ }
63
+
64
+ /**
65
+ * Build a record's `SubagentInfo`. A key whose value is unknown is omitted,
66
+ * never present as `undefined`, as on `subagents:usage`.
67
+ */
68
+ export function toSubagentInfo(
69
+ record: AgentRecord,
70
+ now = Date.now(),
71
+ ): SubagentInfo {
72
+ // `lifetimeUsage` is lifetime-accumulated (Σ over every assistant
73
+ // message_end), so it survives compaction: input + output ≤ total always.
74
+ const u = record.lifetimeUsage
75
+ const total = getLifetimeTotal(u)
76
+ // Two conventions, kept as they shipped. `usage` is pi's own `Usage`, so
77
+ // `usage.cost.total` is where a listener already looks. `tokens` is a flat
78
+ // view model like pi's `SessionStats`, carrying the DISPLAY total. Neither
79
+ // derives from the other. Both are ungated by `showCost`: that governs what
80
+ // a human is shown, not what the event carries.
81
+ const usage = toReportedUsage(u)
82
+ const ownUsage = toReportedUsage(record.ownUsage)
83
+ return {
84
+ id: record.id,
85
+ type: record.type,
86
+ description: record.description,
87
+ status: record.status,
88
+ depth: record.depth ?? 1,
89
+ ...(record.parentAgentId !== undefined
90
+ ? { parentAgentId: record.parentAgentId }
91
+ : {}),
92
+ ...(record.workflowId !== undefined
93
+ ? { workflowId: record.workflowId }
94
+ : {}),
95
+ startedAt: record.startedAt,
96
+ ...(record.completedAt !== undefined
97
+ ? { completedAt: record.completedAt }
98
+ : {}),
99
+ durationMs: (record.completedAt ?? now) - record.startedAt,
100
+ toolUses: record.toolUses,
101
+ ...(record.result !== undefined ? { result: record.result } : {}),
102
+ ...(record.error !== undefined ? { error: record.error } : {}),
103
+ ...(record.structuredJson !== undefined
104
+ ? { structuredJson: record.structuredJson }
105
+ : {}),
106
+ ...(record.sessionFile !== undefined
107
+ ? { sessionFile: record.sessionFile }
108
+ : {}),
109
+ ...(total > 0
110
+ ? { tokens: { input: u.input, output: u.output, total } }
111
+ : {}),
112
+ ...(usage !== undefined ? { usage } : {}),
113
+ ...(ownUsage !== undefined ? { ownUsage } : {}),
114
+ }
115
+ }