@astralyn/pi 0.85.1 → 0.85.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/cli.js +94 -91
  3. package/dist/core/agent-session.js +2 -2
  4. package/dist/core/agent-session.js.map +1 -1
  5. package/dist/core/background/history.d.ts.map +1 -1
  6. package/dist/core/background/history.js +6 -0
  7. package/dist/core/background/history.js.map +1 -1
  8. package/dist/core/background/presentation.d.ts.map +1 -1
  9. package/dist/core/background/presentation.js +41 -4
  10. package/dist/core/background/presentation.js.map +1 -1
  11. package/dist/core/background/service.d.ts +2 -2
  12. package/dist/core/background/service.d.ts.map +1 -1
  13. package/dist/core/background/service.js +38 -15
  14. package/dist/core/background/service.js.map +1 -1
  15. package/dist/core/background/types.d.ts +9 -0
  16. package/dist/core/background/types.d.ts.map +1 -1
  17. package/dist/core/background/types.js +4 -0
  18. package/dist/core/background/types.js.map +1 -1
  19. package/dist/core/compaction/compaction.d.ts +5 -12
  20. package/dist/core/compaction/compaction.d.ts.map +1 -1
  21. package/dist/core/compaction/compaction.js +11 -19
  22. package/dist/core/compaction/compaction.js.map +1 -1
  23. package/dist/core/compaction/settings.d.ts +27 -0
  24. package/dist/core/compaction/settings.d.ts.map +1 -0
  25. package/dist/core/compaction/settings.js +40 -0
  26. package/dist/core/compaction/settings.js.map +1 -0
  27. package/dist/core/keybindings.d.ts +15 -0
  28. package/dist/core/keybindings.d.ts.map +1 -1
  29. package/dist/core/keybindings.js +12 -0
  30. package/dist/core/keybindings.js.map +1 -1
  31. package/dist/core/model-config.d.ts +32 -10
  32. package/dist/core/model-config.d.ts.map +1 -1
  33. package/dist/core/model-config.js +38 -1
  34. package/dist/core/model-config.js.map +1 -1
  35. package/dist/core/model-runtime.d.ts +2 -0
  36. package/dist/core/model-runtime.d.ts.map +1 -1
  37. package/dist/core/model-runtime.js +4 -0
  38. package/dist/core/model-runtime.js.map +1 -1
  39. package/dist/core/settings-manager.d.ts +4 -7
  40. package/dist/core/settings-manager.d.ts.map +1 -1
  41. package/dist/core/settings-manager.js +7 -6
  42. package/dist/core/settings-manager.js.map +1 -1
  43. package/dist/core/tools/bash.js +1 -1
  44. package/dist/core/tools/bash.js.map +1 -1
  45. package/dist/core/tools/shell-execution.d.ts.map +1 -1
  46. package/dist/core/tools/shell-execution.js +3 -1
  47. package/dist/core/tools/shell-execution.js.map +1 -1
  48. package/dist/extensions/background/manager.d.ts +8 -5
  49. package/dist/extensions/background/manager.d.ts.map +1 -1
  50. package/dist/extensions/background/manager.js +115 -39
  51. package/dist/extensions/background/manager.js.map +1 -1
  52. package/dist/extensions/background/task-view.d.ts +5 -0
  53. package/dist/extensions/background/task-view.d.ts.map +1 -1
  54. package/dist/extensions/background/task-view.js +4 -0
  55. package/dist/extensions/background/task-view.js.map +1 -1
  56. package/dist/extensions/btw/controller.d.ts +1 -1
  57. package/dist/extensions/btw/controller.d.ts.map +1 -1
  58. package/dist/extensions/btw/controller.js +4 -4
  59. package/dist/extensions/btw/controller.js.map +1 -1
  60. package/dist/extensions/btw/index.js +3 -3
  61. package/dist/extensions/btw/index.js.map +1 -1
  62. package/dist/extensions/index.js +2 -2
  63. package/dist/extensions/index.js.map +1 -1
  64. package/dist/extensions/provider/catalog.d.ts +57 -0
  65. package/dist/extensions/provider/catalog.d.ts.map +1 -0
  66. package/dist/extensions/provider/catalog.js +181 -0
  67. package/dist/extensions/provider/catalog.js.map +1 -0
  68. package/dist/extensions/provider/compat-fields.d.ts +25 -0
  69. package/dist/extensions/provider/compat-fields.d.ts.map +1 -0
  70. package/dist/extensions/provider/compat-fields.js +148 -0
  71. package/dist/extensions/provider/compat-fields.js.map +1 -0
  72. package/dist/extensions/provider/configuration.d.ts +8 -0
  73. package/dist/extensions/provider/configuration.d.ts.map +1 -0
  74. package/dist/extensions/provider/configuration.js +21 -0
  75. package/dist/extensions/provider/configuration.js.map +1 -0
  76. package/dist/extensions/provider/connection.d.ts +14 -0
  77. package/dist/extensions/provider/connection.d.ts.map +1 -0
  78. package/dist/extensions/provider/connection.js +86 -0
  79. package/dist/extensions/provider/connection.js.map +1 -0
  80. package/dist/extensions/provider/constants.d.ts +38 -0
  81. package/dist/extensions/provider/constants.d.ts.map +1 -0
  82. package/dist/extensions/provider/constants.js +75 -0
  83. package/dist/extensions/provider/constants.js.map +1 -0
  84. package/dist/extensions/provider/index.d.ts +4 -0
  85. package/dist/extensions/provider/index.d.ts.map +1 -0
  86. package/dist/extensions/provider/index.js +65 -0
  87. package/dist/extensions/provider/index.js.map +1 -0
  88. package/dist/extensions/provider/probe.d.ts +34 -0
  89. package/dist/extensions/provider/probe.d.ts.map +1 -0
  90. package/dist/extensions/provider/probe.js +178 -0
  91. package/dist/extensions/provider/probe.js.map +1 -0
  92. package/dist/extensions/provider/refresh.d.ts +30 -0
  93. package/dist/extensions/provider/refresh.d.ts.map +1 -0
  94. package/dist/extensions/provider/refresh.js +66 -0
  95. package/dist/extensions/provider/refresh.js.map +1 -0
  96. package/dist/extensions/provider/store.d.ts +131 -0
  97. package/dist/extensions/provider/store.d.ts.map +1 -0
  98. package/dist/extensions/provider/store.js +503 -0
  99. package/dist/extensions/provider/store.js.map +1 -0
  100. package/dist/extensions/provider/ui/app.d.ts +25 -0
  101. package/dist/extensions/provider/ui/app.d.ts.map +1 -0
  102. package/dist/extensions/provider/ui/app.js +153 -0
  103. package/dist/extensions/provider/ui/app.js.map +1 -0
  104. package/dist/extensions/provider/ui/builtin-data.d.ts +53 -0
  105. package/dist/extensions/provider/ui/builtin-data.d.ts.map +1 -0
  106. package/dist/extensions/provider/ui/builtin-data.js +315 -0
  107. package/dist/extensions/provider/ui/builtin-data.js.map +1 -0
  108. package/dist/extensions/provider/ui/compat.d.ts +57 -0
  109. package/dist/extensions/provider/ui/compat.d.ts.map +1 -0
  110. package/dist/extensions/provider/ui/compat.js +427 -0
  111. package/dist/extensions/provider/ui/compat.js.map +1 -0
  112. package/dist/extensions/provider/ui/dialogs.d.ts +30 -0
  113. package/dist/extensions/provider/ui/dialogs.d.ts.map +1 -0
  114. package/dist/extensions/provider/ui/dialogs.js +89 -0
  115. package/dist/extensions/provider/ui/dialogs.js.map +1 -0
  116. package/dist/extensions/provider/ui/dictionary.d.ts +29 -0
  117. package/dist/extensions/provider/ui/dictionary.d.ts.map +1 -0
  118. package/dist/extensions/provider/ui/dictionary.js +385 -0
  119. package/dist/extensions/provider/ui/dictionary.js.map +1 -0
  120. package/dist/extensions/provider/ui/editor.d.ts +91 -0
  121. package/dist/extensions/provider/ui/editor.d.ts.map +1 -0
  122. package/dist/extensions/provider/ui/editor.js +667 -0
  123. package/dist/extensions/provider/ui/editor.js.map +1 -0
  124. package/dist/extensions/provider/ui/fetch-models.d.ts +39 -0
  125. package/dist/extensions/provider/ui/fetch-models.d.ts.map +1 -0
  126. package/dist/extensions/provider/ui/fetch-models.js +320 -0
  127. package/dist/extensions/provider/ui/fetch-models.js.map +1 -0
  128. package/dist/extensions/provider/ui/model-fields.d.ts +43 -0
  129. package/dist/extensions/provider/ui/model-fields.d.ts.map +1 -0
  130. package/dist/extensions/provider/ui/model-fields.js +441 -0
  131. package/dist/extensions/provider/ui/model-fields.js.map +1 -0
  132. package/dist/extensions/provider/ui/model-options.d.ts +93 -0
  133. package/dist/extensions/provider/ui/model-options.d.ts.map +1 -0
  134. package/dist/extensions/provider/ui/model-options.js +529 -0
  135. package/dist/extensions/provider/ui/model-options.js.map +1 -0
  136. package/dist/extensions/provider/ui/pane.d.ts +81 -0
  137. package/dist/extensions/provider/ui/pane.d.ts.map +1 -0
  138. package/dist/extensions/provider/ui/pane.js +3 -0
  139. package/dist/extensions/provider/ui/pane.js.map +1 -0
  140. package/dist/extensions/provider/ui/provider-fields.d.ts +60 -0
  141. package/dist/extensions/provider/ui/provider-fields.d.ts.map +1 -0
  142. package/dist/extensions/provider/ui/provider-fields.js +326 -0
  143. package/dist/extensions/provider/ui/provider-fields.js.map +1 -0
  144. package/dist/extensions/provider/ui/provider-list.d.ts +34 -0
  145. package/dist/extensions/provider/ui/provider-list.d.ts.map +1 -0
  146. package/dist/extensions/provider/ui/provider-list.js +162 -0
  147. package/dist/extensions/provider/ui/provider-list.js.map +1 -0
  148. package/dist/extensions/provider/ui/session.d.ts +20 -0
  149. package/dist/extensions/provider/ui/session.d.ts.map +1 -0
  150. package/dist/extensions/provider/ui/session.js +52 -0
  151. package/dist/extensions/provider/ui/session.js.map +1 -0
  152. package/dist/extensions/provider/ui/thinking-map.d.ts +20 -0
  153. package/dist/extensions/provider/ui/thinking-map.d.ts.map +1 -0
  154. package/dist/extensions/provider/ui/thinking-map.js +166 -0
  155. package/dist/extensions/provider/ui/thinking-map.js.map +1 -0
  156. package/dist/extensions/provider/ui/value-row.d.ts +88 -0
  157. package/dist/extensions/provider/ui/value-row.d.ts.map +1 -0
  158. package/dist/extensions/provider/ui/value-row.js +158 -0
  159. package/dist/extensions/provider/ui/value-row.js.map +1 -0
  160. package/dist/extensions/statusline/index.js +2 -2
  161. package/dist/extensions/statusline/index.js.map +1 -1
  162. package/dist/extensions/subagent/index.d.ts.map +1 -1
  163. package/dist/extensions/subagent/index.js +4 -2
  164. package/dist/extensions/subagent/index.js.map +1 -1
  165. package/dist/extensions/subagent/resolve.d.ts +5 -0
  166. package/dist/extensions/subagent/resolve.d.ts.map +1 -1
  167. package/dist/extensions/subagent/resolve.js +15 -7
  168. package/dist/extensions/subagent/resolve.js.map +1 -1
  169. package/dist/extensions/subagent/schema.d.ts +2 -0
  170. package/dist/extensions/subagent/schema.d.ts.map +1 -1
  171. package/dist/extensions/subagent/schema.js +1 -0
  172. package/dist/extensions/subagent/schema.js.map +1 -1
  173. package/dist/modes/interactive/components/tool-execution.d.ts +10 -0
  174. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  175. package/dist/modes/interactive/components/tool-execution.js +20 -2
  176. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  177. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  178. package/dist/modes/interactive/interactive-mode.js +6 -1
  179. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  180. package/dist/rpc-entry.js +94 -91
  181. package/docs/bundled/README.md +1 -1
  182. package/docs/bundled/extensions/background.md +5 -5
  183. package/docs/bundled/extensions/provider.md +117 -0
  184. package/docs/bundled/extensions/statusline.md +1 -1
  185. package/docs/bundled/extensions/subagent.md +7 -3
  186. package/docs/compaction.md +16 -6
  187. package/docs/docs.json +2 -2
  188. package/docs/keybindings.md +3 -0
  189. package/docs/settings.md +11 -7
  190. package/npm-shrinkwrap.json +2 -2
  191. package/package.json +1 -1
  192. package/dist/extensions/router/constants.d.ts +0 -23
  193. package/dist/extensions/router/constants.d.ts.map +0 -1
  194. package/dist/extensions/router/constants.js +0 -30
  195. package/dist/extensions/router/constants.js.map +0 -1
  196. package/dist/extensions/router/dialog-host.d.ts +0 -60
  197. package/dist/extensions/router/dialog-host.d.ts.map +0 -1
  198. package/dist/extensions/router/dialog-host.js +0 -196
  199. package/dist/extensions/router/dialog-host.js.map +0 -1
  200. package/dist/extensions/router/dialog.d.ts +0 -45
  201. package/dist/extensions/router/dialog.d.ts.map +0 -1
  202. package/dist/extensions/router/dialog.js +0 -378
  203. package/dist/extensions/router/dialog.js.map +0 -1
  204. package/dist/extensions/router/identity.d.ts +0 -15
  205. package/dist/extensions/router/identity.d.ts.map +0 -1
  206. package/dist/extensions/router/identity.js +0 -173
  207. package/dist/extensions/router/identity.js.map +0 -1
  208. package/dist/extensions/router/index.d.ts +0 -15
  209. package/dist/extensions/router/index.d.ts.map +0 -1
  210. package/dist/extensions/router/index.js +0 -70
  211. package/dist/extensions/router/index.js.map +0 -1
  212. package/dist/extensions/router/presets.d.ts +0 -51
  213. package/dist/extensions/router/presets.d.ts.map +0 -1
  214. package/dist/extensions/router/presets.js +0 -108
  215. package/dist/extensions/router/presets.js.map +0 -1
  216. package/dist/extensions/router/probe.d.ts +0 -26
  217. package/dist/extensions/router/probe.d.ts.map +0 -1
  218. package/dist/extensions/router/probe.js +0 -216
  219. package/dist/extensions/router/probe.js.map +0 -1
  220. package/dist/extensions/router/register.d.ts +0 -12
  221. package/dist/extensions/router/register.d.ts.map +0 -1
  222. package/dist/extensions/router/register.js +0 -90
  223. package/dist/extensions/router/register.js.map +0 -1
  224. package/dist/extensions/router/state.d.ts +0 -20
  225. package/dist/extensions/router/state.d.ts.map +0 -1
  226. package/dist/extensions/router/state.js +0 -169
  227. package/dist/extensions/router/state.js.map +0 -1
  228. package/dist/extensions/router/store.d.ts +0 -12
  229. package/dist/extensions/router/store.d.ts.map +0 -1
  230. package/dist/extensions/router/store.js +0 -266
  231. package/dist/extensions/router/store.js.map +0 -1
  232. package/dist/extensions/router/stream.d.ts +0 -12
  233. package/dist/extensions/router/stream.d.ts.map +0 -1
  234. package/dist/extensions/router/stream.js +0 -233
  235. package/dist/extensions/router/stream.js.map +0 -1
  236. package/dist/extensions/router/transport.d.ts +0 -9
  237. package/dist/extensions/router/transport.d.ts.map +0 -1
  238. package/dist/extensions/router/transport.js +0 -81
  239. package/dist/extensions/router/transport.js.map +0 -1
  240. package/dist/extensions/router/types.d.ts +0 -39
  241. package/dist/extensions/router/types.d.ts.map +0 -1
  242. package/dist/extensions/router/types.js +0 -2
  243. package/dist/extensions/router/types.js.map +0 -1
  244. package/dist/extensions/router/ui.d.ts +0 -26
  245. package/dist/extensions/router/ui.d.ts.map +0 -1
  246. package/dist/extensions/router/ui.js +0 -897
  247. package/dist/extensions/router/ui.js.map +0 -1
  248. package/docs/bundled/extensions/router.md +0 -197
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/core/background/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,eAA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EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { parseBackgroundHistory } from \"./history.ts\";\nimport { BACKGROUND_TITLE_BYTES, boundedResult, boundText, finiteLimit, readOutputSlice, sliceText } from \"./output.ts\";\nimport { readBackgroundProjection } from \"./presentation.ts\";\nimport {\n\ttype BackgroundCompletion,\n\ttype BackgroundContext,\n\ttype BackgroundControl,\n\ttype BackgroundExecution,\n\tBackgroundExecutionError,\n\ttype BackgroundRead,\n\ttype BackgroundServiceOptions,\n\ttype BackgroundTask,\n\ttype BackgroundToolOutcome,\n\tSUBAGENT_BACKGROUND_REJECTION,\n} from \"./types.ts\";\n\ninterface RecordState {\n\ttask: BackgroundTask;\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tsettled: boolean;\n\taccounted: boolean;\n\tvisible: boolean;\n\tsuppressed: boolean;\n\tdelivery: \"pending\" | \"claimed\" | \"delivered\";\n\tpins: number;\n\tcleanup?: () => void | Promise<void>;\n\treadError?: string;\n\tpublishedUsage?: Usage;\n\twaiters: Set<() => void>;\n\tremoveParent: () => void;\n\thandoff: () => void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Background execution failed (unprintable error)\";\n\t}\n}\n\nfunction storeResult(task: BackgroundTask, result: AgentToolResult<unknown>, truncated = false): void {\n\tconst bounded = boundedResult(result);\n\ttask.result = bounded;\n\ttask.resultTruncated =\n\t\ttruncated ||\n\t\tbounded.content.length !== result.content.length ||\n\t\tbounded.content.some((block, index) => {\n\t\t\tconst original = result.content[index];\n\t\t\treturn original?.type !== \"text\" || block.type !== \"text\" || block.text !== original.text;\n\t\t});\n}\n\n/** Session-local supervision. Executors own their processes, workers and output files. */\nexport class BackgroundService implements BackgroundContext {\n\tprivate readonly records = new Map<string, RecordState>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate readonly cleanups = new Set<Promise<void>>();\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\tprivate pauses = 0;\n\n\tprivate readonly options: BackgroundServiceOptions;\n\n\tconstructor(options: BackgroundServiceOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory);\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt first (later input\n\t * wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored, including for worker projections.\n\t * The host supplies the current branch; closed services ignore restoration.\n\t */\n\trestoreHistory(records: readonly unknown[]): void {\n\t\tif (this.closed) return;\n\t\t// Restoration must not evict runtime-owned records or run their cleanup callbacks.\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(\n\t\t\t\tthis.maxHistory - this.historyRecords().length,\n\t\t\t\tthis.maxRetained - this.records.size - this.cleanups.size,\n\t\t\t),\n\t\t);\n\t\tconst newest = new Map<string, BackgroundTask>();\n\t\tfor (const value of records) {\n\t\t\tconst task = parseBackgroundHistory(value);\n\t\t\tif (!task) continue;\n\t\t\tconst existing = this.records.get(task.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.settled) existing.visible = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (capacity === 0) continue;\n\t\t\tconst previous = newest.get(task.id);\n\t\t\tif (previous && previous.endedAt! > task.endedAt!) continue;\n\t\t\tnewest.delete(task.id);\n\t\t\tnewest.set(task.id, task);\n\t\t\tif (newest.size > capacity) {\n\t\t\t\tlet oldest: BackgroundTask | undefined;\n\t\t\t\tfor (const candidate of newest.values()) {\n\t\t\t\t\tif (!oldest || candidate.endedAt! < oldest.endedAt!) oldest = candidate;\n\t\t\t\t}\n\t\t\t\tnewest.delete(oldest!.id);\n\t\t\t}\n\t\t}\n\t\tfor (const task of [...newest.values()].sort((a, b) => a.endedAt! - b.endedAt!)) {\n\t\t\tthis.records.set(task.id, {\n\t\t\t\ttask,\n\t\t\t\tcontroller: new AbortController(),\n\t\t\t\taccepted: false,\n\t\t\t\thandedOff: false,\n\t\t\t\tdetachRequested: false,\n\t\t\t\tsettled: true,\n\t\t\t\taccounted: true,\n\t\t\t\tvisible: true,\n\t\t\t\tsuppressed: true,\n\t\t\t\tdelivery: \"delivered\",\n\t\t\t\tpins: 0,\n\t\t\t\twaiters: new Set(),\n\t\t\t\tremoveParent: () => {},\n\t\t\t\thandoff: () => {},\n\t\t\t\tdone: Promise.resolve(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.role !== \"subagent\";\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\tasync execute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (this.options.role === \"subagent\") throw new Error(SUBAGENT_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Background service is closed\");\n\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif ([...this.records.values()].filter((record) => !record.settled).length >= this.maxActive) {\n\t\t\tthrow new Error(`Background execution limit reached (${this.maxActive})`);\n\t\t}\n\t\tif (this.records.size + this.cleanups.size >= this.maxRetained) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Background history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t);\n\t\t}\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192)\n\t\t\tthrow new Error(\"Background branch anchor is too large\");\n\t\tconst task: BackgroundTask = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, BACKGROUND_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t};\n\t\tlet resolveCaller!: (outcome: BackgroundToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<BackgroundToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: RecordState = {\n\t\t\ttask,\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tsettled: false,\n\t\t\taccounted: false,\n\t\t\tvisible: true,\n\t\t\tsuppressed: false,\n\t\t\tdelivery: \"pending\",\n\t\t\tpins: 0,\n\t\t\twaiters: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!record.accepted ||\n\t\t\t\t\t!record.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\trecord.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\trecord.suppressed ||\n\t\t\t\t\trecord.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\trecord.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\trecord.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: this.snapshot(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!record.detachRequested || !record.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\trecord.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.records.set(task.id, record);\n\t\tconst control: BackgroundControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: record.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || record.accepted || this.closed || record.controller.signal.aborted) return;\n\t\t\t\trecord.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tif (record.detachRequested) record.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(record.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result, projection) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tstoreResult(task, result);\n\t\t\t\tif (result.usage !== undefined) record.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (projection) task.projection = readBackgroundProjection(projection);\n\t\t\t\tif (!record.detachRequested && !record.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Background execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Background output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: BackgroundCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\trecord.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof BackgroundExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: record.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tstoreResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tthis.snapshot(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? record.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\trecord.publishedUsage = undefined;\n\t\t\trecord.accounted = true;\n\t\t\tif (!record.handedOff) {\n\t\t\t\trecord.delivery = \"delivered\";\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst records = [...this.records.values()].filter(\n\t\t\t(record) => !record.settled && !record.detachRequested && !record.controller.signal.aborted,\n\t\t);\n\t\t// Update the whole batch before callbacks/observers can re-enter.\n\t\tfor (const record of records) {\n\t\t\trecord.detachRequested = true;\n\t\t\trecord.task.mode = \"background\";\n\t\t\tif (record.accepted) record.removeParent();\n\t\t}\n\t\tfor (const record of records) record.handoff();\n\t\tif (records.length) this.emit();\n\t\treturn records.length;\n\t}\n\n\tlist(): BackgroundTask[] {\n\t\treturn [...this.records.values()].filter((record) => record.visible).map((record) => this.snapshot(record));\n\t}\n\n\tprivate lookup(id: string): RecordState {\n\t\tconst exact = this.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1)\n\t\t\tthrow new Error(matches.length > 1 ? \"Ambiguous background task ID\" : \"Unknown background task ID\");\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): BackgroundTask {\n\t\treturn this.snapshot(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<BackgroundRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.pin(record.task.id);\n\t\ttry {\n\t\t\tconst task = this.snapshot(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: BackgroundTask): string {\n\t\treturn boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.projection?.text ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(id: string, timeoutMs = 20_000, signal?: AbortSignal): Promise<BackgroundTask> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return this.snapshot(record);\n\t\treturn new Promise<BackgroundTask>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\trecord.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve(this.snapshot(record));\n\t\t\t\tthis.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\trecord.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, 20_000, 60_000));\n\t\t\tif (this.closed) wake();\n\t\t});\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: RecordState): boolean {\n\t\tif (record.settled || record.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\trecord.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tpin(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.trim();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): BackgroundTask[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.records.values()]\n\t\t\t.filter((record) => this.candidate(record))\n\t\t\t.map((record) => this.snapshot(record));\n\t}\n\n\tprivate candidate(record: RecordState): boolean {\n\t\treturn (\n\t\t\trecord.visible &&\n\t\t\trecord.settled &&\n\t\t\trecord.accounted &&\n\t\t\trecord.handedOff &&\n\t\t\t!record.suppressed &&\n\t\t\trecord.delivery === \"pending\" &&\n\t\t\trecord.waiters.size === 0\n\t\t);\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.suppressed = true;\n\t\t\trecord.removeParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.records.values()], graceMs);\n\t}\n\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\t\t// Returning to a branch revives its undelivered completions; restored history\n\t\t\t// stays delivered and suppressed.\n\t\t\tif (record.visible && record.delivery === \"pending\") record.suppressed = false;\n\t\t}\n\t\tconst outside = [...this.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) record.suppressed = true;\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: RecordState[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => record.done)).then(() => Promise.all(this.cleanups)),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate snapshot(record: RecordState): BackgroundTask {\n\t\treturn structuredClone(record.task);\n\t}\n\n\tprivate cleanupOutput(record: RecordState): void {\n\t\tif (!record.settled || record.pins || record.waiters.size || !record.cleanup) return;\n\t\tconst cleanup = record.cleanup;\n\t\trecord.cleanup = undefined;\n\t\t// Snapshots retain final bounded text; expired files are never needed to render history.\n\t\trecord.task.outputPath = undefined;\n\t\trecord.readError = \"Output has expired: the managed log was released; showing the stored result.\";\n\t\tconst pending = Promise.resolve()\n\t\t\t.then(cleanup)\n\t\t\t.catch((error: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onCleanupError?.(errorText(error));\n\t\t\t\t} catch {\n\t\t\t\t\t/* Cleanup/reporting is best effort, never an unhandled rejection. */\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => this.cleanups.delete(pending));\n\t\tthis.cleanups.add(pending);\n\t}\n\n\t/** Pending delivery, active reads and pins have their own bounded retention allowance. */\n\tprivate historyRecords(): RecordState[] {\n\t\treturn [...this.records.values()].filter(\n\t\t\t(record) => record.settled && record.delivery === \"delivered\" && !record.pins && !record.waiters.size,\n\t\t);\n\t}\n\n\tprivate trim(): void {\n\t\tif (this.closed) {\n\t\t\tfor (const record of this.records.values()) this.cleanupOutput(record);\n\t\t\treturn;\n\t\t}\n\t\t// Undelivered notifications and claims are never evicted. Admission bounds all retention.\n\t\tconst history = this.historyRecords();\n\t\t// Delivered history can be restored from branch snapshots; hidden rows must\n\t\t// not occupy the current branch's history budget. Pending results stay owned.\n\t\tconst hidden = history.filter((record) => !record.visible);\n\t\tconst visible = history.filter((record) => record.visible);\n\t\tvisible.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0));\n\t\tfor (const record of [...hidden, ...visible.slice(0, Math.max(0, visible.length - this.maxHistory))]) {\n\t\t\tthis.records.delete(record.task.id);\n\t\t\tthis.cleanupOutput(record);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/core/background/service.ts"],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AAC;QACD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC9B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACpC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;IACF,CAAC;IAEO,IAAI;QACX,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,KAAK,MAAM,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5C,IAAI,IAAI,CAAC,MAAM;gBAAE,MAAM;YACvB,IAAI,CAAC;gBACJ,QAAQ,EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { parseBackgroundHistory } from \"./history.ts\";\nimport { BACKGROUND_TITLE_BYTES, boundedResult, boundText, finiteLimit, readOutputSlice, sliceText } from \"./output.ts\";\nimport { readBackgroundProjection } from \"./presentation.ts\";\nimport {\n\ttype BackgroundCompletion,\n\ttype BackgroundContext,\n\ttype BackgroundControl,\n\ttype BackgroundExecution,\n\tBackgroundExecutionError,\n\ttype BackgroundRead,\n\ttype BackgroundServiceOptions,\n\ttype BackgroundTask,\n\ttype BackgroundToolOutcome,\n\tisForegroundShellTask,\n\tSUBAGENT_BACKGROUND_REJECTION,\n} from \"./types.ts\";\n\ninterface RecordState {\n\ttask: BackgroundTask;\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tsettled: boolean;\n\taccounted: boolean;\n\tvisible: boolean;\n\tsuppressed: boolean;\n\tdelivery: \"pending\" | \"claimed\" | \"delivered\";\n\tpins: number;\n\tcleanup?: () => void | Promise<void>;\n\treadError?: string;\n\tpublishedUsage?: Usage;\n\twaiters: Set<() => void>;\n\tremoveParent: () => void;\n\thandoff: () => void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Background execution failed (unprintable error)\";\n\t}\n}\n\nfunction storeResult(task: BackgroundTask, result: AgentToolResult<unknown>, truncated = false): void {\n\tconst bounded = boundedResult(result);\n\ttask.result = bounded;\n\ttask.resultTruncated =\n\t\ttruncated ||\n\t\tbounded.content.length !== result.content.length ||\n\t\tbounded.content.some((block, index) => {\n\t\t\tconst original = result.content[index];\n\t\t\treturn original?.type !== \"text\" || block.type !== \"text\" || block.text !== original.text;\n\t\t});\n}\n\nfunction oldestTask(tasks: Iterable<BackgroundTask>): BackgroundTask | undefined {\n\tlet oldest: BackgroundTask | undefined;\n\tfor (const task of tasks) {\n\t\tif (!oldest || task.endedAt! < oldest.endedAt!) oldest = task;\n\t}\n\treturn oldest;\n}\n\n/** Session-local supervision. Executors own their processes, workers and output files. */\nexport class BackgroundService implements BackgroundContext {\n\tprivate readonly records = new Map<string, RecordState>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate readonly cleanups = new Set<Promise<void>>();\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\tprivate pauses = 0;\n\n\tprivate readonly options: BackgroundServiceOptions;\n\n\tconstructor(options: BackgroundServiceOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground shell history, plus the existing history/protected-record allowance.\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt in each history\n\t * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored, including for worker projections.\n\t * The host supplies the current branch; closed services ignore restoration.\n\t */\n\trestoreHistory(records: readonly unknown[]): void {\n\t\tif (this.closed) return;\n\t\t// Restoration must not evict runtime-owned records or run their cleanup callbacks.\n\t\tconst history = this.historyRecords();\n\t\tconst shells = history.filter((record) => isForegroundShellTask(record.task)).length;\n\t\tconst shellCapacity = Math.max(0, this.maxHistory - shells);\n\t\tconst taskCapacity = Math.max(0, this.maxHistory - (history.length - shells));\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(shellCapacity + taskCapacity, this.maxRetained - this.records.size - this.cleanups.size),\n\t\t);\n\t\tconst newest = new Map<string, BackgroundTask>();\n\t\tfor (const value of records) {\n\t\t\tconst task = parseBackgroundHistory(value);\n\t\t\tif (!task) continue;\n\t\t\tconst existing = this.records.get(task.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.settled) existing.visible = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (capacity === 0) continue;\n\t\t\tconst previous = newest.get(task.id);\n\t\t\tif (previous && previous.endedAt! > task.endedAt!) continue;\n\t\t\tnewest.delete(task.id);\n\t\t\tconst shell = isForegroundShellTask(task);\n\t\t\tconst limit = shell ? shellCapacity : taskCapacity;\n\t\t\tif (limit === 0) continue;\n\t\t\tnewest.set(task.id, task);\n\t\t\tconst group = [...newest.values()].filter((candidate) => isForegroundShellTask(candidate) === shell);\n\t\t\tif (group.length > limit) newest.delete(oldestTask(group)!.id);\n\t\t\tif (newest.size > capacity) {\n\t\t\t\t// Protected runtime records can leave less room than both histories allow.\n\t\t\t\t// Restore inspectable tasks before hidden foreground shell logs in that case.\n\t\t\t\tconst foreground = [...newest.values()].filter(isForegroundShellTask);\n\t\t\t\tnewest.delete(oldestTask(foreground.length ? foreground : newest.values())!.id);\n\t\t\t}\n\t\t}\n\t\tfor (const task of [...newest.values()].sort((a, b) => a.endedAt! - b.endedAt!)) {\n\t\t\tthis.records.set(task.id, {\n\t\t\t\ttask,\n\t\t\t\tcontroller: new AbortController(),\n\t\t\t\taccepted: false,\n\t\t\t\thandedOff: false,\n\t\t\t\tdetachRequested: false,\n\t\t\t\tsettled: true,\n\t\t\t\taccounted: true,\n\t\t\t\tvisible: true,\n\t\t\t\tsuppressed: true,\n\t\t\t\tdelivery: \"delivered\",\n\t\t\t\tpins: 0,\n\t\t\t\twaiters: new Set(),\n\t\t\t\tremoveParent: () => {},\n\t\t\t\thandoff: () => {},\n\t\t\t\tdone: Promise.resolve(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.role !== \"subagent\";\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\tasync execute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (this.options.role === \"subagent\") throw new Error(SUBAGENT_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Background service is closed\");\n\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif ([...this.records.values()].filter((record) => !record.settled).length >= this.maxActive) {\n\t\t\tthrow new Error(`Background execution limit reached (${this.maxActive})`);\n\t\t}\n\t\tif (this.records.size + this.cleanups.size >= this.maxRetained) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Background history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t);\n\t\t}\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192)\n\t\t\tthrow new Error(\"Background branch anchor is too large\");\n\t\tconst task: BackgroundTask = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, BACKGROUND_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t};\n\t\tlet resolveCaller!: (outcome: BackgroundToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<BackgroundToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: RecordState = {\n\t\t\ttask,\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tsettled: false,\n\t\t\taccounted: false,\n\t\t\tvisible: true,\n\t\t\tsuppressed: false,\n\t\t\tdelivery: \"pending\",\n\t\t\tpins: 0,\n\t\t\twaiters: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!record.accepted ||\n\t\t\t\t\t!record.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\trecord.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\trecord.suppressed ||\n\t\t\t\t\trecord.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\trecord.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\trecord.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: this.snapshot(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!record.detachRequested || !record.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\trecord.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.records.set(task.id, record);\n\t\tconst control: BackgroundControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: record.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || record.accepted || this.closed || record.controller.signal.aborted) return;\n\t\t\t\trecord.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tif (record.detachRequested) record.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(record.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result, projection) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tstoreResult(task, result);\n\t\t\t\tif (result.usage !== undefined) record.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (projection) task.projection = readBackgroundProjection(projection);\n\t\t\t\tif (!record.detachRequested && !record.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Background execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Background output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: BackgroundCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\trecord.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof BackgroundExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: record.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tstoreResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t\tif (completion.exitCode !== undefined) task.exitCode = completion.exitCode;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tthis.snapshot(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? record.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\trecord.publishedUsage = undefined;\n\t\t\trecord.accounted = true;\n\t\t\tif (!record.handedOff) {\n\t\t\t\trecord.delivery = \"delivered\";\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst records = [...this.records.values()].filter(\n\t\t\t(record) => !record.settled && !record.detachRequested && !record.controller.signal.aborted,\n\t\t);\n\t\t// Update the whole batch before callbacks/observers can re-enter.\n\t\tfor (const record of records) {\n\t\t\trecord.detachRequested = true;\n\t\t\trecord.task.mode = \"background\";\n\t\t\tif (record.accepted) record.removeParent();\n\t\t}\n\t\tfor (const record of records) record.handoff();\n\t\tif (records.length) this.emit();\n\t\treturn records.length;\n\t}\n\n\tlist(): BackgroundTask[] {\n\t\treturn [...this.records.values()].filter((record) => record.visible).map((record) => this.snapshot(record));\n\t}\n\n\tprivate lookup(id: string): RecordState {\n\t\tconst exact = this.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1)\n\t\t\tthrow new Error(matches.length > 1 ? \"Ambiguous background task ID\" : \"Unknown background task ID\");\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): BackgroundTask {\n\t\treturn this.snapshot(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<BackgroundRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.pin(record.task.id);\n\t\ttry {\n\t\t\tconst task = this.snapshot(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: BackgroundTask): string {\n\t\treturn boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.projection?.text ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(id: string, timeoutMs = 20_000, signal?: AbortSignal): Promise<BackgroundTask> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return this.snapshot(record);\n\t\treturn new Promise<BackgroundTask>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\trecord.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve(this.snapshot(record));\n\t\t\t\tthis.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\trecord.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, 20_000, 60_000));\n\t\t\tif (this.closed) wake();\n\t\t});\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: RecordState): boolean {\n\t\tif (record.settled || record.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\trecord.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tpin(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.trim();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): BackgroundTask[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.records.values()]\n\t\t\t.filter((record) => this.candidate(record))\n\t\t\t.map((record) => this.snapshot(record));\n\t}\n\n\tprivate candidate(record: RecordState): boolean {\n\t\treturn (\n\t\t\trecord.visible &&\n\t\t\trecord.settled &&\n\t\t\trecord.accounted &&\n\t\t\trecord.handedOff &&\n\t\t\t!record.suppressed &&\n\t\t\trecord.delivery === \"pending\" &&\n\t\t\trecord.waiters.size === 0\n\t\t);\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.suppressed = true;\n\t\t\trecord.removeParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.records.values()], graceMs);\n\t}\n\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\t\t// Returning to a branch revives its undelivered completions; restored history\n\t\t\t// stays delivered and suppressed.\n\t\t\tif (record.visible && record.delivery === \"pending\") record.suppressed = false;\n\t\t}\n\t\tconst outside = [...this.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) record.suppressed = true;\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: RecordState[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => record.done)).then(() => Promise.all(this.cleanups)),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate snapshot(record: RecordState): BackgroundTask {\n\t\treturn structuredClone(record.task);\n\t}\n\n\tprivate cleanupOutput(record: RecordState): void {\n\t\tif (!record.settled || record.pins || record.waiters.size || !record.cleanup) return;\n\t\tconst cleanup = record.cleanup;\n\t\trecord.cleanup = undefined;\n\t\t// Snapshots retain final bounded text; expired files are never needed to render history.\n\t\trecord.task.outputPath = undefined;\n\t\trecord.readError = \"Output has expired: the managed log was released; showing the stored result.\";\n\t\tconst pending = Promise.resolve()\n\t\t\t.then(cleanup)\n\t\t\t.catch((error: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onCleanupError?.(errorText(error));\n\t\t\t\t} catch {\n\t\t\t\t\t/* Cleanup/reporting is best effort, never an unhandled rejection. */\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => this.cleanups.delete(pending));\n\t\tthis.cleanups.add(pending);\n\t}\n\n\t/** Pending delivery, active reads and pins have their own bounded retention allowance. */\n\tprivate historyRecords(): RecordState[] {\n\t\treturn [...this.records.values()].filter(\n\t\t\t(record) => record.settled && record.delivery === \"delivered\" && !record.pins && !record.waiters.size,\n\t\t);\n\t}\n\n\tprivate trim(): void {\n\t\tif (this.closed) {\n\t\t\tfor (const record of this.records.values()) this.cleanupOutput(record);\n\t\t\treturn;\n\t\t}\n\t\t// Undelivered notifications and claims are never evicted. Admission bounds all retention.\n\t\tconst history = this.historyRecords();\n\t\t// Delivered history can be restored from branch snapshots; hidden rows must\n\t\t// not occupy the current branch's history budget. Pending results stay owned.\n\t\tconst expired = history.filter((record) => !record.visible);\n\t\tfor (const shell of [false, true]) {\n\t\t\tconst group = history.filter((record) => record.visible && isForegroundShellTask(record.task) === shell);\n\t\t\tgroup.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0));\n\t\t\texpired.push(...group.slice(0, Math.max(0, group.length - this.maxHistory)));\n\t\t}\n\t\tfor (const record of expired) {\n\t\t\tthis.records.delete(record.task.id);\n\t\t\tthis.cleanupOutput(record);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -49,6 +49,8 @@ export type BackgroundCompletionSnapshot = BackgroundCompletionBase & ({
49
49
  command?: BackgroundText;
