@cortex-agent/server 2026.10.15 → 2026.10.25

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 (469) hide show
  1. package/README.md +81 -51
  2. package/defaults/board/board.css +140 -62
  3. package/defaults/board/scaffold.html +36 -13
  4. package/defaults/config/environments/creative.json +0 -1
  5. package/defaults/config/environments/main.json +1 -2
  6. package/defaults/context/projects/AGENTS.md +1 -1
  7. package/defaults/gitignore +3 -3
  8. package/defaults/hooks/new-session-hook.mjs +1 -1
  9. package/defaults/hooks/status-md-guard.mjs +6 -6
  10. package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
  11. package/defaults/plugins/cortex-system/plugin.json +2 -2
  12. package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
  13. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +16 -9
  14. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +2 -2
  15. package/defaults/rules/agents-md.md +1 -1
  16. package/defaults/rules/issues-md.md +1 -1
  17. package/defaults/rules/meta-conventions.md +3 -3
  18. package/defaults/rules/mission-md.md +1 -1
  19. package/defaults/rules/status-md.md +1 -1
  20. package/dist/agent-adapter/claude/adapter.d.ts +2 -5
  21. package/dist/agent-adapter/claude/adapter.js +6 -5
  22. package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
  23. package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
  24. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +3 -1
  25. package/dist/agent-adapter/claude/bg-task-tracker.js +6 -2
  26. package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
  27. package/dist/agent-adapter/claude/cache-refresh.js +145 -0
  28. package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
  29. package/dist/agent-adapter/claude/cache-touch.js +75 -0
  30. package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
  31. package/dist/agent-adapter/claude/event-parser.js +33 -17
  32. package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
  33. package/dist/agent-adapter/claude/event-translator.js +2 -0
  34. package/dist/agent-adapter/claude/mcp-config.js +11 -0
  35. package/dist/agent-adapter/claude/session-options.d.ts +6 -13
  36. package/dist/agent-adapter/claude/session-options.js +2 -13
  37. package/dist/agent-adapter/claude/spawn-args.d.ts +4 -21
  38. package/dist/agent-adapter/claude/spawn-args.js +17 -24
  39. package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
  40. package/dist/agent-adapter/claude/transcript-clear.js +217 -0
  41. package/dist/agent-adapter/claude/turn-machine.d.ts +5 -3
  42. package/dist/agent-adapter/claude/turn-machine.js +29 -73
  43. package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
  44. package/dist/agent-adapter/claude/window-warmup.js +38 -0
  45. package/dist/agent-adapter/continuation-phase.d.ts +6 -3
  46. package/dist/agent-adapter/continuation-phase.js +11 -3
  47. package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
  48. package/dist/agent-adapter/pi/adapter.d.ts +0 -1
  49. package/dist/agent-adapter/pi/adapter.js +5 -13
  50. package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
  51. package/dist/agent-adapter/pi/event-parser.js +43 -27
  52. package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
  53. package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
  54. package/dist/agent-adapter/pi/pi-session.js +15 -0
  55. package/dist/agent-adapter/pi/providers-config.d.ts +2 -2
  56. package/dist/agent-adapter/pi/providers-config.js +1 -1
  57. package/dist/agent-adapter/pi/quota-sink.d.ts +3 -3
  58. package/dist/agent-adapter/pi/quota-sink.js +3 -3
  59. package/dist/agent-adapter/pi/runtime.js +6 -1
  60. package/dist/agent-adapter/pi/session-options.d.ts +9 -13
  61. package/dist/agent-adapter/pi/session-options.js +12 -25
  62. package/dist/agent-adapter/run-events.d.ts +15 -10
  63. package/dist/agent-adapter/run-events.js +2 -0
  64. package/dist/agent-adapter/types.d.ts +14 -6
  65. package/dist/build-info.json +1 -0
  66. package/dist/client-bundle/client.mjs +10 -5
  67. package/dist/client-bundle/manifest.json +3 -3
  68. package/dist/core/claude-credentials.d.ts +6 -0
  69. package/dist/core/claude-credentials.js +11 -0
  70. package/dist/core/codex-quota.d.ts +1 -1
  71. package/dist/core/codex-quota.js +1 -1
  72. package/dist/core/gateway-generator.d.ts +26 -11
  73. package/dist/core/gateway-generator.js +73 -62
  74. package/dist/core/hook-bus.d.ts +1 -1
  75. package/dist/core/hook-bus.js +1 -8
  76. package/dist/core/locales/en.d.ts +52 -77
  77. package/dist/core/locales/slices/commands.d.ts +26 -31
  78. package/dist/core/locales/slices/commands.js +54 -64
  79. package/dist/core/locales/slices/init.d.ts +9 -19
  80. package/dist/core/locales/slices/init.js +19 -53
  81. package/dist/core/locales/slices/interactions.d.ts +3 -3
  82. package/dist/core/locales/slices/interactions.js +6 -6
  83. package/dist/core/locales/slices/notices.d.ts +1 -3
  84. package/dist/core/locales/slices/notices.js +2 -6
  85. package/dist/core/locales/slices/scheduling.d.ts +9 -9
  86. package/dist/core/locales/slices/scheduling.js +18 -18
  87. package/dist/core/locales/slices/status.d.ts +0 -4
  88. package/dist/core/locales/slices/status.js +0 -8
  89. package/dist/core/locales/slices/tui.d.ts +0 -1
  90. package/dist/core/locales/slices/tui.js +0 -2
  91. package/dist/core/locales/slices/uimsg.d.ts +4 -7
  92. package/dist/core/locales/slices/uimsg.js +9 -15
  93. package/dist/core/log.d.ts +3 -0
  94. package/dist/core/log.js +18 -1
  95. package/dist/core/models-generator.d.ts +29 -0
  96. package/dist/core/models-generator.js +82 -0
  97. package/dist/core/paths.d.ts +1 -1
  98. package/dist/core/paths.js +1 -1
  99. package/dist/core/settings-spec.d.ts +30 -0
  100. package/dist/core/settings-spec.js +38 -0
  101. package/dist/core/status-format.d.ts +3 -2
  102. package/dist/core/status-format.js +2 -2
  103. package/dist/core/types/agent-types.d.ts +3 -1
  104. package/dist/core/types/environment-types.d.ts +1 -8
  105. package/dist/domain/agents/agent-state.d.ts +11 -56
  106. package/dist/domain/agents/agent-state.js +48 -115
  107. package/dist/domain/agents/agent-switch.d.ts +2 -24
  108. package/dist/domain/agents/agent-switch.js +9 -72
  109. package/dist/domain/agents/config.d.ts +11 -61
  110. package/dist/domain/agents/config.js +47 -154
  111. package/dist/domain/agents/engine-selection.d.ts +21 -0
  112. package/dist/domain/agents/engine-selection.js +37 -0
  113. package/dist/domain/agents/environments/registry.js +4 -2
  114. package/dist/domain/agents/environments/resolve.js +0 -1
  115. package/dist/domain/agents/environments/schema.d.ts +3 -3
  116. package/dist/domain/agents/environments/schema.js +4 -4
  117. package/dist/domain/agents/index.d.ts +2 -1
  118. package/dist/domain/agents/index.js +3 -7
  119. package/dist/domain/agents/model-selection.d.ts +18 -70
  120. package/dist/domain/agents/model-selection.js +100 -150
  121. package/dist/domain/agents/models.d.ts +12 -0
  122. package/dist/domain/agents/models.js +94 -0
  123. package/dist/domain/agents/subagent/registry.d.ts +2 -0
  124. package/dist/domain/agents/subagent/registry.js +8 -0
  125. package/dist/domain/agents/subagent/runner.d.ts +5 -5
  126. package/dist/domain/agents/subagent/runner.js +12 -35
  127. package/dist/domain/auth/auth-status.d.ts +4 -4
  128. package/dist/domain/auth/auth-status.js +17 -28
  129. package/dist/domain/auth/auth-watch.js +48 -18
  130. package/dist/domain/auth/gateway-sync.d.ts +6 -26
  131. package/dist/domain/auth/gateway-sync.js +31 -75
  132. package/dist/domain/benchmark/identity.d.ts +3 -5
  133. package/dist/domain/benchmark/identity.js +0 -1
  134. package/dist/domain/benchmark/production-attempt-identity.d.ts +6 -5
  135. package/dist/domain/benchmark/production-attempt-identity.js +32 -35
  136. package/dist/domain/benchmark/session-evidence.d.ts +2 -1
  137. package/dist/domain/benchmark/session-evidence.js +8 -1
  138. package/dist/domain/browser/broker.d.ts +99 -0
  139. package/dist/domain/browser/broker.js +487 -0
  140. package/dist/domain/costs/claude-account.js +21 -0
  141. package/dist/domain/costs/rate-limit-throttle.js +3 -1
  142. package/dist/domain/costs/reset-account.d.ts +2 -0
  143. package/dist/domain/costs/usage-service.d.ts +1 -1
  144. package/dist/domain/costs/usage-service.js +20 -7
  145. package/dist/domain/mcp/tools/context.d.ts +5 -7
  146. package/dist/domain/mcp/tools/context.js +17 -4
  147. package/dist/domain/mcp/tools/subagent.js +1 -1
  148. package/dist/domain/mcp/tools/ui-file.js +1 -1
  149. package/dist/domain/monitor/event-loop-monitor.d.ts +2 -0
  150. package/dist/domain/monitor/event-loop-monitor.js +5 -1
  151. package/dist/domain/pi-providers/custom-provider-model.d.ts +1 -1
  152. package/dist/domain/pi-providers/custom-provider-model.js +1 -1
  153. package/dist/domain/plugins/authoring.d.ts +8 -1
  154. package/dist/domain/plugins/authoring.js +24 -9
  155. package/dist/domain/plugins/runtime-gc.d.ts +7 -0
  156. package/dist/domain/plugins/runtime-gc.js +52 -19
  157. package/dist/domain/plugins/runtime.js +2 -1
  158. package/dist/domain/remote/client-bootstrap.js +1 -1
  159. package/dist/domain/remote/client-manager.js +6 -1
  160. package/dist/domain/remote/device-browser.js +1 -1
  161. package/dist/domain/remote/device-chrome-commands.js +2 -0
  162. package/dist/domain/remote/device-port.js +2 -2
  163. package/dist/domain/runs/attempt.d.ts +3 -3
  164. package/dist/domain/runs/attempt.js +2 -3
  165. package/dist/domain/runs/builders.d.ts +4 -4
  166. package/dist/domain/runs/builders.js +4 -5
  167. package/dist/domain/runs/compact.d.ts +4 -17
  168. package/dist/domain/runs/compact.js +14 -56
  169. package/dist/domain/runs/config-resolver.d.ts +15 -83
  170. package/dist/domain/runs/config-resolver.js +24 -150
  171. package/dist/domain/runs/engine-spec.d.ts +8 -8
  172. package/dist/domain/runs/engine-spec.js +15 -31
  173. package/dist/domain/runs/events.d.ts +1 -1
  174. package/dist/domain/runs/fallback.d.ts +6 -38
  175. package/dist/domain/runs/fallback.js +10 -72
  176. package/dist/domain/runs/notices.d.ts +1 -11
  177. package/dist/domain/runs/notices.js +3 -30
  178. package/dist/domain/runs/request.d.ts +4 -3
  179. package/dist/domain/runs/retryable-errors.d.ts +0 -13
  180. package/dist/domain/runs/retryable-errors.js +3 -18
  181. package/dist/domain/runs/run.d.ts +12 -42
  182. package/dist/domain/runs/run.js +40 -147
  183. package/dist/domain/runs/service.d.ts +0 -9
  184. package/dist/domain/runs/service.js +33 -14
  185. package/dist/domain/runs/spec-loader.d.ts +1 -1
  186. package/dist/domain/runs/spend.d.ts +1 -1
  187. package/dist/domain/runs/spend.js +1 -1
  188. package/dist/domain/scheduling/builtin-job-controller.d.ts +3 -1
  189. package/dist/domain/scheduling/builtin-job-controller.js +5 -2
  190. package/dist/domain/scheduling/builtin-jobs.js +7 -0
  191. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +3 -2
  192. package/dist/domain/scheduling/jobs/scheduled-task.js +25 -19
  193. package/dist/domain/scheduling/schedule-ops.d.ts +0 -1
  194. package/dist/domain/scheduling/schedule-ops.js +2 -5
  195. package/dist/domain/scheduling/schedule-selection.d.ts +3 -0
  196. package/dist/domain/scheduling/schedule-selection.js +16 -0
  197. package/dist/domain/scheduling/schedule-spec.d.ts +6 -5
  198. package/dist/domain/scheduling/schedule-spec.js +6 -6
  199. package/dist/domain/scheduling/scheduler.d.ts +3 -1
  200. package/dist/domain/scheduling/scheduler.js +36 -26
  201. package/dist/domain/sessions/session-hooks.d.ts +5 -4
  202. package/dist/domain/sessions/session-hooks.js +15 -33
  203. package/dist/domain/sessions/session-lifecycle.d.ts +19 -51
  204. package/dist/domain/sessions/session-lifecycle.js +34 -96
  205. package/dist/domain/system/doctor.d.ts +3 -3
  206. package/dist/domain/system/doctor.js +22 -26
  207. package/dist/domain/system/own-bin-path.d.ts +13 -0
  208. package/dist/domain/system/own-bin-path.js +36 -0
  209. package/dist/domain/system/server-update-check.js +2 -1
  210. package/dist/domain/system/terminal-cli/index.d.ts +58 -0
  211. package/dist/domain/system/terminal-cli/index.js +100 -0
  212. package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
  213. package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
  214. package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
  215. package/dist/domain/system/terminal-cli/registrar.js +1 -0
  216. package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
  217. package/dist/domain/system/terminal-cli/shims.js +108 -0
  218. package/dist/domain/system/terminal-cli/state.d.ts +7 -0
  219. package/dist/domain/system/terminal-cli/state.js +36 -0
  220. package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
  221. package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
  222. package/dist/domain/telemetry/bus-collector.d.ts +3 -0
  223. package/dist/domain/telemetry/bus-collector.js +22 -0
  224. package/dist/domain/telemetry/child-exit.d.ts +11 -0
  225. package/dist/domain/telemetry/child-exit.js +36 -0
  226. package/dist/domain/telemetry/client-kind.d.ts +4 -0
  227. package/dist/domain/telemetry/client-kind.js +7 -0
  228. package/dist/domain/telemetry/crash-limits.d.ts +15 -0
  229. package/dist/domain/telemetry/crash-limits.js +50 -0
  230. package/dist/domain/telemetry/crash.d.ts +25 -0
  231. package/dist/domain/telemetry/crash.js +70 -0
  232. package/dist/domain/telemetry/daily-upload.d.ts +5 -0
  233. package/dist/domain/telemetry/daily-upload.js +20 -0
  234. package/dist/domain/telemetry/daily.d.ts +5 -0
  235. package/dist/domain/telemetry/daily.js +104 -0
  236. package/dist/domain/telemetry/endpoint.d.ts +7 -0
  237. package/dist/domain/telemetry/endpoint.js +40 -0
  238. package/dist/domain/telemetry/envelope.d.ts +6 -0
  239. package/dist/domain/telemetry/envelope.js +35 -0
  240. package/dist/domain/telemetry/error-digest.d.ts +7 -0
  241. package/dist/domain/telemetry/error-digest.js +43 -0
  242. package/dist/domain/telemetry/funnel.d.ts +6 -0
  243. package/dist/domain/telemetry/funnel.js +22 -0
  244. package/dist/domain/telemetry/gate.d.ts +19 -0
  245. package/dist/domain/telemetry/gate.js +67 -0
  246. package/dist/domain/telemetry/heartbeat.d.ts +17 -0
  247. package/dist/domain/telemetry/heartbeat.js +49 -0
  248. package/dist/domain/telemetry/info.d.ts +9 -0
  249. package/dist/domain/telemetry/info.js +12 -0
  250. package/dist/domain/telemetry/init-answer.d.ts +12 -0
  251. package/dist/domain/telemetry/init-answer.js +42 -0
  252. package/dist/domain/telemetry/install-id.d.ts +5 -0
  253. package/dist/domain/telemetry/install-id.js +42 -0
  254. package/dist/domain/telemetry/normalize.d.ts +33 -0
  255. package/dist/domain/telemetry/normalize.js +88 -0
  256. package/dist/domain/telemetry/outbox.d.ts +18 -0
  257. package/dist/domain/telemetry/outbox.js +93 -0
  258. package/dist/domain/telemetry/panic-group.d.ts +4 -0
  259. package/dist/domain/telemetry/panic-group.js +51 -0
  260. package/dist/domain/telemetry/paths.d.ts +7 -0
  261. package/dist/domain/telemetry/paths.js +11 -0
  262. package/dist/domain/telemetry/redact.d.ts +18 -0
  263. package/dist/domain/telemetry/redact.js +109 -0
  264. package/dist/domain/telemetry/rollup-types.d.ts +81 -0
  265. package/dist/domain/telemetry/rollup-types.js +31 -0
  266. package/dist/domain/telemetry/rollup.d.ts +16 -0
  267. package/dist/domain/telemetry/rollup.js +102 -0
  268. package/dist/domain/telemetry/schema.d.ts +931 -0
  269. package/dist/domain/telemetry/schema.js +275 -0
  270. package/dist/domain/telemetry/service.d.ts +34 -0
  271. package/dist/domain/telemetry/service.js +146 -0
  272. package/dist/domain/telemetry/state.d.ts +17 -0
  273. package/dist/domain/telemetry/state.js +29 -0
  274. package/dist/domain/telemetry/turns.d.ts +17 -0
  275. package/dist/domain/telemetry/turns.js +176 -0
  276. package/dist/domain/telemetry/upgrade.d.ts +14 -0
  277. package/dist/domain/telemetry/upgrade.js +87 -0
  278. package/dist/domain/telemetry/uploader.d.ts +21 -0
  279. package/dist/domain/telemetry/uploader.js +82 -0
  280. package/dist/domain/telemetry/usage.d.ts +25 -0
  281. package/dist/domain/telemetry/usage.js +153 -0
  282. package/dist/domain/telemetry/web-report.d.ts +8 -0
  283. package/dist/domain/telemetry/web-report.js +15 -0
  284. package/dist/domain/tui-session/tui-session-service.js +1 -1
  285. package/dist/domain/tui-session/types.d.ts +2 -2
  286. package/dist/domain/ui-service/app-router.d.ts +117 -95
  287. package/dist/domain/ui-service/app-router.js +17 -14
  288. package/dist/domain/ui-service/assistant-snapshots.js +2 -0
  289. package/dist/domain/ui-service/contract.parity.d.ts +19 -0
  290. package/dist/domain/ui-service/contract.parity.js +1 -0
  291. package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
  292. package/dist/domain/ui-service/inline-media-types.js +1 -0
  293. package/dist/domain/ui-service/input-schemas.d.ts +120 -119
  294. package/dist/domain/ui-service/input-schemas.js +47 -85
  295. package/dist/domain/ui-service/mutate/approvals.d.ts +3 -2
  296. package/dist/domain/ui-service/mutate/approvals.js +3 -2
  297. package/dist/domain/ui-service/mutate/auth.d.ts +1 -1
  298. package/dist/domain/ui-service/mutate/auth.js +3 -2
  299. package/dist/domain/ui-service/mutate/config.d.ts +0 -8
  300. package/dist/domain/ui-service/mutate/config.js +0 -22
  301. package/dist/domain/ui-service/mutate/models.d.ts +13 -0
  302. package/dist/domain/ui-service/mutate/models.js +137 -0
  303. package/dist/domain/ui-service/mutate/plugin-packages.js +1 -1
  304. package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
  305. package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
  306. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -2
  307. package/dist/domain/ui-service/mutate/sessions.js +29 -126
  308. package/dist/domain/ui-service/mutate/telemetry.d.ts +5 -0
  309. package/dist/domain/ui-service/mutate/telemetry.js +6 -0
  310. package/dist/domain/ui-service/query/approvals.js +4 -3
  311. package/dist/domain/ui-service/query/config.js +22 -42
  312. package/dist/domain/ui-service/query/machine-probe.d.ts +1 -1
  313. package/dist/domain/ui-service/query/machine-probe.js +3 -2
  314. package/dist/domain/ui-service/query/models.d.ts +3 -0
  315. package/dist/domain/ui-service/query/models.js +49 -32
  316. package/dist/domain/ui-service/query/plugin-source.js +4 -3
  317. package/dist/domain/ui-service/query/schedules.js +1 -1
  318. package/dist/domain/ui-service/query/sessions.js +8 -13
  319. package/dist/domain/ui-service/query/telemetry.d.ts +3 -0
  320. package/dist/domain/ui-service/query/telemetry.js +4 -0
  321. package/dist/domain/ui-service/trpc.d.ts +8 -3
  322. package/dist/domain/ui-service/trpc.js +1 -1
  323. package/dist/domain/ui-service/types.d.ts +71 -179
  324. package/dist/domain/ui-service/ui-service.d.ts +56 -53
  325. package/dist/domain/ui-service/ui-service.js +27 -24
  326. package/dist/entry/app.js +62 -21
  327. package/dist/entry/browser-cli.d.ts +39 -0
  328. package/dist/entry/browser-cli.js +317 -0
  329. package/dist/entry/cli-help.d.ts +1 -0
  330. package/dist/entry/cli-help.js +64 -20
  331. package/dist/entry/cli.js +16 -14
  332. package/dist/entry/daemon.d.ts +1 -1
  333. package/dist/entry/daemon.js +88 -72
  334. package/dist/entry/init-auth.js +1 -1
  335. package/dist/entry/init.d.ts +10 -8
  336. package/dist/entry/init.js +138 -276
  337. package/dist/entry/path-cli.d.ts +4 -0
  338. package/dist/entry/path-cli.js +65 -0
  339. package/dist/entry/schedule-cli.js +13 -6
  340. package/dist/entry/shutdown.d.ts +1 -1
  341. package/dist/entry/shutdown.js +11 -1
  342. package/dist/entry/signal-cli.js +8 -11
  343. package/dist/entry/start-ui-http.js +48 -18
  344. package/dist/entry/telemetry-wiring.d.ts +12 -0
  345. package/dist/entry/telemetry-wiring.js +56 -0
  346. package/dist/entry/ui-cli.d.ts +0 -11
  347. package/dist/entry/ui-cli.js +42 -33
  348. package/dist/entry/ui-service-wiring.js +8 -10
  349. package/dist/events/event-types.d.ts +4 -6
  350. package/dist/orchestration/agent-runner.d.ts +2 -2
  351. package/dist/orchestration/agent-runner.js +10 -9
  352. package/dist/orchestration/benchmark-session-webhook.js +13 -1
  353. package/dist/orchestration/browser-webhook.d.ts +11 -0
  354. package/dist/orchestration/browser-webhook.js +28 -0
  355. package/dist/orchestration/cache-keep-warm.d.ts +77 -0
  356. package/dist/orchestration/cache-keep-warm.js +213 -0
  357. package/dist/orchestration/claude-window-warmup.d.ts +40 -0
  358. package/dist/orchestration/claude-window-warmup.js +126 -0
  359. package/dist/orchestration/conversation-request.d.ts +6 -10
  360. package/dist/orchestration/conversation-request.js +5 -23
  361. package/dist/orchestration/delta-coalescer.d.ts +4 -2
  362. package/dist/orchestration/delta-coalescer.js +5 -5
  363. package/dist/orchestration/edit-retry.js +9 -11
  364. package/dist/orchestration/inline-media-eager.d.ts +13 -0
  365. package/dist/orchestration/inline-media-eager.js +58 -0
  366. package/dist/orchestration/inline-media.d.ts +22 -0
  367. package/dist/orchestration/inline-media.js +151 -0
  368. package/dist/orchestration/interactions/ask-user-resume.js +3 -7
  369. package/dist/orchestration/interactions/interaction-handlers.js +6 -6
  370. package/dist/orchestration/mid-turn-inject.d.ts +2 -1
  371. package/dist/orchestration/mid-turn-inject.js +1 -1
  372. package/dist/orchestration/pending-injection-recovery.d.ts +2 -1
  373. package/dist/orchestration/pending-injection-recovery.js +1 -1
  374. package/dist/orchestration/routing/commands/index.js +4 -4
  375. package/dist/orchestration/routing/commands/mode.d.ts +5 -44
  376. package/dist/orchestration/routing/commands/mode.js +98 -272
  377. package/dist/orchestration/routing/commands/schedule.js +29 -18
  378. package/dist/orchestration/routing/commands/session.js +9 -9
  379. package/dist/orchestration/routing/commands/status.js +1 -1
  380. package/dist/orchestration/routing/commands/usage-format.js +3 -0
  381. package/dist/orchestration/routing/message-router.js +2 -0
  382. package/dist/orchestration/routing/webhook.js +6 -0
  383. package/dist/orchestration/session-compact.d.ts +0 -1
  384. package/dist/orchestration/session-compact.js +5 -7
  385. package/dist/orchestration/session-events.d.ts +2 -1
  386. package/dist/orchestration/session-events.js +1 -0
  387. package/dist/orchestration/status-helpers.d.ts +0 -4
  388. package/dist/orchestration/status-helpers.js +0 -18
  389. package/dist/orchestration/subagent-webhook.js +9 -34
  390. package/dist/orchestration/team-webhook.d.ts +8 -9
  391. package/dist/orchestration/team-webhook.js +16 -42
  392. package/dist/orchestration/transcript-sink.d.ts +12 -0
  393. package/dist/orchestration/transcript-sink.js +38 -2
  394. package/dist/orchestration/turn/terminal.js +7 -7
  395. package/dist/orchestration/turn/turn-prep.d.ts +0 -8
  396. package/dist/orchestration/turn/turn-prep.js +0 -51
  397. package/dist/orchestration/turn/turn-tracking.d.ts +2 -2
  398. package/dist/orchestration/turn/turn-tracking.js +8 -5
  399. package/dist/orchestration/turn/turn.d.ts +0 -2
  400. package/dist/orchestration/turn/turn.js +13 -15
  401. package/dist/orchestration/waitpoint-ingress.js +3 -0
  402. package/dist/platform/adapters/tui/ports.d.ts +1 -1
  403. package/dist/platform/adapters/tui/tui-transcript.js +2 -0
  404. package/dist/platform/browser/agent-browser.d.ts +50 -0
  405. package/dist/platform/browser/agent-browser.js +165 -0
  406. package/dist/platform/browser/managed-browser.d.ts +1 -11
  407. package/dist/platform/browser/managed-browser.js +4 -12
  408. package/dist/platform/ui-http/browser-stream.d.ts +110 -0
  409. package/dist/platform/ui-http/browser-stream.js +447 -0
  410. package/dist/platform/ui-http/ui-auth-routes.d.ts +2 -0
  411. package/dist/platform/ui-http/ui-auth-routes.js +9 -2
  412. package/dist/platform/ui-http/ui-device-routes.d.ts +13 -0
  413. package/dist/platform/ui-http/ui-device-routes.js +81 -0
  414. package/dist/platform/ui-http/ui-devices.d.ts +24 -0
  415. package/dist/platform/ui-http/ui-devices.js +107 -0
  416. package/dist/platform/ui-http/ui-http-server.d.ts +22 -3
  417. package/dist/platform/ui-http/ui-http-server.js +33 -12
  418. package/dist/platform/ui-http/ui-pairing.d.ts +25 -0
  419. package/dist/platform/ui-http/ui-pairing.js +98 -0
  420. package/dist/store/conversation-history-reader.js +8 -0
  421. package/dist/store/conversation-history-repo.d.ts +8 -1
  422. package/dist/store/conversation-history-repo.js +5 -0
  423. package/dist/store/conversation-ledger-repo.d.ts +6 -6
  424. package/dist/store/conversation-ledger-repo.js +4 -4
  425. package/dist/store/gitignore-migration.d.ts +2 -0
  426. package/dist/store/gitignore-migration.js +16 -0
  427. package/dist/store/hook-registry.d.ts +1 -1
  428. package/dist/store/hook-registry.js +11 -6
  429. package/dist/store/models-repo.d.ts +18 -0
  430. package/dist/store/models-repo.js +74 -0
  431. package/dist/store/pending-injection-repo.d.ts +2 -1
  432. package/dist/store/pending-injection-repo.js +3 -1
  433. package/dist/store/retire-profiles-migration.d.ts +28 -0
  434. package/dist/store/retire-profiles-migration.js +335 -0
  435. package/dist/store/schedule-repo.d.ts +2 -1
  436. package/dist/store/session-registry-import.js +3 -2
  437. package/dist/store/session-registry-journal.d.ts +10 -13
  438. package/dist/store/session-registry-journal.js +51 -25
  439. package/dist/store/session-registry-repo.d.ts +4 -4
  440. package/dist/store/session-registry-repo.js +4 -5
  441. package/dist/store/version-migrations.d.ts +7 -3
  442. package/dist/store/version-migrations.js +133 -80
  443. package/dist/tui/components/Dashboard.js +4 -3
  444. package/dist/tui/hooks/useDashboardData.js +1 -1
  445. package/dist/tui/slash-commands.js +2 -2
  446. package/dist/tui/turn-status.js +1 -1
  447. package/package.json +6 -4
  448. package/web/dist/assets/board-math-css-spk7yR6n.js +2 -0
  449. package/web/dist/assets/index-BQ69u-92.css +1 -0
  450. package/web/dist/assets/{index-CndZZ1IQ.js → index-CKNLatCd.js} +1 -1
  451. package/web/dist/assets/index-CkzWfC98.js +525 -0
  452. package/web/dist/index.html +3 -2
  453. package/web/dist/theme.css +6 -0
  454. package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
  455. package/dist/agent-adapter/browser-mcp-server.js +0 -28
  456. package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
  457. package/dist/agent-adapter/claude/browser-mcp.js +0 -10
  458. package/dist/core/profile-generator.d.ts +0 -79
  459. package/dist/core/profile-generator.js +0 -215
  460. package/dist/domain/agents/profile-manager.d.ts +0 -103
  461. package/dist/domain/agents/profile-manager.js +0 -286
  462. package/dist/domain/agents/profile-switch.d.ts +0 -49
  463. package/dist/domain/agents/profile-switch.js +0 -62
  464. package/dist/domain/ui-service/mutate/profiles.d.ts +0 -36
  465. package/dist/domain/ui-service/mutate/profiles.js +0 -151
  466. package/dist/store/profile-repo.d.ts +0 -20
  467. package/dist/store/profile-repo.js +0 -97
  468. package/web/dist/assets/index-B76ueW3q.js +0 -494
  469. package/web/dist/assets/index-C8O0yxg8.css +0 -1
