@cortex-agent/server 2026.9.9 → 2026.9.14

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 (816) hide show
  1. package/defaults/config/hooks/CORTEX.md +0 -3
  2. package/defaults/context/CORTEX.md +2 -2
  3. package/defaults/context/user/CORTEX.md +2 -2
  4. package/defaults/data/schedules.json +3 -13
  5. package/defaults/hooks/CORTEX.md +0 -2
  6. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +2 -2
  7. package/defaults/plugins/cortex-system/plugin.json +2 -2
  8. package/defaults/plugins/cortex-system/skills/approval/SKILL.md +1 -1
  9. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +6 -6
  10. package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +1 -1
  11. package/defaults/rules/correction-propagation.md +1 -1
  12. package/defaults/rules/mission-md.md +2 -2
  13. package/defaults/rules/overview-md.md +1 -1
  14. package/defaults/rules/roadmap-md.md +1 -1
  15. package/dist/agent-adapter/bg-wait.d.ts +3 -29
  16. package/dist/agent-adapter/bg-wait.js +6 -266
  17. package/dist/agent-adapter/browser-mcp-server.js +0 -4
  18. package/dist/agent-adapter/capabilities.d.ts +10 -1
  19. package/dist/agent-adapter/capabilities.js +16 -4
  20. package/dist/agent-adapter/claude/active-capture-registry.js +0 -4
  21. package/dist/agent-adapter/claude/adapter.d.ts +109 -211
  22. package/dist/agent-adapter/claude/adapter.js +229 -1208
  23. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +1 -1
  24. package/dist/agent-adapter/claude/bg-task-tracker.js +0 -4
  25. package/dist/agent-adapter/claude/browser-mcp.js +0 -4
  26. package/dist/agent-adapter/claude/compact-window.js +0 -4
  27. package/dist/agent-adapter/claude/context-usage.js +0 -4
  28. package/dist/agent-adapter/claude/defaults.d.ts +30 -38
  29. package/dist/agent-adapter/claude/defaults.js +33 -46
  30. package/dist/agent-adapter/claude/engine.d.ts +84 -0
  31. package/dist/agent-adapter/claude/engine.js +207 -0
  32. package/dist/agent-adapter/claude/event-parser.d.ts +2 -1
  33. package/dist/agent-adapter/claude/event-parser.js +5 -9
  34. package/dist/agent-adapter/claude/event-translator.d.ts +46 -0
  35. package/dist/agent-adapter/claude/event-translator.js +112 -0
  36. package/dist/agent-adapter/claude/hooks-builder.d.ts +5 -9
  37. package/dist/agent-adapter/claude/hooks-builder.js +9 -26
  38. package/dist/agent-adapter/claude/mcp-config.js +0 -4
  39. package/dist/agent-adapter/claude/remote-mcp-proxy.js +0 -4
  40. package/dist/agent-adapter/claude/spawn-args.d.ts +2 -9
  41. package/dist/agent-adapter/claude/spawn-args.js +79 -30
  42. package/dist/agent-adapter/claude/tmux-control.d.ts +5 -2
  43. package/dist/agent-adapter/claude/tmux-control.js +5 -6
  44. package/dist/agent-adapter/claude/tool-summarizers.js +0 -4
  45. package/dist/agent-adapter/claude/transcript-path.d.ts +28 -0
  46. package/dist/agent-adapter/claude/transcript-path.js +36 -0
  47. package/dist/agent-adapter/claude/turn-machine.d.ts +209 -0
  48. package/dist/agent-adapter/claude/turn-machine.js +746 -0
  49. package/dist/agent-adapter/continuation-phase.d.ts +125 -0
  50. package/dist/agent-adapter/continuation-phase.js +366 -0
  51. package/dist/agent-adapter/index.d.ts +1 -14
  52. package/dist/agent-adapter/index.js +1 -95
  53. package/dist/agent-adapter/mcp-private-dir.js +0 -4
  54. package/dist/agent-adapter/mcp-remote-fetch.js +0 -4
  55. package/dist/agent-adapter/normalize/event-stream.d.ts +3 -0
  56. package/dist/agent-adapter/normalize/event-stream.js +1 -5
  57. package/dist/agent-adapter/normalize/event-types.d.ts +9 -0
  58. package/dist/agent-adapter/normalize/event-types.js +0 -4
  59. package/dist/agent-adapter/normalize/hooks.js +0 -4
  60. package/dist/agent-adapter/normalize/prompt-builder.d.ts +3 -2
  61. package/dist/agent-adapter/normalize/prompt-builder.js +1 -1
  62. package/dist/agent-adapter/normalize/todo.js +1 -5
  63. package/dist/agent-adapter/pi/adapter.d.ts +69 -24
  64. package/dist/agent-adapter/pi/adapter.js +127 -130
  65. package/dist/agent-adapter/pi/agent-dir.d.ts +22 -5
  66. package/dist/agent-adapter/pi/agent-dir.js +41 -22
  67. package/dist/agent-adapter/pi/background-subagent.d.ts +16 -0
  68. package/dist/agent-adapter/pi/background-subagent.js +1 -0
  69. package/dist/agent-adapter/pi/child-events.d.ts +30 -0
  70. package/dist/agent-adapter/pi/child-events.js +116 -0
  71. package/dist/agent-adapter/pi/child-runner.d.ts +37 -0
  72. package/dist/agent-adapter/pi/child-runner.js +139 -0
  73. package/dist/agent-adapter/pi/child-session.js +0 -4
  74. package/dist/agent-adapter/pi/custom-catalog.js +0 -4
  75. package/dist/agent-adapter/pi/defaults.js +0 -4
  76. package/dist/agent-adapter/pi/discovery.d.ts +23 -2
  77. package/dist/agent-adapter/pi/discovery.js +25 -60
  78. package/dist/agent-adapter/pi/engine.d.ts +74 -0
  79. package/dist/agent-adapter/pi/engine.js +247 -0
  80. package/dist/agent-adapter/pi/event-parser.d.ts +11 -3
  81. package/dist/agent-adapter/pi/event-parser.js +15 -37
  82. package/dist/agent-adapter/pi/extensions.d.ts +10 -1
  83. package/dist/agent-adapter/pi/extensions.js +9 -7
  84. package/dist/agent-adapter/pi/hook-bridge.js +0 -4
  85. package/dist/agent-adapter/pi/mcp-bridge-logic.js +0 -4
  86. package/dist/agent-adapter/pi/mcp-bridge.d.ts +10 -1
  87. package/dist/agent-adapter/pi/mcp-bridge.js +33 -23
  88. package/dist/agent-adapter/pi/pi-session.d.ts +13 -2
  89. package/dist/agent-adapter/pi/pi-session.js +12 -7
  90. package/dist/agent-adapter/pi/providers-config.d.ts +1 -1
  91. package/dist/agent-adapter/pi/providers-config.js +1 -5
  92. package/dist/agent-adapter/pi/quota-probe.d.ts +1 -1
  93. package/dist/agent-adapter/pi/quota-probe.js +1 -5
  94. package/dist/agent-adapter/pi/quota-sink.d.ts +14 -10
  95. package/dist/agent-adapter/pi/quota-sink.js +10 -13
  96. package/dist/agent-adapter/pi/runtime.d.ts +17 -6
  97. package/dist/agent-adapter/pi/runtime.js +8 -5
  98. package/dist/agent-adapter/pi/session-files.js +0 -4
  99. package/dist/agent-adapter/pi/session-options.d.ts +6 -6
  100. package/dist/agent-adapter/pi/session-options.js +41 -45
  101. package/dist/agent-adapter/pi/session-support.d.ts +3 -4
  102. package/dist/agent-adapter/pi/session-support.js +4 -4
  103. package/dist/agent-adapter/pi/subagent-bridge.d.ts +17 -0
  104. package/dist/agent-adapter/pi/subagent-bridge.js +1 -0
  105. package/dist/agent-adapter/pi/subagent.d.ts +59 -58
  106. package/dist/agent-adapter/pi/subagent.js +151 -503
  107. package/dist/agent-adapter/pi/tool-shims.d.ts +18 -1
  108. package/dist/agent-adapter/pi/tool-shims.js +52 -22
  109. package/dist/agent-adapter/pi/ui-context.js +0 -4
  110. package/dist/agent-adapter/pi/web-fetch.js +0 -4
  111. package/dist/agent-adapter/pi/web-search.js +0 -4
  112. package/dist/agent-adapter/run-events.d.ts +167 -0
  113. package/dist/agent-adapter/run-events.js +119 -0
  114. package/dist/agent-adapter/types.d.ts +219 -147
  115. package/dist/agent-adapter/types.js +0 -4
  116. package/dist/core/agents/roles.d.ts +47 -0
  117. package/dist/core/agents/roles.js +170 -0
  118. package/dist/core/agents/subagent/attribution.d.ts +11 -0
  119. package/dist/core/agents/subagent/attribution.js +53 -0
  120. package/dist/core/agents/subagent/catalog.d.ts +48 -0
  121. package/dist/core/agents/subagent/catalog.js +227 -0
  122. package/dist/core/agents/subagent/orchestrate.d.ts +25 -0
  123. package/dist/core/agents/subagent/orchestrate.js +92 -0
  124. package/dist/core/agents/subagent/schema.d.ts +12 -0
  125. package/dist/core/agents/subagent/schema.js +53 -0
  126. package/dist/core/agents/subagent/types.d.ts +57 -0
  127. package/dist/core/agents/subagent/types.js +1 -0
  128. package/dist/core/agents/subagent/usage.d.ts +8 -0
  129. package/dist/core/agents/subagent/usage.js +32 -0
  130. package/dist/core/anthropic-model-discovery.d.ts +60 -0
  131. package/dist/core/anthropic-model-discovery.js +165 -0
  132. package/dist/core/anthropic-models.d.ts +1 -0
  133. package/dist/core/anthropic-models.js +17 -0
  134. package/dist/core/async-mutex.js +0 -4
  135. package/dist/core/atomic-write.js +0 -4
  136. package/dist/core/auth.js +0 -1
  137. package/dist/core/cached-scan.d.ts +42 -0
  138. package/dist/core/cached-scan.js +101 -0
  139. package/dist/core/calver.js +0 -4
  140. package/dist/core/claude-credentials.d.ts +42 -0
  141. package/dist/core/claude-credentials.js +173 -0
  142. package/dist/core/cli-utils.js +0 -4
  143. package/dist/{domain/costs → core}/codex-quota.js +0 -4
  144. package/dist/core/config-generator.js +0 -4
  145. package/dist/core/debug-mode.js +0 -4
  146. package/dist/core/gateway-generator.d.ts +11 -1
  147. package/dist/core/gateway-generator.js +46 -33
  148. package/dist/core/hook-bus.js +0 -4
  149. package/dist/core/hook-exec.js +0 -4
  150. package/dist/core/i18n.js +0 -1
  151. package/dist/core/json-repository.js +0 -4
  152. package/dist/core/locales/en.d.ts +21 -6
  153. package/dist/core/locales/en.js +0 -1
  154. package/dist/core/locales/slices/commands.d.ts +21 -6
  155. package/dist/core/locales/slices/commands.js +42 -16
  156. package/dist/core/locales/slices/providers.js +0 -4
  157. package/dist/core/locales/slices/status.js +0 -4
  158. package/dist/core/log.js +0 -4
  159. package/dist/core/loopback-http.js +0 -4
  160. package/dist/core/mcp-bundles.js +0 -4
  161. package/dist/core/mcp-timeout.js +0 -4
  162. package/dist/core/mcp-tool-gate.d.ts +8 -0
  163. package/dist/core/mcp-tool-gate.js +15 -5
  164. package/dist/core/media-types.d.ts +5 -0
  165. package/dist/core/media-types.js +5 -0
  166. package/dist/{domain/plugins → core}/native-name.js +0 -4
  167. package/dist/core/paths.js +0 -1
  168. package/dist/core/pi-sdk.js +0 -4
  169. package/dist/core/pi-session-filename.js +0 -4
  170. package/dist/core/production-benchmark-evidence.js +0 -4
  171. package/dist/core/profile-generator.js +0 -4
  172. package/dist/core/prompt-template.d.ts +14 -0
  173. package/dist/core/prompt-template.js +29 -0
  174. package/dist/core/resilient-watch.js +0 -4
  175. package/dist/core/resume-reminder.js +0 -4
  176. package/dist/core/{running-executions.d.ts → run-registry.d.ts} +44 -8
  177. package/dist/core/{running-executions.js → run-registry.js} +65 -12
  178. package/dist/core/runtime-env.js +0 -4
  179. package/dist/core/session-holds.d.ts +88 -0
  180. package/dist/core/session-holds.js +168 -0
  181. package/dist/core/session-retention-liveness.d.ts +4 -4
  182. package/dist/core/session-retention-liveness.js +0 -8
  183. package/dist/core/session-state.d.ts +33 -0
  184. package/dist/core/session-state.js +40 -0
  185. package/dist/core/session-todos.js +1 -5
  186. package/dist/core/settings-migration.js +0 -4
  187. package/dist/core/settings-spec.d.ts +24 -2
  188. package/dist/core/settings-spec.js +49 -2
  189. package/dist/core/settings.js +0 -4
  190. package/dist/core/singleton-lock.js +0 -4
  191. package/dist/core/status-format.d.ts +49 -0
  192. package/dist/core/status-format.js +32 -4
  193. package/dist/core/task-node.js +0 -1
  194. package/dist/core/task-parser.js +0 -4
  195. package/dist/{agent-adapter/normalize → core}/tool-names.d.ts +3 -3
  196. package/dist/{agent-adapter/normalize → core}/tool-names.js +2 -6
  197. package/dist/core/types/agent-types.d.ts +34 -8
  198. package/dist/core/types/agent-types.js +0 -4
  199. package/dist/core/types/thread-types.d.ts +40 -14
  200. package/dist/core/types/thread-types.js +0 -4
  201. package/dist/core/utils.js +0 -1
  202. package/dist/core/version.js +0 -4
  203. package/dist/domain/agents/agent-state.d.ts +60 -0
  204. package/dist/domain/agents/agent-state.js +143 -0
  205. package/dist/domain/agents/config.d.ts +51 -36
  206. package/dist/domain/agents/config.js +140 -117
  207. package/dist/domain/agents/index.d.ts +3 -1
  208. package/dist/domain/agents/index.js +12 -3
  209. package/dist/domain/agents/model-selection.d.ts +79 -0
  210. package/dist/domain/agents/model-selection.js +161 -0
  211. package/dist/domain/agents/profile-manager.d.ts +56 -18
  212. package/dist/domain/agents/profile-manager.js +96 -12
  213. package/dist/domain/agents/profile-switch.js +5 -7
  214. package/dist/domain/agents/provider-run-lifecycle.d.ts +1 -8
  215. package/dist/domain/agents/provider-run-lifecycle.js +0 -43
  216. package/dist/domain/agents/subagent/foreign.d.ts +13 -0
  217. package/dist/domain/agents/subagent/foreign.js +31 -0
  218. package/dist/domain/agents/subagent/registry.d.ts +100 -0
  219. package/dist/domain/agents/subagent/registry.js +239 -0
  220. package/dist/domain/agents/subagent/runner.d.ts +74 -0
  221. package/dist/domain/agents/subagent/runner.js +367 -0
  222. package/dist/domain/agents/subagent/service.d.ts +26 -0
  223. package/dist/domain/agents/subagent/service.js +68 -0
  224. package/dist/domain/auth/auth-events.js +0 -4
  225. package/dist/domain/auth/auth-format.js +0 -4
  226. package/dist/domain/auth/auth-status.js +14 -7
  227. package/dist/domain/auth/auth-watch.js +0 -4
  228. package/dist/domain/auth/cc-auth-cli.js +0 -4
  229. package/dist/domain/auth/cc-login.js +0 -4
  230. package/dist/domain/auth/cc-subscription.js +0 -4
  231. package/dist/domain/auth/claude-user-settings.js +0 -4
  232. package/dist/domain/auth/gateway-sync.js +0 -4
  233. package/dist/domain/auth/index.js +0 -4
  234. package/dist/domain/auth/login-flow.js +0 -4
  235. package/dist/domain/auth/login-service.js +0 -4
  236. package/dist/domain/auth/logout.js +0 -4
  237. package/dist/domain/auth/pi-login.js +0 -4
  238. package/dist/domain/auth/pi-oauth.js +0 -4
  239. package/dist/domain/auth/pi-runtime.js +0 -4
  240. package/dist/domain/benchmark/accounting-reconciliation.js +0 -4
  241. package/dist/domain/{agent-run → benchmark}/atif.js +0 -4
  242. package/dist/domain/benchmark/attempt-record.d.ts +2 -2
  243. package/dist/domain/benchmark/attempt-record.js +0 -4
  244. package/dist/domain/benchmark/composite-manifest.js +0 -4
  245. package/dist/domain/benchmark/decimal-text.js +0 -4
  246. package/dist/domain/{agent-run → benchmark}/identity.js +0 -4
  247. package/dist/domain/{agent-run → benchmark}/journal.js +0 -4
  248. package/dist/domain/{agent-run → benchmark}/manifest-contract.js +0 -4
  249. package/dist/domain/{agent-run → benchmark}/production-attempt-identity.d.ts +8 -6
  250. package/dist/domain/{agent-run → benchmark}/production-attempt-identity.js +40 -44
  251. package/dist/domain/{agent-run → benchmark}/production-attempt-journal.d.ts +3 -3
  252. package/dist/domain/{agent-run → benchmark}/production-attempt-journal.js +4 -8
  253. package/dist/domain/benchmark/production-evidence-export.js +0 -4
  254. package/dist/domain/benchmark/production-evidence-journal.d.ts +3 -3
  255. package/dist/domain/benchmark/production-evidence-journal.js +0 -4
  256. package/dist/domain/benchmark/production-evidence-projection.d.ts +2 -2
  257. package/dist/domain/benchmark/production-evidence-projection.js +4 -8
  258. package/dist/domain/benchmark/production-evidence-topology.d.ts +1 -1
  259. package/dist/domain/benchmark/production-evidence-topology.js +0 -4
  260. package/dist/domain/benchmark/role-surface.d.ts +4 -0
  261. package/dist/domain/{agent-run → benchmark}/role-surface.js +22 -26
  262. package/dist/domain/commissions/commission-context.js +0 -4
  263. package/dist/domain/commissions/commission-draft.js +0 -4
  264. package/dist/domain/commissions/commission-finalize.js +0 -4
  265. package/dist/domain/commissions/commission-paths.js +0 -4
  266. package/dist/domain/commissions/decision-projection.js +0 -4
  267. package/dist/domain/commissions/prompt-block.js +0 -4
  268. package/dist/domain/costs/cost-tracker.js +0 -4
  269. package/dist/domain/costs/gateway-manager.js +0 -4
  270. package/dist/domain/costs/rate-limit-throttle.js +0 -4
  271. package/dist/domain/costs/resume-registry.js +0 -4
  272. package/dist/domain/costs/usage-service.d.ts +29 -12
  273. package/dist/domain/costs/usage-service.js +353 -197
  274. package/dist/domain/costs/usage-store.d.ts +24 -1
  275. package/dist/domain/costs/usage-store.js +39 -10
  276. package/dist/domain/executions/log-tailer.js +0 -1
  277. package/dist/domain/executions/registry.js +4 -5
  278. package/dist/domain/hooks/hook-view.js +0 -4
  279. package/dist/domain/mcp/bundled-server.d.ts +4 -0
  280. package/dist/domain/mcp/bundled-server.js +13 -7
  281. package/dist/domain/mcp/core-server.js +0 -4
  282. package/dist/domain/mcp/feishu/client.js +0 -1
  283. package/dist/domain/mcp/feishu/file.js +0 -4
  284. package/dist/domain/mcp/feishu/index.js +0 -1
  285. package/dist/domain/mcp/feishu/types.js +0 -4
  286. package/dist/domain/mcp/feishu/user-auth.js +0 -1
  287. package/dist/domain/mcp/feishu-server.js +0 -1
  288. package/dist/domain/mcp/interaction-server.js +0 -4
  289. package/dist/domain/mcp/manager-qa-server.js +0 -4
  290. package/dist/domain/mcp/server.js +0 -4
  291. package/dist/domain/mcp/slack-server.js +0 -1
  292. package/dist/domain/mcp/tasks-server.js +0 -4
  293. package/dist/domain/mcp/thread-server.js +0 -4
  294. package/dist/domain/mcp/tools/commission-tools.js +0 -4
  295. package/dist/domain/mcp/tools/context.d.ts +8 -0
  296. package/dist/domain/mcp/tools/context.js +4 -4
  297. package/dist/domain/mcp/tools/cortex-md.js +0 -2
  298. package/dist/domain/mcp/tools/cost.js +0 -4
  299. package/dist/domain/mcp/tools/executions.js +0 -4
  300. package/dist/domain/mcp/tools/interaction-ask.js +0 -4
  301. package/dist/domain/mcp/tools/interaction-plan.js +0 -4
  302. package/dist/domain/mcp/tools/manager-qa.js +0 -4
  303. package/dist/domain/mcp/tools/schedule.js +0 -4
  304. package/dist/domain/mcp/tools/slack.js +0 -4
  305. package/dist/domain/mcp/tools/subagent.d.ts +23 -0
  306. package/dist/domain/mcp/tools/subagent.js +187 -0
  307. package/dist/domain/mcp/tools/task-monitor.js +0 -1
  308. package/dist/domain/mcp/tools/task-ops.js +0 -4
  309. package/dist/domain/mcp/tools/thread-ops.js +0 -4
  310. package/dist/domain/mcp/tools/time.js +0 -4
  311. package/dist/domain/mcp/tools/ui-decision.js +0 -4
  312. package/dist/domain/mcp/tools/ui-file.js +0 -4
  313. package/dist/domain/mcp/tools/ui-view.js +0 -4
  314. package/dist/domain/mcp/web-server.js +0 -4
  315. package/dist/domain/memory/consolidate.js +0 -4
  316. package/dist/domain/memory/cortex-md-injector.js +0 -4
  317. package/dist/domain/memory/cortex-md-scanner.js +0 -4
  318. package/dist/domain/memory/index-regen.js +0 -4
  319. package/dist/domain/memory/rules-loader.js +0 -4
  320. package/dist/domain/memory/skill-scanner.js +0 -4
  321. package/dist/domain/memory/user-context.js +0 -4
  322. package/dist/domain/memory/watcher.js +0 -4
  323. package/dist/domain/monitor/disk-monitor.js +0 -4
  324. package/dist/domain/monitor/event-loop-monitor.js +0 -4
  325. package/dist/domain/monitor/gpu-monitor.js +0 -4
  326. package/dist/domain/pi-providers/custom-provider-model.js +0 -4
  327. package/dist/domain/pi-providers/custom-provider-service.js +0 -4
  328. package/dist/domain/pi-providers/gateway-route-store.js +0 -4
  329. package/dist/domain/pi-providers/index.js +0 -4
  330. package/dist/domain/pi-providers/models-json-store.js +0 -4
  331. package/dist/domain/plugins/agent-plugins-v1.js +0 -4
  332. package/dist/domain/plugins/authoring.js +0 -4
  333. package/dist/domain/plugins/catalog-types.js +0 -4
  334. package/dist/domain/plugins/catalog.js +0 -4
  335. package/dist/domain/plugins/fs-helpers.js +0 -4
  336. package/dist/domain/plugins/mcp.js +0 -4
  337. package/dist/domain/plugins/runtime.js +46 -22
  338. package/dist/domain/plugins/skill-projection.js +0 -4
  339. package/dist/domain/plugins/skill.js +0 -4
  340. package/dist/domain/projects/project-store.js +0 -4
  341. package/dist/domain/projects/project-types.js +0 -4
  342. package/dist/domain/remote/client-bootstrap.js +0 -4
  343. package/dist/domain/remote/client-hot-reload.js +0 -4
  344. package/dist/domain/remote/client-manager.js +15 -10
  345. package/dist/domain/remote/client-ssh-tunnel.d.ts +10 -0
  346. package/dist/domain/remote/client-ssh-tunnel.js +46 -8
  347. package/dist/domain/remote/cortex-client-config.js +0 -4
  348. package/dist/domain/remote/cortex-client.js +0 -4
  349. package/dist/domain/remote/device-browser.js +0 -4
  350. package/dist/domain/remote/device-chrome-commands.js +0 -4
  351. package/dist/domain/remote/device-port.js +0 -4
  352. package/dist/domain/remote/reverse-stream.js +0 -4
  353. package/dist/domain/runs/adapters.d.ts +15 -0
  354. package/dist/domain/runs/adapters.js +57 -0
  355. package/dist/domain/runs/attempt.d.ts +37 -0
  356. package/dist/domain/runs/attempt.js +235 -0
  357. package/dist/domain/runs/builders.d.ts +33 -0
  358. package/dist/domain/runs/builders.js +52 -0
  359. package/dist/domain/runs/compact.d.ts +39 -0
  360. package/dist/domain/runs/compact.js +99 -0
  361. package/dist/domain/runs/config-resolver.d.ts +84 -0
  362. package/dist/domain/runs/config-resolver.js +149 -0
  363. package/dist/domain/runs/engine-spec.d.ts +59 -0
  364. package/dist/domain/runs/engine-spec.js +284 -0
  365. package/dist/domain/runs/engines.d.ts +63 -0
  366. package/dist/domain/runs/engines.js +169 -0
  367. package/dist/domain/runs/events.d.ts +2 -0
  368. package/dist/domain/runs/events.js +7 -0
  369. package/dist/domain/runs/fallback.d.ts +42 -0
  370. package/dist/domain/runs/fallback.js +76 -0
  371. package/dist/domain/runs/notices.d.ts +49 -0
  372. package/dist/domain/runs/notices.js +122 -0
  373. package/dist/domain/runs/observers/resume-recorder.d.ts +41 -0
  374. package/dist/domain/runs/observers/resume-recorder.js +44 -0
  375. package/dist/domain/runs/prompt.d.ts +69 -0
  376. package/dist/domain/runs/prompt.js +122 -0
  377. package/dist/domain/runs/request.d.ts +99 -0
  378. package/dist/domain/runs/request.js +1 -0
  379. package/dist/domain/runs/run.d.ts +218 -0
  380. package/dist/domain/runs/run.js +585 -0
  381. package/dist/domain/runs/service.d.ts +12 -0
  382. package/dist/domain/runs/service.js +50 -0
  383. package/dist/domain/runs/spec-loader.d.ts +78 -0
  384. package/dist/domain/runs/spec-loader.js +61 -0
  385. package/dist/domain/scheduling/builtin-job-controller.js +0 -4
  386. package/dist/domain/scheduling/builtin-job-migration.js +0 -4
  387. package/dist/domain/scheduling/builtin-jobs.js +0 -4
  388. package/dist/domain/scheduling/job-registry.d.ts +28 -19
  389. package/dist/domain/scheduling/job-registry.js +12 -2
  390. package/dist/domain/scheduling/jobs/auth-expiry-scan.js +0 -4
  391. package/dist/domain/scheduling/jobs/{_shared.d.ts → register-thread-session.d.ts} +1 -6
  392. package/dist/domain/scheduling/jobs/register-thread-session.js +37 -0
  393. package/dist/domain/scheduling/jobs/scheduled-task.js +86 -101
  394. package/dist/domain/scheduling/jobs/sync-public.js +0 -4
  395. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -1
  396. package/dist/domain/scheduling/jobs/task-dispatch.js +145 -130
  397. package/dist/domain/scheduling/runner.d.ts +0 -1
  398. package/dist/domain/scheduling/runner.js +0 -5
  399. package/dist/domain/scheduling/schedule-cli.js +0 -4
  400. package/dist/domain/scheduling/schedule-command.js +0 -4
  401. package/dist/domain/scheduling/scheduler.js +0 -4
  402. package/dist/domain/sessions/session-backup.js +0 -4
  403. package/dist/domain/sessions/session-hooks.d.ts +17 -5
  404. package/dist/domain/sessions/session-hooks.js +75 -18
  405. package/dist/domain/sessions/session-lifecycle.d.ts +6 -1
  406. package/dist/domain/sessions/session-lifecycle.js +26 -8
  407. package/dist/domain/sessions/session-retention.d.ts +4 -0
  408. package/dist/domain/sessions/session-retention.js +3 -4
  409. package/dist/domain/sessions/session.d.ts +3 -3
  410. package/dist/domain/sessions/session.js +2 -4
  411. package/dist/domain/system/doctor.js +11 -8
  412. package/dist/domain/system/install-cli.js +0 -4
  413. package/dist/domain/system/notice-history.d.ts +18 -0
  414. package/dist/domain/system/notice-history.js +27 -0
  415. package/dist/domain/system/preferences.d.ts +18 -0
  416. package/dist/domain/system/preferences.js +35 -6
  417. package/dist/domain/system/server-update-check.js +0 -4
  418. package/dist/domain/system/system-notice.js +2 -4
  419. package/dist/domain/system/update-prompt.js +0 -4
  420. package/dist/domain/tasks/acceptance-ledger.js +0 -4
  421. package/dist/domain/tasks/archiver.js +0 -4
  422. package/dist/domain/tasks/claim-recovery.js +0 -1
  423. package/dist/domain/tasks/dispatch-utils.js +0 -4
  424. package/dist/domain/tasks/dispatcher.js +1 -5
  425. package/dist/domain/tasks/mutator.js +0 -4
  426. package/dist/domain/tasks/parser.js +0 -1
  427. package/dist/domain/tasks/pending-tracker.js +0 -4
  428. package/dist/domain/tasks/production-topology-ledger.js +0 -4
  429. package/dist/domain/tasks/recommendation/extractor.js +0 -4
  430. package/dist/domain/tasks/recommendation/patterns.js +0 -4
  431. package/dist/domain/tasks/recommendation/types.js +0 -4
  432. package/dist/domain/tasks/system/cortex-run.js +0 -4
  433. package/dist/domain/tasks/system/task-cli.js +0 -4
  434. package/dist/domain/tasks/system/task-completion.js +0 -4
  435. package/dist/domain/tasks/system/task-file-input.js +0 -4
  436. package/dist/domain/tasks/system/task-id-utils.js +0 -4
  437. package/dist/domain/tasks/system/task-lifecycle-edit.js +0 -4
  438. package/dist/domain/tasks/system/task-lock.js +0 -4
  439. package/dist/domain/tasks/system/task-mutations.js +0 -4
  440. package/dist/domain/tasks/system/task-process.js +0 -4
  441. package/dist/domain/tasks/system/task-state.js +0 -4
  442. package/dist/domain/threads/artifact-io.js +0 -4
  443. package/dist/domain/threads/auto-thread.js +0 -4
  444. package/dist/domain/threads/contract.js +0 -1
  445. package/dist/domain/threads/evidence-context.js +0 -4
  446. package/dist/domain/threads/hook-runner.js +61 -83
  447. package/dist/domain/threads/pending-user-inputs.js +0 -4
  448. package/dist/domain/threads/prompt-builder.d.ts +12 -31
  449. package/dist/domain/threads/prompt-builder.js +43 -164
  450. package/dist/domain/threads/runner.d.ts +28 -5
  451. package/dist/domain/threads/runner.js +206 -203
  452. package/dist/domain/threads/shell-templates.js +0 -1
  453. package/dist/domain/threads/state-machine.d.ts +1 -1
  454. package/dist/domain/threads/state-machine.js +1 -5
  455. package/dist/domain/threads/template-loader.js +0 -4
  456. package/dist/domain/threads/template-resolver.js +0 -4
  457. package/dist/domain/threads/template-validate.js +0 -4
  458. package/dist/domain/threads/template-validate.parity.js +0 -1
  459. package/dist/domain/threads/template-writer.js +0 -1
  460. package/dist/domain/threads/thread-transcript.js +17 -4
  461. package/dist/domain/threads/tree.js +0 -4
  462. package/dist/domain/ui-service/app-router.d.ts +44 -0
  463. package/dist/domain/ui-service/app-router.js +11 -1
  464. package/dist/domain/ui-service/input-schemas.d.ts +56 -0
  465. package/dist/domain/ui-service/input-schemas.js +33 -0
  466. package/dist/domain/ui-service/mutate/auth.js +0 -4
  467. package/dist/domain/ui-service/mutate/commissions.js +0 -4
  468. package/dist/domain/ui-service/mutate/config.d.ts +1 -1
  469. package/dist/domain/ui-service/mutate/config.js +11 -5
  470. package/dist/domain/ui-service/mutate/custom-providers.js +0 -4
  471. package/dist/domain/ui-service/mutate/hooks.js +0 -4
  472. package/dist/domain/ui-service/mutate/notes.js +0 -4
  473. package/dist/domain/ui-service/mutate/plugin-packages.js +0 -4
  474. package/dist/domain/ui-service/mutate/plugins.js +0 -4
  475. package/dist/domain/ui-service/mutate/profiles.js +0 -4
  476. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  477. package/dist/domain/ui-service/mutate/sessions.js +77 -4
  478. package/dist/domain/ui-service/mutate/system.js +0 -4
  479. package/dist/domain/ui-service/mutate/thread-templates.js +0 -1
  480. package/dist/domain/ui-service/plugins-shared.js +1 -1
  481. package/dist/domain/ui-service/query/auth.js +0 -4
  482. package/dist/domain/ui-service/query/commissions.js +0 -4
  483. package/dist/domain/ui-service/query/config.d.ts +3 -3
  484. package/dist/domain/ui-service/query/config.js +12 -5
  485. package/dist/domain/ui-service/query/custom-providers.js +0 -4
  486. package/dist/domain/ui-service/query/hooks.js +0 -4
  487. package/dist/domain/ui-service/query/machine-detail.js +0 -4
  488. package/dist/domain/ui-service/query/machine-probe.js +0 -4
  489. package/dist/domain/ui-service/query/machines.js +0 -1
  490. package/dist/domain/ui-service/query/models.d.ts +24 -0
  491. package/dist/domain/ui-service/query/models.js +108 -0
  492. package/dist/domain/ui-service/query/notes.js +0 -4
  493. package/dist/domain/ui-service/query/plugin-source.js +0 -4
  494. package/dist/domain/ui-service/query/plugins.js +0 -4
  495. package/dist/domain/ui-service/query/sessions.js +64 -41
  496. package/dist/domain/ui-service/query/skills.js +0 -1
  497. package/dist/domain/ui-service/query/system.d.ts +2 -1
  498. package/dist/domain/ui-service/query/system.js +4 -4
  499. package/dist/domain/ui-service/query/tasks.js +0 -4
  500. package/dist/domain/ui-service/query/thread-template-detail.js +0 -1
  501. package/dist/domain/ui-service/query/thread-templates.js +0 -1
  502. package/dist/domain/ui-service/query/threads.js +0 -4
  503. package/dist/domain/ui-service/query-input-schemas.js +0 -4
  504. package/dist/domain/ui-service/trpc.d.ts +34 -0
  505. package/dist/domain/ui-service/trpc.js +30 -0
  506. package/dist/domain/ui-service/types.d.ts +192 -14
  507. package/dist/domain/ui-service/ui-service.js +6 -2
  508. package/dist/entry/admin-channel-hot-reload.js +0 -4
  509. package/dist/entry/app.js +101 -37
  510. package/dist/entry/auth-cli.js +0 -4
  511. package/dist/entry/boot-jobs.js +0 -4
  512. package/dist/entry/cli-help.js +2 -6
  513. package/dist/entry/cli.js +3 -6
  514. package/dist/entry/cortex-cli.js +0 -4
  515. package/dist/entry/daemon-notice.js +0 -4
  516. package/dist/entry/daemon.d.ts +43 -0
  517. package/dist/entry/daemon.js +0 -4
  518. package/dist/entry/doctor-cli.js +0 -1
  519. package/dist/entry/draft-attachments.js +0 -4
  520. package/dist/entry/fast-install.js +0 -4
  521. package/dist/entry/feishu-login.js +0 -4
  522. package/dist/entry/hook-cli.js +0 -4
  523. package/dist/entry/init.d.ts +1 -1
  524. package/dist/entry/init.js +11 -13
  525. package/dist/entry/local-ui.js +0 -4
  526. package/dist/entry/production-app-bootstrap.js +0 -4
  527. package/dist/entry/production-evidence-export-cli.js +1 -5
  528. package/dist/entry/provider-cli.js +0 -4
  529. package/dist/entry/start-ui-http.d.ts +7 -0
  530. package/dist/entry/start-ui-http.js +48 -8
  531. package/dist/entry/startup-helpers.js +0 -4
  532. package/dist/entry/startup-notify.js +0 -4
  533. package/dist/entry/ui-cli.js +0 -4
  534. package/dist/entry/ui-http-gate.js +0 -4
  535. package/dist/events/event-bus.js +0 -4
  536. package/dist/events/event-logger.js +0 -4
  537. package/dist/events/event-replay.js +0 -4
  538. package/dist/events/event-types.d.ts +1 -1
  539. package/dist/events/event-types.js +0 -4
  540. package/dist/events/index.js +0 -4
  541. package/dist/orchestration/agent-decision-send.js +0 -4
  542. package/dist/orchestration/agent-file-send.js +0 -4
  543. package/dist/orchestration/agent-runner.d.ts +14 -76
  544. package/dist/orchestration/agent-runner.js +80 -620
  545. package/dist/orchestration/agent-view-send.js +0 -4
  546. package/dist/orchestration/busy-tracker.js +0 -4
  547. package/dist/orchestration/conduit-queue.d.ts +0 -6
  548. package/dist/orchestration/conduit-queue.js +13 -5
  549. package/dist/orchestration/conversation-request.d.ts +82 -0
  550. package/dist/orchestration/conversation-request.js +175 -0
  551. package/dist/orchestration/delta-coalescer.js +1 -2
  552. package/dist/orchestration/dispatch-reconciler.js +2 -6
  553. package/dist/orchestration/durable-helpers.js +0 -4
  554. package/dist/orchestration/edit-retry.d.ts +39 -0
  555. package/dist/orchestration/edit-retry.js +146 -0
  556. package/dist/orchestration/human-answer-backstop.d.ts +36 -0
  557. package/dist/orchestration/human-answer-backstop.js +79 -0
  558. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  559. package/dist/orchestration/interactions/ask-user-question.js +15 -17
  560. package/dist/orchestration/interactions/ask-user-resume.d.ts +13 -0
  561. package/dist/orchestration/interactions/ask-user-resume.js +89 -0
  562. package/dist/orchestration/interactions/command-action-router.js +0 -1
  563. package/dist/orchestration/interactions/interaction-handlers.js +16 -19
  564. package/dist/orchestration/interactions/interaction-records.js +0 -1
  565. package/dist/orchestration/interactions/plan-response.js +7 -11
  566. package/dist/orchestration/interactions/update-prompt-slack.js +0 -1
  567. package/dist/orchestration/interactions/update-prompt.js +0 -1
  568. package/dist/orchestration/manager-qa.d.ts +6 -3
  569. package/dist/orchestration/manager-qa.js +68 -44
  570. package/dist/orchestration/mid-turn-inject.d.ts +22 -79
  571. package/dist/orchestration/mid-turn-inject.js +24 -269
  572. package/dist/orchestration/orchestrator.js +0 -4
  573. package/dist/orchestration/outputs-store.js +0 -4
  574. package/dist/orchestration/pending-injection-recovery.d.ts +1 -0
  575. package/dist/orchestration/pending-injection-recovery.js +1 -4
  576. package/dist/orchestration/pi-background-subagent.d.ts +15 -0
  577. package/dist/orchestration/pi-background-subagent.js +30 -0
  578. package/dist/orchestration/resume-dispatcher.d.ts +10 -10
  579. package/dist/orchestration/resume-dispatcher.js +24 -42
  580. package/dist/orchestration/resume-target-sink.d.ts +37 -0
  581. package/dist/orchestration/resume-target-sink.js +70 -0
  582. package/dist/orchestration/routing/commands/cancel.d.ts +33 -8
  583. package/dist/orchestration/routing/commands/cancel.js +76 -23
  584. package/dist/orchestration/routing/commands/compact.js +0 -4
  585. package/dist/orchestration/routing/commands/cost.js +0 -4
  586. package/dist/orchestration/routing/commands/index.d.ts +3 -0
  587. package/dist/orchestration/routing/commands/index.js +6 -8
  588. package/dist/orchestration/routing/commands/lang.d.ts +7 -1
  589. package/dist/orchestration/routing/commands/lang.js +35 -27
  590. package/dist/orchestration/routing/commands/login-custom.js +0 -4
  591. package/dist/orchestration/routing/commands/login-notice.js +0 -4
  592. package/dist/orchestration/routing/commands/login.js +3 -5
  593. package/dist/orchestration/routing/commands/mode.d.ts +36 -0
  594. package/dist/orchestration/routing/commands/mode.js +126 -16
  595. package/dist/orchestration/routing/commands/session.js +4 -3
  596. package/dist/orchestration/routing/commands/status.js +2 -5
  597. package/dist/orchestration/routing/commands/thread-handlers.js +4 -8
  598. package/dist/orchestration/routing/commands/usage.js +0 -4
  599. package/dist/orchestration/routing/edit-handler.d.ts +2 -2
  600. package/dist/orchestration/routing/edit-handler.js +10 -15
  601. package/dist/orchestration/routing/file-handler.d.ts +1 -3
  602. package/dist/orchestration/routing/file-handler.js +1 -7
  603. package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +1 -1
  604. package/dist/orchestration/routing/hook-bridge-subscribers.js +13 -7
  605. package/dist/orchestration/routing/hook-bridge.d.ts +4 -16
  606. package/dist/orchestration/routing/hook-bridge.js +4 -26
  607. package/dist/orchestration/routing/webhook.js +44 -76
  608. package/dist/orchestration/runtime.d.ts +30 -0
  609. package/dist/orchestration/runtime.js +37 -0
  610. package/dist/orchestration/session-compact.d.ts +7 -7
  611. package/dist/orchestration/session-compact.js +8 -13
  612. package/dist/orchestration/session-events.d.ts +6 -2
  613. package/dist/orchestration/session-events.js +13 -16
  614. package/dist/orchestration/session-gateway.d.ts +50 -0
  615. package/dist/orchestration/session-gateway.js +81 -0
  616. package/dist/orchestration/session-retention-controller.js +0 -4
  617. package/dist/orchestration/session-rewind.js +10 -14
  618. package/dist/orchestration/status-helpers.d.ts +10 -33
  619. package/dist/orchestration/status-helpers.js +20 -73
  620. package/dist/orchestration/subagent-adopt.d.ts +37 -0
  621. package/dist/orchestration/subagent-adopt.js +54 -0
  622. package/dist/orchestration/subagent-attribution.d.ts +22 -0
  623. package/dist/orchestration/subagent-attribution.js +132 -0
  624. package/dist/orchestration/subagent-delivery.d.ts +43 -0
  625. package/dist/orchestration/subagent-delivery.js +120 -0
  626. package/dist/orchestration/subagent-rows.js +0 -4
  627. package/dist/orchestration/subagent-webhook.d.ts +6 -0
  628. package/dist/orchestration/subagent-webhook.js +122 -0
  629. package/dist/orchestration/thread-callback.d.ts +14 -76
  630. package/dist/orchestration/thread-callback.js +42 -336
  631. package/dist/orchestration/thread-delivery.d.ts +40 -0
  632. package/dist/orchestration/thread-delivery.js +84 -0
  633. package/dist/orchestration/thread-executor.d.ts +5 -35
  634. package/dist/orchestration/thread-executor.js +59 -198
  635. package/dist/orchestration/thread-input.d.ts +16 -0
  636. package/dist/orchestration/thread-input.js +61 -0
  637. package/dist/orchestration/thread-notices.d.ts +45 -0
  638. package/dist/orchestration/thread-notices.js +208 -0
  639. package/dist/orchestration/thread-run/index.d.ts +3 -0
  640. package/dist/orchestration/thread-run/index.js +3 -0
  641. package/dist/orchestration/thread-run/render-summary.d.ts +57 -0
  642. package/dist/orchestration/thread-run/render-summary.js +117 -0
  643. package/dist/orchestration/thread-run/render-task.d.ts +96 -0
  644. package/dist/orchestration/thread-run/render-task.js +165 -0
  645. package/dist/orchestration/thread-run/settle.d.ts +11 -0
  646. package/dist/orchestration/thread-run/settle.js +24 -0
  647. package/dist/orchestration/thread-run/thread-run.d.ts +131 -0
  648. package/dist/orchestration/thread-run/thread-run.js +191 -0
  649. package/dist/orchestration/thread-run/thread-surface.d.ts +41 -0
  650. package/dist/orchestration/thread-run/thread-surface.js +29 -0
  651. package/dist/orchestration/thread-run/verdict.d.ts +11 -0
  652. package/dist/orchestration/thread-run/verdict.js +24 -0
  653. package/dist/orchestration/transcript-sink.d.ts +151 -0
  654. package/dist/orchestration/transcript-sink.js +465 -0
  655. package/dist/orchestration/turn/active-turns.d.ts +69 -0
  656. package/dist/orchestration/turn/active-turns.js +113 -0
  657. package/dist/orchestration/turn/background-hold.d.ts +167 -0
  658. package/dist/orchestration/turn/background-hold.js +273 -0
  659. package/dist/orchestration/turn/hold-render-platform.d.ts +41 -0
  660. package/dist/orchestration/turn/hold-render-platform.js +149 -0
  661. package/dist/orchestration/turn/hold-render-web.d.ts +32 -0
  662. package/dist/orchestration/turn/hold-render-web.js +80 -0
  663. package/dist/orchestration/turn/terminal.d.ts +98 -0
  664. package/dist/orchestration/turn/terminal.js +198 -0
  665. package/dist/orchestration/turn/turn-prep.d.ts +50 -0
  666. package/dist/orchestration/turn/turn-prep.js +138 -0
  667. package/dist/orchestration/turn/turn-tracking.d.ts +22 -0
  668. package/dist/orchestration/turn/turn-tracking.js +86 -0
  669. package/dist/orchestration/turn/turn.d.ts +195 -0
  670. package/dist/orchestration/turn/turn.js +631 -0
  671. package/dist/orchestration/turn-mutation-lock.js +0 -4
  672. package/dist/orchestration/turn-notify.js +1 -5
  673. package/dist/platform/adapter.js +0 -4
  674. package/dist/platform/adapters/composite-adapter.js +0 -4
  675. package/dist/platform/adapters/feishu-http.d.ts +51 -0
  676. package/dist/platform/adapters/feishu-http.js +106 -0
  677. package/dist/platform/adapters/feishu-output-stream.js +0 -1
  678. package/dist/platform/adapters/feishu.js +4 -4
  679. package/dist/platform/adapters/index.js +0 -4
  680. package/dist/platform/adapters/project-conduits.js +0 -1
  681. package/dist/platform/adapters/slack-output-stream.js +0 -1
  682. package/dist/platform/adapters/slack-project-conduits.js +0 -1
  683. package/dist/platform/adapters/slack.js +1 -5
  684. package/dist/platform/adapters/tui/index.js +0 -4
  685. package/dist/platform/adapters/tui/tui-conduit-state.js +0 -4
  686. package/dist/platform/adapters/tui/tui-connection.js +0 -4
  687. package/dist/platform/adapters/tui/tui-gateway.js +0 -4
  688. package/dist/platform/adapters/tui/tui-notifications.js +0 -4
  689. package/dist/platform/adapters/tui/tui-output-stream.js +0 -4
  690. package/dist/platform/adapters/tui/tui-transcript.js +0 -1
  691. package/dist/platform/browser/display.js +0 -4
  692. package/dist/platform/browser/managed-browser.js +0 -4
  693. package/dist/platform/index.js +0 -4
  694. package/dist/platform/interactive-builder.js +0 -4
  695. package/dist/platform/output-stream.js +0 -4
  696. package/dist/platform/testing.js +0 -4
  697. package/dist/platform/tool-trace.js +0 -4
  698. package/dist/platform/tui/protocol.js +0 -4
  699. package/dist/platform/types.d.ts +6 -0
  700. package/dist/platform/types.js +0 -4
  701. package/dist/platform/ui-http/access-jwt.js +0 -1
  702. package/dist/platform/ui-http/app-update.js +0 -1
  703. package/dist/platform/ui-http/browser-status.js +0 -4
  704. package/dist/platform/ui-http/device-ports.js +0 -4
  705. package/dist/platform/ui-http/listening-ports.js +0 -4
  706. package/dist/platform/ui-http/port-forward.js +0 -4
  707. package/dist/platform/ui-http/ui-auth-routes.d.ts +56 -0
  708. package/dist/platform/ui-http/ui-auth-routes.js +161 -0
  709. package/dist/platform/ui-http/ui-http-server.d.ts +36 -0
  710. package/dist/platform/ui-http/ui-http-server.js +34 -12
  711. package/dist/platform/ui-http/ui-ota.js +0 -1
  712. package/dist/platform/ui-http/ui-session.d.ts +33 -0
  713. package/dist/platform/ui-http/ui-session.js +134 -0
  714. package/dist/platform/ui-http/zip-writer.js +0 -1
  715. package/dist/platform/utils/rate-limiter.js +0 -4
  716. package/dist/platform/utils/reaction-diagnostics.d.ts +5 -0
  717. package/dist/platform/utils/reaction-diagnostics.js +0 -4
  718. package/dist/store/commission-repo.js +0 -4
  719. package/dist/store/conversation-display-projection.js +0 -4
  720. package/dist/store/conversation-history-reader.js +1 -4
  721. package/dist/store/conversation-history-repo.d.ts +8 -1
  722. package/dist/store/conversation-history-repo.js +1 -4
  723. package/dist/store/conversation-ledger-repo.js +0 -4
  724. package/dist/store/cost-repo.js +0 -1
  725. package/dist/store/execution-repo.d.ts +24 -2
  726. package/dist/store/execution-repo.js +17 -6
  727. package/dist/store/hook-registry.js +0 -4
  728. package/dist/store/hook-sync.js +0 -4
  729. package/dist/store/hook-writer.js +0 -4
  730. package/dist/store/in-memory-repository.js +0 -4
  731. package/dist/store/outbound-queue.js +0 -4
  732. package/dist/store/pending-injection-repo.d.ts +5 -0
  733. package/dist/store/pending-injection-repo.js +0 -4
  734. package/dist/store/plugin-retirement.d.ts +41 -0
  735. package/dist/store/plugin-retirement.js +153 -0
  736. package/dist/store/plugin-sync.js +3 -1
  737. package/dist/store/profile-repo.js +0 -4
  738. package/dist/store/project-dir-repo.js +0 -1
  739. package/dist/store/project-notes-repo.js +0 -4
  740. package/dist/store/prompt-migration-replacements.js +0 -4
  741. package/dist/store/provider-state-repo.js +0 -4
  742. package/dist/store/retention-candidate-repo.js +0 -4
  743. package/dist/store/schedule-repo.js +0 -4
  744. package/dist/store/session-registry-repo.d.ts +2 -1
  745. package/dist/store/session-registry-repo.js +2 -1
  746. package/dist/store/session-repo.d.ts +40 -5
  747. package/dist/store/session-repo.js +100 -26
  748. package/dist/store/session-totals-repo.d.ts +45 -0
  749. package/dist/store/session-totals-repo.js +108 -0
  750. package/dist/store/session-totals.d.ts +69 -0
  751. package/dist/store/session-totals.js +93 -0
  752. package/dist/store/task-repo.js +0 -1
  753. package/dist/store/thread-repo.js +0 -4
  754. package/dist/store/version-migrations.d.ts +18 -1
  755. package/dist/store/version-migrations.js +109 -8
  756. package/dist/tui/turn-status.js +1 -1
  757. package/package.json +4 -4
  758. package/scripts/install-bundled-dependencies.mjs +0 -5
  759. package/web/dist/assets/index-BuXbCsuz.js +444 -0
  760. package/web/dist/assets/{index-4EnTLUto.css → index-CCPxQ94C.css} +1 -1
  761. package/web/dist/assets/{index-C6HFAjjh.js → index-aHbOZSP6.js} +1 -1
  762. package/web/dist/index.html +2 -3
  763. package/web/dist/theme.css +0 -1
  764. package/defaults/config/hooks/03-ask-user-question-hook.json +0 -19
  765. package/defaults/config/hooks/04-exit-plan-mode-hook.json +0 -19
  766. package/defaults/config/hooks/09-permission-request-auto-allow.json +0 -11
  767. package/defaults/context/decisions/DR-0012.md +0 -54
  768. package/defaults/hooks/ask-user-question-hook.mjs +0 -72
  769. package/defaults/hooks/exit-plan-mode-hook.mjs +0 -90
  770. package/dist/agent-adapter/claude/adapter-tui.d.ts +0 -236
  771. package/dist/agent-adapter/claude/adapter-tui.js +0 -664
  772. package/dist/agent-adapter/claude/cost-from-usage.d.ts +0 -62
  773. package/dist/agent-adapter/claude/cost-from-usage.js +0 -97
  774. package/dist/agent-adapter/claude/jsonl-tail.d.ts +0 -60
  775. package/dist/agent-adapter/claude/jsonl-tail.js +0 -422
  776. package/dist/agent-adapter/claude/subagent-jsonl-mux.d.ts +0 -62
  777. package/dist/agent-adapter/claude/subagent-jsonl-mux.js +0 -294
  778. package/dist/agent-adapter/event-tee.d.ts +0 -19
  779. package/dist/agent-adapter/event-tee.js +0 -145
  780. package/dist/core/bg-held-sessions.d.ts +0 -37
  781. package/dist/core/bg-held-sessions.js +0 -83
  782. package/dist/domain/agent-run/role-surface.d.ts +0 -4
  783. package/dist/domain/agents/facade.d.ts +0 -96
  784. package/dist/domain/agents/facade.js +0 -615
  785. package/dist/domain/agents/spawn-config.d.ts +0 -177
  786. package/dist/domain/agents/spawn-config.js +0 -205
  787. package/dist/domain/scheduling/jobs/_shared.js +0 -65
  788. package/dist/domain/sessions/session-registry.d.ts +0 -28
  789. package/dist/domain/sessions/session-registry.js +0 -46
  790. package/dist/hooks/ask-user-question-hook.mjs +0 -72
  791. package/dist/hooks/exit-plan-mode-hook.mjs +0 -90
  792. package/dist/orchestration/bg-continuation.d.ts +0 -70
  793. package/dist/orchestration/bg-continuation.js +0 -77
  794. package/dist/orchestration/bg-wait-guard.d.ts +0 -31
  795. package/dist/orchestration/bg-wait-guard.js +0 -79
  796. package/dist/orchestration/conversation-runner.d.ts +0 -116
  797. package/dist/orchestration/conversation-runner.js +0 -218
  798. package/dist/orchestration/lifecycle.d.ts +0 -97
  799. package/dist/orchestration/lifecycle.js +0 -601
  800. package/dist/orchestration/session-send.d.ts +0 -21
  801. package/dist/orchestration/session-send.js +0 -38
  802. package/dist/orchestration/superseded-edits.d.ts +0 -22
  803. package/dist/orchestration/superseded-edits.js +0 -31
  804. package/dist/orchestration/web-bg-hold.d.ts +0 -66
  805. package/dist/orchestration/web-bg-hold.js +0 -159
  806. package/web/dist/CORTEX.md +0 -10
  807. package/web/dist/assets/index-DMImrhdJ.js +0 -443
  808. /package/defaults/{pi/agents → agents}/explore.md +0 -0
  809. /package/defaults/{pi/agents → agents}/general-purpose.md +0 -0
  810. /package/defaults/{pi/agents → agents}/plan.md +0 -0
  811. /package/dist/{domain/costs → core}/codex-quota.d.ts +0 -0
  812. /package/dist/{domain/plugins → core}/native-name.d.ts +0 -0
  813. /package/dist/domain/{agent-run → benchmark}/atif.d.ts +0 -0
  814. /package/dist/domain/{agent-run → benchmark}/identity.d.ts +0 -0
  815. /package/dist/domain/{agent-run → benchmark}/journal.d.ts +0 -0
  816. /package/dist/domain/{agent-run → benchmark}/manifest-contract.d.ts +0 -0
