@herbertgao/pi-extensions 2026.11.18 → 2026.11.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +2 -23
  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/package.json +11 -14
  97. package/node_modules/pi-antigravity/README.md +0 -298
  98. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  99. package/node_modules/pi-antigravity/package.json +0 -87
  100. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  101. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  102. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  103. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  104. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  105. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  106. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  107. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  108. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  109. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  110. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  111. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  112. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  113. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  114. package/node_modules/pi-antigravity/src/index.ts +0 -547
  115. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  116. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  117. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  118. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  119. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  120. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  121. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  122. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  123. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  124. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  125. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  126. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  127. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  128. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  129. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  130. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  131. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  132. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  133. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  134. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  135. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  136. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  137. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  138. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  139. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  140. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  141. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  142. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  143. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  144. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  145. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  146. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  147. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  148. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  149. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  150. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  151. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -475,10 +475,17 @@ export class AgentManager {
475
475
  */
476
476
  private startups = new Map<string, Promise<void>>()
477
477
 
478
+ /**
479
+ * Every `record.promise` that has not settled yet. A settled promise stays on
480
+ * its record, so this is what tells `isSettling` and `waitForSettled` a run is
481
+ * over.
482
+ */
483
+ private unsettled = new Set<Promise<unknown>>()
484
+
478
485
  /**
479
486
  * Evicted agents that can still be reached by name, keyed by handle. Outlives
480
- * the 10-minute record cleanup — that timer bounds memory after results are
481
- * consumed — and is cleared alongside
487
+ * the 10-minute record cleanup — that timer exists to bound memory, not to
488
+ * expire a conversation the user might still want — and is cleared alongside
482
489
  * completed records on session start/switch.
483
490
  */
484
491
  private tombstones = new Map<string, AgentTombstone>()
@@ -522,7 +529,7 @@ export class AgentManager {
522
529
  this.onUsage = onUsage
523
530
  this.onSteered = onSteered
524
531
  this.maxConcurrent = maxConcurrent
525
- // Cleanup consumed completed agents after 10 minutes
532
+ // Cleanup completed agents after 10 minutes (but keep sessions for resume)
526
533
  this.cleanupInterval = setInterval(() => this.cleanup(), 60_000)
527
534
  this.cleanupInterval.unref()
528
535
  }
@@ -1194,7 +1201,7 @@ export class AgentManager {
1194
1201
  return ""
1195
1202
  })
1196
1203
 
1197
- record.promise = promise
1204
+ this.trackRun(record, promise)
1198
1205
 
1199
1206
  // Notify caller that spawn is complete (record is in the map, promise is set).
1200
1207
  // Called synchronously — onSessionCreated fires asynchronously inside runAgent.
@@ -1279,7 +1286,7 @@ export class AgentManager {
1279
1286
  const record = this.agents.get(next.id)
1280
1287
  // Stale entries (aborted while queued) are not started — but are still
1281
1288
  // released, since nothing else will.
1282
- if (record?.status !== "queued") {
1289
+ if (!record || record.status !== "queued") {
1283
1290
  next.release()
1284
1291
  continue
1285
1292
  }
@@ -1687,7 +1694,7 @@ export class AgentManager {
1687
1694
  return ""
1688
1695
  })
1689
1696
 
1690
- record.promise = promise
1697
+ this.trackRun(record, promise)
1691
1698
  }
1692
1699
 
