@openchamber/web 1.24.0 → 1.24.2

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 (227) hide show
  1. package/bin/cli.test.js +29 -6
  2. package/bin/lib/cli-http.js +5 -1
  3. package/bin/lib/commands-status.js +5 -0
  4. package/dist/assets/{CodeMirrorCommentWidgets-C9kV-n7r.js → CodeMirrorCommentWidgets-B_vBPQYm.js} +1 -1
  5. package/dist/assets/DiffView-Ce0oBXXQ.js +4 -0
  6. package/dist/assets/{FilesView-vjJx7VaM.js → FilesView-DtXueAWP.js} +6 -6
  7. package/dist/assets/GitView-k0hUF8KB.js +6 -0
  8. package/dist/assets/GuestAttachDialog-DIf2U85Z.js +1 -0
  9. package/dist/assets/{JsonTreeView-D_4G5X6-.js → JsonTreeView-4AnJ04Pw.js} +1 -1
  10. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  11. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  12. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  13. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  14. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  15. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  16. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  17. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  18. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  19. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  20. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  21. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  22. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  23. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  24. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  25. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  26. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  27. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  28. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  29. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  30. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  31. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  32. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  33. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  34. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  35. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  36. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  37. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  38. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  39. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  40. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  41. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  42. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  46. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  47. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  48. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  49. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  50. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  51. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  52. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  53. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  54. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  55. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  56. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  57. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  58. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  59. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  60. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  61. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  62. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  63. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  64. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  65. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  66. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  67. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  68. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  69. package/dist/assets/{LinearIssuesView-1uKhePfH.js → LinearIssuesView-z_9p2GuO.js} +1 -1
  70. package/dist/assets/{MarkdownImageGallery-Ix7N_2wp.js → MarkdownImageGallery-BC-BNN-s.js} +1 -1
  71. package/dist/assets/{MarkdownRendererImpl-Deel_y5S.js → MarkdownRendererImpl-DyaBTUbH.js} +6 -6
  72. package/dist/assets/{OnboardingScreen-ToIakxb_.js → OnboardingScreen-DKU_yTb6.js} +1 -1
  73. package/dist/assets/{PatchDiff-BjMgezr1.js → PatchDiff-DpGmHRnV.js} +1 -1
  74. package/dist/assets/PierreDiffViewer-CgLl_tp7.js +210 -0
  75. package/dist/assets/{PlanView-BGAzxDwD.js → PlanView-CrfB4qqY.js} +4 -4
  76. package/dist/assets/PluginPane-B5cn-jPy.js +3 -0
  77. package/dist/assets/SettingsView-DMKKwezx.js +29 -0
  78. package/dist/assets/SettingsWindow-DwbnVzOC.js +1 -0
  79. package/dist/assets/{SubmoduleDiffSummary--YFqK6Ih.js → SubmoduleDiffSummary-hkGcvs0E.js} +1 -1
  80. package/dist/assets/{ToolOutputDialog-DRWBvdaJ.js → ToolOutputDialog-DuoIOc0j.js} +6 -6
  81. package/dist/assets/{ToolPartDiffPreview-BxZJCU28.js → ToolPartDiffPreview-t1Bvq_2Y.js} +2 -2
  82. package/dist/assets/{VirtualizedFileDiff-DCXjBGRf.js → VirtualizedFileDiff-BK4aU5qJ.js} +1 -1
  83. package/dist/assets/{WalkthroughView-CfIPvWWa.js → WalkthroughView-Bk6TPNFw.js} +2 -2
  84. package/dist/assets/{appThemeRegistry-DDROzcUO.js → appThemeRegistry-DnOVbJjF.js} +1 -1
  85. package/dist/assets/commitAndPush-DLWNZkkY.js +1 -0
  86. package/dist/assets/{computeVirtualFileMetrics-DHgQIkUq.js → computeVirtualFileMetrics-BVTujWSX.js} +1 -1
  87. package/dist/assets/{de-CX_f-T5U.js → de-zEHaAIi3.js} +4 -4
  88. package/dist/assets/{es-BERmWNn_.js → es-CBDgEzgk.js} +4 -4
  89. package/dist/assets/{fr-BjYYE_-z.js → fr-DjiTptT_.js} +4 -4
  90. package/dist/assets/index-AgOdanig.css +1 -0
  91. package/dist/assets/index-B-2_X4DD.js +40 -0
  92. package/dist/assets/{index-WjufPkIV.js → index-CkA4p2IK.js} +1 -1
  93. package/dist/assets/{isDiffPlainText-D9faP70y.js → isDiffPlainText-D3yX_vx4.js} +1 -1
  94. package/dist/assets/{isFilePlainText-6qOcz5Ky.js → isFilePlainText-CZR9TcHV.js} +1 -1
  95. package/dist/assets/ja-CerMgj3r.js +16 -0
  96. package/dist/assets/{ko-Dty1aUod.js → ko-DHYDAze5.js} +4 -4
  97. package/dist/assets/main-BDka4W43.js +896 -0
  98. package/dist/assets/main-Dl7Dyge_.js +2 -0
  99. package/dist/assets/markdownCore-DFmr0rUR.js +5 -0
  100. package/dist/assets/miniChat-CLKQPPpO.js +2 -0
  101. package/dist/assets/mobile--giD2Q1L.js +2 -0
  102. package/dist/assets/{patchFileDiff-BvU6KOQC.js → patchFileDiff-DRh-AQvd.js} +1 -1
  103. package/dist/assets/{pl-CX-_ROkr.js → pl-BTB_93bq.js} +6 -6
  104. package/dist/assets/{pt-BR-DhRR1arx.js → pt-BR-BwA3oyCK.js} +4 -4
  105. package/dist/assets/renderElectronMiniChatApp-DmB7zpVK.js +2 -0
  106. package/dist/assets/renderMobileApp-pMfOuQfl.js +25 -0
  107. package/dist/assets/runtimeEndpointReset-Gqhmkm3U.js +25 -0
  108. package/dist/assets/{scheduledTasksApi-DW3xqMQ8.js → scheduledTasksApi-CeRAIUmW.js} +1 -1
  109. package/dist/assets/{shikiHighlight-DsxD9QEa.js → shikiHighlight-BfjuB3CD.js} +1 -1
  110. package/dist/assets/{textMateThemeFromAppTheme-Da7ed8qM.js → textMateThemeFromAppTheme-BP60t9SX.js} +1 -1
  111. package/dist/assets/tr-CcPsJoNM.js +7 -0
  112. package/dist/assets/{uk-CD21CXFV.js → uk-B68WibXi.js} +4 -4
  113. package/dist/assets/{useAppFontEffects-hfv2s6mZ.js → useAppFontEffects-DcdrFv2Z.js} +147 -147
  114. package/dist/assets/{useInlineCommentController-BmtfVbo8.js → useInlineCommentController-Cq4SUjsA.js} +2 -2
  115. package/dist/assets/useRootScrollLock-CSdR6Wnm.js +2 -0
  116. package/dist/assets/{vendor-codemirror-language-data-BPMJpOpT.js → vendor-codemirror-language-data-BFm1Ju2w.js} +2 -2
  117. package/dist/assets/vendor-katex-Cp579UoJ.css +1 -0
  118. package/dist/assets/{vendor-tanstack-react-virtual-g05Cx3z9.js → vendor-tanstack-react-virtual-ClYN8CzB.js} +1 -1
  119. package/dist/assets/{vendor-tanstack-virtual-core-Dubg10g5.js → vendor-tanstack-virtual-core-BewVQryB.js} +1 -1
  120. package/dist/assets/{vendor-zod-fZppILAM.js → vendor-zod-CgAdXWZO.js} +4 -4
  121. package/dist/assets/{web-components-U-hWbgJo.js → web-components-2vo9YsZc.js} +1 -1
  122. package/dist/assets/zh-CN-DbFHYXwP.js +16 -0
  123. package/dist/assets/{zh-TW-CRp5dJU2.js → zh-TW-DmXAwdty.js} +4 -4
  124. package/dist/index.html +6 -4
  125. package/dist/mini-chat.html +6 -4
  126. package/dist/mobile.html +6 -4
  127. package/package.json +6 -5
  128. package/server/index.js +29 -7
  129. package/server/lib/agent-tool/DOCUMENTATION.md +17 -4
  130. package/server/lib/agent-tool/runtime.js +62 -15
  131. package/server/lib/agent-tool/runtime.test.js +88 -2
  132. package/server/lib/changelog/update-notes.js +2 -1
  133. package/server/lib/changelog/update-notes.test.js +19 -0
  134. package/server/lib/event-stream/DOCUMENTATION.md +23 -0
  135. package/server/lib/event-stream/delta-coalescer.js +0 -0
  136. package/server/lib/event-stream/delta-coalescer.test.js +292 -0
  137. package/server/lib/event-stream/global-hub.js +53 -23
  138. package/server/lib/event-stream/global-hub.test.js +160 -0
  139. package/server/lib/event-stream/global-ws-bridge.js +1 -0
  140. package/server/lib/event-stream/index.js +4 -0
  141. package/server/lib/fs/DOCUMENTATION.md +2 -1
  142. package/server/lib/fs/routes.js +56 -4
  143. package/server/lib/fs/routes.test.js +116 -0
  144. package/server/lib/git/DOCUMENTATION.md +18 -5
  145. package/server/lib/git/routes.js +1 -1
  146. package/server/lib/git/serial-refresh.js +93 -0
  147. package/server/lib/git/serial-refresh.test.js +112 -0
  148. package/server/lib/git/service.js +325 -70
  149. package/server/lib/git/service.test.js +291 -0
  150. package/server/lib/github/pr-status.js +5 -5
  151. package/server/lib/github/pr-status.test.js +1 -1
  152. package/server/lib/github/routes.js +4 -4
  153. package/server/lib/guests/DOCUMENTATION.md +5 -3
  154. package/server/lib/guests/background.test.js +83 -0
  155. package/server/lib/guests/catalog.js +20 -9
  156. package/server/lib/guests/catalog.test.js +5 -5
  157. package/server/lib/guests/routes.js +2 -2
  158. package/server/lib/message-queue/DOCUMENTATION.md +10 -1
  159. package/server/lib/message-queue/runtime.js +21 -1
  160. package/server/lib/message-queue/runtime.test.js +52 -5
  161. package/server/lib/notifications/routes.js +5 -0
  162. package/server/lib/openchamber-sessions/routes.js +18 -18
  163. package/server/lib/openchamber-sessions/routes.test.js +49 -0
  164. package/server/lib/opencode/DOCUMENTATION.md +1 -1
  165. package/server/lib/opencode/bootstrap-runtime.js +1 -0
  166. package/server/lib/opencode/feature-routes-runtime.js +5 -0
  167. package/server/lib/opencode/session-runtime.js +68 -0
  168. package/server/lib/opencode/session-runtime.test.js +43 -0
  169. package/server/lib/opencode/settings-helpers.js +3 -0
  170. package/server/lib/opencode/settings-registry.json +8 -0
  171. package/server/lib/permission-auto-accept/DOCUMENTATION.md +8 -0
  172. package/server/lib/permission-auto-accept/runtime.js +13 -0
  173. package/server/lib/permission-auto-accept/runtime.test.js +37 -1
  174. package/server/lib/projects/project-config.js +2 -2
  175. package/server/lib/realtime-proxy-terminal.test.js +150 -0
  176. package/server/lib/realtime-proxy.js +2 -0
  177. package/server/lib/routing/DOCUMENTATION.md +83 -0
  178. package/server/lib/routing/defaults.js +98 -0
  179. package/server/lib/routing/feature-flag.js +11 -0
  180. package/server/lib/routing/history.js +34 -0
  181. package/server/lib/routing/jev.js +98 -0
  182. package/server/lib/routing/routes.http.test.js +100 -0
  183. package/server/lib/routing/routes.js +81 -0
  184. package/server/lib/routing/runtime.js +217 -0
  185. package/server/lib/routing/runtime.test.js +188 -0
  186. package/server/lib/routing/store.js +249 -0
  187. package/server/lib/routing/store.test.js +96 -0
  188. package/server/lib/scheduled-tasks/runtime.js +2 -2
  189. package/server/lib/scheduled-tasks/runtime.test.js +14 -0
  190. package/server/lib/security/request-security.js +9 -5
  191. package/server/lib/security/request-security.test.js +37 -0
  192. package/server/lib/small-model/DOCUMENTATION.md +14 -2
  193. package/server/lib/small-model/call.js +37 -6
  194. package/server/lib/small-model/call.test.js +182 -0
  195. package/server/lib/terminal/DOCUMENTATION.md +21 -2
  196. package/server/lib/terminal/runtime.js +10 -3
  197. package/server/lib/terminal/runtime.test.js +22 -0
  198. package/server/lib/terminal/shutdown.js +106 -0
  199. package/server/lib/terminal/shutdown.test.js +84 -0
  200. package/server/lib/tts/service.test.js +78 -0
  201. package/server/lib/ui-auth/DOCUMENTATION.md +8 -0
  202. package/server/lib/ui-auth/session-cookie.js +51 -0
  203. package/server/lib/ui-auth/session-cookie.test.js +46 -0
  204. package/server/lib/ui-auth/ui-auth.js +13 -9
  205. package/server/lib/ui-auth/ui-auth.test.js +56 -0
  206. package/dist/assets/DiffView-B7YkbY-u.js +0 -4
  207. package/dist/assets/DirtyBranchSwitchDialog-CU0A93Zx.js +0 -1
  208. package/dist/assets/GitView-BLhlMYEY.js +0 -6
  209. package/dist/assets/GuestAttachDialog-B-fwE8r3.js +0 -3
  210. package/dist/assets/PierreDiffViewer-53Ghfnlr.js +0 -161
  211. package/dist/assets/SettingsView-n2X-jfBB.js +0 -29
  212. package/dist/assets/SettingsWindow-Bi8LE9XI.js +0 -1
  213. package/dist/assets/index-DpzTz2UH.css +0 -1
  214. package/dist/assets/index-Dy8xgawx.js +0 -40
  215. package/dist/assets/ja-DxqeAk9N.js +0 -16
  216. package/dist/assets/main-BOYSXfYn.js +0 -896
  217. package/dist/assets/main-Bjcre_GE.js +0 -2
  218. package/dist/assets/markdownCore-DPrwM1rU.js +0 -5
  219. package/dist/assets/miniChat-Dz_bPgMc.js +0 -2
  220. package/dist/assets/mobile-BbZPBJrK.js +0 -2
  221. package/dist/assets/renderElectronMiniChatApp-uNEUkeAI.js +0 -2
  222. package/dist/assets/renderMobileApp-BK1kFlcJ.js +0 -25
  223. package/dist/assets/runtimeEndpointReset-BULHvOwb.js +0 -25
  224. package/dist/assets/tr-cIQtYBpg.js +0 -7
  225. package/dist/assets/useRootScrollLock-Cwc4kSl2.js +0 -1
  226. package/dist/assets/zh-CN-BWvlPHY-.js +0 -16
  227. /package/dist/assets/{vendor-katex-k3Ppq1Ha.js → vendor-katex-CHD9BdDO.js} +0 -0