@@ -1,31 +1,22 @@
1
- // input: Claude streams, spawn config, MCP gate, accounting
2
- // output: Claude turns, fallback and exact accounting
3
- // pos: Claude backend adapter
4
- // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
1
  import { spawn } from 'child_process';
6
- import { createWriteStream, mkdirSync } from 'fs';
7
2
  import { createInterface } from 'readline';
8
- import { Writable } from 'stream';
9
- import * as path from 'path';
10
3
  import * as crypto from 'crypto';
11
- import { AGENT_CWD, resolveSpawnCwd, readableTimestamp } from '../../core/utils.js';
4
+ import { AGENT_CWD, resolveSpawnCwd } from '../../core/utils.js';
12
5
  import { createLogger } from '../../core/log.js';
13
- import { handleRateLimitEvent } from '../../domain/costs/rate-limit-throttle.js';
14
- import { fromCanonical } from '../normalize/tool-names.js';
6
+ import { fromCanonical } from '../../core/tool-names.js';
15
7
  import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
16
8
  import { resolveMcpComposition } from '../types.js';
9
+ import { ClaudeEngineSession } from './engine.js';
17
10
  import { encodeMcpBundles, MCP_BUNDLES_ENV } from '../../core/mcp-bundles.js';
18
- import { parseTodoWrite } from '../normalize/todo.js';
19
- import { createEventStream } from '../normalize/event-stream.js';
20
- import { CancelledError, IDLE_SESSION_TIMEOUT, LOGS_DIR, TURN_IDLE_TIMEOUT, } from './defaults.js';
11
+ import { CancelledError, IDLE_SESSION_TIMEOUT, TURN_IDLE_TIMEOUT, } from './defaults.js';
21
12
  import { buildClaudeEnv, buildSpawnArgs, claudeRouteIdentity, resolveClaudeMcpBundles, } from './spawn-args.js';