1693
1700
  /**
@@ -1971,6 +1978,82 @@ export class AgentManager {
1971
1978
  return count
1972
1979
  }
1973
1980
 
1981
+ /**
1982
+ * Resolve once `id`'s run and the runs of every agent it owns, directly or
1983
+ * transitively, have settled — true then, or false if `timeoutMs` passes
1984
+ * first. Unlike `waitForAll`, it reads promises, not status: `abort()` marks
1985
+ * a record "stopped" at once, while a tool call that ignores the signal can
1986
+ * still be running, and only the promise says when it is not (#443).
1987
+ *
1988
+ * Loops until a pass finds nothing unsettled: a descendant can be spawned,
1989
+ * and a record resumed with a new promise, while the tree unwinds.
1990
+ */
1991
+ async waitForSettled(id: string, timeoutMs: number): Promise<boolean> {
1992
+ let timer: ReturnType<typeof setTimeout> | undefined
1993
+ const expired = new Promise<false>((resolve) => {
1994
+ timer = setTimeout(() => resolve(false), timeoutMs)
1995
+ })
1996
+ const settled = (async () => {
1997
+ for (
1998
+ let pending = this.unsettledInTree(id);
1999
+ pending.length > 0;
2000
+ pending = this.unsettledInTree(id)
2001
+ ) {
2002
+ await Promise.allSettled(pending)
2003
+ }
2004
+ return true
2005
+ })()
2006
+ try {
2007
+ return await Promise.race([settled, expired])
2008
+ } finally {
2009
+ clearTimeout(timer)
2010
+ }
2011
+ }
2012
+
2013
+ /**
2014
+ * Whether anything in `id`'s tree — the agent itself or an agent it owns,
2015
+ * transitively — is still starting up or running, whatever its status says.
2016
+ * A stopped agent reads true until the tool call that ignored the abort ends.
2017
+ */
2018
+ isSettling(id: string): boolean {
2019
+ return this.unsettledInTree(id).length > 0
2020
+ }
2021
+
2022
+ /** The startups and runs in `id`'s tree that have not settled yet. */
2023
+ private unsettledInTree(id: string): Promise<unknown>[] {
2024
+ const pending: Promise<unknown>[] = []
2025
+ for (const record of this.agents.values()) {
2026
+ if (!this.isInTree(record, id)) continue
2027
+ const startup = this.startups.get(record.id)
2028
+ if (startup) pending.push(startup)
2029
+ if (record.promise && this.unsettled.has(record.promise))
2030
+ pending.push(record.promise)
2031
+ }
2032
+ return pending
2033
+ }
2034
+
2035
+ /** Set `record.promise`, and track it in `unsettled` until it settles. */
2036
+ private trackRun(record: AgentRecord, promise: Promise<string>): void {
2037
+ record.promise = promise
2038
+ this.unsettled.add(promise)
2039
+ const done = () => {
2040
+ this.unsettled.delete(promise)
2041
+ }
2042
+ promise.then(done, done)
2043
+ }
2044
+
2045
+ /** Whether `record` is `rootId` itself or one of the agents it owns. */
2046
+ private isInTree(record: AgentRecord, rootId: string): boolean {
2047
+ for (
2048
+ let r: AgentRecord | undefined = record;
2049
+ r;
2050
+ r = r.parentAgentId ? this.agents.get(r.parentAgentId) : undefined
2051
+ ) {
2052
+ if (r.id === rootId) return true
2053
+ }
2054
+ return false
2055
+ }
2056
+
1974
2057
  /** Wait for all running and queued agents to complete (including queued ones). */