@@ -22,6 +22,12 @@ session-knowledge runtime; routes registered in
22
22
  JSON bodies enabled in `opencode/core-routes.js`; stopped by
23
23
  `opencode/shutdown-runtime.js`.
24
24
 
25
+ ## Auto routing
26
+
27
+ `resolvePromptBody` (the routing runtime) runs on the assembled body right
28
+ before the prompt or command send, turning a queued `openchamber/auto` model
29
+ into a real one. The queue captures the sentinel like any other send config.
30
+
25
31
  ## Item
26
32
 
27
33
  An item is what the UI would have sent itself, captured at queue time so the
@@ -98,7 +104,10 @@ persisted "sending" flag would strand a message forever.
98
104
  next one: `GET /session/status` must not list the session as busy/retry,
99
105
  and the trailing message must not be an unfinished assistant reply (the
100
106
  status map only lists busy sessions, so a missed busy event leaves no
101
- entry while a turn still streams). A failed fetch is unknown, never idle:
107
+ entry while a turn still streams). An unfinished reply created before this
108
+ runtime started does not block: its run died with the previous server and
109
+ will never complete, so a restored queue would wait on it forever. A reply
110
+ with no `created` time still blocks. A failed fetch is unknown, never idle:
102
111
  the tick re-arms with backoff.