50
50
  cwd?: string;
51
51
  outputPath?: string;
52
+ /** Process exit code: a number, or null when signal-reaped. */
53
+ exitCode?: number | null;
52
54
  output: BackgroundText;
53
55
  } | {
54
56
  kind: "subagent";
@@ -69,6 +71,8 @@ export interface BackgroundTask {
69
71
  command?: string;
70
72
  commandTruncated?: boolean;
71
73
  cwd?: string;
74
+ /** Process exit code (bash): a number, or null when signal-reaped. Absent while running or unreported. */
75
+ exitCode?: number | null;
72
76
  outputPath?: string;
73
77
  projection?: BackgroundProjection;
74
78
  result?: AgentToolResult<unknown>;
@@ -80,6 +84,8 @@ export interface BackgroundCompletion<T> {
80
84
  status?: BackgroundTerminalStatus;
81
85
  /** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */
82
86
  error?: string;
87
+ /** Process exit code (bash): a number, or null when signal-reaped. */
88
+ exitCode?: number | null;
83
89
  /** Authoritative cumulative usage; overrides result.usage and any published snapshot. */
84
90
  usage?: Usage;
85
91
  }
@@ -150,6 +156,7 @@ export interface BackgroundServiceOptions {
150
156
  role?: "main" | "subagent";
151
157
  anchor?: () => string | null;
152
158
  maxActive?: number;
159
+ /** Per-history limit: foreground shells and background tasks/all subagents each get this allowance. */
153
160
  maxHistory?: number;
154
161
  /** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */
155
162
  onCleanupError?: (message: string) => void;
@@ -158,6 +165,8 @@ export interface BackgroundServiceOptions {
158
165
  }
159
166
  export declare const SUBAGENT_BACKGROUND_REJECTION = "Background execution is not available inside subagents. Run this command with background: false (or omit background). Only the parent agent or the user can background the entire subagent invocation. No command was started.";
160
167
  export declare function isBackgroundTerminal(status: BackgroundStatus): boolean;
168
+ /** Foreground shell logs have their own history; subagent groups remain inspectable in either mode. */
169
+ export declare function isForegroundShellTask(task: Pick<BackgroundTask, "kind" | "mode">): boolean;
161
170
  /** Preserve the foreground throwing contract without guessing status from output text. */
162
171
  export declare class BackgroundExecutionError extends Error {
163
172
  readonly status: BackgroundTerminalStatus;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/core/background/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACr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MAAM,GAAG,UAAU,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uGAAuG;IACvG,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0FAA0F;IAC1F,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,0EAA0E;IAC1E,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,KAAK,GAAG,SAAS,KAAK,IAAI,CAAC;CACrE;AAED,eAAO,MAAM,6BAA6B,mOACuL,CAAC;AAElO,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAEtE;AAED,uGAAuG;AACvG,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAAC,GAAG,OAAO,CAE1F;AAED,0FAA0F;AAC1F,qBAAa,wBAAyB,SAAQ,KAAK;IAClD,QAAQ,CAAC,MAAM,EAAE,wBAAwB,CAAC;gBAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,wBAAwB;CAK7D"}
@@ -2,6 +2,10 @@ export const SUBAGENT_BACKGROUND_REJECTION = "Background execution is not availa
2
2
  export function isBackgroundTerminal(status) {
3
3
  return status !== "queued" && status !== "running" && status !== "stopping";
4
4
  }
5
+ /** Foreground shell logs have their own history; subagent groups remain inspectable in either mode. */
6
+ export function isForegroundShellTask(task) {
7
+ return task.kind === "bash" && task.mode === "foreground";
8
+ }
5
9
  /** Preserve the foreground throwing contract without guessing status from output text. */
6
10
  export class BackgroundExecutionError extends Error {
7
11
  constructor(message, status) {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/background/types.ts"],"names":[],"mappings":"AAqKA,MAAM,CAAC,MAAM,6BAA6B,GACzC,gOAAgO,CAAC;AAElO,MAAM,UAAU,oBAAoB,CAAC,MAAwB;IAC5D,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,UAAU,CAAC;AAC7E,CAAC;AAED,0FAA0F;AAC1F,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAElD,YAAY,OAAe,EAAE,MAAgC;QAC5D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\n\nexport type BackgroundKind = \"bash\" | \"subagent\";\nexport type BackgroundMode = \"foreground\" | \"background\";\nexport type BackgroundTerminalStatus = \"completed\" | \"partial\" | \"failed\" | \"cancelled\" | \"timeout\";\nexport type BackgroundStatus = \"queued\" | \"running\" | \"stopping\" | BackgroundTerminalStatus;\n\n/** A bounded snapshot; truncation is recorded at the source, never inferred from text. */\nexport interface BackgroundText {\n\ttext: string;\n\ttruncated: boolean;\n}\n\nexport interface BackgroundWorkerReport {\n\tid: string;\n\tlabel: string;\n\tprofile: string;\n\tdescription: string;\n\tstatus: string;\n\treport: BackgroundText;\n\terror?: string;\n}\n\n/** A serializable, domain-owned projection. No extension-private renderer imports. */\nexport interface BackgroundWorker extends BackgroundWorkerReport {\n\tprompt: string;\n\tactivity: string;\n\tmodel?: string;\n\tusage?: string;\n}\n\nexport interface BackgroundProjection {\n\ttext?: string;\n\tshell?: { name: string; output: BackgroundText };\n\tworkers?: BackgroundWorker[];\n}\n\ninterface BackgroundCompletionBase {\n\tversion: 1;\n\ttaskId: string;\n\ttitle: string;\n\tstatus: BackgroundTerminalStatus;\n\tstartedAt: number;\n\tendedAt: number;\n\terror?: string;\n}\n\n/** Self-contained completion-message details. No live handles, tool-private details or accounting. */\nexport type BackgroundCompletionSnapshot = BackgroundCompletionBase &\n\t(\n\t\t| {\n\t\t\t\tkind: \"bash\";\n\t\t\t\tshell?: string;\n\t\t\t\tcommand?: BackgroundText;\n\t\t\t\tcwd?: string;\n\t\t\t\toutputPath?: string;\n\t\t\t\toutput: BackgroundText;\n\t\t }\n\t\t| {\n\t\t\t\tkind: \"subagent\";\n\t\t\t\tworkers: BackgroundWorkerReport[];\n\t\t\t\t/** Plain fallback when an executor has no worker projection. */\n\t\t\t\toutput?: BackgroundText;\n\t\t }\n\t);\n\nexport interface BackgroundTask {\n\tid: string;\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tanchorId: string | null;\n\tmode: BackgroundMode;\n\tstatus: BackgroundStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\tcommand?: string;\n\tcommandTruncated?: boolean;\n\tcwd?: string;\n\toutputPath?: string;\n\tprojection?: BackgroundProjection;\n\tresult?: AgentToolResult<unknown>;\n\tresultTruncated?: boolean;\n\terror?: string;\n}\n\nexport interface BackgroundCompletion<T> {\n\tresult: AgentToolResult<T>;\n\tstatus?: BackgroundTerminalStatus;\n\t/** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */\n\terror?: string;\n\t/** Authoritative cumulative usage; overrides result.usage and any published snapshot. */\n\tusage?: Usage;\n}\n\nexport interface BackgroundControl<T> {\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\treadonly mode: BackgroundMode;\n\t/** Accept only after whole-invocation preflight; required before returning a handoff. */\n\taccept(): void;\n\t/**\n\t * result.usage is a cumulative snapshot, never a delta. The most recent explicitly\n\t * published usage is settled once on rejection (never inferred from details).\n\t * Final completion.usage, then completion.result.usage, override that snapshot.\n\t */\n\tpublish(result: AgentToolResult<T>, projection?: BackgroundProjection): void;\n\t/** Register once; cleanup must own only this exclusively-created file and close its writer first. */\n\tsetOutputPath(path: string, cleanup?: () => void | Promise<void>): void;\n}\n\nexport interface BackgroundExecution<T> {\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tcommand?: string;\n\tcwd?: string;\n\tbackground?: boolean;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<T>) => void;\n\trun(control: BackgroundControl<T>): Promise<BackgroundCompletion<T>>;\n}\n\nexport type BackgroundToolOutcome<T> =\n\t| { kind: \"result\"; result: AgentToolResult<T>; status?: BackgroundTerminalStatus; error?: string }\n\t| { kind: \"background\"; task: BackgroundTask };\n\nexport interface BackgroundRead {\n\ttask: BackgroundTask;\n\ttext: string;\n\t/** Bounded log-read/expiry diagnostic, independent of text slicing and byte offsets. */\n\treadError?: string;\n\ttotalBytes: number;\n\ttruncated: boolean;\n\tfromByte?: number;\n}\n\n/** Session-bound public capability. Captured instances close on runtime replacement. */\nexport interface BackgroundContext {\n\treadonly enabled: boolean;\n\treadonly closed?: boolean;\n\texecute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>>;\n\tlist(): BackgroundTask[];\n\tget(id: string): BackgroundTask;\n\tread(id: string, options?: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number }): Promise<BackgroundRead>;\n\t/** Observation only: terminal delivery is acknowledged by the host via markDelivered after result persistence. */\n\twait(id: string, timeoutMs?: number, signal?: AbortSignal): Promise<BackgroundTask>;\n\tkill(id: string): boolean;\n\tsubscribe(listener: () => void): () => void;\n\tpin(id: string): () => void;\n}\n\nexport interface BackgroundServiceOptions {\n\tenabled?: boolean;\n\trole?: \"main\" | \"subagent\";\n\tanchor?: () => string | null;\n\tmaxActive?: number;\n\tmaxHistory?: number;\n\t/** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */\n\tonCleanupError?: (message: string) => void;\n\t/** Synchronous persistence before terminal observers or notifications. */\n\tonSettled?: (task: BackgroundTask, usage: Usage | undefined) => void;\n}\n\nexport const SUBAGENT_BACKGROUND_REJECTION =\n\t\"Background execution is not available inside subagents. Run this command with background: false (or omit background). Only the parent agent or the user can background the entire subagent invocation. No command was started.\";\n\nexport function isBackgroundTerminal(status: BackgroundStatus): boolean {\n\treturn status !== \"queued\" && status !== \"running\" && status !== \"stopping\";\n}\n\n/** Preserve the foreground throwing contract without guessing status from output text. */\nexport class BackgroundExecutionError extends Error {\n\treadonly status: BackgroundTerminalStatus;\n\tconstructor(message: string, status: BackgroundTerminalStatus) {\n\t\tsuper(message);\n\t\tthis.name = \"BackgroundExecutionError\";\n\t\tthis.status = status;\n\t}\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/background/types.ts"],"names":[],"mappings":"AA4KA,MAAM,CAAC,MAAM,6BAA6B,GACzC,gOAAgO,CAAC;AAElO,MAAM,UAAU,oBAAoB,CAAC,MAAwB;IAC5D,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,UAAU,CAAC;AAC7E,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,qBAAqB,CAAC,IAA2C;IAChF,OAAO,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC;AAC3D,CAAC;AAED,0FAA0F;AAC1F,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAElD,YAAY,OAAe,EAAE,MAAgC;QAC5D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\n\nexport type BackgroundKind = \"bash\" | \"subagent\";\nexport type BackgroundMode = \"foreground\" | \"background\";\nexport type BackgroundTerminalStatus = \"completed\" | \"partial\" | \"failed\" | \"cancelled\" | \"timeout\";\nexport type BackgroundStatus = \"queued\" | \"running\" | \"stopping\" | BackgroundTerminalStatus;\n\n/** A bounded snapshot; truncation is recorded at the source, never inferred from text. */\nexport interface BackgroundText {\n\ttext: string;\n\ttruncated: boolean;\n}\n\nexport interface BackgroundWorkerReport {\n\tid: string;\n\tlabel: string;\n\tprofile: string;\n\tdescription: string;\n\tstatus: string;\n\treport: BackgroundText;\n\terror?: string;\n}\n\n/** A serializable, domain-owned projection. No extension-private renderer imports. */\nexport interface BackgroundWorker extends BackgroundWorkerReport {\n\tprompt: string;\n\tactivity: string;\n\tmodel?: string;\n\tusage?: string;\n}\n\nexport interface BackgroundProjection {\n\ttext?: string;\n\tshell?: { name: string; output: BackgroundText };\n\tworkers?: BackgroundWorker[];\n}\n\ninterface BackgroundCompletionBase {\n\tversion: 1;\n\ttaskId: string;\n\ttitle: string;\n\tstatus: BackgroundTerminalStatus;\n\tstartedAt: number;\n\tendedAt: number;\n\terror?: string;\n}\n\n/** Self-contained completion-message details. No live handles, tool-private details or accounting. */\nexport type BackgroundCompletionSnapshot = BackgroundCompletionBase &\n\t(\n\t\t| {\n\t\t\t\tkind: \"bash\";\n\t\t\t\tshell?: string;\n\t\t\t\tcommand?: BackgroundText;\n\t\t\t\tcwd?: string;\n\t\t\t\toutputPath?: string;\n\t\t\t\t/** Process exit code: a number, or null when signal-reaped. */\n\t\t\t\texitCode?: number | null;\n\t\t\t\toutput: BackgroundText;\n\t\t }\n\t\t| {\n\t\t\t\tkind: \"subagent\";\n\t\t\t\tworkers: BackgroundWorkerReport[];\n\t\t\t\t/** Plain fallback when an executor has no worker projection. */\n\t\t\t\toutput?: BackgroundText;\n\t\t }\n\t);\n\nexport interface BackgroundTask {\n\tid: string;\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tanchorId: string | null;\n\tmode: BackgroundMode;\n\tstatus: BackgroundStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\tcommand?: string;\n\tcommandTruncated?: boolean;\n\tcwd?: string;\n\t/** Process exit code (bash): a number, or null when signal-reaped. Absent while running or unreported. */\n\texitCode?: number | null;\n\toutputPath?: string;\n\tprojection?: BackgroundProjection;\n\tresult?: AgentToolResult<unknown>;\n\tresultTruncated?: boolean;\n\terror?: string;\n}\n\nexport interface BackgroundCompletion<T> {\n\tresult: AgentToolResult<T>;\n\tstatus?: BackgroundTerminalStatus;\n\t/** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */\n\terror?: string;\n\t/** Process exit code (bash): a number, or null when signal-reaped. */\n\texitCode?: number | null;\n\t/** Authoritative cumulative usage; overrides result.usage and any published snapshot. */\n\tusage?: Usage;\n}\n\nexport interface BackgroundControl<T> {\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\treadonly mode: BackgroundMode;\n\t/** Accept only after whole-invocation preflight; required before returning a handoff. */\n\taccept(): void;\n\t/**\n\t * result.usage is a cumulative snapshot, never a delta. The most recent explicitly\n\t * published usage is settled once on rejection (never inferred from details).\n\t * Final completion.usage, then completion.result.usage, override that snapshot.\n\t */\n\tpublish(result: AgentToolResult<T>, projection?: BackgroundProjection): void;\n\t/** Register once; cleanup must own only this exclusively-created file and close its writer first. */\n\tsetOutputPath(path: string, cleanup?: () => void | Promise<void>): void;\n}\n\nexport interface BackgroundExecution<T> {\n\tkind: BackgroundKind;\n\ttitle: string;\n\ttoolCallId: string;\n\tcommand?: string;\n\tcwd?: string;\n\tbackground?: boolean;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<T>) => void;\n\trun(control: BackgroundControl<T>): Promise<BackgroundCompletion<T>>;\n}\n\nexport type BackgroundToolOutcome<T> =\n\t| { kind: \"result\"; result: AgentToolResult<T>; status?: BackgroundTerminalStatus; error?: string }\n\t| { kind: \"background\"; task: BackgroundTask };\n\nexport interface BackgroundRead {\n\ttask: BackgroundTask;\n\ttext: string;\n\t/** Bounded log-read/expiry diagnostic, independent of text slicing and byte offsets. */\n\treadError?: string;\n\ttotalBytes: number;\n\ttruncated: boolean;\n\tfromByte?: number;\n}\n\n/** Session-bound public capability. Captured instances close on runtime replacement. */\nexport interface BackgroundContext {\n\treadonly enabled: boolean;\n\treadonly closed?: boolean;\n\texecute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>>;\n\tlist(): BackgroundTask[];\n\tget(id: string): BackgroundTask;\n\tread(id: string, options?: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number }): Promise<BackgroundRead>;\n\t/** Observation only: terminal delivery is acknowledged by the host via markDelivered after result persistence. */\n\twait(id: string, timeoutMs?: number, signal?: AbortSignal): Promise<BackgroundTask>;\n\tkill(id: string): boolean;\n\tsubscribe(listener: () => void): () => void;\n\tpin(id: string): () => void;\n}\n\nexport interface BackgroundServiceOptions {\n\tenabled?: boolean;\n\trole?: \"main\" | \"subagent\";\n\tanchor?: () => string | null;\n\tmaxActive?: number;\n\t/** Per-history limit: foreground shells and background tasks/all subagents each get this allowance. */\n\tmaxHistory?: number;\n\t/** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */\n\tonCleanupError?: (message: string) => void;\n\t/** Synchronous persistence before terminal observers or notifications. */\n\tonSettled?: (task: BackgroundTask, usage: Usage | undefined) => void;\n}\n\nexport const SUBAGENT_BACKGROUND_REJECTION =\n\t\"Background execution is not available inside subagents. Run this command with background: false (or omit background). Only the parent agent or the user can background the entire subagent invocation. No command was started.\";\n\nexport function isBackgroundTerminal(status: BackgroundStatus): boolean {\n\treturn status !== \"queued\" && status !== \"running\" && status !== \"stopping\";\n}\n\n/** Foreground shell logs have their own history; subagent groups remain inspectable in either mode. */\nexport function isForegroundShellTask(task: Pick<BackgroundTask, \"kind\" | \"mode\">): boolean {\n\treturn task.kind === \"bash\" && task.mode === \"foreground\";\n}\n\n/** Preserve the foreground throwing contract without guessing status from output text. */\nexport class BackgroundExecutionError extends Error {\n\treadonly status: BackgroundTerminalStatus;\n\tconstructor(message: string, status: BackgroundTerminalStatus) {\n\t\tsuper(message);\n\t\tthis.name = \"BackgroundExecutionError\";\n\t\tthis.status = status;\n\t}\n}\n"]}
@@ -8,7 +8,9 @@ import type { AgentMessage, StreamFn, ThinkingLevel } from "@earendil-works/pi-a
8
8
  import { type RetryCallbacks, type RetryPolicy } from "@earendil-works/pi-ai";
9
9
  import type { AssistantMessage, Context, Model, SimpleStreamOptions, Usage } from "@earendil-works/pi-ai/compat";
10
10
  import { type SessionEntry } from "../session-manager.ts";
11
+ import { type CompactionSettings } from "./settings.ts";
11
12
  import { type FileOperations } from "./utils.ts";
13
+ export { type CompactionSettings, clampTriggerPercent, DEFAULT_COMPACTION_SETTINGS, DEFAULT_TRIGGER_PERCENT, MAX_TRIGGER_PERCENT, MIN_TRIGGER_PERCENT, SUMMARY_RESERVE_TOKENS, shouldCompact, } from "./settings.ts";
12
14
  /** Details stored in CompactionEntry.details for file tracking */
13
15
  export interface CompactionDetails {
14
16
  readFiles: string[];
@@ -25,12 +27,6 @@ export interface CompactionResult<T = unknown> {
25
27
  /** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
26
28
  details?: T;
27
29
  }
28
- export interface CompactionSettings {
29
- enabled: boolean;
30
- reserveTokens: number;
31
- keepRecentTokens: number;
32
- }
33
- export declare const DEFAULT_COMPACTION_SETTINGS: CompactionSettings;
34
30
  /**
35
31
  * Calculate total context tokens from usage.
36
32
  * Uses the native totalTokens field when available, falls back to computing from components.
@@ -51,10 +47,6 @@ export interface ContextUsageEstimate {
51
47
  * If there are messages after the last usage, estimate their tokens with estimateTokens.
52
48
  */
53
49
  export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;
54
- /**
55
- * Check if compaction should trigger based on context usage.
56
- */
57
- export declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean;
58
50
  /**
59
51
  * Estimate token count for a message using chars/4 heuristic.
60
52
  * This is conservative (overestimates tokens).
@@ -129,10 +121,11 @@ export interface CompactionPreparation {
129
121
  previousSummary?: string;
130
122
  /** File operations extracted from messagesToSummarize */
131
123
  fileOps: FileOperations;
132
- /** Compaction settions from settings.jsonl */
124
+ /** Configured compaction settings, before applying the model's budget limits. */
133
125
  settings: CompactionSettings;
134
126
  }
135
- export declare function prepareCompaction(pathEntries: SessionEntry[], settings: CompactionSettings): CompactionPreparation | undefined;
127
+ /** Pass the model's context window to adapt retention to the configured trigger. */
128
+ export declare function prepareCompaction(pathEntries: SessionEntry[], settings: CompactionSettings, contextWindow?: number): CompactionPreparation | undefined;
136
129
  /**
137
130
  * Generate summaries for compaction using prepared data.
138
131
  * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.
@@ -1 +1 @@
1
- {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC3F,OAAO,EAAe,KAAK,cAAc,EAAE,KAAK,WAAW,EAA8B,MAAM,uBAAuB,CAAC;AACvH,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAGjH,OAAO,EAGN,KAAK,YAAY,EAEjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAIN,KAAK,cAAc,EAInB,MAAM,YAAY,CAAC;AAMpB,kEAAkE;AAClE,MAAM,WAAW,iBAAiB;IACjC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,aAAa,EAAE,MAAM,EAAE,CAAC;CACxB;AAkDD,8EAA8E;AAC9E,MAAM,WAAW,gBAAgB,CAAC,CAAC,GAAG,OAAO;IAC5C,OAAO,EAAE,MAAM,CAAC;IAChB,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,2EAA2E;IAC3E,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,+FAA+F;IAC/F,OAAO,CAAC,EAAE,CAAC,CAAC;CACZ;AA6BD,MAAM,WAAW,kBAAkB;IAClC,OAAO,EA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W,EACnB,SAAS,CAAC,EAAE,cAAc,EAC1B,SAAS,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,gBAAgB,CAAC,CA6F3B"}
@@ -8,7 +8,9 @@ import { contentText, retryAssistantCall, uuidv7 } from "@earendil-works/pi-ai";
8
8
  import { completeSimple } from "@earendil-works/pi-ai/compat";
9
9
  import { convertToLlm } from "../messages.js";
10
10
  import { buildSessionContext, sessionEntryToContextMessages, } from "../session-manager.js";
11
+ import { getCompactionBudget } from "./settings.js";
11
12
  import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
13
+ export { clampTriggerPercent, DEFAULT_COMPACTION_SETTINGS, DEFAULT_TRIGGER_PERCENT, MAX_TRIGGER_PERCENT, MIN_TRIGGER_PERCENT, SUMMARY_RESERVE_TOKENS, shouldCompact, } from "./settings.js";
12
14
  /**
13
15
  * Extract file operations from messages and previous compaction entries.
14
16
  */
@@ -71,11 +73,6 @@ function combineUsage(first, second) {
71
73
  },
72
74
  };
73
75
  }
74
- export const DEFAULT_COMPACTION_SETTINGS = {
75
- enabled: true,
76
- reserveTokens: 16384,
77
- keepRecentTokens: 20000,
78
- };
79
76
  // ============================================================================
80
77
  // Token calculation
81
78
  // ============================================================================
@@ -154,14 +151,6 @@ export function estimateContextTokens(messages) {
154
151
  lastUsageIndex: usageInfo.index,
155
152
  };
156
153
  }
157
- /**
158
- * Check if compaction should trigger based on context usage.
159
- */
160
- export function shouldCompact(contextTokens, contextWindow, settings) {
161
- if (!settings.enabled)
162
- return false;
163
- return contextTokens > contextWindow - settings.reserveTokens;
164
- }
165
154
  // ============================================================================
166
155
  // Cut point detection
167
156
  // ============================================================================
@@ -514,7 +503,8 @@ export async function generateSummaryWithUsage(currentMessages, model, reserveTo
514
503
  const textContent = contentText(response.content);
515
504
  return { text: textContent, usage: response.usage };
516
505
  }
517
- export function prepareCompaction(pathEntries, settings) {
506
+ /** Pass the model's context window to adapt retention to the configured trigger. */
507
+ export function prepareCompaction(pathEntries, settings, contextWindow) {
518
508
  if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
519
509
  return undefined;
520
510
  }
@@ -535,7 +525,8 @@ export function prepareCompaction(pathEntries, settings) {
535
525
  }
536
526
  const boundaryEnd = pathEntries.length;
537
527
  const tokensBefore = estimateContextTokens(buildSessionContext(pathEntries).messages).tokens;
538
- const cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);
528
+ const budget = getCompactionBudget(settings, contextWindow);
529
+ const cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, budget.keepRecentTokens);
539
530
  // Get UUID of first kept entry