22
- import { ClaudeTuiSession, defaultTailFactory, computeJsonlPath, resolveTuiResume } from './adapter-tui.js';
13
+ import { computeTranscriptPath, resolveResumeAgainstTranscript } from './transcript-path.js';
23
14
  import { TmuxControl } from './tmux-control.js';
24
15
  import { TUI_TMUX_NAME_PREFIX } from './defaults.js';
25
- import { buildPrompt, clearActivePlanFile, extractAskUserQuestions, extractResult, formatEvent, getCurrentPlanFilePath, isPlanFilePath, mergeSubstantialOutput, setActivePlanFile, createStreamDeltaState, parseStreamEvent, takeTextBlockId, parseModelFallbackEvent, } from './event-parser.js';
26
- import { BgTaskTracker, isContinuationResult, routeLine } from './bg-task-tracker.js';
16
+ import { buildPrompt, clearActivePlanFile, extractAskUserQuestions, getCurrentPlanFilePath, mergeSubstantialOutput, createStreamDeltaState, } from './event-parser.js';
17
+ import { BgTaskTracker } from './bg-task-tracker.js';
18
+ import { ClaudeTurnMachine } from './turn-machine.js';
27
19
  import { ClaudeContextUsageTracker } from './context-usage.js';
28
- import { activeClaudeCaptureRegistry } from './active-capture-registry.js';
29
20
  import { resolveAutoCompactWindow } from './compact-window.js';
