@openchamber/web 1.22.1 → 1.22.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 (111) hide show
  1. package/bin/cli.js +4 -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-BI-TY1UG.js} +1 -1
  6. package/dist/assets/{DiffView-CNnDxRmO.js → DiffView-cOmByCaX.js} +3 -3
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-BwSnDlNy.js} +1 -1
  8. package/dist/assets/FilesView-DRRy_6oZ.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-B7YCg1YM.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-CjzNsiIU.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BYlE0YrW.js} +1 -1
  12. package/dist/assets/{MarkdownImageGallery-DffjmciG.js → MarkdownImageGallery-DlTF-wua.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-CqgeZRlP.js +12 -0
  14. package/dist/assets/{OnboardingScreen-CTZe6HZn.js → OnboardingScreen-BsJU7oav.js} +1 -1
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CDNu968J.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BvwtCxW4.js → PierreDiffViewer-BoBsAanf.js} +1 -1
  17. package/dist/assets/{PlanView-C1qvAm7m.js → PlanView-Cxr8LQT1.js} +4 -4
  18. package/dist/assets/SettingsView-bsKpCZbB.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-B0rHQdw4.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-6zP8hwzX.js} +6 -6
  21. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-Bvwh4Y31.js} +2 -2
  22. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-aaIfrRxl.js} +1 -1
  23. package/dist/assets/{WalkthroughView-D-HFgdmM.js → WalkthroughView-baZ0ssy9.js} +2 -2
  24. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-DfgllYQc.js} +2 -2
  25. package/dist/assets/{contextPanelEmbeddedChat-CV-DwAiX.js → contextPanelEmbeddedChat-prHos-tt.js} +1 -1
  26. package/dist/assets/{de-Cv_4FoXm.js → de-hknQLFxa.js} +2 -2
  27. package/dist/assets/{es-BIWNEbnS.js → es-C_bD3kvW.js} +2 -2
  28. package/dist/assets/{fr-SD3OfMHJ.js → fr-BVF-C2Nu.js} +2 -2
  29. package/dist/assets/index-B0aX0JeI.js +39 -0
  30. package/dist/assets/{index-DLiD86ge.js → index-DUwZ2cWA.js} +1 -1
  31. package/dist/assets/index-Dl3xbAB_.css +1 -0
  32. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-COIS9Df5.js} +1 -1
  33. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-D7LEG-KY.js} +1 -1
  34. package/dist/assets/{ja-D7I9HofF.js → ja-B2G5hD59.js} +2 -2
  35. package/dist/assets/{ko-BsVJM_PQ.js → ko-D6OrOdZ3.js} +2 -2
  36. package/dist/assets/main-BBuBZzoi.js +930 -0
  37. package/dist/assets/{main-DCB4JgVe.js → main-CwIEELQq.js} +2 -2
  38. package/dist/assets/{markdownCore-BoQVG5-a.js → markdownCore-BE_Hhps5.js} +2 -2
  39. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CeXAoWiF.js} +2 -2
  40. package/dist/assets/{mobile-DZV_sfX7.js → mobile-ilq39yLQ.js} +2 -2
  41. package/dist/assets/{patchFileDiff-Chmiz6hq.js → patchFileDiff-DLky6SYr.js} +5 -5
  42. package/dist/assets/{pl-XR9Bs8Be.js → pl-CVroZXt1.js} +2 -2
  43. package/dist/assets/{pt-BR-Due4be8g.js → pt-BR-eH3onaIW.js} +2 -2
  44. package/dist/assets/{renderElectronMiniChatApp-8tXADjfl.js → renderElectronMiniChatApp-BsywqmJT.js} +2 -2
  45. package/dist/assets/{renderMobileApp-Cji7Hma5.js → renderMobileApp-CDun1795.js} +7 -7
  46. package/dist/assets/runtimeEndpointReset-DebJIo5U.js +17 -0
  47. package/dist/assets/{scheduledTasksApi-9e-UX6im.js → scheduledTasksApi-B0tChXQC.js} +1 -1
  48. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-DJSXdcG4.js} +1 -1
  49. package/dist/assets/tr-BvtU2tXS.js +7 -0
  50. package/dist/assets/{uk-COYh2BaN.js → uk-nu36iqFz.js} +2 -2
  51. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-Bb1Zihd2.js} +134 -131
  52. package/dist/assets/useInlineCommentController-B8dQWRpH.js +2 -0
  53. package/dist/assets/{useRootScrollLock-KzOUytpn.js → useRootScrollLock-DrJ8gE-x.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-CNjvbb69.js} +2 -2
  55. package/dist/assets/vendor-zod-CK21ihK-.js +39 -0
  56. package/dist/assets/{web-components-B6QgbmTo.js → web-components-C06MmTcR.js} +1 -1
  57. package/dist/assets/{zh-CN-Cjk6lzhc.js → zh-CN-BClBzZ64.js} +2 -2
  58. package/dist/assets/{zh-TW-Dk0dOg03.js → zh-TW-CXtSqJHF.js} +2 -2
  59. package/dist/index.html +5 -5
  60. package/dist/mini-chat.html +4 -4
  61. package/dist/mobile.html +4 -4
  62. package/package.json +3 -3
  63. package/server/index.js +7 -1
  64. package/server/lib/changelog/update-notes.js +82 -0
  65. package/server/lib/changelog/update-notes.test.js +59 -0
  66. package/server/lib/fs/DOCUMENTATION.md +2 -0
  67. package/server/lib/fs/routes.js +32 -21
  68. package/server/lib/fs/routes.test.js +77 -0
  69. package/server/lib/git/service.js +10 -0
  70. package/server/lib/git/service.test.js +18 -0
  71. package/server/lib/message-queue/DOCUMENTATION.md +17 -7
  72. package/server/lib/message-queue/runtime.js +59 -7
  73. package/server/lib/message-queue/runtime.test.js +59 -3
  74. package/server/lib/opencode/DOCUMENTATION.md +8 -4
  75. package/server/lib/opencode/config-paths.test.js +116 -0
  76. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  77. package/server/lib/opencode/input-history-scope.js +14 -0
  78. package/server/lib/opencode/plugins.js +2 -2
  79. package/server/lib/opencode/providers.js +44 -2
  80. package/server/lib/opencode/providers.test.js +131 -4
  81. package/server/lib/opencode/routes.js +4 -4
  82. package/server/lib/opencode/server-startup-runtime.js +1 -1
  83. package/server/lib/opencode/settings-helpers.js +28 -0
  84. package/server/lib/opencode/settings-helpers.test.js +177 -0
  85. package/server/lib/opencode/shared.js +4 -1
  86. package/server/lib/opencode/skill-routes.js +2 -1
  87. package/server/lib/opencode/snippets.js +1 -2
  88. package/server/lib/package-manager.js +3 -28
  89. package/server/lib/quota/utils/auth.js +1 -1
  90. package/server/lib/relay/host-client.test.js +9 -1
  91. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  92. package/server/lib/session-goal/runtime.js +76 -11
  93. package/server/lib/session-goal/runtime.test.js +426 -0
  94. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  95. package/server/lib/skills-catalog/install.js +3 -2
  96. package/server/lib/terminal/DOCUMENTATION.md +11 -7
  97. package/server/lib/terminal/runtime.js +150 -19
  98. package/server/lib/terminal/runtime.test.js +553 -26
  99. package/server/lib/terminal/shells.js +17 -0
  100. package/server/lib/terminal/shells.test.js +32 -1
  101. package/server/lib/walkthrough/routes.test.js +26 -5
  102. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  103. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  104. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  105. package/dist/assets/index-CHUT_bDS.css +0 -1
  106. package/dist/assets/index-DDInLQDd.js +0 -40
  107. package/dist/assets/main-De8Z5w49.js +0 -928
  108. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  109. package/dist/assets/tr-DBJcAv4y.js +0 -7
  110. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  111. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
