@cortex-agent/server 2026.10.15 → 2026.10.21

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 (333) hide show
  1. package/README.md +76 -50
  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/plugins/cortex-board/skills/board/SKILL.md +30 -22
  7. package/defaults/plugins/cortex-system/plugin.json +2 -2
  8. package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
  9. package/dist/agent-adapter/claude/adapter.d.ts +2 -5
  10. package/dist/agent-adapter/claude/adapter.js +6 -5
  11. package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
  12. package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
  13. package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
  14. package/dist/agent-adapter/claude/cache-refresh.js +145 -0
  15. package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
  16. package/dist/agent-adapter/claude/cache-touch.js +75 -0
  17. package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
  18. package/dist/agent-adapter/claude/event-parser.js +33 -17
  19. package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
  20. package/dist/agent-adapter/claude/event-translator.js +2 -0
  21. package/dist/agent-adapter/claude/session-options.d.ts +6 -13
  22. package/dist/agent-adapter/claude/session-options.js +2 -13
  23. package/dist/agent-adapter/claude/spawn-args.d.ts +4 -21
  24. package/dist/agent-adapter/claude/spawn-args.js +17 -24
  25. package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
  26. package/dist/agent-adapter/claude/transcript-clear.js +217 -0
  27. package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
  28. package/dist/agent-adapter/claude/turn-machine.js +21 -68
  29. package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
  30. package/dist/agent-adapter/claude/window-warmup.js +38 -0
  31. package/dist/agent-adapter/continuation-phase.js +3 -0
  32. package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
  33. package/dist/agent-adapter/pi/adapter.d.ts +0 -1
  34. package/dist/agent-adapter/pi/adapter.js +5 -13
  35. package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
  36. package/dist/agent-adapter/pi/event-parser.js +43 -27
  37. package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
  38. package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
  39. package/dist/agent-adapter/pi/pi-session.js +15 -0
  40. package/dist/agent-adapter/pi/providers-config.d.ts +2 -2
  41. package/dist/agent-adapter/pi/providers-config.js +1 -1
  42. package/dist/agent-adapter/pi/quota-sink.d.ts +3 -3
  43. package/dist/agent-adapter/pi/quota-sink.js +3 -3
  44. package/dist/agent-adapter/pi/runtime.js +6 -1
  45. package/dist/agent-adapter/pi/session-options.d.ts +9 -13
  46. package/dist/agent-adapter/pi/session-options.js +12 -25
  47. package/dist/agent-adapter/run-events.d.ts +11 -10
  48. package/dist/agent-adapter/run-events.js +2 -0
  49. package/dist/agent-adapter/types.d.ts +5 -4
  50. package/dist/client-bundle/manifest.json +2 -2
  51. package/dist/core/codex-quota.d.ts +1 -1
  52. package/dist/core/codex-quota.js +1 -1
  53. package/dist/core/gateway-generator.d.ts +9 -11
  54. package/dist/core/gateway-generator.js +31 -58
  55. package/dist/core/locales/en.d.ts +51 -77
  56. package/dist/core/locales/slices/commands.d.ts +26 -31
  57. package/dist/core/locales/slices/commands.js +54 -64
  58. package/dist/core/locales/slices/init.d.ts +8 -19
  59. package/dist/core/locales/slices/init.js +17 -53
  60. package/dist/core/locales/slices/interactions.d.ts +3 -3
  61. package/dist/core/locales/slices/interactions.js +6 -6
  62. package/dist/core/locales/slices/notices.d.ts +1 -3
  63. package/dist/core/locales/slices/notices.js +2 -6
  64. package/dist/core/locales/slices/scheduling.d.ts +9 -9
  65. package/dist/core/locales/slices/scheduling.js +18 -18
  66. package/dist/core/locales/slices/status.d.ts +0 -4
  67. package/dist/core/locales/slices/status.js +0 -8
  68. package/dist/core/locales/slices/tui.d.ts +0 -1
  69. package/dist/core/locales/slices/tui.js +0 -2
  70. package/dist/core/locales/slices/uimsg.d.ts +4 -7
  71. package/dist/core/locales/slices/uimsg.js +9 -15
  72. package/dist/core/models-generator.d.ts +29 -0
  73. package/dist/core/models-generator.js +82 -0
  74. package/dist/core/paths.d.ts +1 -1
  75. package/dist/core/paths.js +1 -1
  76. package/dist/core/settings-spec.d.ts +25 -0
  77. package/dist/core/settings-spec.js +34 -0
  78. package/dist/core/status-format.d.ts +3 -2
  79. package/dist/core/status-format.js +2 -2
  80. package/dist/core/types/environment-types.d.ts +0 -2
  81. package/dist/domain/agents/agent-state.d.ts +11 -56
  82. package/dist/domain/agents/agent-state.js +48 -115
  83. package/dist/domain/agents/agent-switch.d.ts +2 -24
  84. package/dist/domain/agents/agent-switch.js +9 -72
  85. package/dist/domain/agents/config.d.ts +11 -61
  86. package/dist/domain/agents/config.js +47 -154
  87. package/dist/domain/agents/engine-selection.d.ts +21 -0
  88. package/dist/domain/agents/engine-selection.js +37 -0
  89. package/dist/domain/agents/environments/registry.js +2 -1
  90. package/dist/domain/agents/environments/resolve.js +0 -1
  91. package/dist/domain/agents/environments/schema.d.ts +0 -1
  92. package/dist/domain/agents/environments/schema.js +0 -1
  93. package/dist/domain/agents/index.d.ts +2 -1
  94. package/dist/domain/agents/index.js +3 -7
  95. package/dist/domain/agents/model-selection.d.ts +18 -70
  96. package/dist/domain/agents/model-selection.js +100 -150
  97. package/dist/domain/agents/models.d.ts +12 -0
  98. package/dist/domain/agents/models.js +94 -0
  99. package/dist/domain/agents/subagent/registry.d.ts +2 -0
  100. package/dist/domain/agents/subagent/registry.js +8 -0
  101. package/dist/domain/agents/subagent/runner.d.ts +5 -5
  102. package/dist/domain/agents/subagent/runner.js +12 -35
  103. package/dist/domain/auth/auth-status.d.ts +4 -4
  104. package/dist/domain/auth/auth-status.js +17 -28
  105. package/dist/domain/auth/gateway-sync.d.ts +6 -26
  106. package/dist/domain/auth/gateway-sync.js +31 -75
  107. package/dist/domain/benchmark/identity.d.ts +3 -5
  108. package/dist/domain/benchmark/identity.js +0 -1
  109. package/dist/domain/benchmark/production-attempt-identity.d.ts +6 -5
  110. package/dist/domain/benchmark/production-attempt-identity.js +32 -35
  111. package/dist/domain/benchmark/session-evidence.d.ts +2 -1
  112. package/dist/domain/benchmark/session-evidence.js +8 -1
  113. package/dist/domain/browser/broker.d.ts +99 -0
  114. package/dist/domain/browser/broker.js +487 -0
  115. package/dist/domain/costs/claude-account.js +21 -0
  116. package/dist/domain/costs/rate-limit-throttle.js +3 -1
  117. package/dist/domain/costs/reset-account.d.ts +2 -0
  118. package/dist/domain/costs/usage-service.d.ts +1 -1
  119. package/dist/domain/costs/usage-service.js +20 -7
  120. package/dist/domain/mcp/tools/context.d.ts +5 -6
  121. package/dist/domain/mcp/tools/context.js +17 -3
  122. package/dist/domain/mcp/tools/subagent.js +1 -1
  123. package/dist/domain/mcp/tools/ui-file.js +1 -1
  124. package/dist/domain/pi-providers/custom-provider-model.d.ts +1 -1
  125. package/dist/domain/pi-providers/custom-provider-model.js +1 -1
  126. package/dist/domain/remote/device-browser.js +1 -1
  127. package/dist/domain/remote/device-chrome-commands.js +2 -0
  128. package/dist/domain/remote/device-port.js +2 -2
  129. package/dist/domain/runs/attempt.d.ts +3 -3
  130. package/dist/domain/runs/attempt.js +2 -3
  131. package/dist/domain/runs/builders.d.ts +4 -4
  132. package/dist/domain/runs/builders.js +4 -5
  133. package/dist/domain/runs/compact.d.ts +4 -17
  134. package/dist/domain/runs/compact.js +14 -56
  135. package/dist/domain/runs/config-resolver.d.ts +15 -83
  136. package/dist/domain/runs/config-resolver.js +24 -150
  137. package/dist/domain/runs/engine-spec.d.ts +8 -8
  138. package/dist/domain/runs/engine-spec.js +15 -31
  139. package/dist/domain/runs/events.d.ts +1 -1
  140. package/dist/domain/runs/fallback.d.ts +6 -38
  141. package/dist/domain/runs/fallback.js +10 -72
  142. package/dist/domain/runs/notices.d.ts +1 -11
  143. package/dist/domain/runs/notices.js +3 -30
  144. package/dist/domain/runs/request.d.ts +4 -3
  145. package/dist/domain/runs/retryable-errors.d.ts +0 -13
  146. package/dist/domain/runs/retryable-errors.js +0 -17
  147. package/dist/domain/runs/run.d.ts +12 -42
  148. package/dist/domain/runs/run.js +40 -147
  149. package/dist/domain/runs/service.d.ts +1 -1
  150. package/dist/domain/runs/service.js +8 -3
  151. package/dist/domain/runs/spec-loader.d.ts +1 -1
  152. package/dist/domain/runs/spend.d.ts +1 -1
  153. package/dist/domain/runs/spend.js +1 -1
  154. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +3 -2
  155. package/dist/domain/scheduling/jobs/scheduled-task.js +25 -19
  156. package/dist/domain/scheduling/schedule-ops.d.ts +0 -1
  157. package/dist/domain/scheduling/schedule-ops.js +2 -5
  158. package/dist/domain/scheduling/schedule-selection.d.ts +3 -0
  159. package/dist/domain/scheduling/schedule-selection.js +16 -0
  160. package/dist/domain/scheduling/schedule-spec.d.ts +6 -5
  161. package/dist/domain/scheduling/schedule-spec.js +6 -6
  162. package/dist/domain/scheduling/scheduler.d.ts +3 -1
  163. package/dist/domain/scheduling/scheduler.js +22 -21
  164. package/dist/domain/sessions/session-hooks.d.ts +5 -4
  165. package/dist/domain/sessions/session-hooks.js +15 -33
  166. package/dist/domain/sessions/session-lifecycle.d.ts +19 -51
  167. package/dist/domain/sessions/session-lifecycle.js +34 -96
  168. package/dist/domain/system/doctor.d.ts +3 -3
  169. package/dist/domain/system/doctor.js +22 -26
  170. package/dist/domain/system/own-bin-path.d.ts +13 -0
  171. package/dist/domain/system/own-bin-path.js +36 -0
  172. package/dist/domain/system/terminal-cli/index.d.ts +58 -0
  173. package/dist/domain/system/terminal-cli/index.js +100 -0
  174. package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
  175. package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
  176. package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
  177. package/dist/domain/system/terminal-cli/registrar.js +1 -0
  178. package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
  179. package/dist/domain/system/terminal-cli/shims.js +108 -0
  180. package/dist/domain/system/terminal-cli/state.d.ts +7 -0
  181. package/dist/domain/system/terminal-cli/state.js +36 -0
  182. package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
  183. package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
  184. package/dist/domain/tui-session/tui-session-service.js +1 -1
  185. package/dist/domain/tui-session/types.d.ts +2 -2
  186. package/dist/domain/ui-service/app-router.d.ts +49 -71
  187. package/dist/domain/ui-service/app-router.js +9 -13
  188. package/dist/domain/ui-service/assistant-snapshots.js +2 -0
  189. package/dist/domain/ui-service/contract.parity.d.ts +19 -0
  190. package/dist/domain/ui-service/contract.parity.js +1 -0
  191. package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
  192. package/dist/domain/ui-service/inline-media-types.js +1 -0
  193. package/dist/domain/ui-service/input-schemas.d.ts +52 -115
  194. package/dist/domain/ui-service/input-schemas.js +38 -84
  195. package/dist/domain/ui-service/mutate/auth.d.ts +1 -1
  196. package/dist/domain/ui-service/mutate/auth.js +3 -2
  197. package/dist/domain/ui-service/mutate/config.d.ts +0 -8
  198. package/dist/domain/ui-service/mutate/config.js +0 -22
  199. package/dist/domain/ui-service/mutate/models.d.ts +13 -0
  200. package/dist/domain/ui-service/mutate/models.js +137 -0
  201. package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
  202. package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
  203. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -2
  204. package/dist/domain/ui-service/mutate/sessions.js +29 -126
  205. package/dist/domain/ui-service/query/config.js +22 -42
  206. package/dist/domain/ui-service/query/models.js +2 -2
  207. package/dist/domain/ui-service/query/schedules.js +1 -1
  208. package/dist/domain/ui-service/query/sessions.js +7 -13
  209. package/dist/domain/ui-service/types.d.ts +51 -177
  210. package/dist/domain/ui-service/ui-service.d.ts +23 -49
  211. package/dist/domain/ui-service/ui-service.js +8 -6
  212. package/dist/entry/app.js +42 -19
  213. package/dist/entry/browser-cli.d.ts +39 -0
  214. package/dist/entry/browser-cli.js +317 -0
  215. package/dist/entry/cli-help.d.ts +1 -0
  216. package/dist/entry/cli-help.js +37 -6
  217. package/dist/entry/cli.js +16 -14
  218. package/dist/entry/daemon.js +2 -0
  219. package/dist/entry/init-auth.js +1 -1
  220. package/dist/entry/init.d.ts +7 -8
  221. package/dist/entry/init.js +89 -249
  222. package/dist/entry/path-cli.d.ts +4 -0
  223. package/dist/entry/path-cli.js +65 -0
  224. package/dist/entry/schedule-cli.js +13 -6
  225. package/dist/entry/shutdown.d.ts +1 -1
  226. package/dist/entry/shutdown.js +8 -1
  227. package/dist/entry/start-ui-http.js +8 -0
  228. package/dist/entry/ui-service-wiring.js +8 -10
  229. package/dist/events/event-types.d.ts +3 -2
  230. package/dist/orchestration/agent-runner.d.ts +2 -2
  231. package/dist/orchestration/agent-runner.js +10 -9
  232. package/dist/orchestration/benchmark-session-webhook.js +13 -1
  233. package/dist/orchestration/browser-webhook.d.ts +11 -0
  234. package/dist/orchestration/browser-webhook.js +28 -0
  235. package/dist/orchestration/cache-keep-warm.d.ts +77 -0
  236. package/dist/orchestration/cache-keep-warm.js +213 -0
  237. package/dist/orchestration/claude-window-warmup.d.ts +40 -0
  238. package/dist/orchestration/claude-window-warmup.js +126 -0
  239. package/dist/orchestration/conversation-request.d.ts +6 -10
  240. package/dist/orchestration/conversation-request.js +5 -23
  241. package/dist/orchestration/delta-coalescer.d.ts +4 -2
  242. package/dist/orchestration/delta-coalescer.js +5 -5
  243. package/dist/orchestration/edit-retry.js +9 -11
  244. package/dist/orchestration/inline-media-eager.d.ts +13 -0
  245. package/dist/orchestration/inline-media-eager.js +58 -0
  246. package/dist/orchestration/inline-media.d.ts +22 -0
  247. package/dist/orchestration/inline-media.js +151 -0
  248. package/dist/orchestration/interactions/ask-user-resume.js +3 -7
  249. package/dist/orchestration/interactions/interaction-handlers.js +6 -6
  250. package/dist/orchestration/mid-turn-inject.d.ts +2 -1
  251. package/dist/orchestration/mid-turn-inject.js +1 -1
  252. package/dist/orchestration/pending-injection-recovery.d.ts +2 -1
  253. package/dist/orchestration/pending-injection-recovery.js +1 -1
  254. package/dist/orchestration/routing/commands/index.js +4 -4
  255. package/dist/orchestration/routing/commands/mode.d.ts +5 -44
  256. package/dist/orchestration/routing/commands/mode.js +98 -272
  257. package/dist/orchestration/routing/commands/schedule.js +29 -18
  258. package/dist/orchestration/routing/commands/session.js +9 -9
  259. package/dist/orchestration/routing/commands/status.js +1 -1
  260. package/dist/orchestration/routing/commands/usage-format.js +3 -0
  261. package/dist/orchestration/routing/webhook.js +4 -0
  262. package/dist/orchestration/session-compact.d.ts +0 -1
  263. package/dist/orchestration/session-compact.js +5 -7
  264. package/dist/orchestration/session-events.d.ts +2 -1
  265. package/dist/orchestration/session-events.js +1 -0
  266. package/dist/orchestration/status-helpers.d.ts +0 -4
  267. package/dist/orchestration/status-helpers.js +0 -18
  268. package/dist/orchestration/subagent-webhook.js +9 -34
  269. package/dist/orchestration/team-webhook.d.ts +8 -9
  270. package/dist/orchestration/team-webhook.js +16 -42
  271. package/dist/orchestration/transcript-sink.d.ts +6 -0
  272. package/dist/orchestration/transcript-sink.js +21 -2
  273. package/dist/orchestration/turn/terminal.js +7 -7
  274. package/dist/orchestration/turn/turn-prep.d.ts +0 -8
  275. package/dist/orchestration/turn/turn-prep.js +0 -51
  276. package/dist/orchestration/turn/turn-tracking.d.ts +2 -2
  277. package/dist/orchestration/turn/turn-tracking.js +8 -5
  278. package/dist/orchestration/turn/turn.d.ts +0 -2
  279. package/dist/orchestration/turn/turn.js +13 -15
  280. package/dist/platform/adapters/tui/ports.d.ts +1 -1
  281. package/dist/platform/adapters/tui/tui-transcript.js +2 -0
  282. package/dist/platform/browser/agent-browser.d.ts +50 -0
  283. package/dist/platform/browser/agent-browser.js +165 -0
  284. package/dist/platform/browser/managed-browser.d.ts +1 -11
  285. package/dist/platform/browser/managed-browser.js +4 -12
  286. package/dist/platform/ui-http/browser-stream.d.ts +110 -0
  287. package/dist/platform/ui-http/browser-stream.js +447 -0
  288. package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
  289. package/dist/platform/ui-http/ui-http-server.js +23 -6
  290. package/dist/store/conversation-history-reader.js +8 -0
  291. package/dist/store/conversation-history-repo.d.ts +8 -1
  292. package/dist/store/conversation-history-repo.js +5 -0
  293. package/dist/store/conversation-ledger-repo.d.ts +6 -6
  294. package/dist/store/conversation-ledger-repo.js +4 -4
  295. package/dist/store/models-repo.d.ts +18 -0
  296. package/dist/store/models-repo.js +74 -0
  297. package/dist/store/pending-injection-repo.d.ts +2 -1
  298. package/dist/store/pending-injection-repo.js +3 -1
  299. package/dist/store/retire-profiles-migration.d.ts +28 -0
  300. package/dist/store/retire-profiles-migration.js +335 -0
  301. package/dist/store/schedule-repo.d.ts +2 -1
  302. package/dist/store/session-registry-import.js +3 -2
  303. package/dist/store/session-registry-journal.d.ts +10 -13
  304. package/dist/store/session-registry-journal.js +48 -25
  305. package/dist/store/session-registry-repo.d.ts +4 -4
  306. package/dist/store/session-registry-repo.js +4 -5
  307. package/dist/store/version-migrations.d.ts +2 -3
  308. package/dist/store/version-migrations.js +19 -3
  309. package/dist/tui/slash-commands.js +2 -2
  310. package/dist/tui/turn-status.js +1 -1
  311. package/package.json +6 -4
  312. package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
  313. package/web/dist/assets/index-CaSZPg_H.css +1 -0
  314. package/web/dist/assets/index-CzOR7Edh.js +522 -0
  315. package/web/dist/assets/{index-CndZZ1IQ.js → index-cIGFv27z.js} +1 -1
  316. package/web/dist/index.html +3 -2
  317. package/web/dist/theme.css +6 -0
  318. package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
  319. package/dist/agent-adapter/browser-mcp-server.js +0 -28
  320. package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
  321. package/dist/agent-adapter/claude/browser-mcp.js +0 -10
  322. package/dist/core/profile-generator.d.ts +0 -79
  323. package/dist/core/profile-generator.js +0 -215
  324. package/dist/domain/agents/profile-manager.d.ts +0 -103
  325. package/dist/domain/agents/profile-manager.js +0 -286
  326. package/dist/domain/agents/profile-switch.d.ts +0 -49
  327. package/dist/domain/agents/profile-switch.js +0 -62
  328. package/dist/domain/ui-service/mutate/profiles.d.ts +0 -36
  329. package/dist/domain/ui-service/mutate/profiles.js +0 -151
  330. package/dist/store/profile-repo.d.ts +0 -20
  331. package/dist/store/profile-repo.js +0 -97
  332. package/web/dist/assets/index-B76ueW3q.js +0 -494
  333. package/web/dist/assets/index-C8O0yxg8.css +0 -1
