@kabmo-labs/kabmo 0.24.0 → 0.26.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 (325) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +585 -512
  3. package/dist/client/static/js/{index-jcr5twtp.js → index-95b3n20k.js} +1105 -1207
  4. package/dist/client/static/js/index-p2yw9ywf.css +1 -0
  5. package/package.json +2 -4
  6. package/src/cli/lib/args.js +24 -1
  7. package/src/cli/lib/args.test.js +16 -0
  8. package/src/cli/lib/commands/session.js +233 -0
  9. package/src/cli/lib/commands/session.test.js +103 -0
  10. package/src/cli/main.js +1 -1
  11. package/src/client/components/common/ComposerPicker.tsx +3 -0
  12. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  13. package/src/client/components/common/code-surface/shiki.ts +28 -7
  14. package/src/client/components/common/session-actions-menu/index.tsx +59 -2
  15. package/src/client/components/common/session-branch/BranchGuides.tsx +93 -0
  16. package/src/client/components/common/session-branch/SubagentRow.tsx +77 -0
  17. package/src/client/components/common/session-branch/index.tsx +169 -0
  18. package/src/client/components/common/session-branch/session-branch.test.tsx +240 -0
  19. package/src/client/components/common/session-branch/style.ts +29 -0
  20. package/src/client/components/common/session-row/StatusSlot.tsx +17 -5
  21. package/src/client/components/common/session-row/index.tsx +28 -3
  22. package/src/client/components/common/session-row/session-row.test.tsx +11 -0
  23. package/src/client/components/common/session-state-provider/index.tsx +1 -1
  24. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  25. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +70 -61
  26. package/src/client/components/layout/session-sidebar/SessionItem.batch.test.ts +3 -3
  27. package/src/client/components/layout/session-sidebar/SessionItem.test.ts +25 -2
  28. package/src/client/components/layout/session-sidebar/SessionItem.tsx +35 -7
  29. package/src/client/components/layout/session-sidebar/about-modal/HarnessRow.tsx +261 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +39 -198
  31. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +114 -0
  32. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  33. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +128 -0
  34. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +56 -0
  35. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +44 -36
  36. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +62 -47
  37. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +63 -50
  38. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.test.ts +5 -0
  39. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +37 -12
  40. package/src/client/components/settings/Sidebar.tsx +1 -1
  41. package/src/client/components/settings/categories/NotificationSettings.test.tsx +92 -0
  42. package/src/client/components/settings/categories/NotificationSettings.tsx +112 -2
  43. package/src/client/components/settings/categories/harness-settings/HarnessCard.tsx +1 -1
  44. package/src/client/components/workspace/chat-timeline/AiMessageFooter.fork.test.ts +94 -0
  45. package/src/client/components/workspace/chat-timeline/AiMessageFooter.tsx +31 -5
  46. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  47. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  48. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +128 -122
  49. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  50. package/src/client/components/workspace/chat-timeline/MessageList.tsx +11 -5
  51. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +10 -0
  52. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +12 -3
  53. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  54. package/src/client/components/workspace/chat-timeline/chat-input/AttachmentToolbar.tsx +2 -0
  55. package/src/client/components/workspace/chat-timeline/chat-input/ModeToggles.tsx +15 -1
  56. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.test.tsx +85 -0
  57. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.tsx +84 -0
  58. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +2 -0
  59. package/src/client/components/workspace/chat-timeline/chat-input/modes-props.ts +5 -0
  60. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  61. package/src/client/components/workspace/chat-timeline/index.tsx +11 -20
  62. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +115 -0
  63. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +173 -0
  64. package/src/client/components/workspace/chat-timeline/target-picker/parent-session-options.test.ts +49 -0
  65. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  66. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  67. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  68. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  69. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  70. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  71. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  72. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  73. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  74. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  75. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  76. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  77. package/src/client/data/settings/omp-schema.json +1 -1
  78. package/src/client/data/theme/terminal.test.ts +25 -0
  79. package/src/client/data/theme/terminal.ts +96 -79
  80. package/src/client/hooks/chat/composer/items.test.ts +31 -26
  81. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  82. package/src/client/hooks/chat/omp/folder-auto-expand.ts +1 -1
  83. package/src/client/hooks/chat/omp/pending-adoption.ts +51 -0
  84. package/src/client/hooks/chat/omp/pending-child.test.ts +73 -0
  85. package/src/client/hooks/chat/omp/pending-entry.ts +59 -0
  86. package/src/client/hooks/chat/omp/pending-rows.ts +6 -2
  87. package/src/client/hooks/chat/omp/pending-sessions.test.ts +1 -2
  88. package/src/client/hooks/chat/omp/pending-sessions.ts +45 -69
  89. package/src/client/hooks/chat/omp/pending-waiting.ts +1 -1
  90. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  91. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  92. package/src/client/hooks/chat/omp/run-switch.ts +1 -1
  93. package/src/client/hooks/chat/omp/session-list.tsx +4 -0
  94. package/src/client/hooks/chat/subagents/roster.ts +122 -0
  95. package/src/client/hooks/chat/timeline/child-spawn.test.ts +55 -0
  96. package/src/client/hooks/chat/timeline/child-spawn.ts +45 -0
  97. package/src/client/hooks/chat/timeline/fork-request.test.ts +54 -0
  98. package/src/client/hooks/chat/timeline/fork-request.ts +43 -0
  99. package/src/client/hooks/chat/timeline/mode-availability.test.ts +1 -1
  100. package/src/client/hooks/chat/timeline/mode-availability.ts +33 -0
  101. package/src/client/hooks/chat/timeline/mode-markers.ts +7 -1
  102. package/src/client/hooks/chat/timeline/mode-post.ts +15 -3
  103. package/src/client/hooks/chat/timeline/modes-contract.ts +9 -4
  104. package/src/client/hooks/chat/timeline/modes.test.ts +56 -18
  105. package/src/client/hooks/chat/timeline/modes.ts +42 -29
  106. package/src/client/hooks/chat/timeline/pending-branch.ts +205 -0
  107. package/src/client/hooks/chat/timeline/pending-dispatch.ts +253 -0
  108. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  109. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  110. package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
  111. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  112. package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
  113. package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
  114. package/src/client/hooks/chat/timeline/send.test.ts +3 -1
  115. package/src/client/hooks/chat/timeline/send.ts +48 -133
  116. package/src/client/hooks/chat/timeline/session-harness.ts +6 -0
  117. package/src/client/hooks/chat/timeline/stop-with-queue.ts +42 -0
  118. package/src/client/hooks/chat/timeline/use-fork-session.ts +58 -0
  119. package/src/client/hooks/models/use-harness-update.test.ts +286 -0
  120. package/src/client/hooks/models/use-harness-update.ts +250 -0
  121. package/src/client/hooks/ui/input-required-alert.ts +12 -5
  122. package/src/client/hooks/ui/notifications.ts +45 -0
  123. package/src/client/hooks/ui/run-outcome-alert.ts +48 -0
  124. package/src/client/hooks/workspace/expanded-sessions.ts +36 -7
  125. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  126. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  127. package/src/client/lib/native/open-session.ts +33 -0
  128. package/src/client/lib/notifications/os.test.ts +125 -0
  129. package/src/client/lib/notifications/os.ts +130 -0
  130. package/src/client/lib/plugins/sidebar-bridge.ts +2 -20
  131. package/src/client/lib/router/open-session.test.ts +75 -0
  132. package/src/client/lib/router/open-session.ts +34 -0
  133. package/src/client/lib/session-tree.test.ts +50 -0
  134. package/src/client/lib/session-tree.ts +59 -0
  135. package/src/client/lib/signals.ts +5 -1
  136. package/src/client/main.tsx +6 -0
  137. package/src/client/tailwind.css +17 -11
  138. package/src/server/index.ts +2 -0
  139. package/src/server/lib/auth/guard.ts +10 -0
  140. package/src/server/lib/btw/session-copy.server.ts +6 -44
  141. package/src/server/lib/btw/session-copy.test.ts +2 -1
  142. package/src/server/lib/db/schema.ts +5 -0
  143. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  144. package/src/server/lib/db/seed.test.ts +1 -1
  145. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  146. package/src/server/lib/harness/acp/background-work.ts +320 -0
  147. package/src/server/lib/harness/acp/calls.ts +15 -1
  148. package/src/server/lib/harness/acp/client-capabilities.test.ts +55 -0
  149. package/src/server/lib/harness/acp/client-capabilities.ts +61 -0
  150. package/src/server/lib/harness/acp/client-fs.test.ts +135 -0
  151. package/src/server/lib/harness/acp/client-fs.ts +131 -0
  152. package/src/server/lib/harness/acp/client-initialize.test.ts +70 -0
  153. package/src/server/lib/harness/acp/client-initialize.ts +84 -0
  154. package/src/server/lib/harness/acp/client.ts +33 -23
  155. package/src/server/lib/harness/acp/commands.test.ts +5 -5
  156. package/src/server/lib/harness/acp/commands.ts +14 -2
  157. package/src/server/lib/harness/acp/frames-timing.test.ts +68 -0
  158. package/src/server/lib/harness/acp/frames-v2.test.ts +85 -0
  159. package/src/server/lib/harness/acp/frames.ts +71 -158
  160. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  161. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  162. package/src/server/lib/harness/acp/mapper.test.ts +40 -0
  163. package/src/server/lib/harness/acp/mapper.ts +12 -0
  164. package/src/server/lib/harness/acp/permissions.ts +6 -0
  165. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  166. package/src/server/lib/harness/acp/prompt.ts +19 -3
  167. package/src/server/lib/harness/acp/protocol.ts +41 -2
  168. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  169. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  170. package/src/server/lib/harness/acp/session-facts.ts +1 -1
  171. package/src/server/lib/harness/acp/session-handshake.test.ts +197 -0
  172. package/src/server/lib/harness/acp/session-handshake.ts +110 -7
  173. package/src/server/lib/harness/acp/session-idle.ts +7 -6
  174. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  175. package/src/server/lib/harness/acp/session-notifications.ts +41 -2
  176. package/src/server/lib/harness/acp/session-observers.test.ts +63 -0
  177. package/src/server/lib/harness/acp/session-permissions.test.ts +29 -0
  178. package/src/server/lib/harness/acp/session-permissions.ts +36 -0
  179. package/src/server/lib/harness/acp/session-requests.test.ts +92 -0
  180. package/src/server/lib/harness/acp/session-requests.ts +89 -0
  181. package/src/server/lib/harness/acp/session-turns.ts +28 -8
  182. package/src/server/lib/harness/acp/session-usage.ts +4 -0
  183. package/src/server/lib/harness/acp/session-web-state.ts +30 -2
  184. package/src/server/lib/harness/acp/session.test-util.ts +42 -2
  185. package/src/server/lib/harness/acp/session.ts +115 -115
  186. package/src/server/lib/harness/acp/tool-calls.ts +223 -0
  187. package/src/server/lib/harness/acp/turn.test.ts +183 -0
  188. package/src/server/lib/harness/acp/turn.ts +102 -10
  189. package/src/server/lib/harness/acp/v2.test.ts +144 -0
  190. package/src/server/lib/harness/acp/v2.ts +220 -0
  191. package/src/server/lib/harness/acp/verbs.ts +58 -8
  192. package/src/server/lib/harness/launch.test.ts +25 -0
  193. package/src/server/lib/harness/launch.ts +24 -10
  194. package/src/server/lib/harness/session.ts +3 -0
  195. package/src/server/lib/harness/spawn.server.ts +15 -2
  196. package/src/server/lib/harness/update-job-store.test.ts +151 -0
  197. package/src/server/lib/harness/update-job-store.ts +115 -0
  198. package/src/server/lib/harness/update-job.server.ts +94 -0
  199. package/src/server/lib/harness/update-queue.server.ts +292 -0
  200. package/src/server/lib/harness/update-queue.test.ts +265 -0
  201. package/src/server/lib/harness/update-spawn.server.ts +96 -0
  202. package/src/server/lib/harness/update-worker.test.ts +153 -0
  203. package/src/server/lib/harness/update-worker.ts +202 -0
  204. package/src/server/lib/lifecycle/after-listen.ts +9 -0
  205. package/src/server/lib/lifecycle/paths.ts +28 -0
  206. package/src/server/lib/omp/rpc/manager.ts +5 -5
  207. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  208. package/src/server/lib/omp/rpc/run-settle.server.ts +10 -1
  209. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  210. package/src/server/lib/omp/rpc/subagent-liveness.ts +5 -5
  211. package/src/server/lib/omp/rpc/terminal-settle.ts +58 -6
  212. package/src/server/lib/omp/session/delete-flow.server.ts +48 -0
  213. package/src/server/lib/omp/session/delete.server.ts +5 -0
  214. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  215. package/src/server/lib/omp/session/sidebar-data.server.ts +16 -18
  216. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  217. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  218. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  219. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  220. package/src/server/lib/sessions/answers.server.ts +37 -0
  221. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  222. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  223. package/src/server/lib/sessions/fork.server.test.ts +277 -0
  224. package/src/server/lib/sessions/fork.server.ts +329 -0
  225. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  226. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  227. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  228. package/src/server/lib/sessions/notify.server.ts +212 -0
  229. package/src/server/lib/sessions/relation-types.ts +76 -0
  230. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  231. package/src/server/lib/sessions/relations.server.ts +337 -0
  232. package/src/server/lib/sessions/resolve.server.ts +106 -0
  233. package/src/server/lib/sessions/schema.server.ts +82 -0
  234. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  235. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  236. package/src/server/lib/sessions/spawn.server.test.ts +237 -0
  237. package/src/server/lib/sessions/spawn.server.ts +335 -0
  238. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  239. package/src/server/lib/terminal/output.test.ts +2 -2
  240. package/src/server/lib/terminal/output.ts +1 -1
  241. package/src/server/lib/terminal/resize.test.ts +99 -0
  242. package/src/server/lib/terminal/runtime.server.ts +26 -6
  243. package/src/server/lib/terminal/send-result.test.ts +18 -1
  244. package/src/server/lib/terminal/send-result.ts +26 -2
  245. package/src/server/lib/terminal/session.server.ts +6 -6
  246. package/src/server/lib/usage/new-api.test.ts +92 -0
  247. package/src/server/lib/usage/new-api.ts +131 -0
  248. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  249. package/src/server/lib/usage/provider-key.ts +33 -0
  250. package/src/server/lib/usage/providers.server.ts +10 -3
  251. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  252. package/src/server/lib/usage/vendor-http.ts +41 -0
  253. package/src/server/lib/usage/window.ts +55 -0
  254. package/src/server/routes/agent/command.ts +14 -1
  255. package/src/server/routes/agent/harness-command.ts +12 -5
  256. package/src/server/routes/agent/new.ts +15 -0
  257. package/src/server/routes/chat/stream.ts +7 -2
  258. package/src/server/routes/harness/add-provider.test.ts +9 -1
  259. package/src/server/routes/harness/import-action.ts +4 -0
  260. package/src/server/routes/harness/import.test.ts +1 -1
  261. package/src/server/routes/harness/index.ts +5 -1
  262. package/src/server/routes/harness/update-status.ts +32 -0
  263. package/src/server/routes/harness/update.test.ts +156 -0
  264. package/src/server/routes/harness/update.ts +64 -147
  265. package/src/server/routes/sessions/answer.ts +24 -0
  266. package/src/server/routes/sessions/batch-delete.ts +11 -5
  267. package/src/server/routes/sessions/body-readers.ts +43 -0
  268. package/src/server/routes/sessions/delete.ts +4 -2
  269. package/src/server/routes/sessions/fork.ts +89 -0
  270. package/src/server/routes/sessions/index.ts +14 -0
  271. package/src/server/routes/sessions/relations.ts +85 -0
  272. package/src/server/routes/sessions/routes.test.ts +1 -2
  273. package/src/server/routes/sessions/session.ts +23 -0
  274. package/src/server/routes/sessions/spawn.ts +137 -0
  275. package/src/server/routes/terminal/ws.ts +3 -3
  276. package/src/shared/lib/chat/composer/client.ts +31 -2
  277. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  278. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  279. package/src/shared/lib/chat/notice-text.ts +1 -1
  280. package/src/shared/lib/chat/omp/agent-events.ts +11 -0
  281. package/src/shared/lib/chat/omp/session-modes-signal.test.ts +41 -0
  282. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  283. package/src/shared/lib/code/ansi.ts +1 -1
  284. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  285. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  286. package/src/shared/lib/harness/mode-signal.ts +20 -0
  287. package/src/shared/lib/harness/provider-facts.test.ts +27 -0
  288. package/src/shared/lib/harness/providers.ts +35 -1
  289. package/src/shared/lib/harness/session-modes.ts +24 -0
  290. package/src/shared/lib/harness/update-job.ts +80 -0
  291. package/src/shared/lib/harness/update-plan.test.ts +21 -6
  292. package/src/shared/lib/harness/update-plan.ts +12 -4
  293. package/src/shared/lib/icons/tint-hues.generated.ts +34 -34
  294. package/src/shared/lib/notifications/outcomes.test.ts +96 -0
  295. package/src/shared/lib/notifications/outcomes.ts +64 -0
  296. package/src/shared/lib/notifications/settings.test.ts +49 -0
  297. package/src/shared/lib/notifications/settings.ts +34 -0
  298. package/src/shared/lib/omp/session/default-title.ts +5 -4
  299. package/src/shared/lib/omp/session/prewarm-misc.test.ts +3 -2
  300. package/src/shared/lib/omp/session/schema-migrations.ts +4 -0
  301. package/src/shared/lib/omp/session/stream-state.server.test.ts +19 -0
  302. package/src/shared/lib/omp/session/stream-state.server.ts +24 -4
  303. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  304. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  305. package/src/shared/lib/settings/defaults.ts +3 -0
  306. package/src/shared/lib/theme/catalog.test.ts +13 -9
  307. package/src/shared/lib/theme/color.test.ts +2 -2
  308. package/src/shared/lib/theme/color.ts +4 -4
  309. package/src/shared/lib/theme/theme.test.ts +1 -1
  310. package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
  311. package/src/shared/lib/workspace/terminal/input.ts +33 -0
  312. package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
  313. package/src/shared/lib/workspace/terminal/keys.ts +7 -7
  314. package/src/shared/types/chat.ts +1 -1
  315. package/src/shared/types/harness-update.ts +89 -0
  316. package/src/shared/types/omp/agent.ts +19 -2
  317. package/src/shared/types/realtime.ts +2 -0
  318. package/src/shared/types/settings/state.ts +10 -0
  319. package/src/shared/types/workspace.ts +8 -0
  320. package/src/test-support/fake-omp-fork.ts +16 -2
  321. package/src/test-support/harness-table.test-util.ts +31 -1
  322. package/dist/client/static/js/index-z3w7n85q.css +0 -1
  323. package/src/client/components/common/subagent-list/index.tsx +0 -165
  324. package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
  325. package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
