@kabmo-labs/kabmo 0.23.0 → 0.25.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.
- package/dist/client/index.html +1 -1
- package/dist/client/index.js +805 -736
- package/dist/client/static/js/index-bc9aa4mx.css +1 -0
- package/dist/client/static/js/{index-ph0q59rs.js → index-ga8cbpt4.js} +1071 -1171
- package/package.json +2 -4
- package/src/cli/lib/args.js +24 -1
- package/src/cli/lib/args.test.js +16 -0
- package/src/cli/lib/commands/session.js +233 -0
- package/src/cli/lib/commands/session.test.js +103 -0
- package/src/cli/main.js +1 -1
- package/src/client/components/common/ComposerPicker.tsx +3 -0
- package/src/client/components/common/Modal.tsx +2 -6
- package/src/client/components/common/code-surface/shiki.test.ts +82 -0
- package/src/client/components/common/code-surface/shiki.ts +28 -7
- package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
- package/src/client/components/common/session-actions-menu/index.tsx +33 -2
- package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
- package/src/client/components/common/session-row/index.tsx +27 -1
- package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +7 -1
- package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
- package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
- package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
- package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
- package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.test.tsx +20 -0
- package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +59 -12
- package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
- package/src/client/components/layout/session-sidebar/about-modal/index.test.tsx +122 -0
- package/src/client/components/layout/session-sidebar/about-modal/index.tsx +55 -46
- package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
- package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
- package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
- package/src/client/components/settings/categories/harness-settings/EnvProviderForm.tsx +31 -0
- package/src/client/components/settings/categories/harness-settings/provider-panel.test.tsx +49 -0
- package/src/client/components/workspace/chat-timeline/ChatOverlays.tsx +5 -2
- package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
- package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
- package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
- package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
- package/src/client/components/workspace/chat-timeline/MessageList.test.ts +14 -0
- package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
- package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
- package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +4 -3
- package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
- package/src/client/components/workspace/chat-timeline/index.tsx +5 -2
- package/src/client/components/workspace/chat-timeline/pending-harness.test.tsx +1 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FrameControl.tsx +11 -20
- package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/GroupedAsk.tsx +1 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/QuestionBlock.tsx +1 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/drafts.ts +1 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/index.tsx +2 -1
- package/src/client/components/workspace/file-explorer/index.test.ts +25 -0
- package/src/client/components/workspace/file-explorer/index.tsx +9 -3
- package/src/client/components/workspace/model-dropdown/harness-models.test.ts +17 -0
- package/src/client/components/workspace/model-dropdown/harness-models.ts +33 -18
- package/src/client/components/workspace/model-dropdown/index.tsx +3 -3
- package/src/client/components/workspace/model-dropdown/popover-metrics.ts +4 -1
- package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
- package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
- package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
- package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
- package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
- package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
- package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
- package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
- package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
- package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
- package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
- package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
- package/src/client/data/settings/omp-schema.json +5 -5
- package/src/client/data/theme/terminal.test.ts +25 -0
- package/src/client/data/theme/terminal.ts +96 -79
- package/src/client/hooks/chat/composer/items.test.ts +12 -26
- package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
- package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
- package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
- package/src/client/hooks/chat/timeline/actions.ts +2 -2
- package/src/client/hooks/chat/timeline/ask-frames.ts +5 -4
- package/src/client/hooks/chat/timeline/new-chat-open.test.ts +86 -0
- package/src/client/hooks/chat/timeline/new-chat-open.ts +23 -5
- package/src/client/hooks/chat/timeline/new-chat.test.ts +32 -4
- package/src/client/hooks/chat/timeline/new-chat.ts +18 -6
- package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
- package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
- package/src/client/hooks/chat/timeline/rewind-actions.test.ts +24 -1
- package/src/client/hooks/chat/timeline/rewind-actions.ts +15 -11
- package/src/client/hooks/chat/timeline/run-identity.test.ts +52 -0
- package/src/client/hooks/chat/timeline/run-identity.ts +23 -11
- package/src/client/hooks/chat/timeline/send-execute.test.ts +56 -0
- package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
- package/src/client/hooks/chat/timeline/send-props.ts +5 -3
- package/src/client/hooks/chat/timeline/send-steer.test.ts +4 -4
- package/src/client/hooks/chat/timeline/send.test-util.ts +8 -2
- package/src/client/hooks/chat/timeline/send.test.ts +4 -4
- package/src/client/hooks/chat/timeline/send.ts +59 -53
- package/src/client/hooks/chat/timeline/session-load.test-util.ts +6 -2
- package/src/client/hooks/chat/timeline/session-load.test.ts +31 -0
- package/src/client/hooks/chat/timeline/session-load.ts +6 -14
- package/src/client/hooks/chat/timeline/session-shapes.ts +32 -0
- package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
- package/src/client/hooks/models/harness-catalog.ts +114 -0
- package/src/client/hooks/models/provider-writes.test.ts +81 -0
- package/src/client/hooks/models/provider-writes.ts +10 -3
- package/src/client/hooks/models/use-harness-update.test.ts +193 -0
- package/src/client/hooks/models/use-harness-update.ts +202 -0
- package/src/client/hooks/models/use-harnesses-controller.ts +57 -0
- package/src/client/hooks/models/use-harnesses-signal.test.ts +128 -0
- package/src/client/hooks/models/use-harnesses.test.ts +2 -1
- package/src/client/hooks/models/use-harnesses.ts +48 -114
- package/src/client/hooks/workspace/child-expansion.ts +33 -0
- package/src/client/hooks/workspace/terminal/index.ts +17 -3
- package/src/client/hooks/workspace/terminal/socket.ts +9 -4
- package/src/client/lib/session-tree.test.ts +50 -0
- package/src/client/lib/session-tree.ts +59 -0
- package/src/client/tailwind.css +26 -12
- package/src/server/index.ts +2 -0
- package/src/server/lib/auth/guard.ts +10 -0
- package/src/server/lib/btw/session-copy.server.ts +6 -44
- package/src/server/lib/btw/session-copy.test.ts +2 -1
- package/src/server/lib/db/schema.ts +4 -0
- package/src/server/lib/db/seed-terminal.test.ts +1 -1
- package/src/server/lib/db/seed.test.ts +1 -1
- package/src/server/lib/harness/acp/activation.test.ts +81 -0
- package/src/server/lib/harness/acp/activation.ts +72 -0
- package/src/server/lib/harness/acp/background-work.test.ts +262 -0
- package/src/server/lib/harness/acp/background-work.ts +320 -0
- package/src/server/lib/harness/acp/client.ts +2 -2
- package/src/server/lib/harness/acp/frames.test.ts +50 -1
- package/src/server/lib/harness/acp/frames.ts +17 -5
- package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
- package/src/server/lib/harness/acp/gateway-env.ts +70 -0
- package/src/server/lib/harness/acp/mapper.ts +6 -4
- package/src/server/lib/harness/acp/prompt.test.ts +20 -0
- package/src/server/lib/harness/acp/prompt.ts +19 -3
- package/src/server/lib/harness/acp/session-background.test.ts +129 -0
- package/src/server/lib/harness/acp/session-config.test.ts +73 -0
- package/src/server/lib/harness/acp/session-config.ts +87 -6
- package/src/server/lib/harness/acp/session-exit.ts +31 -0
- package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
- package/src/server/lib/harness/acp/session-handshake.ts +36 -3
- package/src/server/lib/harness/acp/session-idle.ts +51 -0
- package/src/server/lib/harness/acp/session-listeners.ts +31 -0
- package/src/server/lib/harness/acp/session-notifications.ts +19 -3
- package/src/server/lib/harness/acp/session-observers.test.ts +9 -0
- package/src/server/lib/harness/acp/session-options.ts +33 -0
- package/src/server/lib/harness/acp/session-reaper.test.ts +96 -0
- package/src/server/lib/harness/acp/session-requests.ts +47 -0
- package/src/server/lib/harness/acp/session-turns.ts +20 -5
- package/src/server/lib/harness/acp/session.test-util.ts +54 -3
- package/src/server/lib/harness/acp/session.test.ts +65 -3
- package/src/server/lib/harness/acp/session.ts +79 -79
- package/src/server/lib/harness/acp/turn.test.ts +81 -0
- package/src/server/lib/harness/acp/turn.ts +54 -13
- package/src/server/lib/harness/acp/verbs.ts +12 -2
- package/src/server/lib/harness/auto-probe.server.test.ts +121 -0
- package/src/server/lib/harness/auto-probe.server.ts +178 -0
- package/src/server/lib/harness/config.server.test.ts +1 -1
- package/src/server/lib/harness/config.server.ts +1 -1
- package/src/server/lib/harness/launch-table.ts +195 -0
- package/src/server/lib/harness/launch.test.ts +37 -0
- package/src/server/lib/harness/launch.ts +16 -116
- package/src/server/lib/harness/provider-entry.ts +32 -0
- package/src/server/lib/harness/provider-file.server.ts +3 -0
- package/src/server/lib/harness/provider-sources.server.test.ts +45 -0
- package/src/server/lib/harness/provider-sources.server.ts +26 -2
- package/src/server/lib/harness/provider-write.server.ts +21 -32
- package/src/server/lib/harness/provider-zcode.server.test.ts +270 -0
- package/src/server/lib/harness/provider-zcode.server.ts +324 -0
- package/src/server/lib/harness/spawn.server.ts +15 -2
- package/src/server/lib/harness/update-job-store.test.ts +126 -0
- package/src/server/lib/harness/update-job-store.ts +109 -0
- package/src/server/lib/harness/update-job.server.ts +203 -0
- package/src/server/lib/harness/update-state.server.ts +15 -20
- package/src/server/lib/harness/update-worker.test.ts +153 -0
- package/src/server/lib/harness/update-worker.ts +197 -0
- package/src/server/lib/lifecycle/after-listen.ts +7 -0
- package/src/server/lib/lifecycle/paths.ts +23 -0
- package/src/server/lib/models/registry-refresh.server.test.ts +87 -0
- package/src/server/lib/models/registry-refresh.server.ts +98 -0
- package/src/server/lib/omp/rpc/child-config.ts +5 -4
- package/src/server/lib/omp/rpc/constants.test.ts +2 -1
- package/src/server/lib/omp/rpc/forked-resume.test.ts +14 -3
- package/src/server/lib/omp/rpc/manager.ts +5 -5
- package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
- package/src/server/lib/omp/rpc/session-registry.ts +14 -2
- package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
- package/src/server/lib/omp/session/delete-flow.server.ts +62 -8
- package/src/server/lib/omp/session/delete.server.ts +17 -0
- package/src/server/lib/omp/session/rewind-file.ts +39 -21
- package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
- package/src/server/lib/omp/session/transcript-copy.ts +123 -0
- package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
- package/src/server/lib/sessions/agent-token.server.ts +134 -0
- package/src/server/lib/sessions/answers.server.test.ts +33 -0
- package/src/server/lib/sessions/answers.server.ts +37 -0
- package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
- package/src/server/lib/sessions/dispatch.server.ts +128 -0
- package/src/server/lib/sessions/fork.server.test.ts +209 -0
- package/src/server/lib/sessions/fork.server.ts +304 -0
- package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
- package/src/server/lib/sessions/lifecycle.server.ts +71 -0
- package/src/server/lib/sessions/notify.server.test.ts +112 -0
- package/src/server/lib/sessions/notify.server.ts +212 -0
- package/src/server/lib/sessions/relation-types.ts +76 -0
- package/src/server/lib/sessions/relations.server.test.ts +207 -0
- package/src/server/lib/sessions/relations.server.ts +337 -0
- package/src/server/lib/sessions/resolve.server.ts +106 -0
- package/src/server/lib/sessions/schema.server.ts +82 -0
- package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
- package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
- package/src/server/lib/sessions/spawn.server.test.ts +196 -0
- package/src/server/lib/sessions/spawn.server.ts +310 -0
- package/src/server/lib/terminal/attach-replay.test.ts +2 -2
- package/src/server/lib/terminal/output.test.ts +2 -2
- package/src/server/lib/terminal/output.ts +1 -1
- package/src/server/lib/terminal/resize.test.ts +99 -0
- package/src/server/lib/terminal/runtime.server.ts +26 -6
- package/src/server/lib/terminal/send-result.test.ts +18 -1
- package/src/server/lib/terminal/send-result.ts +26 -2
- package/src/server/lib/terminal/session.server.ts +6 -6
- package/src/server/lib/usage/new-api.test.ts +92 -0
- package/src/server/lib/usage/new-api.ts +131 -0
- package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
- package/src/server/lib/usage/provider-key.ts +33 -0
- package/src/server/lib/usage/providers.server.ts +10 -3
- package/src/server/lib/usage/vendor-balance.server.ts +4 -53
- package/src/server/lib/usage/vendor-http.ts +41 -0
- package/src/server/lib/usage/window.ts +55 -0
- package/src/server/routes/agent/command.ts +14 -1
- package/src/server/routes/agent/harness-command.ts +6 -0
- package/src/server/routes/agent/new.ts +15 -0
- package/src/server/routes/chat/rewind.test.ts +147 -0
- package/src/server/routes/chat/rewind.ts +29 -7
- package/src/server/routes/chat/session.test.ts +165 -10
- package/src/server/routes/chat/session.ts +60 -7
- package/src/server/routes/harness/add-provider.test.ts +9 -1
- package/src/server/routes/harness/import-action.ts +22 -4
- package/src/server/routes/harness/import.test.ts +1 -1
- package/src/server/routes/harness/index.ts +5 -1
- package/src/server/routes/harness/root.ts +8 -49
- package/src/server/routes/harness/toggle.test.ts +20 -0
- package/src/server/routes/harness/update-status.ts +26 -0
- package/src/server/routes/harness/update.test.ts +119 -0
- package/src/server/routes/harness/update.ts +67 -113
- package/src/server/routes/harness/versions.ts +5 -1
- package/src/server/routes/sessions/answer.ts +24 -0
- package/src/server/routes/sessions/batch-delete.ts +11 -5
- package/src/server/routes/sessions/delete-acp.test.ts +227 -0
- package/src/server/routes/sessions/delete.ts +4 -2
- package/src/server/routes/sessions/fork.ts +74 -0
- package/src/server/routes/sessions/index.ts +14 -0
- package/src/server/routes/sessions/relations.ts +85 -0
- package/src/server/routes/sessions/session.ts +4 -0
- package/src/server/routes/sessions/spawn.ts +134 -0
- package/src/server/routes/settings/model-override.ts +5 -2
- package/src/server/routes/settings/provider-entry.ts +2 -2
- package/src/server/routes/settings/provider-model.ts +2 -2
- package/src/server/routes/settings/provider-models.ts +2 -2
- package/src/server/routes/settings/provider-refresh.ts +6 -4
- package/src/server/routes/settings/providers.ts +3 -1
- package/src/server/routes/settings/settings-config-routes.test.ts +10 -2
- package/src/server/routes/terminal/ws.ts +3 -3
- package/src/shared/lib/chat/ask-form/fields.ts +76 -0
- package/src/shared/lib/chat/ask-form/index.ts +323 -0
- package/src/shared/lib/chat/ask-form/tokens.ts +199 -0
- package/src/shared/lib/chat/ask-form/types.ts +43 -0
- package/src/shared/lib/chat/ask-form.test.ts +137 -0
- package/src/shared/lib/chat/ask-questions.test.ts +65 -1
- package/src/shared/lib/chat/ask-questions.ts +51 -145
- package/src/shared/lib/chat/ask-results.ts +198 -0
- package/src/shared/lib/chat/composer/client.ts +31 -2
- package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
- package/src/shared/lib/chat/composer/delegation.ts +206 -0
- package/src/shared/lib/chat/notice-text.ts +1 -1
- package/src/shared/lib/chat/timeline/omp-callbacks.ts +13 -1
- package/src/shared/lib/chat/timeline/prompt-error.test.ts +146 -0
- package/src/shared/lib/chat/timeline/prompt-error.ts +88 -0
- package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
- package/src/shared/lib/code/ansi.ts +1 -1
- package/src/shared/lib/fonts/nerd-symbols.css +4 -3
- package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
- package/src/shared/lib/harness/catalog.test.ts +1 -1
- package/src/shared/lib/harness/config-fields.test.ts +4 -0
- package/src/shared/lib/harness/config-fields.ts +19 -4
- package/src/shared/lib/harness/dialects.test.ts +8 -0
- package/src/shared/lib/harness/dialects.ts +12 -0
- package/src/shared/lib/harness/provider-facts.test.ts +59 -8
- package/src/shared/lib/harness/provider-facts.ts +46 -11
- package/src/shared/lib/harness/providers.ts +44 -1
- package/src/shared/lib/harness/rewind.ts +24 -0
- package/src/shared/lib/harness/update-job.ts +33 -0
- package/src/shared/lib/harness/update-plan.test.ts +69 -4
- package/src/shared/lib/harness/update-plan.ts +57 -9
- package/src/shared/lib/harness/updates.test.ts +22 -0
- package/src/shared/lib/harness/updates.ts +24 -1
- package/src/shared/lib/models/client.ts +10 -1
- package/src/shared/lib/omp/dialog-methods.ts +4 -3
- package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
- package/src/shared/lib/omp/session/wait-idle.ts +12 -2
- package/src/shared/lib/theme/catalog.test.ts +13 -9
- package/src/shared/lib/theme/color.test.ts +2 -2
- package/src/shared/lib/theme/color.ts +4 -4
- package/src/shared/lib/theme/css.ts +2 -0
- package/src/shared/lib/theme/ink-scale.ts +21 -1
- package/src/shared/lib/theme/theme.test.ts +26 -10
- package/src/shared/lib/ui/safe-area.test.ts +28 -0
- package/src/shared/lib/ui/safe-area.ts +42 -0
- package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
- package/src/shared/lib/workspace/terminal/input.ts +33 -0
- package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
- package/src/shared/lib/workspace/terminal/keys.ts +7 -7
- package/src/shared/types/chat.ts +1 -1
- package/src/shared/types/harness-update.ts +65 -0
- package/src/shared/types/harness.ts +30 -4
- package/src/shared/types/omp/agent.ts +19 -2
- package/src/shared/types/workspace.ts +4 -0
- package/src/test-support/fake-omp-fork.ts +16 -2
- package/src/test-support/file-explorer-render.test-util.ts +37 -0
- package/src/test-support/file-explorer.test-util.ts +20 -18
- package/src/test-support/harness-table.test-util.ts +21 -4
- package/dist/client/static/js/index-jhmg4w91.css +0 -1
- package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
- package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* exactly once: the replay's last line followed immediately by live output.
|
|
9
9
|
*
|
|
10
10
|
* The two ways this breaks are both silent, and both are duplicate/garbled text
|
|
11
|
-
* in
|
|
12
|
-
* delivery, so a replay captured BEFORE the queue is flushed carries the pending
|
|
11
|
+
* in the terminal rather than an error. Output is appended to `history` and
|
|
12
|
+
* queued for delivery, so a replay captured BEFORE the queue is flushed carries the pending
|
|
13
13
|
* bytes and the queued frame carries them again (each line printed twice); a
|
|
14
14
|
* frame delivered before the replay arrives ahead of it in the wrong order.
|
|
15
15
|
* `attachTerminal` flushes first for exactly this reason, and this is the test
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* receives must equal the concatenation of the reads, in the same order, and the
|
|
10
10
|
* framing must be bounded.
|
|
11
11
|
*
|
|
12
|
-
* Two failures it must not have, both of which
|
|
13
|
-
* than as an error: dropping a trailing partial frame (a prompt that never
|
|
12
|
+
* Two failures it must not have, both of which the renderer draws as garbage
|
|
13
|
+
* rather than as an error: dropping a trailing partial frame (a prompt that never
|
|
14
14
|
* appears until the next keypress) and reordering (an escape sequence split
|
|
15
15
|
* across two reads, reassembled after a later one).
|
|
16
16
|
*
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* concatenated after exit are byte-identical), and `history.append` already
|
|
22
22
|
* retains those views for its 512 KiB scrollback, so a defensive copy per
|
|
23
23
|
* read would cost exactly what the coalescing is there to save.
|
|
24
|
-
* - **Split sequences.**
|
|
24
|
+
* - **Split sequences.** the parser reads a byte stream across `write` calls, so a
|
|
25
25
|
* frame boundary mid-escape is harmless — dropping bytes is not, which is why
|
|
26
26
|
* a flush never discards anything it accepted.
|
|
27
27
|
* - **Buffer without a bound.** The flush is size- or time-triggered, so a
|
|
@@ -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
|
|
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
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
*
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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;
|