103
112
  5. The head is marked in flight (broadcast), then sent:
104
113
  - text starting with `/` that names a command in OpenCode's `/command`
@@ -211,6 +211,9 @@ export function createMessageQueueRuntime({
211
211
  sessionKnowledgeRuntime = null,
212
212
  broadcastGlobalUiEvent,
213
213
  onPromptSent,
214
+ // Turns the `openchamber/auto` model into a real one right before the send;
215
+ // absent means the queue never sees the sentinel.
216
+ resolvePromptBody = null,
214
217
  dataDir,
215
218
  fetchImpl = fetch,
216
219
  now = Date.now,
@@ -227,6 +230,13 @@ export function createMessageQueueRuntime({
227
230
  let writePromise = Promise.resolve();
228
231
  let stopped = false;
229
232
 
233
+ // An unfinished assistant message older than this marker is a run that died
234
+ // with the previous server, not a streaming turn: no completion event will
235
+ // ever arrive for it, so treating it as live strands restored queue items
236
+ // forever. A run that outlived the restart (external OpenCode) is still
237
+ // caught by the live status check, which runs first.
238
+ const runtimeStartedAt = now();
239
+
230
240
  /** In-memory only — a restart has no in-flight sends. */
231
241
  const sending = new Map(); // sessionId → itemId
232
242
  const timers = new Map(); // sessionId → timeout
@@ -393,7 +403,15 @@ export function createMessageQueueRuntime({
393
403
  }).catch(() => null));
394
404
  if (!messages) return null;
395
405
  const last = asRecord(asRecord(messages[messages.length - 1])?.info);
396
- if (last?.role === 'assistant' && asCount(asRecord(last.time)?.completed) === null) return false;
406
+ const lastTime = asRecord(last?.time);
407
+ if (last?.role === 'assistant' && asCount(lastTime?.completed) === null) {
408
+ const created = asCount(lastTime?.created);
409
+ if (created === null || created >= runtimeStartedAt) return false;
410
+ // Unfinished tail from before this runtime started: its run died with
411
+ // the previous server, so it must not block delivery. (A missing
412
+ // created timestamp stays conservative and blocks, as before.)
413
+ console.log(`[message-queue] ignoring pre-boot unfinished tail for ${sessionId}`);
414
+ }
397
415
  return true;
398
416
  };
399
417
 
@@ -469,6 +487,7 @@ export function createMessageQueueRuntime({
469
487
  if (agent) body.agent = agent;
470
488
  if (variant) body.variant = variant;
471
489
  if (fileParts.length > 0) body.parts = fileParts;
490
+ await resolvePromptBody?.(body, { sessionId, directory });
472
491
  await openCodeFetch(`/session/${encodeURIComponent(sessionId)}/command`, { directory, method: 'POST', body });
473
492
  return;
474
493
  }
@@ -503,6 +522,7 @@ export function createMessageQueueRuntime({
503
522
  if (agent) body.agent = agent;
504
523
  if (variant) body.variant = variant;
505
524
  body.parts = parts;
525
+ await resolvePromptBody?.(body, { sessionId, directory });
506
526
  await openCodeFetch(`/session/${encodeURIComponent(sessionId)}/prompt_async`, { directory, method: 'POST', body });
507
527
  if (knowledge.text && sessionKnowledgeRuntime) {
508
528
  // After the prompt is accepted, so a rejected dispatch carries it again.
@@ -58,7 +58,7 @@ const createOpenCode = () => {
58
58
  return { state, fetchImpl };
59
59
  };
60
60
 
61
- const createRuntime = ({ dataDir = makeDataDir(), openCode = createOpenCode(), knowledge = null, retryDelayMs } = {}) => {
61
+ const createRuntime = ({ dataDir = makeDataDir(), openCode = createOpenCode(), knowledge = null, retryDelayMs, resolvePromptBody, now } = {}) => {
62
62
  let eventHandler = () => {};
63
63
  let statusHandler = () => {};
64
64
  const broadcasts = [];
@@ -79,6 +79,8 @@ const createRuntime = ({ dataDir = makeDataDir(), openCode = createOpenCode(), k
79
79
  abortHoldMs: 50,
80
80
  };
81
81
  if (retryDelayMs) options.retryDelayMs = retryDelayMs;
82
+ if (resolvePromptBody) options.resolvePromptBody = resolvePromptBody;
83
+ if (now) options.now = now;
82
84
  const runtime = createMessageQueueRuntime(options);
83
85
  return {
84
86
  runtime,
@@ -95,6 +97,36 @@ const settle = async (ms = 30) => {
95
97
  await new Promise((resolve) => setTimeout(resolve, ms));
96
98
  };
97
99
 
100
+ describe('auto routing', () => {
101
+ it('lets the routing hook rewrite the model of a queued prompt and a queued command', async () => {
102
+ const resolvePromptBody = vi.fn(async (body) => {
103
+ if (body.model?.modelID === 'auto') body.model = { providerID: 'openai', modelID: 'gpt-6-astra' };
104
+ if (body.model === 'openchamber/auto') body.model = 'openai/gpt-6-astra';
105
+ return null;
106
+ });
107
+ const { runtime, openCode, emit } = createRuntime({ resolvePromptBody });
108
+ runtime.start();
109
+ openCode.state.statuses = { [SESSION]: { type: 'busy' } };
110
+ openCode.state.commands = [{ name: 'review', template: 'Review $ARGUMENTS' }];
111
+ const auto = { providerID: 'openchamber', modelID: 'auto', agent: 'build' };
112
+ await runtime.enqueue(SESSION, DIRECTORY, item({ content: 'plain', text: 'plain', sendConfig: auto }));
113
+ await runtime.enqueue(SESSION, DIRECTORY, item({ content: '/review src', text: '/review src', sendConfig: auto }));
114
+
115
+ openCode.state.statuses = {};
116
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
117
+ await settle();
118
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
119
+ await settle();
120
+
121
+ expect(openCode.state.sent.map((entry) => entry.body.model)).toEqual([
122
+ { providerID: 'openai', modelID: 'gpt-6-astra' },
123
+ 'openai/gpt-6-astra',
124
+ ]);
125
+ expect(resolvePromptBody).toHaveBeenCalledTimes(2);
126
+ expect(resolvePromptBody.mock.calls[0][1]).toEqual({ sessionId: SESSION, directory: DIRECTORY });
127
+ });
128
+ });
129
+
98
130
  describe('parseQueuedItemInput', () => {
99
131
  it('rejects an item the server could not deliver later', () => {
100
132
  expect(() => parseQueuedItemInput({ content: 'x' })).toThrow(TypeError);
@@ -175,9 +207,10 @@ describe('message queue runtime', () => {
175
207
  });
176
208
 
177
209
  it('does not send into a running turn even when the status event says idle', async () => {
178
- const { runtime, openCode, emit } = createRuntime();
210
+ const { runtime, openCode, emit } = createRuntime({ now: () => 10_000 });
179
211
  runtime.start();
180
- openCode.state.tail = [{ info: { role: 'assistant', time: { created: 1 } } }];
212
+ // Live unfinished turn: created after this runtime started.
213
+ openCode.state.tail = [{ info: { role: 'assistant', time: { created: 10_001 } } }];
181
214
  await runtime.enqueue(SESSION, DIRECTORY, item());
182
215
  emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
183
216
  await settle();
@@ -185,10 +218,24 @@ describe('message queue runtime', () => {
185
218
 
186
219
  // The reply completes: that alone drains the queue (a missed idle event
187
220
  // must not strand it).
188
- openCode.state.tail = [{ info: { role: 'assistant', time: { created: 1, completed: 2 } } }];
189
- emit({ type: 'message.updated', properties: { info: { role: 'assistant', sessionID: SESSION, time: { created: 1, completed: 2 } } } });
221
+ openCode.state.tail = [{ info: { role: 'assistant', time: { created: 10_001, completed: 10_002 } } }];
222
+ emit({ type: 'message.updated', properties: { info: { role: 'assistant', sessionID: SESSION, time: { created: 10_001, completed: 10_002 } } } });
223
+ await settle();
224
+ expect(openCode.state.sent).toHaveLength(1);
225
+ });
226
+
227
+ it('delivers past an unfinished tail that predates this runtime (dead pre-restart run)', async () => {
228
+ const { runtime, openCode, emit } = createRuntime({ now: () => 10_000 });
229
+ runtime.start();
230
+ // Assistant reply interrupted by a server restart: unfinished, but older
231
+ // than this runtime — no completion event will ever arrive for it, so it
232
+ // must not block a restored queue forever.
233
+ openCode.state.tail = [{ info: { role: 'assistant', time: { created: 1 } } }];
234
+ await runtime.enqueue(SESSION, DIRECTORY, item());
235
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
190
236
  await settle();
191
237
  expect(openCode.state.sent).toHaveLength(1);
238
+ expect(openCode.state.sent[0].path).toBe(`/session/${SESSION}/prompt_async`);
192
239
  });
193
240
 
194
241
  it('treats an unreachable OpenCode as unknown, not idle', async () => {
@@ -44,6 +44,7 @@ export const registerNotificationRoutes = (app, dependencies) => {
44
44
  writeSseEvent,
45
45
  getSessionActivitySnapshot,
46
46
  getSessionStateSnapshot,
47
+ getPendingBlockingRequestsSnapshot,
47
48
  getSessionAttentionSnapshot,
48
49
  getSessionState,
49
50
  getSessionAttentionState,
@@ -295,11 +296,15 @@ export const registerNotificationRoutes = (app, dependencies) => {
295
296
  });
296
297
  });
297
298
 
299
+ // Cross-project seed for clients that do not initialize every directory:
300
+ // live status per session plus the permission and question requests still
301
+ // waiting for an answer. Both come from the server's single upstream stream.
298
302
  app.get('/api/sessions/status', async (_req, res) => {
299
303
  await ensureSessionWatcher();
300
304
  const snapshot = getSessionStateSnapshot();
301
305
  res.json({
302
306
  sessions: snapshot,
307
+ pending: typeof getPendingBlockingRequestsSnapshot === 'function' ? getPendingBlockingRequestsSnapshot() : {},
303
308
  serverTime: Date.now(),
304
309
  });
305
310
  });
@@ -422,6 +422,10 @@ export const createOpenChamberSessionService = (dependencies) => {
422
422
  emitSessionCreatedEvent,
423
423
  createSessionGoal: createSessionGoalOverride,
424
424
  sessionKnowledgeRuntime = null,
425
+ // Auto routing. Prompts dispatched here go straight to OpenCode, not
426
+ // through the proxy that rewrites the Auto sentinel, so the same hook runs
427
+ // on the body before it is sent. Null when routing is not wired in.
428
+ resolvePromptBody = null,
425
429
  } = dependencies;
426
430
 
427
431
  // Last user message of an existing session, as a selection to reuse. Returns
@@ -596,25 +600,21 @@ export const createOpenChamberSessionService = (dependencies) => {
596
600
  ? await sessionKnowledgeRuntime.resolvePendingForSession(sessionID, directory)
597
601
  .catch(() => ({ text: '', signature: '' }))
598
602
  : { text: '', signature: '' };
603
+ const payload = {
604
+ model,
605
+ ...(agent ? { agent } : {}),
606
+ ...(variant ? { variant } : {}),
607
+ parts: [
608
+ ...(knowledge.text ? [{ type: 'text', text: knowledge.text, synthetic: true }] : []),
609
+ { type: 'text', text: expandedPrompt },
610
+ ...(goalInput.enabled
611
+ ? [{ type: 'text', text: buildGoalIntroText(goalInput.tokenBudget), synthetic: true }]
612
+ : []),
613
+ ],
614
+ };
615
+ await resolvePromptBody?.(payload, { sessionId: sessionID, directory });
599
616
  try {
600
- await runPromptAsync({
601
- baseUrl,
602
- authHeaders,
603
- sessionID,
604
- directory,
605
- payload: {
606
- model,
607
- ...(agent ? { agent } : {}),
608
- ...(variant ? { variant } : {}),
609
- parts: [
610
- ...(knowledge.text ? [{ type: 'text', text: knowledge.text, synthetic: true }] : []),
611
- { type: 'text', text: expandedPrompt },
612
- ...(goalInput.enabled
613
- ? [{ type: 'text', text: buildGoalIntroText(goalInput.tokenBudget), synthetic: true }]
614
- : []),
615
- ],
616
- },
617
- });
617
+ await runPromptAsync({ baseUrl, authHeaders, sessionID, directory, payload });
618
618
  } catch (error) {
619
619
  throw markGoalPartial(error);
620
620
  }
@@ -361,6 +361,55 @@ describe('openchamber session routes', () => {
361
361
  }
362
362
  });
363
363
 
364
+ it('lets the routing hook replace an Auto default before the prompt leaves', async () => {
365
+ const originalFetch = globalThis.fetch;
366
+ const fetchMock = vi.fn(async (url) => {
367
+ const text = String(url);
368
+ if (text.includes('/prompt_async')) {
369
+ return { ok: true, text: async () => '' };
370
+ }
371
+ if (text.includes('/config/providers')) {
372
+ return { ok: true, json: async () => ({ providers: [{ id: 'openai', models: { 'gpt-5.5': { id: 'gpt-5.5' } } }] }) };
373
+ }
374
+ if (text.includes('/agent')) {
375
+ return { ok: true, json: async () => [{ name: 'build', mode: 'primary' }] };
376
+ }
377
+ if (text.includes('/config')) {
378
+ return { ok: true, json: async () => ({}) };
379
+ }
380
+ return { ok: true, json: async () => ({ id: 'ses_123' }) };
381
+ });
382
+ globalThis.fetch = fetchMock;
383
+ const seen = [];
384
+ const resolvePromptBody = vi.fn(async (body, target) => {
385
+ seen.push({ model: body.model, target });
386
+ body.model = { providerID: 'openai', modelID: 'gpt-5.5' };
387
+ });
388
+ const { app } = createApp({
389
+ readSettingsFromDiskMigrated: async () => ({
390
+ defaultModel: 'openchamber/auto',
391
+ defaultAgent: 'build',
392
+ projects: [{ id: 'proj_1', path: '/repo/app' }],
393
+ }),
394
+ resolvePromptBody,
395
+ });
396
+ try {
397
+ await request(app)
398
+ .post('/api/openchamber/sessions')
399
+ .send({ directory: '/repo/app', prompt: 'Run this' })
400
+ .expect(200);
401
+
402
+ expect(seen).toEqual([{
403
+ model: { providerID: 'openchamber', modelID: 'auto' },
404
+ target: { sessionId: 'ses_123', directory: '/repo/app' },
405
+ }]);
406
+ const promptCall = fetchMock.mock.calls.find(([url]) => String(url).includes('/prompt_async'));
407
+ expect(JSON.parse(promptCall?.[1]?.body).model).toEqual({ providerID: 'openai', modelID: 'gpt-5.5' });
408
+ } finally {
409
+ globalThis.fetch = originalFetch;
410
+ }
411
+ });
412
+
364
413
  it.each([
365
414
  ['', { projectId: 'proj_1' }],
366
415
  ['', { directory: '/repo/app', worktree: { name: 'side-task' } }],
@@ -32,7 +32,7 @@ This module provides OpenCode server integration utilities for the web server ru
32
32
  - `packages/web/server/lib/opencode/tunnel-wiring-runtime.js`: tunnel service/routes composition runtime and active-port wiring for main server startup.
33
33
  - `packages/web/server/lib/opencode/startup-pipeline-runtime.js`: server startup tail orchestration runtime for terminal/proxy/static/start-listen flow.
34
34
  - `packages/web/server/lib/opencode/startup-performance.js`: opt-in startup phase diagnostics with fixed labels and numeric metadata allowlists.
35
- - `packages/web/server/lib/agent-tool/runtime.js`: managed OpenCode custom-tool materialization, environment injection, loopback authentication, and fixed CLI action dispatch.
35
+ - `packages/web/server/lib/agent-tool/runtime.js`: managed OpenCode custom-tool materialization, environment injection, same-machine authentication (loopback, or the bound address for a concrete bind), and fixed CLI action dispatch.
36
36
  - `packages/web/server/lib/system-prompt/runtime.js`: opt-in managed OpenCode system-prompt optimizer materialization and plugin injection.
37
37
  - `packages/web/server/lib/opencode/managed-plugin-config.js`: the one `OPENCODE_CONFIG_CONTENT` merge every managed plugin (agent tools, system prompt optimizer) appends itself through.
38
38
  - `packages/web/server/lib/opencode/server-utils-runtime.js`: shared server runtime utilities for OpenCode proxy wiring, OpenCode port/readiness helpers, and snapshot fetchers.
@@ -131,6 +131,7 @@ export const createBootstrapRuntime = (dependencies) => {
131
131
  writeSseEvent,
132
132
  getSessionActivitySnapshot: sessionRuntime.getSessionActivitySnapshot,
133
133
  getSessionStateSnapshot: sessionRuntime.getSessionStateSnapshot,
134
+ getPendingBlockingRequestsSnapshot: sessionRuntime.getPendingBlockingRequestsSnapshot,
134
135
  getSessionAttentionSnapshot: sessionRuntime.getSessionAttentionSnapshot,
135
136
  getSessionState: sessionRuntime.getSessionState,
136
137
  getSessionAttentionState: sessionRuntime.getSessionAttentionState,
@@ -18,6 +18,7 @@ import { registerAgentMemoryRoutes } from '../agent-memory/routes.js';
18
18
  import { registerSessionKnowledgeRoutes } from '../session-knowledge/routes.js';
19
19
  import { registerPermissionAutoAcceptRoutes } from '../permission-auto-accept/runtime.js';
20
20
  import { registerMessageQueueRoutes } from '../message-queue/runtime.js';
21
+ import { registerRoutingPromptRewrite, registerRoutingRoutes } from '../routing/routes.js';
21
22
  import { registerConfigEntityRoutes } from './config-entity-routes.js';
22
23
  import { registerSettingsUtilityRoutes } from './core-routes.js';
23
24
  import { registerProjectIconRoutes } from './project-icon-routes.js';
@@ -141,6 +142,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
141
142
  emitSessionCreatedEvent,
142
143
  permissionAutoAcceptRuntime,
143
144
  messageQueueRuntime,
145
+ routingRuntime,
144
146
  openchamberVersion,
145
147
  } = routeDependencies;
146
148
 
@@ -154,6 +156,9 @@ export const createFeatureRoutesRuntime = (dependencies) => {
154
156
 
155
157
  registerPermissionAutoAcceptRoutes(app, permissionAutoAcceptRuntime);
156
158
  registerMessageQueueRoutes(app, messageQueueRuntime);
159
+ registerRoutingRoutes(app, routingRuntime);
160
+ // Before the generic OpenCode proxy: turns `openchamber/auto` into a real model.
161
+ registerRoutingPromptRewrite(app, routingRuntime);
157
162
 
158
163
  registerOpenCodeRoutes(app, {
159
164
  crypto,
@@ -38,13 +38,76 @@ const extractSessionStatusUpdate = (payload) => {
38
38
  };
39
39
  };
40
40
 
41
+ const readRequestId = (value) => (typeof value === 'string' && value.trim() ? value.trim() : '');
42
+
41
43
  export const createSessionRuntime = ({ writeSseEvent, getNotificationClients, broadcastEvent }) => {
42
44
  const sessionActivityPhases = new Map();
43
45
  const sessionActivityCooldowns = new Map();
44
46
  const sessionStates = new Map();
45
47
  const sessionAttentionStates = new Map();
48
+ // Pending permission and question requests per session, kept from the same
49
+ // upstream stream. Clients that do not initialize a directory cannot read
50
+ // its pending list from OpenCode (that read creates an instance), so this
51
+ // map is their seed. Entries live until the matching reply, the session's
52
+ // deletion, or an OpenCode restart, which drops every pending request.
53
+ const pendingRequestsBySession = new Map();
46
54
  let activeSessionCount = 0;
47
55
 
56
+ const getOrCreatePendingRequests = (sessionId) => {
57
+ let entry = pendingRequestsBySession.get(sessionId);
58
+ if (!entry) {
59
+ entry = { permissions: new Map(), questions: new Map() };
60
+ pendingRequestsBySession.set(sessionId, entry);
61
+ }
62
+ return entry;
63
+ };
64
+
65
+ const settlePendingRequest = (kind, sessionId, requestId) => {
66
+ const entry = pendingRequestsBySession.get(sessionId);
67
+ if (!entry) return;
68
+ // OpenCode may omit the request ID on a reply; the session then has no
69
+ // pending request of that kind we can still vouch for.
70
+ if (requestId) entry[kind].delete(requestId);
71
+ else entry[kind].clear();
72
+ if (entry.permissions.size === 0 && entry.questions.size === 0) pendingRequestsBySession.delete(sessionId);
73
+ };
74
+
75
+ const processBlockingRequestPayload = (payload) => {
76
+ if (!payload || typeof payload.type !== 'string') return;
77
+ const properties = payload.properties && typeof payload.properties === 'object' ? payload.properties : {};
78
+ if (payload.type === 'permission.asked' || payload.type === 'question.asked') {
79
+ const sessionId = readRequestId(properties.sessionID);
80
+ const requestId = readRequestId(properties.id);
81
+ if (!sessionId || !requestId) return;
82
+ getOrCreatePendingRequests(sessionId)[payload.type === 'permission.asked' ? 'permissions' : 'questions'].set(requestId, properties);
83
+ return;
84
+ }
85
+ if (payload.type === 'permission.replied') {
86
+ settlePendingRequest('permissions', readRequestId(properties.sessionID), readRequestId(properties.requestID));
87
+ return;
88
+ }
89
+ if (payload.type === 'question.replied' || payload.type === 'question.rejected') {
90
+ settlePendingRequest('questions', readRequestId(properties.sessionID), readRequestId(properties.requestID));
91
+ return;
92
+ }
93
+ if (payload.type === 'session.deleted') {
94
+ const info = properties.info && typeof properties.info === 'object' ? properties.info : {};
95
+ const sessionId = readRequestId(properties.sessionID) || readRequestId(info.id);
96
+ if (sessionId) pendingRequestsBySession.delete(sessionId);
97
+ }
98
+ };
99
+
100
+ const getPendingBlockingRequestsSnapshot = () => {
101
+ const result = {};
102
+ for (const [sessionId, entry] of pendingRequestsBySession) {
103
+ result[sessionId] = {
104
+ permissions: [...entry.permissions.values()],
105
+ questions: [...entry.questions.values()],
106
+ };
107
+ }
108
+ return result;
109
+ };
110
+
48
111
  const getOrCreateAttentionState = (sessionId) => {
49
112
  if (!sessionId || typeof sessionId !== 'string') return null;
50
113
 
@@ -307,6 +370,8 @@ export const createSessionRuntime = ({ writeSseEvent, getNotificationClients, br
307
370
  }
308
371
  }
309
372
 
373
+ // A restarted OpenCode forgot every pending request with the turns.
374
+ pendingRequestsBySession.clear();
310
375
  const eventId = `opencode-restart-${Date.now()}`;
311
376
  for (const sessionId of interruptedSessionIds) {
312
377
  updateSessionState(sessionId, 'idle', eventId, {
@@ -354,6 +419,7 @@ export const createSessionRuntime = ({ writeSseEvent, getNotificationClients, br
354
419
  const cleanupInterval = setInterval(cleanupOldSessionStates, SESSION_STATE_CLEANUP_INTERVAL_MS);
355
420
 
356
421
  const processOpenCodeSsePayload = (payload) => {
422
+ processBlockingRequestPayload(payload);
357
423
  const update = extractSessionStatusUpdate(payload);
358
424
  if (!update) return;
359
425
 
@@ -379,6 +445,7 @@ export const createSessionRuntime = ({ writeSseEvent, getNotificationClients, br
379
445
  sessionActivityPhases.clear();
380
446
  sessionStates.clear();
381
447
  sessionAttentionStates.clear();
448
+ pendingRequestsBySession.clear();
382
449
  activeSessionCount = 0;
383
450
  };
384
451
 
@@ -387,6 +454,7 @@ export const createSessionRuntime = ({ writeSseEvent, getNotificationClients, br
387
454
  getSessionActivitySnapshot,
388
455
  getActiveSessionCount,
389
456
  getSessionStateSnapshot,
457
+ getPendingBlockingRequestsSnapshot,
390
458
  getSessionAttentionSnapshot,
391
459
  getSessionState,
392
460
  getSessionAttentionState,
@@ -12,6 +12,49 @@ describe('session runtime', () => {
12
12
  runtimes.length = 0;
13
13
  });
14
14
 
15
+ it('keeps pending permission and question requests until they are answered', () => {
16
+ const runtime = createSessionRuntime({
17
+ writeSseEvent() {},
18
+ getNotificationClients: () => new Set(),
19
+ broadcastEvent: () => {},
20
+ });
21
+ runtimes.push(runtime);
22
+ const permission = { id: 'perm-1', sessionID: 'session-1', permission: 'bash', patterns: ['rm *'], metadata: {}, always: [] };
23
+ const question = { id: 'q-1', sessionID: 'session-2', questions: [{ header: 'Pick', question: 'Which?', options: [] }] };
24
+
25
+ runtime.processOpenCodeSsePayload({ type: 'permission.asked', properties: permission });
26
+ runtime.processOpenCodeSsePayload({ type: 'permission.asked', properties: permission });
27
+ runtime.processOpenCodeSsePayload({ type: 'question.asked', properties: question });
28
+ expect(runtime.getPendingBlockingRequestsSnapshot()).toEqual({
29
+ 'session-1': { permissions: [permission], questions: [] },
30
+ 'session-2': { permissions: [], questions: [question] },
31
+ });
32
+
33
+ runtime.processOpenCodeSsePayload({ type: 'permission.replied', properties: { sessionID: 'session-1', requestID: 'perm-1' } });
34
+ runtime.processOpenCodeSsePayload({ type: 'question.rejected', properties: { sessionID: 'session-2' } });
35
+ expect(runtime.getPendingBlockingRequestsSnapshot()).toEqual({});
36
+ });
37
+
38
+ it('drops pending requests when the session is deleted or OpenCode restarts', () => {
39
+ const runtime = createSessionRuntime({
40
+ writeSseEvent() {},
41
+ getNotificationClients: () => new Set(),
42
+ broadcastEvent: () => {},
43
+ });
44
+ runtimes.push(runtime);
45
+ const ask = (sessionID, id) => runtime.processOpenCodeSsePayload({
46
+ type: 'permission.asked', properties: { id, sessionID, permission: 'edit', patterns: [], metadata: {}, always: [] },
47
+ });
48
+
49
+ ask('session-1', 'perm-1');
50
+ ask('session-2', 'perm-2');
51
+ runtime.processOpenCodeSsePayload({ type: 'session.deleted', properties: { info: { id: 'session-1' } } });
52
+ expect(Object.keys(runtime.getPendingBlockingRequestsSnapshot())).toEqual(['session-2']);
53
+
54
+ runtime.interruptBusySessionsAfterRestart();
55
+ expect(runtime.getPendingBlockingRequestsSnapshot()).toEqual({});
56
+ });
57
+
15
58
  it('broadcasts attention clears through the shared broadcaster', () => {
16
59
  const events = [];
17
60
  const runtime = createSessionRuntime({
@@ -1,6 +1,7 @@
1
1
  import { createRequire } from 'node:module';
2
2
 
3
3
  import { isAgentMemoryFeatureAvailable } from '../agent-memory/feature-flag.js';
4
+ import { isRoutingFeatureAvailable } from '../routing/feature-flag.js';
4
5
 
5
6
  // Generated from packages/ui/src/lib/settings/registry.ts by
6
7
  // `bun run settings-registry:generate`; `registry.test.ts` fails when stale.
@@ -1013,6 +1014,8 @@ export const createSettingsHelpers = (dependencies) => {
1013
1014
  // Tells the client whether agent memory exists in this build at all, so
1014
1015
  // its settings row and panel tab can be absent rather than merely off.
1015
1016
  agentMemoryFeatureAvailable: isAgentMemoryFeatureAvailable(),
1017
+ // Same idea for Jev routing: absent from the picker and Settings unless the build has it.
1018
+ routingFeatureAvailable: isRoutingFeatureAvailable(),
1016
1019
  ...(pwaAppName ? { pwaAppName } : {}),
1017
1020
  pwaOrientation,
1018
1021
  mobileKeyboardMode,
@@ -127,6 +127,10 @@
127
127
  "scope": "instance",
128
128
  "computed": true
129
129
  },
130
+ "routingFeatureAvailable": {
131
+ "scope": "instance",
132
+ "computed": true
133
+ },
130
134
  "openCodeUpdateToastDismissedVersion": {
131
135
  "scope": "instance"
132
136
  },
@@ -624,6 +628,10 @@
624
628
  "scope": "device",
625
629
  "local": true
626
630
  },
631
+ "messageQueueExpanded": {
632
+ "scope": "device",
633
+ "local": true
634
+ },
627
635
  "workStatusScrollTop": {
628
636
  "scope": "device",
629
637
  "local": true
@@ -16,6 +16,14 @@ Policy inheritance uses the nearest explicit session value. A child `false` ther
16
16
 
17
17
  Unknown lineage and failed policy loads fail closed. A failed pending-permission fetch is distinct from an empty successful response and never clears policy state.
18
18
 
19
+ ## Safety net
20
+
21
+ `evaluatePermission` (the routing runtime, `../routing/DOCUMENTATION.md`) is
22
+ consulted after the policy check and before the reply. `hold` counts the
23
+ request as handled without replying, so it stays on screen; `accept` replies as
24
+ before. A `permission.replied` event is passed to `onPermissionReplied` so the
25
+ routing runtime forgets its cached decision.
26
+
19
27
  ## Routes
20
28
 
21
29
  - `GET /api/permission-auto-accept`
@@ -25,6 +25,10 @@ export function createPermissionAutoAcceptRuntime({
25
25
  readSettingsFromDiskMigrated,
26
26
  persistSettings,
27
27
  broadcastGlobalUiEvent,
28
+ // The routing safety net: asked once per request before the automatic reply.
29
+ // `hold` leaves the request for the user; absent means every request is replied to.
30
+ evaluatePermission = null,
31
+ onPermissionReplied = null,
28
32
  fetchImpl = fetch,
29
33
  retryDelaysMs = RETRY_DELAYS_MS,
30
34
  requestTimeoutMs = REQUEST_TIMEOUT_MS,
@@ -148,6 +152,10 @@ export function createPermissionAutoAcceptRuntime({
148
152
  if (!permission?.id || !permission?.sessionID) return false;
149
153
  await load();
150
154
  if (!(await isSessionAutoAccepting(permission.sessionID, directory))) return false;
155
+ if (evaluatePermission) {
156
+ const verdict = await evaluatePermission(permission, directory);
157
+ if (verdict?.action === 'hold') return true;
158
+ }
151
159
  await request(`/permission/${encodeURIComponent(permission.id)}/reply`, {
152
160
  directory,
153
161
  method: 'POST',
@@ -218,6 +226,11 @@ export function createPermissionAutoAcceptRuntime({
218
226
  }
219
227
  if (payload?.type === 'permission.asked') {
220
228
  void processPermission(payload.properties, directory);
229
+ return;
230
+ }
231
+ if (payload?.type === 'permission.replied') {
232
+ const permissionId = payload.properties?.requestID;
233
+ if (typeof permissionId === 'string') onPermissionReplied?.(permissionId);
221
234
  }
222
235
  };
223
236
 
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
2
  import { createPermissionAutoAcceptRuntime } from './runtime.js';
3
3
 
4
- const createRuntime = ({ stored, fetchImpl, retryDelaysMs = [0] } = {}) => {
4
+ const createRuntime = ({ stored, fetchImpl, retryDelaysMs = [0], evaluatePermission, onPermissionReplied } = {}) => {
5
5
  let settings = stored ?? { permissionAutoAccept: { sessions: {} } };
6
6
  let eventHandler;
7
7
  let statusHandler;
@@ -16,6 +16,8 @@ const createRuntime = ({ stored, fetchImpl, retryDelaysMs = [0] } = {}) => {
16
16
  persistSettings: async (changes) => { settings = { ...settings, ...changes }; },
17
17
  fetchImpl: fetchImpl ?? vi.fn(async () => new Response('[]')),
18
18
  retryDelaysMs,
19
+ evaluatePermission,
20
+ onPermissionReplied,
19
21
  });
20
22
  runtime.start();
21
23
  return {
@@ -143,4 +145,38 @@ describe('permission auto-accept runtime', () => {
143
145
  expect(fetchImpl.mock.calls.some(([url]) => new URL(url).searchParams.get('directory') === '/project')).toBe(true);
144
146
  expect(await runtime.load()).toEqual({ sessions: { root: true }, revision: 1 });
145
147
  });
148
+
149
+ it('leaves a request held by the safety net unanswered and forgets it once replied', async () => {
150
+ const fetchImpl = vi.fn(async () => new Response('[]'));
151
+ const verdicts = { held: { action: 'hold', score: 0.9, kind: 'git_history' }, safe: { action: 'accept', score: 0.1 } };
152
+ const evaluatePermission = vi.fn(async (permission) => verdicts[permission.id]);
153
+ const onPermissionReplied = vi.fn();
154
+ const { runtime, emit } = createRuntime({
155
+ stored: { permissionAutoAccept: { sessions: { root: true } } },
156
+ fetchImpl,
157
+ evaluatePermission,
158
+ onPermissionReplied,
159
+ });
160
+ await runtime.load();
161
+
162
+ emit({ type: 'permission.asked', properties: { id: 'held', sessionID: 'root', permission: 'bash', metadata: {} } });
163
+ emit({ type: 'permission.asked', properties: { id: 'safe', sessionID: 'root', permission: 'bash', metadata: {} } });
164
+ await flush();
165
+
166
+ const replies = fetchImpl.mock.calls.map(([url]) => String(url)).filter((url) => url.includes('/reply'));
167
+ expect(replies).toEqual(['http://opencode.test/permission/safe/reply?directory=%2Fproject']);
168
+ expect(evaluatePermission).toHaveBeenCalledTimes(2);
169
+
170
+ emit({ type: 'permission.replied', properties: { sessionID: 'root', requestID: 'held', reply: 'once' } });
171
+ expect(onPermissionReplied).toHaveBeenCalledWith('held');
172
+ });
173
+
174
+ it('does not consult the safety net for sessions that are not auto-accepting', async () => {
175
+ const evaluatePermission = vi.fn(async () => ({ action: 'hold' }));
176
+ const { runtime, emit } = createRuntime({ evaluatePermission });
177
+ await runtime.load();
178
+ emit({ type: 'permission.asked', properties: { id: 'p', sessionID: 'manual', permission: 'bash', metadata: {} } });
179
+ await flush();
180
+ expect(evaluatePermission).not.toHaveBeenCalled();
181
+ });
146
182
  });