30
21
  import { validateClaudeSupplementalMcpConfig, writeClaudeSupplementalMcpConfig, } from './mcp-config.js';
31
22
  import { writeBrowserMcpConfig } from './browser-mcp.js';
@@ -38,58 +29,6 @@ function spawnClaudeProcess(spawner, args, options, cliPath) {
38
29
  return spawner(command, args, options);
39
30
  return { process: spawn(command, args, { ...options, stdio: ['pipe', 'pipe', 'pipe'] }) };
40
31
  }
41
- /** The two subagent line shapes §17 G4-SA6 admits. A replay echo is the CLI's delivery ack for an
42
- * injected message, not subagent work, so it is not a census line. */
43
- /** Read the subagent linkage the CLI puts on every stdout line. Undefined = the main agent's
44
- * own call. Nothing is added to any tool's parameter schema: this rides the transport
45
- * envelope, so the model neither sees nor reports it. */
46
- function subagentAttribution(data) {
47
- const parentToolUseId = data?.parent_tool_use_id;
48
- if (typeof parentToolUseId !== 'string' || !parentToolUseId)
49
- return undefined;
50
- return {
51
- parentToolUseId,
52
- type: typeof data?.subagent_type === 'string' ? data.subagent_type : null,
53
- description: typeof data?.task_description === 'string' ? data.task_description : null,
54
- model: typeof data?.message?.model === 'string' ? data.message.model : null,
55
- };
56
- }
57
- /** Flatten a `tool_result` block's content to the string shape every sink expects. Shared by the
58
- * in-turn path and the orphan-subagent path so the two cannot drift. */
59
- function toolResultText(block) {
60
- if (typeof block.content === 'string')
61
- return block.content;
62
- if (Array.isArray(block.content)) {
63
- const allText = block.content.every((item) => item?.type === 'text' && typeof item.text === 'string');
64
- return allText ? block.content.map((item) => item.text).join('\n') : JSON.stringify(block.content);
65
- }
66
- return JSON.stringify(block.content ?? '');
67
- }
68
- function subagentActivityKind(data) {
69
- if (data.type === 'assistant')
70
- return 'assistant';
71
- if (data.type === 'user' && !data.isReplay)
72
- return 'tool_result';
73
- return null;
74
- }
75
- function tokenValue(value) {
76
- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
77
- }
78
- function sumKnownTokens(values) {
79
- const tokens = values.map(tokenValue);
80
- if (tokens.some(value => value === null))
81
- return null;
82
- const total = tokens.reduce((sum, value) => sum + value, 0);
83
- return Number.isSafeInteger(total) ? total : null;
84
- }
85
- function promptAccounting(usage) {
86
- return {
87
- promptTokens: sumKnownTokens([
88
- usage?.input, usage?.cacheCreation, usage?.cacheRead,
89
- ]),
90
- cachedTokens: sumKnownTokens([usage?.cacheRead]),
91
- };
92
- }
93
32
  /** Single source of truth for ClaudeSession fields → ClaudeSpawnOptions CLI args translation.
94
33
  * Used by both ClaudeSession.toSpawnOptions() (production) and _test.computeSpawnArgs (lock-in test). */
