@openchamber/web 1.22.1 → 1.23.0

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 (205) hide show
  1. package/bin/cli.js +11 -1
  2. package/bin/cli.test.js +92 -0
  3. package/bin/lib/cli-startup.js +49 -0
  4. package/bin/lib/commands-startup.js +41 -6
  5. package/dist/assets/{CodeMirrorCommentWidgets-BO_2OW4E.js → CodeMirrorCommentWidgets-DbcnxAfY.js} +1 -1
  6. package/dist/assets/DiffView-Dp1tomqK.js +4 -0
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-DE2sKIYv.js} +1 -1
  8. package/dist/assets/FilesView-C_of2nIT.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-CKgUkb5Z.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-Bce2ettZ.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BZVWM2zw.js} +1 -1
  12. package/dist/assets/MarkdownImageGallery-DdROVz29.js +1 -0
  13. package/dist/assets/MarkdownRendererImpl-CenrzmMN.js +12 -0
  14. package/dist/assets/OnboardingScreen-DyqYG_NP.js +1 -0
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CR3RVO5I.js} +1 -1
  16. package/dist/assets/PierreDiffViewer-KihzO94X.js +161 -0
  17. package/dist/assets/PlanView-jcQAfr2A.js +5 -0
  18. package/dist/assets/SettingsView-Buvom5A2.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-CV_hzB5v.js} +1 -1
  20. package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
  21. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-llKecK_Z.js} +6 -6
  22. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-ZDMTdCGn.js} +2 -2
  23. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-ClvqQ4j0.js} +1 -1
  24. package/dist/assets/WalkthroughView-BgpSnSlU.js +4 -0
  25. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-Nm5_wabb.js} +2 -2
  26. package/dist/assets/contextPanelEmbeddedChat-CirXEPJq.js +1 -0
  27. package/dist/assets/de-DTQDjaiv.js +10 -0
  28. package/dist/assets/es-SOCFd_r-.js +16 -0
  29. package/dist/assets/fr-CP6jqIzw.js +14 -0
  30. package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
  31. package/dist/assets/index-B68h5S5B.css +1 -0
  32. package/dist/assets/index-CRf2xk51.js +39 -0
  33. package/dist/assets/{index-DLiD86ge.js → index-Du9sZhDb.js} +1 -1
  34. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-EQERIius.js} +1 -1
  35. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-BCoVpkQy.js} +1 -1
  36. package/dist/assets/ja-BKfafwsD.js +16 -0
  37. package/dist/assets/ko-BA5xgCYp.js +16 -0
  38. package/dist/assets/main-BNiPEont.js +930 -0
  39. package/dist/assets/{main-DCB4JgVe.js → main-DPf32fO6.js} +2 -2
  40. package/dist/assets/markdownCore-CQ7CAuuV.js +5 -0
  41. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CHqVTsgj.js} +2 -2
  42. package/dist/assets/{mobile-DZV_sfX7.js → mobile-BQmgHA57.js} +2 -2
  43. package/dist/assets/patchFileDiff-C4X_trug.js +13 -0
  44. package/dist/assets/pl-B215pG1Y.js +16 -0
  45. package/dist/assets/pt-BR-Bo2pnlEa.js +16 -0
  46. package/dist/assets/renderElectronMiniChatApp-BUcHPOXW.js +2 -0
  47. package/dist/assets/renderMobileApp-BvTmuRE-.js +25 -0
  48. package/dist/assets/runtimeEndpointReset-C8GAA2kS.js +17 -0
  49. package/dist/assets/scheduledTasksApi-BAScWwt3.js +1 -0
  50. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-BTObuQCR.js} +1 -1
  51. package/dist/assets/surface-BvRzS58U.js +1 -0
  52. package/dist/assets/tr-CUaxHc8X.js +7 -0
  53. package/dist/assets/uk-YTJgyqAZ.js +16 -0
  54. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-theH_IJL.js} +143 -137
  55. package/dist/assets/useGitComparison-B94I6kOI.js +1 -0
  56. package/dist/assets/useInlineCommentController-Bs3PgeA8.js +2 -0
  57. package/dist/assets/useRootScrollLock-hSYwnxZs.js +1 -0
  58. package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-DdV8vhHn.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-Cxgr01md.js} +2 -2
  60. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  61. package/dist/assets/vendor-zod-BPAANqvH.js +39 -0
  62. package/dist/assets/{web-components-B6QgbmTo.js → web-components-CaS0ksnZ.js} +1 -1
  63. package/dist/assets/zh-CN-CZ2BxZS6.js +16 -0
  64. package/dist/assets/zh-TW-BsUrPdXz.js +16 -0
  65. package/dist/index.html +5 -43
  66. package/dist/mini-chat.html +4 -4
  67. package/dist/mobile.html +4 -4
  68. package/package.json +3 -4
  69. package/server/index.d.ts +15 -0
  70. package/server/index.js +52 -10
  71. package/server/lib/changelog/update-notes.js +82 -0
  72. package/server/lib/changelog/update-notes.test.js +59 -0
  73. package/server/lib/data-dir-migration.js +40 -0
  74. package/server/lib/data-dir-migration.test.js +59 -0
  75. package/server/lib/event-stream/runtime.test.js +12 -12
  76. package/server/lib/fs/DOCUMENTATION.md +5 -0
  77. package/server/lib/fs/routes.js +63 -21
  78. package/server/lib/fs/routes.test.js +187 -1
  79. package/server/lib/git/DOCUMENTATION.md +29 -5
  80. package/server/lib/git/routes.js +24 -4
  81. package/server/lib/git/service.js +194 -198
  82. package/server/lib/git/service.test.js +440 -25
  83. package/server/lib/inherited-env.js +16 -9
  84. package/server/lib/inherited-env.test.js +8 -9
  85. package/server/lib/message-queue/DOCUMENTATION.md +20 -7
  86. package/server/lib/message-queue/runtime.js +59 -7
  87. package/server/lib/message-queue/runtime.test.js +59 -3
  88. package/server/lib/network-defaults.js +23 -0
  89. package/server/lib/network-defaults.test.js +52 -0
  90. package/server/lib/opencode/DOCUMENTATION.md +25 -5
  91. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  92. package/server/lib/opencode/config-paths.test.js +116 -0
  93. package/server/lib/opencode/feature-routes-runtime.js +4 -0
  94. package/server/lib/opencode/input-history-scope.js +14 -0
  95. package/server/lib/opencode/openchamber-routes.js +64 -4
  96. package/server/lib/opencode/openchamber-routes.test.js +128 -1
  97. package/server/lib/opencode/plugins.js +2 -2
  98. package/server/lib/opencode/providers.js +44 -2
  99. package/server/lib/opencode/providers.test.js +131 -4
  100. package/server/lib/opencode/routes.js +9 -7
  101. package/server/lib/opencode/server-startup-runtime.js +1 -1
  102. package/server/lib/opencode/settings-files.js +214 -0
  103. package/server/lib/opencode/settings-helpers.js +113 -41
  104. package/server/lib/opencode/settings-helpers.test.js +342 -0
  105. package/server/lib/opencode/settings-registry.json +747 -0
  106. package/server/lib/opencode/settings-runtime.js +139 -18
  107. package/server/lib/opencode/settings-runtime.test.js +163 -5
  108. package/server/lib/opencode/shared.js +4 -1
  109. package/server/lib/opencode/skill-routes.js +2 -1
  110. package/server/lib/opencode/snippets.js +1 -2
  111. package/server/lib/package-manager.js +3 -28
  112. package/server/lib/project-context/DOCUMENTATION.md +25 -1
  113. package/server/lib/project-context/routes.http.test.js +18 -0
  114. package/server/lib/project-context/routes.js +15 -0
  115. package/server/lib/project-context/runtime.js +248 -23
  116. package/server/lib/project-context/runtime.test.js +106 -3
  117. package/server/lib/projects/DOCUMENTATION.md +76 -0
  118. package/server/lib/projects/project-config.js +142 -9
  119. package/server/lib/projects/project-id.js +17 -0
  120. package/server/lib/projects/project-setup.js +409 -0
  121. package/server/lib/projects/project-setup.test.js +557 -0
  122. package/server/lib/projects/routes.js +59 -0
  123. package/server/lib/quota/DOCUMENTATION.md +38 -1
  124. package/server/lib/quota/index.js +1 -0
  125. package/server/lib/quota/providers/cline-pass.js +125 -0
  126. package/server/lib/quota/providers/cline-pass.test.js +103 -0
  127. package/server/lib/quota/providers/hyper.js +118 -0
  128. package/server/lib/quota/providers/hyper.test.js +126 -0
  129. package/server/lib/quota/providers/index.js +15 -0
  130. package/server/lib/quota/providers/neuralwatt.js +3 -6
  131. package/server/lib/quota/providers/neuralwatt.test.js +7 -7
  132. package/server/lib/quota/providers/ollama-cloud.js +31 -0
  133. package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
  134. package/server/lib/quota/providers/opencode-go.js +1 -1
  135. package/server/lib/quota/providers/opencode-go.test.js +26 -1
  136. package/server/lib/quota/providers/openrouter.js +119 -24
  137. package/server/lib/quota/providers/openrouter.test.js +330 -0
  138. package/server/lib/quota/utils/auth.js +1 -1
  139. package/server/lib/relay/DOCUMENTATION.md +55 -0
  140. package/server/lib/relay/cross-compat.test.js +26 -0
  141. package/server/lib/relay/downstream-scheduler.js +154 -0
  142. package/server/lib/relay/downstream-scheduler.test.js +162 -0
  143. package/server/lib/relay/e2ee.js +10 -8
  144. package/server/lib/relay/flow-control.test.js +177 -0
  145. package/server/lib/relay/host-client.js +37 -8
  146. package/server/lib/relay/host-client.test.js +9 -1
  147. package/server/lib/relay/tunnel-codec.js +9 -0
  148. package/server/lib/relay/tunnel-host.js +66 -17
  149. package/server/lib/session-assist/runtime.js +6 -10
  150. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  151. package/server/lib/session-goal/runtime.js +80 -20
  152. package/server/lib/session-goal/runtime.test.js +426 -0
  153. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  154. package/server/lib/skills-catalog/install.js +3 -2
  155. package/server/lib/small-model/DOCUMENTATION.md +3 -2
  156. package/server/lib/small-model/call.js +9 -4
  157. package/server/lib/small-model/call.test.js +29 -0
  158. package/server/lib/small-model/index.js +5 -10
  159. package/server/lib/small-model/runtime-providers.js +15 -7
  160. package/server/lib/small-model/runtime-providers.test.js +7 -1
  161. package/server/lib/terminal/DOCUMENTATION.md +14 -10
  162. package/server/lib/terminal/runtime.js +160 -24
  163. package/server/lib/terminal/runtime.test.js +571 -37
  164. package/server/lib/terminal/shells.js +17 -0
  165. package/server/lib/terminal/shells.test.js +32 -1
  166. package/server/lib/walkthrough/DOCUMENTATION.md +33 -14
  167. package/server/lib/walkthrough/model-settings.js +8 -12
  168. package/server/lib/walkthrough/prompt.js +3 -1
  169. package/server/lib/walkthrough/routes.test.js +26 -5
  170. package/server/lib/walkthrough/sources.js +23 -2
  171. package/dist/assets/DiffView-CNnDxRmO.js +0 -4
  172. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  173. package/dist/assets/MarkdownImageGallery-DffjmciG.js +0 -1
  174. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  175. package/dist/assets/OnboardingScreen-CTZe6HZn.js +0 -1
  176. package/dist/assets/PierreDiffViewer-BvwtCxW4.js +0 -157
  177. package/dist/assets/PlanView-C1qvAm7m.js +0 -5
  178. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  179. package/dist/assets/WalkthroughView-D-HFgdmM.js +0 -4
  180. package/dist/assets/contextPanelEmbeddedChat-CV-DwAiX.js +0 -1
  181. package/dist/assets/de-Cv_4FoXm.js +0 -10
  182. package/dist/assets/es-BIWNEbnS.js +0 -16
  183. package/dist/assets/fr-SD3OfMHJ.js +0 -14
  184. package/dist/assets/index-CHUT_bDS.css +0 -1
  185. package/dist/assets/index-DDInLQDd.js +0 -40
  186. package/dist/assets/ja-D7I9HofF.js +0 -16
  187. package/dist/assets/ko-BsVJM_PQ.js +0 -16
  188. package/dist/assets/main-De8Z5w49.js +0 -928
  189. package/dist/assets/markdownCore-BoQVG5-a.js +0 -3
  190. package/dist/assets/patchFileDiff-Chmiz6hq.js +0 -10
  191. package/dist/assets/pl-XR9Bs8Be.js +0 -16
  192. package/dist/assets/pt-BR-Due4be8g.js +0 -16
  193. package/dist/assets/renderElectronMiniChatApp-8tXADjfl.js +0 -2
  194. package/dist/assets/renderMobileApp-Cji7Hma5.js +0 -25
  195. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  196. package/dist/assets/scheduledTasksApi-9e-UX6im.js +0 -1
  197. package/dist/assets/tr-DBJcAv4y.js +0 -7
  198. package/dist/assets/uk-COYh2BaN.js +0 -16
  199. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  200. package/dist/assets/useRootScrollLock-KzOUytpn.js +0 -1
  201. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
  202. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  203. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
  204. package/dist/assets/zh-CN-Cjk6lzhc.js +0 -16
  205. package/dist/assets/zh-TW-Dk0dOg03.js +0 -16