@@ -0,0 +1,99 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * A resize moves the PTY *and* the grid the retained history is replayed at.
8
+ *
9
+ * The replay size used to be frozen at the session's spawn size. That is wrong
10
+ * the moment the panel is resized: the history is the shell's screen stream, and
11
+ * after a resize the shell's screen is the new grid, so replaying at the old one
12
+ * re-wraps every line written since. Measured on the real panel: after a resize
13
+ * each reload laid the history out at the old 40×31, then fitted to 41×47, so the
14
+ * transcript shifted and the shell redrew its prompt on the resize that followed
15
+ * — one more block of history per reload, which is exactly the "the rows march
16
+ * down on every reload" report.
17
+ *
18
+ * The records here are fakes (no PTY): the decision is the session's, and the
19
+ * probe is the real one because "did the size change" is what the test is about.
20
+ */
21
+
22
+ import { afterEach, describe, expect, test } from 'bun:test';
23
+ import { resizeTerminal } from '@/server/lib/terminal/runtime.server';
24
+ import { terminalStore, type TerminalStore } from '@/server/lib/terminal/store';
25
+ import { createTerminalOutputQueue } from '@/server/lib/terminal/output';
26
+ import type { TerminalSession } from '@/server/lib/terminal/session.server';
27
+
28
+ function fakeSession(over: Partial<TerminalSession> = {}): TerminalSession {
29
+ return {
30
+ id: 'resize-test',
31
+ cwd: '/tmp',
32
+ shell: '/bin/sh',
33
+ term: { resize: () => {}, write: () => {} } as unknown as TerminalSession['term'],
34
+ proc: null,
35
+ history: { append: () => {}, replay: () => new Uint8Array(), size: () => 0 } as unknown as TerminalSession['history'],
36
+ output: createTerminalOutputQueue(() => {}),
37
+ viewers: new Set(),
38
+ cols: 80,
39
+ rows: 24,
40
+ replayCols: 80,
41
+ replayRows: 24,
42
+ status: 'running',
43
+ exitCode: null,
44
+ signal: null,
45
+ lastActivity: Date.now(),
46
+ ...over,
47
+ };
48
+ }
49
+
50
+ function store(): TerminalStore {
51
+ return terminalStore();
52
+ }
53
+
54
+ afterEach(() => {
55
+ const { sessions, resizeTimers } = store();
56
+ for (const timer of resizeTimers.values()) clearTimeout(timer);
57
+ resizeTimers.clear();
58
+ for (const session of sessions.values()) session.output.dispose();
59
+ sessions.clear();
60
+ });
61
+
62
+ describe('resizeTerminal', () => {
63
+ test('moves the PTY and the replay grid together', () => {
64
+ const session = fakeSession();
65
+ store().sessions.set(session.id, session);
66
+
67
+ resizeTerminal(session.id, 41, 47);
68
+
69
+ expect(session.cols).toBe(41);
70
+ expect(session.rows).toBe(47);
71
+ // The replay follows, or every reload re-wraps the history at the old size.
72
+ expect(session.replayCols).toBe(41);
73
+ expect(session.replayRows).toBe(47);
74
+ });
75
+
76
+ test('does nothing for the size the session already has', () => {
77
+ let resizes = 0;
78
+ const session = fakeSession({
79
+ term: { resize: () => { resizes += 1; }, write: () => {} } as unknown as TerminalSession['term'],
80
+ });
81
+ store().sessions.set(session.id, session);
82
+
83
+ resizeTerminal(session.id, 80, 24);
84
+
85
+ expect(resizes).toBe(0);
86
+ });
87
+
88
+ test('clamps a grid to the protocol bounds before applying it', () => {
89
+ const session = fakeSession();
90
+ store().sessions.set(session.id, session);
91
+
92
+ resizeTerminal(session.id, 1, 100_000);
93
+
94
+ expect(session.cols).toBe(2);
95
+ expect(session.rows).toBe(500);
96
+ expect(session.replayCols).toBe(2);
97
+ expect(session.replayRows).toBe(500);
98
+ });
99
+ });
@@ -55,10 +55,20 @@ const resizeTimers = registry.resizeTimers;
55
55
  export async function attachTerminal(viewer: TerminalViewer, request: AttachRequest): Promise<TerminalAttachment> {
56
56
  const session = await openTerminal(request);
57
57
 
58
+ // The attach states the viewer's grid, and that has to be the PTY's size: a
59
+ // shell only learns a size from `resize`, and a page that just fitted to the
60
+ // grid the session already had sends no resize frame at all. Without this, a
61
+ // shell left at a squeezed size by an earlier mount (the panel opens with a
62
+ // width transition; measured `resize 5x37` while it was still animating) kept
63
+ // drawing every later prompt hard-wrapped, and that garbage is replayed on
64
+ // every reconnect. Equal sizes early-return in `resizeTerminal`, so the
65
+ // common attach sends no signal.
66
+ resizeTerminal(session.id, request.cols, request.rows);
67
+
58
68
  // Pending bytes are already in history, so they have to leave the coalescer
59
69
  // BEFORE the replay is captured: delivered after, the viewer would receive
60
70
  // them twice; captured first, they would be missing from the replay and then
61
- // arrive out of order. Either way xterm shows duplicated or shuffled lines.
71
+ // arrive out of order. Either way the terminal shows duplicated or shuffled lines.
62
72
  session.output.flush();
63
73
  const replay = session.history.replay();
64
74
  const snapshot = snapshotOf(session);
@@ -170,6 +180,16 @@ export function resizeTerminal(id: string, cols: number, rows: number): void {
170
180
  if (size.cols === session.cols && size.rows === session.rows) return;
171
181
  session.cols = size.cols;
172
182
  session.rows = size.rows;
183
+ // The replay grid follows the PTY, it does not stay at the spawn size.
184
+ //
185
+ // The retained history is the shell's screen stream, and after a resize the
186
+ // shell's screen IS this grid: replaying at the size the session was created
187
+ // with re-wraps every line written since into the old width. Measured after a
188
+ // panel resize: each reload laid the history out at the old 40×31 and then
189
+ // fitted to 41×47, so the transcript shifted and the shell redrew its prompt
190
+ // on the resize that followed — one more block of history per reload.
191
+ session.replayCols = size.cols;
192
+ session.replayRows = size.rows;
173
193
  session.lastActivity = Date.now();
174
194
  try {
175
195
  session.term.resize(size.cols, size.rows);
@@ -184,11 +204,11 @@ export function resizeTerminal(id: string, cols: number, rows: number): void {
184
204
  /**
185
205
  * Debounce for `resizeTerminal`.
186
206
  *
187
- * A panel drag produces a burst of sizes — the pointer moves in steps and
188
- * xterm's FitAddon refits on every animation frame — and each accepted size
189
- * sends SIGWINCH. The shell answers every one of them by redrawing its prompt,
190
- * so a single drag used to print the prompt a dozen times (measured: 10
191
- * SIGWINCH in one second for one drag).
207
+ * A panel drag produces a burst of sizes — the pointer moves in steps and the
208
+ * host's ResizeObserver reports most of them — and each accepted size sends
209
+ * SIGWINCH. The shell answers every one of them by redrawing its prompt, so a
210
+ * single drag used to print the prompt a dozen times (measured: 10 SIGWINCH in
211
+ * one second for one drag).
192
212
  *
193
213
  * Only the trailing size matters: the PTY ends at the final grid either way,
194
214
  * and a repaint of an intermediate size is invisible work. A single timeout is
@@ -11,7 +11,24 @@
11
11
  */
12
12
 
13
13
  import { describe, expect, test } from 'bun:test';
14
- import { frameAccepted } from '@/server/lib/terminal/send-result';
14
+ import { asBinaryFrame, frameAccepted } from '@/server/lib/terminal/send-result';
15
+
16
+ describe('asBinaryFrame', () => {
17
+ test('a Uint8Array becomes a Buffer VIEW over the same bytes', () => {
18
+ const source = new Uint8Array([0x1b, 0x5b, 0x4d, 0x20, 0x20, 0x20]);
19
+ const frame = asBinaryFrame(source);
20
+ expect(Buffer.isBuffer(frame)).toBe(true);
21
+ expect([...(frame as Buffer)]).toEqual([...source]);
22
+ // Elysia only keeps bytes binary for Buffer; a copy would be correct but
23
+ // would double the cost of every PTY frame, so this pins the view.
24
+ (frame as Buffer)[0] = 0x41;
25
+ expect(source[0]).toBe(0x41);
26
+ });
27
+
28
+ test('a string stays text', () => {
29
+ expect(asBinaryFrame('{"t":"ready"}')).toBe('{"t":"ready"}');
30
+ });
31
+ });
15
32
 
16
33
  describe('frameAccepted', () => {
17
34
  test('bytes queued is a delivery', () => {
@@ -18,15 +18,39 @@
18
18
  * more than `backpressureLimit` (16 MiB by default). The bytes are gone.
19
19
  *
20
20
  * Reading `-1` as failure closes a healthy viewer at the first burst; reading
21
- * `0` as success is worse, because the client keeps xterm attached to a stream
22
- * with a hole in it — exactly the mid-sequence corruption the drop rule exists
21
+ * `0` as success is worse, because the client keeps the terminal attached to a
22
+ * stream with a hole in it — exactly the mid-sequence corruption the drop rule exists
23
23
  * to prevent. Measured against Bun 1.4.4, 20,000 frames of 4 KiB: the old
24
24
  * `!== -1` rule stopped at frame 160 (655 KiB, 0.8 %) while the socket was
25
25
  * still accepting, and a 40,000 × 1 KiB burst returned `-1` 17,870 times and
26
26
  * `0` 20,851 times.
27
27
  *
28
28
  * Never call this with an empty frame: `send('')` succeeds but reports `0`.
29
+ *
30
+ * The module also owns `asBinaryFrame`, the other half of handing a frame to
31
+ * Bun's socket: Elysia only keeps bytes binary when they arrive as a Buffer.
29
32
  */
30
33
  export function frameAccepted(result: number): boolean {
31
34
  return result !== 0;
32
35
  }
36
+
37
+ /**
38
+ * Hand raw terminal bytes to Elysia as a Buffer.
39
+ *
40
+ * Elysia's `ws.send` JSON-stringifies every object that is not a Buffer
41
+ * (`node_modules/elysia/dist/ws/index.js`: `Buffer.isBuffer(data) ? raw.send(data)
42
+ * : … typeof data == "object" && (data = JSON.stringify(data))`). A
43
+ * `Uint8Array` therefore reaches the browser as TEXT — measured: the shell's
44
+ * `echo` arrived as `{"0":101,"1":99,…}` and the client dropped it as an
45
+ * unknown control frame. That is a correctness bug first, and a throughput bug
46
+ * second: every output byte expands to ~4 JSON bytes and the client must parse
47
+ * them back.
48
+ *
49
+ * `Buffer.from(arrayBuffer, offset, length)` is a VIEW over the same memory, so
50
+ * this does not copy a PTY frame. No cast is needed: Buffer is a Uint8Array,
51
+ * and `Buffer.isBuffer` is what selects Elysia's binary branch.
52
+ */
53
+ export function asBinaryFrame(frame: string | Uint8Array): string | Buffer {
54
+ if (typeof frame === 'string') return frame;
55
+ return Buffer.isBuffer(frame) ? frame : Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);
56
+ }
@@ -28,7 +28,7 @@
28
28
  * SIGWINCH itself.
29
29
  *
30
30
  * A fourth: a PTY read may split a multi-byte character, so bytes are forwarded
31
- * verbatim and xterm's own streaming decoder reassembles them.
31
+ * verbatim and the renderer's own streaming decoder reassembles them.
32
32
  *
33
33
  * A fifth, and the reason `output.ts` exists: **reads are coalesced into frames,
34
34
  * never forwarded one-per-read**. One read is one line for a line-oriented
@@ -82,7 +82,7 @@ export interface TerminalSession {
82
82
  viewers: Set<TerminalViewer>;
83
83
  cols: number;
84
84
  rows: number;
85
- /** Grid the retained scrollback was drawn for — replay must match it. */
85
+ /** Grid the retained scrollback is replayed at: the PTY's current size. */
86
86
  replayCols: number;
87
87
  replayRows: number;
88
88
  status: 'running' | 'exited';
@@ -96,8 +96,8 @@ export interface TerminalSession {
96
96
  *
97
97
  * A viewer reports false only for a real drop (`send-result.ts` owns that
98
98
  * contract: Bun's `-1` means "queued, draining" and `0` means "dropped"). A
99
- * dropped viewer is closed rather than skipped — skipping would leave xterm's
100
- * parser mid-sequence, so the honest outcome is a reconnect that replays the
99
+ * dropped viewer is closed rather than skipped — skipping would leave the
100
+ * renderer's parser mid-sequence, so the honest outcome is a reconnect that replays the
101
101
  * scrollback. The PTY cannot be paused, so this is the only backpressure a
102
102
  * terminal has; coalescing in `output.ts` is what keeps it from firing on a
103
103
  * producer that simply emits many small reads.
@@ -201,8 +201,8 @@ export async function createSession(request: AttachRequest): Promise<TerminalSes
201
201
  session.exitCode = code ?? null;
202
202
  session.signal = signalName(proc.signalCode);
203
203
  session.lastActivity = Date.now();
204
- // Queued output is older than this frame. Flushing first keeps xterm's
205
- // order honest: otherwise the shell's last bytes would print after the
204
+ // Queued output is older than this frame. Flushing first keeps the
205
+ // renderer's order honest: otherwise the shell's last bytes would print after the
206
206
  // notice that the shell is gone.
207
207
  session.output.flush();
208
208
  const frame = JSON.stringify({ t: 'exit', exitCode: session.exitCode, signal: session.signal });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * New API gateways report a dollar amount only through their OpenAI-compatible
8
+ * billing endpoints, in cents, with a sentinel instead of "unlimited". Each
9
+ * payload below is the verbatim shape aihub.brisnets.com returned for the
10
+ * stored `sk-` key (New API v1.0.0-rc.26-aihub.3.12).
11
+ */
12
+
13
+ import { describe, expect, test } from 'bun:test';
14
+
15
+ import { isNewApiGatewayBaseUrl, newApiBillingUrl, parseNewApiBilling } from '@/server/lib/usage/new-api';
16
+
17
+ describe('isNewApiGatewayBaseUrl', () => {
18
+ test('matches the gateway hosts at any path or subdomain', () => {
19
+ expect(isNewApiGatewayBaseUrl('https://aihub.brisnets.com/v1')).toBe(true);
20
+ expect(isNewApiGatewayBaseUrl('https://aihub.brisnets.com/v1/')).toBe(true);
21
+ expect(isNewApiGatewayBaseUrl('https://api.aihub.brisnets.com/v1')).toBe(true);
22
+ expect(isNewApiGatewayBaseUrl('https://easyaihub.ai/v1')).toBe(true);
23
+ });
24
+
25
+ test('a vendor host, a look-alike host and a malformed URL are not gateways', () => {
26
+ expect(isNewApiGatewayBaseUrl('https://api.deepseek.com/v1')).toBe(false);
27
+ expect(isNewApiGatewayBaseUrl('https://notbrisnets.com/v1')).toBe(false);
28
+ expect(isNewApiGatewayBaseUrl('aihub.brisnets.com')).toBe(false);
29
+ expect(isNewApiGatewayBaseUrl('')).toBe(false);
30
+ });
31
+ });
32
+
33
+ describe('newApiBillingUrl', () => {
34
+ test('billing endpoints hang off the provider base URL', () => {
35
+ expect(newApiBillingUrl('https://aihub.brisnets.com/v1', 'usage'))
36
+ .toBe('https://aihub.brisnets.com/v1/dashboard/billing/usage');
37
+ expect(newApiBillingUrl('https://aihub.brisnets.com/v1/', 'subscription'))
38
+ .toBe('https://aihub.brisnets.com/v1/dashboard/billing/subscription');
39
+ expect(newApiBillingUrl('https://aihub.brisnets.com', 'usage'))
40
+ .toBe('https://aihub.brisnets.com/v1/dashboard/billing/usage');
41
+ });
42
+ });
43
+
44
+ describe('parseNewApiBilling', () => {
45
+ test('an unlimited token reports spend only, never the sentinel as a limit', () => {
46
+ const windows = parseNewApiBilling(
47
+ 'aihub-brisnets-jatis',
48
+ { object: 'list', total_usage: 1365.635 },
49
+ { object: 'billing_subscription', hard_limit_usd: 100_000_000, access_until: 0 },
50
+ );
51
+
52
+ expect(windows).toHaveLength(1);
53
+ expect(windows[0].id).toBe('aihub-brisnets-jatis:spent');
54
+ expect(windows[0].unit).toBe('usd');
55
+ expect(windows[0].used).toBeCloseTo(13.65635, 6);
56
+ expect(windows[0].limit).toBeUndefined();
57
+ expect(windows[0].usedFraction).toBeUndefined();
58
+ expect(windows[0].notes?.join(' ')).toContain('gateway console');
59
+ });
60
+
61
+ test('a limited token derives the remaining credit from remain+used', () => {
62
+ const [window] = parseNewApiBilling(
63
+ 'relay',
64
+ { object: 'list', total_usage: 500 },
65
+ { hard_limit_usd: 20 },
66
+ );
67
+
68
+ expect(window.id).toBe('relay:credit');
69
+ expect(window.used).toBe(5);
70
+ expect(window.limit).toBe(20);
71
+ expect(window.remaining).toBe(15);
72
+ expect(window.usedFraction).toBeCloseTo(0.25, 6);
73
+ expect(window.status).toBe('ok');
74
+ });
75
+
76
+ test('an exhausted token clamps the remaining credit at zero', () => {
77
+ const [window] = parseNewApiBilling('relay', { total_usage: 2500 }, { hard_limit_usd: 20 });
78
+
79
+ expect(window.remaining).toBe(0);
80
+ expect(window.status).toBe('exhausted');
81
+ });
82
+
83
+ test('a missing subscription still reports the spend', () => {
84
+ const windows = parseNewApiBilling('relay', { total_usage: 100 }, undefined);
85
+ expect(windows[0].used).toBe(1);
86
+ expect(windows[0].limit).toBeUndefined();
87
+ });
88
+
89
+ test('a body without total_usage is a schema change, not an empty balance', () => {
90
+ expect(() => parseNewApiBilling('relay', { object: 'list' })).toThrow('unexpected billing response');
91
+ });
92
+ });
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * New API gateways (github.com/Calcium-Ion/new-api, a one-api fork).
8
+ *
9
+ * A gateway is not a vendor with one fixed endpoint: every deployment lives at
10
+ * its own base URL, and the provider is registered under the user's own slug
11
+ * (`aihub-brisnets-jatis`), so the URL has to come from the provider entry.
12
+ * The host is the only thing that identifies the family.
13
+ *
14
+ * Verified against aihub.brisnets.com (New API `v1.0.0-rc.26-aihub.3.12`,
15
+ * `quota_display_type` USD, `quota_per_unit` 500000) with the stored `sk-` key:
16
+ *
17
+ * GET <base>/dashboard/billing/usage → {"object":"list","total_usage":1365.635}
18
+ * GET <base>/dashboard/billing/subscription → {"hard_limit_usd":100000000,…}
19
+ * GET /api/user/self → 401 "invalid access token"
20
+ *
21
+ * `total_usage` is USD **cents** (`amount * 100` in controller/billing.go), and
22
+ * `hard_limit_usd` is `remaining + used`. The literal 100000000 is the sentinel
23
+ * New API writes for a token with `unlimited_quota`, not a real balance. Real
24
+ * account balance needs a console **access token** on `/api/user/self`; an
25
+ * `sk-` key cannot read it, so an unlimited key shows spend only.
26
+ */
27
+
28
+ import { resolveProviderEndpoint, type ProviderEndpoint } from '@/server/lib/usage/provider-key';
29
+ import { fetchProviderJson } from '@/server/lib/usage/vendor-http';
30
+ import type { VendorBalance } from '@/server/lib/usage/vendor-balance.server';
31
+ import { num, usdWindow } from '@/server/lib/usage/window';
32
+ import { isRecord } from '@/shared/lib/util/guards';
33
+ import type { UsageLimitWindow } from '@/shared/types';
34
+
35
+ /**
36
+ * Hosts that serve New API. `easyaihub.ai` is the same operator's China domain
37
+ * (`/api/status` advertises it next to `aihub.brisnets.com`).
38
+ */
39
+ const GATEWAY_HOSTS: readonly string[] = ['aihub.brisnets.com', 'easyaihub.ai'];
40
+
41
+ /** New API's "no limit on this token" marker, not a dollar amount. */
42
+ const UNLIMITED_SENTINEL = 100_000_000;
43
+
44
+ /** Whether a provider's base URL is a New API gateway. */
45
+ export function isNewApiGatewayBaseUrl(baseUrl: string): boolean {
46
+ let host: string;
47
+ try {
48
+ host = new URL(baseUrl).hostname.toLowerCase();
49
+ } catch {
50
+ return false; // a malformed URL is not a gateway
51
+ }
52
+ return GATEWAY_HOSTS.some((known) => host === known || host.endsWith(`.${known}`));
53
+ }
54
+
55
+ /** A billing endpoint under the provider's base URL (`…/v1` is implied). */
56
+ export function newApiBillingUrl(baseUrl: string, path: 'usage' | 'subscription'): string {
57
+ const trimmed = baseUrl.trim().replace(/\/+$/, '');
58
+ const base = /\/v1$/i.test(trimmed) ? trimmed : `${trimmed}/v1`;
59
+ return `${base}/dashboard/billing/${path}`;
60
+ }
61
+
62
+ /**
63
+ * Map the two billing payloads into quota windows. `usage` is required — a body
64
+ * without `total_usage` is a schema change, not an empty balance — while the
65
+ * subscription is best-effort because the spend alone is still useful.
66
+ */
67
+ export function parseNewApiBilling(
68
+ slug: string,
69
+ usage: unknown,
70
+ subscription?: unknown,
71
+ ): UsageLimitWindow[] {
72
+ const spentCents = isRecord(usage) ? num(usage.total_usage) : undefined;
73
+ if (spentCents === undefined) throw new Error('unexpected billing response');
74
+ const used = spentCents / 100;
75
+ const limit = isRecord(subscription) ? num(subscription.hard_limit_usd) : undefined;
76
+
77
+ if (limit === undefined || limit >= UNLIMITED_SENTINEL) {
78
+ return [
79
+ usdWindow({
80
+ id: `${slug}:spent`,
81
+ label: 'Spent (all time)',
82
+ used,
83
+ note: 'This key has no spending limit; the remaining balance is in the gateway console.',
84
+ }),
85
+ ];
86
+ }
87
+
88
+ return [
89
+ usdWindow({
90
+ id: `${slug}:credit`,
91
+ label: 'Key credit',
92
+ used,
93
+ limit,
94
+ remaining: Math.max(0, limit - used),
95
+ }),
96
+ ];
97
+ }
98
+
99
+ async function fetchGatewayBilling(slug: string, endpoint: ProviderEndpoint): Promise<VendorBalance> {
100
+ try {
101
+ const [usage, subscription] = await Promise.all([
102
+ fetchProviderJson(newApiBillingUrl(endpoint.baseUrl, 'usage'), endpoint.apiKey, slug),
103
+ // A failed subscription leaves the spend intact; only the limit is lost.
104
+ fetchProviderJson(newApiBillingUrl(endpoint.baseUrl, 'subscription'), endpoint.apiKey, slug)
105
+ .catch(() => undefined),
106
+ ]);
107
+ return { limits: parseNewApiBilling(slug, usage, subscription) };
108
+ } catch (error) {
109
+ return {
110
+ limits: [],
111
+ error: error instanceof Error ? error.message : `${slug} usage request failed`,
112
+ };
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Billing reports for every credentialed slug whose stored endpoint is a New
118
+ * API gateway. Providers with another endpoint are silently skipped, and one
119
+ * provider's failure never rejects the batch.
120
+ */
121
+ export async function buildNewApiReports(slugs: Iterable<string>): Promise<Map<string, VendorBalance>> {
122
+ const reports = new Map<string, VendorBalance>();
123
+ const targets = await Promise.all(
124
+ [...slugs].map(async (slug) => [slug, await resolveProviderEndpoint(slug)] as const),
125
+ );
126
+ await Promise.all(targets.map(async ([slug, endpoint]) => {
127
+ if (!endpoint || !isNewApiGatewayBaseUrl(endpoint.baseUrl)) return;
128
+ reports.set(slug, await fetchGatewayBilling(slug, endpoint));
129
+ }));
130
+ return reports;
131
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * `resolveProviderEndpoint` is the half `resolveApiKey` cannot answer: a relay
8
+ * serves its usage API at the base URL the user registered, so the endpoint has
9
+ * to be read from the same store as the key. These tests pin which store wins
10
+ * and what counts as a usable pair.
11
+ */
12
+
13
+ import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
14
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
15
+ import { tmpdir } from 'node:os';
16
+ import { join } from 'node:path';
17
+
18
+ import { getDb } from '@/server/db.server';
19
+ import { resolveProviderEndpoint } from '@/server/lib/usage/provider-key';
20
+ import { removeDir } from '@/test-support/remove-dir';
21
+
22
+ const dirs: string[] = [];
23
+ let agentDir = '';
24
+ let realAgentDir: string | undefined;
25
+
26
+ function tempDir(): string {
27
+ const dir = mkdtempSync(join(tmpdir(), 'kabmo-endpoint-'));
28
+ dirs.push(dir);
29
+ return dir;
30
+ }
31
+
32
+ beforeAll(() => {
33
+ agentDir = tempDir();
34
+ realAgentDir = Bun.env.PI_CODING_AGENT_DIR;
35
+ Bun.env.PI_CODING_AGENT_DIR = agentDir;
36
+ writeFileSync(join(agentDir, 'models.yml'), 'providers: {}\n');
37
+ });
38
+
39
+ afterAll(() => {
40
+ if (realAgentDir === undefined) delete Bun.env.PI_CODING_AGENT_DIR;
41
+ else Bun.env.PI_CODING_AGENT_DIR = realAgentDir;
42
+ for (const dir of dirs.splice(0)) removeDir(dir);
43
+ });
44
+
45
+ afterEach(() => {
46
+ globalThis.__kabmoDb?.resolved?.raw.close();
47
+ globalThis.__kabmoDb = undefined;
48
+ delete Bun.env.KABMO_DB_PATH;
49
+ writeFileSync(join(agentDir, 'models.yml'), 'providers: {}\n');
50
+ rmSync(join(agentDir, 'agent.db'), { force: true });
51
+ });
52
+
53
+ function useTempDb(): void {
54
+ Bun.env.KABMO_DB_PATH = join(tempDir(), 'db.sqlite');
55
+ Bun.env.SYNC_WORKSPACE = 'false';
56
+ delete Bun.env.MOCK;
57
+ globalThis.__kabmoDb = undefined;
58
+ }
59
+
60
+ async function writeOverlayValue(value: string): Promise<void> {
61
+ const db = await getDb();
62
+ await db.run('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)', ['omp_providers_config', value]);
63
+ }
64
+
65
+ describe('resolveProviderEndpoint', () => {
66
+ test('reads the key and endpoint from the provider own models.yml entry', async () => {
67
+ useTempDb();
68
+ writeFileSync(
69
+ join(agentDir, 'models.yml'),
70
+ 'providers:\n aihub-brisnets-jatis:\n baseUrl: https://aihub.brisnets.com/v1\n apiKey: sk-live\n',
71
+ );
72
+
73
+ expect(await resolveProviderEndpoint('aihub-brisnets-jatis')).toEqual({
74
+ apiKey: 'sk-live',
75
+ baseUrl: 'https://aihub.brisnets.com/v1',
76
+ });
77
+ });
78
+
79
+ test('the Kabmo overlay wins when it holds both a key and an endpoint', async () => {
80
+ useTempDb();
81
+ await writeOverlayValue(JSON.stringify([
82
+ { name: 'AI HUB', slug: 'aihub', baseUrl: 'https://aihub.brisnets.com/v1', apiKey: 'overlay-key' },
83
+ ]));
84
+ writeFileSync(
85
+ join(agentDir, 'models.yml'),
86
+ 'providers:\n aihub:\n baseUrl: https://aihub.brisnets.com/v1\n apiKey: yml-key\n',
87
+ );
88
+
89
+ expect(await resolveProviderEndpoint('aihub')).toEqual({
90
+ apiKey: 'overlay-key',
91
+ baseUrl: 'https://aihub.brisnets.com/v1',
92
+ });
93
+ });
94
+
95
+ test('a masked overlay key is not a credential', async () => {
96
+ useTempDb();
97
+ await writeOverlayValue(JSON.stringify([
98
+ { name: 'AI HUB', slug: 'aihub', baseUrl: 'https://aihub.brisnets.com/v1', apiKey: '••••••••' },
99
+ ]));
100
+ writeFileSync(join(agentDir, 'models.yml'), 'providers:\n aihub:\n apiKey: yml-key\n');
101
+
102
+ // The overlay row cannot supply a key, and models.yml carries no baseUrl,
103
+ // so there is no endpoint to resolve — not a half-valid pair.
104
+ expect(await resolveProviderEndpoint('aihub')).toBeNull();
105
+ });
106
+ });
@@ -117,6 +117,39 @@ export function resolveDeepSeekApiKey(): Promise<string | null> {
117
117
  );
118
118
  }
119
119
 
120
+ /** A provider's key AND the endpoint it was registered with. */
121
+ export interface ProviderEndpoint {
122
+ apiKey: string;
123
+ baseUrl: string;
124
+ }
125
+
126
+ /**
127
+ * The provider's key plus its own base URL. `resolveApiKey` alone cannot locate
128
+ * a gateway's billing API: a self-hosted relay (New API, one-api) lives at the
129
+ * URL the user configured, so the endpoint has to come from the provider entry
130
+ * rather than from a vendor constant. agent.db credentials carry no URL, so a
131
+ * provider whose only store is agent.db resolves to null.
132
+ */
133
+ export async function resolveProviderEndpoint(slug: string): Promise<ProviderEndpoint | null> {
134
+ const target = slug.trim().toLowerCase();
135
+ for (const entry of await loadProviderEntries()) {
136
+ const own = (entry.slug || entry.name).trim().toLowerCase();
137
+ if (own !== target) continue;
138
+ const apiKey = entry.apiKey.trim();
139
+ const baseUrl = entry.baseUrl.trim();
140
+ if (apiKey.length === 0 || MASKED_KEY_PATTERN.test(apiKey) || baseUrl.length === 0) continue;
141
+ return { apiKey, baseUrl };
142
+ }
143
+ for (const info of await readNativeProviders()) {
144
+ if (info.slug.trim().toLowerCase() !== target) continue;
145
+ const baseUrl = info.baseUrl?.trim();
146
+ if (!baseUrl) continue;
147
+ const apiKey = await readOmpProviderApiKey(target);
148
+ if (apiKey) return { apiKey, baseUrl };
149
+ }
150
+ return null;
151
+ }
152
+
120
153
  /** A provider slug with at least one usable credential, and where it came from. */
121
154
  export interface CredentialedProvider {
122
155
  slug: string;