@@ -220,6 +220,10 @@ export function createMessageQueueRuntime({
220
220
  const failures = new Map(); // sessionId → { itemId, failures, nextAttemptAt }
221
221
  const abortedAt = new Map(); // sessionId → timestamp
222
222
  const holds = new Map(); // sessionId → expiresAt
223
+ // sessionId → directory, kept after the queue empties: the UI keys its
224
+ // projection by directory, so the broadcast that removes the last item must
225
+ // still name it or the client cannot tell which queue just finished.
226
+ const directories = new Map();
223
227
 
224
228
  // --- persistence ---------------------------------------------------------
225
229
 
@@ -302,7 +306,7 @@ export function createMessageQueueRuntime({
302
306
  const queue = queues.get(sessionId);
303
307
  return {
304
308
  sessionId,
305
- directory: queue?.directory ?? '',
309
+ directory: queue?.directory ?? directories.get(sessionId) ?? '',
306
310
  items: (queue?.items ?? []).map(toPublicItem),
307
311
  sendingId: sending.get(sessionId) ?? null,
308
312
  };
@@ -329,6 +333,7 @@ export function createMessageQueueRuntime({
329
333
  };
330
334
 
331
335
  const setQueueItems = (sessionId, directory, items) => {
336
+ directories.set(sessionId, directory);
332
337
  if (items.length === 0) {
333
338
  queues.delete(sessionId);
334
339
  return;
@@ -385,8 +390,36 @@ export function createMessageQueueRuntime({
385
390
  const name = head.slice(1);
386
391
  if (!name) return null;
387
392
  const commands = asList(await openCodeFetch('/command', { directory })) ?? [];
388
- if (!commands.some((command) => asRecord(command)?.name === name)) return null;
389
- return { name, arguments: tail.join(' ') };
393
+ const match = commands.map(asRecord).find((command) => command?.name === name);
394
+ if (!match) return null;
395
+ return {
396
+ name,
397
+ arguments: tail.join(' '),
398
+ isSkill: match.source === 'skill',
399
+ template: asNonEmptyString(match.template),
400
+ };
401
+ };
402
+
403
+ /**
404
+ * The prompt a slash command stands for, expanded the way OpenCode expands
405
+ * it: `$ARGUMENTS` takes the whole argument string, `$1..$N` take quoted or
406
+ * bare words with the last position absorbing the rest, and a template with
407
+ * no placeholder gets the arguments appended. Twin of the UI's
408
+ * `expandSlashCommandGoalObjective` in `packages/ui/src/sync/session-ui-store.ts`.
409
+ */
410
+ const expandCommandTemplate = (template, argumentsText) => {
411
+ if (template.includes('$ARGUMENTS')) return template.replaceAll('$ARGUMENTS', argumentsText);
412
+ const positions = [...template.matchAll(/\$(\d+)/g)].map((match) => Number(match[1]));
413
+ if (positions.length > 0) {
414
+ const parsed = [...argumentsText.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)]
415
+ .map((match) => match[1] ?? match[2] ?? match[3] ?? '');
416
+ const last = Math.max(...positions);
417
+ return template.replace(/\$(\d+)/g, (_match, value) => {
418
+ const position = Number(value);
419
+ return position === last ? parsed.slice(position - 1).join(' ') : (parsed[position - 1] ?? '');
420
+ });
421
+ }
422
+ return argumentsText ? `${template}\n\n${argumentsText}` : template;
390
423
  };
391
424
 
392
425
  const toFilePart = (attachment) => ({
@@ -412,16 +445,31 @@ export function createMessageQueueRuntime({
412
445
  const { providerID, modelID, agent, variant } = item.sendConfig;
413
446
  const fileParts = item.attachments.map(toFilePart);
414
447
  const contextParts = item.context.flatMap(toContextParts);
448
+ // OpenCode's command route takes file parts only, so a command queued
449
+ // with captured context cannot go through it. Same rule as the composer:
450
+ // without context the command route keeps its semantics; with context the
451
+ // prompt route carries the expanded template (or the skill invocation as an
452
+ // explicit instruction) together with the context.
415
453
  const command = await resolveSlashCommand(item.text, directory);
416
- if (command) {
454
+ if (command && contextParts.length === 0) {
417
455
  const body = { command: command.name, arguments: command.arguments, model: `${providerID}/${modelID}` };
418
456
  if (agent) body.agent = agent;
419
457
  if (variant) body.variant = variant;
420
- const extraParts = [...fileParts, ...contextParts];
421
- if (extraParts.length > 0) body.parts = extraParts;
458
+ if (fileParts.length > 0) body.parts = fileParts;
422
459
  await openCodeFetch(`/session/${encodeURIComponent(sessionId)}/command`, { directory, method: 'POST', body });
423
460
  return;
424
461
  }
462
+ let text = item.text;
463
+ const commandParts = [];
464
+ if (command?.isSkill) {
465
+ commandParts.push({
466
+ type: 'text',
467
+ text: `The user explicitly invoked the ${command.name} skill. Use the corresponding skill tool to handle this request.`,
468
+ synthetic: true,
469
+ });
470
+ } else if (command?.template) {
471
+ text = expandCommandTemplate(command.template, command.arguments);
472
+ }
425
473
 
426
474
  // Standing project context rides the prompt exactly as a UI send would
427
475
  // attach it; a failed lookup sends without it rather than not at all.
@@ -432,9 +480,10 @@ export function createMessageQueueRuntime({
432
480
  // Same order as a UI send: the user's text and files, the context queued
433
481
  // with them, then the standing context, then the mentioned agent.
434
482
  const parts = [];
435
- if (item.text.trim()) parts.push({ type: 'text', text: item.text });
483
+ if (text.trim()) parts.push({ type: 'text', text });
436
484
  parts.push(...fileParts);
437
485
  parts.push(...contextParts);
486
+ parts.push(...commandParts);
438
487
  if (knowledge.text) parts.push({ type: 'text', text: knowledge.text, synthetic: true });
439
488
  if (item.agentMention) parts.push({ type: 'agent', name: item.agentMention });
440
489
  const body = { model: { providerID, modelID } };
@@ -564,6 +613,7 @@ export function createMessageQueueRuntime({
564
613
  const existing = queues.get(sessionId);
565
614
  const items = [...(existing?.items ?? []), item].slice(-MAX_ITEMS_PER_SESSION);
566
615
  queues.set(sessionId, { directory, items });
616
+ directories.set(sessionId, directory);
567
617
  if (queues.size > MAX_SESSIONS) {
568
618
  const oldest = Array.from(queues.entries())
569
619
  .filter(([id]) => id !== sessionId && !sending.has(id))
@@ -573,6 +623,7 @@ export function createMessageQueueRuntime({
573
623
  queues.delete(staleId);
574
624
  clearTimer(staleId);
575
625
  broadcast(staleId);
626
+ directories.delete(staleId);
576
627
  }
577
628
  }
578
629
  const result = commit(sessionId);
@@ -675,6 +726,7 @@ export function createMessageQueueRuntime({
675
726
  clearTimer(deletedSessionId);
676
727
  failures.delete(deletedSessionId);
677
728
  commit(deletedSessionId);
729
+ directories.delete(deletedSessionId);
678
730
  return;
679
731
  }
680
732
 
@@ -315,6 +315,21 @@ describe('message queue runtime', () => {
315
315
  expect(runtime.snapshot().sessions).toEqual([]);
316
316
  });
317
317
 
318
+ it('names the directory in the broadcast that empties a queue', async () => {
319
+ // The UI keys its projection by directory; without it the client cannot
320
+ // tell which queue just delivered its last message and keeps showing it.
321
+ const { runtime, emit, broadcasts, openCode } = createRuntime();
322
+ runtime.start();
323
+ await runtime.enqueue(SESSION, DIRECTORY, item());
324
+ openCode.state.statuses = {};
325
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
326
+ await settle();
327
+
328
+ expect(openCode.state.sent).toHaveLength(1);
329
+ expect(runtime.snapshot().sessions).toEqual([]);
330
+ expect(broadcasts.at(-1).properties.session).toEqual({ sessionId: SESSION, directory: DIRECTORY, items: [], sendingId: null });
331
+ });
332
+
318
333
  it('reorders only with a complete permutation', async () => {
319
334
  const { runtime } = createRuntime();
320
335
  runtime.start();
@@ -377,19 +392,60 @@ describe('message queue runtime', () => {
377
392
  ]);
378
393
  });
379
394
 
380
- it('sends captured context with a slash command too', async () => {
395
+ it('keeps files on the command route, which is all that route accepts', async () => {
381
396
  const { runtime, openCode, emit } = createRuntime();
382
397
  runtime.start();
383
398
  openCode.state.commands = [{ name: 'review' }];
384
399
  await runtime.enqueue(SESSION, DIRECTORY, item({
385
400
  content: '/review',
386
401
  text: '/review',
387
- context: [{ kind: 'synthetic', text: 'focus on tests' }],
402
+ attachments: [{ id: 'a', filename: 'f.txt', mimeType: 'text/plain', size: 1, source: 'local', dataUrl: 'data:text/plain,hi' }],
388
403
  }));
389
404
  emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
390
405
  await settle();
391
406
  expect(openCode.state.sent[0].path).toBe(`/session/${SESSION}/command`);
392
- expect(openCode.state.sent[0].body.parts).toEqual([{ type: 'text', text: 'focus on tests', synthetic: true }]);
407
+ expect(openCode.state.sent[0].body.parts).toEqual([{ type: 'file', mime: 'text/plain', filename: 'f.txt', url: 'data:text/plain,hi' }]);
408
+ });
409
+
410
+ it('sends a command queued with context as its expanded prompt, context included', async () => {
411
+ // The command route rejects text parts, so a command with captured
412
+ // context takes the prompt route with the template expanded, exactly as
413
+ // the composer does.
414
+ const { runtime, openCode, emit } = createRuntime();
415
+ runtime.start();
416
+ openCode.state.commands = [{ name: 'review', source: 'command', template: 'Review $1 with focus on $2' }];
417
+ const metadata = { openchamberContext: { kind: 'chat-quote', quote: 'q', text: 'why?' } };
418
+ await runtime.enqueue(SESSION, DIRECTORY, item({
419
+ content: '/review src "error handling"',
420
+ text: '/review src "error handling"',
421
+ context: [{ kind: 'context', text: 'quoted', metadata }],
422
+ }));
423
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
424
+ await settle();
425
+ expect(openCode.state.sent[0].path).toBe(`/session/${SESSION}/prompt_async`);
426
+ expect(openCode.state.sent[0].body.parts).toEqual([
427
+ { type: 'text', text: 'Review src with focus on error handling' },
428
+ { type: 'text', text: 'quoted', synthetic: true, metadata },
429
+ ]);
430
+ });
431
+
432
+ it('sends a skill queued with context as an explicit invocation, context included', async () => {
433
+ const { runtime, openCode, emit } = createRuntime();
434
+ runtime.start();
435
+ openCode.state.commands = [{ name: 'grill', source: 'skill', template: 'skill body' }];
436
+ await runtime.enqueue(SESSION, DIRECTORY, item({
437
+ content: '/grill auth',
438
+ text: '/grill auth',
439
+ context: [{ kind: 'synthetic', text: 'focus on tests' }],
440
+ }));
441
+ emit({ type: 'session.status', properties: { sessionID: SESSION, status: { type: 'idle' } } });
442
+ await settle();
443
+ expect(openCode.state.sent[0].path).toBe(`/session/${SESSION}/prompt_async`);
444
+ expect(openCode.state.sent[0].body.parts).toEqual([
445
+ { type: 'text', text: '/grill auth' },
446
+ { type: 'text', text: 'focus on tests', synthetic: true },
447
+ { type: 'text', text: 'The user explicitly invoked the grill skill. Use the corresponding skill tool to handle this request.', synthetic: true },
448
+ ]);
393
449
  });
394
450
 
395
451
  it('keeps captured context out of snapshots and broadcasts, and hands it back on take', async () => {
@@ -63,12 +63,12 @@ This module provides OpenCode server integration utilities for the web server ru
63
63
 
64
64
  ## Public exports (providers.js)
65
65
  - `getProviderSources(providerId, workingDirectory)`: Resolves which OpenCode config layers define a provider.
66
- - `upsertProviderConfig(providerId, config, workingDirectory, scope?, options?)`: Validates and writes a custom OpenAI-compatible provider block (`npm`, `name`, `options.baseURL`, `models`, optional `env`/`headers`) into the user/project/custom config layer. Does not store API keys. Requires `config.env` or `options.hasStoredAuth` (auth already written via OpenCode `auth.set`). Edit flows must pass the provider's effective existing layer (`custom` > `project` > `user`) so updates do not create a global user override.
67
- - `validateCustomProviderConfig(providerId, config, options?)`: Structural validation for custom provider payloads (id format, http(s) base URL, models, credentials via `env` or `hasStoredAuth`).
66
+ - `upsertProviderConfig(providerId, config, workingDirectory, scope?, options?)`: Validates and writes a custom provider block (`npm`, `name`, `options.baseURL`, `models`, optional `env`/`headers`) into the user/project/custom config layer. The adapter may be OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages. Existing provider, option, and retained-model fields not managed by the form are preserved; omitted models, headers, and env credentials remain explicit removals. Updating a legacy `providers` entry migrates it to the canonical `provider` key. Does not store API keys. Requires `config.env` or `options.hasStoredAuth` (auth already written via OpenCode `auth.set`). Edit flows must pass the provider's effective existing layer (`custom` > `project` > `user`) so updates do not create a global user override.
67
+ - `validateCustomProviderConfig(providerId, config, options?)`: Structural validation for custom provider payloads (id format, adapter allowlist `@ai-sdk/openai-compatible`/`@ai-sdk/openai`/`@ai-sdk/anthropic`, http(s) base URL, models, credentials via `env` or `hasStoredAuth`).
68
68
  - `removeProviderConfig(providerId, workingDirectory, scope?)`: Removes a provider block from the selected config layer.
69
69
 
70
70
  ## Public exports (shared.js)
71
- - `OPENCODE_CONFIG_DIR`, `AGENT_DIR`, `COMMAND_DIR`, `SKILL_DIR`, `CONFIG_FILE`: Path constants. `OPENCODE_CONFIG` is resolved at call time for the custom config layer path.
71
+ - `OPENCODE_CONFIG_DIR`, `AGENT_DIR`, `COMMAND_DIR`, `SKILL_DIR`, `CONFIG_FILE`: Path constants rooted at `$XDG_CONFIG_HOME/opencode` when `XDG_CONFIG_HOME` is non-empty, otherwise `~/.config/opencode`. These constants are evaluated when the module loads; no files are migrated. `OPENCODE_CONFIG` remains a separate explicit config-file path and is resolved at call time for the custom config layer; it does not replace the global config directory.
72
72
  - `AGENT_SCOPE`, `COMMAND_SCOPE`, `SKILL_SCOPE`: Scope constants with USER and PROJECT values.
73
73
  - `ensureDirs()`: Creates required OpenCode directories.
74
74
  - `parseMdFile(filePath)`, `writeMdFile(filePath, frontmatter, body)`: Markdown file operations with YAML frontmatter.
@@ -421,7 +421,7 @@ an authoritative loopback callback URL even when OpenChamber binds port `0`.
421
421
 
422
422
  ## Storage and configuration
423
423
  - Provider auth: `~/.local/share/opencode/auth.json`.
424
- - User config: `~/.config/opencode/opencode.json`.
424
+ - User config: `$XDG_CONFIG_HOME/opencode/opencode.json`, falling back to `~/.config/opencode/opencode.json` when unset or blank.
425
425
  - Project config: `<workingDirectory>/.opencode/opencode.json` or `opencode.json`.
426
426
  - Custom config: `OPENCODE_CONFIG` env var path.
427
427
  - Rate limit config: `OPENCHAMBER_RATE_LIMIT_MAX_ATTEMPTS`, `OPENCHAMBER_RATE_LIMIT_NO_IP_MAX_ATTEMPTS` env vars.
@@ -433,3 +433,7 @@ an authoritative loopback callback URL even when OpenChamber binds port `0`.
433
433
  - Config merging follows priority: custom > project > user.
434
434
  - UI auth uses scrypt for password hashing with constant-time comparison.
435
435
  - Tunnel auth treats `host.docker.internal` as local-only when the socket remote IP is private/loopback.
436
+
437
+ The behavior `GET /api/behavior/agents-md` response includes `path`, the effective
438
+ server-side filename, whether or not the file exists. Settings displays this
439
+ path without deriving a directory from the browser environment.
@@ -0,0 +1,116 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ const originalXdgConfigHome = process.env.XDG_CONFIG_HOME;
7
+ const originalOpenCodeConfig = process.env.OPENCODE_CONFIG;
8
+
9
+ afterEach(() => {
10
+ if (originalXdgConfigHome === undefined) delete process.env.XDG_CONFIG_HOME;
11
+ else process.env.XDG_CONFIG_HOME = originalXdgConfigHome;
12
+ if (originalOpenCodeConfig === undefined) delete process.env.OPENCODE_CONFIG;
13
+ else process.env.OPENCODE_CONFIG = originalOpenCodeConfig;
14
+ vi.resetModules();
15
+ });
16
+
17
+ async function loadOpenCodeModules() {
18
+ vi.resetModules();
19
+ return Promise.all([
20
+ import('./shared.js'),
21
+ import('./agents.js'),
22
+ import('./commands.js'),
23
+ import('./skills.js'),
24
+ import('./snippets.js'),
25
+ import('./plugins.js'),
26
+ import('./routes.js'),
27
+ ]);
28
+ }
29
+
30
+ describe('OpenCode global config paths', () => {
31
+ it('derives all shared constants from a non-empty XDG_CONFIG_HOME', async () => {
32
+ const xdgConfigHome = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-xdg-'));
33
+ process.env.XDG_CONFIG_HOME = xdgConfigHome;
34
+
35
+ const [{ OPENCODE_CONFIG_DIR, AGENT_DIR, COMMAND_DIR, SKILL_DIR, CONFIG_FILE }] = await loadOpenCodeModules();
36
+ const configDir = path.join(xdgConfigHome, 'opencode');
37
+ expect(OPENCODE_CONFIG_DIR).toBe(configDir);
38
+ expect(AGENT_DIR).toBe(path.join(configDir, 'agents'));
39
+ expect(COMMAND_DIR).toBe(path.join(configDir, 'commands'));
40
+ expect(SKILL_DIR).toBe(path.join(configDir, 'skills'));
41
+ expect(CONFIG_FILE).toBe(path.join(configDir, 'config.json'));
42
+
43
+ fs.rmSync(xdgConfigHome, { recursive: true, force: true });
44
+ });
45
+
46
+ it.each([undefined, ' '])('falls back to ~/.config/opencode when XDG_CONFIG_HOME is %s', async (xdgConfigHome) => {
47
+ if (xdgConfigHome === undefined) delete process.env.XDG_CONFIG_HOME;
48
+ else process.env.XDG_CONFIG_HOME = xdgConfigHome;
49
+
50
+ const [{ OPENCODE_CONFIG_DIR }] = await loadOpenCodeModules();
51
+ expect(OPENCODE_CONFIG_DIR).toBe(path.join(os.homedir(), '.config', 'opencode'));
52
+ });
53
+
54
+ it('keeps global CRUD below XDG_CONFIG_HOME while project files stay in the project', async () => {
55
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-config-paths-'));
56
+ const xdgConfigHome = path.join(root, 'xdg');
57
+ const projectDir = path.join(root, 'project');
58
+ process.env.XDG_CONFIG_HOME = xdgConfigHome;
59
+ delete process.env.OPENCODE_CONFIG;
60
+
61
+ const [, agents, commands, skills, snippets, plugins] = await loadOpenCodeModules();
62
+ agents.createAgent('global-agent', { description: 'Global', prompt: 'Global prompt' }, projectDir, 'user');
63
+ commands.createCommand('global-command', { description: 'Global', template: 'Global template' }, projectDir, 'user');
64
+ skills.createSkill('global-skill', { description: 'Global', instructions: 'Global instructions' }, projectDir, 'user');
65
+ snippets.createSnippet('global-snippet', { content: 'Global snippet' }, projectDir, 'global');
66
+ plugins.createPluginEntry({ spec: 'global-plugin', scope: 'user' }, projectDir);
67
+
68
+ const configDir = path.join(xdgConfigHome, 'opencode');
69
+ expect(fs.existsSync(path.join(configDir, 'agents', 'global-agent.md'))).toBe(true);
70
+ expect(fs.existsSync(path.join(configDir, 'commands', 'global-command.md'))).toBe(true);
71
+ expect(fs.existsSync(path.join(configDir, 'skills', 'global-skill', 'SKILL.md'))).toBe(true);
72
+ expect(fs.existsSync(path.join(configDir, 'snippet', 'global-snippet.md'))).toBe(true);
73
+ expect(JSON.parse(fs.readFileSync(path.join(configDir, 'config.json'), 'utf8')).plugin).toEqual(['global-plugin']);
74
+
75
+ agents.createAgent('project-agent', { description: 'Project', prompt: 'Project prompt' }, projectDir, 'project');
76
+ commands.createCommand('project-command', { description: 'Project', template: 'Project template' }, projectDir, 'project');
77
+ skills.createSkill('project-skill', { description: 'Project', instructions: 'Project instructions' }, projectDir, 'project');
78
+
79
+ expect(fs.existsSync(path.join(projectDir, '.opencode', 'agents', 'project-agent.md'))).toBe(true);
80
+ expect(fs.existsSync(path.join(projectDir, '.opencode', 'commands', 'project-command.md'))).toBe(true);
81
+ expect(fs.existsSync(path.join(projectDir, '.opencode', 'skills', 'project-skill', 'SKILL.md'))).toBe(true);
82
+
83
+ fs.rmSync(root, { recursive: true, force: true });
84
+ });
85
+
86
+ it('writes global AGENTS.md below XDG_CONFIG_HOME', async () => {
87
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-agents-md-'));
88
+ process.env.XDG_CONFIG_HOME = path.join(root, 'xdg');
89
+ delete process.env.OPENCODE_CONFIG;
90
+
91
+ const [, , , , , , routes] = await loadOpenCodeModules();
92
+ const handlers = new Map();
93
+ const app = {
94
+ get(route, ...callbacks) { handlers.set(`GET ${route}`, callbacks.at(-1)); },
95
+ put(route, ...callbacks) { handlers.set(`PUT ${route}`, callbacks.at(-1)); },
96
+ post() {},
97
+ delete() {},
98
+ };
99
+ routes.registerOpenCodeRoutes(app, {});
100
+
101
+ const response = { json: vi.fn(), status: vi.fn(() => response) };
102
+ await handlers.get('GET /api/behavior/agents-md')({}, response);
103
+ expect(response.json).toHaveBeenLastCalledWith({
104
+ content: '', exists: false, path: path.join(process.env.XDG_CONFIG_HOME, 'opencode', 'AGENTS.md'),
105
+ });
106
+
107
+ await handlers.get('PUT /api/behavior/agents-md')({ body: { content: 'Global behavior' } }, response);
108
+
109
+ expect(fs.readFileSync(path.join(process.env.XDG_CONFIG_HOME, 'opencode', 'AGENTS.md'), 'utf8')).toBe('Global behavior');
110
+ await handlers.get('GET /api/behavior/agents-md')({}, response);
111
+ expect(response.json).toHaveBeenLastCalledWith({
112
+ content: 'Global behavior', exists: true, path: path.join(process.env.XDG_CONFIG_HOME, 'opencode', 'AGENTS.md'),
113
+ });
114
+ fs.rmSync(root, { recursive: true, force: true });
115
+ });
116
+ });
@@ -98,6 +98,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
98
98
  createFsSearchRuntime,
99
99
  openchamberDataDir,
100
100
  openchamberUserConfigRoot,
101
+ managedChatsRoot,
101
102
  normalizeDirectoryPath,
102
103
  resolveProjectDirectory,
103
104
  resolveOptionalProjectDirectory,
@@ -332,6 +333,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
332
333
  buildAugmentedPath,
333
334
  resolveGitBinaryForSpawn,
334
335
  openchamberUserConfigRoot,
336
+ managedChatsRoot,
335
337
  });
336
338
  };
337
339
 
@@ -0,0 +1,14 @@
1
+ export const DEFAULT_INPUT_HISTORY_SCOPE = 'session';
2
+ export const DEFAULT_INPUT_HISTORY_LIMIT = 40;
3
+ const MIN_INPUT_HISTORY_LIMIT = 1;
4
+ const MAX_INPUT_HISTORY_LIMIT = 100;
5
+
6
+ export const isInputHistoryScope = (value) => (
7
+ value === 'global' || value === 'session'
8
+ );
9
+
10
+ export const isInputHistoryLimit = (value) => (
11
+ Number.isInteger(value)
12
+ && value >= MIN_INPUT_HISTORY_LIMIT
13
+ && value <= MAX_INPUT_HISTORY_LIMIT
14
+ );
@@ -1,8 +1,8 @@
1
1
  import fs from 'fs';
2
- import os from 'os';
3
2
  import path from 'path';
4
3
  import {
5
4
  AGENT_SCOPE,
5
+ OPENCODE_CONFIG_DIR,
6
6
  readConfigFile,
7
7
  readConfigLayer,
8
8
  writeConfig,
@@ -71,7 +71,7 @@ function getActiveOpencodeConfigDir() {
71
71
  if (customConfigPath) {
72
72
  return path.dirname(path.resolve(customConfigPath));
73
73
  }
74
- return path.join(os.homedir(), '.config', 'opencode');
74
+ return OPENCODE_CONFIG_DIR;
75
75
  }
76
76
 
77
77
  function getActiveUserConfigPaths() {
@@ -152,6 +152,37 @@ function validateCustomProviderConfig(providerId, config, options = {}) {
152
152
  return { ok: true, value: { providerId, config: normalized } };
153
153
  }
154
154
 
155
+ function mergeCustomProviderConfig(existingValue, normalizedConfig) {
156
+ const existing = isPlainObject(existingValue) ? existingValue : {};
157
+ const existingOptions = isPlainObject(existing.options) ? existing.options : {};
158
+ const normalizedOptions = isPlainObject(normalizedConfig.options) ? normalizedConfig.options : {};
159
+ const mergedOptions = { ...existingOptions, ...normalizedOptions };
160
+ if (!Object.prototype.hasOwnProperty.call(normalizedOptions, 'headers')) {
161
+ delete mergedOptions.headers;
162
+ }
163
+
164
+ const existingModels = isPlainObject(existing.models) ? existing.models : {};
165
+ const normalizedModels = isPlainObject(normalizedConfig.models) ? normalizedConfig.models : {};
166
+ const mergedModels = Object.fromEntries(
167
+ Object.entries(normalizedModels).map(([modelId, normalizedModel]) => {
168
+ const existingModel = isPlainObject(existingModels[modelId]) ? existingModels[modelId] : {};
169
+ const nextModel = isPlainObject(normalizedModel) ? normalizedModel : {};
170
+ return [modelId, { ...existingModel, ...nextModel }];
171
+ }),
172
+ );
173
+
174
+ const merged = {
175
+ ...existing,
176
+ ...normalizedConfig,
177
+ options: mergedOptions,
178
+ models: mergedModels,
179
+ };
180
+ if (!Object.prototype.hasOwnProperty.call(normalizedConfig, 'env')) {
181
+ delete merged.env;
182
+ }
183
+ return merged;
184
+ }
185
+
155
186
  /**
156
187
  * Persist (create or update) a custom provider block in OpenCode user/project/custom config.
157
188
  * Does not write secrets — API keys remain in auth.json via the OpenCode auth API.
@@ -183,8 +214,19 @@ function upsertProviderConfig(providerId, config, workingDirectory, scope = 'use
183
214
 
184
215
  const targetConfig = getConfigForPath(layers, targetPath);
185
216
  const providerConfig = isPlainObject(targetConfig.provider) ? { ...targetConfig.provider } : {};
186
- providerConfig[validated.value.providerId] = validated.value.config;
217
+ const providersAlias = isPlainObject(targetConfig.providers) ? { ...targetConfig.providers } : {};
218
+ const existingProvider = providerConfig[validated.value.providerId] ?? providersAlias[validated.value.providerId];
219
+ const mergedConfig = mergeCustomProviderConfig(existingProvider, validated.value.config);
220
+ providerConfig[validated.value.providerId] = mergedConfig;
187
221
  targetConfig.provider = providerConfig;
222
+ if (Object.prototype.hasOwnProperty.call(providersAlias, validated.value.providerId)) {
223
+ delete providersAlias[validated.value.providerId];
224
+ if (Object.keys(providersAlias).length === 0) {
225
+ delete targetConfig.providers;
226
+ } else {
227
+ targetConfig.providers = providersAlias;
228
+ }
229
+ }
188
230
 
189
231
  if (Array.isArray(targetConfig.disabled_providers)) {
190
232
  targetConfig.disabled_providers = targetConfig.disabled_providers.filter(
@@ -198,7 +240,7 @@ function upsertProviderConfig(providerId, config, workingDirectory, scope = 'use
198
240
  return {
199
241
  providerId: validated.value.providerId,
200
242
  path: writePath,
201
- config: validated.value.config,
243
+ config: mergedConfig,
202
244
  };
203
245
  }
204
246
 
@@ -9,6 +9,7 @@ import {
9
9
  getProviderSources,
10
10
  removeProviderConfig,
11
11
  } from './providers.js';
12
+ import { OPENCODE_CONFIG_DIR } from './shared.js';
12
13
 
13
14
  let projectDir;
14
15
 
@@ -162,6 +163,132 @@ describe('custom provider config persistence', () => {
162
163
  expect(written.disabled_providers).toEqual(['other']);
163
164
  });
164
165
 
166
+ test('upsertProviderConfig preserves unmanaged provider and model metadata', () => {
167
+ const configPath = path.join(projectDir, 'opencode.json');
168
+ writeJson(configPath, {
169
+ provider: {
170
+ 'campus-llm': {
171
+ npm: '@ai-sdk/openai-compatible',
172
+ name: 'Old',
173
+ customProviderField: { owner: 'user' },
174
+ env: ['OLD_KEY'],
175
+ options: {
176
+ baseURL: 'https://old.example.edu/v1',
177
+ headers: { 'X-Old': '1' },
178
+ timeout: 45_000,
179
+ },
180
+ models: {
181
+ retained: {
182
+ name: 'Old retained name',
183
+ reasoning: true,
184
+ attachment: true,
185
+ tool_call: true,
186
+ modalities: { input: ['text', 'image', 'pdf'], output: ['text'] },
187
+ limit: { context: 1_050_000, input: 922_000, output: 128_000 },
188
+ options: { instructions: 'Keep this instruction' },
189
+ variants: {
190
+ low: { reasoningEffort: 'low' },
191
+ high: { reasoningEffort: 'high' },
192
+ },
193
+ customModelField: { source: 'manual' },
194
+ },
195
+ removed: {
196
+ name: 'Remove me',
197
+ reasoning: true,
198
+ },
199
+ },
200
+ },
201
+ },
202
+ });
203
+
204
+ upsertProviderConfig('campus-llm', {
205
+ name: 'Campus LLM',
206
+ options: { baseURL: 'https://new.example.edu/v1' },
207
+ models: {
208
+ retained: { name: 'Retained model' },
209
+ added: { name: 'Added model' },
210
+ },
211
+ }, projectDir, 'project', { hasStoredAuth: true });
212
+
213
+ const written = readJson(configPath).provider['campus-llm'];
214
+ expect(written).toEqual({
215
+ npm: '@ai-sdk/openai-compatible',
216
+ name: 'Campus LLM',
217
+ customProviderField: { owner: 'user' },
218
+ options: {
219
+ baseURL: 'https://new.example.edu/v1',
220
+ timeout: 45_000,
221
+ },
222
+ models: {
223
+ retained: {
224
+ name: 'Retained model',
225
+ reasoning: true,
226
+ attachment: true,
227
+ tool_call: true,
228
+ modalities: { input: ['text', 'image', 'pdf'], output: ['text'] },
229
+ limit: { context: 1_050_000, input: 922_000, output: 128_000 },
230
+ options: { instructions: 'Keep this instruction' },
231
+ variants: {
232
+ low: { reasoningEffort: 'low' },
233
+ high: { reasoningEffort: 'high' },
234
+ },
235
+ customModelField: { source: 'manual' },
236
+ },
237
+ added: { name: 'Added model' },
238
+ },
239
+ });
240
+ });
241
+
242
+ test('upsertProviderConfig preserves metadata while migrating the legacy providers alias', () => {
243
+ const configPath = path.join(projectDir, 'opencode.json');
244
+ writeJson(configPath, {
245
+ providers: {
246
+ legacy: {
247
+ name: 'Legacy provider',
248
+ options: { baseURL: 'https://old.example.com/v1', timeout: 30_000 },
249
+ models: { model: { name: 'Old model', reasoning: true } },
250
+ },
251
+ },
252
+ });
253
+
254
+ upsertProviderConfig('legacy', {
255
+ name: 'Updated provider',
256
+ options: { baseURL: 'https://new.example.com/v1' },
257
+ models: { model: { name: 'Updated model' } },
258
+ }, projectDir, 'project', { hasStoredAuth: true });
259
+
260
+ const written = readJson(configPath);
261
+ expect(written.providers).toBeUndefined();
262
+ expect(written.provider.legacy).toEqual({
263
+ npm: '@ai-sdk/openai-compatible',
264
+ name: 'Updated provider',
265
+ options: { baseURL: 'https://new.example.com/v1', timeout: 30_000 },
266
+ models: { model: { name: 'Updated model', reasoning: true } },
267
+ });
268
+ });
269
+
270
+ test('migrating one legacy providers entry keeps the other legacy entries', () => {
271
+ const configPath = path.join(projectDir, 'opencode.json');
272
+ writeJson(configPath, {
273
+ providers: {
274
+ legacy: { name: 'Legacy provider', options: { baseURL: 'https://old.example.com/v1' }, models: { model: { name: 'Old model' } } },
275
+ untouched: { name: 'Untouched', options: { baseURL: 'https://other.example.com/v1' }, models: { model: { name: 'Other model' } } },
276
+ },
277
+ });
278
+
279
+ upsertProviderConfig('legacy', {
280
+ name: 'Updated provider',
281
+ options: { baseURL: 'https://new.example.com/v1' },
282
+ models: { model: { name: 'Updated model' } },
283
+ }, projectDir, 'project', { hasStoredAuth: true });
284
+
285
+ const written = readJson(configPath);
286
+ expect(written.providers).toEqual({
287
+ untouched: { name: 'Untouched', options: { baseURL: 'https://other.example.com/v1' }, models: { model: { name: 'Other model' } } },
288
+ });
289
+ expect(written.provider.legacy.name).toBe('Updated provider');
290
+ });
291
+
165
292
  test('upsert then remove restores absence', () => {
166
293
  upsertProviderConfig('temp-provider', {
167
294
  name: 'Temp',
@@ -230,8 +357,8 @@ describe('custom provider config persistence', () => {
230
357
  expect(sources.sources.custom.exists).toBe(false);
231
358
 
232
359
  for (const userPath of [
233
- path.join(os.homedir(), '.config', 'opencode', 'opencode.json'),
234
- path.join(os.homedir(), '.config', 'opencode', 'config.json'),
360
+ path.join(OPENCODE_CONFIG_DIR, 'opencode.json'),
361
+ path.join(OPENCODE_CONFIG_DIR, 'config.json'),
235
362
  ]) {
236
363
  if (!fs.existsSync(userPath)) continue;
237
364
  const userConfig = readJson(userPath);
@@ -269,8 +396,8 @@ describe('custom provider config persistence', () => {
269
396
  expect(sources.sources.project.exists).toBe(false);
270
397
 
271
398
  for (const userPath of [
272
- path.join(os.homedir(), '.config', 'opencode', 'opencode.json'),
273
- path.join(os.homedir(), '.config', 'opencode', 'config.json'),
399
+ path.join(OPENCODE_CONFIG_DIR, 'opencode.json'),
400
+ path.join(OPENCODE_CONFIG_DIR, 'config.json'),
274
401
  ]) {
275
402
  if (!fs.existsSync(userPath)) continue;
276
403
  const userConfig = readJson(userPath);