@@ -46,6 +46,78 @@ const startIdleTick = async (fetchImpl) => {
46
46
  return { runtime, getSmallModelService };
47
47
  };
48
48
 
49
+ const assistantMessage = (id, infoOverrides = {}) => ({
50
+ info: {
51
+ id,
52
+ sessionID: SESSION_ID,
53
+ role: 'assistant',
54
+ providerID: 'provider',
55
+ modelID: 'model',
56
+ time: { created: 2, completed: 2 },
57
+ tokens: { input: 1, output: 1, cache: { read: 0 } },
58
+ ...infoOverrides,
59
+ },
60
+ parts: [{ type: 'text', text: 'The agent made progress.' }],
61
+ });
62
+
63
+ const createRuntimeHarness = ({ messages, messageFactory, goalOverrides = {}, maxAutoTurns = 20 }) => {
64
+ const requests = [];
65
+ let messageFetchCount = 0;
66
+ const activeSession = {
67
+ ...session,
68
+ metadata: { openchamber: { goal: { ...goal, ...goalOverrides } } },
69
+ };
70
+ const service = {
71
+ generateSmallModelText: vi.fn(async () => ({
72
+ text: '{"verdict":"continue","note":"More work remains"}',
73
+ providerID: 'provider',
74
+ modelID: 'model',
75
+ })),
76
+ };
77
+ const fetchImpl = vi.fn(async (input, init = {}) => {
78
+ const pathname = requestPath(input);
79
+ requests.push({ pathname, method: init.method ?? 'GET', body: init.body });
80
+ if (pathname === `/session/${SESSION_ID}` && init.method === 'PATCH') {
81
+ activeSession.metadata = JSON.parse(init.body).metadata;
82
+ return jsonResponse(activeSession);
83
+ }
84
+ if (pathname === `/session/${SESSION_ID}`) return jsonResponse(activeSession);
85
+ if (pathname === '/session/status') return jsonResponse({});
86
+ if (pathname === `/session/${SESSION_ID}/children`) return jsonResponse([]);
87
+ if (pathname === `/session/${SESSION_ID}/message`) {
88
+ const nextMessages = messageFactory ? messageFactory(messageFetchCount) : messages;
89
+ messageFetchCount += 1;
90
+ return jsonResponse(nextMessages);
91
+ }
92
+ if (pathname === `/session/${SESSION_ID}/prompt_async`) return jsonResponse({ ok: true });
93
+ throw new Error(`Unexpected request: ${pathname}`);
94
+ });
95
+ vi.stubGlobal('fetch', fetchImpl);
96
+ const runtime = createSessionGoalRuntime({
97
+ buildOpenCodeUrl: (pathname) => `http://opencode.test${pathname}`,
98
+ getOpenCodeAuthHeaders: () => ({}),
99
+ getSmallModelService: async () => service,
100
+ isEnabled: () => true,
101
+ idleQuietMs: 10,
102
+ maxAutoTurns,
103
+ });
104
+ return { runtime, requests, service, activeSession };
105
+ };
106
+
107
+ const runIdleTick = async (runtime) => {
108
+ runtime.processPayload({
109
+ type: 'session.status',
110
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
111
+ });
112
+ await vi.runOnlyPendingTimersAsync();
113
+ };
114
+
115
+ const lastPatchedGoal = (requests) => {
116
+ const patches = requests.filter((request) => request.pathname === `/session/${SESSION_ID}` && request.method === 'PATCH');
117
+ expect(patches.length).toBeGreaterThan(0);
118
+ return JSON.parse(patches.at(-1).body).metadata.openchamber.goal;
119
+ };
120
+
49
121
  describe('session goal live activity gate', () => {
50
122
  beforeEach(() => {
51
123
  vi.useFakeTimers();
@@ -178,4 +250,358 @@ describe('session goal live activity gate', () => {
178
250
  });
179
251
  runtime.stop();
180
252
  });
253
+
254
+ it('skips audit and sends continuation prompt when assistant message finishes with length stop', async () => {
255
+ const requests = [];
256
+ const fetchImpl = vi.fn(async (input, init = {}) => {
257
+ const pathname = requestPath(input);
258
+ requests.push({ pathname, method: init.method ?? 'GET', body: init.body });
259
+ if (pathname === `/session/${SESSION_ID}` && init.method === 'PATCH') return jsonResponse(session);
260
+ if (pathname === `/session/${SESSION_ID}`) return jsonResponse(session);
261
+ if (pathname === '/session/status') return jsonResponse({});
262
+ if (pathname === `/session/${SESSION_ID}/children`) return jsonResponse([]);
263
+ if (pathname === `/session/${SESSION_ID}/prompt_async`) return jsonResponse({ ok: true });
264
+ if (pathname === `/session/${SESSION_ID}/message`) {
265
+ return jsonResponse([{
266
+ info: {
267
+ id: 'msg_assistant_len',
268
+ sessionID: SESSION_ID,
269
+ role: 'assistant',
270
+ providerID: 'provider',
271
+ modelID: 'model',
272
+ finish: 'length',
273
+ time: { completed: 2 },
274
+ tokens: { input: 100, output: 4096, reasoning: 4096, cache: { read: 0 } },
275
+ },
276
+ parts: [{ type: 'reasoning', text: 'Drafting extensive implementation...' }],
277
+ }]);
278
+ }
279
+ throw new Error(`Unexpected request: ${pathname}`);
280
+ });
281
+ const service = {
282
+ generateSmallModelText: vi.fn(),
283
+ };
284
+ vi.stubGlobal('fetch', fetchImpl);
285
+ const runtime = createSessionGoalRuntime({
286
+ buildOpenCodeUrl: (pathname) => `http://opencode.test${pathname}`,
287
+ getOpenCodeAuthHeaders: () => ({}),
288
+ getSmallModelService: async () => service,
289
+ isEnabled: () => true,
290
+ idleQuietMs: 10,
291
+ });
292
+
293
+ runtime.processPayload({
294
+ type: 'session.status',
295
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
296
+ });
297
+ await vi.runOnlyPendingTimersAsync();
298
+
299
+ // Audit must be skipped on length-truncated turn
300
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
301
+
302
+ // Goal accounting is persisted and turnsUsed incremented
303
+ const patch = requests.find((request) => request.pathname === `/session/${SESSION_ID}` && request.method === 'PATCH');
304
+ expect(patch).toBeDefined();
305
+ const writtenGoal = JSON.parse(patch.body).metadata.openchamber.goal;
306
+ expect(writtenGoal).toMatchObject({
307
+ status: 'active',
308
+ turnsUsed: 2,
309
+ });
310
+
311
+ // Continuation prompt is dispatched
312
+ const promptAsync = requests.find((request) => request.pathname === `/session/${SESSION_ID}/prompt_async` && request.method === 'POST');
313
+ expect(promptAsync).toBeDefined();
314
+ const promptBody = JSON.parse(promptAsync.body);
315
+ expect(promptBody.parts[0].text).toContain('Continue working toward the active session goal.');
316
+ runtime.stop();
317
+ });
318
+
319
+ it('skips audit and sends continuation prompt when assistant message carries MessageOutputLengthError', async () => {
320
+ const requests = [];
321
+ const fetchImpl = vi.fn(async (input, init = {}) => {
322
+ const pathname = requestPath(input);
323
+ requests.push({ pathname, method: init.method ?? 'GET', body: init.body });
324
+ if (pathname === `/session/${SESSION_ID}` && init.method === 'PATCH') return jsonResponse(session);
325
+ if (pathname === `/session/${SESSION_ID}`) return jsonResponse(session);
326
+ if (pathname === '/session/status') return jsonResponse({});
327
+ if (pathname === `/session/${SESSION_ID}/children`) return jsonResponse([]);
328
+ if (pathname === `/session/${SESSION_ID}/prompt_async`) return jsonResponse({ ok: true });
329
+ if (pathname === `/session/${SESSION_ID}/message`) {
330
+ return jsonResponse([{
331
+ info: {
332
+ id: 'msg_assistant_len_err',
333
+ sessionID: SESSION_ID,
334
+ role: 'assistant',
335
+ providerID: 'provider',
336
+ modelID: 'model',
337
+ error: { name: 'MessageOutputLengthError', message: 'Maximum token limit reached' },
338
+ time: { completed: 2 },
339
+ tokens: { input: 100, output: 4096, reasoning: 4096, cache: { read: 0 } },
340
+ },
341
+ parts: [{ type: 'reasoning', text: 'Drafting extensive implementation...' }],
342
+ }]);
343
+ }
344
+ throw new Error(`Unexpected request: ${pathname}`);
345
+ });
346
+ const service = {
347
+ generateSmallModelText: vi.fn(),
348
+ };
349
+ vi.stubGlobal('fetch', fetchImpl);
350
+ const runtime = createSessionGoalRuntime({
351
+ buildOpenCodeUrl: (pathname) => `http://opencode.test${pathname}`,
352
+ getOpenCodeAuthHeaders: () => ({}),
353
+ getSmallModelService: async () => service,
354
+ isEnabled: () => true,
355
+ idleQuietMs: 10,
356
+ });
357
+
358
+ runtime.processPayload({
359
+ type: 'session.status',
360
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
361
+ });
362
+ await vi.runOnlyPendingTimersAsync();
363
+
364
+ // Audit must be skipped on MessageOutputLengthError
365
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
366
+
367
+ // Goal remains active and turnsUsed incremented
368
+ const patch = requests.find((request) => request.pathname === `/session/${SESSION_ID}` && request.method === 'PATCH');
369
+ expect(patch).toBeDefined();
370
+ const writtenGoal = JSON.parse(patch.body).metadata.openchamber.goal;
371
+ expect(writtenGoal).toMatchObject({
372
+ status: 'active',
373
+ turnsUsed: 2,
374
+ });
375
+
376
+ // Continuation prompt is dispatched
377
+ const promptAsync = requests.find((request) => request.pathname === `/session/${SESSION_ID}/prompt_async` && request.method === 'POST');
378
+ expect(promptAsync).toBeDefined();
379
+ runtime.stop();
380
+ });
381
+
382
+ it.each([
383
+ { name: 'APIError', error: { name: 'APIError', message: 'provider failed' } },
384
+ { name: 'StructuredOutputError', error: { name: 'StructuredOutputError', message: 'invalid output' } },
385
+ { name: 'unnamed errors', error: {} },
386
+ ])('blocks a length finish when the assistant also has a non-length $name', async ({ error }) => {
387
+ const { runtime, requests, service } = createRuntimeHarness({
388
+ messages: [assistantMessage('msg_assistant_error', { finish: 'length', error })],
389
+ });
390
+
391
+ await runIdleTick(runtime);
392
+
393
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
394
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
395
+ expect(lastPatchedGoal(requests)).toMatchObject({
396
+ status: 'blocked',
397
+ statusReason: error.name || 'assistant turn failed',
398
+ });
399
+ runtime.stop();
400
+ });
401
+
402
+ it('blocks after two consecutive length-truncated agent turns without persisting a counter, regardless of message IDs', async () => {
403
+ const firstLength = assistantMessage('z', { finish: 'length', time: { created: 10, completed: 11 } });
404
+ const summary = assistantMessage('summary', { summary: true, time: { created: 15, completed: 16 } });
405
+ const secondLength = assistantMessage('a', { finish: 'length', time: { created: 20, completed: 21 } });
406
+ const { runtime, requests, service } = createRuntimeHarness({
407
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, summary, secondLength],
408
+ });
409
+
410
+ await runIdleTick(runtime);
411
+ runtime.processPayload({
412
+ type: 'session.status',
413
+ properties: { sessionID: SESSION_ID, status: { type: 'idle' }, directory: DIRECTORY },
414
+ });
415
+ await vi.runOnlyPendingTimersAsync();
416
+
417
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
418
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(1);
419
+ expect(lastPatchedGoal(requests)).toMatchObject({
420
+ status: 'blocked',
421
+ statusReason: 'repeated output truncation',
422
+ });
423
+ runtime.stop();
424
+ });
425
+
426
+ it('allows one explicit Resume after repeated truncation, then blocks another cutoff', async () => {
427
+ const first = assistantMessage('first', { finish: 'length', time: { created: 10, completed: 11 } });
428
+ const second = assistantMessage('second', { finish: 'length', time: { created: 20, completed: 21 } });
429
+ const messages = [first, second];
430
+ const { runtime, requests, activeSession } = createRuntimeHarness({ messages });
431
+ try {
432
+ await runIdleTick(runtime);
433
+ expect(lastPatchedGoal(requests).status).toBe('blocked');
434
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(0);
435
+ Object.assign(activeSession.metadata.openchamber.goal, { status: 'active', statusReason: 'resumed', turnsUsed: 0 });
436
+ await runIdleTick(runtime);
437
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active', statusReason: '', turnsUsed: 1 });
438
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(1);
439
+ messages.push(assistantMessage('third', { finish: 'length', time: { created: 30, completed: 31 } }));
440
+ await runIdleTick(runtime);
441
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'blocked', statusReason: 'repeated output truncation' });
442
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(1);
443
+ } finally {
444
+ runtime.stop();
445
+ }
446
+ });
447
+
448
+ it.each([
449
+ { tokenBudget: 1, error: undefined, expectedStatus: 'budgetLimited' },
450
+ { tokenBudget: null, error: { name: 'APIError' }, expectedStatus: 'blocked' },
451
+ ])('keeps $expectedStatus protection on explicit Resume', async ({ tokenBudget, error, expectedStatus }) => {
452
+ const { runtime, requests } = createRuntimeHarness({
453
+ goalOverrides: { statusReason: 'resumed', tokenBudget },
454
+ messages: [assistantMessage('resumed', { finish: 'length', error })],
455
+ });
456
+ try {
457
+ await runIdleTick(runtime);
458
+ expect(lastPatchedGoal(requests).status).toBe(expectedStatus);
459
+ expect(requests.filter((request) => request.pathname.endsWith('/prompt_async'))).toHaveLength(0);
460
+ } finally {
461
+ runtime.stop();
462
+ }
463
+ });
464
+
465
+ it('continues after a truncated agent turn followed by a length-finished summary', async () => {
466
+ const firstLength = assistantMessage('agent-length', { finish: 'length', time: { created: 10, completed: 11 } });
467
+ const summary = assistantMessage('summary', {
468
+ summary: true,
469
+ finish: 'length',
470
+ time: { created: 15, completed: 16 },
471
+ });
472
+ const { runtime, requests, service } = createRuntimeHarness({
473
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, summary],
474
+ });
475
+
476
+ await runIdleTick(runtime);
477
+ await runIdleTick(runtime);
478
+
479
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
480
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
481
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
482
+ runtime.stop();
483
+ });
484
+
485
+ it('does not infer a repeated streak when a completed assistant timestamp is missing', async () => {
486
+ const firstLength = assistantMessage('z', { finish: 'length', time: { completed: 11 } });
487
+ const secondLength = assistantMessage('a', { finish: 'length', time: { created: 20, completed: 21 } });
488
+ const { runtime, requests, service } = createRuntimeHarness({
489
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, secondLength],
490
+ });
491
+
492
+ await runIdleTick(runtime);
493
+ await runIdleTick(runtime);
494
+
495
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
496
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
497
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
498
+ runtime.stop();
499
+ });
500
+
501
+ it('ignores a missing timestamp on an older assistant when known post-goal turns establish a streak', async () => {
502
+ const olderLength = assistantMessage('legacy', { finish: 'length', time: { completed: 5 } });
503
+ const firstLength = assistantMessage('z', { finish: 'length', time: { created: 10, completed: 11 } });
504
+ const secondLength = assistantMessage('a', { finish: 'length', time: { created: 20, completed: 21 } });
505
+ const { runtime, requests, service } = createRuntimeHarness({
506
+ goalOverrides: { createdAt: 6 },
507
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [olderLength, firstLength, secondLength],
508
+ });
509
+
510
+ await runIdleTick(runtime);
511
+ await runIdleTick(runtime);
512
+
513
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
514
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(1);
515
+ expect(lastPatchedGoal(requests)).toMatchObject({
516
+ status: 'blocked',
517
+ statusReason: 'repeated output truncation',
518
+ });
519
+ runtime.stop();
520
+ });
521
+
522
+ it('does not count a previous truncated turn created at the goal boundary', async () => {
523
+ const firstLength = assistantMessage('before-boundary', { finish: 'length', time: { created: 10, completed: 11 } });
524
+ const secondLength = assistantMessage('after-boundary', { finish: 'length', time: { created: 20, completed: 21 } });
525
+ const { runtime, requests, service } = createRuntimeHarness({
526
+ goalOverrides: { createdAt: 10 },
527
+ messageFactory: (fetchCount) => fetchCount < 2 ? [firstLength] : [firstLength, secondLength],
528
+ });
529
+
530
+ await runIdleTick(runtime);
531
+ await runIdleTick(runtime);
532
+
533
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
534
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
535
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
536
+ runtime.stop();
537
+ });
538
+
539
+ it('allows length recovery after an ordinary assistant turn breaks the streak', async () => {
540
+ const firstLength = assistantMessage('msg_length_before_normal', { finish: 'length' });
541
+ const normal = assistantMessage('msg_normal');
542
+ const secondLength = assistantMessage('msg_length_after_normal', { finish: 'length' });
543
+ const { runtime, requests, service } = createRuntimeHarness({
544
+ messageFactory: (fetchCount) => fetchCount < 2
545
+ ? [firstLength]
546
+ : [firstLength, normal, secondLength],
547
+ });
548
+
549
+ await runIdleTick(runtime);
550
+ await runIdleTick(runtime);
551
+
552
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
553
+ expect(requests.filter((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toHaveLength(2);
554
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'active' });
555
+ runtime.stop();
556
+ });
557
+
558
+ it('keeps MessageAbortedError pause behavior instead of continuing', async () => {
559
+ const { runtime, requests, service } = createRuntimeHarness({
560
+ messages: [assistantMessage('msg_aborted', { error: { name: 'MessageAbortedError' } })],
561
+ });
562
+
563
+ await runIdleTick(runtime);
564
+
565
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
566
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
567
+ expect(lastPatchedGoal(requests)).toMatchObject({
568
+ status: 'paused',
569
+ statusReason: 'paused after abort',
570
+ });
571
+ runtime.stop();
572
+ });
573
+
574
+ it('checks the token budget before allowing length recovery', async () => {
575
+ const { runtime, requests, service } = createRuntimeHarness({
576
+ goalOverrides: { tokenBudget: 5 },
577
+ messages: [assistantMessage('msg_budget_length', {
578
+ finish: 'length',
579
+ tokens: { input: 3, output: 3, cache: { read: 0 } },
580
+ })],
581
+ });
582
+
583
+ await runIdleTick(runtime);
584
+
585
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
586
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
587
+ expect(lastPatchedGoal(requests)).toMatchObject({ status: 'budgetLimited' });
588
+ runtime.stop();
589
+ });
590
+
591
+ it('checks the auto-continuation cap before allowing length recovery', async () => {
592
+ const { runtime, requests, service } = createRuntimeHarness({
593
+ maxAutoTurns: 1,
594
+ messages: [assistantMessage('msg_cap_length', { finish: 'length' })],
595
+ });
596
+
597
+ await runIdleTick(runtime);
598
+
599
+ expect(service.generateSmallModelText).not.toHaveBeenCalled();
600
+ expect(requests.some((request) => request.pathname === `/session/${SESSION_ID}/prompt_async`)).toBe(false);
601
+ expect(lastPatchedGoal(requests)).toMatchObject({
602
+ status: 'blocked',
603
+ statusReason: 'auto-continuation limit reached',
604
+ });
605
+ runtime.stop();
606
+ });
181
607
  });