@@ -17,10 +17,6 @@ const MCP_CONFIGS = {
17
17
  direct: [MCP_CONFIG],
18
18
  none: [EMPTY_MCP_CONFIG],
19
19
  };
20
- function appendBrowserMcpConfig(configs, options, isDirect) {
21
- if (options.browserMcpConfigPath && isDirect)
22
- configs.push(options.browserMcpConfigPath);
23
- }
24
20
  function resolveMcpConfigs(options, composition) {
25
21
  const configs = options.mcpConfigPaths
26
22
  ? [...options.mcpConfigPaths]
@@ -28,7 +24,6 @@ function resolveMcpConfigs(options, composition) {
28
24
  if (options.supplementalMcpConfigPath && composition === 'direct') {
29
25
  configs.push(options.supplementalMcpConfigPath);
30
26
  }
31
- appendBrowserMcpConfig(configs, options, composition === 'direct');
32
27
  const bundles = resolveClaudeMcpBundles(options);
33
28
  // Only an explicitly declared allowlist materializes a gated config (subagents). A direct session
34
29
  // declares none and therefore registers its bundles whole — deliberate since DR-0037 v4: no tool
@@ -48,6 +43,8 @@ function printModeArgs(options) {
48
43
  if (options.streamDeltas ?? isStreamDeltasEnabled()) {
49
44
  args.push('--include-partial-messages');
50
45
  }
46
+ if (getSettings().showThinking)
47
+ args.push('--thinking-display', 'summarized');
51
48
  return args;
52
49
  }
53
50
  export function resolveClaudeMcpBundles(options) {
@@ -148,10 +145,6 @@ function appendEnvironmentOptions(args, options) {
148
145
  if (options.settingSources)
149
146
  args.push('--setting-sources', options.settingSources.join(','));
150
147
  }
151
- function appendExtraOptions(args, options) {
152
- for (const [flag, value] of Object.entries(options ?? {}))
153
- args.push(flag, value);
154
- }
155
148
  function buildClaudeSettings(options, effectiveTools) {
156
149
  const settings = {
157
150
  hooks: options.disableHooks ? {} : buildHooksSettings(effectiveTools),
@@ -177,7 +170,6 @@ export function buildSpawnArgs(options) {
177
170
  appendPromptOptions(args, options);
178
171
  appendRepeatedOption(args, '--plugin-dir', options.pluginDirs);
179
172
  appendEnvironmentOptions(args, options);
180
- appendExtraOptions(args, options.extraOption);
181
173
  args.push('--settings', JSON.stringify(buildClaudeSettings(options, tools)));
182
174
  appendSessionIdentity(args, options);
183
175
  return args;
@@ -185,7 +177,8 @@ export function buildSpawnArgs(options) {
185
177
  /** Ambient Cortex context keys re-derived on every spawn, so a stale parent value can never leak
186
178
  * in. CORTEX_EXECUTION_ID is deliberately absent: it is set from context but never reset. */
187
179
  const CORTEX_CONTEXT_RESET_KEYS = [
188
- 'CORTEX_PROFILE', 'CORTEX_PROJECT', 'CORTEX_SESSION_NAME',
180
+ 'CORTEX_PROFILE', 'CORTEX_PROJECT', 'CORTEX_SESSION_NAME', // Never inherit the retired key.
181
+ 'CORTEX_BACKEND', 'CORTEX_MODEL', 'CORTEX_PROVIDER', 'CORTEX_THINKING', 'CORTEX_MODE',
189
182
  ];
190
183
  function setIfPresent(env, key, value) {
191
184
  if (value)
@@ -243,11 +236,11 @@ function applyChannelEnv(env, channel, pinned) {
243
236
  env.FEISHU_CHANNEL = channel;
244
237
  env.SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;
245
238
  }
246
- /** Per-spawn env overrides: `extraEnv` sets (last-wins over everything above), then `unsetEnv`
239
+ /** Per-spawn route environment sets, then `unsetEnv`
247
240
  * deletes. Deletion is a separate channel because a value can never mean "absent" — the empty
248
241
  * string is a legal value elsewhere in the spawn path. */
249
- function applyEnvOverrides(env, extraEnv, unsetEnv) {
250
- for (const [key, value] of Object.entries(extraEnv ?? {}))
242
+ function applyEnvOverrides(env, routeEnv, unsetEnv) {
243
+ for (const [key, value] of Object.entries(routeEnv ?? {}))
251
244
  env[key] = value;
252
245
  for (const key of unsetEnv ?? [])
253
246
  delete env[key];
@@ -263,12 +256,12 @@ function credentialFingerprint(value) {
263
256
  return `sha256:${createHash('sha256').update(value).digest('hex').slice(0, 8)}`;
264
257
  }
265
258
  /** What the child ends up with for `key`, in the order {@link buildClaudeEnv} applies: the
266
- * dedicated field is the base, `extraEnv` overrides it, `unsetEnv` deletes it.
259
+ * dedicated field is the base, `routeEnv` overrides it, `unsetEnv` deletes it.
267
260
  * `null` = deleted, `undefined` = inherited from the daemon env. */
268
261
  function routeEnvValue(key, route, base) {
269
262
  if (route.unsetEnv?.includes(key))
270
263
  return null;
271
- return route.extraEnv?.[key] ?? base;
264
+ return route.routeEnv?.[key] ?? base;
272
265
  }
273
266
  /** `deleted` and `inherited` stay distinct on purpose: one pins the child to no credential at
274
267
  * all, the other leaves it to whatever the daemon env happens to hold at spawn time. */
@@ -292,13 +285,17 @@ export function claudeRouteIdentity(route) {
292
285
  }
293
286
  function cortexContextEnv(context) {
294
287
  return {
295
- CORTEX_PROFILE: context?.profile,
288
+ CORTEX_BACKEND: 'claude',
289
+ CORTEX_MODEL: context?.selection?.model,
290
+ CORTEX_PROVIDER: context?.selection?.provider,
291
+ CORTEX_THINKING: context?.selection?.thinking,
292
+ CORTEX_MODE: context?.selection?.mode,
296
293
  CORTEX_PROJECT: context?.project,
297
294
  CORTEX_EXECUTION_ID: context?.executionId,
298
295
  };
299
296
  }
300
297
  /** Authoritative last word on the Cortex context keys: a child can neither inherit a stale value
301
- * nor forge one through extraEnv/unsetEnv. */
298
+ * nor forge one through routeEnv/unsetEnv. */
302
299
  function applyCortexContextEnv(env, context) {
303
300
  for (const key of CORTEX_CONTEXT_RESET_KEYS)
304
301
  delete env[key];
@@ -348,7 +345,7 @@ function applySubagentModelEnv(env) {
348
345
  for (const [key, value] of Object.entries(subagentModelEnv()))
349
346
  setIfPresent(env, key, value);
350
347
  }
351
- export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskId, anthropicBaseUrl, extraEnv, context, pinnedEnv, unsetEnv) {
348
+ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskId, anthropicBaseUrl, routeEnv, context, pinnedEnv, unsetEnv) {
352
349
  // Allowlist-first for a pinned trial: the child starts from the exact trial environment and
353
350
  // inherits nothing from the host, so no denylist can leak a host credential or platform
354
351
  // surface into the trial (design §13 C5/C7).
@@ -358,17 +355,13 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
358
355
  // CORTEX_SESSION_ID is the stable Cortex tracking id (session-activity log routing + MCP context),
359
356
  // NOT the backend CLI's self-assigned session id. Falls back to the backend id when unset.
360
357
  env.CORTEX_SESSION_ID = context?.trackSessionId ?? sessionId;
361
- // Declared, not inferred: hooks branch on which backend loaded the AGENTS.md chain natively
362
- // (agents-md-injector.mjs), and "absent means Claude" would silently mis-handle any future
363
- // spawn path that forgets to set it. PI states itself in agent-adapter/pi/session-options.ts.
364
- env.CORTEX_BACKEND = 'claude';
365
358
  setIfPresent(env, 'CORTEX_CALLBACK_SOURCE', callbackSource);
366
359
  setIfPresent(env, 'CORTEX_SCHEDULE_TASK_ID', scheduleTaskId);
367
360
  setIfPresent(env, 'ANTHROPIC_BASE_URL', anthropicBaseUrl);
368
361
  if (!pinnedEnv)
369
362
  applyHostClaudeEnv(env);
370
363
  applySubagentModelEnv(env);
371
- applyEnvOverrides(env, extraEnv, unsetEnv);
364
+ applyEnvOverrides(env, routeEnv, unsetEnv);
372
365
  applyCortexContextEnv(env, context);
373
366
  return env;
374
367
  }
@@ -0,0 +1,42 @@
1
+ /** The stub Claude Code itself writes when it clears an old tool result. */
2
+ export declare const CLEARED_TOOL_RESULT = "[Old tool result content cleared]";
3
+ export interface ToolResultClearing {
4
+ lines: string[];
5
+ clearedCount: number;
6
+ charsRemoved: number;
7
+ }
8
+ export type ColdResumeSkip = 'disabled' | 'warm' | 'unreadable' | 'small-context' | 'too-little' | 'write-failed';
9
+ export type ColdResumeClearing = {
10
+ cleared: true;
11
+ clearedCount: number;
12
+ charsRemoved: number;
13
+ } | {
14
+ cleared: false;
15
+ reason: ColdResumeSkip;
16
+ };
17
+ /** The file operations the clearing needs; replaced in tests. */
18
+ export interface TranscriptFs {
19
+ readFileSync(path: string): Buffer;
20
+ statSync(path: string): {
21
+ mode: number;
22
+ };
23
+ writeFileSync(path: string, data: Buffer, mode: number): void;
24
+ appendFileSync(path: string, data: string): void;
25
+ renameSync(from: string, to: string): void;
26
+ unlinkSync(path: string): void;
27
+ }
28
+ /**
29
+ * Stub the content of every tool result after the last compact boundary except the most recent
30
+ * `keepRecent`. Only `message.content` of those blocks changes; every other line, and every field
31
+ * of a changed line, is kept, and an unchanged line is returned as the same string.
32
+ */
33
+ export declare function clearOldToolResults(lines: readonly string[], keepRecent?: number): ToolResultClearing;
34
+ /** The context size the last model request after the last compact boundary carried, if any. */
35
+ export declare function liveContextTokens(lines: readonly string[]): number | null;
36
+ /**
37
+ * Before `--resume` of a session whose prompt cache has certainly expired, stub all but the most
38
+ * recent tool results so the CLI re-sends a smaller context. The cache is cold either way, so no
39
+ * cached prefix is lost; the turn's pre-run snapshot keeps the uncleared transcript for rewind. Any
40
+ * failure leaves the transcript untouched.
41
+ */
42
+ export declare function clearToolResultsForColdResume(transcriptPath: string, backendSessionId: string, now?: number, io?: TranscriptFs): ColdResumeClearing;
@@ -0,0 +1,217 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { isUtf8 } from 'node:buffer';
4
+ import { createLogger } from '../../core/log.js';
5
+ import { getSettings } from '../../core/settings.js';
6
+ import { lastCacheTouch } from './cache-touch.js';
7
+ const log = createLogger('claude-bridge');
8
+ /** The stub Claude Code itself writes when it clears an old tool result. */
9
+ export const CLEARED_TOOL_RESULT = '[Old tool result content cleared]';
10
+ const KEEP_RECENT_TOOL_RESULTS = 10;
11
+ /** Past the 1h prompt-cache TTL with margin; also the idle close, so an ordinary cold wake qualifies. */
12
+ const COLD_CACHE_MS = 65 * 60_000;
13
+ const MIN_CONTEXT_TOKENS = 100_000;
14
+ const MIN_CHARS_REMOVED = 40_000;
15
+ const BOUNDARY_NEEDLE = Buffer.from('"compact_boundary"');
16
+ const nodeFs = {
17
+ readFileSync: (p) => fs.readFileSync(p),
18
+ statSync: (p) => fs.statSync(p),
19
+ writeFileSync: (p, data, mode) => fs.writeFileSync(p, data, { mode }),
20
+ appendFileSync: (p, data) => fs.appendFileSync(p, data),
21
+ renameSync: (from, to) => fs.renameSync(from, to),
22
+ unlinkSync: (p) => fs.unlinkSync(p),
23
+ };
24
+ function parseRecord(line) {
25
+ try {
26
+ const value = JSON.parse(line);
27
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function isCompactBoundary(line) {
34
+ if (!line.includes('"compact_boundary"'))
35
+ return false;
36
+ const record = parseRecord(line);
37
+ return record?.type === 'system' && record.subtype === 'compact_boundary';
38
+ }
39
+ /** Index of the first line the resumed model still sees: right after the last compact boundary. */
40
+ function liveSegmentStart(lines) {
41
+ for (let i = lines.length - 1; i >= 0; i--) {
42
+ if (isCompactBoundary(lines[i]))
43
+ return i + 1;
44
+ }
45
+ return 0;
46
+ }
47
+ function messageOf(record) {
48
+ const message = record?.message;
49
+ return message !== null && typeof message === 'object' ? message : null;
50
+ }
51
+ function toolResultBlocks(record) {
52
+ if (record?.type !== 'user' || record.isSidechain === true)
53
+ return [];
54
+ const content = messageOf(record)?.content;
55
+ if (!Array.isArray(content))
56
+ return [];
57
+ return content.filter((block) => block !== null && typeof block === 'object' && block.type === 'tool_result');
58
+ }
59
+ function collectToolResults(lines, start) {
60
+ const refs = [];
61
+ for (let line = start; line < lines.length; line++) {
62
+ if (!lines[line].includes('"tool_result"'))
63
+ continue;
64
+ const record = parseRecord(lines[line]);
65
+ for (const block of toolResultBlocks(record))
66
+ refs.push({ line, record: record, block });
67
+ }
68
+ return refs;
69
+ }
70
+ const PLACEHOLDER_CHARS = JSON.stringify(CLEARED_TOOL_RESULT).length;
71
+ /** Stub one block; returns the characters saved. A result no longer than the stub stays as it is. */
72
+ function clearBlock(block) {
73
+ const saved = JSON.stringify(block.content ?? '').length - PLACEHOLDER_CHARS;
74
+ if (saved <= 0)
75
+ return 0;
76
+ block.content = CLEARED_TOOL_RESULT;
77
+ return saved;
78
+ }
79
+ /**
80
+ * Stub the content of every tool result after the last compact boundary except the most recent
81
+ * `keepRecent`. Only `message.content` of those blocks changes; every other line, and every field
82
+ * of a changed line, is kept, and an unchanged line is returned as the same string.
83
+ */
84
+ export function clearOldToolResults(lines, keepRecent = KEEP_RECENT_TOOL_RESULTS) {
85
+ const refs = collectToolResults(lines, liveSegmentStart(lines));
86
+ const changed = new Map();
87
+ let clearedCount = 0;
88
+ let charsRemoved = 0;
89
+ for (const ref of refs.slice(0, Math.max(0, refs.length - keepRecent))) {
90
+ const saved = clearBlock(ref.block);
91
+ if (saved === 0)
92
+ continue;
93
+ changed.set(ref.line, ref.record);
94
+ clearedCount++;
95
+ charsRemoved += saved;
96
+ }
97
+ const out = lines.map((line, i) => (changed.has(i) ? JSON.stringify(changed.get(i)) : line));
98
+ return { lines: out, clearedCount, charsRemoved };
99
+ }
100
+ function tokenCount(value) {
101
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
102
+ }
103
+ function assistantContextTokens(record) {
104
+ if (record?.type !== 'assistant' || record.isSidechain === true)
105
+ return null;
106
+ const usage = messageOf(record)?.usage;
107
+ if (usage === null || typeof usage !== 'object')
108
+ return null;
109
+ const total = tokenCount(usage.input_tokens) + tokenCount(usage.cache_read_input_tokens)
110
+ + tokenCount(usage.cache_creation_input_tokens);
111
+ // A synthetic assistant message (an API error, an interrupted turn) reports all zeros.
112
+ return total > 0 ? total : null;
113
+ }
114
+ /** The context size the last model request after the last compact boundary carried, if any. */
115
+ export function liveContextTokens(lines) {
116
+ const start = liveSegmentStart(lines);
117
+ for (let i = lines.length - 1; i >= start; i--) {
118
+ if (!lines[i].includes('"usage"'))
119
+ continue;
120
+ const tokens = assistantContextTokens(parseRecord(lines[i]));
121
+ if (tokens !== null)
122
+ return tokens;
123
+ }
124
+ return null;
125
+ }
126
+ /**
127
+ * Byte offset of the line holding the last compact boundary, or 0. Everything before it is outside
128
+ * the resumed context, so it is copied through without being decoded.
129
+ */
130
+ function liveSegmentOffset(buf) {
131
+ let hit = buf.lastIndexOf(BOUNDARY_NEEDLE);
132
+ while (hit !== -1) {
133
+ const lineStart = buf.lastIndexOf(0x0a, hit) + 1;
134
+ const newline = buf.indexOf(0x0a, hit);
135
+ if (isCompactBoundary(buf.toString('utf8', lineStart, newline === -1 ? buf.length : newline)))
136
+ return lineStart;
137
+ if (lineStart === 0)
138
+ return 0;
139
+ hit = buf.lastIndexOf(BOUNDARY_NEEDLE, lineStart - 1);
140
+ }
141
+ return 0;
142
+ }
143
+ function coldGate(transcriptPath, backendSessionId, now) {
144
+ if (!getSettings().coldResumeClearToolResults)
145
+ return 'disabled';
146
+ const touched = lastCacheTouch(transcriptPath, backendSessionId);
147
+ return touched === null || now - touched <= COLD_CACHE_MS ? 'warm' : null;
148
+ }
149
+ function readTranscript(transcriptPath, io) {
150
+ try {
151
+ return io.readFileSync(transcriptPath);
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ }
157
+ function planClearing(liveText) {
158
+ const lines = liveText.split('\n');
159
+ const tokens = liveContextTokens(lines);
160
+ if (tokens === null || tokens < MIN_CONTEXT_TOKENS)
161
+ return 'small-context';
162
+ const clearing = clearOldToolResults(lines);
163
+ return clearing.charsRemoved < MIN_CHARS_REMOVED ? 'too-little' : clearing;
164
+ }
165
+ /** Same-directory temp file, then rename over the transcript. Throws with the temp file removed. */
166
+ function replaceTranscript(transcriptPath, head, liveText, io) {
167
+ const tmp = `${transcriptPath}.${process.pid}.clear.tmp`;
168
+ try {
169
+ io.writeFileSync(tmp, head, io.statSync(transcriptPath).mode & 0o777);
170
+ io.appendFileSync(tmp, liveText);
171
+ io.renameSync(tmp, transcriptPath);
172
+ }
173
+ catch (error) {
174
+ try {
175
+ io.unlinkSync(tmp);
176
+ }
177
+ catch { /* never created */ }
178
+ throw error;
179
+ }
180
+ }
181
+ function writeClearing(transcriptPath, head, clearing, io) {
182
+ try {
183
+ replaceTranscript(transcriptPath, head, clearing.lines.join('\n'), io);
184
+ }
185
+ catch (error) {
186
+ log.warn(`Cold-resume tool-result clearing failed for ${path.basename(transcriptPath)}, resuming it as is: ${error.message}`);
187
+ return { cleared: false, reason: 'write-failed' };
188
+ }
189
+ return { cleared: true, clearedCount: clearing.clearedCount, charsRemoved: clearing.charsRemoved };
190
+ }
191
+ function clearTranscript(transcriptPath, io) {
192
+ const buf = readTranscript(transcriptPath, io);
193
+ if (!buf)
194
+ return { cleared: false, reason: 'unreadable' };
195
+ const offset = liveSegmentOffset(buf);
196
+ const live = buf.subarray(offset);
197
+ if (!isUtf8(live))
198
+ return { cleared: false, reason: 'unreadable' };
199
+ const plan = planClearing(live.toString('utf8'));
200
+ if (typeof plan === 'string')
201
+ return { cleared: false, reason: plan };
202
+ return writeClearing(transcriptPath, buf.subarray(0, offset), plan, io);
203
+ }
204
+ /**
205
+ * Before `--resume` of a session whose prompt cache has certainly expired, stub all but the most
206
+ * recent tool results so the CLI re-sends a smaller context. The cache is cold either way, so no
207
+ * cached prefix is lost; the turn's pre-run snapshot keeps the uncleared transcript for rewind. Any
208
+ * failure leaves the transcript untouched.
209
+ */
210
+ export function clearToolResultsForColdResume(transcriptPath, backendSessionId, now = Date.now(), io = nodeFs) {
211
+ const gated = coldGate(transcriptPath, backendSessionId, now);
212
+ const outcome = gated ? { cleared: false, reason: gated } : clearTranscript(transcriptPath, io);
213
+ if (outcome.cleared) {
214
+ log.info(`Cleared ${outcome.clearedCount} old tool results before cold resume: ${backendSessionId.substring(0, 8)} (-${outcome.charsRemoved} chars)`);
215
+ }
216
+ return outcome;
217
+ }
@@ -30,6 +30,8 @@ export interface PendingTurn {
30
30
  /** Incremental text chunk while a block is still being generated (never the accumulated total).
31
31
  * Web UI preview only — the complete message above stays authoritative. */
32
32
  onAssistantDelta: ((text: string, blockId: string) => void) | null;
33
+ onAssistantThinking: ((text: string, blockId?: string) => void) | null;
34
+ onAssistantThinkingDelta: ((text: string, blockId: string) => void) | null;
33
35
  /** `subagent` is set only when a native subagent made the call (see ToolUseSubagent).
34
36
  * Optional so existing implementations that ignore attribution still satisfy the type. */
35
37
  onToolUse: ((name: string, input: any, toolUseId: string, subagent?: ToolUseSubagent) => void) | null;
@@ -170,7 +172,8 @@ export declare class ClaudeTurnMachine {
170
172
  private handleReplayEcho;
171
173
  private continuationCallbacks;
172
174
  /** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
173
- * background task finishes. Its output is delivered or buffered for backgroundTurnSink. */
175
+ * background task finishes (or after an injected message it consumed with no turn in flight).
176
+ * Its output is delivered or buffered for backgroundTurnSink. */
174
177
  private openContinuationTurn;
175
178
  compactUsage(result: AgentResult): AgentCompactUsage | null;
176
179
  /** Start a fresh process's cost cursor at the total the CLI restored on `--resume` (0 for a new
@@ -193,9 +196,8 @@ export declare class ClaudeTurnMachine {
193
196
  * anything from a subagent that ran beside it.
194
197
  */
195
198
  private handleOrphanSubagentLine;
196
- private handleAssistantToolBlock;
197
- private handleAssistantTextBlock;
198
199
  private handleAssistantEvent;
200
+ private handleStreamEvent;
199
201
  private emitContextUsage;
200
202
  /**
201
203
  * OC-11 / §17 G4-SA5 — read the linkage the CLI already puts on the wire. A non-null
@@ -3,9 +3,11 @@ import { Writable } from 'stream';
3
3
  import * as path from 'path';
4
4
  import { readableTimestamp } from '../../core/utils.js';
5
5
  import { createLogger } from '../../core/log.js';
6
+ import { getSettings } from '../../core/settings.js';
7
+ import { handleAssistantBlocks } from './assistant-blocks.js';
6
8
  import { toolResultImages } from '../normalize/tool-result-images.js';
7
9
  import { CancelledError, LOGS_DIR } from './defaults.js';
8
- import { buildPrompt, clearActivePlanFile, extractResult, formatEvent, isPlanFilePath, setActivePlanFile, createStreamDeltaState, parseStreamEvent, takeTextBlockId, parseModelFallbackEvent, } from './event-parser.js';
10
+ import { buildPrompt, clearActivePlanFile, extractResult, formatEvent, createStreamDeltaState, parseStreamEvent, parseModelFallbackEvent, } from './event-parser.js';
9
11
  import { BgTaskTracker, isContinuationResult, routeLine } from './bg-task-tracker.js';
10
12
  import { promptAccounting, tokenValue, } from './event-translator.js';
11
13
  import { activeClaudeCaptureRegistry } from './active-capture-registry.js';
@@ -197,6 +199,8 @@ export class ClaudeTurnMachine {
197
199
  onProgress: options.onProgress || null,
198
200
  onAssistantMessage: options.onAssistantMessage || null,
199
201
  onAssistantDelta: options.onAssistantDelta || null,
202
+ onAssistantThinking: options.onAssistantThinking || null,
203
+ onAssistantThinkingDelta: options.onAssistantThinkingDelta || null,
200
204
  onToolUse: options.onToolUse || null,
201
205
  onToolResult: options.onToolResult || null,
202
206
  onCompact: options.onCompact || null,
@@ -301,6 +305,7 @@ export class ClaudeTurnMachine {
301
305
  resolve: (value) => this.deliverContinuation(sink => sink.onResult(value)),
302
306
  reject: (error) => log.warn('continuation turn rejected:', error?.message ?? String(error)),
303
307
  onAssistantMessage: (text, _blockId, model, subagent) => this.deliverContinuation(sink => sink.onAssistantText(text, model, subagent)),
308
+ onAssistantThinking: (text, blockId) => this.deliverContinuation(sink => sink.onAssistantThinking?.(text, blockId)),
304
309
  onToolUse: (name, input, id, subagent) => this.deliverContinuation(sink => sink.onToolUse?.(name, input, id, subagent)),
305
310
  onToolResult: (id, content, isError, subagent, images) => this.deliverContinuation(sink => sink.onToolResult?.(id, content, isError, subagent, images)),
306
311
  onContextUsage: (usage) => this.deliverContinuation(sink => sink.onContextUsage?.(usage)),
@@ -308,13 +313,16 @@ export class ClaudeTurnMachine {
308
313
  };
309
314
  }
310
315
  /** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
311
- * background task finishes. Its output is delivered or buffered for backgroundTurnSink. */
312
- openContinuationTurn(label = '[background-task continuation]') {
313
- this.bgTracker.disarmContinuation();
316
+ * background task finishes (or after an injected message it consumed with no turn in flight).
317
+ * Its output is delivered or buffered for backgroundTurnSink. */
318
+ openContinuationTurn(fromInjection) {
319
+ const summaries = this.bgTracker.disarmContinuation();
320
+ const label = fromInjection ? '[injected-message continuation]' : '[background-task continuation]';
314
321
  const streams = this.createTurnStreams(label);
315
322
  // The hold's watchdogs bound the WAIT for this turn, not the turn itself: a continuation
316
323
  // that runs longer than the grace/max-wait window must not be sealed idle mid-stream.
317
- this.deliverContinuation(sink => sink.onTurnOpen?.());
324
+ const wake = fromInjection ? undefined : { summaries };
325
+ this.deliverContinuation(sink => sink.onTurnOpen?.(wake));
318
326
  this.currentTurn = {
319
327
  ...this.continuationCallbacks(),
320
328
  resultData: null, planFilePath: null,
@@ -323,7 +331,7 @@ export class ClaudeTurnMachine {
323
331
  capturePairKey: streams.pairKey,
324
332
  releaseCapture: streams.releaseCapture,
325
333
  onProgress: null, onAssistantDelta: null, onCompact: null, onSubagentActivity: null,
326
- onSubagentEnd: null,
334
+ onSubagentEnd: null, onAssistantThinkingDelta: null,
327
335
  rawStream: streams.rawStream, txtStream: streams.txtStream,
328
336
  killed: false, spontaneous: true,
329
337
  };
@@ -471,65 +479,22 @@ export class ClaudeTurnMachine {
471
479
  }
472
480
  }
473
481
  }
474
- handleAssistantToolBlock(turn, block, subagent) {
475
- if (block.name === 'Write' && isPlanFilePath(block.input?.file_path)) {
476
- turn.planFilePath = block.input.file_path;
477
- setActivePlanFile(this.host.sessionId, block.input.file_path);
478
- }
479
- if (block.name === 'EnterPlanMode')
480
- turn.enteredPlanMode = true;
481
- if (block.name === 'ExitPlanMode')
482
- turn.exitedPlanMode = true;
483
- if (typeof turn.onToolUse !== 'function')
484
- return;
485
- try {
486
- turn.onToolUse(block.name || '?', block.input || {}, typeof block.id === 'string' ? block.id : '', subagent);
487
- }
488
- catch (error) {
489
- log.warn('onToolUse threw:', error.message);
490
- }
482
+ handleAssistantEvent(turn, data) {
483
+ handleAssistantBlocks(turn, data, this.streamDeltaState, this.host.sessionId, subagentAttribution(data));
491
484
  }
492
- handleAssistantTextBlock(turn, data, block, subagent) {
493
- if (!block.text)
494
- return;
495
- const model = typeof data.message?.model === 'string' ? data.message.model : null;
496
- // A subagent's text is NOT this turn's answer, and it did not stream: the CLI attaches subagent
497
- // linkage only to complete `assistant`/`user` messages, never to `stream_event`. So it must not
498
- // become finalOutput, must not win longestOutput, and — above all — must not consume the delta
499
- // cursor, which belongs to a main-agent block still being streamed.
500
- if (subagent) {
501
- turn.onAssistantMessage?.(block.text, undefined, model, subagent);
485
+ handleStreamEvent(data) {
486
+ this.emitContextUsage(data);
487
+ const delta = parseStreamEvent(data, this.streamDeltaState);
488
+ if (!delta)
502
489
  return;
490
+ const callback = delta.kind === 'thinking'
491
+ ? (getSettings().showThinking ? this.currentTurn?.onAssistantThinkingDelta : null)
492
+ : this.currentTurn?.onAssistantDelta;
493
+ try {
494
+ callback?.(delta.text, delta.blockId);
503
495
  }
504
- turn.finalOutput = block.text;
505
- if (block.text.length > (turn.longestOutput?.length || 0))
506
- turn.longestOutput = block.text;
507
- const blockId = takeTextBlockId(this.streamDeltaState) ?? undefined;
508
- const streamedModel = this.streamDeltaState.messageId === data.message?.id
509
- ? this.streamDeltaState.model
510
- : null;
511
- turn.onAssistantMessage?.(block.text, blockId, model ?? streamedModel);
512
- }
513
- handleAssistantEvent(turn, data) {
514
- // Every line still walks every branch below — subagent lines are TAGGED, never dropped, so the
515
- // journal keeps a complete trajectory. What the tag changes is attribution: a subagent's turns
516
- // are counted apart from the main agent's, and its text cannot be mistaken for the answer.
517
- const subagent = subagentAttribution(data);
518
- if (subagent)
519
- turn.subagentTurnCount += 1;
520
- else
521
- turn.turnCount += 1;
522
- for (const block of (data.message?.content || [])) {
523
- if (block.type === 'tool_use')
524
- this.handleAssistantToolBlock(turn, block, subagent);
525
- if (block.type === 'text')
526
- this.handleAssistantTextBlock(turn, data, block, subagent);
527
- }
528
- // A subagent's message did not advance the main agent's turn, so re-rendering progress would
529
- // redraw the same number. The JSONL path withholds turn_progress on sidechain records for the
530
- // same reason.
531
- if (!subagent) {
532
- turn.onProgress?.({ num_turns: turn.turnCount, total_cost_usd: null, duration_ms: null });
496
+ catch (e) {
497
+ log.warn('assistant delta callback threw:', e.message);
533
498
  }
534
499
  }
535
500
  emitContextUsage(data) {
@@ -599,16 +564,7 @@ export class ClaudeTurnMachine {
599
564
  // are deliberately kept out of the per-turn raw jsonl and the daemon log. Handled first, and
600
565
  // separately, because everything below is about complete events.
601
566
  if (isJson && parsed?.type === 'stream_event') {
602
- this.emitContextUsage(parsed);
603
- const delta = parseStreamEvent(parsed, this.streamDeltaState);
604
- if (delta && typeof this.currentTurn?.onAssistantDelta === 'function') {
605
- try {
606
- this.currentTurn.onAssistantDelta(delta.text, delta.blockId);
607
- }
608
- catch (e) {
609
- log.warn('onAssistantDelta threw:', e.message);
610
- }
611
- }
567
+ this.handleStreamEvent(parsed);
612
568
  return;
613
569
  }
614
570
  if (this.currentTurn?.rawStream)
@@ -687,7 +643,7 @@ export class ClaudeTurnMachine {
687
643
  && (this.injectionContinuationArmed || routeLine(this.bgTracker, data) === 'open-continuation')) {
688
644
  const fromInjection = this.injectionContinuationArmed;
689
645
  this.injectionContinuationArmed = false;
690
- this.openContinuationTurn(fromInjection ? '[injected-message continuation]' : '[background-task continuation]');
646
+ this.openContinuationTurn(fromInjection);
691
647
  }
692
648
  if (data.type === 'result' && this.currentTurn) {
693
649
  // A task-notification turn's result can only settle a spontaneous turn. When it lands on
@@ -0,0 +1,13 @@
1
+ import { runFile } from '../../core/exec-async.js';
2
+ export declare const WINDOW_WARMUP_TIMEOUT_MS = 120000;
3
+ /** No tools, no MCP servers, no session file. The prompt goes on stdin because `--tools` takes a
4
+ * variable number of values and would swallow a trailing positional prompt. */
5
+ export declare const WINDOW_WARMUP_ARGS: readonly string[];
6
+ export interface WindowWarmupLaunch {
7
+ command: string;
8
+ env: NodeJS.ProcessEnv;
9
+ cwd: string;
10
+ }
11
+ export type WindowWarmupRunner = typeof runFile;
12
+ /** Resolves once Claude answered; rejects with the CLI's own error text otherwise. */
13
+ export declare function runWindowWarmup(launch: WindowWarmupLaunch, run?: WindowWarmupRunner): Promise<void>;
@@ -0,0 +1,38 @@
1
+ import { runFile } from '../../core/exec-async.js';
2
+ // One tiny request through Claude Code itself. It opens Claude's five-hour subscription window, and
3
+ // on the way Claude Code refreshes its own login under its own lock, which Cortex must not do
4
+ // behind its back.
5
+ export const WINDOW_WARMUP_TIMEOUT_MS = 120_000;
6
+ const WARMUP_PROMPT = 'ok';
7
+ /** No tools, no MCP servers, no session file. The prompt goes on stdin because `--tools` takes a
8
+ * variable number of values and would swallow a trailing positional prompt. */
9
+ export const WINDOW_WARMUP_ARGS = [
10
+ '-p', '--output-format', 'json', '--model', 'haiku', '--max-turns', '1',
11
+ '--no-session-persistence', '--strict-mcp-config',
12
+ '--system-prompt', 'Reply with exactly: ok', '--tools', '',
13
+ ];
14
+ function parseResult(stdout) {
15
+ try {
16
+ const record = JSON.parse(stdout.trim());
17
+ return record && typeof record === 'object' && record.type === 'result' ? record : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ function failureText(result, output) {
24
+ if (result.timedOut)
25
+ return `timed out after ${WINDOW_WARMUP_TIMEOUT_MS}ms`;
26
+ const text = typeof output?.result === 'string' ? output.result : result.stderr.trim() || result.error;
27
+ return (text || `exit ${result.code}`).slice(-300);
28
+ }
29
+ /** Resolves once Claude answered; rejects with the CLI's own error text otherwise. */
30
+ export async function runWindowWarmup(launch, run = runFile) {
31
+ const result = await run(launch.command, WINDOW_WARMUP_ARGS, {
32
+ cwd: launch.cwd, env: launch.env, timeoutMs: WINDOW_WARMUP_TIMEOUT_MS, stdin: WARMUP_PROMPT,
33
+ });
34
+ const output = parseResult(result.stdout);
35
+ if (result.ok && output && output.is_error !== true)
36
+ return;
37
+ throw new Error(`Claude warm-up failed: ${failureText(result, output)}`);
38
+ }
@@ -1,5 +1,5 @@
1
1
  import type { AgentResult } from '../core/types/agent-types.js';
2
- import type { BackgroundTurnSink } from './types.js';
2
+ import type { BackgroundTurnSink, BackgroundWake } from './types.js';
3
3
  import type { RunEvent } from './run-events.js';
4
4
  /** What the caller asked the engine to do about a run's background work. */
5
5
  export type AwaitBackground = 'none' | 'hold';
@@ -96,8 +96,11 @@ export declare class ContinuationPhase {
96
96
  * result decides what happens next. Releasing it on the ack instead would close the stream
97
97
  * before the reply it is owed could land; never releasing it (as was the case) left a run whose
98
98
  * foreground turn ended with one injected message pending open forever — the max-wait watchdog
99
- * bounds a WAIT, it does not finish a run. */
100
- onTurnOpen(): void;
99
+ * bounds a WAIT, it does not finish a run.
100
+ *
101
+ * A turn that finished background work opened carries its `wake`, reported ahead of anything
102
+ * the turn says. */
103
+ onTurnOpen(wake?: BackgroundWake): void;
101
104
  private enterBackground;
102
105
  /** Everything that reaches this run's stream passes through here, so the phase can react to the
103
106
  * couple of events that change what the run still owes (injection acks, a turn opening). */