@@ -15,23 +15,43 @@ export function parseModelFallbackEvent(raw) {
15
15
  return { type: 'model_fallback', originalModel, fallbackModel };
16
16
  }
17
17
  export function createStreamDeltaState() {
18
- return { messageId: null, model: null, textBlockId: null };
18
+ return { messageId: null, model: null, textBlockId: null, thinkingBlockId: null };
19
19
  }
20
20
  function observeMessageStart(event, state) {
21
21
  state.messageId = typeof event.message?.id === 'string' ? event.message.id : null;
22
22
  state.model = typeof event.message?.model === 'string' ? event.message.model : null;
23
23
  state.textBlockId = null;
24
+ state.thinkingBlockId = null;
24
25
  }
25
26
  function observeBlockStart(event, state) {
26
- if (event.content_block?.type !== 'text' || !state.messageId)
27
- return;
28
- if (typeof event.index !== 'number')
27
+ if (!state.messageId || typeof event.index !== 'number')
29
28
  return;
30
- state.textBlockId = `${state.messageId}:${event.index}`;
29
+ const blockId = `${state.messageId}:${event.index}`;
30
+ if (event.content_block?.type === 'text')
31
+ state.textBlockId = blockId;
32
+ if (event.content_block?.type === 'thinking')
33
+ state.thinkingBlockId = blockId;
31
34
  }