@@ -58,7 +58,7 @@ The following functions are internal helpers used by exported functions:
58
58
  - `safeRm(dir)`: Safely remove directory recursively (ignores errors).
59
59
  - `ensureDir(dirPath)`: Ensure directory exists with recursive creation.
60
60
  - `copyDirectoryNoSymlinks(srcDir, dstDir)`: Copy directory contents without symlinks, with path traversal protection.
61
- - `normalizeUserSkillDir(userSkillDir)`: Normalize user skill directory path (handles legacy `~/.config/opencode/skill` → `~/.config/opencode/skills` migration).
61
+ - `normalizeUserSkillDir(userSkillDir)`: Normalize the user skill directory path (handles the legacy `skill` directory in the XDG config location, or `~/.config/opencode/skill` when XDG is unset, by selecting the plural `skills` directory when appropriate).
62
62
 
63
63
  ### Git Clone Helpers (`install.js`, `scan.js`)
64
64
  - `cloneRepo({ cloneUrl, identity, tempDir })`: Clone git repository with preferred partial clone (`--filter=blob:none`) and fallback. Uses non-interactive mode.
@@ -4,13 +4,14 @@ import path from 'path';
4
4
 
5
5
  import { assertGitAvailable, looksLikeAuthError, runGit } from './git.js';