540
531
  const firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];
541
532
  if (!firstKeptEntry?.id) {
@@ -607,7 +598,8 @@ Be concise. Focus on what's needed to understand the kept suffix.`;
607
598
  * @param sessionId - Optional routing session ID forwarded without enabling prompt caching
608
599
  */
609
600
  export async function compact(preparation, model, apiKey, headers, customInstructions, signal, thinkingLevel, streamFn, env, retry, callbacks, sessionId) {
610
- const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, settings, } = preparation;
601
+ const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, } = preparation;
602
+ const { summaryReserveTokens } = getCompactionBudget(preparation.settings, model.contextWindow);
611
603
  // Generate summaries and merge into one
612
604
  let summary;
613
605
  let summaryUsage;
@@ -615,18 +607,18 @@ export async function compact(preparation, model, apiKey, headers, customInstruc
615
607
  let historyText = "No prior history.";
616
608
  let historyUsage;
617
609
  if (messagesToSummarize.length > 0) {
618
- const historyResult = await generateSummaryWithUsage(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, env, retry, callbacks, sessionId);
610
+ const historyResult = await generateSummaryWithUsage(messagesToSummarize, model, summaryReserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, env, retry, callbacks, sessionId);
619
611
  historyText = historyResult.text;
620
612
  historyUsage = historyResult.usage;
621
613
  }
622
- const turnPrefixResult = await generateTurnPrefixSummary(turnPrefixMessages, model, settings.reserveTokens, apiKey, headers, env, signal, thinkingLevel, streamFn, retry, callbacks, sessionId);
614
+ const turnPrefixResult = await generateTurnPrefixSummary(turnPrefixMessages, model, summaryReserveTokens, apiKey, headers, env, signal, thinkingLevel, streamFn, retry, callbacks, sessionId);
623
615
  // Merge into single summary
624
616
  summary = `${historyText}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult.text}`;
625
617
  summaryUsage = historyUsage ? combineUsage(historyUsage, turnPrefixResult.usage) : turnPrefixResult.usage;
626
618
  }
627
619
  else {
628
620
  // Just generate history summary
629
- const result = await generateSummaryWithUsage(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, env, retry, callbacks, sessionId);
621
+ const result = await generateSummaryWithUsage(messagesToSummarize, model, summaryReserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, env, retry, callbacks, sessionId);
630
622
  summary = result.text;
631
623
  summaryUsage = result.usage;
632
624
  }