operon-agents-core 0.1.0-alpha.0

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 (511) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +7 -0
  3. package/dist/agent/agent.d.ts +65 -0
  4. package/dist/agent/agent.js +39 -0
  5. package/dist/agent/compose-hooks.d.ts +13 -0
  6. package/dist/agent/compose-hooks.js +197 -0
  7. package/dist/agent/concurrency.d.ts +22 -0
  8. package/dist/agent/concurrency.js +70 -0
  9. package/dist/agent/context-report.d.ts +60 -0
  10. package/dist/agent/context-report.js +45 -0
  11. package/dist/agent/graph.d.ts +48 -0
  12. package/dist/agent/graph.js +129 -0
  13. package/dist/agent/guardrail.d.ts +105 -0
  14. package/dist/agent/guardrail.js +314 -0
  15. package/dist/agent/handoff-executor.d.ts +21 -0
  16. package/dist/agent/handoff-executor.js +95 -0
  17. package/dist/agent/handoff.d.ts +42 -0
  18. package/dist/agent/handoff.js +70 -0
  19. package/dist/agent/index.d.ts +25 -0
  20. package/dist/agent/index.js +19 -0
  21. package/dist/agent/instruction-context.d.ts +33 -0
  22. package/dist/agent/instruction-context.js +100 -0
  23. package/dist/agent/pause.d.ts +12 -0
  24. package/dist/agent/pause.js +82 -0
  25. package/dist/agent/profile-builtins.d.ts +8 -0
  26. package/dist/agent/profile-builtins.js +130 -0
  27. package/dist/agent/profiles.d.ts +94 -0
  28. package/dist/agent/profiles.js +264 -0
  29. package/dist/agent/recovery.d.ts +10 -0
  30. package/dist/agent/recovery.js +151 -0
  31. package/dist/agent/run-support.d.ts +79 -0
  32. package/dist/agent/run-support.js +211 -0
  33. package/dist/agent/runner.d.ts +246 -0
  34. package/dist/agent/runner.js +786 -0
  35. package/dist/agent/session.d.ts +363 -0
  36. package/dist/agent/session.js +937 -0
  37. package/dist/agent/subagent-tools.d.ts +18 -0
  38. package/dist/agent/subagent-tools.js +650 -0
  39. package/dist/agent/subagent.d.ts +56 -0
  40. package/dist/agent/subagent.js +50 -0
  41. package/dist/agent/toolset.d.ts +24 -0
  42. package/dist/agent/toolset.js +112 -0
  43. package/dist/agent/workflow/index.d.ts +9 -0
  44. package/dist/agent/workflow/index.js +8 -0
  45. package/dist/agent/workflow/journal.d.ts +180 -0
  46. package/dist/agent/workflow/journal.js +224 -0
  47. package/dist/agent/workflow/manager.d.ts +27 -0
  48. package/dist/agent/workflow/manager.js +33 -0
  49. package/dist/agent/workflow/parse.d.ts +17 -0
  50. package/dist/agent/workflow/parse.js +174 -0
  51. package/dist/agent/workflow/prompt.d.ts +8 -0
  52. package/dist/agent/workflow/prompt.js +84 -0
  53. package/dist/agent/workflow/runtime.d.ts +64 -0
  54. package/dist/agent/workflow/runtime.js +380 -0
  55. package/dist/agent/workflow/sandbox.d.ts +35 -0
  56. package/dist/agent/workflow/sandbox.js +90 -0
  57. package/dist/agent/workflow/snapshot.d.ts +36 -0
  58. package/dist/agent/workflow/snapshot.js +9 -0
  59. package/dist/agent/workflow/structured.d.ts +35 -0
  60. package/dist/agent/workflow/structured.js +79 -0
  61. package/dist/agent/workflow/tool.d.ts +14 -0
  62. package/dist/agent/workflow/tool.js +569 -0
  63. package/dist/agent/workflow/types.d.ts +100 -0
  64. package/dist/agent/workflow/types.js +17 -0
  65. package/dist/agent/worktree.d.ts +38 -0
  66. package/dist/agent/worktree.js +56 -0
  67. package/dist/capabilities/assembler.d.ts +39 -0
  68. package/dist/capabilities/assembler.js +171 -0
  69. package/dist/capabilities/background/agent-task.d.ts +51 -0
  70. package/dist/capabilities/background/agent-task.js +101 -0
  71. package/dist/capabilities/background/command-task.d.ts +43 -0
  72. package/dist/capabilities/background/command-task.js +86 -0
  73. package/dist/capabilities/background/index.d.ts +20 -0
  74. package/dist/capabilities/background/index.js +57 -0
  75. package/dist/capabilities/background/manager.d.ts +194 -0
  76. package/dist/capabilities/background/manager.js +1131 -0
  77. package/dist/capabilities/background/persist-disk.d.ts +17 -0
  78. package/dist/capabilities/background/persist-disk.js +66 -0
  79. package/dist/capabilities/background/persist.d.ts +61 -0
  80. package/dist/capabilities/background/persist.js +117 -0
  81. package/dist/capabilities/background/question-task.d.ts +32 -0
  82. package/dist/capabilities/background/question-task.js +56 -0
  83. package/dist/capabilities/background/registrar.d.ts +12 -0
  84. package/dist/capabilities/background/registrar.js +9 -0
  85. package/dist/capabilities/background/swappable-sink.d.ts +20 -0
  86. package/dist/capabilities/background/swappable-sink.js +20 -0
  87. package/dist/capabilities/background/task.d.ts +114 -0
  88. package/dist/capabilities/background/task.js +20 -0
  89. package/dist/capabilities/background/tools.d.ts +6 -0
  90. package/dist/capabilities/background/tools.js +190 -0
  91. package/dist/capabilities/background/workflow-task.d.ts +48 -0
  92. package/dist/capabilities/background/workflow-task.js +91 -0
  93. package/dist/capabilities/capability-state.d.ts +13 -0
  94. package/dist/capabilities/capability-state.js +37 -0
  95. package/dist/capabilities/capability.d.ts +145 -0
  96. package/dist/capabilities/capability.js +2 -0
  97. package/dist/capabilities/compaction/full.d.ts +27 -0
  98. package/dist/capabilities/compaction/full.js +155 -0
  99. package/dist/capabilities/compaction/index.d.ts +17 -0
  100. package/dist/capabilities/compaction/index.js +145 -0
  101. package/dist/capabilities/compaction/instruction.d.ts +2 -0
  102. package/dist/capabilities/compaction/instruction.js +31 -0
  103. package/dist/capabilities/compaction/micro.d.ts +17 -0
  104. package/dist/capabilities/compaction/micro.js +57 -0
  105. package/dist/capabilities/compaction/service.d.ts +28 -0
  106. package/dist/capabilities/compaction/service.js +52 -0
  107. package/dist/capabilities/compaction/strategy.d.ts +43 -0
  108. package/dist/capabilities/compaction/strategy.js +116 -0
  109. package/dist/capabilities/compaction/tokens.d.ts +5 -0
  110. package/dist/capabilities/compaction/tokens.js +28 -0
  111. package/dist/capabilities/goal/goal-store.d.ts +69 -0
  112. package/dist/capabilities/goal/goal-store.js +172 -0
  113. package/dist/capabilities/goal/index.d.ts +6 -0
  114. package/dist/capabilities/goal/index.js +31 -0
  115. package/dist/capabilities/goal/injector.d.ts +9 -0
  116. package/dist/capabilities/goal/injector.js +79 -0
  117. package/dist/capabilities/goal/tools.d.ts +6 -0
  118. package/dist/capabilities/goal/tools.js +86 -0
  119. package/dist/capabilities/index.d.ts +25 -0
  120. package/dist/capabilities/index.js +22 -0
  121. package/dist/capabilities/injection.d.ts +44 -0
  122. package/dist/capabilities/injection.js +112 -0
  123. package/dist/capabilities/plan/index.d.ts +6 -0
  124. package/dist/capabilities/plan/index.js +25 -0
  125. package/dist/capabilities/plan/injector.d.ts +13 -0
  126. package/dist/capabilities/plan/injector.js +83 -0
  127. package/dist/capabilities/plan/plan-mode.d.ts +38 -0
  128. package/dist/capabilities/plan/plan-mode.js +113 -0
  129. package/dist/capabilities/plan/policies.d.ts +6 -0
  130. package/dist/capabilities/plan/policies.js +89 -0
  131. package/dist/capabilities/plan/tools.d.ts +15 -0
  132. package/dist/capabilities/plan/tools.js +87 -0
  133. package/dist/capabilities/skills/flow-provider.d.ts +6 -0
  134. package/dist/capabilities/skills/flow-provider.js +50 -0
  135. package/dist/capabilities/skills/index.d.ts +43 -0
  136. package/dist/capabilities/skills/index.js +48 -0
  137. package/dist/capabilities/skills/injector.d.ts +11 -0
  138. package/dist/capabilities/skills/injector.js +27 -0
  139. package/dist/capabilities/skills/parser.d.ts +36 -0
  140. package/dist/capabilities/skills/parser.js +334 -0
  141. package/dist/capabilities/skills/registry.d.ts +33 -0
  142. package/dist/capabilities/skills/registry.js +118 -0
  143. package/dist/capabilities/skills/scanner.d.ts +26 -0
  144. package/dist/capabilities/skills/scanner.js +154 -0
  145. package/dist/capabilities/skills/service.d.ts +39 -0
  146. package/dist/capabilities/skills/service.js +68 -0
  147. package/dist/capabilities/skills/skill-tool.d.ts +13 -0
  148. package/dist/capabilities/skills/skill-tool.js +72 -0
  149. package/dist/capabilities/skills/types.d.ts +62 -0
  150. package/dist/capabilities/skills/types.js +26 -0
  151. package/dist/capabilities/task/index.d.ts +23 -0
  152. package/dist/capabilities/task/index.js +38 -0
  153. package/dist/capabilities/task/injector.d.ts +9 -0
  154. package/dist/capabilities/task/injector.js +62 -0
  155. package/dist/capabilities/task/persist-disk.d.ts +19 -0
  156. package/dist/capabilities/task/persist-disk.js +84 -0
  157. package/dist/capabilities/task/persist.d.ts +52 -0
  158. package/dist/capabilities/task/persist.js +84 -0
  159. package/dist/capabilities/task/task-store.d.ts +44 -0
  160. package/dist/capabilities/task/task-store.js +106 -0
  161. package/dist/capabilities/task/tools.d.ts +12 -0
  162. package/dist/capabilities/task/tools.js +164 -0
  163. package/dist/capabilities/todo/index.d.ts +8 -0
  164. package/dist/capabilities/todo/index.js +21 -0
  165. package/dist/capabilities/todo/injector.d.ts +9 -0
  166. package/dist/capabilities/todo/injector.js +68 -0
  167. package/dist/capabilities/todo/todo-store.d.ts +19 -0
  168. package/dist/capabilities/todo/todo-store.js +36 -0
  169. package/dist/capabilities/todo/tools.d.ts +6 -0
  170. package/dist/capabilities/todo/tools.js +70 -0
  171. package/dist/capabilities/tool-provider.d.ts +12 -0
  172. package/dist/capabilities/tool-provider.js +20 -0
  173. package/dist/capabilities/user-hooks/engine.d.ts +22 -0
  174. package/dist/capabilities/user-hooks/engine.js +105 -0
  175. package/dist/capabilities/user-hooks/index.d.ts +13 -0
  176. package/dist/capabilities/user-hooks/index.js +126 -0
  177. package/dist/capabilities/user-hooks/types.d.ts +26 -0
  178. package/dist/capabilities/user-hooks/types.js +19 -0
  179. package/dist/capabilities/workflow/index.d.ts +16 -0
  180. package/dist/capabilities/workflow/index.js +15 -0
  181. package/dist/commands/index.d.ts +31 -0
  182. package/dist/commands/index.js +318 -0
  183. package/dist/config/config-store.d.ts +29 -0
  184. package/dist/config/config-store.js +103 -0
  185. package/dist/config/file-source.d.ts +40 -0
  186. package/dist/config/file-source.js +78 -0
  187. package/dist/config/flags.d.ts +13 -0
  188. package/dist/config/flags.js +25 -0
  189. package/dist/config/index.d.ts +17 -0
  190. package/dist/config/index.js +10 -0
  191. package/dist/config/merge.d.ts +5 -0
  192. package/dist/config/merge.js +57 -0
  193. package/dist/config/model-catalog.d.ts +17 -0
  194. package/dist/config/model-catalog.js +37 -0
  195. package/dist/config/paths.d.ts +31 -0
  196. package/dist/config/paths.js +28 -0
  197. package/dist/config/provider-manager.d.ts +57 -0
  198. package/dist/config/provider-manager.js +344 -0
  199. package/dist/config/resolver.d.ts +40 -0
  200. package/dist/config/resolver.js +52 -0
  201. package/dist/config/schema.d.ts +389 -0
  202. package/dist/config/schema.js +132 -0
  203. package/dist/events/events.d.ts +348 -0
  204. package/dist/events/events.js +146 -0
  205. package/dist/events/index.d.ts +10 -0
  206. package/dist/events/index.js +5 -0
  207. package/dist/events/projection.d.ts +207 -0
  208. package/dist/events/projection.js +438 -0
  209. package/dist/events/publisher.d.ts +48 -0
  210. package/dist/events/publisher.js +404 -0
  211. package/dist/events/redacting-sink.d.ts +11 -0
  212. package/dist/events/redacting-sink.js +31 -0
  213. package/dist/home.d.ts +16 -0
  214. package/dist/home.js +20 -0
  215. package/dist/index.d.ts +22 -0
  216. package/dist/index.js +22 -0
  217. package/dist/internal.d.ts +33 -0
  218. package/dist/internal.js +29 -0
  219. package/dist/llm/auth.d.ts +22 -0
  220. package/dist/llm/auth.js +112 -0
  221. package/dist/llm/capability.d.ts +13 -0
  222. package/dist/llm/capability.js +45 -0
  223. package/dist/llm/define-model.d.ts +110 -0
  224. package/dist/llm/define-model.js +252 -0
  225. package/dist/llm/errors.d.ts +33 -0
  226. package/dist/llm/errors.js +154 -0
  227. package/dist/llm/index.d.ts +14 -0
  228. package/dist/llm/index.js +8 -0
  229. package/dist/llm/model.d.ts +43 -0
  230. package/dist/llm/model.js +9 -0
  231. package/dist/llm/retry.d.ts +35 -0
  232. package/dist/llm/retry.js +160 -0
  233. package/dist/llm/runtime.d.ts +25 -0
  234. package/dist/llm/runtime.js +38 -0
  235. package/dist/logging/diagnostics.d.ts +21 -0
  236. package/dist/logging/diagnostics.js +46 -0
  237. package/dist/logging/index.d.ts +11 -0
  238. package/dist/logging/index.js +7 -0
  239. package/dist/logging/logger.d.ts +25 -0
  240. package/dist/logging/logger.js +54 -0
  241. package/dist/logging/paths.d.ts +11 -0
  242. package/dist/logging/paths.js +20 -0
  243. package/dist/logging/policy.d.ts +5 -0
  244. package/dist/logging/policy.js +19 -0
  245. package/dist/logging/redact.d.ts +10 -0
  246. package/dist/logging/redact.js +95 -0
  247. package/dist/logging/sinks.d.ts +67 -0
  248. package/dist/logging/sinks.js +117 -0
  249. package/dist/loop/context.d.ts +69 -0
  250. package/dist/loop/context.js +129 -0
  251. package/dist/loop/errors.d.ts +8 -0
  252. package/dist/loop/errors.js +27 -0
  253. package/dist/loop/events.d.ts +14 -0
  254. package/dist/loop/events.js +2 -0
  255. package/dist/loop/index.d.ts +10 -0
  256. package/dist/loop/index.js +7 -0
  257. package/dist/loop/interruption.d.ts +118 -0
  258. package/dist/loop/interruption.js +191 -0
  259. package/dist/loop/run-turn.d.ts +54 -0
  260. package/dist/loop/run-turn.js +203 -0
  261. package/dist/loop/scheduler.d.ts +18 -0
  262. package/dist/loop/scheduler.js +71 -0
  263. package/dist/loop/steer.d.ts +122 -0
  264. package/dist/loop/steer.js +209 -0
  265. package/dist/loop/tool-call.d.ts +41 -0
  266. package/dist/loop/tool-call.js +326 -0
  267. package/dist/loop/turn-step.d.ts +57 -0
  268. package/dist/loop/turn-step.js +298 -0
  269. package/dist/loop/types.d.ts +217 -0
  270. package/dist/loop/types.js +2 -0
  271. package/dist/loop/usage.d.ts +6 -0
  272. package/dist/loop/usage.js +44 -0
  273. package/dist/mcp/auth-tool.d.ts +12 -0
  274. package/dist/mcp/auth-tool.js +92 -0
  275. package/dist/mcp/capability.d.ts +7 -0
  276. package/dist/mcp/capability.js +91 -0
  277. package/dist/mcp/config-loader.d.ts +28 -0
  278. package/dist/mcp/config-loader.js +115 -0
  279. package/dist/mcp/filter.d.ts +18 -0
  280. package/dist/mcp/filter.js +35 -0
  281. package/dist/mcp/index.d.ts +23 -0
  282. package/dist/mcp/index.js +13 -0
  283. package/dist/mcp/manager.d.ts +51 -0
  284. package/dist/mcp/manager.js +412 -0
  285. package/dist/mcp/mock-transport.d.ts +40 -0
  286. package/dist/mcp/mock-transport.js +68 -0
  287. package/dist/mcp/oauth/callback-server.d.ts +14 -0
  288. package/dist/mcp/oauth/callback-server.js +122 -0
  289. package/dist/mcp/oauth/index.d.ts +9 -0
  290. package/dist/mcp/oauth/index.js +5 -0
  291. package/dist/mcp/oauth/provider.d.ts +39 -0
  292. package/dist/mcp/oauth/provider.js +121 -0
  293. package/dist/mcp/oauth/service.d.ts +34 -0
  294. package/dist/mcp/oauth/service.js +130 -0
  295. package/dist/mcp/oauth/store.d.ts +40 -0
  296. package/dist/mcp/oauth/store.js +134 -0
  297. package/dist/mcp/output.d.ts +12 -0
  298. package/dist/mcp/output.js +110 -0
  299. package/dist/mcp/provider.d.ts +7 -0
  300. package/dist/mcp/provider.js +56 -0
  301. package/dist/mcp/sdk-transport.d.ts +25 -0
  302. package/dist/mcp/sdk-transport.js +228 -0
  303. package/dist/mcp/server.d.ts +77 -0
  304. package/dist/mcp/server.js +120 -0
  305. package/dist/mcp/tool-naming.d.ts +4 -0
  306. package/dist/mcp/tool-naming.js +26 -0
  307. package/dist/mcp/types.d.ts +75 -0
  308. package/dist/mcp/types.js +2 -0
  309. package/dist/net/index.d.ts +3 -0
  310. package/dist/net/index.js +2 -0
  311. package/dist/net/proxy.d.ts +16 -0
  312. package/dist/net/proxy.js +42 -0
  313. package/dist/permission/auto-approver/index.d.ts +3 -0
  314. package/dist/permission/auto-approver/index.js +3 -0
  315. package/dist/permission/auto-approver/llm-auto-approver.d.ts +53 -0
  316. package/dist/permission/auto-approver/llm-auto-approver.js +122 -0
  317. package/dist/permission/auto-approver/prompts-data.d.ts +9 -0
  318. package/dist/permission/auto-approver/prompts-data.js +155 -0
  319. package/dist/permission/auto-approver/prompts.d.ts +18 -0
  320. package/dist/permission/auto-approver/prompts.js +40 -0
  321. package/dist/permission/auto-approver/transcript.d.ts +22 -0
  322. package/dist/permission/auto-approver/transcript.js +75 -0
  323. package/dist/permission/auto-approver/xml.d.ts +5 -0
  324. package/dist/permission/auto-approver/xml.js +25 -0
  325. package/dist/permission/index.d.ts +7 -0
  326. package/dist/permission/index.js +5 -0
  327. package/dist/permission/manager.d.ts +74 -0
  328. package/dist/permission/manager.js +162 -0
  329. package/dist/permission/matches-rule.d.ts +27 -0
  330. package/dist/permission/matches-rule.js +54 -0
  331. package/dist/permission/policies.d.ts +14 -0
  332. package/dist/permission/policies.js +233 -0
  333. package/dist/permission/types.d.ts +84 -0
  334. package/dist/permission/types.js +2 -0
  335. package/dist/plugins/archive.d.ts +3 -0
  336. package/dist/plugins/archive.js +58 -0
  337. package/dist/plugins/github-resolver.d.ts +13 -0
  338. package/dist/plugins/github-resolver.js +20 -0
  339. package/dist/plugins/hooks.d.ts +28 -0
  340. package/dist/plugins/hooks.js +296 -0
  341. package/dist/plugins/index.d.ts +23 -0
  342. package/dist/plugins/index.js +23 -0
  343. package/dist/plugins/injector.d.ts +11 -0
  344. package/dist/plugins/injector.js +32 -0
  345. package/dist/plugins/manager.d.ts +37 -0
  346. package/dist/plugins/manager.js +330 -0
  347. package/dist/plugins/manifest.d.ts +9 -0
  348. package/dist/plugins/manifest.js +234 -0
  349. package/dist/plugins/marketplace.d.ts +85 -0
  350. package/dist/plugins/marketplace.js +205 -0
  351. package/dist/plugins/source.d.ts +23 -0
  352. package/dist/plugins/source.js +87 -0
  353. package/dist/plugins/store.d.ts +20 -0
  354. package/dist/plugins/store.js +30 -0
  355. package/dist/plugins/types.d.ts +118 -0
  356. package/dist/plugins/types.js +5 -0
  357. package/dist/protocol/index.d.ts +4 -0
  358. package/dist/protocol/index.js +2 -0
  359. package/dist/protocol/tool-schema.d.ts +6 -0
  360. package/dist/protocol/tool-schema.js +2 -0
  361. package/dist/store/blob-store.d.ts +45 -0
  362. package/dist/store/blob-store.js +120 -0
  363. package/dist/store/catalog-store.d.ts +32 -0
  364. package/dist/store/catalog-store.js +73 -0
  365. package/dist/store/disk-store.d.ts +58 -0
  366. package/dist/store/disk-store.js +369 -0
  367. package/dist/store/index.d.ts +23 -0
  368. package/dist/store/index.js +15 -0
  369. package/dist/store/lock.d.ts +86 -0
  370. package/dist/store/lock.js +104 -0
  371. package/dist/store/log-store.d.ts +89 -0
  372. package/dist/store/log-store.js +296 -0
  373. package/dist/store/migrate.d.ts +26 -0
  374. package/dist/store/migrate.js +32 -0
  375. package/dist/store/origin.d.ts +89 -0
  376. package/dist/store/origin.js +16 -0
  377. package/dist/store/pg.d.ts +90 -0
  378. package/dist/store/pg.js +344 -0
  379. package/dist/store/redacting-store.d.ts +21 -0
  380. package/dist/store/redacting-store.js +46 -0
  381. package/dist/store/redis.d.ts +89 -0
  382. package/dist/store/redis.js +370 -0
  383. package/dist/store/repository.d.ts +150 -0
  384. package/dist/store/repository.js +508 -0
  385. package/dist/store/session-catalog.d.ts +32 -0
  386. package/dist/store/session-catalog.js +117 -0
  387. package/dist/store/storage.d.ts +27 -0
  388. package/dist/store/storage.js +54 -0
  389. package/dist/store/store.d.ts +262 -0
  390. package/dist/store/store.js +129 -0
  391. package/dist/store/workdir-key.d.ts +4 -0
  392. package/dist/store/workdir-key.js +28 -0
  393. package/dist/tool/access.d.ts +37 -0
  394. package/dist/tool/access.js +79 -0
  395. package/dist/tool/ask.d.ts +22 -0
  396. package/dist/tool/ask.js +38 -0
  397. package/dist/tool/background.d.ts +109 -0
  398. package/dist/tool/background.js +39 -0
  399. package/dist/tool/builtin/ask-user-question.d.ts +2 -0
  400. package/dist/tool/builtin/ask-user-question.js +175 -0
  401. package/dist/tool/builtin/bash.d.ts +2 -0
  402. package/dist/tool/builtin/bash.js +407 -0
  403. package/dist/tool/builtin/edit.d.ts +2 -0
  404. package/dist/tool/builtin/edit.js +202 -0
  405. package/dist/tool/builtin/glob.d.ts +3 -0
  406. package/dist/tool/builtin/glob.js +260 -0
  407. package/dist/tool/builtin/grep.d.ts +2 -0
  408. package/dist/tool/builtin/grep.js +574 -0
  409. package/dist/tool/builtin/line-endings.d.ts +10 -0
  410. package/dist/tool/builtin/line-endings.js +41 -0
  411. package/dist/tool/builtin/read.d.ts +28 -0
  412. package/dist/tool/builtin/read.js +498 -0
  413. package/dist/tool/builtin/write.d.ts +2 -0
  414. package/dist/tool/builtin/write.js +179 -0
  415. package/dist/tool/define.d.ts +46 -0
  416. package/dist/tool/define.js +45 -0
  417. package/dist/tool/file-freshness.d.ts +81 -0
  418. package/dist/tool/file-freshness.js +67 -0
  419. package/dist/tool/filesystem-tools.d.ts +16 -0
  420. package/dist/tool/filesystem-tools.js +19 -0
  421. package/dist/tool/git-context.d.ts +20 -0
  422. package/dist/tool/git-context.js +114 -0
  423. package/dist/tool/index.d.ts +37 -0
  424. package/dist/tool/index.js +34 -0
  425. package/dist/tool/machine-base.d.ts +138 -0
  426. package/dist/tool/machine-base.js +388 -0
  427. package/dist/tool/machine-local.d.ts +35 -0
  428. package/dist/tool/machine-local.js +316 -0
  429. package/dist/tool/machine-null.d.ts +36 -0
  430. package/dist/tool/machine-null.js +64 -0
  431. package/dist/tool/machine-ssh.d.ts +86 -0
  432. package/dist/tool/machine-ssh.js +576 -0
  433. package/dist/tool/machine.d.ts +333 -0
  434. package/dist/tool/machine.js +15 -0
  435. package/dist/tool/policies/path-access.d.ts +48 -0
  436. package/dist/tool/policies/path-access.js +186 -0
  437. package/dist/tool/policies/sensitive.d.ts +3 -0
  438. package/dist/tool/policies/sensitive.js +60 -0
  439. package/dist/tool/questions.d.ts +40 -0
  440. package/dist/tool/questions.js +8 -0
  441. package/dist/tool/search/activation.d.ts +13 -0
  442. package/dist/tool/search/activation.js +31 -0
  443. package/dist/tool/search/deferral.d.ts +37 -0
  444. package/dist/tool/search/deferral.js +128 -0
  445. package/dist/tool/search/search-tool.d.ts +9 -0
  446. package/dist/tool/search/search-tool.js +62 -0
  447. package/dist/tool/shell-env.d.ts +9 -0
  448. package/dist/tool/shell-env.js +34 -0
  449. package/dist/tool/support/bash-destructive.d.ts +24 -0
  450. package/dist/tool/support/bash-destructive.js +63 -0
  451. package/dist/tool/support/bash-paths.d.ts +7 -0
  452. package/dist/tool/support/bash-paths.js +247 -0
  453. package/dist/tool/support/bash-read-only.d.ts +8 -0
  454. package/dist/tool/support/bash-read-only.js +165 -0
  455. package/dist/tool/support/bash-rule-match.d.ts +20 -0
  456. package/dist/tool/support/bash-rule-match.js +191 -0
  457. package/dist/tool/support/file-type.d.ts +10 -0
  458. package/dist/tool/support/file-type.js +149 -0
  459. package/dist/tool/support/git-worktree.d.ts +10 -0
  460. package/dist/tool/support/git-worktree.js +63 -0
  461. package/dist/tool/support/image-compress.d.ts +69 -0
  462. package/dist/tool/support/image-compress.js +265 -0
  463. package/dist/tool/support/machine-ops.d.ts +34 -0
  464. package/dist/tool/support/machine-ops.js +34 -0
  465. package/dist/tool/support/path-glob-match.d.ts +12 -0
  466. package/dist/tool/support/path-glob-match.js +84 -0
  467. package/dist/tool/support/result-builder.d.ts +27 -0
  468. package/dist/tool/support/result-builder.js +108 -0
  469. package/dist/tool/support/rg-locator.d.ts +20 -0
  470. package/dist/tool/support/rg-locator.js +42 -0
  471. package/dist/tool/support/ripgrep-run.d.ts +65 -0
  472. package/dist/tool/support/ripgrep-run.js +40 -0
  473. package/dist/tool/support/rule-match.d.ts +6 -0
  474. package/dist/tool/support/rule-match.js +23 -0
  475. package/dist/tool/support/tool-path.d.ts +8 -0
  476. package/dist/tool/support/tool-path.js +28 -0
  477. package/dist/tool/support/workspace.d.ts +5 -0
  478. package/dist/tool/support/workspace.js +2 -0
  479. package/dist/tool/types.d.ts +131 -0
  480. package/dist/tool/types.js +2 -0
  481. package/dist/tool/web/fetch-url.d.ts +4 -0
  482. package/dist/tool/web/fetch-url.js +61 -0
  483. package/dist/tool/web/index.d.ts +11 -0
  484. package/dist/tool/web/index.js +7 -0
  485. package/dist/tool/web/providers/direct-fetch.d.ts +33 -0
  486. package/dist/tool/web/providers/direct-fetch.js +198 -0
  487. package/dist/tool/web/providers/firecrawl.d.ts +16 -0
  488. package/dist/tool/web/providers/firecrawl.js +59 -0
  489. package/dist/tool/web/providers/tavily.d.ts +14 -0
  490. package/dist/tool/web/providers/tavily.js +43 -0
  491. package/dist/tool/web/types.d.ts +41 -0
  492. package/dist/tool/web/types.js +7 -0
  493. package/dist/tool/web/web-search.d.ts +4 -0
  494. package/dist/tool/web/web-search.js +68 -0
  495. package/dist/tool/workspace-spec.d.ts +74 -0
  496. package/dist/tool/workspace-spec.js +177 -0
  497. package/dist/tracing/bridge.d.ts +7 -0
  498. package/dist/tracing/bridge.js +171 -0
  499. package/dist/tracing/index.d.ts +9 -0
  500. package/dist/tracing/index.js +5 -0
  501. package/dist/tracing/otel.d.ts +38 -0
  502. package/dist/tracing/otel.js +221 -0
  503. package/dist/tracing/processor.d.ts +47 -0
  504. package/dist/tracing/processor.js +94 -0
  505. package/dist/tracing/spans.d.ts +94 -0
  506. package/dist/tracing/spans.js +56 -0
  507. package/dist/ui/ai-sdk.d.ts +114 -0
  508. package/dist/ui/ai-sdk.js +175 -0
  509. package/dist/ui/index.d.ts +2 -0
  510. package/dist/ui/index.js +2 -0
  511. package/package.json +101 -0