32
- /** Translate a partial stdout event into one text delta while advancing the message cursor. */
35
+ function parseBlockDelta(event, state) {
36
+ const kind = event.delta?.type;
37
+ if (kind !== 'text_delta' && kind !== 'thinking_delta')
38
+ return null;
39
+ const text = kind === 'thinking_delta' ? event.delta.thinking : event.delta.text;
40
+ if (typeof text !== 'string' || text.length === 0)
41
+ return null;
42
+ if (!state.messageId || typeof event.index !== 'number')
43
+ return null;
44
+ const blockId = `${state.messageId}:${event.index}`;
45
+ if (kind === 'thinking_delta') {
46
+ state.thinkingBlockId = blockId;
47
+ return { kind: 'thinking', text, blockId };
48
+ }
49
+ state.textBlockId = blockId;
50
+ return { text, blockId };
51
+ }
52
+ /** Translate a partial stdout event while advancing only its own block cursor. */
33
53
  export function parseStreamEvent(data, state) {
34
- if (!data || data.type !== 'stream_event')
54
+ if (!data || data.type !== 'stream_event' || data.parent_tool_use_id)
35
55
  return null;
36
56
  const event = data.event;
37
57
  if (!event || typeof event.type !== 'string')
@@ -44,16 +64,7 @@ export function parseStreamEvent(data, state) {
44
64
  observeBlockStart(event, state);
45
65
  return null;
46
66
  }
47
- if (event.type !== 'content_block_delta' || event.delta?.type !== 'text_delta')
48
- return null;
49
- const text = event.delta.text;
50
- if (typeof text !== 'string' || text.length === 0)
51
- return null;
52
- if (!state.messageId || typeof event.index !== 'number')
53
- return null;
54
- const blockId = `${state.messageId}:${event.index}`;
55
- state.textBlockId = blockId;
56
- return { text, blockId };
67
+ return event.type === 'content_block_delta' ? parseBlockDelta(event, state) : null;
57
68
  }
