@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
@@ -5,7 +5,6 @@ import { compactAgentContext, isSessionCompactionSupported } from '../domain/run
5
5
  import { conduitQueues, enqueueAndWait } from './conduit-queue.js';
6
6
  import { conversationEngineRequest } from './conversation-request.js';
7
7
  import { publishSessionContextCompacted } from './session-events.js';
8
- import { withTurnBrowser } from './turn/turn-prep.js';
9
8
  const defaultDeps = {
10
9
  sessions: sessionStore,
11
10
  engineBusy: (session) => channelEngineBusy(session.channel, session.sessionId),
@@ -20,22 +19,21 @@ const defaultDeps = {
20
19
  };
21
20
  /**
22
21
  * Compaction asks the pool for the session's engine exactly as the session's next turn would: the
23
- * same request (agent, profile, policy, route) and the same browser, held for the command. Anything
24
- * else is a different identity, and the pool would respawn the process — compacting a fresh one
25
- * and leaving the next turn to respawn it again.
22
+ * same request (agent, selection, policy, route). Anything else is a different identity, and the pool
23
+ * would respawn the process — compacting a fresh one and leaving the next turn to respawn it again.
26
24
  */
27
25
  function compactLiveEngine(session, backendSessionId) {
28
26
  const { backend, channel } = session;
29
- return withTurnBrowser({ backend, browser: session.browser ?? null }, (cdpEndpoint) => compactAgentContext({
27
+ return compactAgentContext({
30
28
  backend: backend,
31
29
  request: conversationEngineRequest({
32
30
  ids: {
33
31
  sessionId: session.sessionId, backendSessionId,
34
32
  projectId: session.projectId ?? 'general',
35
33
  },
36
- channel, session, browserCdpEndpoint: cdpEndpoint, trigger: 'manual-compact',
34
+ channel, session, trigger: 'manual-compact',
37
35
  }),
38
- }));
36
+ });
39
37
  }
40
38
  function currentUsage(session) {
41
39
  return session.contextUsage ?? null;
@@ -7,7 +7,7 @@ export interface SessionMessagePayload {
7
7
  sessionId: string;
8
8
  channel: string;
9
9
  /** `worker-progress`: a team worker's interim reply, shown in its lead's chat (see `worker`). */
10
- role: 'user' | 'assistant' | 'tool' | 'worker-progress';
10
+ role: 'user' | 'assistant' | 'thinking' | 'tool' | 'worker-progress';
11
11
  text: string;
12
12
  /** User messages only: Cortex authored this turn (resume signal, backgrounded agent result,
13
13
  * waitpoint signal, team hand-off) rather than a human. Chat surfaces render it as a hint
@@ -102,6 +102,7 @@ export declare function publishSessionMessageDelta(p: {
102
102
  text: string;
103
103
  /** 0-based, per blockId; lets a client notice it missed one. */
104
104
  seq: number;
105
+ kind?: 'thinking';
105
106
  }): void;
106
107
  /** Emit a `session.message.delivered` event: a message injected into a turn already in flight has
107
108
  * now been consumed by the model (or its injection window closed without that happening). The
@@ -63,6 +63,7 @@ export function publishSessionMessageDelta(p) {
63
63
  blockId: p.blockId,
64
64
  text: p.text,
65
65
  seq: p.seq,
66
+ ...(p.kind ? { kind: p.kind } : {}),
66
67
  });
67
68
  }
68
69
  /** Emit a `session.message.delivered` event: a message injected into a turn already in flight has
@@ -3,10 +3,6 @@ export { computeElapsed, formatMetricsSuffix, buildUserProcessingMessage, render
3
3
  /** Feature gate: the "New (quiet)" status button (=!newq, skips the pre-close hook). */
4
4
  export declare function isStatusNewqButtonEnabled(): boolean;
5
5
  export declare function buildExecutionStatusReport(): string;
6
- /** Report an attempt switch on the status message, from the already-rendered `model/mode` labels.
7
- * The run layer reports a fallback as two labels (`RunEvent.run_fallback`); the callback below
8
- * renders the same labels out of a pair of attempt configs. */
9
- export declare function makeFallbackLabelNotifier(statusMsg: MessageRef | null, adapter: PlatformAdapter): (fromLabel: string, toLabel: string, reason: 'rate-limited' | 'transport-error') => Promise<void>;
10
6
  /** Build a streaming callback that aggregates assistant messages via OutputStream. */
11
7
  export declare function makeStreamingMessageCallback(adapter: PlatformAdapter, destination: Destination, threadAnchorId?: string | null, onMessagePosted?: ((ref: MessageRef) => void) | null, durable?: import('../platform/types.js').DurableHooks | null): ((text: string) => void) & {
12
8
  stream: OutputStream;
@@ -1,6 +1,5 @@
1
1
  import { createLogger } from '../core/log.js';
2
2
  import { getSettings } from '../core/settings.js';
3
- import { Icons } from '../core/icons.js';
4
3
  import { t } from '../core/i18n.js';
5
4
  import * as executionRegistry from '../domain/executions/registry.js';
6
5
  import { durableUpdate, getOutboundQueue } from '../store/outbound-queue.js';
@@ -22,23 +21,6 @@ export function buildExecutionStatusReport() {
22
21
  }
23
22
  return lines.join('\n');
24
23
  }
25
- /** Report an attempt switch on the status message, from the already-rendered `model/mode` labels.
26
- * The run layer reports a fallback as two labels (`RunEvent.run_fallback`); the callback below
27
- * renders the same labels out of a pair of attempt configs. */
28
- export function makeFallbackLabelNotifier(statusMsg, adapter) {
29
- return async (fromLabel, toLabel, reason) => {
30
- log.info(`Fallback (${reason}): ${fromLabel} \u2192 ${toLabel}`);
31
- if (statusMsg) {
32
- const key = reason === 'rate-limited' ? 'notice.fallback.rateLimited' : 'notice.fallback.transportError';
33
- try {
34
- await adapter.updateMessage(statusMsg, {
35
- text: `${Icons.warning} ${t(key, { from: fromLabel, to: `*${toLabel}*` })}`,
36
- });
37
- }
38
- catch { }
39
- }
40
- };
41
- }
42
24
  /** Build a streaming callback that aggregates assistant messages via OutputStream. */
43
25
  export function makeStreamingMessageCallback(adapter, destination, threadAnchorId = null, onMessagePosted = null, durable) {
44
26
  const stream = adapter.openOutputStream(destination, { threadId: threadAnchorId, onMessagePosted, durable: durable ?? null });
@@ -1,47 +1,22 @@
1
- import { createLogger } from '../core/log.js';
2
- import { resolveProfileConfig } from '../domain/agents/profile-manager.js';
1
+ import { sessionStore } from '../store/session-registry-repo.js';
3
2
  import { detachSubagentRun, stopSubagentRun, waitForSubagentRun, } from '../domain/agents/subagent/registry.js';
4
3
  import { startDaemonSubagentRun } from '../domain/agents/subagent/service.js';
5
4
  import { adoptForegroundRun, settleAdoptedRun } from './subagent-adopt.js';
6
5
  import { backgroundNoticeSink, parentNoticeSink } from './subagent-attribution.js';
7
6
  import { startBackgroundSubagentRun } from './subagent-delivery.js';
8
- import { resolveRunConfig } from '../domain/runs/config-resolver.js';
9
- const log = createLogger('subagent-webhook');
10
- /**
11
- * The delegating session's own routing, reconstructed from what its MCP sidecar knows about it.
12
- *
13
- * The profile is read only to learn what the PARENT is running — it never selects the child, which
14
- * takes its model from the task or the role. When there is no profile the daemon's current Claude
15
- * model and mode stand in, which is the same pair an unprofiled turn would have used.
16
- */
17
- function parentContextFor(data) {
7
+ import { resolveRunSelection } from '../domain/runs/config-resolver.js';
8
+ /** The parent's materialized choice supplies routing, not the child's task/role model. */
9
+ async function parentContextFor(data) {
18
10
  const channel = typeof data.channel === 'string' ? data.channel : undefined;
19
- // D5: with no profile named, the parent's routing is whatever that channel's next run would
20
- // use — the same profile, resolved the same way, instead of three retired global getters.
21
- const channelDefault = resolveRunConfig({ channel }).profile;
22
- const profile = resolveProfileSafely(data.profile) ?? channelDefault;
23
- const backend = (profile.backend ?? data.backend);
11
+ const sessionId = typeof data.sessionId === 'string' ? data.sessionId : null;
12
+ const session = sessionId ? await sessionStore.getById(sessionId) : null;
13
+ const selection = resolveRunSelection({ channel, session, selection: data.selection });
24
14
  return {
25
- backend,
26
- mode: profile.mode,
27
- provider: profile.provider ?? null,
28
- model: profile.model || null,
29
- channel,
15
+ ...selection, channel, sessionId,
30
16
  project: typeof data.project === 'string' ? data.project : undefined,
31
17
  env: process.env,
32
18
  };
33
19
  }
34
- function resolveProfileSafely(name) {
35
- if (typeof name !== 'string' || !name)
36
- return null;
37
- try {
38
- return resolveProfileConfig(name);
39
- }
40
- catch (error) {
41
- log.warn(`Subagent parent profile "${name}" could not be resolved: ${error.message}`);
42
- return null;
43
- }
44
- }
45
20
  function resultText(result) {
46
21
  return result?.content?.map(block => block.text).join('\n') || '(no output)';
47
22
  }
@@ -60,7 +35,7 @@ export async function handleSubagentWebhook(data) {
60
35
  const sessionId = typeof data.sessionId === 'string' && data.sessionId ? data.sessionId : null;
61
36
  try {
62
37
  if (data.action === 'start') {
63
- const parent = parentContextFor(data);
38
+ const parent = await parentContextFor(data);
64
39
  const background = !!data.background;
65
40
  const request = {
66
41
  params: data.params,
@@ -1,6 +1,7 @@
1
1
  import type { Backend } from '../core/types/agent-types.js';
2
2
  import { sessionStore } from '../store/session-registry-repo.js';
3
- import { type ApplySelectionRequest, type ApplySelectionResult, type ChannelSelection } from '../domain/agents/index.js';
3
+ import { applyChannelSelection } from '../domain/agents/index.js';
4
+ import type { EngineSelection } from '../domain/agents/engine-selection.js';
4
5
  import { type DeliverToSessionOptions } from './session-gateway.js';
5
6
  import { type InteractionRecords } from './interactions/interaction-records.js';
6
7
  import { type WorkerView } from './team-state.js';
@@ -12,12 +13,12 @@ export interface TeamWebhookReply {
12
13
  type Outcome = 'resolved' | 'already-resolved' | 'not-found';
13
14
  export interface TeamWebhookDeps {
14
15
  sessions: Pick<typeof sessionStore, 'getById' | 'listWorkers' | 'rename' | 'bindBoard'>;
15
- /** Creates the worker on a channel whose selection is already written. Naming the same profile
16
- * again only records it on the session; it leaves the channel's selection as written. */
16
+ /** Create the worker with its materialized choice without moving the user's draft seed. */
17
17
  createSession: (opts: {
18
18
  projectId: string;
19
19
  sessionId: string;
20
- profileName: string;
20
+ selection: EngineSelection;
21
+ seedDefault: false;
21
22
  teamLeadId: string;
22
23
  workerName: string;
23
24
  workerBrief: string;
@@ -34,11 +35,9 @@ export interface TeamWebhookDeps {
34
35
  }) => Promise<void>;
35
36
  deliver: (opts: Pick<DeliverToSessionOptions, 'channel' | 'text' | 'origin'>) => void;
36
37
  cancel: (channel: string) => Promise<number>;
37
- readSelection: (channel: string) => ChannelSelection;
38
- defaultProfile: (backend: Backend) => string | null;
39
- /** The PI profile configured for a provider, if any. */
40
- providerProfile: (provider: string) => string | null;
41
- applySelection: (request: ApplySelectionRequest) => Promise<ApplySelectionResult>;
38
+ readSelection: (channel: string) => EngineSelection;
39
+ defaultSelection: (backend: Backend) => EngineSelection | null;
40
+ applySelection: typeof applyChannelSelection;
42
41
  interactions: Pick<InteractionRecords, 'get'>;
43
42
  answerQuestion: (requestId: string, answers: Record<string, string>) => Outcome;
44
43
  /** The question texts of a pending ask, or null when it has no live group. */
@@ -8,7 +8,7 @@ import { setSessionAsync } from '../domain/sessions/session.js';
8
8
  import { isTeamLead, isTeamWorker, MAX_RUNNING_WORKERS, WORKER_NAME_RE } from '../domain/sessions/team.js';
9
9
  import { sessionState } from '../core/session-state.js';
10
10
  import { applyChannelSelection, readChannelSelection, resolveBackendForChannel, } from '../domain/agents/index.js';
11
- import { findProfileForProvider, getDefaultProfileForBackend } from '../domain/agents/profile-manager.js';
11
+ import { getDefaultSelectionForBackend, resolveModelRef } from '../domain/agents/models.js';
12
12
  import { parseModelSpec } from '../core/agents/subagent/model-spec.js';
13
13
  import { isRebuildHeld } from '../domain/system/rebuild-hold.js';
14
14
  import { deliverToSessionDetached } from './session-gateway.js';
@@ -40,8 +40,7 @@ const defaultDeps = {
40
40
  deliver: (opts) => deliverToSessionDetached(opts),
41
41
  cancel: (channel) => cancelChannelRuns(channel),
42
42
  readSelection: (channel) => readChannelSelection(channel),
43
- defaultProfile: (backend) => getDefaultProfileForBackend(backend),
44
- providerProfile: (provider) => findProfileForProvider('pi', provider)?.name ?? null,
43
+ defaultSelection: getDefaultSelectionForBackend,
45
44
  applySelection: (request) => applyChannelSelection(request),
46
45
  interactions: interactionRecords,
47
46
  answerQuestion: (requestId, answers) => answerQuestion(requestId, answers, 'agent'),
@@ -93,51 +92,25 @@ function refuseWhileRestarting(deps, what) {
93
92
  function capError() {
94
93
  return new TeamError(`${MAX_RUNNING_WORKERS} workers are already running; wait for a report or stop one (worker_stop) first`);
95
94
  }
96
- /**
97
- * What a new worker runs: the lead's own profile and selection, unless the call names a backend or
98
- * model. `model` is the `agent` tool's `provider/model[:thinking]`; a field it gives replaces the
99
- * lead's, a field it omits keeps it. Another backend starts from that backend's default profile,
100
- * since none of the lead's choices mean anything there.
101
- */
95
+ /** Copy the lead's exact choice; another backend starts from its default or first favorite. */
102
96
  function resolveWorkerSelection(lead, data, deps) {
103
- const own = deps.readSelection(lead.channel);
97
+ const own = lead.selection ?? deps.readSelection(lead.channel);
104
98
  const requested = str(data.backend);
105
99
  if (requested && requested !== 'claude' && requested !== 'pi') {
106
100
  throw new TeamError('backend must be "claude" or "pi"');
107
101
  }
108
- const backend = requested || own.backend;
109
102
  const spec = parseModelSpec(str(data.model) || undefined);
110
- // A bare Claude model id has no provider segment; one written for PI is dropped, not smuggled in.
111
- if (backend === 'claude')
112
- delete spec.provider;
113
- // A PI provider with a profile of its own runs on that profile, as a pick in the composer does,
114
- // so its route and settings are the ones configured for it.
115
- const leavesProvider = spec.provider !== undefined && !(backend === own.backend && spec.provider === own.provider);
116
- const sibling = backend === 'pi' && leavesProvider ? deps.providerProfile(spec.provider) : null;
117
- if (sibling) {
118
- return { profileName: sibling, model: spec.model ?? null, provider: null, thinking: spec.thinking ?? null, mode: null };
119
- }
120
- if (backend === own.backend) {
121
- const base = own.override ?? {};
122
- // A route belongs to its provider's endpoint, so it does not survive a move to another one.
123
- const movesProvider = spec.provider !== undefined && spec.provider !== own.provider;
124
- return {
125
- profileName: own.profileName,
126
- model: spec.model ?? base.model ?? null,
127
- provider: spec.provider ?? base.provider ?? null,
128
- thinking: spec.thinking ?? base.thinking ?? null,
129
- mode: movesProvider ? null : base.mode ?? null,
130
- };
131
- }
132
- const profileName = deps.defaultProfile(backend);
133
- if (!profileName)
134
- throw new TeamError(`no profile is configured for the ${backend} backend`);
103
+ const backend = requested || (spec.provider ? 'pi' : own.backend);
104
+ const base = backend === own.backend ? own : deps.defaultSelection(backend);
105
+ if (!base)
106
+ throw new TeamError(`no default or favorite for the ${backend} backend; favorite a model first`);
107
+ const ref = spec.model ? resolveModelRef(spec.provider && backend === 'pi'
108
+ ? `${spec.provider}/${spec.model}` : spec.model, backend) : base;
109
+ const provider = backend === 'pi' ? (spec.provider ?? (backend === own.backend ? own.provider : ref.provider)) : null;
135
110
  return {
136
- profileName,
137
- model: spec.model ?? null,
138
- provider: spec.provider ?? null,
139
- thinking: spec.thinking ?? null,
140
- mode: null,
111
+ ...base, backend, provider, model: ref.model,
112
+ thinking: spec.thinking ?? base.thinking,
113
+ mode: backend === 'pi' && provider !== base.provider ? provider ?? base.mode : base.mode,
141
114
  };
142
115
  }
143
116
  async function spawn(lead, data, deps) {
@@ -167,7 +140,8 @@ async function spawn(lead, data, deps) {
167
140
  const created = await deps.createSession({
168
141
  projectId: lead.projectId,
169
142
  sessionId,
170
- profileName: applied.profileName,
143
+ selection: { backend: applied.backend, provider: applied.provider, model: applied.model, thinking: applied.thinking, mode: applied.mode },
144
+ seedDefault: false,
171
145
  teamLeadId: lead.sessionId,
172
146
  workerName: name,
173
147
  workerBrief: briefOf(prompt),
@@ -33,11 +33,17 @@ export interface TranscriptSinkDeps extends ToolImageDeps {
33
33
  appendToolResult: (sessionId: string, opts: Parameters<typeof conversationHistory.appendToolResult>[1]) => Promise<void>;
34
34
  appendSubagentEnd: (sessionId: string, opts: Parameters<typeof conversationHistory.appendSubagentEnd>[1]) => Promise<void>;
35
35
  appendAssistant: (sessionId: string, opts: Parameters<typeof conversationHistory.appendAssistant>[1]) => Promise<void>;
36
+ appendThinking: (sessionId: string, opts: Parameters<typeof conversationHistory.appendThinking>[1]) => Promise<void>;
36
37
  setTodos: (sessionId: string, snapshot: TodoSnapshot) => void;
37
38
  publishMessage: typeof publishSessionMessage;
38
39
  publishTodos: typeof publishSessionTodos;
39
40
  publishDebugUpdated: typeof publishSessionDebugUpdated;
40
41
  persistContextUsage: typeof persistSessionContextUsage;
42
+ snapshotMedia: (message: {
43
+ sessionId: string;
44
+ ts: string;
45
+ text: string;
46
+ }) => void;
41
47
  /** The worker that raised a request a lead's `worker_answer` names, when known. */
42
48
  workerForRequest: (requestId: string) => string | null;
43
49
  }
@@ -9,6 +9,7 @@ import { publishSessionContextUsage, publishSessionDebugUpdated, publishSessionM
9
9
  import { subagentPayloadFields, subagentRowRef } from './subagent-rows.js';
10
10
  import { writeToolImages } from '../store/tool-image-files.js';
11
11
  import { workerNameForRequest } from './team-state.js';
12
+ import { eagerSnapshotInlineMedia } from './inline-media-eager.js';
12
13
  const log = createLogger('transcript-sink');
13
14
  const defaultContextUsagePersistence = {
14
15
  now: () => new Date().toISOString(),
@@ -48,16 +49,20 @@ const DEFAULT_DEPS = {
48
49
  appendToolResult: (sessionId, opts) => conversationHistory.appendToolResult(sessionId, opts),
49
50
  appendSubagentEnd: (sessionId, opts) => conversationHistory.appendSubagentEnd(sessionId, opts),
50
51
  appendAssistant: (sessionId, opts) => conversationHistory.appendAssistant(sessionId, opts),
52
+ appendThinking: (sessionId, opts) => conversationHistory.appendThinking(sessionId, opts),
51
53
  setTodos: (sessionId, snapshot) => sessionTodos.set(sessionId, snapshot),
52
54
  publishMessage: publishSessionMessage,
53
55
  publishTodos: publishSessionTodos,
54
56
  publishDebugUpdated: publishSessionDebugUpdated,
55
57
  persistContextUsage: persistSessionContextUsage,
58
+ snapshotMedia: message => {
59
+ void eagerSnapshotInlineMedia(message).catch(error => log.warn('Inline media snapshot failed:', String(error)));
60
+ },
56
61
  workerForRequest: (requestId) => workerNameForRequest(requestId),
57
62
  };
58
63
  /** The event kinds this sink writes as transcript rows (context usage is stored beside them). */
59
64
  const ROW_EVENT_TYPES = new Set([
60
- 'assistant_text', 'tool_use', 'tool_result', 'todo_update', 'subagent_end', 'context_usage',
65
+ 'assistant_text', 'assistant_thinking', 'tool_use', 'tool_result', 'todo_update', 'subagent_end', 'context_usage',
61
66
  ]);
62
67
  /** A background-phase event this sink would write: what a hold or the injection ledger forwards. */
63
68
  export function isBackgroundRowEvent(event) {
@@ -140,6 +145,17 @@ export function createTranscriptSink(opts) {
140
145
  subagentId: parentToolUseId, subagentEnded: status,
141
146
  });
142
147
  }
148
+ function persistThinking(text, blockId) {
149
+ if (blockId)
150
+ opts.flushDelta?.(blockId);
151
+ if (!text)
152
+ return;
153
+ const ts = new Date().toISOString();
154
+ recordHistory(deps.appendThinking(sessionId, { text, ts, ...(blockId ? { blockId } : {}) }));
155
+ deps.publishMessage({
156
+ sessionId, channel, role: 'thinking', text, ts, ...(blockId ? { blockId } : {}),
157
+ });
158
+ }
143
159
  function persistAssistant(text, blockId, noticeLevel, noticeAction, subagent, phase) {
144
160
  // Drain this block's preview FIRST: the authoritative message must never be overtaken by
145
161
  // a delta still sitting in the coalescer, or the UI would replace the row and then append
@@ -165,7 +181,7 @@ export function createTranscriptSink(opts) {
165
181
  text, ts, noticeLevel, noticeAction,
166
182
  ...(ref ? { subagent: ref } : {}),
167
183
  ...(attributedSpawn ? { subagentSpawns: [attributedSpawn] } : {}),
168
- }));
184
+ }), () => deps.snapshotMedia({ sessionId, ts, text }));
169
185
  deps.publishMessage({
170
186
  sessionId, channel, role: 'assistant', text, ts,
171
187
  ...(blockId ? { blockId } : {}),
@@ -206,6 +222,9 @@ export function createTranscriptSink(opts) {
206
222
  if (event.phase === 'foreground')
207
223
  opts.onTodoUpdate?.(event.snapshot);
208
224
  return;
225
+ case 'assistant_thinking':
226
+ persistThinking(event.text, event.blockId);
227
+ return;
209
228
  case 'assistant_text':
210
229
  persistAssistant(event.text, event.blockId, event.noticeLevel, event.noticeAction, event.subagent, event.phase);
211
230
  return;
@@ -7,10 +7,10 @@ import { sessionStore } from '../../store/session-registry-repo.js';
7
7
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
8
8
  import { runMessageEndForTurn } from '../../domain/sessions/session-hooks.js';
9
9
  import * as askUserQuestion from '../interactions/ask-user-question.js';
10
- import { getActiveProfile, resolveBackendForChannel } from '../../domain/agents/index.js';
10
+ import { resolveRunSelection } from '../../domain/runs/config-resolver.js';
11
11
  import { maybeNotifyTurnComplete } from '../turn-notify.js';
12
12
  import { recordDirectResume } from '../../domain/runs/observers/resume-recorder.js';
13
- import { isApiRateLimitError, isNotRetriedFailure } from '../../domain/runs/retryable-errors.js';
13
+ import { isApiRateLimitError } from '../../domain/runs/retryable-errors.js';
14
14
  import { isProviderRateLimited } from '../../domain/costs/rate-limit-throttle.js';
15
15
  import { durablePost, getOutboundQueue } from '../../store/outbound-queue.js';
16
16
  const log = createLogger('lifecycle');
@@ -95,9 +95,8 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
95
95
  // edit-retry below). The execution record and the live-run registry were already closed by the
96
96
  // run's own terminal handler (domain/runs/service); this handler owns the SURFACE. Only when a
97
97
  // userMessage is available (direct/TUI turns) — edit callers without it fall through to the
98
- // normal error path. A failure the run chose not to retry (it had already run tools) is a plain
99
- // error: its message asks the user to send again, and a resume would contradict it.
100
- if (userMessage && !isNotRetriedFailure(error) && isApiRateLimitError(error.message)
98
+ // normal error path.
99
+ if (userMessage && isApiRateLimitError(error.message)
101
100
  && isProviderRateLimited(error.rateLimitProvider)) {
102
101
  recordDirectResume({ provider: error.rateLimitProvider, channel, trackSessionId: sessionId, userMessage });
103
102
  const rateLimitText = renderTurnStatus({ kind: 'rate-limited' }, { sessionId, elapsedStr });
@@ -157,7 +156,8 @@ export async function persistErrorSession(args) {
157
156
  }
158
157
  if (!trackSessionId)
159
158
  return;
160
- const backend = resolveBackendForChannel(channel);
159
+ const selection = resolveRunSelection({ channel });
160
+ const backend = selection.backend;
161
161
  await setSessionAsync(channel, trackSessionId);
162
162
  // Backfill the ledger's session id: a conversation opened before the backend reported one.
163
163
  const conv = await conversationLedger.getConversation(channel);
@@ -165,7 +165,7 @@ export async function persistErrorSession(args) {
165
165
  await conversationLedger.updateSessionId(channel, trackSessionId);
166
166
  const existing = await sessionStore.getById(trackSessionId);
167
167
  if (!existing) {
168
- await sessionStore.registerSession({ sessionId: trackSessionId, channel, backend, kind: 'local', origin: 'direct', profileName: getActiveProfile(channel), projectId: (await adapter.resolveInboundProject(channel)) ?? 'general' });
168
+ await sessionStore.registerSession({ sessionId: trackSessionId, channel, backend, kind: 'local', origin: 'direct', selection, projectId: (await adapter.resolveInboundProject(channel)) ?? 'general' });
169
169
  }
170
170
  }
171
171
  // --- The conversation path's terminal branch ---
@@ -31,11 +31,3 @@ export interface TurnFiles {
31
31
  * Feishu-sent picture simply vanished from the transcript.
32
32
  */
33
33
  export declare function collectTurnFiles(message: IncomingMessage, loadPlatformFiles: () => Promise<InboundFiles>): Promise<TurnFiles>;
34
- /** Run one turn holding the browser its session opted into (`session.browser`), released when the
35
- * turn is over. The turn receives the CDP endpoint, or null when it runs without one. */
36
- export declare function withTurnBrowser<T>(args: {
37
- backend: string;
38
- browser: {
39
- device: string;
40
- } | null;
41
- }, turn: (cdpEndpoint: string | null) => Promise<T>): Promise<T>;
@@ -1,11 +1,7 @@
1
1
  import { inboundAttachmentMeta } from '../attachments-store.js';
2
- import { createLogger } from '../../core/log.js';
3
2
  import { resolveWorkspaceRelPath } from '../../core/paths.js';
4
3
  import { sessionStore } from '../../store/session-registry-repo.js';
5
4
  import { acquireSessionUse } from '../../domain/sessions/session-use.js';
6
- import { acquireBrowser, releaseBrowser, backendSupportsBrowser, BROWSER_DEVICE_SERVER } from '../../platform/browser/managed-browser.js';
7
- import { acquireDeviceBrowser, releaseDeviceBrowser } from '../../domain/remote/device-browser.js';
8
- const log = createLogger('turn-prep');
9
5
  /** Take the session's use lease, or null when the record is gone / pending deletion. The lease is
10
6
  * what stops retention from deleting a session out from under a turn that is still opening. */
11
7
  export async function acquireSessionUseLease(sessionId) {
@@ -46,50 +42,3 @@ export async function collectTurnFiles(message, loadPlatformFiles) {
46
42
  failures,
47
43
  };
48
44
  }
49
- /**
50
- * A browser-enabled session holds the shared Chrome for the duration of its turn. Acquiring outside
51
- * the adapter keeps the spawn path synchronous and gives us one obvious place to pair with a
52
- * release. A browser that cannot start degrades the turn to "no browser tools" instead of failing
53
- * it — the session is still worth running.
54
- */
55
- async function acquireTurnBrowser(args) {
56
- const { backend, browser } = args;
57
- if (!browser)
58
- return { held: null, cdpEndpoint: null };
59
- if (!backendSupportsBrowser(backend)) {
60
- log.warn(`session opted into the browser but the ${backend} backend cannot use it — skipping`);
61
- return { held: null, cdpEndpoint: null };
62
- }
63
- const device = browser.device;
64
- try {
65
- // `server` is this host's own Chrome; anything else is a Chrome the device launches for us,
66
- // reachable only because the reverse channel maps its debugging port onto a local one. Both
67
- // hand back a plain http://127.0.0.1:<port>, so nothing downstream knows the difference.
68
- const cdpEndpoint = device === BROWSER_DEVICE_SERVER
69
- ? (await acquireBrowser()).cdpEndpoint
70
- : (await acquireDeviceBrowser(device)).cdpEndpoint;
71
- return { held: device, cdpEndpoint };
72
- }
73
- catch (error) {
74
- log.warn(`browser session requested on "${device}" but Chrome could not start: ${error.message}`);
75
- return { held: null, cdpEndpoint: null };
76
- }
77
- }
78
- /** Release whatever {@link acquireTurnBrowser} took. No-op when it took nothing. */
79
- function releaseTurnBrowser(held) {
80
- if (held === BROWSER_DEVICE_SERVER)
81
- releaseBrowser();
82
- else if (held)
83
- releaseDeviceBrowser(held);
84
- }
85
- /** Run one turn holding the browser its session opted into (`session.browser`), released when the
86
- * turn is over. The turn receives the CDP endpoint, or null when it runs without one. */
87
- export async function withTurnBrowser(args, turn) {
88
- const browser = await acquireTurnBrowser(args);
89
- try {
90
- return await turn(browser.cdpEndpoint);
91
- }
92
- finally {
93
- releaseTurnBrowser(browser.held);
94
- }
95
- }
@@ -1,9 +1,9 @@
1
1
  import type { TurnMutationRelease } from '../turn-mutation-lock.js';
2
2
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
3
3
  import * as sessionBackup from '../../domain/sessions/session-backup.js';
4
+ import type { EngineSelection } from '../../domain/agents/engine-selection.js';
4
5
  interface TurnTrackingDeps {
5
- resolveBackend(channel: string): string;
6
- getProfile(channel: string): string | null;
6
+ getSelection(channel: string, sessionId: string | null): EngineSelection | Promise<EngineSelection>;
7
7
  ledger: Pick<typeof conversationLedger, 'initAndBeginTurn' | 'setBackupPath'>;
8
8
  backup: Pick<typeof sessionBackup, 'findPISessionFile' | 'backupSessionFile' | 'createBackup'>;
9
9
  }
@@ -1,10 +1,12 @@
1
1
  import { acquireTurnMutationLock } from '../turn-mutation-lock.js';
2
2
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
3
3
  import * as sessionBackup from '../../domain/sessions/session-backup.js';
4
- import { getActiveProfile, resolveBackendForChannel } from '../../domain/agents/index.js';
4
+ import { resolveRunSelection } from '../../domain/runs/config-resolver.js';
5
+ import { sessionStore } from '../../store/session-registry-repo.js';
5
6
  const defaultTurnTrackingDeps = {
6
- resolveBackend: resolveBackendForChannel,
7
- getProfile: getActiveProfile,
7
+ getSelection: async (channel, sessionId) => resolveRunSelection({
8
+ channel, session: sessionId ? await sessionStore.getById(sessionId) : null,
9
+ }),
8
10
  ledger: conversationLedger,
9
11
  backup: sessionBackup,
10
12
  };
@@ -53,10 +55,11 @@ async function runTurnTracking(args, options, token) {
53
55
  const release = options.mutationRelease ?? await acquireTurnMutationLock(args.channel);
54
56
  try {
55
57
  const deps = options.deps ?? defaultTurnTrackingDeps;
56
- const backend = deps.resolveBackend(args.channel);
58
+ const selection = await deps.getSelection(args.channel, args.trackSessionId);
59
+ const backend = selection.backend;
57
60
  const { turnIndex } = await deps.ledger.initAndBeginTurn(args.channel, {
58
61
  sessionId: args.trackSessionId || null, backend,
59
- profileName: deps.getProfile(args.channel), userMessageTs: args.userMessageTs,
62
+ selection, userMessageTs: args.userMessageTs,
60
63
  userMessageText: args.userMessageText || '', statusMessageTs: args.statusMessageTs,
61
64
  });
62
65
  const backupPath = await snapshotTurn(deps, backend, args.backendSessionId, turnIndex);
@@ -172,8 +172,6 @@ export declare function emitTurnProgress(deps: TurnProgressDeps, progress: {
172
172
  num_turns?: unknown;
173
173
  } | null | undefined): void;
174
174
  export interface AgentCallbacks {
175
- /** Attempt switch of the profile's fallback chain, as two `model/mode` labels. */
176
- onFallback: (fromLabel: string, toLabel: string, reason: 'rate-limited' | 'transport-error') => Promise<void>;
177
175
  onAssistantMsg: ((text: string) => void) & {
178
176
  stream?: OutputStream;
179
177
  };