6
6
  import { parseSkillRepoSource } from './source.js';
7
+ import { OPENCODE_CONFIG_DIR } from '../opencode/shared.js';
7
8
 
8
9
  const SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/;
9
10
 
10
11
  function normalizeUserSkillDir(userSkillDir) {
11
12
  if (!userSkillDir) return null;
12
- const legacySkillDir = path.join(os.homedir(), '.config', 'opencode', 'skill');
13
- const pluralSkillDir = path.join(os.homedir(), '.config', 'opencode', 'skills');
13
+ const legacySkillDir = path.join(OPENCODE_CONFIG_DIR, 'skill');
14
+ const pluralSkillDir = path.join(OPENCODE_CONFIG_DIR, 'skills');
14
15
  if (userSkillDir === legacySkillDir) {
15
16
  if (fs.existsSync(legacySkillDir) && !fs.existsSync(pluralSkillDir)) return legacySkillDir;
16
17
  return pluralSkillDir;
@@ -117,8 +117,9 @@ other runtime API.
117
117
  - Everything else: OpenAI-compatible `/chat/completions` against the
118
118
  provider's base URL, resolved from (1) `provider.<id>.options.baseURL`
119
119
  in the OpenCode config, (2) the hardcoded `https://api.openai.com/v1`
120
- endpoint, (3) the endpoint OpenCode resolved at runtime, or (4) the
121
- provider's `api` field from the models.dev catalog. The credential follows
120
+ endpoint, (3) the selected model's endpoint OpenCode resolved at runtime,
121
+ (4) the provider-level runtime endpoint, or (5) the provider's `api` field
122
+ from the models.dev catalog. The credential follows
122
123
  the same shape: config `options.apiKey`, then the runtime credential, then
123
124
  the auth.json entry. `provider.<id>.options.headers` is sent with the
124
125
  request and overrides the bearer default, so gateways that authenticate on
@@ -606,6 +606,8 @@ const readProviderConfig = (workingDirectory, providerID) => {
606
606
  }
607
607
  }
608
608
 
609
+ const getRuntimeModel = (runtimeProvider, modelID) => runtimeProvider?.models?.get(modelID) ?? null;
610
+
609
611
  // ---------------------------------------------------------------------------
610
612
  // Dispatch
611
613
  // ---------------------------------------------------------------------------
@@ -650,6 +652,7 @@ export async function callSmallModel({ auth, catalog, workingDirectory, sessionI
650
652
  const tokens = Number(maxOutputTokens) > 0 ? Number(maxOutputTokens) : DEFAULT_MAX_OUTPUT_TOKENS;
651
653
  const providerConfig = readProviderConfig(workingDirectory, providerID);
652
654
  const runtimeProvider = await getRuntimeProvider(providerID);
655
+ const runtimeModel = getRuntimeModel(runtimeProvider, modelID);
653
656
  // Match OpenCode's resolveSDK precedence: config `provider.<id>.options`
654
657
  // wins, then what OpenCode itself resolved at runtime (the only place a
655
658
  // plugin's credential exists), and the auth.json entry last.
@@ -759,9 +762,10 @@ export async function callSmallModel({ auth, catalog, workingDirectory, sessionI
759
762
  // base URL for that provider (openai itself included). When a custom provider
760
763
  // is not in the catalog (e.g. a user-configured OpenAI-compatible proxy),
761
764
  // fall back to its baseURL from the OpenCode provider config, then to the
762
- // endpoint OpenCode resolved at runtime — which for a plugin provider is the
763
- // only place it exists, and for several of them is a local proxy the plugin
764
- // itself runs. The openai provider also respects
765
+ // selected model's endpoint OpenCode resolved at runtime, then to the
766
+ // provider-level runtime endpoint. For a plugin provider, the runtime listing
767
+ // is the only place those endpoints exist, and several are local proxies the
768
+ // plugin itself runs. The openai provider also respects
765
769
  // provider.openai.options.baseURL — OpenCode itself uses the same config for
766
770
  // all providers including openai.
767
771
  const provider = getCatalogProvider(catalog, providerID);
@@ -771,7 +775,8 @@ export async function callSmallModel({ auth, catalog, workingDirectory, sessionI
771
775
  ? providerConfigUrl
772
776
  : providerID === 'openai'
773
777
  ? defaultOpenaiUrl
774
- : runtimeProvider?.baseURL
778
+ : runtimeModel?.api?.url
779
+ ?? runtimeProvider?.baseURL
775
780
  ?? (typeof provider?.api === 'string' && provider.api
776
781
  ? provider.api
777
782
  : null);
@@ -565,6 +565,35 @@ describe('callSmallModel — custom provider config', () => {
565
565
  expect(init.headers.Authorization).toBe('Bearer plugin-key');
566
566
  });
567
567
 
568
+ it('uses the selected runtime model endpoint', async () => {
569
+ readConfig.mockReturnValue({});
570
+ getRuntimeProvider.mockResolvedValue({
571
+ id: 'runtime-provider',
572
+ apiKey: 'plugin-key',
573
+ baseURL: 'https://runtime-provider/v1beta',
574
+ models: new Map([
575
+ ['first-model', { api: { url: 'https://runtime-provider/v1beta', npm: '@ai-sdk/google' } }],
576
+ ['selected-model', { api: { url: 'https://runtime-provider/v1', npm: '@ai-sdk/openai' } }],
577
+ ]),
578
+ anonymousZen: false,
579
+ });
580
+ fetchMock.mockResolvedValue(ok('done'));
581
+
582
+ await callSmallModel({
583
+ auth: {},
584
+ catalog: {},
585
+ workingDirectory: '/proj',
586
+ providerID: 'runtime-provider',
587
+ modelID: 'selected-model',
588
+ prompt: 'hi',
589
+ });
590
+
591
+ const { url, init } = lastCall(fetchMock);
592
+ expect(url).toBe('https://runtime-provider/v1/chat/completions');
593
+ expect(url).not.toContain('/v1beta');
594
+ expect(JSON.parse(init.body).model).toBe('selected-model');
595
+ });
596
+
568
597
  it('keeps the ChatGPT-plan login on its own transport instead of the runtime key', async () => {
569
598
  readConfig.mockReturnValue({});
570
599
  // OpenCode reports an OAuth access token as `options.apiKey` for openai;
@@ -6,6 +6,7 @@ import { readConfigLayers } from '../opencode/shared.js';
6
6
  import { getModelCatalog } from './catalog.js';
7
7
  import { resolveSmallModel, parseModelRef, isUsableAuthEntry, getAuthEntryForProvider } from './resolve.js';
8
8
  import { DEDICATED_WIRE_FORMAT_PROVIDERS, callSmallModel, resolveProviderLogin } from './call.js';
9
+ import { readMergedSettingsSync } from '../opencode/settings-files.js';
9
10
  import { getRuntimeProviderSnapshot } from './runtime-providers.js';
10
11
 
11
12
  // Never a small model, whatever the transport looks like. A plugin can publish
@@ -26,16 +27,10 @@ const OPENCHAMBER_SETTINGS_FILE = path.join(
26
27
  // OpenChamber's own settings: when the user unchecks "use default small model"
27
28
  // their explicit override outranks every other resolution step.
28
29
  const readSmallModelSettingsOverride = () => {
29
- try {
30
- const raw = fs.readFileSync(OPENCHAMBER_SETTINGS_FILE, 'utf8');
31
- const settings = JSON.parse(raw);
32
- if (!settings || typeof settings !== 'object') return null;
33
- if (settings.smallModelUseDefault !== false) return null;
34
- const override = typeof settings.smallModelOverride === 'string' ? settings.smallModelOverride.trim() : '';
35
- return override || null;
36
- } catch {
37
- return null;
38
- }
30
+ const settings = readMergedSettingsSync({ fs, path, settingsFilePath: OPENCHAMBER_SETTINGS_FILE });
31
+ if (settings.smallModelUseDefault !== false) return null;
32
+ const override = typeof settings.smallModelOverride === 'string' ? settings.smallModelOverride.trim() : '';
33
+ return override || null;
39
34
  };
40
35
 
41
36
  // Rough safety clamp so a huge input never blows the model's context window.
@@ -8,7 +8,8 @@
8
8
  //
9
9
  // `GET /provider` is where that state becomes visible. It reports, per
10
10
  // provider, the resolved `options.baseURL` and `options.apiKey`, and per model
11
- // the wire adapter (`api.npm`) and endpoint (`api.url`).
11
+ // the wire adapter (`api.npm`) and endpoint (`api.url`). The provider-level
12
+ // endpoint remains only as a fallback when the selected model has no endpoint.
12
13
  //
13
14
  // What it does NOT report is `options.fetch`. OpenCode strips functions from
14
15
  // the response, and a plugin is free to put its whole protocol in there:
@@ -61,8 +62,8 @@ export function resetOpenCodeRuntimeProviders() {
61
62
  /**
62
63
  * The boundary. Everything the `/provider` payload claims is checked here, so
63
64
  * the rest of this module and its callers work with settled values:
64
- * a credential we may use, an endpoint, and whether the provider is the
65
- * anonymous zen case.
65
+ * a credential we may use, provider and model endpoints, and whether the
66
+ * provider is the anonymous zen case.
66
67
  *
67
68
  * The credential deliberately prefers `options.apiKey` over the `key` field:
68
69
  * for a plugin provider the former is what its auth loader produced and what
@@ -82,13 +83,22 @@ function parseProviderListing(payload) {
82
83
  const id = text(record(raw).id);
83
84
  if (!id) continue;
84
85
  const options = record(record(raw).options);
85
- const firstModel = record(Object.values(record(record(raw).models))[0]);
86
+ const models = new Map();
87
+ for (const [modelID, rawModel] of Object.entries(record(record(raw).models))) {
88
+ const model = record(rawModel);
89
+ const api = record(model.api);
90
+ const modelURL = endpoint(api.url);
91
+ const modelNpm = text(api.npm);
92
+ models.set(modelID, { api: { url: modelURL, npm: modelNpm } });
93
+ }
94
+ const firstModel = models.values().next().value;
86
95
  const declaredKey = text(options.apiKey);
87
96
  providers.set(id, {
88
97
  id,
89
98
  source: text(record(raw).source),
90
99
  apiKey: declaredKey === ZEN_ANONYMOUS_API_KEY ? null : (declaredKey ?? text(record(raw).key)),
91
- baseURL: endpoint(options.baseURL) ?? endpoint(record(firstModel.api).url),
100
+ baseURL: endpoint(options.baseURL) ?? firstModel?.api?.url ?? null,
101
+ models,
92
102
  // True only for the zen-without-login case: a provider that is present
93
103
  // and usable through OpenCode, but that we must not call ourselves.
94
104
  anonymousZen: declaredKey === ZEN_ANONYMOUS_API_KEY,
@@ -152,5 +162,3 @@ export async function getRuntimeProvider(providerID) {
152
162
  const current = await getRuntimeProviderSnapshot();
153
163
  return current?.providers.get(providerID) ?? null;
154
164
  }
155
-
156
-
@@ -14,7 +14,10 @@ const providerPayload = (overrides = {}) => ({
14
14
  id: 'llmapi',
15
15
  source: 'config',
16
16
  options: { apiKey: 'plugin-key', baseURL: 'https://api.llmapi.ai/v1/' },
17
- models: { 'claude-opus-4-8': { api: { id: 'claude-opus-4-8', url: '', npm: '@ai-sdk/anthropic' } } },
17
+ models: {
18
+ 'claude-opus-4-8': { api: { id: 'claude-opus-4-8', url: '', npm: '@ai-sdk/anthropic' } },
19
+ 'gpt-5.6-luna': { api: { id: 'gpt-5.6-luna', url: 'https://api.llmapi.ai/v1', npm: '@ai-sdk/openai' } },
20
+ },
18
21
  },
19
22
  {
20
23
  id: 'opencode',
@@ -59,6 +62,9 @@ describe('OpenCode runtime provider snapshot', () => {
59
62
  const provider = await getRuntimeProvider('llmapi');
60
63
 
61
64
  expect(provider).toMatchObject({ apiKey: 'plugin-key', baseURL: 'https://api.llmapi.ai/v1' });
65
+ expect(provider.models.get('gpt-5.6-luna')).toEqual({
66
+ api: { url: 'https://api.llmapi.ai/v1', npm: '@ai-sdk/openai' },
67
+ });
62
68
  expect(fetchMock.mock.calls[0][0]).toBe('http://127.0.0.1:4096/provider');
63
69
  expect(fetchMock.mock.calls[0][1].headers).toMatchObject({ Authorization: 'Basic test' });
64
70
  });