58
69
  /**
59
70
  * Consume the blockId of the streamed text block that the complete `assistant` event now being
@@ -68,6 +79,11 @@ export function takeTextBlockId(state) {
68
79
  state.textBlockId = null;
69
80
  return id;
70
81
  }
82
+ export function takeThinkingBlockId(state) {
83
+ const id = state.thinkingBlockId;
84
+ state.thinkingBlockId = null;
85
+ return id;
86
+ }
71
87
  export function formatAssistantEvent(data) {
72
88
  const parts = [];
73
89
  for (const block of (data.message?.content || [])) {
@@ -22,6 +22,8 @@ export interface ClaudeTurnCallbacks {
22
22
  onProgress?: ((progress: any) => void) | null;
23
23
  onAssistantMessage?: ((text: string, blockId?: string, model?: string | null, subagent?: ToolUseSubagent) => void) | null;
24
24
  onAssistantDelta?: ((text: string, blockId: string) => void) | null;
25
+ onAssistantThinking?: ((text: string, blockId?: string) => void) | null;
26
+ onAssistantThinkingDelta?: ((text: string, blockId: string) => void) | null;
25
27
  onToolUse?: ((name: string, input: any, toolUseId: string, subagent?: ToolUseSubagent) => void) | null;
26
28
  onToolResult?: ((toolUseId: string, content: string, isError: boolean, subagent?: ToolUseSubagent, images?: ToolResultImage[]) => void) | null;
27
29
  onCompact?: ((info: {
@@ -28,6 +28,8 @@ export function claudeTurnCallbacks(push) {
28
28
  // Token-level preview of the block above. Same FIFO stream, so every delta is delivered
29
29
  // before the complete message that supersedes it.
30
30
  onAssistantDelta: (text, blockId) => push({ type: 'assistant_delta', text, blockId }),
31
+ onAssistantThinking: (text, blockId) => push({ type: 'assistant_thinking', text, ...(blockId ? { blockId } : {}) }),
32
+ onAssistantThinkingDelta: (text, blockId) => push({ type: 'assistant_thinking_delta', text, blockId }),
31
33
  onToolUse: (name, input, toolUseId, subagent) => {
32
34
  push({ type: 'tool_use', toolUseId, name, input, ...(subagent ? { subagent } : {}) });
33
35
  // Derived semantic event alongside the raw call (cf. plan_written /
@@ -1,5 +1,4 @@
1
- import type { AgentProcessSpawner, EngineSpec, McpComposition } from '../types.js';
2
- import { type CortexAgentContext } from './spawn-args.js';
1
+ import type { AgentProcessSpawner, CortexContextEnv, EngineSpec, McpComposition } from '../types.js';
3
2
  /** What a Claude session runs with: one EngineSpec, translated once. Every (re)spawn of the
4
3
  * session's process reads this same object, and the pool identity is computed from it. */