@@ -0,0 +1,1131 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { StringDecoder } from "node:string_decoder";
3
+ import { errorMessage } from "../../loop/errors.js";
4
+ import { reduceHistory } from "../../store/index.js";
5
+ import { CommandBackgroundTask } from "./command-task.js";
6
+ import { QuestionBackgroundTask } from "./question-task.js";
7
+ import { SwappableSink } from "./swappable-sink.js";
8
+ import { isPersistedTaskTerminal } from "./persist.js";
9
+ import { TERMINAL_STATUSES, isBackgroundTaskTerminal, taskOutputRef, } from "./task.js";
10
+ const MAX_OUTPUT_BYTES = 1024 * 1024; // 1 MiB
11
+ const SIGTERM_GRACE_MS = 5_000;
12
+ const _ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
13
+ function generateTaskId(kind) {
14
+ const bytes = randomBytes(8);
15
+ let suffix = "";
16
+ for (let i = 0; i < 8; i++)
17
+ suffix += _ALPHABET[bytes[i] % 36];
18
+ return `${kind}-${suffix}`;
19
+ }
20
+ /** Remove task-store bookkeeping before a persisted ghost crosses the public manager API. */
21
+ function publicTaskInfo(task) {
22
+ const { schemaVersion: _schemaVersion, revision: _revision, notificationQueuedAt: _notificationQueuedAt, notifiedAt: _notifiedAt, ...info } = task;
23
+ return info;
24
+ }
25
+ /**
26
+ * UTF-8 window alignment. Every read in this file is a BYTE window over text — the tail of a
27
+ * log, a delta from an offset — and a byte offset lands mid-character often enough to matter:
28
+ * any CJK log produces a replacement character at the seam on essentially every read.
29
+ *
30
+ * Two directions, because the two window kinds are cut differently. A tail is cut at the
31
+ * FRONT (start at `size - n`), so the fix is to skip a leading run of continuation bytes. A
32
+ * delta is cut at the BACK (read `n` bytes from a cursor), so the fix is to drop a trailing
33
+ * partial sequence and leave those bytes for the next read — which is why `nextCursor` must be
34
+ * derived from the trimmed length, never from what was read.
35
+ *
36
+ * Deliberately not a StringDecoder: that carries state across calls, which is right for a
37
+ * follower with one reader and wrong here, where reads are independent, repeatable, and may
38
+ * come from several consumers at different offsets.
39
+ */
40
+ function utf8ContinuationByte(byte) {
41
+ return (byte & 0b1100_0000) === 0b1000_0000;
42
+ }
43
+ /** Bytes a leading sequence needs, from its first byte. 1 when it is not a lead byte. */
44
+ function utf8SequenceLength(byte) {
45
+ if ((byte & 0b1000_0000) === 0)
46
+ return 1;
47
+ if ((byte & 0b1110_0000) === 0b1100_0000)
48
+ return 2;
49
+ if ((byte & 0b1111_0000) === 0b1110_0000)
50
+ return 3;
51
+ if ((byte & 0b1111_1000) === 0b1111_0000)
52
+ return 4;
53
+ return 1;
54
+ }
55
+ /** Offset of the first whole character, skipping a partial one the window opened inside of. */
56
+ function utf8AlignStart(buf) {
57
+ const max = Math.min(buf.byteLength, 3);
58
+ let i = 0;
59
+ while (i < max && utf8ContinuationByte(buf[i]))
60
+ i += 1;
61
+ return i;
62
+ }
63
+ /** Length of the longest prefix that ends on a character boundary. */
64
+ function utf8AlignEnd(buf) {
65
+ const len = buf.byteLength;
66
+ // A sequence spans at most 4 bytes, so only the last 3 can be an unfinished one.
67
+ for (let back = 1; back <= Math.min(3, len); back += 1) {
68
+ const start = len - back;
69
+ const byte = buf[start];
70
+ if (utf8ContinuationByte(byte))
71
+ continue;
72
+ const needed = utf8SequenceLength(byte);
73
+ return needed > back ? start : len;
74
+ }
75
+ return len;
76
+ }
77
+ /** The journal record name workflow runs append under (see agent/workflow/journal.ts). */
78
+ const WORKFLOW_JOURNAL_ENTRY = "wf_journal";
79
+ /**
80
+ * One journal entry as a line of a run's story.
81
+ *
82
+ * Deliberately a separate renderer from `renderWorkflowProgress`: that one formats LIVE events
83
+ * for a terminal, this one formats RECORDS for a model reading back. The entries carry more
84
+ * than the events did (a full result rather than a preview), and unknown types are skipped so
85
+ * a record written by a newer version never breaks an older reader.
86
+ */
87
+ function renderWorkflowJournalEntry(data) {
88
+ if (typeof data !== "object" || data === null)
89
+ return undefined;
90
+ const e = data;
91
+ const where = [e["phase"], e["label"]].filter((v) => typeof v === "string" && v.length > 0).join(" / ");
92
+ switch (e["type"]) {
93
+ case "run":
94
+ return `workflow: ${String(e["name"])}${e["args"] === undefined ? "" : `\nargs: ${safeJson(e["args"])}`}`;
95
+ case "phase":
96
+ return `── phase ${String(e["index"])}: ${String(e["title"])}`;
97
+ case "started":
98
+ return `▶ ${where || String(e["agentId"] ?? "agent")}`;
99
+ case "result":
100
+ return `✔ ${where || String(e["agentId"] ?? "agent")} → ${safeJson(e["result"])}`;
101
+ case "error":
102
+ return `✘ ${where || String(e["agentId"] ?? "agent")}: ${String(e["error"])}`;
103
+ case "log":
104
+ return String(e["message"]);
105
+ case "outcome":
106
+ return e["ok"] === true
107
+ ? `outcome: ${String(e["status"] ?? "completed")} (${String(e["agentCount"] ?? 0)} agents)\nresult: ${safeJson(e["result"])}`
108
+ : `outcome: ${String(e["status"] ?? "failed")} (${String(e["agentCount"] ?? 0)} agents)\nerror: ${String(e["error"] ?? "")}`;
109
+ default:
110
+ return undefined;
111
+ }
112
+ }
113
+ function safeJson(value) {
114
+ if (typeof value === "string")
115
+ return value;
116
+ try {
117
+ return JSON.stringify(value) ?? String(value);
118
+ }
119
+ catch {
120
+ return String(value);
121
+ }
122
+ }
123
+ function emptyOutputSnapshot() {
124
+ return { content: "", sizeBytes: 0, contentBytes: 0, truncated: false };
125
+ }
126
+ /** A front-sliced window over an in-memory text value — unlike a log tail, an answer or a
127
+ * shard reduction reads from its beginning. */
128
+ function textSnapshot(text, maxBytes) {
129
+ const full = Buffer.from(text, "utf-8");
130
+ const window = full.subarray(0, Math.min(Math.max(0, Math.trunc(maxBytes)), full.byteLength));
131
+ const aligned = window.subarray(0, utf8AlignEnd(window));
132
+ return {
133
+ content: aligned.toString("utf-8"),
134
+ sizeBytes: full.byteLength,
135
+ contentBytes: aligned.byteLength,
136
+ truncated: full.byteLength > aligned.byteLength,
137
+ };
138
+ }
139
+ /**
140
+ * The last `maxBytes` of a task's output file. Reads only that window — a 2 GB build log
141
+ * costs the same as a 2 KB one — and reports the file's full size so the caller learns how
142
+ * much it is NOT seeing. The file keeps everything either way; this is just the window.
143
+ */
144
+ async function tailFileSnapshot(file, maxBytes) {
145
+ try {
146
+ const size = (await file.machine.fileInfo(file.path)).size;
147
+ const windowBytes = Math.min(maxBytes, size);
148
+ if (windowBytes === 0)
149
+ return { content: "", sizeBytes: size, contentBytes: 0, truncated: size > 0 };
150
+ const bytes = await file.machine.readBytes(file.path, { offset: size - windowBytes, length: windowBytes });
151
+ const aligned = bytes.subarray(utf8AlignStart(bytes));
152
+ return {
153
+ content: aligned.toString("utf-8"),
154
+ sizeBytes: size,
155
+ contentBytes: aligned.byteLength,
156
+ truncated: size > aligned.byteLength,
157
+ };
158
+ }
159
+ catch {
160
+ // The file may have been removed or its Machine may no longer be reachable. Empty is the
161
+ // honest snapshot; the task metadata still preserves the canonical location.
162
+ return emptyOutputSnapshot();
163
+ }
164
+ }
165
+ /** How often a WATCHED output file is checked for new bytes. Only ticks while someone is
166
+ * attached with a live tap; a detached task nobody is looking at costs nothing. */
167
+ const FOLLOW_INTERVAL_MS = 1_000;
168
+ /** How long a foreground run must last before the user is offered "move to background". */
169
+ const DETACHABLE_AFTER_MS = 2_000;
170
+ /**
171
+ * Tail an output file for a watcher, reading only what was appended since the last tick — so
172
+ * a tick costs what was WRITTEN, not what the file has accumulated. A decoder spans ticks
173
+ * because a multi-byte character can straddle two reads.
174
+ */
175
+ function followOutputFile(file, emit) {
176
+ const decoder = new StringDecoder("utf8");
177
+ let offset = 0;
178
+ let inFlight;
179
+ let stopped = false;
180
+ const pump = async () => {
181
+ // Serialize: a slow read must not let the next tick re-read the same bytes.
182
+ if (inFlight !== undefined)
183
+ return await inFlight;
184
+ inFlight = (async () => {
185
+ try {
186
+ const bytes = await file.machine.readBytes(file.path, { offset });
187
+ if (bytes.byteLength > 0) {
188
+ offset += bytes.byteLength;
189
+ const text = decoder.write(bytes);
190
+ if (text.length > 0)
191
+ emit(text);
192
+ }
193
+ }
194
+ catch {
195
+ // Not created yet (the redirect is part of the command) or gone after a kill. The
196
+ // live tap is best-effort; the command's own result is what settles the task.
197
+ }
198
+ })();
199
+ try {
200
+ await inFlight;
201
+ }
202
+ finally {
203
+ inFlight = undefined;
204
+ }
205
+ };
206
+ const timer = setInterval(() => void pump(), FOLLOW_INTERVAL_MS);
207
+ if (typeof timer.unref === "function")
208
+ timer.unref();
209
+ return {
210
+ async drain() {
211
+ if (stopped)
212
+ return;
213
+ stopped = true;
214
+ clearInterval(timer);
215
+ await pump();
216
+ const tail = decoder.end();
217
+ if (tail.length > 0)
218
+ emit(tail);
219
+ },
220
+ stop() {
221
+ stopped = true;
222
+ clearInterval(timer);
223
+ },
224
+ };
225
+ }
226
+ export class BackgroundManager {
227
+ tasks = new Map();
228
+ // Per-tool-call detach triggers: the loop registers one around each running tool call
229
+ // (keyed by toolCallId); firing it moves an attached foreground run into a background task.
230
+ detachControllers = new Map();
231
+ // Tasks loaded from the persistence store on reopen with no live process driving them.
232
+ // `reconcile` reclassifies the non-terminal ones as `lost`. Terminal ghosts stay as a
233
+ // read-through record for `/tasks` (list activeOnly=false) and `getTask`.
234
+ ghosts = new Map();
235
+ // Settles this process has already resent. The durable ledger cannot carry this: its entry
236
+ // only closes when the recipient CONSUMES the message, so between the resend and that
237
+ // confirmation the record still reads "owed" — and `reconcile` is a public call a host may
238
+ // make more than once. Process-local by design: a real restart starts empty and resends.
239
+ redelivered = new Set();
240
+ maxRunningTasks;
241
+ now;
242
+ steer;
243
+ events;
244
+ sessionId = "";
245
+ address = "main";
246
+ persistence;
247
+ store;
248
+ unsubscribeConsumption;
249
+ /** Serialize the whole task store, including the KV backend's shared task index. */
250
+ persistenceChain = Promise.resolve();
251
+ constructor(options = {}) {
252
+ this.maxRunningTasks = options.maxRunningTasks;
253
+ this.now = options.now ?? Date.now;
254
+ }
255
+ attach(runtime) {
256
+ this.steer = runtime.steer;
257
+ this.events = runtime.events;
258
+ this.sessionId = runtime.sessionId ?? "";
259
+ this.address = runtime.address ?? "main";
260
+ // These are session identity, so an explicit storeless attach must clear a prior session's
261
+ // handles instead of accidentally reading/writing the old session.
262
+ this.persistence = runtime.persistence;
263
+ this.store = runtime.store;
264
+ // Close the settle-notification ledger from the only evidence that counts: the message
265
+ // reaching the recipient's conversation. `steer` alone only reaches an in-memory queue.
266
+ this.unsubscribeConsumption?.();
267
+ this.unsubscribeConsumption = runtime.events?.subscribe((event) => {
268
+ if (event.type !== "message.appended")
269
+ return;
270
+ const origin = event.origin;
271
+ if (origin?.kind !== "background_task")
272
+ return;
273
+ this.stampNotified(origin.taskId);
274
+ });
275
+ }
276
+ /** Undo `attach`'s subscription. (Not `detach` — that one moves a tool call to the
277
+ * background and is part of the spawner surface.) */
278
+ detachRuntime() {
279
+ this.unsubscribeConsumption?.();
280
+ this.unsubscribeConsumption = undefined;
281
+ }
282
+ /**
283
+ * Load persisted task records for this session (called on reopen, before `reconcile`).
284
+ * Records whose id is already a live task in this process are skipped — live always wins.
285
+ */
286
+ async loadFromDisk() {
287
+ // `attach` may move a manager to another session. A storeless target must see an empty
288
+ // durable registry, not the prior session's already-loaded ghosts.
289
+ this.ghosts.clear();
290
+ if (this.persistence === undefined)
291
+ return;
292
+ for (const task of await this.persistence.listTasks()) {
293
+ if (this.tasks.has(task.taskId))
294
+ continue;
295
+ this.ghosts.set(task.taskId, task);
296
+ }
297
+ }
298
+ /**
299
+ * Reclassify orphaned tasks — a non-terminal ghost means the process that spawned it exited
300
+ * without writing a terminal status, so it is dead → `lost`. Writes the terminal status back
301
+ * (idempotent: `lost` is itself terminal, so a later reopen skips it) and emits a terminated
302
+ * event. Call after `loadFromDisk` on session reopen. Returns the reclassified records.
303
+ */
304
+ async reconcile() {
305
+ const lost = [];
306
+ for (const [id, task] of this.ghosts) {
307
+ if (!isPersistedTaskTerminal(task.status)) {
308
+ const updated = {
309
+ ...task,
310
+ status: "lost",
311
+ endedAt: task.endedAt ?? this.now(),
312
+ revision: task.revision + 1,
313
+ };
314
+ this.ghosts.set(id, updated);
315
+ await this.enqueuePersist(updated);
316
+ const info = publicTaskInfo(updated);
317
+ this.emitTerminated(info);
318
+ this.steerLost(info);
319
+ lost.push(info);
320
+ continue;
321
+ }
322
+ // Terminal, so the work itself finished — but if its notification was queued and never
323
+ // confirmed, the process died before the model ever saw the result. Resend it. (Neither
324
+ // stamp ⇒ nothing was ever owed: a suppressed settle. Leave it alone.)
325
+ if (task.notificationQueuedAt !== undefined && task.notifiedAt === undefined && !this.redelivered.has(id)) {
326
+ this.redelivered.add(id);
327
+ this.steerUnconfirmed(task);
328
+ }
329
+ }
330
+ return lost;
331
+ }
332
+ spawnCommand(start, command, description, options) {
333
+ return this.registerTask(new CommandBackgroundTask(start, command, description, options));
334
+ }
335
+ spawnQuestion(run, description, options) {
336
+ const taskId = this.registerTask(new QuestionBackgroundTask(run, description, options));
337
+ return { taskId, status: this.getTask(taskId)?.status ?? "running" };
338
+ }
339
+ // ── Attach / detach (foreground ↔ background) ─────────────────────────────────
340
+ registerDetachable(toolCallId) {
341
+ let controller = this.detachControllers.get(toolCallId);
342
+ if (controller === undefined) {
343
+ controller = new AbortController();
344
+ this.detachControllers.set(toolCallId, controller);
345
+ }
346
+ return controller.signal;
347
+ }
348
+ unregisterDetachable(toolCallId) {
349
+ this.detachControllers.delete(toolCallId);
350
+ }
351
+ detach(toolCallId) {
352
+ const controller = this.detachControllers.get(toolCallId);
353
+ if (controller === undefined)
354
+ return false;
355
+ controller.abort();
356
+ return true;
357
+ }
358
+ async runCommandAttached(start, command, description, options) {
359
+ const task = new CommandBackgroundTask(start, command, description, {
360
+ logPath: options.logPath,
361
+ machine: options.machine,
362
+ parentAddress: options.parentAddress,
363
+ toolCallId: options.toolCallId,
364
+ });
365
+ return this.runAttached(task, {
366
+ foregroundSignal: options.foregroundSignal,
367
+ detachSignal: options.detachSignal,
368
+ foregroundTimeoutMs: options.foregroundTimeoutMs,
369
+ onLive: options.onLive,
370
+ onDetachable: options.onDetachable,
371
+ getExitCode: () => task.exitCode,
372
+ });
373
+ }
374
+ /**
375
+ * Drive a task attached to the foreground, racing its settlement against a detach trigger.
376
+ * Owns the ONE controller both phases use: while attached it is bridged from
377
+ * `foregroundSignal` (abort → kill) and an optional foreground timeout; on detach the bridge
378
+ * is dropped (so the turn ending can't kill the now-background process) and the SAME
379
+ * controller is handed to the manager so BackgroundStop still works.
380
+ */
381
+ async runAttached(task, opts) {
382
+ // BackgroundManager's attached driver always requires canonical durable output, even when
383
+ // a low-level caller omitted the detach routing signal. Validate before starting so the
384
+ // optional routing seam can never silently reintroduce a pipe-only manager path.
385
+ this.assertDurableOutput(task);
386
+ const controller = new AbortController();
387
+ const sink = new SwappableSink(controller.signal);
388
+ let detached = false;
389
+ let cause;
390
+ let resolveSettled;
391
+ const settledP = new Promise((resolve) => {
392
+ resolveSettled = resolve;
393
+ });
394
+ let resolveDetached;
395
+ const detachedP = new Promise((resolve) => {
396
+ resolveDetached = resolve;
397
+ });
398
+ // A file-backed task pushes nothing (its output never enters this process), so the live
399
+ // echo comes from reading the file. The poll exists ONLY while someone is watching: it
400
+ // starts because `onLive` was supplied, and stops the moment the run detaches or settles.
401
+ // Nobody watching → not a single read, which is the whole reason the file is the store.
402
+ const follow = task.outputLocation?.kind === "file" && opts.onLive !== undefined
403
+ ? followOutputFile(task.outputLocation, (chunk) => {
404
+ if (!detached)
405
+ opts.onLive?.(chunk);
406
+ })
407
+ : undefined;
408
+ sink.setDownstream({
409
+ settle: async (settlement) => {
410
+ // Final read first: the command may have written between the last tick and its exit.
411
+ await follow?.drain();
412
+ resolveSettled(settlement);
413
+ return true;
414
+ },
415
+ });
416
+ // Aborting IS the whole stop protocol: a command task forwards the signal to `machine.run`,
417
+ // where SIGTERM → grace → SIGKILL escalation lives (the layer that can actually kill).
418
+ const kill = (why) => {
419
+ if (cause === undefined)
420
+ cause = why;
421
+ controller.abort();
422
+ };
423
+ const onForegroundAbort = () => kill("aborted");
424
+ if (opts.foregroundSignal.aborted)
425
+ kill("aborted");
426
+ else
427
+ opts.foregroundSignal.addEventListener("abort", onForegroundAbort);
428
+ const timeoutTimer = opts.foregroundTimeoutMs !== undefined ? setTimeout(() => kill("timeout"), opts.foregroundTimeoutMs) : undefined;
429
+ // Start the task. Its output already goes to its durable location; the sink owns only stop
430
+ // and settlement. On an error before settle, synthesize one so `settledP` always resolves.
431
+ const startPromise = Promise.resolve()
432
+ .then(() => task.start(sink))
433
+ .catch(async (error) => {
434
+ const aborted = controller.signal.aborted;
435
+ await sink.settle({
436
+ status: aborted ? "killed" : "failed",
437
+ stopReason: aborted ? undefined : errorMessage(error),
438
+ });
439
+ });
440
+ // "Long enough to be worth offering." A command that returns in milliseconds never makes
441
+ // the UI flash a "move to background" affordance the user could not have acted on; one
442
+ // that is still going after this gets the offer, and only then. Mirrors the threshold a
443
+ // progress indicator appears at, because it answers the same question: is this run slow?
444
+ const detachableTimer = opts.detachSignal !== undefined && opts.onDetachable !== undefined
445
+ ? setTimeout(() => {
446
+ if (!detached)
447
+ opts.onDetachable?.();
448
+ }, DETACHABLE_AFTER_MS)
449
+ : undefined;
450
+ if (detachableTimer !== undefined && typeof detachableTimer.unref === "function")
451
+ detachableTimer.unref();
452
+ const onDetach = () => {
453
+ if (detached)
454
+ return;
455
+ detached = true;
456
+ // The watcher is gone; the task keeps running and its file keeps growing, but nobody
457
+ // is looking, so nobody reads. BackgroundOutput windows the file on demand instead.
458
+ follow?.stop();
459
+ opts.foregroundSignal.removeEventListener("abort", onForegroundAbort);
460
+ if (timeoutTimer !== undefined)
461
+ clearTimeout(timeoutTimer);
462
+ const taskId = this.adoptRunning(task, controller, sink, startPromise);
463
+ resolveDetached(taskId);
464
+ };
465
+ if (opts.detachSignal !== undefined) {
466
+ if (opts.detachSignal.aborted)
467
+ onDetach();
468
+ else
469
+ opts.detachSignal.addEventListener("abort", onDetach, { once: true });
470
+ }
471
+ try {
472
+ const outcome = await Promise.race([
473
+ settledP.then((settlement) => ({ settlement })),
474
+ detachedP.then((taskId) => ({ taskId })),
475
+ ]);
476
+ if ("taskId" in outcome) {
477
+ return { kind: "detached", taskId: outcome.taskId };
478
+ }
479
+ let status = outcome.settlement.status === "paused" ? "failed" : outcome.settlement.status;
480
+ // The task reports a plain "killed" on abort; distinguish a foreground timeout.
481
+ if (status === "killed" && cause === "timeout")
482
+ status = "timed_out";
483
+ return { kind: "settled", status, exitCode: opts.getExitCode?.() ?? null };
484
+ }
485
+ finally {
486
+ follow?.stop();
487
+ if (detachableTimer !== undefined)
488
+ clearTimeout(detachableTimer);
489
+ opts.foregroundSignal.removeEventListener("abort", onForegroundAbort);
490
+ opts.detachSignal?.removeEventListener("abort", onDetach);
491
+ if (timeoutTimer !== undefined)
492
+ clearTimeout(timeoutTimer);
493
+ }
494
+ }
495
+ /**
496
+ * Adopt an already-running task (started by `runAttached`) into the managed set, reusing its
497
+ * existing abort controller and swapping the sink downstream to this manager. Does NOT call
498
+ * `task.start` (already running) and intentionally bypasses the running-task cap: detaching
499
+ * promotes work that is already executing, it does not start new work.
500
+ */
501
+ adoptRunning(task, controller, sink, lifecyclePromise) {
502
+ this.assertDurableOutput(task);
503
+ const taskId = generateTaskId(task.idPrefix);
504
+ const entry = {
505
+ taskId,
506
+ task,
507
+ status: "running",
508
+ startedAt: this.now(),
509
+ endedAt: null,
510
+ waiters: [],
511
+ terminalFired: false,
512
+ revision: 0,
513
+ abortController: controller,
514
+ lifecyclePromise,
515
+ };
516
+ this.tasks.set(taskId, entry);
517
+ // Hand the still-running task's eventual settlement to this manager entry. Its output
518
+ // continues writing to the same durable location it had while attached.
519
+ sink.setDownstream({
520
+ settle: (settlement) => this.settleTask(entry, settlement),
521
+ });
522
+ this.emitStarted(this.toInfo(entry));
523
+ void this.persistLive(entry);
524
+ return taskId;
525
+ }
526
+ registerTask(task) {
527
+ this.assertDurableOutput(task);
528
+ this.assertCanRegister();
529
+ const taskId = generateTaskId(task.idPrefix);
530
+ const entry = {
531
+ taskId,
532
+ task,
533
+ status: "running",
534
+ startedAt: this.now(),
535
+ endedAt: null,
536
+ waiters: [],
537
+ terminalFired: false,
538
+ revision: 0,
539
+ abortController: new AbortController(),
540
+ lifecyclePromise: Promise.resolve(),
541
+ };
542
+ this.tasks.set(taskId, entry);
543
+ // Persist the origin + stable task id BEFORE starting user work. If the process dies after
544
+ // start but before the spawn ack reaches conversation history, cold recovery can still map
545
+ // `(parentAddress, toolCallId)` back to this task. A failed persistence backend is already
546
+ // fail-soft inside persistLive; storeless sessions simply continue in memory.
547
+ const persisted = this.persistLive(entry);
548
+ entry.lifecyclePromise = persisted
549
+ .then(() => task.start({
550
+ signal: entry.abortController.signal,
551
+ settle: (settlement) => this.settleTask(entry, settlement),
552
+ }))
553
+ .catch(async (error) => {
554
+ const aborted = entry.abortController.signal.aborted;
555
+ await this.settleTask(entry, {
556
+ status: aborted ? "killed" : "failed",
557
+ stopReason: aborted ? undefined : errorMessage(error),
558
+ });
559
+ });
560
+ this.emitStarted(this.toInfo(entry));
561
+ return taskId;
562
+ }
563
+ /** The durable projection of a task. The output's address comes from the task itself and is
564
+ * never reconstructed from an id. */
565
+ toPersisted(entry) {
566
+ const info = this.toInfo(entry);
567
+ const ledger = {
568
+ ...(entry.notificationQueuedAt !== undefined ? { notificationQueuedAt: entry.notificationQueuedAt } : {}),
569
+ ...(entry.notifiedAt !== undefined ? { notifiedAt: entry.notifiedAt } : {}),
570
+ };
571
+ return { ...info, schemaVersion: 2, revision: entry.revision, ...ledger };
572
+ }
573
+ /** Queue a snapshot behind every earlier write. This prevents a slow `running` write from
574
+ * landing after a terminal snapshot, and prevents concurrent KV index updates losing ids. */
575
+ enqueuePersist(task) {
576
+ const persistence = this.persistence;
577
+ if (persistence === undefined)
578
+ return Promise.resolve();
579
+ const write = this.persistenceChain
580
+ .catch(() => undefined)
581
+ .then(() => persistence.writeTask(task))
582
+ .then(() => undefined, () => undefined);
583
+ this.persistenceChain = write;
584
+ return write;
585
+ }
586
+ /** Capture the next monotonic revision before placing it on the persistence queue. */
587
+ async persistLive(entry) {
588
+ if (this.persistence === undefined)
589
+ return;
590
+ entry.revision += 1;
591
+ await this.enqueuePersist(this.toPersisted(entry));
592
+ }
593
+ assertCanRegister() {
594
+ if (this.maxRunningTasks === undefined)
595
+ return;
596
+ if (this.activeTaskCount() < this.maxRunningTasks)
597
+ return;
598
+ throw new Error("Too many background tasks are already running.");
599
+ }
600
+ /** Background status is metadata, never a result store. Every non-question task must point
601
+ * at exactly one authoritative durable output location before it can enter the registry. */
602
+ assertDurableOutput(task) {
603
+ const kind = task.outputLocation?.kind;
604
+ const valid = (task.kind === "process" && kind === "file") ||
605
+ (task.kind === "agent" && kind === "conversation") ||
606
+ (task.kind === "workflow" && kind === "workflow-run") ||
607
+ (task.kind === "question" && kind === undefined);
608
+ if (!valid) {
609
+ throw new Error(`Background ${task.kind} tasks require their canonical durable output location.`);
610
+ }
611
+ if ((kind === "conversation" || kind === "workflow-run") && this.store === undefined) {
612
+ throw new Error(`Background ${task.kind} tasks require an attached durable session store.`);
613
+ }
614
+ }
615
+ activeTaskCount() {
616
+ let count = 0;
617
+ for (const entry of this.tasks.values())
618
+ if (!TERMINAL_STATUSES.has(entry.status))
619
+ count++;
620
+ return count;
621
+ }
622
+ getTask(taskId) {
623
+ const entry = this.tasks.get(taskId);
624
+ if (entry !== undefined)
625
+ return this.toInfo(entry);
626
+ const ghost = this.ghosts.get(taskId);
627
+ return ghost === undefined ? undefined : publicTaskInfo(ghost);
628
+ }
629
+ /** Find the task spawned by one assistant tool call. `toolCallId` is provider-scoped, so the
630
+ * parent conversation address is part of the identity. Used internally by cold recovery;
631
+ * model-facing reads continue to use the stable task id via BackgroundOutput. */
632
+ findByOrigin(parentAddress, toolCallId) {
633
+ for (const entry of this.tasks.values()) {
634
+ if (entry.task.parentAddress === parentAddress && entry.task.toolCallId === toolCallId) {
635
+ return this.toInfo(entry);
636
+ }
637
+ }
638
+ for (const task of this.ghosts.values()) {
639
+ if (task.parentAddress === parentAddress && task.toolCallId === toolCallId)
640
+ return publicTaskInfo(task);
641
+ }
642
+ return undefined;
643
+ }
644
+ list(activeOnly = true, limit) {
645
+ const result = [];
646
+ for (const entry of this.tasks.values()) {
647
+ if (activeOnly && TERMINAL_STATUSES.has(entry.status))
648
+ continue;
649
+ result.push(this.toInfo(entry));
650
+ if (limit !== undefined && result.length >= limit)
651
+ return result;
652
+ }
653
+ // Ghosts are all terminal (loaded from a prior process, then reconciled), so they only
654
+ // surface when the caller wants terminal tasks too. Skip any now driven live.
655
+ if (!activeOnly) {
656
+ for (const [id, task] of this.ghosts) {
657
+ if (this.tasks.has(id))
658
+ continue;
659
+ result.push(publicTaskInfo(task));
660
+ if (limit !== undefined && result.length >= limit)
661
+ return result;
662
+ }
663
+ }
664
+ return result;
665
+ }
666
+ /**
667
+ * A bounded WINDOW onto a task's output, plus the truth about how much it is a window of.
668
+ * Never the whole thing: `sizeBytes` says how much exists, `truncated` admits the
669
+ * rest was dropped, and the location says where the complete record lives.
670
+ *
671
+ * Dispatch is on WHERE the output lives, not on what kind of task produced it — a file gets
672
+ * a byte window and a shard gets its durable record reduced to a useful preview. A question
673
+ * has no output location — its answer rides on the task record itself — so it is served
674
+ * from there: the settle notification truncates a long answer and points here for the rest.
675
+ */
676
+ async readOutput(taskId, maxBytes = MAX_OUTPUT_BYTES) {
677
+ const entry = this.tasks.get(taskId);
678
+ // A ghost (loaded from a prior process) has no live entry but may still name a location —
679
+ // a log file outlives the process that wrote it, and so does a shard.
680
+ if (entry === undefined)
681
+ return await this.ghostOutputSnapshot(taskId, maxBytes);
682
+ const location = entry.task.outputLocation;
683
+ if (location?.kind === "file")
684
+ return await tailFileSnapshot(location, Math.max(0, Math.trunc(maxBytes)));
685
+ if (location?.kind === "conversation")
686
+ return await this.conversationSnapshot(location.address, Math.max(0, Math.trunc(maxBytes)));
687
+ if (location?.kind === "workflow-run")
688
+ return await this.workflowRunSnapshot(location.address, Math.max(0, Math.trunc(maxBytes)));
689
+ const info = this.toInfo(entry);
690
+ if (info.kind === "question" && info.answer !== undefined)
691
+ return textSnapshot(info.answer, maxBytes);
692
+ return emptyOutputSnapshot();
693
+ }
694
+ /**
695
+ * A sub-agent's output, read back from its own conversation shard.
696
+ *
697
+ * The shard is the record — the same one the projection folds for a UI — so this reads it
698
+ * rather than keeping a copy. It works on a RUNNING agent too: its messages are appended as
699
+ * the run proceeds, so the latest answer is whatever it has said so far, not a blank until
700
+ * the run settles.
701
+ */
702
+ async conversationSnapshot(address, maxBytes) {
703
+ const store = this.store;
704
+ if (store === undefined)
705
+ return emptyOutputSnapshot();
706
+ try {
707
+ const records = [];
708
+ for await (const record of store.readRecords({ address }))
709
+ records.push(record);
710
+ const { messages } = reduceHistory(records);
711
+ // The agent's answer is the last thing it said. Tool calls and their results are steps
712
+ // toward it, already in the shard for anyone who wants the whole trace.
713
+ return textSnapshot(lastAssistantText(messages), maxBytes);
714
+ }
715
+ catch {
716
+ return emptyOutputSnapshot();
717
+ }
718
+ }
719
+ /**
720
+ * A workflow run, rendered from its journal.
721
+ *
722
+ * The journal is the run's whole story in append order — inputs, each agent starting and
723
+ * returning, the script's own `log()` lines, failures, and the outcome — so this reads it
724
+ * rather than keeping a parallel copy of the progress stream. It answers for a RUNNING run
725
+ * too: entries land as each step completes, so "where is it up to" is just the story so far.
726
+ */
727
+ async workflowRunSnapshot(address, maxBytes) {
728
+ const store = this.store;
729
+ if (store === undefined)
730
+ return emptyOutputSnapshot();
731
+ try {
732
+ const lines = [];
733
+ for await (const record of store.readRecords({ address })) {
734
+ if (record.type !== "custom" || record.name !== WORKFLOW_JOURNAL_ENTRY)
735
+ continue;
736
+ const line = renderWorkflowJournalEntry(record.data);
737
+ if (line !== undefined)
738
+ lines.push(line);
739
+ }
740
+ // Cut at the BACK: a run reads forward from its first step.
741
+ return textSnapshot(lines.join("\n"), maxBytes);
742
+ }
743
+ catch {
744
+ return emptyOutputSnapshot();
745
+ }
746
+ }
747
+ /** A task with no live entry: its location, if any, outlived the process that ran it. */
748
+ async ghostOutputSnapshot(taskId, maxBytes) {
749
+ const ghost = this.ghosts.get(taskId);
750
+ if (ghost === undefined)
751
+ return emptyOutputSnapshot();
752
+ const limit = Math.max(0, Math.trunc(maxBytes));
753
+ if (ghost.outputRef?.kind === "conversation") {
754
+ return await this.conversationSnapshot(ghost.outputRef.address, limit);
755
+ }
756
+ if (ghost.outputRef?.kind === "workflow-run") {
757
+ return await this.workflowRunSnapshot(ghost.outputRef.address, limit);
758
+ }
759
+ // A question's answer is persisted on the task record itself, so it survives the process.
760
+ if (ghost.kind === "question" && ghost.answer !== undefined)
761
+ return textSnapshot(ghost.answer, limit);
762
+ // A process ghost knows its output path but not the machine it lived on — the Machine is a
763
+ // live handle, not a serialisable one. The tool surfaces `output_path` for a `Read`.
764
+ return emptyOutputSnapshot();
765
+ }
766
+ /**
767
+ * Everything appended since `cursor`, for a viewer that is following along — the shape
768
+ * a live panel needs, and the one that keeps a tick costing what was WRITTEN rather than
769
+ * what the task has produced in total.
770
+ *
771
+ * Only file-backed tasks can serve it: their output has a stable byte offset because the
772
+ * file keeps everything. Anything else is not followable and the caller falls back to a
773
+ * snapshot — for a shard-backed agent the better live view is the SessionProjection, which
774
+ * folds the same records the UI already subscribes to.
775
+ */
776
+ async readOutputDelta(taskId, cursor, maxBytes = MAX_OUTPUT_BYTES) {
777
+ const from = Math.max(0, Math.trunc(cursor));
778
+ const entry = this.tasks.get(taskId);
779
+ if (entry === undefined)
780
+ return { content: "", nextCursor: from, followable: false };
781
+ const location = entry.task.outputLocation;
782
+ if (location?.kind !== "file")
783
+ return { content: "", nextCursor: from, followable: false };
784
+ const file = location;
785
+ try {
786
+ const bytes = await file.machine.readBytes(file.path, { offset: from, length: Math.max(0, Math.trunc(maxBytes)) });
787
+ // Leave a trailing partial sequence behind and advance the cursor only past what was
788
+ // decodable: the next tick re-reads those bytes and completes the character.
789
+ const whole = bytes.subarray(0, utf8AlignEnd(bytes));
790
+ return { content: whole.toString("utf-8"), nextCursor: from + whole.byteLength, followable: true };
791
+ }
792
+ catch {
793
+ // Gone after cleanup or the Machine is temporarily unreachable.
794
+ return { content: "", nextCursor: from, followable: true };
795
+ }
796
+ }
797
+ async suppressTerminalNotification(taskId) {
798
+ const entry = this.tasks.get(taskId);
799
+ if (entry === undefined || entry.terminalNotificationSuppressed === true)
800
+ return;
801
+ entry.terminalNotificationSuppressed = true;
802
+ }
803
+ async stop(taskId, reason) {
804
+ const entry = this.tasks.get(taskId);
805
+ if (!entry)
806
+ return undefined;
807
+ const trimmedReason = reason?.trim();
808
+ const stopReason = trimmedReason === undefined || trimmedReason.length === 0 ? undefined : trimmedReason;
809
+ if (TERMINAL_STATUSES.has(entry.status)) {
810
+ return this.toInfo(entry);
811
+ }
812
+ entry.stopReason = stopReason;
813
+ entry.abortController.abort(stopReason);
814
+ // Wait up to 5s for the lifecycle path to settle, then SIGKILL. Waiting on
815
+ // lifecyclePromise lets a natural completion win the race over the kill.
816
+ let graceTimer;
817
+ const graceful = await Promise.race([
818
+ entry.lifecyclePromise.then(() => true, () => true),
819
+ new Promise((resolve) => {
820
+ graceTimer = setTimeout(() => resolve(false), SIGTERM_GRACE_MS);
821
+ }),
822
+ ]);
823
+ if (graceTimer !== undefined)
824
+ clearTimeout(graceTimer);
825
+ if (TERMINAL_STATUSES.has(entry.status)) {
826
+ return this.toInfo(entry);
827
+ }
828
+ // `graceful: false` adds no second escalation step here — the task's own backend already
829
+ // escalated when the signal fired. What is left is to record the terminal status.
830
+ await this.settleTask(entry, { status: "killed", stopReason });
831
+ return this.toInfo(entry);
832
+ }
833
+ async stopAll(reason) {
834
+ const ids = Array.from(this.tasks.keys());
835
+ const results = await Promise.all(ids.map((id) => this.stop(id, reason)));
836
+ return results.filter((info) => info !== undefined);
837
+ }
838
+ async wait(taskId, timeoutMs = 30_000) {
839
+ const entry = this.tasks.get(taskId);
840
+ if (!entry)
841
+ return undefined;
842
+ if (TERMINAL_STATUSES.has(entry.status)) {
843
+ return this.toInfo(entry);
844
+ }
845
+ let terminalWaiter;
846
+ let timeout;
847
+ try {
848
+ await Promise.race([
849
+ new Promise((resolve) => {
850
+ terminalWaiter = resolve;
851
+ entry.waiters.push(resolve);
852
+ }),
853
+ new Promise((resolve) => {
854
+ timeout = setTimeout(resolve, timeoutMs);
855
+ }),
856
+ ]);
857
+ }
858
+ finally {
859
+ if (timeout !== undefined)
860
+ clearTimeout(timeout);
861
+ if (terminalWaiter !== undefined) {
862
+ const index = entry.waiters.indexOf(terminalWaiter);
863
+ if (index !== -1)
864
+ entry.waiters.splice(index, 1);
865
+ }
866
+ }
867
+ return this.toInfo(entry);
868
+ }
869
+ async settleTask(entry, settlement) {
870
+ if (TERMINAL_STATUSES.has(entry.status)) {
871
+ if (entry.status === "killed" && settlement.status === "killed") {
872
+ entry.endedAt = Math.max(this.now(), (entry.endedAt ?? 0) + 1);
873
+ this.fireTerminalEffects(entry);
874
+ this.resolveWaiters(entry);
875
+ }
876
+ return false;
877
+ }
878
+ entry.status = settlement.status;
879
+ entry.endedAt = this.now();
880
+ entry.stopReason = settlement.stopReason ?? (settlement.status === "killed" ? entry.stopReason : undefined);
881
+ // Persist the terminal status before firing effects so the durable record is written
882
+ // before the run is observably done — a crash after this leaves a correct terminal record,
883
+ // not a `running` one that reconcile would wrongly mark lost.
884
+ await this.persistLive(entry);
885
+ this.fireTerminalEffects(entry);
886
+ this.resolveWaiters(entry);
887
+ return true;
888
+ }
889
+ resolveWaiters(entry) {
890
+ for (const resolve of entry.waiters.splice(0))
891
+ resolve();
892
+ }
893
+ fireTerminalEffects(entry) {
894
+ if (entry.terminalFired)
895
+ return;
896
+ entry.terminalFired = true;
897
+ const info = this.toInfo(entry);
898
+ this.emitTerminated(info);
899
+ this.steerTerminal(info);
900
+ }
901
+ steerTerminal(info) {
902
+ if (this.steer === undefined)
903
+ return;
904
+ if (this.isTerminalNotificationSuppressed(info.taskId))
905
+ return;
906
+ const summary = buildTerminalSummary(info, { answer: this.answeredQuestionOutput(info) });
907
+ // The rendered tag is the durable settle record (journaled next turn); the identity
908
+ // attrs are what the subagent/workflow folds match on.
909
+ this.steer.steer(summary, {
910
+ kind: "background_done",
911
+ taskId: info.taskId,
912
+ summary,
913
+ ...(settleToolCallId(info) !== undefined ? { toolCallId: settleToolCallId(info) } : {}),
914
+ ...settleIdentity(info),
915
+ });
916
+ this.stampNotificationQueued(info.taskId);
917
+ }
918
+ /**
919
+ * A finished question's answer.
920
+ *
921
+ * The ONE kind whose settle must carry its output. Every other kind's substance survives
922
+ * the notification: a command's bytes are in its log file, a subagent's final message is in
923
+ * its shard, a workflow's agent results are in its journal. A question's answer is the user
924
+ * SPEAKING — unreproducible, and held nowhere but this process's memory. Leaving it out of
925
+ * the settle would drop what the user said out of the conversation record entirely.
926
+ *
927
+ * Read straight off the task's own record — no buffer involved, so this stays synchronous
928
+ * and `steerTerminal` never has to await (awaiting would reopen the suppression race that
929
+ * going sync closed).
930
+ */
931
+ answeredQuestionOutput(info) {
932
+ if (info.kind !== "question" || info.status !== "completed")
933
+ return undefined;
934
+ return info.answer !== undefined && info.answer.length > 0 ? info.answer : undefined;
935
+ }
936
+ /**
937
+ * Open the ledger entry: a notification is owed from here until its `message.appended`
938
+ * confirms it. Deliberately written AFTER the enqueue, not before — the write is the slow
939
+ * part, and a crash between the two only costs a duplicate settle on reopen, whereas
940
+ * enqueueing after a failed write would cost a silent loss.
941
+ */
942
+ stampNotificationQueued(taskId) {
943
+ if (this.persistence === undefined)
944
+ return;
945
+ const entry = this.tasks.get(taskId);
946
+ if (entry !== undefined) {
947
+ entry.notificationQueuedAt = this.now();
948
+ void this.persistLive(entry);
949
+ return;
950
+ }
951
+ const ghost = this.ghosts.get(taskId);
952
+ if (ghost === undefined)
953
+ return;
954
+ const updated = { ...ghost, notificationQueuedAt: this.now(), revision: ghost.revision + 1 };
955
+ this.ghosts.set(taskId, updated);
956
+ void this.enqueuePersist(updated);
957
+ }
958
+ /** Close it: the settle is in the recipient's conversation and will never need resending. */
959
+ stampNotified(taskId) {
960
+ if (this.persistence === undefined)
961
+ return;
962
+ const entry = this.tasks.get(taskId);
963
+ if (entry !== undefined) {
964
+ if (entry.notifiedAt !== undefined)
965
+ return;
966
+ entry.notifiedAt = this.now();
967
+ void this.persistLive(entry);
968
+ return;
969
+ }
970
+ const ghost = this.ghosts.get(taskId);
971
+ if (ghost === undefined || ghost.notifiedAt !== undefined)
972
+ return;
973
+ const updated = { ...ghost, notifiedAt: this.now(), revision: ghost.revision + 1 };
974
+ this.ghosts.set(taskId, updated);
975
+ void this.enqueuePersist(updated);
976
+ }
977
+ isTerminalNotificationSuppressed(taskId) {
978
+ return this.tasks.get(taskId)?.terminalNotificationSuppressed === true;
979
+ }
980
+ /** Steer a lost notification for a task reconciled on reopen, so the model learns its
981
+ * background work died with the previous process (the journaled tag is the settle record). */
982
+ steerLost(info) {
983
+ if (this.steer === undefined)
984
+ return;
985
+ const summary = `${info.description} was running when the previous process exited; marked lost.`;
986
+ this.steer.steer(summary, { kind: "background_done", taskId: info.taskId, summary, ...settleIdentity(info) });
987
+ // A lost-notice can itself be lost — the ledger covers it on the same terms.
988
+ this.stampNotificationQueued(info.taskId);
989
+ }
990
+ /**
991
+ * Resend a settle whose notification was queued but never confirmed — i.e. the process died
992
+ * in the window between the enqueue and the recipient consuming it.
993
+ *
994
+ * Output survival is stated by `outputRef`, not inferred from task kind. Files, conversation
995
+ * shards, and workflow journals all outlive this manager; an answered question is recovered
996
+ * from the task record itself.
997
+ */
998
+ steerUnconfirmed(task) {
999
+ if (this.steer === undefined)
1000
+ return;
1001
+ const answer = task.kind === "question" && task.status === "completed" ? task.answer : undefined;
1002
+ const readable = answer !== undefined ||
1003
+ task.outputRef?.kind === "file" ||
1004
+ ((task.outputRef?.kind === "conversation" || task.outputRef?.kind === "workflow-run") && this.store !== undefined);
1005
+ const note = readable
1006
+ ? "(Settled in an earlier process; its durable output is still available.)"
1007
+ : "(Settled in an earlier process; no durable output reference is available.)";
1008
+ const summary = `${buildTerminalSummary(task, { outputReadable: readable, answer })}\n${note}`;
1009
+ this.steer.steer(summary, { kind: "background_done", taskId: task.taskId, summary, ...settleIdentity(task) });
1010
+ this.stampNotificationQueued(task.taskId);
1011
+ }
1012
+ emitStarted(info) {
1013
+ void this.events?.emit({ address: this.address, sessionId: this.sessionId, type: "background.task.started", info });
1014
+ }
1015
+ emitTerminated(info) {
1016
+ void this.events?.emit({ address: this.address, sessionId: this.sessionId, type: "background.task.terminated", info });
1017
+ }
1018
+ toInfo(entry) {
1019
+ const outputRef = taskOutputRef(entry.task.outputLocation);
1020
+ const base = {
1021
+ taskId: entry.taskId,
1022
+ ...(entry.task.parentAddress !== undefined ? { parentAddress: entry.task.parentAddress } : {}),
1023
+ ...(entry.task.toolCallId !== undefined ? { toolCallId: entry.task.toolCallId } : {}),
1024
+ description: entry.task.description,
1025
+ status: entry.status,
1026
+ startedAt: entry.startedAt,
1027
+ endedAt: entry.endedAt,
1028
+ stopReason: entry.stopReason,
1029
+ terminalNotificationSuppressed: entry.terminalNotificationSuppressed,
1030
+ timeoutMs: entry.task.timeoutMs,
1031
+ ...(outputRef !== undefined ? { outputRef } : {}),
1032
+ };
1033
+ return entry.task.toInfo(base);
1034
+ }
1035
+ }
1036
+ /** Identity + fine-grained status attrs for a settle notification, per task kind. */
1037
+ /** The tool call a task was spawned from, for the kinds that record one. */
1038
+ function settleToolCallId(info) {
1039
+ return info.toolCallId;
1040
+ }
1041
+ function settleIdentity(info) {
1042
+ if (info.kind === "agent") {
1043
+ return { agentId: info.agentId, status: info.agentStatus ?? subagentStatusFromTask(info.status) };
1044
+ }
1045
+ if (info.kind === "workflow") {
1046
+ return { runId: info.runId, status: info.runStatus ?? workflowStatusFromTask(info.status) };
1047
+ }
1048
+ return {};
1049
+ }
1050
+ /** Coarse fallback when the run didn't report its own status (e.g. timed out, killed). */
1051
+ function subagentStatusFromTask(status) {
1052
+ return status === "completed"
1053
+ ? "completed"
1054
+ : status === "paused"
1055
+ ? "paused"
1056
+ : status === "killed"
1057
+ ? "cancelled"
1058
+ : status === "lost"
1059
+ ? "lost"
1060
+ : "error";
1061
+ }
1062
+ function workflowStatusFromTask(status) {
1063
+ return status === "completed" ? "completed" : status === "killed" || status === "lost" ? "aborted" : "failed";
1064
+ }
1065
+ /** Generous by design: a hand-typed answer never approaches it, so the cap only ever fires on
1066
+ * something pathological, and the notice stays the whole record in every real case. */
1067
+ const QUESTION_ANSWER_MAX_CHARS = 8_000;
1068
+ /**
1069
+ * The settle notification: METADATA ONLY, with one exception.
1070
+ *
1071
+ * A terminal notice arrives unbidden. Nobody asked for it, and it lands in the recipient's
1072
+ * context whether or not the substance is wanted — so it carries what only the settle knows
1073
+ * (how it ended, the exit code, where the log lives) and stops there. The output is a
1074
+ * resource, fetched deliberately, paid for at the moment the model decides it needs it.
1075
+ * Attaching a fixed tail instead would charge every task the same bytes regardless: too few
1076
+ * to conclude anything on a long run, pure waste on one whose exit code already said it all.
1077
+ *
1078
+ * The exception is a question's answer, which is not output but conversation — the user's own
1079
+ * words, held nowhere else. It rides along in full, and the read instruction is dropped with
1080
+ * it: there is nothing left to go fetch.
1081
+ *
1082
+ * The task id is already an attribute of the enclosing `<background-task-done>` tag; it is
1083
+ * repeated in the read instruction so that line can be copied straight into a call.
1084
+ */
1085
+ /** The last thing the assistant said, which is a sub-agent's answer. Mirrors `finalText` in
1086
+ * run-support, kept local so the capability does not depend on the agent layer. */
1087
+ function lastAssistantText(messages) {
1088
+ for (let i = messages.length - 1; i >= 0; i--) {
1089
+ const message = messages[i];
1090
+ if (message?.role !== "assistant")
1091
+ continue;
1092
+ return message.content
1093
+ .filter((part) => part.type === "text")
1094
+ .map((part) => part.text)
1095
+ .join("");
1096
+ }
1097
+ return "";
1098
+ }
1099
+ function buildTerminalSummary(info, options = {}) {
1100
+ // Exit code is a process fact; the other kinds report their outcome through `status`.
1101
+ const exit = info.kind === "process" && info.exitCode !== null ? ` (exit code ${String(info.exitCode)})` : "";
1102
+ const head = info.status === "timed_out"
1103
+ ? `${info.description} timed out${exit}.`
1104
+ : info.stopReason
1105
+ ? `${info.description} ${info.status === "killed" ? "was killed" : info.status}${exit}: ${info.stopReason}.`
1106
+ : `${info.description} ${info.status}${exit}.`;
1107
+ const logPath = info.outputRef?.kind === "file" ? info.outputRef.path : undefined;
1108
+ const lines = [head];
1109
+ if (logPath !== undefined)
1110
+ lines.push(`output_log: ${logPath}`);
1111
+ // Character-truncated, not byte-windowed: the answer is a JSON string, and slicing it at a
1112
+ // byte offset would split a multi-byte character — the very defect the byte-window readers
1113
+ // elsewhere in this file still carry.
1114
+ const answer = options.answer;
1115
+ if (answer !== undefined) {
1116
+ const truncated = answer.length > QUESTION_ANSWER_MAX_CHARS;
1117
+ lines.push(truncated ? "[answer, truncated]" : "[answer]", truncated ? answer.slice(0, QUESTION_ANSWER_MAX_CHARS) : answer);
1118
+ // Only a truncated answer leaves anything behind to fetch.
1119
+ if (truncated)
1120
+ lines.push(`Read the full answer with BackgroundOutput(task_id="${info.taskId}").`);
1121
+ return lines.join("\n");
1122
+ }
1123
+ if (options.outputReadable ?? true) {
1124
+ lines.push(logPath !== undefined
1125
+ ? `Read its output with BackgroundOutput(task_id="${info.taskId}"), or Read the log file above for the full, never-truncated record.`
1126
+ : `Read its output with BackgroundOutput(task_id="${info.taskId}").`);
1127
+ }
1128
+ return lines.join("\n");
1129
+ }
1130
+ export { isBackgroundTaskTerminal };
1131
+ //# sourceMappingURL=manager.js.map