@openchamber/web 1.18.4 → 1.20.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 (251) hide show
  1. package/README.md +1 -0
  2. package/dist/assets/{CodeMirrorCommentWidgets-4qZbrEXU.js → CodeMirrorCommentWidgets-C36E738Y.js} +1 -1
  3. package/dist/assets/{CommitSection-MJmntVPJ.js → CommitSection-C-F3AX6D.js} +1 -1
  4. package/dist/assets/{DiagramEditor-jnG3Hbxg.js → DiagramEditor-BPECg1jS.js} +1 -1
  5. package/dist/assets/DiagramView-D0YNMix8.js +1 -0
  6. package/dist/assets/DiffView-BHWaMYCC.js +4 -0
  7. package/dist/assets/FilesView-NMBCW2Tm.js +14 -0
  8. package/dist/assets/{GitView-DBFrDDBv.js → GitView-Rp8P1KEI.js} +4 -4
  9. package/dist/assets/{JsonTreeView-DLW2Wy1g.js → JsonTreeView-KnXFN2A-.js} +1 -1
  10. package/dist/assets/MarkdownImageGallery-BMn3mtor.js +1 -0
  11. package/dist/assets/MarkdownRendererImpl-kD6N03pH.js +12 -0
  12. package/dist/assets/OnboardingScreen-CenIeD4v.js +1 -0
  13. package/dist/assets/{PatchDiff-BuLPx7AN.js → PatchDiff-BzVOVog8.js} +1 -1
  14. package/dist/assets/{PierreDiffViewer-BHm4Yr0X.js → PierreDiffViewer-Dlby4XqT.js} +2 -2
  15. package/dist/assets/PlanView-Czu1KMJa.js +4 -0
  16. package/dist/assets/SessionSwitcherDropdown-IETz58DB.js +1 -0
  17. package/dist/assets/SettingsView-B6vmuf-c.js +28 -0
  18. package/dist/assets/SettingsWindow-CauZpdD3.js +1 -0
  19. package/dist/assets/ToolOutputDialog-BB1c--Zr.js +15 -0
  20. package/dist/assets/ToolPartDiffPreview-DaOIDISD.js +8 -0
  21. package/dist/assets/{VirtualizedFileDiff-CwGocYQd.js → VirtualizedFileDiff-lESMT-2b.js} +4 -4
  22. package/dist/assets/{WalkthroughView-5DyvN03T.js → WalkthroughView-CaSYE0lw.js} +2 -2
  23. package/dist/assets/{computeVirtualFileMetrics-Da00Jg7M.js → computeVirtualFileMetrics-DkRR5b75.js} +2 -2
  24. package/dist/assets/contextPanelEmbeddedChat-BEARQjgn.js +1 -0
  25. package/dist/assets/de-DFdX3ABv.js +9 -0
  26. package/dist/assets/document-attachments-DFAWlG3U.js +31 -0
  27. package/dist/assets/es-iC-FKvV9.js +15 -0
  28. package/dist/assets/fr-BBbi_1AL.js +13 -0
  29. package/dist/assets/index-BiEgzzkg.js +1 -0
  30. package/dist/assets/index-Cwmuwk3V.js +7 -0
  31. package/dist/assets/index-GNm1wgUH.css +1 -0
  32. package/dist/assets/{isDiffPlainText-D9YpoLrV.js → isDiffPlainText-BG53Ixxy.js} +1 -1
  33. package/dist/assets/{isFilePlainText-gTibdNIe.js → isFilePlainText-BbV-39jl.js} +1 -1
  34. package/dist/assets/ja-DQLQJL2J.js +15 -0
  35. package/dist/assets/ko-BeElEB4Y.js +15 -0
  36. package/dist/assets/{lua-BgMRiT3U.js → lua-VAEuO923.js} +1 -1
  37. package/dist/assets/main-Dpzo18z7.js +2 -0
  38. package/dist/assets/main-WMjtYzJs.js +921 -0
  39. package/dist/assets/markdownCore--tDmyI_v.js +2 -0
  40. package/dist/assets/miniChat-ldEghBLB.js +2 -0
  41. package/dist/assets/mobile-Dk-VGreF.js +2 -0
  42. package/dist/assets/{patchFileDiff-KNkxM1C1.js → patchFileDiff-BcFaMtMu.js} +1 -1
  43. package/dist/assets/pl-CLHt2_vV.js +15 -0
  44. package/dist/assets/pt-BR-C_MPUq7e.js +15 -0
  45. package/dist/assets/renderElectronMiniChatApp-DIgCOmXY.js +2 -0
  46. package/dist/assets/renderMobileApp-CDfHS5rr.js +25 -0
  47. package/dist/assets/runtimeEndpointReset-ovNbaZ-x.js +15 -0
  48. package/dist/assets/scheduledTasksApi-BFSlqgnG.js +1 -0
  49. package/dist/assets/{shikiHighlight-C7LTbwFx.js → shikiHighlight-DCT2Sq_z.js} +1 -1
  50. package/dist/assets/uk-PhsC-c4-.js +15 -0
  51. package/dist/assets/{useAppFontEffects-BikB6enL.js → useAppFontEffects-B53Rb6m7.js} +168 -164
  52. package/dist/assets/useInlineCommentController-DSfrIBKT.js +2 -0
  53. package/dist/assets/{vendor-base-ui-D_V6hAcE.js → vendor-base-ui-DsHmyMwp.js} +1 -1
  54. package/dist/assets/vendor-codemirror-autocomplete-DzPz9Wgq.js +1 -0
  55. package/dist/assets/vendor-codemirror-commands-B7H_j0iU.js +1 -0
  56. package/dist/assets/{vendor-codemirror-lang-angular-CgY7_gQ1.js → vendor-codemirror-lang-angular-DEPs2M5t.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-cpp-B5Ta4enQ.js → vendor-codemirror-lang-cpp-DhkseaMo.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-css-VgNqFSH-.js → vendor-codemirror-lang-css-O0cZX78y.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-go-LxLz62pp.js → vendor-codemirror-lang-go-fMdQYcON.js} +1 -1
  60. package/dist/assets/vendor-codemirror-lang-html-CfgK872x.js +1 -0
  61. package/dist/assets/{vendor-codemirror-lang-java-Bksi1PH4.js → vendor-codemirror-lang-java-CQj4S3zl.js} +1 -1
  62. package/dist/assets/vendor-codemirror-lang-javascript-Cc2ZYbgX.js +13 -0
  63. package/dist/assets/{vendor-codemirror-lang-jinja-C7npuDD7.js → vendor-codemirror-lang-jinja-BmZZv8g-.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-json-ryCw7nab.js → vendor-codemirror-lang-json-CMBS2tG9.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-less-BxsZJD6N.js → vendor-codemirror-lang-less-C6Eo8hVS.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-liquid-De6qch10.js → vendor-codemirror-lang-liquid-DSTR47-H.js} +1 -1
  67. package/dist/assets/vendor-codemirror-lang-markdown-BPGOH9ye.js +1 -0
  68. package/dist/assets/{vendor-codemirror-lang-php-Cm1es33p.js → vendor-codemirror-lang-php-DD9udfPH.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-python-N414WYK-.js → vendor-codemirror-lang-python-HahnQaAS.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-rust-C_WuUStH.js → vendor-codemirror-lang-rust-nLTovbjv.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-sass-8UHTCAOM.js → vendor-codemirror-lang-sass-pL2Yc72v.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sql-CV3sMA5D.js → vendor-codemirror-lang-sql-BVBnan19.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-vue-DzvC1Dhk.js → vendor-codemirror-lang-vue-BqGzJVm1.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-wast-jlr-LDdA.js → vendor-codemirror-lang-wast-B0_m5DqU.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-xml-CrO63OVp.js → vendor-codemirror-lang-xml-Dj3voadT.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-yaml-dxi6CISW.js → vendor-codemirror-lang-yaml-yu-9Z5u7.js} +1 -1
  77. package/dist/assets/vendor-codemirror-language-BgPj_McA.js +3 -0
  78. package/dist/assets/{vendor-codemirror-language-data-CLHw8NWn.js → vendor-codemirror-language-data-vch3tJ4c.js} +2 -2
  79. package/dist/assets/vendor-codemirror-search-BmS-GmcX.js +2 -0
  80. package/dist/assets/{vendor-codemirror-state-CNWM3Q8V.js → vendor-codemirror-state-C9awkmn-.js} +5 -5
  81. package/dist/assets/vendor-codemirror-view-CiLROUVV.js +4 -0
  82. package/dist/assets/vendor-replit-codemirror-vim-B2DJlAhT.js +6 -0
  83. package/dist/assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js +34 -0
  84. package/dist/assets/vendor-zod-C9ioTTSo.js +39 -0
  85. package/dist/assets/{web-components-GMc3oR3i.js → web-components-pcwCTWjC.js} +4 -4
  86. package/dist/assets/zh-CN-wF-NOFHM.js +15 -0
  87. package/dist/assets/zh-TW-4m4-A7rT.js +15 -0
  88. package/dist/index.html +5 -4
  89. package/dist/mini-chat.html +4 -3
  90. package/dist/mobile.html +4 -3
  91. package/package.json +3 -5
  92. package/server/index.js +152 -3
  93. package/server/lib/agent-memory/actions.js +243 -0
  94. package/server/lib/agent-memory/actions.test.js +343 -0
  95. package/server/lib/agent-memory/feature-flag.js +19 -0
  96. package/server/lib/agent-memory/feature-flag.test.js +38 -0
  97. package/server/lib/agent-memory/project-resolution.js +65 -0
  98. package/server/lib/agent-memory/project-resolution.test.js +94 -0
  99. package/server/lib/agent-memory/routes.http.test.js +270 -0
  100. package/server/lib/agent-memory/routes.js +169 -0
  101. package/server/lib/agent-memory/runtime.js +432 -0
  102. package/server/lib/agent-memory/runtime.test.js +344 -0
  103. package/server/lib/agent-memory/threat-patterns.js +61 -0
  104. package/server/lib/agent-memory/threat-patterns.test.js +61 -0
  105. package/server/lib/agent-tool/DOCUMENTATION.md +14 -0
  106. package/server/lib/agent-tool/runtime.js +63 -13
  107. package/server/lib/agent-tool/runtime.test.js +85 -2
  108. package/server/lib/context-obligatory/runtime.js +34 -3
  109. package/server/lib/context-obligatory/runtime.test.js +114 -0
  110. package/server/lib/dictation/DOCUMENTATION.md +32 -8
  111. package/server/lib/dictation/local/sherpa-recognizer.js +35 -78
  112. package/server/lib/dictation/local/worker-process.js +2 -2
  113. package/server/lib/dictation/openai-compatible-session.js +3 -2
  114. package/server/lib/dictation/stream-manager.js +77 -34
  115. package/server/lib/dictation/stream-manager.test.js +60 -2
  116. package/server/lib/fs/DOCUMENTATION.md +3 -0
  117. package/server/lib/fs/routes.js +149 -32
  118. package/server/lib/fs/routes.test.js +301 -0
  119. package/server/lib/git/DOCUMENTATION.md +8 -0
  120. package/server/lib/git/routes.js +43 -0
  121. package/server/lib/git/service.js +206 -72
  122. package/server/lib/git/service.test.js +222 -0
  123. package/server/lib/github/DOCUMENTATION.md +14 -3
  124. package/server/lib/github/pr-status.js +188 -83
  125. package/server/lib/github/pr-status.test.js +182 -0
  126. package/server/lib/github/routes.js +36 -30
  127. package/server/lib/notifications/template-runtime.js +2 -3
  128. package/server/lib/openchamber-control/action-resolution.test.js +65 -0
  129. package/server/lib/openchamber-control/actions.js +78 -0
  130. package/server/lib/openchamber-control/service.js +7 -0
  131. package/server/lib/openchamber-sessions/routes.js +14 -0
  132. package/server/lib/opencode/DOCUMENTATION.md +12 -6
  133. package/server/lib/opencode/claude-cli-auth.js +60 -0
  134. package/server/lib/opencode/claude-cli-auth.test.js +54 -0
  135. package/server/lib/opencode/feature-routes-runtime.js +16 -9
  136. package/server/lib/opencode/lifecycle.js +202 -26
  137. package/server/lib/opencode/lifecycle.test.js +179 -1
  138. package/server/lib/opencode/plugins.js +12 -3
  139. package/server/lib/opencode/plugins.test.js +18 -0
  140. package/server/lib/opencode/providers.js +9 -4
  141. package/server/lib/opencode/providers.test.js +27 -0
  142. package/server/lib/opencode/proxy-agent-wiring.test.js +152 -0
  143. package/server/lib/opencode/proxy.js +116 -6
  144. package/server/lib/opencode/proxy.test.js +158 -1
  145. package/server/lib/opencode/restart-session-recovery.test.js +59 -0
  146. package/server/lib/opencode/routes.js +4 -1
  147. package/server/lib/opencode/session-runtime.js +39 -2
  148. package/server/lib/opencode/session-runtime.test.js +74 -0
  149. package/server/lib/opencode/settings-helpers.js +26 -0
  150. package/server/lib/opencode/settings-helpers.test.js +57 -0
  151. package/server/lib/opencode/settings-normalization-runtime.js +3 -0
  152. package/server/lib/opencode/settings-normalization-runtime.test.js +16 -0
  153. package/server/lib/opencode/settings-runtime.js +83 -10
  154. package/server/lib/opencode/settings-runtime.test.js +85 -0
  155. package/server/lib/opencode/shared.js +120 -16
  156. package/server/lib/opencode/shared.test.js +185 -1
  157. package/server/lib/opencode/skill-routes.js +29 -73
  158. package/server/lib/opencode/skill-routes.test.js +2 -5
  159. package/server/lib/project-context/DOCUMENTATION.md +160 -0
  160. package/server/lib/project-context/routes.http.test.js +264 -0
  161. package/server/lib/project-context/routes.js +237 -0
  162. package/server/lib/project-context/runtime.js +672 -0
  163. package/server/lib/project-context/runtime.test.js +498 -0
  164. package/server/lib/projects/project-config.js +7 -2
  165. package/server/lib/quota/DOCUMENTATION.md +17 -2
  166. package/server/lib/quota/providers/claude/auth.js +113 -0
  167. package/server/lib/quota/providers/claude/auth.test.js +117 -0
  168. package/server/lib/quota/providers/claude/index.js +151 -0
  169. package/server/lib/quota/providers/claude/index.test.js +147 -0
  170. package/server/lib/quota/providers/claude/transforms.js +127 -0
  171. package/server/lib/quota/providers/claude/transforms.test.js +82 -0
  172. package/server/lib/quota/providers/command-code.js +90 -0
  173. package/server/lib/quota/providers/command-code.test.js +85 -0
  174. package/server/lib/quota/providers/index.js +30 -2
  175. package/server/lib/quota/providers/index.test.js +10 -1
  176. package/server/lib/quota/providers/zai.js +26 -6
  177. package/server/lib/quota/providers/zai.test.js +33 -0
  178. package/server/lib/quota/utils/formatters.js +2 -1
  179. package/server/lib/scheduled-tasks/runtime.js +21 -2
  180. package/server/lib/session-knowledge/DOCUMENTATION.md +89 -0
  181. package/server/lib/session-knowledge/routes.js +107 -0
  182. package/server/lib/session-knowledge/runtime.js +331 -0
  183. package/server/lib/session-knowledge/runtime.test.js +275 -0
  184. package/server/lib/skills-catalog/DOCUMENTATION.md +18 -45
  185. package/server/lib/skills-catalog/cache.js +120 -1
  186. package/server/lib/skills-catalog/cache.test.js +77 -0
  187. package/server/lib/skills-catalog/curated-sources.js +21 -5
  188. package/server/lib/skills-catalog/curated-sources.test.js +10 -0
  189. package/server/lib/skills-catalog/disk-cache.js +52 -0
  190. package/server/lib/skills-catalog/github-meta.js +139 -0
  191. package/server/lib/skills-catalog/github-meta.test.js +71 -0
  192. package/server/lib/skills-catalog/source.js +0 -5
  193. package/server/lib/small-model/DOCUMENTATION.md +74 -6
  194. package/server/lib/small-model/call.js +46 -12
  195. package/server/lib/small-model/call.test.js +79 -0
  196. package/server/lib/small-model/index.js +57 -6
  197. package/server/lib/small-model/index.test.js +102 -2
  198. package/server/lib/small-model/routes.js +4 -2
  199. package/server/lib/small-model/runtime-providers.js +156 -0
  200. package/server/lib/small-model/runtime-providers.test.js +112 -0
  201. package/dist/assets/DiagramView-CFXxgg_a.js +0 -1
  202. package/dist/assets/DiffView-DZIoOnV7.js +0 -4
  203. package/dist/assets/FilesView-BKL6YlKG.js +0 -14
  204. package/dist/assets/MarkdownImageGallery-DKIylIK7.js +0 -1
  205. package/dist/assets/MarkdownRendererImpl-CLv8hxvv.js +0 -12
  206. package/dist/assets/OnboardingScreen-D2Y6djMw.js +0 -1
  207. package/dist/assets/PlanView-ZYEJn8A_.js +0 -4
  208. package/dist/assets/SessionSwitcherDropdown-rro-SsaO.js +0 -1
  209. package/dist/assets/SettingsView-5RmswFZe.js +0 -28
  210. package/dist/assets/SettingsWindow-BZhAYFdS.js +0 -1
  211. package/dist/assets/ToolOutputDialog-Za6V4VMJ.js +0 -15
  212. package/dist/assets/ToolPartDiffPreview-BL-9ixyC.js +0 -8
  213. package/dist/assets/contextPanelEmbeddedChat-B-bSg3P5.js +0 -1
  214. package/dist/assets/de-u7gSnqWs.js +0 -9
  215. package/dist/assets/document-attachments-CX_YaDsu.js +0 -30
  216. package/dist/assets/es-T9O7aAOr.js +0 -15
  217. package/dist/assets/fr-Oor7ewbE.js +0 -13
  218. package/dist/assets/index-BzIpNlNE.css +0 -1
  219. package/dist/assets/index-C0yNhuZw.js +0 -1
  220. package/dist/assets/index-DRpChWux.js +0 -7
  221. package/dist/assets/ja-DHpqbVmr.js +0 -15
  222. package/dist/assets/ko-CwLkS3nx.js +0 -15
  223. package/dist/assets/main-D7UcL3VQ.js +0 -2
  224. package/dist/assets/main-DPMd2iKS.js +0 -915
  225. package/dist/assets/markdownCore-DDrHVneM.js +0 -2
  226. package/dist/assets/miniChat-O_GVoEbc.js +0 -2
  227. package/dist/assets/mobile-Br4TtAqc.js +0 -2
  228. package/dist/assets/pl-CcZILN8q.js +0 -15
  229. package/dist/assets/pt-BR-DYHhVK6o.js +0 -15
  230. package/dist/assets/renderElectronMiniChatApp-CJpdxTT1.js +0 -2
  231. package/dist/assets/renderMobileApp-toj9cXoh.js +0 -25
  232. package/dist/assets/runtimeEndpointReset-BVmispdD.js +0 -13
  233. package/dist/assets/scheduledTasksApi-ByKya3Un.js +0 -1
  234. package/dist/assets/uk-BA2kZR38.js +0 -15
  235. package/dist/assets/useInlineCommentController-CYPvYJDt.js +0 -2
  236. package/dist/assets/vendor-codemirror-autocomplete-BjbBRsUA.js +0 -1
  237. package/dist/assets/vendor-codemirror-commands-ARAOgp1x.js +0 -1
  238. package/dist/assets/vendor-codemirror-lang-html-B3Qe3OpS.js +0 -1
  239. package/dist/assets/vendor-codemirror-lang-javascript-Bbw3D7r0.js +0 -13
  240. package/dist/assets/vendor-codemirror-lang-markdown-FGQydhTc.js +0 -1
  241. package/dist/assets/vendor-codemirror-language-DUOssd4j.js +0 -3
  242. package/dist/assets/vendor-codemirror-search-8kyQdB3f.js +0 -2
  243. package/dist/assets/vendor-codemirror-view-DSzLbZiS.js +0 -4
  244. package/dist/assets/vendor-replit-codemirror-vim-B0Ecqnlh.js +0 -39
  245. package/dist/assets/zh-CN-dlOQK6v9.js +0 -15
  246. package/dist/assets/zh-TW-BnqQ-WL5.js +0 -15
  247. package/server/lib/quota/providers/claude.js +0 -107
  248. package/server/lib/skills-catalog/clawdhub/api.js +0 -126
  249. package/server/lib/skills-catalog/clawdhub/install.js +0 -238
  250. package/server/lib/skills-catalog/clawdhub/install.test.js +0 -100
  251. package/server/lib/skills-catalog/clawdhub/scan.js +0 -61