5
4
  export interface ClaudeSessionOptions {
@@ -16,8 +15,8 @@ export interface ClaudeSessionOptions {
16
15
  tools?: string | null;
17
16
  pluginDirs?: string[] | null;
18
17
  anthropicBaseUrl?: string;
19
- extraEnv?: Record<string, string>;
20
- /** Keys deleted from the child env after `extraEnv` is applied (EngineSpec.env.unsets). */
18
+ routeEnv?: Record<string, string>;
19
+ /** Keys deleted from the child env after route environment is applied (EngineSpec.env.unsets). */
21
20
  unsetEnv?: string[];
22
21
  /** Resolved spawn cwd; also where the transcript lives. */
23
22
  cwd: string;
@@ -26,10 +25,6 @@ export interface ClaudeSessionOptions {
26
25
  mcpToolAllowlist?: string[];
27
26
  supplementalMcpConfigPath?: string | null;
28
27
  supplementalMcpConfigIdentity?: string | null;
29
- /** Playwright MCP config for a browser-enabled session. Kept separate from the supplemental
30
- * (plugin) config because a session can legitimately have both. */
31
- browserMcpConfigPath?: string | null;
32
- browserMcpConfigIdentity?: string | null;
33
28
  pluginCapabilityFingerprint?: string | null;
34
29
  disableHooks?: boolean;
35
30
  /** Drop the CLI's whole skill layer; see {@link ClaudeSpawnOptions.disableSkills}. */
@@ -43,13 +38,11 @@ export interface ClaudeSessionOptions {
43
38
  cliPath?: string;
44
39
  /** Exact allowlisted child environment for an isolated process. */
45
40
  pinnedEnv?: NodeJS.ProcessEnv;
46
- /** Extra CLI options from profile (e.g. {"--thinking": "xhigh"}). */
47
- extraOption?: Record<string, string>;
48
- /** Thinking level from the profile's `thinking` field → `--effort <level>`. Absent → no flag. */
41
+ /** Selected thinking level → `--effort <level>`. Absent → no flag. */
49
42
  thinking?: string | null;
50
- /** Cortex execution context surfaced to the MCP server child as CORTEX_PROFILE/PROJECT/SESSION_NAME env vars.
43
+ /** Cortex execution identity and engine selection surfaced to the MCP server child as env vars.
51
44
  * Captured at spawn time; later turns on the same session reuse the original snapshot. */
52
- context?: CortexAgentContext;
45
+ context?: CortexContextEnv;
53
46
  }
54
47
  /** One launch of a session's process: which transcript, whether it resumes, and the options. */
55
48
  export interface ClaudeLaunchInput {
@@ -5,7 +5,6 @@ import { encodeMcpBundles, MCP_BUNDLES_ENV } from '../../core/mcp-bundles.js';
5
5
  import { resolveMcpComposition } from '../types.js';
6
6
  import { buildClaudeEnv, buildSpawnArgs, resolveClaudeMcpBundles, } from './spawn-args.js';
7
7
  import { writeClaudeSupplementalMcpConfig } from './mcp-config.js';
8
- import { writeBrowserMcpConfig } from './browser-mcp.js';
9
8
  /** The prompt and model half of the CLI options. An empty string reads as unset. */
10
9
  function promptSpawnOptions(options) {
11
10
  return {
@@ -16,7 +15,6 @@ function promptSpawnOptions(options) {
16
15
  claudeAgent: options.claudeAgent || null,
17
16
  pluginDirs: options.pluginDirs || null,
18
17
  outputStyle: options.outputStyle || null,
19
- extraOption: options.extraOption,
20
18
  thinking: options.thinking ?? null,
21
19
  };
22
20
  }
@@ -27,7 +25,6 @@ function surfaceSpawnOptions(options) {
27
25
  mcpConfigPaths: options.mcpConfigPaths,
28
26
  mcpToolAllowlist: options.mcpToolAllowlist,
29
27
  supplementalMcpConfigPath: options.supplementalMcpConfigPath ?? null,
30
- browserMcpConfigPath: options.browserMcpConfigPath ?? null,
31
28
  disableHooks: options.disableHooks === true,
32
29
  disableSkills: options.disableSkills === true,
33
30
  settingSources: options.settingSources,
@@ -59,7 +56,7 @@ function claudeSpawnOptions(launch) {
59
56
  export function claudeProcessLaunch(launch) {
60
57
  const spawnOptions = claudeSpawnOptions(launch);
61
58
  const { options } = launch;
62
- const env = buildClaudeEnv(launch.channel, launch.sessionId, options.callbackSource || null, options.scheduleTaskId || null, options.anthropicBaseUrl, options.extraEnv, options.context, options.pinnedEnv, options.unsetEnv);
59
+ const env = buildClaudeEnv(launch.channel, launch.sessionId, options.callbackSource || null, options.scheduleTaskId || null, options.anthropicBaseUrl, options.routeEnv, options.context, options.pinnedEnv, options.unsetEnv);
63
60
  env[MCP_BUNDLES_ENV] = encodeMcpBundles(resolveClaudeMcpBundles(spawnOptions));
64
61
  return { args: buildSpawnArgs(spawnOptions), env };
65
62
  }
@@ -108,14 +105,9 @@ function sessionPresentationOptions(spec) {
108
105
  }
109
106
  function sessionRuntimeOptions(spec, composition) {
110
107
  const supplemental = supplementalMcpConfig(spec, composition);
111
- // Browser tools ride on the direct composition only: an agent configured with composition
112
- // `none` gets no Cortex MCP servers, the browser included.
113
- const browser = spec.mcp.browserCdpEndpoint && composition === 'direct'
114
- ? writeBrowserMcpConfig(spec.mcp.browserCdpEndpoint)
115
- : null;
116
108
  return {
117
109
  anthropicBaseUrl: spec.route.anthropicBaseUrl,
118
- extraEnv: spec.env.sets,
110
+ routeEnv: spec.env.sets,
119
111
  unsetEnv: spec.env.unsets,
120
112
  cwd: resolveSpawnCwd(spec.cwd),
121
113
  mcpComposition: composition,
@@ -123,8 +115,6 @@ function sessionRuntimeOptions(spec, composition) {
123
115
  mcpToolAllowlist: spec.mcp.allowlist,
124
116
  supplementalMcpConfigPath: supplemental?.path ?? null,
125
117
  supplementalMcpConfigIdentity: supplemental?.identity ?? null,
126
- browserMcpConfigPath: browser?.path ?? null,
127
- browserMcpConfigIdentity: browser?.identity ?? null,
128
118
  pluginCapabilityFingerprint: spec.plugins.fingerprint ?? null,
129
119
  disableHooks: spec.flags.disableHooks,
130
120
  disableSkills: spec.flags.disableSkills,
@@ -134,7 +124,6 @@ function sessionRuntimeOptions(spec, composition) {
134
124
  processSpawner: spec.process.spawner,
135
125
  cliPath: spec.process.cliPath,
136
126
  pinnedEnv: spec.env.pinned,
137
- extraOption: spec.extraOption,
138
127
  context: spec.env.context,
139
128
  };
140
129
  }
@@ -1,5 +1,5 @@
1
1
  import type { McpBundleName } from '../../core/mcp-bundles.js';
2
- import type { McpComposition } from '../types.js';
2
+ import type { CortexContextEnv, McpComposition } from '../types.js';
3
3
  export interface ClaudeSpawnOptions {
4
4
  tools: string | null;
5
5
  systemPrompt?: string | null;
@@ -35,14 +35,9 @@ export interface ClaudeSpawnOptions {
35
35
  loadFeishuMcp?: boolean;
36
36
  /** Select Web tools in the bundled server for Web-originated direct sessions. */
37
37
  loadWebMcp?: boolean;
38
- /** Path to a Playwright MCP config for a browser-enabled session. Absent → the session gets zero
39
- * browser tools, which is the default and the reason this is opt-in at all. */
40
- browserMcpConfigPath?: string | null;
41
- /** Thinking level from the profile's `thinking` field → `--effort <level>`
38
+ /** Selected thinking level → `--effort <level>`
42
39
  * (low/medium/high/xhigh/max). Absent → no flag. */
43
40
  thinking?: string | null;
44
- /** Extra CLI options from profile (e.g. {"--thinking": "xhigh"}). */
45
- extraOption?: Record<string, string> | null;
46
41
  /** True for conversation turns (not subagents or the onNew pre-close turn). Such
47
42
  * sessions additionally get the cortex-interaction-bridge MCP tools
48
43
  * (cortex_plan_enter/exit, cortex_ask_user) because the native EnterPlanMode/ExitPlanMode/
@@ -57,23 +52,11 @@ export interface ClaudeSpawnOptions {
57
52
  export declare function isStreamDeltasEnabled(): boolean;
58
53
  export declare function resolveClaudeMcpBundles(options: ClaudeSpawnOptions): McpBundleName[];
59
54
  export declare function buildSpawnArgs(options: ClaudeSpawnOptions): string[];
60
- /** Cortex agent execution context — surfaces as CORTEX_* env vars so MCP tools
61
- * such as cortex_context can discover the current session/profile/etc.
62
- * Optional fields are omitted from env when undefined, so child processes see no key
63
- * rather than an empty string. */
64
- export interface CortexAgentContext {
65
- profile?: string | null;
66
- project?: string | null;
67
- /** Stable Cortex tracking id (decoupled from the backend session id) → CORTEX_SESSION_ID. */
68
- trackSessionId?: string | null;
69
- /** Cortex execution record id, surfaced as CORTEX_EXECUTION_ID to subprocess env. */
70
- executionId?: string | null;
71
- }
72
55
  /** The three per-spawn channels that decide where a child sends its requests and with which
73
56
  * credential: the dedicated base-URL field, the env overrides, and the env deletions. */
74
57
  export interface ClaudeRouteInputs {
75
58
  anthropicBaseUrl?: string;
76
- extraEnv?: Record<string, string>;
59
+ routeEnv?: Record<string, string>;
77
60
  unsetEnv?: string[];
78
61
  }
79
62
  /** Identity of the route this spawn would take: the endpoint verbatim (not a secret, and worth
@@ -84,4 +67,4 @@ export declare function claudeRouteIdentity(route: ClaudeRouteInputs): string;
84
67
  /** The provider/model catalogs the MCP sidecar offers subagents, read from the daemon's caches.
85
68
  * Shared by Claude spawns and the injected PI session snapshot getter. */
86
69
  export declare function subagentModelEnv(): Record<string, string>;
87
- export declare function buildClaudeEnv(channel: string, sessionId: string, callbackSource?: string | null, scheduleTaskId?: string | null, anthropicBaseUrl?: string, extraEnv?: Record<string, string>, context?: CortexAgentContext, pinnedEnv?: NodeJS.ProcessEnv, unsetEnv?: string[]): NodeJS.ProcessEnv;
70
+ export declare function buildClaudeEnv(channel: string, sessionId: string, callbackSource?: string | null, scheduleTaskId?: string | null, anthropicBaseUrl?: string, routeEnv?: Record<string, string>, context?: CortexContextEnv, pinnedEnv?: NodeJS.ProcessEnv, unsetEnv?: string[]): NodeJS.ProcessEnv;
@@ -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
+ }