95
34
  function deriveClaudeSpawnOptions(fields) {
@@ -128,7 +67,7 @@ function sameOptionalTextArray(left, right) {
128
67
  return left === right;
129
68
  return sameTextArray(left, right);
130
69
  }
131
- function sameClaudeSpawnCompatibility(left, right) {
70
+ export function sameClaudeSpawnCompatibility(left, right) {
132
71
  return left.cwd === right.cwd
133
72
  && left.routeIdentity === right.routeIdentity
134
73
  && left.composition === right.composition
@@ -159,26 +98,39 @@ function compatibilityFromOptions(options) {
159
98
  browserMcpConfigIdentity: options.browserMcpConfigIdentity ?? null,
160
99
  };
161
100
  }
101
+ /**
102
+ * A string whose equality is exactly {@link sameClaudeSpawnCompatibility}'s predicate — the pool key
103
+ * `EngineSession.identity` needs. Serialized as an explicit, literal field list rather than
104
+ * `Object.keys`, so the order is stable and a future field cannot silently change the encoding.
105
+ *
106
+ * `null` and `[]` stay distinct for `mcpToolAllowlist` (sameOptionalTextArray is identity-sensitive
107
+ * when either side is null) and arrays keep their order (sameTextArray is order-sensitive).
108
+ */
109
+ export function claudeCompatibilityIdentity(compatibility) {
110
+ const fields = [
111
+ ['cwd', compatibility.cwd],
112
+ ['routeIdentity', compatibility.routeIdentity],
113
+ ['composition', compatibility.composition],
114
+ ['interactionBridge', compatibility.interactionBridge],
115
+ ['commissionTools', compatibility.commissionTools],
116
+ ['tools', compatibility.tools],
117
+ ['pluginCapabilityFingerprint', compatibility.pluginCapabilityFingerprint],
118
+ ['supplementalMcpConfigIdentity', compatibility.supplementalMcpConfigIdentity],
119
+ ['browserMcpConfigIdentity', compatibility.browserMcpConfigIdentity],
120
+ ['pluginDirs', compatibility.pluginDirs],
121
+ ['mcpConfigPaths', compatibility.mcpConfigPaths],
122
+ ['mcpToolAllowlist', compatibility.mcpToolAllowlist],
123
+ ];
124
+ return JSON.stringify(fields);
125
+ }
126
+ /** The resolved-spec identity: the compatibility record the pool would compare, serialized. */
127
+ export function claudeSpecIdentity(spec) {
128
+ return claudeCompatibilityIdentity(compatibilityFromOptions(sessionOptionsFromSpec(spec)));
129
+ }
162
130
  /** Resolve per-session settings from the spawn cwd without falling through a pinned trial's config. */
163
131
  function createContextUsageTracker(modelName, cwd, options) {
164
132
  return new ClaudeContextUsageTracker(modelName, resolveAutoCompactWindow(cwd, options.pinnedEnv?.CLAUDE_CONFIG_DIR));
165
133
  }
166
- /**
167
- * Extract the prompt text from a `--replay-user-messages` echo. `message.content` arrives either
168
- * as a bare string or as text blocks. Returns null for anything else — notably the tool_result
169
- * carriers print mode already emits as `user` lines, which must never be read as a prompt echo.
170
- */
171
- export function extractReplayText(data) {
172
- const content = data?.message?.content;
173
- if (typeof content === 'string')
174
- return content;
175
- if (!Array.isArray(content))
176
- return null;
177
- const parts = content
178
- .filter((b) => b?.type === 'text' && typeof b.text === 'string')
179
- .map((b) => b.text);
180
- return parts.length ? parts.join('') : null;
181
- }
182
134
  class ClaudeSession {
183
135
  proc = null;
184
136
  rl = null;
@@ -218,46 +170,30 @@ class ClaudeSession {
218
170
  extraOption;
219
171
  thinking;
220
172
  context;
221
- currentTurn = null;
222
- /** Cursor over the `stream_event` sequence (--include-partial-messages). Session-scoped rather
223
- * than turn-scoped because the stream is a property of the process, and every `message_start`
224
- * resets it anyway. */
225
- streamDeltaState = createStreamDeltaState();
226
- /** Current provider-call usage plus configured/result-reconciled context window. */
227
- contextUsageTracker;
228
- /** Tracks in-flight background tasks (run_in_background) for this session. */
229
- bgTracker = new BgTaskTracker();
230
- /** Set by orchestration to receive spontaneous background-task continuation turns. */
231
- continuationSink = null;
232
- /** One-shot events that arrived before completion-only waiting installed its sink. */
233
- pendingContinuationDeliveries = [];
234
- /** Messages injected into an in-flight turn that the CLI has not echoed back yet, in write
235
- * order. Each is popped by its `--replay-user-messages` echo (the delivery ack). */
236
- pendingInjections = [];
237
- /** Set by orchestration to receive injection delivery acks. */
238
- injectionAck = null;
239
- /** Set when an injected message was consumed with NO turn in flight — the CLI is about to start
240
- * a turn of its own for it. Consumed by the next assistant line, which opens the
241
- * synthetic turn that captures the reply. */
242
- injectionContinuationArmed = false;
173
+ /** Pool eviction hooks supplied by the owner: `onSelfClose` preserves the
174
+ * "only if this key still points at me" guard at the pool; `onEvict` is unconditional, matching
175
+ * the fatal stdin-write path it replaced. */
176
+ onSelfClose;
177
+ onEvict;
178
+ /** Injected throttle sink. Unset in a trial, wired to `handleRateLimitEvent` by
179
+ * `domain/runs/adapters.ts` in the daemon. */
180
+ onRateLimit;
181
+ /** The turn half. Built before the process is spawned, so the first line has a home. */
182
+ turns;
243
183
  alive = false;
244
184
  needsResume;
245
185
  idleTimer = null;
246
186
  turnIdleTimer = null;
247
187
  stderr = '';
248
- cumulativeCostUsd = 0;
249
- /** Captured from result event's modelUsage key for cost_record. */
250
- lastModelName = null;
251
- /** Captured from result event's usage for legacy cost_record and compact accounting. */
252
- lastTokenUsage = null;
253
188
  constructor(channel, sessionId, options) {
254
189
  this.channel = channel;
255
190
  this.sessionId = sessionId;
256
191
  this.sessionKey = options.sessionKey || channel;
192
+ this.onRateLimit = options.onRateLimit;
257
193
  this.needsResume = options.needsResume;
258
194
  this.modelName = options.model || null;
259
195
  this.cwd = resolveSpawnCwd(options.cwd);
260
- this.contextUsageTracker = createContextUsageTracker(this.modelName, this.cwd, options);
196
+ this.turns = new ClaudeTurnMachine(this, createContextUsageTracker(this.modelName, this.cwd, options));
261
197
  this.isUserInitiated = options.isUserInitiated || false;
262
198
  this.commissionTools = options.commissionTools === true;
263
199
  this.callbackSource = options.callbackSource || null;
@@ -279,6 +215,8 @@ class ClaudeSession {
279
215
  this.compatibility = compatibilityFromOptions(options);
280
216
  this.disableHooks = options.disableHooks === true;
281
217
  this.streamDeltas = options.streamDeltas;
218
+ this.onSelfClose = options.onSelfClose;
219
+ this.onEvict = options.onEvict;
282
220
  this.initializeExecutionOptions(options);
283
221
  this.spawnProcess();
284
222
  }
@@ -327,65 +265,12 @@ class ClaudeSession {
327
265
  this.turnIdleTimer = null;
328
266
  this.alive = false;
329
267
  clearActivePlanFile(this.sessionId);
330
- if (this.currentTurn) {
331
- const turn = this.currentTurn;
332
- this.currentTurn = null;
333
- this.closeTurnLogs(turn);
334
- if (this.turnIdleTimer)
335
- clearTimeout(this.turnIdleTimer);
336
- if (turn.spontaneous) {
337
- // The process died mid-continuation. The spontaneous turn has no awaiting caller —
338
- // its reject would only log — so deliver the interruption to the sink directly
339
- // (single-fire; the resolve path never ran because no result event arrived).
340
- this.notifyBgInterrupted(true);
341
- }
342
- else if (turn.killed) {
343
- turn.reject(new CancelledError());
344
- }
345
- else {
346
- const result = extractResult(turn.resultData, this.sessionId, false, code || 1, this.stderr, turn.planFilePath, turn.enteredPlanMode, turn.exitedPlanMode, turn.askUserQuestions, turn.finalOutput, turn.longestOutput);
347
- if (result.resolved)
348
- turn.resolve(result.value);
349
- else
350
- turn.reject(result.error);
351
- }
352
- }
268
+ this.turns.abortTurnOnProcessClose(code, this.stderr);
353
269
  // Waiting-window case (no active turn, background tasks pending): the held status would
354
270
  // otherwise wait forever — any process death (restart / crash / kill / timeout) must
355
271
  // seal it. No-op when nothing is pending; always releases the sink (session is gone).
356
- this.notifyBgInterrupted();
357
- if (sessions.get(this.sessionKey) === this)
358
- sessions.delete(this.sessionKey);
359
- }
360
- /** Deliver a synthetic interrupted result to the continuation sink (single-fire: the sink
361
- * reference is cleared before invoking). Fires only when background work may still produce
362
- * a continuation (or `force`, for a dying spontaneous turn); otherwise just clears the sink. */
363
- notifyBgInterrupted(force = false) {
364
- const sink = this.continuationSink;
365
- if (!sink)
366
- return;
367
- this.continuationSink = null;
368
- // An injected message that was never echoed back, or one already consumed into a spontaneous
369
- // turn that never arrived, is work the caller is still waiting on — seal it like pending
370
- // background work rather than dropping the sink silently.
371
- const injectionOutstanding = this.pendingInjections.length > 0 || this.injectionContinuationArmed;
372
- if (!force && !this.bgTracker.hasPending() && !this.bgTracker.continuationArmed && !injectionOutstanding)
373
- return;
374
- const result = {
375
- sessionId: this.sessionId,
376
- total_cost_usd: null, num_turns: null,
377
- rateLimited: false, rateLimitMessage: null,
378
- planFilePath: null, enteredPlanMode: false, exitedPlanMode: false,
379
- finalOutput: null,
380
- pendingBackgroundTasks: 0, undeliveredBackgroundTasks: 0,
381
- backgroundInterrupted: true,
382
- };
383
- try {
384
- sink.onResult(result);
385
- }
386
- catch (e) {
387
- log.warn('bg-interrupted sink onResult threw:', e.message);
388
- }
272
+ this.turns.notifyBgInterrupted();
273
+ this.onSelfClose?.(this.sessionKey, this);
389
274
  }
390
275
  validateSupplementalMcpConfig() {
391
276
  const configPath = this.supplementalMcpConfigPath;
@@ -410,7 +295,7 @@ class ClaudeSession {
410
295
  this.supervision = spawned.supervision;
411
296
  this.stderr = '';
412
297
  this.rl = createInterface({ input: this.proc.stdout, crlfDelay: Infinity });
413
- this.rl.on('line', (line) => this.handleLine(line));
298
+ this.rl.on('line', (line) => this.turns.handleLine(line));
414
299
  this.proc.stderr.on('data', (data) => { this.stderr += data.toString(); });
415
300
  this.proc.on('close', (code) => this.handleProcessClose(code));
416
301
  }
@@ -426,187 +311,6 @@ class ClaudeSession {
426
311
  this.attachSpawnedProcess(spawned);
427
312
  this.armProcessTimers();
428
313
  }
429
- createTurnStreams(userMessage) {
430
- if (!this.captureTranscriptLogs) {
431
- const sink = () => new Writable({ write(_chunk, _encoding, done) { done(); } });
432
- return { rawStream: sink(), txtStream: sink(), pairKey: null, releaseCapture: null };
433
- }
434
- mkdirSync(LOGS_DIR, { recursive: true });
435
- const ts = readableTimestamp();
436
- const rawPath = path.join(LOGS_DIR, `claude-output-${ts}.jsonl`);
437
- const txtPath = path.join(LOGS_DIR, `claude-output-${ts}.txt`);
438
- const rawStream = createWriteStream(rawPath, { flags: 'a' });
439
- const txtStream = createWriteStream(txtPath, { flags: 'a' });
440
- const releaseCapture = activeClaudeCaptureRegistry.register(ts, [rawPath, txtPath]);
441
- txtStream.write(`=== Cortex session started at ${new Date().toISOString()} ===\n=== channel=${this.channel}, session=${this.sessionId} ===\n\n`);
442
- txtStream.write(`[user-input] ${userMessage}\n\n`);
443
- return { rawStream, txtStream, pairKey: ts, releaseCapture };
444
- }
445
- registerTurn(resolve, reject, streams, options) {
446
- clearActivePlanFile(this.sessionId);
447
- this.currentTurn = {
448
- resolve, reject,
449
- resultData: null,
450
- planFilePath: null,
451
- enteredPlanMode: false,
452
- exitedPlanMode: false,
453
- askUserQuestions: [],
454
- finalOutput: null,
455
- longestOutput: null,
456
- turnCount: 0,
457
- subagentTurnCount: 0,
458
- capturePairKey: streams.pairKey,
459
- releaseCapture: streams.releaseCapture,
460
- onProgress: options.onProgress || null,
461
- onAssistantMessage: options.onAssistantMessage || null,
462
- onAssistantDelta: options.onAssistantDelta || null,
463
- onToolUse: options.onToolUse || null,
464
- onToolResult: options.onToolResult || null,
465
- onCompact: options.onCompact || null,
466
- onModelFallback: options.onModelFallback || null,
467
- onContextUsage: options.onContextUsage || null,
468
- onSubagentActivity: options.onSubagentActivity || null,
469
- onSubagentEnd: options.onSubagentEnd || null,
470
- rawStream: streams.rawStream,
471
- txtStream: streams.txtStream,
472
- killed: false,
473
- };
474
- }
475
- deliverContinuation(delivery) {
476
- const sink = this.continuationSink;
477
- if (!sink) {
478
- if (this.preserveUnreportedAccounting)
479
- this.pendingContinuationDeliveries.push(delivery);
480
- return;
481
- }
482
- try {
483
- delivery(sink);
484
- }
485
- catch (error) {
486
- log.warn('continuation sink threw:', error.message);
487
- }
488
- }
489
- /** Register/replace the continuation sink. Persists across normal turns; lives as long
490
- * as the pooled session, until close()/kill(). */
491
- setContinuationSink(sink) {
492
- this.continuationSink = sink;
493
- const pending = this.pendingContinuationDeliveries.splice(0);
494
- for (const delivery of pending)
495
- this.deliverContinuation(delivery);
496
- }
497
- clearContinuationSink() {
498
- this.continuationSink = null;
499
- this.pendingContinuationDeliveries.length = 0;
500
- }
501
- /** Register/replace the injection delivery-ack sink. Lifetime mirrors continuationSink. */
502
- setInjectionAckSink(sink) {
503
- this.injectionAck = sink;
504
- }
505
- clearInjectionAckSink() {
506
- this.injectionAck = null;
507
- }
508
- /**
509
- * Deliver a user message into the turn already in flight.
510
- *
511
- * Writes the SAME NDJSON user line a normal turn writes, but registers NO turn: the message is
512
- * absorbed by the run already in progress, so the already-awaited turn promise covers it and no
513
- * second result is fabricated. Cost/turn accounting stays with the running turn.
514
- *
515
- * Where it lands is a race the caller cannot control, so both outcomes are wired here:
516
- * - tool-result boundary → folds into the running turn, ONE result. Nothing extra
517
- * to do; the turn's own callbacks carry the reply.
518
- * - mid-text-generation → the CLI drains its queue only after this turn's result and then
519
- * starts a turn of its own. The echo handler arms the existing spontaneous-turn
520
- * path so that reply is captured by continuationSink instead of dropped.
521
- *
522
- * Returns false when there is no live process or no active turn — the caller then falls back to
523
- * the normal queue.
524
- */
525
- injectUserMessage(message) {
526
- if (!this.alive || !this.proc?.stdin)
527
- return false;
528
- // No turn in flight ⇒ nothing to inject INTO. A message written here would open an untracked
529
- // turn whose reply nobody is awaiting; the caller must enqueue it as a normal turn instead.
530
- if (!this.currentTurn)
531
- return false;
532
- const files = (message.attachments || []).map((a) => ({
533
- mimetype: a.mimeType, localPath: a.path, name: path.basename(a.path),
534
- }));
535
- const prompt = buildPrompt(message.text, files);
536
- try {
537
- this.writeTurnStdin(prompt);
538
- }
539
- catch {
540
- // writeTurnStdin already marked the session dead and rejected the in-flight turn — the pipe
541
- // is gone, so report "cannot inject" rather than propagating into the caller's routing.
542
- return false;
543
- }
544
- this.pendingInjections.push({ prompt, text: message.text });
545
- this.resetIdleTimer();
546
- this.bumpTurnIdleTimer();
547
- log.info(`Injected mid-turn message into ${this.sessionId.substring(0, 8)} (${prompt.length} chars)`);
548
- return true;
549
- }
550
- /**
551
- * Handle a `--replay-user-messages` echo. The CLI echoes EVERY user message, so most echoes are
552
- * the turn's own opening prompt and must be ignored; only an echo matching the head of the
553
- * pending-injection queue is a delivery ack. Nothing else in the system reads these events.
554
- */
555
- handleReplayEcho(data) {
556
- const text = extractReplayText(data);
557
- if (text === null)
558
- return;
559
- const head = this.pendingInjections[0];
560
- if (!head || head.prompt !== text)
561
- return; // the turn's own prompt (or a tool_result carrier)
562
- this.pendingInjections.shift();
563
- // Consumed with no turn in flight ⇒ this is the post-result outcome: the CLI is starting a turn
564
- // of its own. Arm the spontaneous-turn capture before its first assistant line arrives.
565
- const foldedIntoTurn = !!this.currentTurn;
566
- if (!foldedIntoTurn)
567
- this.injectionContinuationArmed = true;
568
- const ack = this.injectionAck;
569
- if (!ack)
570
- return;
571
- try {
572
- ack.onDelivered({ text: head.text, foldedIntoTurn });
573
- }
574
- catch (e) {
575
- log.warn('injection onDelivered threw:', e.message);
576
- }
577
- }
578
- continuationCallbacks() {
579
- return {
580
- resolve: (value) => this.deliverContinuation(sink => sink.onResult(value)),
581
- reject: (error) => log.warn('continuation turn rejected:', error?.message ?? String(error)),
582
- onAssistantMessage: (text, _blockId, model, subagent) => this.deliverContinuation(sink => sink.onAssistantText(text, model, subagent)),
583
- onToolUse: (name, input, id, subagent) => this.deliverContinuation(sink => sink.onToolUse?.(name, input, id, subagent)),
584
- onToolResult: (id, content, isError, subagent) => this.deliverContinuation(sink => sink.onToolResult?.(id, content, isError, subagent)),
585
- onContextUsage: (usage) => this.deliverContinuation(sink => sink.onContextUsage?.(usage)),
586
- onModelFallback: null,
587
- };
588
- }
589
- /** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
590
- * background task finishes. Its output is delivered or buffered for continuationSink. */
591
- openContinuationTurn(label = '[background-task continuation]') {
592
- this.bgTracker.disarmContinuation();
593
- const streams = this.createTurnStreams(label);
594
- // The hold's watchdogs bound the WAIT for this turn, not the turn itself: a continuation
595
- // that runs longer than the grace/max-wait window must not be sealed idle mid-stream.
596
- this.deliverContinuation(sink => sink.onTurnOpen?.());
597
- this.currentTurn = {
598
- ...this.continuationCallbacks(),
599
- resultData: null, planFilePath: null,
600
- enteredPlanMode: false, exitedPlanMode: false,
601
- askUserQuestions: [], finalOutput: null, longestOutput: null, turnCount: 0, subagentTurnCount: 0,
602
- capturePairKey: streams.pairKey,
603
- releaseCapture: streams.releaseCapture,
604
- onProgress: null, onAssistantDelta: null, onCompact: null, onSubagentActivity: null,
605
- onSubagentEnd: null,
606
- rawStream: streams.rawStream, txtStream: streams.txtStream,
607
- killed: false, spontaneous: true,
608
- };
609
- }
610
314
  writeTurnStdin(prompt) {
611
315
  const stdinMsg = JSON.stringify({
612
316
  type: 'user',
@@ -618,13 +322,8 @@ class ClaudeSession {
618
322
  }
619
323
  catch (e) {
620
324
  this.alive = false;
621
- if (this.currentTurn) {
622
- const turn = this.currentTurn;
623
- this.currentTurn = null;
624
- this.closeTurnLogs(turn);
625
- turn.reject(new Error(`Failed to write to claude stdin: ${e.message}`));
626
- }
627
- sessions.delete(this.sessionKey);
325
+ this.turns.failInFlightTurn(new Error(`Failed to write to claude stdin: ${e.message}`));
326
+ this.onEvict?.(this.sessionKey, this);
628
327
  throw new Error(`Claude process stdin write failed: ${e.message}`);
629
328
  }
630
329
  }
@@ -640,17 +339,15 @@ class ClaudeSession {
640
339
  this.spawnProcess();
641
340
  }
642
341
  this.resetIdleTimer();
643
- const prompt = buildPrompt(userMessage, options.files || []);
644
- const streams = this.createTurnStreams(userMessage);
342
+ const prompt = buildPrompt(userMessage, options.attachments ?? []);
343
+ const streams = this.turns.createTurnStreams(userMessage);
645
344
  const turnPromise = new Promise((resolve, reject) => {
646
- this.registerTurn(resolve, reject, streams, options);
345
+ this.turns.registerTurn(resolve, reject, streams, options);
647
346
  });
648
347
  this.writeTurnStdin(prompt);
649
348
  this.startTurnIdleTimer();
650
349
  const result = await turnPromise;
651
- if (this.turnIdleTimer)
652
- clearTimeout(this.turnIdleTimer);
653
- this.turnIdleTimer = null;
350
+ this.clearTurnIdleTimer();
654
351
  this.resetIdleTimer();
655
352
  return result;
656
353
  }
@@ -674,19 +371,7 @@ class ClaudeSession {
674
371
  throw new Error('Claude did not confirm compaction with compact_boundary');
675
372
  return {
676
373
  status: 'compacted', tokensBefore, estimatedTokensAfter: null,
677
- contextUsage: null, usage: this.compactUsage(result),
678
- };
679
- }
680
- compactUsage(result) {
681
- const tokens = this.lastTokenUsage;
682
- if (!tokens && !result.total_cost_usd)
683
- return null;
684
- return {
685
- inputTokens: tokens?.input ?? 0,
686
- outputTokens: tokens?.output ?? 0,
687
- cacheReadTokens: tokens?.cacheRead ?? 0,
688
- cacheWriteTokens: tokens?.cacheCreation ?? 0,
689
- costUsd: result.total_cost_usd,
374
+ contextUsage: null, usage: this.turns.compactUsage(result),
690
375
  };
691
376
  }
692
377
  bumpTurnIdleTimer() {
@@ -695,394 +380,6 @@ class ClaudeSession {
695
380
  clearTimeout(this.turnIdleTimer);
696
381
  this.startTurnIdleTimer();
697
382
  }
698
- turnCost(data) {
699
- if (data.total_cost_usd == null)
700
- return 0;
701
- const cumulativeCost = data.total_cost_usd;
702
- const turnCost = cumulativeCost - this.cumulativeCostUsd;
703
- this.cumulativeCostUsd = cumulativeCost;
704
- return turnCost > 0 ? turnCost : 0;
705
- }
706
- captureTurnAccounting(data) {
707
- const missingToken = this.preserveUnreportedAccounting ? null : 0;
708
- this.lastTokenUsage = data.usage ? {
709
- input: data.usage.input_tokens ?? missingToken,
710
- output: data.usage.output_tokens ?? missingToken,
711
- cacheCreation: data.usage.cache_creation_input_tokens ?? missingToken,
712
- cacheRead: data.usage.cache_read_input_tokens ?? missingToken,
713
- } : null;
714
- const models = data.modelUsage ? Object.keys(data.modelUsage) : [];
715
- this.lastModelName = models[0] ?? null;
716
- return this.turnCost(data);
717
- }
718
- reportedAccounting(data) {
719
- const usage = data.usage;
720
- const turnUsage = usage ? {
721
- input: tokenValue(usage.input_tokens),
722
- output: tokenValue(usage.output_tokens),
723
- cacheCreation: tokenValue(usage.cache_creation_input_tokens),
724
- cacheRead: tokenValue(usage.cache_read_input_tokens),
725
- } : null;
726
- return {
727
- usageReported: usage != null,
728
- inputTokens: turnUsage?.input ?? null,
729
- outputTokens: turnUsage?.output ?? null,
730
- cacheReadTokens: turnUsage?.cacheRead ?? null,
731
- cacheCreationTokens: turnUsage?.cacheCreation ?? null,
732
- ...promptAccounting(turnUsage),
733
- model: data.modelUsage ? Object.keys(data.modelUsage)[0] ?? null : null,
734
- };
735
- }
736
- settleResultTurn(turn, data, result) {
737
- if (result.resolved) {
738
- const value = result.value;
739
- value.reportedAccounting = this.reportedAccounting(data);
740
- if (this.preserveUnreportedAccounting) {
741
- value.costReported = data.total_cost_usd != null;
742
- }
743
- value.pendingBackgroundTasks = this.bgTracker.pendingCount;
744
- // A background notification observed during this turn whose own turn has not opened yet
745
- // (it landed while the model was producing this turn's final text) is one more delivery
746
- // still owed: the CLI opens that turn right after this result. Count it as undelivered so
747
- // the hold waits (grace-bounded) instead of sealing idle between the two turns.
748
- value.undeliveredBackgroundTasks = this.bgTracker.undeliveredCount
749
- + (this.bgTracker.continuationArmed ? 1 : 0);
750
- }
751
- this.currentTurn = null;
752
- if (this.turnIdleTimer)
753
- clearTimeout(this.turnIdleTimer);
754
- this.turnIdleTimer = null;
755
- const formatted = formatEvent(data);
756
- if (formatted)
757
- turn.txtStream.write(formatted + '\n');
758
- turn.txtStream.write(`\n=== Turn finished at ${new Date().toISOString()} ===\n`);
759
- turn.rawStream.end();
760
- turn.txtStream.end();
761
- turn.releaseCapture?.();
762
- turn.releaseCapture = null;
763
- if (result.resolved)
764
- turn.resolve(result.value);
765
- else
766
- turn.reject(result.error);
767
- }
768
- handleResultEvent(turn, data) {
769
- turn.resultData = { ...data, total_cost_usd: this.captureTurnAccounting(data) };
770
- const result = extractResult(turn.resultData, this.sessionId, false, 0, '', turn.planFilePath, turn.enteredPlanMode, turn.exitedPlanMode, turn.askUserQuestions, turn.finalOutput, turn.longestOutput);
771
- this.settleResultTurn(turn, data, result);
772
- }
773
- /** Preserve the complete result carrier that print mode emits as a `user` content block. */
774
- handleToolResultEvent(turn, data) {
775
- if (typeof turn.onToolResult !== 'function')
776
- return;
777
- const content = data.message?.content;
778
- if (!Array.isArray(content))
779
- return;
780
- // A `user` line carrying subagent linkage is the subagent's OWN tool result, not the parent's.
781
- // The parent's `Agent`/`Task` result arrives unlinked, as an ordinary main-agent line.
782
- const subagent = subagentAttribution(data);
783
- for (const block of content) {
784
- if (!block || block.type !== 'tool_result')
785
- continue;
786
- const toolUseId = typeof block.tool_use_id === 'string' ? block.tool_use_id : '';
787
- try {
788
- turn.onToolResult(toolUseId, toolResultText(block), block.is_error === true, subagent);
789
- }
790
- catch (e) {
791
- log.warn('onToolResult threw:', e.message);
792
- }
793
- }
794
- }
795
- /**
796
- * A backgrounded subagent's own `assistant`/`user` line arriving with no turn open. Routed here
797
- * by `routeLine` → 'subagent-orphan' instead of being dropped. Deliberately minimal: it feeds
798
- * the continuation sink the same three attributed callbacks the in-turn path uses, and touches
799
- * NO turn bookkeeping (no turn counts, no finalOutput, no plan-file capture, no delta cursor) —
800
- * there is no turn here to account for, and the main agent's next real turn must not inherit
801
- * anything from a subagent that ran beside it.
802
- */
803
- handleOrphanSubagentLine(data) {
804
- const subagent = subagentAttribution(data);
805
- if (!subagent)
806
- return;
807
- const content = data.message?.content;
808
- if (!Array.isArray(content))
809
- return;
810
- const model = typeof data.message?.model === 'string' ? data.message.model : null;
811
- for (const block of content) {
812
- if (!block)
813
- continue;
814
- if (block.type === 'tool_use') {
815
- const id = typeof block.id === 'string' ? block.id : '';
816
- this.deliverContinuation(s => s.onToolUse?.(block.name || '?', block.input || {}, id, subagent));
817
- }
818
- else if (block.type === 'text' && block.text) {
819
- this.deliverContinuation(s => s.onAssistantText(block.text, model, subagent));
820
- }
821
- else if (block.type === 'tool_result') {
822
- const id = typeof block.tool_use_id === 'string' ? block.tool_use_id : '';
823
- this.deliverContinuation(s => s.onToolResult?.(id, toolResultText(block), block.is_error === true, subagent));
824
- }
825
- }
826
- }
827
- handleAssistantToolBlock(turn, block, subagent) {
828
- if (block.name === 'Write' && isPlanFilePath(block.input?.file_path)) {
829
- turn.planFilePath = block.input.file_path;
830
- setActivePlanFile(this.sessionId, block.input.file_path);
831
- }
832
- if (block.name === 'EnterPlanMode')
833
- turn.enteredPlanMode = true;
834
- if (block.name === 'ExitPlanMode')
835
- turn.exitedPlanMode = true;
836
- if (typeof turn.onToolUse !== 'function')
837
- return;
838
- try {
839
- turn.onToolUse(block.name || '?', block.input || {}, typeof block.id === 'string' ? block.id : '', subagent);
840
- }
841
- catch (error) {
842
- log.warn('onToolUse threw:', error.message);
843
- }
844
- }
845
- handleAssistantTextBlock(turn, data, block, subagent) {
846
- if (!block.text)
847
- return;
848
- const model = typeof data.message?.model === 'string' ? data.message.model : null;
849
- // A subagent's text is NOT this turn's answer, and it did not stream: the CLI attaches subagent
850
- // linkage only to complete `assistant`/`user` messages, never to `stream_event`. So it must not
851
- // become finalOutput, must not win longestOutput, and — above all — must not consume the delta
852
- // cursor, which belongs to a main-agent block still being streamed.
853
- if (subagent) {
854
- turn.onAssistantMessage?.(block.text, undefined, model, subagent);
855
- return;
856
- }
857
- turn.finalOutput = block.text;
858
- if (block.text.length > (turn.longestOutput?.length || 0))
859
- turn.longestOutput = block.text;
860
- const blockId = takeTextBlockId(this.streamDeltaState) ?? undefined;
861
- const streamedModel = this.streamDeltaState.messageId === data.message?.id
862
- ? this.streamDeltaState.model
863
- : null;
864
- turn.onAssistantMessage?.(block.text, blockId, model ?? streamedModel);
865
- }
866
- handleAssistantEvent(turn, data) {
867
- // Every line still walks every branch below — subagent lines are TAGGED, never dropped, so the
868
- // journal keeps a complete trajectory. What the tag changes is attribution: a subagent's turns
869
- // are counted apart from the main agent's, and its text cannot be mistaken for the answer.
870
- const subagent = subagentAttribution(data);
871
- if (subagent)
872
- turn.subagentTurnCount += 1;
873
- else
874
- turn.turnCount += 1;
875
- for (const block of (data.message?.content || [])) {
876
- if (block.type === 'tool_use')
877
- this.handleAssistantToolBlock(turn, block, subagent);
878
- if (block.type === 'text')
879
- this.handleAssistantTextBlock(turn, data, block, subagent);
880
- }
881
- // A subagent's message did not advance the main agent's turn, so re-rendering progress would
882
- // redraw the same number. The JSONL path withholds turn_progress on sidechain records for the
883
- // same reason.
884
- if (!subagent) {
885
- turn.onProgress?.({ num_turns: turn.turnCount, total_cost_usd: null, duration_ms: null });
886
- }
887
- }
888
- emitContextUsage(data) {
889
- const usage = this.contextUsageTracker.observe(data);
890
- const callback = this.currentTurn?.onContextUsage;
891
- if (!usage || typeof callback !== 'function')
892
- return;
893
- try {
894
- callback(usage);
895
- }
896
- catch (e) {
897
- log.warn('onContextUsage threw:', e.message);
898
- }
899
- }
900
- /**
901
- * OC-11 / §17 G4-SA5 — read the linkage the CLI already puts on the wire. A non-null
902
- * `parent_tool_use_id` means the line is a native subagent's output; `null` or absent is the
903
- * parent's own turn. Purely ADDITIVE: every branch above still sees the line, because
904
- * `adapter.ts` is shared by every Cortex session and diverting subagent output would change
905
- * assistant streaming and turn counting for every product surface.
906
- */
907
- emitSubagentActivity(data) {
908
- const parentToolUseId = data?.parent_tool_use_id;
909
- if (typeof parentToolUseId !== 'string')
910
- return;
911
- const kind = subagentActivityKind(data);
912
- if (!kind)
913
- return;
914
- const subagentType = typeof data.subagent_type === 'string' ? data.subagent_type : null;
915
- const callback = this.currentTurn?.onSubagentActivity;
916
- if (typeof callback !== 'function')
917
- return;
918
- try {
919
- callback(parentToolUseId, subagentType, kind);
920
- }
921
- catch (e) {
922
- log.warn('onSubagentActivity threw:', e.message);
923
- }
924
- }
925
- emitModelFallback(data) {
926
- const event = parseModelFallbackEvent(data);
927
- const callback = this.currentTurn?.onModelFallback;
928
- if (!event || !callback)
929
- return;
930
- try {
931
- callback({ originalModel: event.originalModel, fallbackModel: event.fallbackModel });
932
- }
933
- catch (e) {
934
- log.warn('onModelFallback threw:', e.message);
935
- }
936
- }
937
- handleLine(line) {
938
- if (!line)
939
- return;
940
- this.resetIdleTimer();
941
- this.bumpTurnIdleTimer();
942
- let parsed;
943
- let isJson = false;
944
- try {
945
- parsed = JSON.parse(line);
946
- isJson = true;
947
- }
948
- catch { /* handled below */ }
949
- // `stream_event` lines are the token-level preview of a block the CLI will also deliver
950
- // complete. They dominate stdout once --include-partial-messages is on (measured: 74-86% of
951
- // all lines), and everything they carry is repeated verbatim by the complete event, so they
952
- // are deliberately kept out of the per-turn raw jsonl and the daemon log. Handled first, and
953
- // separately, because everything below is about complete events.
954
- if (isJson && parsed?.type === 'stream_event') {
955
- this.emitContextUsage(parsed);
956
- const delta = parseStreamEvent(parsed, this.streamDeltaState);
957
- if (delta && typeof this.currentTurn?.onAssistantDelta === 'function') {
958
- try {
959
- this.currentTurn.onAssistantDelta(delta.text, delta.blockId);
960
- }
961
- catch (e) {
962
- log.warn('onAssistantDelta threw:', e.message);
963
- }
964
- }
965
- return;
966
- }
967
- if (this.currentTurn?.rawStream)
968
- this.currentTurn.rawStream.write(line + '\n');
969
- try {
970
- const data = parsed;
971
- if (!isJson)
972
- throw new Error('not json');
973
- // Context compaction boundary: invalidate the old provider-call cursor immediately, then
974
- // surface the boundary to the active turn so observers (e.g. Slack) can notify.
975
- if (data.type === 'system' && data.subtype === 'compact_boundary')
976
- this.emitContextUsage(data);
977
- if (data.type === 'system' && data.subtype === 'compact_boundary' && this.currentTurn?.onCompact) {
978
- const meta = data.compact_metadata ?? {};
979
- try {
980
- this.currentTurn.onCompact({
981
- trigger: typeof meta.trigger === 'string' ? meta.trigger : 'auto',
982
- preTokens: typeof meta.pre_tokens === 'number' ? meta.pre_tokens : undefined,
983
- });
984
- }
985
- catch (e) {
986
- log.warn('onCompact threw:', e.message);
987
- }
988
- }
989
- this.emitModelFallback(data);
990
- if (data.type === 'rate_limit_event' && data.rate_limit_info) {
991
- const mode = this.anthropicBaseUrl?.match(/\/m\/([^/]+)\//)?.[1] || undefined;
992
- handleRateLimitEvent(data.rate_limit_info, {
993
- provider: 'anthropic', displayName: 'Anthropic', mode,
994
- }).catch(e => log.error('handleRateLimitEvent error:', e));
995
- }
996
- // `--replay-user-messages` echo: the CLI's delivery ack for an injected message.
997
- // Handled here and nowhere else — it is deliberately NOT fed to turn bookkeeping, background
998
- // tracking, or conversation history (a `user` record there would shift every later turn
999
- // index and break edit/rewind). Replays are inert for every other consumer.
1000
- if (data.type === 'user' && data.isReplay)
1001
- this.handleReplayEcho(data);
1002
- if (data.type === 'user' && !data.isReplay && this.currentTurn)
1003
- this.handleToolResultEvent(this.currentTurn, data);
1004
- // Track background-task lifecycle on every line (even with no active turn) so the
1005
- // pending count stays accurate across the turn boundary.
1006
- this.bgTracker.observe(data);
1007
- // Authoritative end-of-subagent, forwarded whether or not a turn is open: a subagent can
1008
- // finish inside its parent turn as easily as beside it, and `subagentEndFor` is consuming,
1009
- // so the signal is emitted exactly once either way.
1010
- const subagentEnd = this.bgTracker.subagentEndFor(data);
1011
- if (subagentEnd) {
1012
- // In-turn first: a subagent that finishes while its parent turn is still open has no
1013
- // continuation sink to reach (one is registered only when the turn ends holding background
1014
- // work), and `subagentEndFor` is consuming — dropping it here loses the end for good.
1015
- const inTurn = this.currentTurn?.onSubagentEnd;
1016
- if (inTurn) {
1017
- try {
1018
- inTurn(subagentEnd.parentToolUseId, subagentEnd.status);
1019
- }
1020
- catch (e) {
1021
- log.warn('onSubagentEnd threw:', e.message);
1022
- }
1023
- }
1024
- else {
1025
- this.deliverContinuation(s => s.onSubagentEnd?.(subagentEnd.parentToolUseId, subagentEnd.status));
1026
- }
1027
- }
1028
- // A backgrounded subagent keeps working after its parent turn closed, and the CLI keeps
1029
- // streaming its lines. With no turn open the branches above skip them, so route them to the
1030
- // continuation sink here — otherwise the whole tail of a background agent's trajectory
1031
- // (tool calls AND its final report) is received and then dropped.
1032
- if (!this.currentTurn && routeLine(this.bgTracker, data, false) === 'subagent-orphan') {
1033
- this.handleOrphanSubagentLine(data);
1034
- }
1035
- // No active turn, and the model just started speaking anyway: either a background task
1036
- // finished (bgTracker armed) or an injected message was consumed after this turn's result
1037
- // Both make the CLI open a turn of its own — open a synthetic turn for it so its
1038
- // output is routed (to continuationSink) instead of being dropped.
1039
- const canCaptureContinuation = this.continuationSink || this.preserveUnreportedAccounting;
1040
- if (!this.currentTurn && canCaptureContinuation && data.type === 'assistant'
1041
- && (this.injectionContinuationArmed || routeLine(this.bgTracker, data, false) === 'open-continuation')) {
1042
- const fromInjection = this.injectionContinuationArmed;
1043
- this.injectionContinuationArmed = false;
1044
- this.openContinuationTurn(fromInjection ? '[injected-message continuation]' : '[background-task continuation]');
1045
- }
1046
- if (data.type === 'result' && this.currentTurn) {
1047
- // A task-notification turn's result can only settle a spontaneous turn. When it lands on
1048
- // a user turn it is the CLI closing a notification turn of its own — on `--resume` it
1049
- // reports background work orphaned by the previous process and emits a 0-turn result
1050
- // BEFORE reading the prompt on stdin. Settling here resolved the user turn empty in ~2s
1051
- // and dropped the minutes of real work that followed (2026-09-06 investigation).
1052
- if (isContinuationResult(data) && !this.currentTurn.spontaneous) {
1053
- log.info(`Ignoring notification-turn result on user turn ${this.sessionId.substring(0, 8)} (num_turns=${data.num_turns ?? '?'})`);
1054
- this.currentTurn.txtStream.write('[notification-turn result ignored — user turn still open]\n');
1055
- return;
1056
- }
1057
- this.emitContextUsage(data);
1058
- this.handleResultEvent(this.currentTurn, data);
1059
- return;
1060
- }
1061
- if (data.type === 'assistant' && this.currentTurn)
1062
- this.handleAssistantEvent(this.currentTurn, data);
1063
- // Emitted last so the census event trails the normalized events the same line already
1064
- // produced, keeping contiguous tool batches contiguous for the ATIF grouper.
1065
- this.emitSubagentActivity(data);
1066
- const formatted = formatEvent(data);
1067
- if (formatted && this.currentTurn?.txtStream)
1068
- this.currentTurn.txtStream.write(formatted + '\n');
1069
- }
1070
- catch {
1071
- if (this.currentTurn?.txtStream)
1072
- this.currentTurn.txtStream.write(`[raw] ${line}\n`);
1073
- }
1074
- log.info('stream:', line.substring(0, 200));
1075
- }
1076
- closeTurnLogs(turn) {
1077
- try {
1078
- turn.txtStream.write(`\n=== Turn ended at ${new Date().toISOString()} ===\n`);
1079
- turn.rawStream.end();
1080
- turn.txtStream.end();
1081
- }
1082
- catch { }
1083
- turn.releaseCapture?.();
1084
- turn.releaseCapture = null;
1085
- }
1086
383
  resetIdleTimer() {
1087
384
  if (this.idleTimer)
1088
385
  clearTimeout(this.idleTimer);
@@ -1090,7 +387,7 @@ class ClaudeSession {
1090
387
  // awaiting its spontaneous turn — the session must stay alive to receive the continuation,
1091
388
  // even through a long silent wait. Don't arm idle-close; the session lives until the
1092
389
  // background work settles or it is closed/killed explicitly.
1093
- if (this.bgTracker.hasPending() || this.pendingInjections.length > 0 || this.injectionContinuationArmed) {
390
+ if (this.turns.holdsIdle()) {
1094
391
  this.idleTimer = null;
1095
392
  return;
1096
393
  }
@@ -1104,17 +401,15 @@ class ClaudeSession {
1104
401
  clearTimeout(this.idleTimer);
1105
402
  if (this.turnIdleTimer)
1106
403
  clearTimeout(this.turnIdleTimer);
1107
- // Do NOT clear continuationSink here: if background tasks are pending, the process
404
+ // Do NOT clear backgroundTurnSink here: if background tasks are pending, the process
1108
405
  // 'close' event (handleProcessClose) must still deliver the interruption to the sink
1109
406
  // so the held "background task running" status seals instead of waiting forever.
1110
407
  if (!this.proc || !this.alive) {
1111
408
  // Process already gone (or never spawned): no 'close' event will come — seal now.
1112
- this.notifyBgInterrupted();
1113
- sessions.delete(this.sessionKey);
409
+ this.turns.notifyBgInterrupted();
1114
410
  return;
1115
411
  }
1116
412
  this.alive = false;
1117
- sessions.delete(this.sessionKey);
1118
413
  try {
1119
414
  this.proc.stdin.end();
1120
415
  }
@@ -1147,10 +442,7 @@ class ClaudeSession {
1147
442
  if (!this.proc || this.proc.exitCode !== null)
1148
443
  return false;
1149
444
  this.alive = false;
1150
- if (sessions.get(this.sessionKey) === this)
1151
- sessions.delete(this.sessionKey);
1152
- if (this.currentTurn)
1153
- this.currentTurn.killed = true;
445
+ this.turns.markCurrentTurnKilled();
1154
446
  if (this.supervision) {
1155
447
  this.supervision.cancel('cancel');
1156
448
  return true;
@@ -1163,6 +455,38 @@ class ClaudeSession {
1163
455
  return false;
1164
456
  }
1165
457
  }
458
+ // --- TurnHost port ---
459
+ /** The live-stdin precondition `injectUserMessage` checks before writing. */
460
+ canWriteStdin() {
461
+ return this.alive && !!this.proc?.stdin;
462
+ }
463
+ clearTurnIdleTimer() {
464
+ if (this.turnIdleTimer)
465
+ clearTimeout(this.turnIdleTimer);
466
+ this.turnIdleTimer = null;
467
+ }
468
+ /** Forward a provider rate-limit window to the host's throttle. With no sink injected the
469
+ * observation is dropped — the adapter has no opinion about quota policy (D10). */
470
+ reportRateLimit(info, origin) {
471
+ return this.onRateLimit ? this.onRateLimit(info, origin) : Promise.resolve();
472
+ }
473
+ // --- Turn delegation. Thin by design: `ClaudeAdapter.spawn` and the unit tests still reach the
474
+ // turn through the session. ---
475
+ handleLine(line) { this.turns.handleLine(line); }
476
+ createTurnStreams(userMessage) { return this.turns.createTurnStreams(userMessage); }
477
+ get currentTurn() { return this.turns.currentTurn; }
478
+ set currentTurn(turn) { this.turns.currentTurn = turn; }
479
+ get backgroundTurnSink() { return this.turns.backgroundTurnSink; }
480
+ set backgroundTurnSink(sink) { this.turns.backgroundTurnSink = sink; }
481
+ get bgTracker() { return this.turns.bgTracker; }
482
+ /** Read by `pushDerivedTurnEvents` as the turn's accountingSource. */
483
+ get lastModelName() { return this.turns.lastModelName; }
484
+ get lastTokenUsage() { return this.turns.lastTokenUsage; }
485
+ setBackgroundTurnSink(sink) { this.turns.setBackgroundTurnSink(sink); }
486
+ clearBackgroundTurnSink() { this.turns.clearBackgroundTurnSink(); }
487
+ setInjectionAckSink(sink) { this.turns.setInjectionAckSink(sink); }
488
+ clearInjectionAckSink() { this.turns.clearInjectionAckSink(); }
489
+ injectUserMessage(message) { return this.turns.injectUserMessage(message); }
1166
490
  getSupervision() {
1167
491
  return this.supervision;
1168
492
  }
@@ -1170,47 +494,6 @@ class ClaudeSession {
1170
494
  return this.alive;
1171
495
  }
1172
496
  }
1173
- // --- Session pool ---
1174
- const sessions = new Map();
1175
- function getOrCreateSession(channel, sessionId, options) {
1176
- const key = options.sessionKey || channel;
1177
- const compatibility = compatibilityFromOptions(options);
1178
- let session = sessions.get(key);
1179
- const incompatible = session && !session.matchesSpawn(compatibility);
1180
- if (!session || !session.isAlive() || incompatible || (options.needsResume && session.sessionId !== sessionId)) {
1181
- if (session)
1182
- session.close();
1183
- session = new ClaudeSession(channel, sessionId, { ...options, sessionKey: key });
1184
- sessions.set(key, session);
1185
- }
1186
- return session;
1187
- }
1188
- export function closeSession(channel, sessionKey) {
1189
- const key = sessionKey || channel;
1190
- const session = sessions.get(key);
1191
- if (session)
1192
- session.close();
1193
- }
1194
- /** Hard-stop the pooled session for a channel (SIGTERM, same path the foreground Stop takes via
1195
- * handle.kill()). Unlike closeSession's graceful stdin-end + 30s grace, this ends the process now
1196
- * — used by the Stop path to actually kill background tasks still running inside it after the
1197
- * foreground turn ended. Returns false when no live session exists for the key. */
1198
- export function killSession(channel, sessionKey) {
1199
- const session = sessions.get(sessionKey || channel);
1200
- return session ? session.kill() : false;
1201
- }
1202
- /** Close all sessions whose key starts with the given prefix (used by Thread cleanup). */
1203
- export function closeSessionsByPrefix(prefix) {
1204
- for (const [key, session] of sessions) {
1205
- if (key.startsWith(prefix))
1206
- session.close();
1207
- }
1208
- }
1209
- export function closeAllSessions() {
1210
- for (const [, session] of sessions)
1211
- session.close();
1212
- sessions.clear();
1213
- }
1214
497
  /**
1215
498
  * Decide whether a print-mode ClaudeSession should spawn with `--resume <id>`.
1216
499
  *
@@ -1221,127 +504,22 @@ export function closeAllSessions() {
1221
504
  * "No conversation found with session ID: <id>". Gating the resume request on the
1222
505
  * transcript actually existing keeps the first turn on `--session-id` (create) and lets
1223
506
  * only later turns / reconnects use `--resume`. Self-healing: a deleted transcript also
1224
- * correctly falls back to create. Mirrors {@link resolveTuiResume} for the tmux path.
507
+ * correctly falls back to create. The decision itself lives in
508
+ * {@link resolveResumeAgainstTranscript} so any print-mode caller shares one rule.
1225
509
  */
1226
510
  export function resolveResumeForPrint(requestedResume, sessionId, exists, cwd = AGENT_CWD) {
1227
- return resolveTuiResume(requestedResume, computeJsonlPath(cwd, sessionId), exists);
1228
- }
1229
- export function runClaude(userMessage, opts) {
1230
- const effectiveSessionId = opts.sessionId || crypto.randomUUID();
1231
- const needsResume = resolveResumeForPrint(!!opts.sessionId, effectiveSessionId);
1232
- const session = getOrCreateSession(opts.channel, effectiveSessionId, { ...opts, needsResume });
1233
- const promise = session.sendMessage(userMessage, {
1234
- files: opts.files || [],
1235
- callbackSource: opts.callbackSource ?? null,
1236
- scheduleTaskId: opts.scheduleTaskId ?? null,
1237
- isUserInitiated: opts.isUserInitiated ?? false,
1238
- onProgress: opts.onProgress ?? null,
1239
- onAssistantMessage: opts.onAssistantMessage ?? null,
1240
- onToolUse: opts.onToolUse ?? null,
1241
- onToolResult: opts.onToolResult ?? null,
1242
- });
1243
- return { promise, kill() { return session.kill(); }, sessionId: effectiveSessionId };
1244
- }
1245
- // --- DR-0012: TUI-mode session pool + dispatch helpers ---
1246
- /** Module-scoped TUI session pool, keyed by sessionKey (parallel to `sessions` for print mode). */
1247
- const tuiSessions = new Map();
1248
- /** Shared TmuxControl singleton — stateless, safe to reuse across all TUI sessions. */
1249
- const sharedTmux = new TmuxControl();
1250
- /** Pure dispatch: select claude adapter mode from an AgentSpawnConfig.
1251
- * Defaults to 'print' for missing or unrecognized values (conservative — never silently
1252
- * flips a session into the experimental TUI path). */
1253
- export function selectClaudeMode(config) {
1254
- return config.claudeBackend === 'tui' ? 'tui' : 'print';
511
+ return resolveResumeAgainstTranscript(requestedResume, computeTranscriptPath(cwd, sessionId), exists);
1255
512
  }
1256
- function matchesTuiSession(session, sessionId, options, composition) {
1257
- return session.sessionId === sessionId
1258
- && session.cwd === options.cwd
1259
- && session.routeIdentity === claudeRouteIdentity(options)
1260
- && session.mcpComposition === composition
1261
- && session.pluginCapabilityFingerprint === (options.pluginCapabilityFingerprint ?? null)
1262
- && session.supplementalMcpConfigIdentity === (options.supplementalMcpConfigIdentity ?? null)
1263
- // TUI processes are pooled and long-lived; without this term, turning the browser on or off
1264
- // would silently do nothing until the existing pane happened to die.
1265
- && session.browserMcpConfigIdentity === (options.browserMcpConfigIdentity ?? null)
1266
- && session.tools === (options.tools ?? null)
1267
- && sameTextArray(session.pluginDirs, cloneTextArray(options.pluginDirs))
1268
- && sameTextArray(session.mcpConfigPaths, cloneTextArray(options.mcpConfigPaths))
1269
- && session.commissionTools === (options.commissionTools === true)
1270
- && sameOptionalTextArray(session.mcpToolAllowlist, optionalTextArray(options.mcpToolAllowlist));
1271
- }
1272
- function tuiPromptFields(options) {
1273
- return {
1274
- tools: options.tools,
1275
- systemPrompt: options.systemPrompt,
1276
- appendSystemPrompt: options.appendSystemPrompt,
1277
- model: options.model,
1278
- claudeAgent: options.claudeAgent,
1279
- pluginDirs: options.pluginDirs,
1280
- outputStyle: options.outputStyle,
1281
- extraOption: options.extraOption ?? null,
1282
- thinking: options.thinking ?? null,
1283
- };
1284
- }
1285
- function tuiSessionConfig(config, sessionId, options, composition) {
1286
- const cwd = resolveSpawnCwd(options.cwd);
1287
- return {
1288
- channel: config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey,
1289
- sessionId, sessionKey: config.sessionKey, cwd,
1290
- needsResume: resolveTuiResume(config.resume, computeJsonlPath(cwd, sessionId)),
1291
- ...tuiPromptFields(options),
1292
- mcpComposition: composition,
1293
- mcpConfigPaths: options.mcpConfigPaths ?? null,
1294
- mcpToolAllowlist: options.mcpToolAllowlist ?? null,
1295
- commissionTools: options.commissionTools === true,
1296
- supplementalMcpConfigPath: options.supplementalMcpConfigPath ?? null,
1297
- disableHooks: options.disableHooks,
1298
- pluginCapabilityFingerprint: options.pluginCapabilityFingerprint ?? null,
1299
- supplementalMcpConfigIdentity: options.supplementalMcpConfigIdentity ?? null,
1300
- browserMcpConfigPath: options.browserMcpConfigPath ?? null,
1301
- browserMcpConfigIdentity: options.browserMcpConfigIdentity ?? null,
1302
- callbackSource: options.callbackSource,
1303
- scheduleTaskId: options.scheduleTaskId,
1304
- anthropicBaseUrl: options.anthropicBaseUrl,
1305
- extraEnv: options.extraEnv,
1306
- unsetEnv: options.unsetEnv,
1307
- context: options.context,
1308
- deps: { tmux: sharedTmux, tailFactory: defaultTailFactory },
1309
- };
1310
- }
1311
- function createTuiSession(config, sessionId, options, composition) {
1312
- const session = new ClaudeTuiSession(tuiSessionConfig(config, sessionId, options, composition));
1313
- tuiSessions.set(config.sessionKey, session);
1314
- return session;
1315
- }
1316
- function tuiComposition(options) {
1317
- return options.mcpComposition ?? 'direct';
1318
- }
1319
- function getOrCreateTuiSession(config, sessionIdEffective) {
1320
- const options = sessionOptionsFromSpawnConfig({ ...config, sessionId: sessionIdEffective });
1321
- const composition = tuiComposition(options);
1322
- let session = tuiSessions.get(config.sessionKey);
1323
- if (session && !matchesTuiSession(session, sessionIdEffective, options, composition)) {
1324
- session.kill();
1325
- session = undefined;
1326
- }
1327
- if (session)
1328
- return session;
1329
- return createTuiSession(config, sessionIdEffective, options, composition);
1330
- }
1331
- // --- ClaudeAdapter — DR-0008 §3.2 generic AgentAdapter entry point ---
513
+ // --- EngineSpec → ClaudeSession options ---
1332
514
  //
1333
- // task f7cf scope:
1334
- // - spawn() returns a real AgentProcess that drives one turn through the pooled ClaudeSession
1335
- // via event-emitting callbacks (onAssistantMessage / onToolUse), then derives
1336
- // ask_user_question / plan_written / rate_limit events from the resolved AgentResult
1337
- // before pushing turn_complete and returning the AgentResult from send().
1338
- // - AgentSpawnConfig.hooks (NormalizedHookSpec[]) is still NOT consumed; buildHooksSettings
1339
- // uses the native tools string per DR-0008 §3.5 (Phase 3 work).
1340
- // - AgentSpawnConfig.mcpServers is projected into a private supplemental --mcp-config file;
515
+ // The helpers below translate one EngineSpec into the fields a ClaudeSession needs:
516
+ // - EngineSpec.mcp.servers is projected into a private supplemental --mcp-config file;
1341
517
  // the base agent-server/mcp-config.json remains first in the composition.
1342
- // - Claude-specific passthrough fields (channel / claudeAgent / callbackSource / scheduleTaskId /
1343
- // isUserInitiated / rawTools / anthropicBaseUrl) are read directly from AgentSpawnConfig;
1344
- // they're Phase-3 cleanup targets (see types.ts).
518
+ // - EngineSpec carries no hook list; the `--settings` hooks are compiled from the resolved
519
+ // native tools string in spawn-args.ts (buildHooksSettings).
520
+ // - Claude-private fields (context.channel / backend.claudeAgent / context.callbackSource /
521
+ // context.scheduleTaskId / flags.isUserInitiated / tools.rawClaude / route.anthropicBaseUrl)
522
+ // are read directly off EngineSpec rather than modelled as backend-neutral fields.
1345
523
  function canonicalToolsToNative(tools) {
1346
524
  if (!tools || tools.length === 0)
1347
525
  return null;
@@ -1350,76 +528,77 @@ function canonicalToolsToNative(tools) {
1350
528
  .filter((n) => typeof n === 'string');
1351
529
  return native.length ? native.join(',') : null;
1352
530
  }
1353
- function supplementalMcpConfig(config, composition) {
1354
- if (!config.mcpServers)
531
+ function supplementalMcpConfig(spec, composition) {
532
+ if (!spec.mcp.servers)
1355
533
  return null;
1356
534
  if (composition !== 'direct' && composition !== 'thread-control')
1357
535
  return null;
1358
- return writeClaudeSupplementalMcpConfig(config.mcpServers);
536
+ return writeClaudeSupplementalMcpConfig(spec.mcp.servers);
1359
537
  }
1360
- function sessionPresentationOptions(config) {
538
+ function sessionPresentationOptions(spec) {
539
+ const claudeBackend = spec.backend.kind === 'claude' ? spec.backend : undefined;
1361
540
  return {
1362
- model: config.model ?? null,
1363
- systemPrompt: config.systemPrompt ?? null,
1364
- appendSystemPrompt: config.appendSystemPrompt ?? null,
1365
- outputStyle: config.outputStyle ?? null,
1366
- tools: config.rawTools ?? canonicalToolsToNative(config.tools),
1367
- pluginDirs: config.pluginDirs ?? null,
1368
- isUserInitiated: !!config.isUserInitiated,
1369
- callbackSource: config.callbackSource ?? null,
1370
- scheduleTaskId: config.scheduleTaskId ?? null,
1371
- claudeAgent: config.claudeAgent ?? null,
1372
- thinking: config.thinking ?? null,
541
+ model: spec.model.id ?? null,
542
+ systemPrompt: spec.prompt.system ?? null,
543
+ appendSystemPrompt: spec.prompt.append ?? null,
544
+ outputStyle: claudeBackend?.outputStyle ?? null,
545
+ tools: spec.tools.rawClaude ?? canonicalToolsToNative(spec.tools.canonical),
546
+ pluginDirs: spec.plugins.dirs ?? null,
547
+ isUserInitiated: !!spec.flags.isUserInitiated,
548
+ callbackSource: spec.context.callbackSource ?? null,
549
+ scheduleTaskId: spec.context.scheduleTaskId ?? null,
550
+ claudeAgent: claudeBackend?.claudeAgent ?? null,
551
+ thinking: spec.model.thinking ?? null,
1373
552
  };
1374
553
  }
1375
- function sessionRuntimeOptions(config, composition) {
1376
- const supplemental = supplementalMcpConfig(config, composition);
554
+ function sessionRuntimeOptions(spec, composition) {
555
+ const supplemental = supplementalMcpConfig(spec, composition);
1377
556
  // Only a direct session can carry browser tools — thread/dispatch workers run unattended, where a
1378
557
  // shared browser would be a cross-run side channel rather than a feature.
1379
- const browser = config.browserCdpEndpoint && composition === 'direct'
1380
- ? writeBrowserMcpConfig(config.browserCdpEndpoint)
558
+ const browser = spec.mcp.browserCdpEndpoint && composition === 'direct'
559
+ ? writeBrowserMcpConfig(spec.mcp.browserCdpEndpoint)
1381
560
  : null;
1382
561
  return {
1383
- anthropicBaseUrl: config.anthropicBaseUrl,
1384
- extraEnv: config.env,
1385
- unsetEnv: config.unsetEnv,
1386
- cwd: resolveSpawnCwd(config.cwd),
562
+ anthropicBaseUrl: spec.route.anthropicBaseUrl,
563
+ extraEnv: spec.env.sets,
564
+ unsetEnv: spec.env.unsets,
565
+ cwd: resolveSpawnCwd(spec.cwd),
1387
566
  mcpComposition: composition,
1388
- mcpConfigPaths: config.mcpConfigPaths,
1389
- mcpToolAllowlist: config.mcpToolAllowlist,
1390
- commissionTools: config.commissionTools === true,
567
+ mcpConfigPaths: spec.mcp.configPaths,
568
+ mcpToolAllowlist: spec.mcp.allowlist,
569
+ commissionTools: spec.mcp.commissionTools === true,
1391
570
  supplementalMcpConfigPath: supplemental?.path ?? null,
1392
571
  supplementalMcpConfigIdentity: supplemental?.identity ?? null,
1393
572
  browserMcpConfigPath: browser?.path ?? null,
1394
573
  browserMcpConfigIdentity: browser?.identity ?? null,
1395
- pluginCapabilityFingerprint: config.pluginCapabilityFingerprint ?? null,
1396
- disableHooks: config.disableHooks,
1397
- streamDeltas: config.streamDeltas,
1398
- captureTranscriptLogs: config.captureTranscriptLogs,
1399
- preserveUnreportedAccounting: config.preserveUnreportedAccounting,
1400
- processSpawner: config.processSpawner,
1401
- cliPath: config.cliPath,
1402
- pinnedEnv: config.pinnedEnv,
1403
- extraOption: config.extraOption,
1404
- context: config.cortexContext,
574
+ pluginCapabilityFingerprint: spec.plugins.fingerprint ?? null,
575
+ disableHooks: spec.flags.disableHooks,
576
+ streamDeltas: spec.flags.streamDeltas,
577
+ captureTranscriptLogs: spec.flags.captureTranscripts,
578
+ preserveUnreportedAccounting: spec.flags.preserveUnreportedAccounting,
579
+ processSpawner: spec.process.spawner,
580
+ cliPath: spec.process.cliPath,
581
+ pinnedEnv: spec.env.pinned,
582
+ extraOption: spec.extraOption,
583
+ context: spec.env.context,
1405
584
  };
1406
585
  }
1407
- function sessionOptionsFromSpawnConfig(config) {
1408
- const composition = resolveMcpComposition(config.mcpComposition, config.cortexContext?.useCoreMcp);
586
+ function sessionOptionsFromSpec(spec) {
587
+ const composition = resolveMcpComposition(spec.mcp.composition, spec.env.context?.useCoreMcp);
1409
588
  return {
1410
- sessionIdEffective: config.sessionId || crypto.randomUUID(),
1411
- needsResume: config.resume,
1412
- sessionKey: config.sessionKey,
1413
- ...sessionPresentationOptions(config),
1414
- ...sessionRuntimeOptions(config, composition),
589
+ sessionIdEffective: spec.resume.backendSessionId || crypto.randomUUID(),
590
+ needsResume: spec.resume.resume,
591
+ sessionKey: spec.engineKey,
592
+ ...sessionPresentationOptions(spec),
593
+ ...sessionRuntimeOptions(spec, composition),
1415
594
  };
1416
595
  }
1417
- /** Test hook: mirror of ClaudeSession.toSpawnOptions() for the AgentSpawnConfig entry point.
596
+ /** Test hook: mirror of ClaudeSession.toSpawnOptions() for the EngineSpec entry point.
1418
597
  * Must stay in sync with ClaudeSession constructor + toSpawnOptions — both paths derive
1419
598
  * ClaudeSpawnOptions through deriveClaudeSpawnOptions(), so any field added to that helper
1420
599
  * is covered here without divergence. */
1421
- function computeSpawnArgsForConfig(config) {
1422
- const opts = sessionOptionsFromSpawnConfig(config);
600
+ function computeSpawnArgsForSpec(spec) {
601
+ const opts = sessionOptionsFromSpec(spec);
1423
602
  const spawnOptions = deriveClaudeSpawnOptions({
1424
603
  tools: opts.tools ?? null,
1425
604
  systemPrompt: opts.systemPrompt ?? null,
@@ -1440,241 +619,82 @@ function computeSpawnArgsForConfig(config) {
1440
619
  disableHooks: opts.disableHooks,
1441
620
  streamDeltas: opts.streamDeltas,
1442
621
  });
1443
- spawnOptions.isUserInitiated = config.isUserInitiated;
1444
- spawnOptions.commissionTools = config.commissionTools === true;
622
+ spawnOptions.isUserInitiated = spec.flags.isUserInitiated;
623
+ spawnOptions.commissionTools = spec.mcp.commissionTools === true;
1445
624
  return buildSpawnArgs(spawnOptions);
1446
625
  }
626
+ /** D9: `claudeBackend: 'tui'` is accepted but deprecated; warn once per process, then run print. */
627
+ let warnedTuiDeprecated = false;
1447
628
  export class ClaudeAdapter {
1448
629
  backend = 'claude';
1449
630
  capabilities = CAPABILITIES_BY_BACKEND.claude;
1450
- spawn(config) {
1451
- // DR-0012: route to TUI implementation when profile selects it.
1452
- if (selectClaudeMode(config) === 'tui')
1453
- return this.spawnTui(config);
1454
- const { sessionIdEffective, ...sessionOptions } = sessionOptionsFromSpawnConfig(config);
1455
- // Gate resume on the transcript actually existing — a pre-registered sessionId
1456
- // (e.g. cortex tui handshake) must spawn `--session-id` on its first turn, not
1457
- // `--resume` (which fails "No conversation found"). See resolveResumeForPrint.
1458
- sessionOptions.needsResume = resolveResumeForPrint(sessionOptions.needsResume, sessionIdEffective, undefined, sessionOptions.cwd);
1459
- const channel = config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey;
1460
- const session = getOrCreateSession(channel, sessionIdEffective, sessionOptions);
1461
- const stream = createEventStream();
1462
- let started = false;
1463
- return {
1464
- sessionKey: config.sessionKey,
1465
- get sessionId() { return session.sessionId; },
1466
- get supervision() { return session.getSupervision(); },
1467
- async send(message) {
1468
- if (!started) {
1469
- stream.push({ type: 'session_started', sessionId: session.sessionId });
1470
- started = true;
1471
- }
1472
- const files = (message.attachments || []).map((a) => ({
1473
- mimetype: a.mimeType, localPath: a.path, name: path.basename(a.path),
1474
- }));
1475
- try {
1476
- const result = await session.sendMessage(message.text, {
1477
- files,
1478
- onAssistantMessage: (text, blockId, model, subagent) => stream.push({
1479
- type: 'assistant_text', text,
1480
- ...(blockId ? { blockId } : {}),
1481
- ...(model != null ? { model } : {}),
1482
- ...(subagent ? { subagent } : {}),
1483
- }),
1484
- // Token-level preview of the block above. Same FIFO stream, so every delta is delivered
1485
- // before the complete message that supersedes it.
1486
- onAssistantDelta: (text, blockId) => stream.push({ type: 'assistant_delta', text, blockId }),
1487
- onToolUse: (name, input, toolUseId, subagent) => {
1488
- stream.push({ type: 'tool_use', toolUseId, name, input, ...(subagent ? { subagent } : {}) });
1489
- // Derived semantic event alongside the raw call (cf. plan_written /
1490
- // ask_user_question). Subagent lists are deliberately dropped: a subagent keeps
1491
- // its own plan and emitting it would clobber the main agent's on every surface.
1492
- if (subagent)
1493
- return;
1494
- const snapshot = parseTodoWrite('claude', name, input);
1495
- if (snapshot)
1496
- stream.push({ type: 'todo_update', toolUseId, snapshot });
1497
- },
1498
- onToolResult: (toolUseId, content, isError, subagent) => stream.push({
1499
- type: 'tool_result', toolUseId, content, ok: !isError,
1500
- ...(subagent ? { subagent } : {}),
1501
- }),
1502
- onCompact: (info) => stream.push({ type: 'context_compacted', trigger: info.trigger, preTokens: info.preTokens }),
1503
- onModelFallback: (event) => stream.push({ type: 'model_fallback', ...event }),
1504
- onContextUsage: (usage) => stream.push({ type: 'context_usage', ...usage }),
1505
- onProgress: (p) => {
1506
- stream.push({ type: 'turn_progress', numTurns: p?.num_turns ?? 0 });
1507
- },
1508
- onSubagentActivity: (parentToolUseId, subagentType, kind) => stream.push({ type: 'subagent_activity', parentToolUseId, subagentType, kind }),
1509
- onSubagentEnd: (parentToolUseId, status) => stream.push({ type: 'subagent_end', parentToolUseId, status }),
1510
- });
1511
- // Derived events, in order, before the terminating turn_complete.
1512
- for (const q of (result.askUserQuestions || [])) {
1513
- stream.push({
1514
- type: 'ask_user_question',
1515
- toolUseId: q.toolUseId ?? '',
1516
- questions: q.questions,
1517
- });
1518
- }
1519
- if (result.planFilePath) {
1520
- stream.push({
1521
- type: 'plan_written',
1522
- toolUseId: '',
1523
- path: result.planFilePath,
1524
- content: '',
1525
- });
1526
- }
1527
- if (result.rateLimited) {
1528
- stream.push({ type: 'rate_limit', raw: { message: result.rateLimitMessage } });
1529
- }
1530
- // Emit cost_record from the resolved turn, not mutable session accounting.
1531
- const preserveReportedness = config.preserveUnreportedAccounting === true;
1532
- const accounting = result.reportedAccounting;
1533
- const hasReportableAccounting = preserveReportedness
1534
- ? result.costReported === true || accounting?.usageReported === true
1535
- : result.total_cost_usd != null || session.lastTokenUsage !== null;
1536
- if (hasReportableAccounting) {
1537
- const legacyUsage = session.lastTokenUsage;
1538
- const exactPrompt = promptAccounting(legacyUsage);
1539
- stream.push({
1540
- type: 'cost_record', provider: 'anthropic',
1541
- model: (preserveReportedness ? accounting?.model : session.lastModelName)
1542
- || session.modelName || 'unknown',
1543
- tokens_in: preserveReportedness
1544
- ? accounting?.promptTokens ?? null : exactPrompt.promptTokens,
1545
- tokens_out: preserveReportedness
1546
- ? accounting?.outputTokens ?? null : legacyUsage?.output ?? 0,
1547
- prompt_tokens: preserveReportedness
1548
- ? accounting?.promptTokens ?? null : exactPrompt.promptTokens,
1549
- cached_tokens: preserveReportedness
1550
- ? accounting?.cachedTokens ?? null : exactPrompt.cachedTokens,
1551
- input_tokens: accounting?.inputTokens ?? null,
1552
- output_tokens: accounting?.outputTokens ?? null,
1553
- cache_read_tokens: accounting?.cacheReadTokens ?? null,
1554
- cache_creation_tokens: accounting?.cacheCreationTokens ?? null,
1555
- provider_requests: Number.isSafeInteger(result.num_turns)
1556
- && Number(result.num_turns) > 0 ? result.num_turns : null,
1557
- cost_usd: preserveReportedness && result.costReported !== true
1558
- ? null : result.total_cost_usd ?? null,
1559
- });
1560
- }
1561
- stream.push({
1562
- type: 'turn_complete',
1563
- numTurns: preserveReportedness ? result.num_turns : result.num_turns ?? 0,
1564
- totalCostUsd: result.total_cost_usd ?? null,
1565
- });
1566
- stream.close();
1567
- return result;
1568
- }
1569
- catch (err) {
1570
- if (!err?.cancelled) {
1571
- stream.push({ type: 'error', message: String(err?.message ?? err), fatal: true });
1572
- }
1573
- stream.close(); // unblock any for-await consumer
1574
- throw err;
1575
- }
1576
- },
1577
- events: stream.iterable,
1578
- compact: () => session.compact(),
1579
- setContinuationSink(sink) { session.setContinuationSink(sink); },
1580
- injectUserMessage(message) { return session.injectUserMessage(message); },
1581
- setInjectionAckSink(sink) { session.setInjectionAckSink(sink); },
1582
- // Intentionally does NOT call session.close(): sessions are pooled per sessionKey and
1583
- // reused across runAgentOnce turns. Pool-level cleanup goes through ClaudeAdapter.close(key)
1584
- // or the legacy closeSession / closeSessionsByPrefix exports.
1585
- async close() { stream.close(); },
1586
- kill() { return session.kill(); },
1587
- };
631
+ onRateLimit;
632
+ constructor(hooks = {}) {
633
+ this.onRateLimit = hooks.onRateLimit;
1588
634
  }
1589
635
  /**
1590
- * DR-0012 TUI-mode dispatch. Returns an AgentProcess whose send() pushes ALL NormalizedEvents
1591
- * (including derived ones — ask_user_question, plan_*, cost_record, turn_complete) via
1592
- * ClaudeTuiSession's onEvent stream, then resolves with the TuiAgentResult cast to AgentResult.
636
+ * Pure construction (plan §3.3): resolve the spec exactly as the old `spawn()` did, build a
637
+ * fresh `ClaudeSession` and wrap it in an engine. No pool read, no pool write, no
638
+ * `getOrCreate*`. The owner (`SessionEngines`) supplies the eviction hooks.
1593
639
  *
1594
- * Sessions are pooled in `tuiSessions` by sessionKey; multi-turn reuses the same tmux session.
1595
- * kill() forwards to ClaudeTuiSession.kill() which tears down the tmux session.
640
+ * "Pure" is about the POOL, not about side effects: `new ClaudeSession(...)` spawns the CLI
641
+ * child in its constructor, as it always has. Every `open()` therefore costs a process — call it
642
+ * only when you have decided to create, the way `acquire` does.
1596
643
  */
1597
- spawnTui(config) {
1598
- const sessionIdEffective = config.sessionId || crypto.randomUUID();
1599
- const session = getOrCreateTuiSession(config, sessionIdEffective);
1600
- const stream = createEventStream();
1601
- let started = false;
1602
- return {
1603
- sessionKey: config.sessionKey,
1604
- get sessionId() { return session.sessionId; },
1605
- async send(message) {
1606
- if (!started) {
1607
- stream.push({ type: 'session_started', sessionId: session.sessionId });
1608
- started = true;
1609
- }
1610
- const files = (message.attachments || []).map((a) => ({
1611
- mimetype: a.mimeType, localPath: a.path, name: path.basename(a.path),
1612
- }));
1613
- try {
1614
- const tuiResult = await session.sendMessage(message.text, {
1615
- files,
1616
- onEvent: (ev) => stream.push(ev),
1617
- });
1618
- stream.close();
1619
- // TuiAgentResult shape lines up with AgentResult — only structural cast needed.
1620
- return tuiResult;
1621
- }
1622
- catch (err) {
1623
- if (!err?.cancelled) {
1624
- stream.push({ type: 'error', message: String(err?.message ?? err), fatal: true });
1625
- }
1626
- stream.close();
1627
- throw err;
1628
- }
1629
- },
1630
- events: stream.iterable,
1631
- setContinuationSink(sink) { session.setContinuationSink(sink); },
1632
- async close() { stream.close(); },
1633
- kill() { return session.kill(); },
1634
- };
644
+ open(spec, hooks = {}) {
645
+ // D9: TUI is deprecated — one warning, then continue down the print path (never a throw).
646
+ if (spec.backend.kind === 'claude' && spec.backend.claudeBackend === 'tui' && !warnedTuiDeprecated) {
647
+ warnedTuiDeprecated = true;
648
+ log.warn('claudeBackend "tui" is deprecated (D9); running this session in print mode');
649
+ }
650
+ const { sessionIdEffective, ...sessionOptions } = sessionOptionsFromSpec(spec);
651
+ // Same resume gate as the old spawn(): a pre-registered sessionId with no transcript yet must create.
652
+ sessionOptions.needsResume = resolveResumeForPrint(sessionOptions.needsResume, sessionIdEffective, undefined, sessionOptions.cwd);
653
+ const channel = spec.context.channel ?? spec.env.sets?.SLACK_CHANNEL ?? spec.engineKey;
654
+ // The old pooled lookup keyed the session on `options.sessionKey || channel`; preserve that.
655
+ const key = sessionOptions.sessionKey || channel;
656
+ const session = new ClaudeSession(channel, sessionIdEffective, {
657
+ ...sessionOptions,
658
+ sessionKey: key,
659
+ onSelfClose: hooks.onSelfClose,
660
+ onEvict: hooks.onEvict,
661
+ onRateLimit: this.onRateLimit,
662
+ });
663
+ return new ClaudeEngineSession(session, spec, claudeSpecIdentity(spec));
1635
664
  }
1636
- async close(sessionKey) {
1637
- closeSession(sessionKey, sessionKey);
1638
- // Also clean up any TUI session under this key (DR-0012).
1639
- const tui = tuiSessions.get(sessionKey);
1640
- if (tui) {
1641
- tui.close();
1642
- tuiSessions.delete(sessionKey);
1643
- }
665
+ /** The comparable identity of the session this spec *would* open — the pool's reuse test. */
666
+ specIdentity(spec) {
667
+ return claudeSpecIdentity(spec);
1644
668
  }
1645
- kill(sessionKey) {
1646
- const session = sessions.get(sessionKey);
1647
- if (session)
1648
- return session.kill();
1649
- const tui = tuiSessions.get(sessionKey);
1650
- if (tui) {
1651
- const killed = tui.kill();
1652
- tuiSessions.delete(sessionKey);
1653
- return killed;
1654
- }
1655
- return false;
1656
- }
1657
- listSessions() {
1658
- return [...sessions.keys(), ...tuiSessions.keys()];
669
+ /** The resume decision `open()` will make for a spec, plus the transcript id it would target.
670
+ * The pool's fourth reuse clause compares this against a live session's `sessionId`: asked to
671
+ * resume transcript X while the pooled session sits on transcript Y ⇒ a fresh process. */
672
+ claudeResumeTarget(spec) {
673
+ const { sessionIdEffective, ...sessionOptions } = sessionOptionsFromSpec(spec);
674
+ return {
675
+ needsResume: resolveResumeForPrint(sessionOptions.needsResume, sessionIdEffective, undefined, sessionOptions.cwd),
676
+ sessionId: sessionIdEffective,
677
+ };
1659
678
  }
1660
679
  }
1661
680
  /**
1662
- * DR-0012 §3.6 startup hook — sweep orphan tmux sessions matching the cortex-claude- prefix.
681
+ * Startup hook — sweep orphan tmux sessions matching the `cortex-claude-` prefix.
1663
682
  *
1664
- * Rationale: tmux sessions are independent of agent-server's process lifetime, but the in-memory
1665
- * `tuiSessions` Map is not. After an agent-server restart we have no record of channel/sessionKey
1666
- * → tmux mapping (it was never persisted), so we cannot re-adopt existing tmux sessions into the
1667
- * pool. The honest choice is to kill them at startup; otherwise they accumulate forever and a
1668
- * later session reusing the same sessionId would conflict with `tmux new-session -s <name>`
1669
- * (which fails on duplicate). Logs the killed names so operators can investigate if needed.
683
+ * This is a one-way MIGRATION SWEEP, not support for a live TUI mode: D9 retired
684
+ * `claudeBackend: 'tui'` and no new TUI tmux session can be created. It exists because tmux
685
+ * sessions outlive agent-server's process, so machines upgrading across the D9 boundary still
686
+ * hold `cortex-claude-<sessionId>` sessions from older builds. The in-memory bookkeeping that
687
+ * could re-adopt them (the TUI session map) is gone, so the honest move is to
688
+ * kill the leftovers at startup — otherwise they accumulate forever and a later session reusing
689
+ * the same sessionId would collide with `tmux new-session -s <name>` (which fails on duplicates).
1670
690
  *
1671
- * Full re-adoption (preserving an in-flight TUI session across restart) requires persisting
1672
- * sessionKey + cwd + needsResume metadata to disk — deferred as a follow-up.
691
+ * Deletable once the deprecation window closes and no pre-D9 build can still be upgraded from.
692
+ * Logs the killed names so operators can investigate if needed.
1673
693
  *
1674
694
  * Override `exec` in tests so we don't touch the real tmux server.
1675
695
  */
1676
696
  export function recoverTuiOrphans(exec) {
1677
- const tmux = exec ? new TmuxControl(exec) : sharedTmux;
697
+ const tmux = exec ? new TmuxControl(exec) : new TmuxControl();
1678
698
  const found = tmux.listSessions(TUI_TMUX_NAME_PREFIX);
1679
699
  if (found.length === 0)
1680
700
  return { found: [], killed: [] };
@@ -1697,24 +717,27 @@ export function recoverTuiOrphans(exec) {
1697
717
  * register cleanup via t.after(() => session.close()) to clear the idle timer. */
1698
718
  function makeSessionForTest(modelName = null, autoCompactWindow = null) {
1699
719
  const s = Object.create(ClaudeSession.prototype);
720
+ const turns = Object.create(ClaudeTurnMachine.prototype);
721
+ turns.host = s;
722
+ s.turns = turns;
1700
723
  s.sessionId = 'test-session';
1701
724
  s.channel = 'test';
1702
725
  s.sessionKey = 'test';
1703
- s.bgTracker = new BgTaskTracker();
1704
- s.streamDeltaState = createStreamDeltaState();
1705
- s.contextUsageTracker = new ClaudeContextUsageTracker(modelName, autoCompactWindow);
1706
- s.continuationSink = null;
1707
- s.pendingContinuationDeliveries = [];
1708
- s.pendingInjections = [];
1709
- s.injectionAck = null;
1710
- s.injectionContinuationArmed = false;
1711
- s.currentTurn = null;
726
+ turns.bgTracker = new BgTaskTracker();
727
+ turns.streamDeltaState = createStreamDeltaState();
728
+ turns.contextUsageTracker = new ClaudeContextUsageTracker(modelName, autoCompactWindow);
729
+ turns.backgroundTurnSink = null;
730
+ turns.pendingContinuationDeliveries = [];
731
+ turns.pendingInjections = [];
732
+ turns.injectionAck = null;
733
+ turns.injectionContinuationArmed = false;
734
+ turns.currentTurn = null;
1712
735
  s.idleTimer = null;
1713
736
  s.turnIdleTimer = null;
1714
- s.cumulativeCostUsd = 0;
737
+ turns.cumulativeCostUsd = 0;
1715
738
  s.preserveUnreportedAccounting = false;
1716
- s.lastTokenUsage = null;
1717
- s.lastModelName = null;
739
+ turns.lastTokenUsage = null;
740
+ turns.lastModelName = null;
1718
741
  s.alive = true;
1719
742
  s.proc = null;
1720
743
  return s;
@@ -1722,10 +745,8 @@ function makeSessionForTest(modelName = null, autoCompactWindow = null) {
1722
745
  export const _test = {
1723
746
  extractAskUserQuestions,
1724
747
  mergeSubstantialOutput,
1725
- computeSpawnArgs: computeSpawnArgsForConfig,
748
+ computeSpawnArgs: computeSpawnArgsForSpec,
1726
749
  makeSessionForTest,
1727
- getPooledPrintSession: (sessionKey) => sessions.get(sessionKey),
1728
- getPooledTuiSession: (sessionKey) => tuiSessions.get(sessionKey),
1729
750
  };
1730
751
  // Re-exported for webhook consumer (parity with pre-refactor claude-bridge.ts:286 export)
1731
752
  export { getCurrentPlanFilePath };