1975
2058
  async waitForAll(): Promise<void> {
1976
2059
  // Loop because drainQueue respects the concurrency limit — as running
@@ -32,6 +32,7 @@ import {
32
32
  getReadOnlyMemoryToolNames,
33
33
  getToolNamesForType,
34
34
  } from "./agent-types.js"
35
+ import { getCacheRetention, installCacheRetention } from "./cache-retention.js"
35
36
  import { runInChildSessionContext } from "./child-context.js"
36
37
  import { buildParentContext, extractText } from "./context.js"
37
38
  import { deniedToolNames } from "./custom-agents.js"
@@ -1512,8 +1513,6 @@ export async function runAgent(
1512
1513
  // Pi 0.80.8 replaced createAgentSession's modelRegistry option with
1513
1514
  // modelRuntime, but ExtensionContext still exposes only the registry facade.
1514
1515
  // Pass both so the full supported Pi range retains the parent's providers.
1515
- // SAFETY: Pi's registry facade exposes its runtime at runtime on versions
1516
- // that support modelRuntime; the optional shape preserves older Pi support.
1517
1516
  const parentModelRuntime = (
1518
1517
  ctx.modelRegistry as unknown as { runtime?: unknown }
1519
1518
  ).runtime
@@ -1552,6 +1551,11 @@ export async function runAgent(
1552
1551
  // to its default. Warned the way pi warns at its own session start, and the
1553
1552
  // way an out-of-scope model is warned: to the user, not the model.
1554
1553
  if (modelFallbackMessage) ctx.ui.notify(modelFallbackMessage, "warning")
1554
+ // Before bindExtensions, so session_start handlers already see the wrapper.
1555
+ installCacheRetention(
1556
+ session,
1557
+ agentConfig?.cacheRetention ?? getCacheRetention(),
1558
+ )
1555
1559
 
1556
1560
  const baseSessionName = agentConfig?.name ?? type
1557
1561
  session.setSessionName(
@@ -135,12 +135,28 @@ function overlayEphemeral(registry: Map<string, AgentConfig>): string[] {
135
135
  return applied
136
136
  }
137
137
 
138
+ /** Whether an ephemeral registration may overlay the live registry for `name`.
139
+ * File- and default-backed keys win; only keys we already own may be replaced. */
140
+ function canOverlayEphemeralName(name: string): boolean {
141
+ const key = resolveKeyIn(agents, name)
142
+ if (key === undefined) return true
143
+ return ephemeralOwned.has(key)
144
+ }
145
+
138
146
  /** Register session-scoped agent types at runtime; spawnable immediately.
139
- * Returns the names actually applied, so a caller can fail loudly when a name
140
- * collides with a file-loaded or default type instead of shadowing it. */
147
+ * The batch is atomic: every name is checked against file/default types before
148
+ * any mutation; a collision fails the whole call with no partial overlay. */
141
149
  export function registerEphemeralAgents(
142
150
  entries: Map<string, AgentConfig>,
143
151
  ): string[] {
152
+ const conflicts = [...entries.keys()].filter(
153
+ (name) => !canOverlayEphemeralName(name),
154
+ )
155
+ if (conflicts.length > 0) {
156
+ throw new Error(
157
+ `agent type already exists: ${conflicts.map((name) => `"${name}"`).join(", ")}`,
158
+ )
159
+ }
144
160
  for (const [name, config] of entries) {
145
161
  // A case-variant of an existing ephemeral key replaces it in place, so
146
162
  // one persona cannot leave a second, unreachable entry behind.
@@ -149,15 +165,8 @@ export function registerEphemeralAgents(
149
165
  ephemeralAgents.delete(existing)
150
166
  ephemeralAgents.set(name, config)
151
167
  }
152
- const applied = overlayEphemeral(agents)
153
- // A skipped name collided with a file/default type: drop it from the store
154
- // as well, so it cannot silently apply later if that type disappears.
155
- for (const name of entries.keys()) {
156
- if (!applied.includes(name)) ephemeralAgents.delete(name)
157
- }
158
- // Report only this call's names: the overlay re-applies the whole store, so
159
- // returning `applied` would list types the caller never sent.
160
- return [...entries.keys()].filter((name) => applied.includes(name))
168
+ overlayEphemeral(agents)
169
+ return [...entries.keys()]
161
170
  }
162
171
 
163
172
  /** Remove ephemeral types by name (case-insensitive); file-backed types stay.
@@ -0,0 +1,39 @@
1
+ // Prompt-cache retention for subagent sessions. A parent on a 1-hour cache
2
+ // (`PI_CACHE_RETENTION=long`) would otherwise make every short-lived child pay
3
+ // the 1-hour write rate. Precedence: an explicit per-request value (pi passes
4
+ // `none` for compaction and branch summaries) > the agent's `cache_retention`
5
+ // frontmatter > the `cacheRetention` setting > pi's own default.
6
+
7
+ import type { AgentSession } from "@earendil-works/pi-coding-agent"
8
+ import type { CacheRetentionSetting } from "./types.js"
9
+
10
+ let cacheRetention: CacheRetentionSetting = "inherit"
11
+
12
+ /** The `cacheRetention` setting; `inherit` leaves pi's default in charge. */
13
+ export function getCacheRetention(): CacheRetentionSetting {
14
+ return cacheRetention
15
+ }
16
+ /** Set the `cacheRetention` setting. Read at spawn, so it applies to agents started after it. */
17
+ export function setCacheRetention(v: CacheRetentionSetting): void {
18
+ cacheRetention = v
19
+ }
20
+
21
+ /**
22
+ * Supply `retention` on every model call the session makes that doesn't set
23
+ * one itself. Wraps the session's own stream function, so pi's routing, auth
24
+ * and cache warming still run — the warmer sees the value and refreshes on the
25
+ * matching TTL. Install it before `bindExtensions`, so `session_start` handlers
26
+ * already see the wrapped function. `inherit` installs nothing.
27
+ */
28
+ export function installCacheRetention(
29
+ session: AgentSession,
30
+ retention: CacheRetentionSetting,
31
+ ): void {
32
+ if (retention === "inherit") return
33
+ const streamFunction = session.agent.streamFunction
34
+ session.agent.streamFunction = (model, context, options) =>
35
+ streamFunction(model, context, {
36
+ ...options,
37
+ cacheRetention: options?.cacheRetention ?? retention,
38
+ })
39
+ }
@@ -64,6 +64,11 @@ export class CompletionOutbox {
64
64
  if (stopReason !== "aborted" && stopReason !== "error") this.flush()
65
65
  }
66
66
 
67
+ /** Whether a notification naming `id` is waiting to be sent. */
68
+ has(id: string): boolean {
69
+ return this.items.some((item) => item.ids.includes(id))
70
+ }
71
+
67
72
  /** The agent's result was read: it must not also be notified. */
68
73
  cancel(id: string): void {
69
74
  for (const item of this.items) item.ids = item.ids.filter((i) => i !== id)
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Cross-extension RPC handlers for the subagents extension.
3
3
  *
4
- * Exposes ping, spawn, stop, consume, and steer RPCs over the pi.events event bus,
5
- * using per-request scoped reply channels.
4
+ * Exposes ping, spawn, stop, consume, steer, get, list, workflow_get, and
5
+ * workflow_list RPCs over the pi.events event bus, using per-request scoped
6
+ * reply channels.
6
7
  *
7
8
  * Reply envelope follows pi-mono convention:
8
9
  * success → { success: true, data?: T }
@@ -22,7 +23,9 @@ import {
22
23
  } from "./agent-types.js"
23
24
  import { type ModelRegistry, resolveModel } from "./model-resolver.js"
24
25
  import { checkModelScope } from "./model-scope.js"
26
+ import { toSubagentInfo } from "./subagent-info.js"
25
27
  import type { AgentConfig, AgentRecord } from "./types.js"
28
+ import type { WorkflowDetail, WorkflowInfo } from "./workflow-info.js"
26
29
 
27
30
  /** Minimal event bus interface needed by the RPC handlers. */
28
31
  export interface EventBus {
@@ -38,6 +41,39 @@ export type RpcReply<T = void> =
38
41
  /** RPC protocol version — bumped when the envelope or method contracts change. */
39
42
  export const PROTOCOL_VERSION = 2
40
43
 
44
+ /**
45
+ * How long `subagents:rpc:stop` waits for the stopped agent and the agents it
46
+ * owns to settle before replying `{ settled: false }`. Below the 10 s pi-tasks
47
+ * gives the stop reply, so a slow settle never reads to it as a failed stop.
48
+ */
49
+ export const STOP_SETTLE_TIMEOUT_MS = 5_000
50
+
51
+ /** The largest `settleTimeoutMs` a `subagents:rpc:stop` caller can ask for. */
52
+ export const STOP_SETTLE_TIMEOUT_MAX_MS = 60_000
53
+
54
+ /**
55
+ * What this build supports, on the `ping` reply. The envelope and spawn
56
+ * contract are still `PROTOCOL_VERSION` 2; these name the additions a caller
57
+ * may need to detect. A missing `features` array means a build older than all
58
+ * of them. Append only: a consumer checks `features.includes(...)`.
59
+ */
60
+ export const FEATURES = [
61
+ "consume",
62
+ "steer",
63
+ "get",
64
+ "list",
65
+ "owned-lifecycle",
66
+ "stop-settles",
67
+ "settling",
68
+ "notification-pending",
69
+ "workflow-events",
70
+ "workflow-get",
71
+ "workflow-list",
72
+ "workflow-result",
73
+ "workflow-args",
74
+ "workflow-logs",
75
+ ] as const
76
+
41
77
  /** Minimal AgentManager interface needed by the spawn/stop/consume RPCs. */
42
78
  export interface SpawnCapable {
43
79
  spawn(
@@ -51,13 +87,29 @@ export interface SpawnCapable {
51
87
  awaitStartup(id: string): Promise<void>
52
88
  abort(id: string): boolean
53
89
  /**
54
- * The record behind an id, for the stop handler's ownership check. Narrowed
55
- * to the two fields `isTopLevelAgent` reads, so the RPC layer keeps its
56
- * deliberately shallow view of the manager.
90
+ * Resolves true once the agent's run and every owned descendant's run have
91
+ * settled, false if `timeoutMs` passes first.
92
+ */
93
+ waitForSettled(id: string, timeoutMs: number): Promise<boolean>
94
+ /**
95
+ * Whether the agent or an agent it owns is still starting up or running,
96
+ * whatever its status says — a stopped agent whose tool call ignored the
97
+ * abort reads true until that call ends.
98
+ */
99
+ isSettling(id: string): boolean
100
+ /**
101
+ * The record behind an id: the stop and steer handlers' ownership check, and
102
+ * what `get` turns into a `SubagentInfo`. Unfiltered — owned agents included.
103
+ */
104
+ getRecord(id: string): AgentRecord | undefined
105
+ /** Every record the manager holds, owned agents included, any status. */
106
+ listAgents(): AgentRecord[]
107
+ /**
108
+ * Whether the agent has settled but the parent has not been sent its
109
+ * completion notification yet — still held for the parent's next boundary
110
+ * or for its `group`. A notification that will start a parent turn.
57
111
  */
58
- getRecord(
59
- id: string,
60
- ): Pick<AgentRecord, "parentAgentId" | "workflowId"> | undefined
112
+ isNotificationPending(id: string): boolean
61
113
  /**
62
114
  * Mark a settled agent's result as read by the caller, suppressing the
63
115
  * completion notification — what `get_subagent_result` does when it returns
@@ -71,14 +123,22 @@ export interface SpawnCapable {
71
123
  steer(id: string, message: string): boolean
72
124
  }
73
125
 
126
+ /** Read-only snapshots of workflow runs, for `workflow_get` / `workflow_list`. */
127
+ export interface WorkflowReader {
128
+ /** One run's live detail (summary + per-agent snapshot), or undefined. */
129
+ get(id: string): WorkflowDetail | undefined
130
+ /** Every current run, summary only. */
131
+ list(): WorkflowInfo[]
132
+ }
133
+
74
134
  export interface RpcDeps {
75
135
  events: EventBus
76
136
  pi: unknown // passed through to manager.spawn
137
+ /** Reload file-backed agents before `list-agents` answers. */
138
+ refreshAgents?: () => void
77
139
  getCtx: () => unknown | undefined // returns current ExtensionContext
78
140
  manager: SpawnCapable
79
- /** Reload agent files before list-agents answers, so the list matches what
80
- * a spawn right now could use. index.ts wires this to reloadCustomAgents. */
81
- refreshAgents?: () => void
141
+ workflows: WorkflowReader
82
142
  }
83
143
 
84
144
  export interface RpcHandle {
@@ -90,6 +150,10 @@ export interface RpcHandle {
90
150
  unsubRegisterAgents: () => void
91
151
  unsubUnregisterAgents: () => void
92
152
  unsubListAgents: () => void
153
+ unsubGet: () => void
154
+ unsubList: () => void
155
+ unsubWorkflowGet: () => void
156
+ unsubWorkflowList: () => void
93
157
  }
94
158
 
95
159
  /**
@@ -157,14 +221,14 @@ export function ephemeralAgentConfig(
157
221
  }
158
222
 
159
223
  /**
160
- * Register ping, spawn, stop, consume, and steer RPC handlers on the event bus.
224
+ * Register ping, spawn, stop, consume, steer, get, and list RPC handlers on the event bus.
161
225
  * Returns unsub functions for cleanup.
162
226
  */
163
227
  export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
164
- const { events, pi, getCtx, manager } = deps
228
+ const { events, pi, getCtx, manager, workflows } = deps
165
229
 
166
230
  const unsubPing = handleRpc(events, "subagents:rpc:ping", () => {
167
- return { version: PROTOCOL_VERSION }
231
+ return { version: PROTOCOL_VERSION, features: [...FEATURES] }
168
232
  })
169
233
 
170
234
  const unsubSpawn = handleRpc<{
@@ -244,10 +308,10 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
244
308
  // Only the session's own agents are this RPC's to stop or steer. A nested
245
309
  // child or a workflow's agent is owned by something that is *waiting on it*,
246
310
  // and aborting or redirecting it out from under that owner turns another
247
- // extension's request into a failed step here. Defence in depth rather than
248
- // a live hole: no RPC hands out agent ids, so a caller has no ordinary way to
249
- // name one it does not own — but the guard is cheap and the id may leak some
250
- // other way. Same refuse-what-we-should-not-touch stance as `consume` below.
311
+ // extension's request into a failed step here. A live boundary: the
312
+ // lifecycle events and `list` hand out every agent's id, owned ones
313
+ // included, so a caller can name one it does not own. Same
314
+ // refuse-what-we-should-not-touch stance as `consume` below.
251
315
  const assertOwned = (agentId: string): void => {
252
316
  const record = manager.getRecord(agentId)
253
317
  if (!record) throw new Error("Agent not found")
@@ -255,17 +319,34 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
255
319
  throw new Error("Agent is owned by another agent or workflow")
256
320
  }
257
321
 
258
- const unsubStop = handleRpc<{ requestId: string; agentId: string }>(
259
- events,
260
- "subagents:rpc:stop",
261
- ({ agentId }) => {
262
- assertOwned(agentId)
263
- // Not "not found" — the lookup above already proved it exists. `abort`
264
- // returns false only for a record that is neither running nor queued,
265
- // which is an agent that has already finished.
266
- if (!manager.abort(agentId)) throw new Error("Agent is not running")
267
- },
268
- )
322
+ const unsubStop = handleRpc<{
323
+ requestId: string
324
+ agentId: string
325
+ settleTimeoutMs?: unknown
326
+ }>(events, "subagents:rpc:stop", async ({ agentId, settleTimeoutMs }) => {
327
+ if (
328
+ settleTimeoutMs !== undefined &&
329
+ (typeof settleTimeoutMs !== "number" || !Number.isFinite(settleTimeoutMs))
330
+ ) {
331
+ throw new Error("settleTimeoutMs must be a number of milliseconds")
332
+ }
333
+ const timeoutMs = Math.min(
334
+ Math.max(settleTimeoutMs ?? STOP_SETTLE_TIMEOUT_MS, 0),
335
+ STOP_SETTLE_TIMEOUT_MAX_MS,
336
+ )
337
+ assertOwned(agentId)
338
+ // `abort` returns false for a record that is neither running nor queued.
339
+ // If its tree is still settling, this is a repeat stop after
340
+ // `settled: false`, and it waits again. Otherwise the agent has finished:
341
+ // not "not found", since the lookup above proved it exists.
342
+ if (!manager.abort(agentId) && !manager.isSettling(agentId))
343
+ throw new Error("Agent is not running")
344
+ // Stop means stopped: the reply waits until no tool call of this agent
345
+ // or of any agent it owns can still land (#443). A caller that does not
346
+ // care need not await it. `settled: false` says the bound passed first
347
+ // and something may still be running; `get` then shows `settling`.
348
+ return { settled: await manager.waitForSettled(agentId, timeoutMs) }
349
+ })
269
350
 
270
351
  // A caller that has already shown the model an agent's result — pi-tasks'
271
352
  // TaskOutput is the one in practice — says so here, so the completion
@@ -284,8 +365,8 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
284
365
  // An extension that spawned an agent over the bus and then learns something
285
366
  // that agent needs — a second CI failure on the head it is already fixing, a
286
367
  // review that landed mid-run — can hand it over instead of spawning a second
287
- // agent for the same work or dropping the fact. Outside the ping version
288
- // handshake, like consume: additive and best-effort.
368
+ // agent for the same work or dropping the fact. Additive: a caller detects
369
+ // it through `FEATURES` on ping, not the version.
289
370
  const unsubSteer = handleRpc<{
290
371
  requestId: string
291
372
  agentId: string
@@ -326,18 +407,6 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
326
407
  entries.set(name, { ...config, builtinToolNames })
327
408
  })
328
409
  const applied = registerEphemeralAgents(entries)
329
- // A skipped name collides with a file-loaded or default type: fail loudly
330
- // rather than let the caller spawn that type believing it is the persona.
331
- const skipped = [...entries.keys()].filter(
332
- (name) => !applied.includes(name),
333
- )
334
- if (skipped.length > 0)
335
- throw new Error(
336
- `agent type already exists: ${skipped.map((name) => `"${name}"`).join(", ")}` +
337
- (applied.length > 0
338
- ? ` (applied: ${applied.map((name) => `"${name}"`).join(", ")})`
339
- : ""),
340
- )
341
410
  // Badge holders (pi-cc-extensions) re-pull list-agents on this event, so a
342
411
  // freshly seated persona gets its colored badge without a new session.
343
412
  events.emit("subagents:agents-changed", {})
@@ -359,7 +428,8 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
359
428
  // its config would render. pi-cc-extensions pulls this once per session (on
360
429
  // subagents:ready) and again on subagents:agents-changed, then draws
361
430
  // transcript badges from it. Additive like the other channels: outside the
362
- // ping handshake, a missing handler just never replies.
431
+ // ping handshake, a missing handler just never replies. Not to be confused
432
+ // with `subagents:rpc:list`, which snapshots running agent instances.
363
433
  const unsubListAgents = handleRpc<{ requestId: string }>(
364
434
  events,
365
435
  "subagents:rpc:list-agents",
@@ -378,6 +448,73 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
378
448
  },
379
449
  )
380
450
 
451
+ // Snapshots, for a listener that joined after the lifecycle events it needed
452
+ // had already fired — bound late, or reloaded mid-run. Reads only, so owned
453
+ // agents are included: they carry `parentAgentId` / `workflowId` exactly as
454
+ // on the events, and the caller filters. `assertOwned` guards only the
455
+ // mutations. Detected through `FEATURES` on ping, like steer.
456
+ //
457
+ // Snapshots also say what the events cannot: `notificationPending`, set while
458
+ // a settled agent's completion is still on its way to the parent. An
459
+ // orchestrator that waits for "nothing active" must wait for it too, or the
460
+ // notification starts a parent turn right after it concluded none would
461
+ // (#103). Not on the events: `completed` fires before the notification is
462
+ // queued, so there it would always read false.
463
+ //
464
+ // `settling` is the other half: set while a terminal agent's tree still has
465
+ // a run in flight — a stopped agent whose tool call ignored the abort, or a
466
+ // child still unwinding (#443). Not on the events either: the terminal
467
+ // event fires from inside the settle path.
468
+ const snapshot = (record: AgentRecord, now?: number) => {
469
+ const terminal = record.status !== "running" && record.status !== "queued"
470
+ return {
471
+ ...toSubagentInfo(record, now),
472
+ ...(terminal && manager.isSettling(record.id) ? { settling: true } : {}),
473
+ ...(manager.isNotificationPending(record.id)
474
+ ? { notificationPending: true }
475
+ : {}),
476
+ }
477
+ }
478
+
479
+ const unsubGet = handleRpc<{ requestId: string; agentId: string }>(
480
+ events,
481
+ "subagents:rpc:get",
482
+ ({ agentId }) => {
483
+ const record = manager.getRecord(agentId)
484
+ if (!record) throw new Error("Agent not found")
485
+ return { agent: snapshot(record) }
486
+ },
487
+ )
488
+
489
+ const unsubList = handleRpc(events, "subagents:rpc:list", () => {
490
+ const now = Date.now()
491
+ return {
492
+ agents: manager.listAgents().map((record) => snapshot(record, now)),
493
+ }
494
+ })
495
+
496
+ // Workflow-run snapshots, for a consumer that missed `workflow_started` or
497
+ // wants the live per-agent detail — pulled rather than pushed, at whatever
498
+ // cadence the consumer wants. A run is top-level, so no ownership guard.
499
+ // `get` carries the per-agent `agents` snapshot; `list` is summaries only.
500
+ const unsubWorkflowGet = handleRpc<{ requestId: string; workflowId: string }>(
501
+ events,
502
+ "subagents:rpc:workflow_get",
503
+ ({ workflowId }) => {
504
+ const workflow = workflows.get(workflowId)
505
+ if (!workflow) throw new Error("Workflow not found")
506
+ return { workflow }
507
+ },
508
+ )
509
+
510
+ const unsubWorkflowList = handleRpc(
511
+ events,
512
+ "subagents:rpc:workflow_list",
513
+ () => {
514
+ return { workflows: workflows.list() }
515
+ },
516
+ )
517
+
381
518
  return {
382
519
  unsubPing,
383
520
  unsubSpawn,
@@ -387,5 +524,9 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
387
524
  unsubRegisterAgents,
388
525
  unsubUnregisterAgents,
389
526
  unsubListAgents,
527
+ unsubGet,
528
+ unsubList,
529
+ unsubWorkflowGet,
530
+ unsubWorkflowList,
390
531
  }
391
532
  }
@@ -222,6 +222,13 @@ function loadOneFile(
222
222
  maxTurns: nonNegativeInt(fm.max_turns),
223
223
  persistSession:
224
224
  fm.persist_session != null ? fm.persist_session === true : undefined,
225
+ // No `inherit` here: omitting the key already defers to the setting.
226
+ cacheRetention:
227
+ fm.cache_retention === "none" ||
228
+ fm.cache_retention === "short" ||
229
+ fm.cache_retention === "long"
230
+ ? fm.cache_retention
231
+ : undefined,
225
232
  outputTranscript:
226
233
  fm.output_transcript != null ? fm.output_transcript !== false : undefined,
227
234
  sessionDir: str(fm.session_dir),
@@ -129,6 +129,15 @@ export class GroupJoinManager {
129
129
  this.groups.delete(groupId)
130
130
  }
131
131
 
132
+ /** Whether `agentId` has completed and its group is holding the result back. */
133
+ isHolding(agentId: string): boolean {
134
+ const groupId = this.agentToGroup.get(agentId)
135
+ return (
136
+ groupId !== undefined &&
137
+ this.groups.get(groupId)?.completedRecords.has(agentId) === true
138
+ )
139
+ }
140
+
132
141
  /** Check if an agent is in a group. */
133
142
  isGrouped(agentId: string): boolean {
134
143
  return this.agentToGroup.has(agentId)