@@ -0,0 +1,90 @@
1
+ import { readAuthFile } from '../../opencode/auth.js';
2
+ import { asObject, buildResult, getAuthEntry, normalizeAuthEntry, toNumber, toUsageWindow } from '../utils/index.js';
3
+
4
+ export const providerId = 'command-code';
5
+ export const providerName = 'Command Code';
6
+ export const aliases = ['command-code', 'commandcode', 'command_code', 'command code'];
7
+
8
+ const API_BASE_URL = 'https://api.commandcode.ai';
9
+
10
+ const getApiKey = (auth = readAuthFile()) => {
11
+ const entry = normalizeAuthEntry(getAuthEntry(auth, aliases));
12
+ const stored = entry?.key ?? entry?.access ?? entry?.token;
13
+ return (typeof stored === 'string' ? stored.trim() : '') || process.env.COMMAND_CODE_API_KEY?.trim() || null;
14
+ };
15
+
16
+ const requestJson = async (path, apiKey, fetchImpl) => {
17
+ const response = await fetchImpl(`${API_BASE_URL}${path}`, {
18
+ headers: {
19
+ Accept: 'application/json',
20
+ Authorization: `Bearer ${apiKey}`,
21
+ 'User-Agent': 'OpenChamber quota provider',
22
+ },
23
+ signal: AbortSignal.timeout(15_000),
24
+ });
25
+ if (response.status === 401 || response.status === 403) throw new Error('Command Code authentication failed');
26
+ if (!response.ok) throw new Error(`Command Code usage API returned HTTP ${response.status}`);
27
+ return response.json().catch(() => null);
28
+ };
29
+
30
+ const formatCredits = (value) => String(Math.round((value + Number.EPSILON) * 100) / 100);
31
+
32
+ const toBalanceWindow = (value) => toUsageWindow({
33
+ usedPercent: null,
34
+ windowSeconds: null,
35
+ resetAt: null,
36
+ valueLabel: formatCredits(value),
37
+ });
38
+
39
+ export const parseCommandCodeCredits = (payload) => {
40
+ const root = asObject(payload);
41
+ const credits = asObject(root?.credits);
42
+ const limits = asObject(root?.windowLimits);
43
+ const windows = {};
44
+
45
+ for (const [label, field] of [['monthly_credits', 'monthlyCredits'], ['purchased_credits', 'purchasedCredits'], ['free_credits', 'freeCredits']]) {
46
+ const value = toNumber(credits?.[field]);
47
+ if (value !== null) windows[label] = toBalanceWindow(value);
48
+ }
49
+
50
+ for (const [label, field, windowSeconds] of [['5h', 'fiveHour', 5 * 60 * 60], ['weekly', 'weekly', 7 * 24 * 60 * 60]]) {
51
+ const limit = asObject(limits?.[field]);
52
+ const used = toNumber(limit?.used);
53
+ const cap = toNumber(limit?.cap);
54
+ if (used === null || cap === null || cap <= 0) continue;
55
+ const resetAt = toNumber(limit?.resetAt);
56
+ windows[label] = toUsageWindow({
57
+ usedPercent: Math.min(100, Math.max(0, used / cap * 100)),
58
+ windowSeconds,
59
+ resetAt: resetAt === null ? null : resetAt < 1_000_000_000_000 ? resetAt * 1000 : resetAt,
60
+ valueLabel: `${formatCredits(used)} / ${formatCredits(cap)}`,
61
+ });
62
+ }
63
+
64
+ return windows;
65
+ };
66
+
67
+ export const fetchCommandCodeUsage = async (apiKey, fetchImpl = fetch) => {
68
+ const identity = asObject(await requestJson('/alpha/whoami', apiKey, fetchImpl));
69
+ const org = asObject(identity?.org);
70
+ const orgId = typeof org?.id === 'string' ? org.id.trim() : '';
71
+ const creditsPath = orgId
72
+ ? `/alpha/billing/credits?orgId=${encodeURIComponent(orgId)}`
73
+ : '/alpha/billing/credits';
74
+ const credits = await requestJson(creditsPath, apiKey, fetchImpl);
75
+ const windows = parseCommandCodeCredits(credits);
76
+ if (Object.keys(windows).length === 0) throw new Error('Command Code usage data could not be parsed');
77
+ return windows;
78
+ };
79
+
80
+ export const isConfigured = () => Boolean(getApiKey());
81
+
82
+ export const fetchQuota = async (auth = readAuthFile()) => {
83
+ const apiKey = getApiKey(auth);
84
+ if (!apiKey) return buildResult({ providerId, providerName, ok: false, configured: false, error: 'Not configured' });
85
+ try {
86
+ return buildResult({ providerId, providerName, ok: true, configured: true, usage: { windows: await fetchCommandCodeUsage(apiKey) } });
87
+ } catch (error) {
88
+ return buildResult({ providerId, providerName, ok: false, configured: true, error: error instanceof Error ? error.message : 'Request failed' });
89
+ }
90
+ };
@@ -0,0 +1,85 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { fetchCommandCodeUsage, fetchQuota, parseCommandCodeCredits } from './command-code.js';
4
+
5
+ const creditsPayload = {
6
+ credits: { monthlyCredits: 120, purchasedCredits: 30, freeCredits: 5 },
7
+ windowLimits: {
8
+ fiveHour: { used: 25, cap: 100, resetAt: 1_776_000_000 },
9
+ weekly: { used: 70, cap: 200, resetAt: 1_776_604_800 },
10
+ },
11
+ };
12
+
13
+ describe('Command Code quota provider', () => {
14
+ it('parses balances and rate-limit windows', () => {
15
+ const windows = parseCommandCodeCredits(creditsPayload);
16
+ expect(windows.monthly_credits).toMatchObject({ usedPercent: null, valueLabel: '120' });
17
+ expect(windows.purchased_credits).toMatchObject({ usedPercent: null, valueLabel: '30' });
18
+ expect(windows.free_credits).toMatchObject({ usedPercent: null, valueLabel: '5' });
19
+ expect(windows['5h']).toMatchObject({ usedPercent: 25, valueLabel: '25 / 100', resetAt: 1_776_000_000_000 });
20
+ expect(windows.weekly.usedPercent).toBe(35);
21
+ });
22
+
23
+ it('formats fractional credit values for display', () => {
24
+ const windows = parseCommandCodeCredits({
25
+ credits: { monthlyCredits: 69.7947070034 },
26
+ windowLimits: { fiveHour: { used: 0.2052929966, cap: 14 } },
27
+ });
28
+ expect(windows.monthly_credits.valueLabel).toBe('69.79');
29
+ expect(windows['5h'].valueLabel).toBe('0.21 / 14');
30
+ });
31
+
32
+ it('resolves the organization before fetching credits', async () => {
33
+ const requests = [];
34
+ const windows = await fetchCommandCodeUsage('secret', async (url, options) => {
35
+ requests.push({ url, options });
36
+ return new Response(JSON.stringify(url.endsWith('/alpha/whoami') ? { org: { id: 'org/a' } } : creditsPayload));
37
+ });
38
+ expect(requests.map(({ url }) => url)).toEqual([
39
+ 'https://api.commandcode.ai/alpha/whoami',
40
+ 'https://api.commandcode.ai/alpha/billing/credits?orgId=org%2Fa',
41
+ ]);
42
+ expect(requests[0].options.headers.Authorization).toBe('Bearer secret');
43
+ expect(windows['5h'].usedPercent).toBe(25);
44
+ });
45
+
46
+ it('fetches account-scoped credits without orgId for personal accounts', async () => {
47
+ const urls = [];
48
+ await fetchCommandCodeUsage('secret', async (url) => {
49
+ urls.push(url);
50
+ return new Response(JSON.stringify(url.endsWith('/alpha/whoami') ? { user: { id: 'user-1' }, org: null } : creditsPayload));
51
+ });
52
+ expect(urls).toEqual([
53
+ 'https://api.commandcode.ai/alpha/whoami',
54
+ 'https://api.commandcode.ai/alpha/billing/credits',
55
+ ]);
56
+ });
57
+
58
+ it('does not expose credentials in authentication errors', async () => {
59
+ await expect(fetchCommandCodeUsage('secret', async () => new Response('', { status: 401 }))).rejects.toThrow('authentication failed');
60
+ });
61
+
62
+ it('reads OAuth access credentials from the OpenCode auth file', async () => {
63
+ const fetchMock = vi.fn()
64
+ .mockResolvedValueOnce(new Response(JSON.stringify({ org: { id: 'org-1' } })))
65
+ .mockResolvedValueOnce(new Response(JSON.stringify(creditsPayload)));
66
+ vi.stubGlobal('fetch', fetchMock);
67
+ const result = await fetchQuota({ 'command-code': { type: 'oauth', access: 'test-token' } });
68
+ expect(result).toMatchObject({ providerId: 'command-code', ok: true, configured: true });
69
+ expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer test-token');
70
+ vi.unstubAllGlobals();
71
+ });
72
+
73
+ it('recognizes Command Code auth entries under supported provider ID variants', async () => {
74
+ for (const providerId of ['commandcode', 'command_code', 'command code']) {
75
+ const fetchMock = vi.fn()
76
+ .mockResolvedValueOnce(new Response(JSON.stringify({ org: { id: 'org-1' } })))
77
+ .mockResolvedValueOnce(new Response(JSON.stringify(creditsPayload)));
78
+ vi.stubGlobal('fetch', fetchMock);
79
+
80
+ const result = await fetchQuota({ [providerId]: { type: 'oauth', access: 'test-token' } });
81
+ expect(result).toMatchObject({ providerId: 'command-code', ok: true, configured: true });
82
+ vi.unstubAllGlobals();
83
+ }
84
+ });
85
+ });
@@ -7,8 +7,9 @@
7
7
 
8
8
  import { buildResult } from '../utils/index.js';
9
9
 
10
- import * as claude from './claude.js';
10
+ import * as claude from './claude/index.js';
11
11
  import * as codex from './codex.js';
12
+ import * as commandCode from './command-code.js';
12
13
  import * as copilot from './copilot.js';
13
14
  import * as crof from './crof.js';
14
15
  import * as cursor from './cursor.js';
@@ -29,6 +30,12 @@ import * as opencodeGo from './opencode-go.js';
29
30
  import * as xai from './xai.js';
30
31
 
31
32
  const registry = {
33
+ 'command-code': {
34
+ providerId: commandCode.providerId,
35
+ providerName: commandCode.providerName,
36
+ isConfigured: commandCode.isConfigured,
37
+ fetchQuota: commandCode.fetchQuota
38
+ },
32
39
  claude: {
33
40
  providerId: claude.providerId,
34
41
  providerName: claude.providerName,
@@ -151,6 +158,15 @@ const registry = {
151
158
  }
152
159
  };
153
160
 
161
+ const pendingFetches = new Map();
162
+
163
+ const normalizeQuotaProviderId = (providerId) => {
164
+ if (typeof providerId !== 'string') return providerId;
165
+ return ['command-code', 'commandcode', 'command_code', 'command code'].includes(providerId.trim().toLowerCase())
166
+ ? 'command-code'
167
+ : providerId;
168
+ };
169
+
154
170
  export const listConfiguredQuotaProviders = () => {
155
171
  const configured = [];
156
172
 
@@ -167,7 +183,7 @@ export const listConfiguredQuotaProviders = () => {
167
183
  return configured;
168
184
  };
169
185
 
170
- export const fetchQuotaForProvider = async (providerId) => {
186
+ const fetchQuotaForProviderUncoalesced = async (providerId) => {
171
187
  const provider = registry[providerId];
172
188
 
173
189
  if (!provider) {
@@ -193,6 +209,18 @@ export const fetchQuotaForProvider = async (providerId) => {
193
209
  }
194
210
  };
195
211
 
212
+ export const fetchQuotaForProvider = (providerId) => {
213
+ const normalizedProviderId = normalizeQuotaProviderId(providerId);
214
+ const existing = pendingFetches.get(normalizedProviderId);
215
+ if (existing) return existing;
216
+
217
+ const pending = fetchQuotaForProviderUncoalesced(normalizedProviderId).finally(() => {
218
+ if (pendingFetches.get(normalizedProviderId) === pending) pendingFetches.delete(normalizedProviderId);
219
+ });
220
+ pendingFetches.set(normalizedProviderId, pending);
221
+ return pending;
222
+ };
223
+
196
224
  export const fetchClaudeQuota = claude.fetchQuota;
197
225
  export const fetchOpenaiQuota = openai.fetchQuota;
198
226
  export const fetchGoogleQuota = google.fetchGoogleQuota;
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
 
3
3
  import * as google from './google/index.js';
4
- import { listConfiguredQuotaProviders } from './index.js';
4
+ import { fetchQuotaForProvider, listConfiguredQuotaProviders } from './index.js';
5
5
 
6
6
  describe('quota provider registry', () => {
7
7
  it('exposes google provider configuration helpers through the provider module', () => {
@@ -14,4 +14,13 @@ describe('quota provider registry', () => {
14
14
  it('can list configured providers without missing provider exports', () => {
15
15
  expect(() => listConfiguredQuotaProviders()).not.toThrow();
16
16
  });
17
+
18
+ it('coalesces concurrent refreshes by provider ID', async () => {
19
+ const first = fetchQuotaForProvider('unsupported-test-provider');
20
+ const second = fetchQuotaForProvider('unsupported-test-provider');
21
+
22
+ expect(first).toBe(second);
23
+ await first;
24
+ expect(fetchQuotaForProvider('unsupported-test-provider')).not.toBe(first);
25
+ });
17
26
  });
@@ -4,6 +4,7 @@ import {
4
4
  normalizeAuthEntry,
5
5
  buildResult,
6
6
  toUsageWindow,
7
+ toNumber,
7
8
  resolveWindowSeconds,
8
9
  resolveWindowLabel,
9
10
  normalizeTimestamp
@@ -13,6 +14,20 @@ export const providerId = 'zai-coding-plan';
13
14
  export const providerName = 'z.ai';
14
15
  const aliases = ['zai-coding-plan', 'zai', 'z.ai'];
15
16
 
17
+ // CREDIT_LIMIT entries carry `usage` (total credits), `currentValue` (consumed),
18
+ // and `remaining`; TOKENS_LIMIT entries only carry a percentage.
19
+ const formatCreditAmount = (value) => {
20
+ if (value < 1000) return value.toLocaleString('en-US');
21
+ return `${Math.round(value / 100) / 10}k`;
22
+ };
23
+
24
+ const formatCreditValueLabel = (limit) => {
25
+ const used = toNumber(limit?.currentValue);
26
+ const total = toNumber(limit?.usage);
27
+ if (used === null || total === null) return null;
28
+ return `${formatCreditAmount(used)} / ${formatCreditAmount(total)} credits`;
29
+ };
30
+
16
31
  export const isConfigured = () => {
17
32
  const auth = readAuthFile();
18
33
  const entry = normalizeAuthEntry(getAuthEntry(auth, aliases));
@@ -56,16 +71,20 @@ export const fetchQuota = async () => {
56
71
  const payload = await response.json();
57
72
  const limits = Array.isArray(payload?.data?.limits) ? payload.data.limits : [];
58
73
  const windows = {};
59
- for (const tokensLimit of limits.filter((limit) => limit?.type === 'TOKENS_LIMIT')) {
60
- const windowSeconds = resolveWindowSeconds(tokensLimit);
74
+ // The API renamed TOKENS_LIMIT to CREDIT_LIMIT; field semantics stayed the same,
75
+ // so both limit types map to the same windows.
76
+ for (const limit of limits.filter((entry) => entry?.type === 'TOKENS_LIMIT' || entry?.type === 'CREDIT_LIMIT')) {
77
+ const windowSeconds = resolveWindowSeconds(limit);
61
78
  const windowLabel = resolveWindowLabel(windowSeconds);
62
- const resetAt = tokensLimit?.nextResetTime ? normalizeTimestamp(tokensLimit.nextResetTime) : null;
63
- const usedPercent = typeof tokensLimit?.percentage === 'number' ? tokensLimit.percentage : null;
79
+ const resetAt = limit?.nextResetTime ? normalizeTimestamp(limit.nextResetTime) : null;
80
+ const usedPercent = typeof limit?.percentage === 'number' ? limit.percentage : null;
81
+ const creditValueLabel = formatCreditValueLabel(limit);
64
82
 
65
83
  windows[windowLabel] = toUsageWindow({
66
84
  usedPercent,
67
85
  windowSeconds,
68
- resetAt
86
+ resetAt,
87
+ valueLabel: creditValueLabel
69
88
  });
70
89
  }
71
90
 
@@ -83,7 +102,8 @@ export const fetchQuota = async () => {
83
102
  providerName,
84
103
  ok: true,
85
104
  configured: true,
86
- usage: { windows }
105
+ usage: { windows },
106
+ planLabel: typeof payload?.data?.level === 'string' && payload.data.level ? payload.data.level : null
87
107
  });
88
108
  } catch (error) {
89
109
  return buildResult({
@@ -51,4 +51,37 @@ describe('Z.ai quota provider', () => {
51
51
  resetAt: 1787128459979,
52
52
  });
53
53
  });
54
+
55
+ it('maps CREDIT_LIMIT entries to windows with credit value labels and plan level', async () => {
56
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
57
+ code: 200,
58
+ data: {
59
+ limits: [
60
+ { type: 'CREDIT_LIMIT', unit: 3, number: 5, usage: 12000, currentValue: 65, remaining: 11934, percentage: 1, nextResetTime: 1787257978907 },
61
+ { type: 'CREDIT_LIMIT', unit: 6, number: 1, usage: 60000, currentValue: 65, remaining: 59934, percentage: 1, nextResetTime: 1787844668997 },
62
+ ],
63
+ level: 'pro',
64
+ },
65
+ })));
66
+
67
+ const result = await fetchQuota();
68
+ const windows = result.usage.windows;
69
+
70
+ expect(result.ok).toBe(true);
71
+ expect(result.planLabel).toBe('pro');
72
+ expect(windows['5h']).toMatchObject({
73
+ usedPercent: 1,
74
+ remainingPercent: 99,
75
+ windowSeconds: 5 * 60 * 60,
76
+ resetAt: 1787257978907,
77
+ valueLabel: '65 / 12k credits',
78
+ });
79
+ expect(windows.weekly).toMatchObject({
80
+ usedPercent: 1,
81
+ remainingPercent: 99,
82
+ windowSeconds: 7 * 24 * 60 * 60,
83
+ resetAt: 1787844668997,
84
+ valueLabel: '65 / 60k credits',
85
+ });
86
+ });
54
87
  });
@@ -53,13 +53,14 @@ export const toUsageWindow = ({ usedPercent, windowSeconds, resetAt, valueLabel
53
53
  };
54
54
  };
55
55
 
56
- export const buildResult = ({ providerId, providerName, ok, configured, usage, error }) => ({
56
+ export const buildResult = ({ providerId, providerName, ok, configured, usage, error, planLabel }) => ({
57
57
  providerId,
58
58
  providerName,
59
59
  ok,
60
60
  configured,
61
61
  usage: usage ?? null,
62
62
  ...(error ? { error } : {}),
63
+ ...(planLabel ? { planLabel } : {}),
63
64
  fetchedAt: Date.now()
64
65
  });
65
66
 
@@ -254,6 +254,7 @@ export const createScheduledTasksRuntime = (deps) => {
254
254
  waitForOpenCodeReady,
255
255
  emitTaskRunEvent,
256
256
  setSessionAutoAccept,
257
+ sessionKnowledgeRuntime = null,
257
258
  logger = console,
258
259
  maxGlobalConcurrency = DEFAULT_GLOBAL_CONCURRENCY,
259
260
  maxProjectConcurrency = DEFAULT_PROJECT_CONCURRENCY,
@@ -451,7 +452,7 @@ export const createScheduledTasksRuntime = (deps) => {
451
452
  return projectRunning < maxProjectConcurrency;
452
453
  };
453
454
 
454
- const buildPromptAsyncPayload = (task, projectPath) => ({
455
+ const buildPromptAsyncPayload = (task, projectPath, knowledgeText = '') => ({
455
456
  model: {
456
457
  providerID: task.execution.providerID,
457
458
  modelID: task.execution.modelID,
@@ -459,6 +460,10 @@ export const createScheduledTasksRuntime = (deps) => {
459
460
  ...(task.execution.agent ? { agent: task.execution.agent } : {}),
460
461
  ...(task.execution.variant ? { variant: task.execution.variant } : {}),
461
462
  parts: [
463
+ // Standing project context first, so the prompt reads against it. A
464
+ // scheduled run has no UI to attach this, which is why it is asked for
465
+ // here rather than assembled by whoever is sending.
466
+ ...(knowledgeText ? [{ type: 'text', text: knowledgeText, synthetic: true }] : []),
462
467
  {
463
468
  type: 'text',
464
469
  text: expandSnippets(task.execution.prompt, projectPath),
@@ -470,6 +475,13 @@ export const createScheduledTasksRuntime = (deps) => {
470
475
  });
471
476
 
472
477
  const runPromptAsync = async ({ baseUrl, authHeaders, sessionID, projectPath, task }) => {
478
+ // Never allowed to fail the run: a task that executes without its
479
+ // background is a lesser loss than a task that does not execute.
480
+ const knowledge = sessionKnowledgeRuntime
481
+ ? await sessionKnowledgeRuntime.resolvePendingForSession(sessionID, projectPath)
482
+ .catch(() => ({ text: '', signature: '' }))
483
+ : { text: '', signature: '' };
484
+
473
485
  const promptUrl = new URL(`${baseUrl}/session/${encodeURIComponent(sessionID)}/prompt_async`);
474
486
  promptUrl.searchParams.set('directory', projectPath);
475
487
  const response = await fetch(promptUrl.toString(), {
@@ -479,13 +491,20 @@ export const createScheduledTasksRuntime = (deps) => {
479
491
  'content-type': 'application/json',
480
492
  accept: 'application/json',
481
493
  },
482
- body: JSON.stringify(buildPromptAsyncPayload(task, projectPath)),
494
+ body: JSON.stringify(buildPromptAsyncPayload(task, projectPath, knowledge.text)),
483
495
  });
484
496
 
485
497
  if (!response.ok) {
486
498
  const body = await response.text().catch(() => '');
487
499
  throw new Error(`prompt_async failed (${response.status})${body ? `: ${body}` : ''}`);
488
500
  }
501
+
502
+ // Recorded only after the prompt is accepted, so a failed dispatch carries
503
+ // the context again on the next run.
504
+ if (knowledge.text && sessionKnowledgeRuntime) {
505
+ await sessionKnowledgeRuntime.recordDelivered(sessionID, projectPath, knowledge.signature)
506
+ .catch(() => undefined);
507
+ }
489
508
  };
490
509
 
491
510
  const resolveScheduledCommand = async ({ client, projectPath, task }) => {
@@ -0,0 +1,89 @@
1
+ # Session Knowledge
2
+
3
+ What a session must be told about the project — that session's pinned notes and
4
+ plans, and the index of what the agent has remembered — and whether it has been
5
+ told yet.
6
+
7
+ ## Why it is here and not in the UI
8
+
9
+ The client used to own this: it assembled the text, decided when to send it, and
10
+ remembered what it had sent in a module-scoped map. Two consequences followed.
11
+
12
+ A session started without a UI got nothing at all. Scheduled tasks and sessions
13
+ the agent dispatches build their prompts on the server and never touch the
14
+ browser, so pinned context and the memory index simply did not exist for them.
15
+
16
+ And a tab's memory of what it sent survives compaction, while the conversation
17
+ does not. After a summary the agent no longer holds the block, but the tab goes
18
+ on believing it does and never sends it again.
19
+
20
+ ## The contract
21
+
22
+ `session.metadata.openchamber.project_context_pins` owns the note and plan ids
23
+ attached to that session. Pins never come from project-wide note or plan state.
24
+ A new-session draft passes its pins into this metadata when its first message
25
+ creates the session.
26
+
27
+ Directories beneath the managed `~/.config/openchamber/chats` root resolve to that root before project context and project memory are read. Every ordinary chat therefore shares one Chats knowledge owner instead of creating an unreachable context store for each dated session directory.
28
+
29
+ `session.metadata.openchamber.knowledge_context_delivered` holds the signature
30
+ of what the session is carrying. It lives with the session, so it survives the
31
+ tab closing and is visible to every sender, including the ones with no tab.
32
+
33
+ The signature covers content revisions, not just identity: editing a pinned note
34
+ must re-send it, not merely renaming one.
35
+
36
+ ## Three moments, two deliveries
37
+
38
+ | Moment | Delivery |
39
+ |---|---|
40
+ | A message from the UI | synthetic part on that message |
41
+ | A scheduled task, a session the agent dispatched | synthetic part on that prompt |
42
+ | After compaction | its own `prompt_async`, alongside the pinned messages |
43
+
44
+ The first two attach to an outgoing message because there is one. Compaction has
45
+ none, which is why it re-sends on its own — and it travels with
46
+ `context-obligatory`'s pinned messages in a single turn, since two synthetic
47
+ messages back to back read as the agent being interrupted twice.
48
+
49
+ ## Failure behaviour
50
+
51
+ Nothing here may fail a send. A message without its background costs the agent
52
+ some context; a failed send costs the user their message. Every caller treats an
53
+ error as "no block this time".
54
+
55
+ A source that will not load never blanks the rest: an unreadable memory store
56
+ still delivers the pinned notes. A memory scope that failed to load is left out
57
+ rather than indexed as empty, which would teach the agent to store again what it
58
+ already has.
59
+
60
+ Delivery is recorded only after the send is accepted. Recording it when the text
61
+ is handed over would leave a failed send believing the agent had context it never
62
+ received.
63
+
64
+ ## Entries that read as instructions
65
+
66
+ Memory is the one place where text from outside can settle permanently. The
67
+ agent reads a page, decides a line is worth keeping, saves it — and from then on
68
+ it rides into every session in every project. An injection anywhere else lives
69
+ for one conversation.
70
+
71
+ `agent-memory/threat-patterns` scans on write and again on every read, so an
72
+ entry written before a pattern existed, or edited on disk since, is judged now.
73
+ A match never deletes: the entry is stored, flagged, kept out of what sessions
74
+ are told, and shown in the panel with a warning. Silently dropping it would hide
75
+ the attempt from the only person able to judge it.
76
+
77
+ Patterns, not a model — this runs on every index build. That buys the blunt
78
+ cases only, which is the honest expectation.
79
+
80
+ ## Shipping dark
81
+
82
+ Agent memory is complete but unreleased. `OPENCHAMBER_MEMORY_ENABLE` decides
83
+ whether it exists in a given process at all: unset, there is no tool, no routes,
84
+ no session index, no settings row and no panel tab — absent rather than switched
85
+ off, which would invite turning on something never announced. The setting itself
86
+ also defaults to off, so setting the variable does not enable memory by itself.
87
+
88
+ Pinned notes and plans are unaffected by the memory switch and remain scoped to
89
+ the session that pinned them.
@@ -0,0 +1,107 @@
1
+ /**
2
+ * What a session still owes in project knowledge, and the record that it was
3
+ * delivered.
4
+ *
5
+ * Two calls rather than one, because only the sender knows whether the message
6
+ * carrying the block actually went out. Handing over the text and recording it
7
+ * as delivered in the same request would leave a failed send believing the
8
+ * agent has context it never received.
9
+ *
10
+ * The body parser is attached per route: there is no global one, because the
11
+ * generic OpenCode proxy needs an unread request stream.
12
+ */
13
+
14
+ import express from 'express';
15
+
16
+ const parseJsonBody = express.json({ limit: '1mb' });
17
+
18
+ const isRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
19
+
20
+ const asNonEmptyString = (value) => (
21
+ typeof value === 'string' && value.trim().length > 0 ? value.trim() : ''
22
+ );
23
+
24
+ export const registerSessionKnowledgeRoutes = (app, dependencies) => {
25
+ const { sessionKnowledgeRuntime } = dependencies;
26
+
27
+ /**
28
+ * Answers with the text to attach and the signature to report back once it
29
+ * has gone. An empty text means the session is already carrying it.
30
+ */
31
+ app.get('/api/session-knowledge', async (req, res) => {
32
+ const directory = asNonEmptyString(req.query.directory);
33
+ const sessionId = asNonEmptyString(req.query.sessionId);
34
+ if (!directory) {
35
+ return res.status(400).json({ error: 'directory is required' });
36
+ }
37
+
38
+ try {
39
+ const pending = sessionId
40
+ ? await sessionKnowledgeRuntime.resolvePendingForSession(sessionId, directory)
41
+ // A session that does not exist yet — a draft about to be created —
42
+ // has been told nothing, so everything is still owed.
43
+ : await sessionKnowledgeRuntime.resolvePending(directory, '');
44
+ return res.json(pending);
45
+ } catch (error) {
46
+ // Never fails the caller's send: a message without its background is far
47
+ // better than no message at all.
48
+ return res.json({ text: '', signature: '', unavailable: true, reason: error?.message ?? 'unknown' });
49
+ }
50
+ });
51
+
52
+ /** Counts and names for the work status panel; assembles no text. */
53
+ app.get('/api/session-knowledge/summary', async (req, res) => {
54
+ const directory = asNonEmptyString(req.query.directory);
55
+ if (!directory) {
56
+ return res.json({ notes: [], plans: [], memory: { global: 0, project: 0 } });
57
+ }
58
+ const sessionId = asNonEmptyString(req.query.sessionId);
59
+ try {
60
+ return res.json(sessionId
61
+ ? await sessionKnowledgeRuntime.collectSummaryForSession(sessionId, directory)
62
+ : await sessionKnowledgeRuntime.collectSummary(directory));
63
+ } catch {
64
+ // A panel that cannot read this shows nothing rather than an error.
65
+ return res.json({ notes: [], plans: [], memory: { global: 0, project: 0 } });
66
+ }
67
+ });
68
+
69
+ app.post('/api/session-knowledge/pin', parseJsonBody, async (req, res) => {
70
+ const body = req.body;
71
+ if (!isRecord(body)) return res.status(400).json({ error: 'Body must be an object' });
72
+ const sessionId = asNonEmptyString(body.sessionId);
73
+ const directory = asNonEmptyString(body.directory);
74
+ const id = asNonEmptyString(body.id);
75
+ const kind = body.kind === 'note' || body.kind === 'plan' ? body.kind : '';
76
+ if (!sessionId || !directory || !id || !kind || typeof body.pinned !== 'boolean') {
77
+ return res.status(400).json({ error: 'sessionId, directory, kind, id and pinned are required' });
78
+ }
79
+ try {
80
+ return res.json({ pins: await sessionKnowledgeRuntime.setPin(sessionId, directory, kind, id, body.pinned) });
81
+ } catch (error) {
82
+ return res.status(500).json({ error: error?.message ?? 'Unable to update pin' });
83
+ }
84
+ });
85
+
86
+ app.post('/api/session-knowledge/delivered', parseJsonBody, async (req, res) => {
87
+ const body = req.body;
88
+ if (!isRecord(body)) {
89
+ return res.status(400).json({ error: 'Body must be an object' });
90
+ }
91
+ const sessionId = asNonEmptyString(body.sessionId);
92
+ const directory = asNonEmptyString(body.directory);
93
+ const signature = asNonEmptyString(body.signature);
94
+ if (!sessionId || !directory || !signature) {
95
+ return res.status(400).json({ error: 'sessionId, directory and signature are required' });
96
+ }
97
+
98
+ try {
99
+ await sessionKnowledgeRuntime.recordDelivered(sessionId, directory, signature);
100
+ return res.json({ recorded: true });
101
+ } catch (error) {
102
+ // The message is already sent; failing here only means the block may be
103
+ // sent once more, which is far better than reporting the send as failed.
104
+ return res.json({ recorded: false, reason: error?.message ?? 'unknown' });
105
+ }
106
+ });
107
+ };