@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
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* ZCode's personal providers: `~/.zcode/v2/provider_config.json` (3.12+).
|
|
8
|
+
*
|
|
9
|
+
* The shape is a RULE GRAPH, not the map every other registry uses:
|
|
10
|
+
*
|
|
11
|
+
* ```json
|
|
12
|
+
* { "schemaVersion": 1,
|
|
13
|
+
* "config": {
|
|
14
|
+
* "providerConfigRules": { "providerRules": [ { "providerId", "providerName", "config": {
|
|
15
|
+
* "access": { "type": "api-key", "apiKey" },
|
|
16
|
+
* "api": { "type": "openai-chat-completions", "baseUrl" } } } ] },
|
|
17
|
+
* "modelConfigRules": {
|
|
18
|
+
* "providerModelRules": [ { "providerId", "modelId", "config": { "enabled": true } } ],
|
|
19
|
+
* "manualProviderModelRules": [] } } }
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* Two measured reasons the file is written carefully:
|
|
23
|
+
*
|
|
24
|
+
* - **A provider alone serves nothing.** The bridge builds its dropdown from
|
|
25
|
+
* the MODEL rules (`loadPersonalModels` reads `modelConfigRules` only), so a
|
|
26
|
+
* provider rule without a model rule is invisible. The writer therefore emits
|
|
27
|
+
* one rule per model id, beside the provider.
|
|
28
|
+
* - **The top level is strict.** `schemaVersion` and `config` are the only keys
|
|
29
|
+
* the backend accepts; everything inside `config` is carried through
|
|
30
|
+
* untouched. This writer merges exactly what it owns and preserves the rest,
|
|
31
|
+
* including manual model rules and the user's own headers.
|
|
32
|
+
*
|
|
33
|
+
* `~/.zcode/v2/config.json` is deliberately NOT touched: it is the desktop app's
|
|
34
|
+
* legacy provider map and its credentials. Personal providers belong in the file
|
|
35
|
+
* this module owns.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { withConfigLock } from '@/server/lib/fs/config-lock';
|
|
39
|
+
import { writeFileAtomic } from '@/server/lib/fs/atomic-write';
|
|
40
|
+
import { asRecord, type ProviderDraft } from '@/server/lib/harness/provider-entry';
|
|
41
|
+
import { ProviderWriteError } from '@/server/lib/harness/provider-write-error';
|
|
42
|
+
import { protocolOfSourceDialect } from '@/shared/lib/harness/dialects';
|
|
43
|
+
import type { ImportableProvider } from '@/server/lib/harness/provider-sources.server';
|
|
44
|
+
import type { ProviderWriteResult } from '@/server/lib/harness/provider-write.server';
|
|
45
|
+
|
|
46
|
+
function stringList(value: unknown): string[] {
|
|
47
|
+
return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0) : [];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function ruleProviderId(rule: Record<string, unknown>): string {
|
|
51
|
+
return typeof rule.providerId === 'string' ? rule.providerId : '';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The provider rules and both model-rule arrays, created when absent. */
|
|
55
|
+
function ruleTables(doc: Record<string, unknown>): {
|
|
56
|
+
providers: unknown[];
|
|
57
|
+
smart: unknown[];
|
|
58
|
+
manual: unknown[];
|
|
59
|
+
} {
|
|
60
|
+
const config = asRecord(doc.config);
|
|
61
|
+
doc.config = config;
|
|
62
|
+
const providerConfigRules = asRecord(config.providerConfigRules);
|
|
63
|
+
config.providerConfigRules = providerConfigRules;
|
|
64
|
+
const modelConfigRules = asRecord(config.modelConfigRules);
|
|
65
|
+
config.modelConfigRules = modelConfigRules;
|
|
66
|
+
const providers = Array.isArray(providerConfigRules.providerRules) ? providerConfigRules.providerRules : [];
|
|
67
|
+
providerConfigRules.providerRules = providers;
|
|
68
|
+
const smart = Array.isArray(modelConfigRules.providerModelRules) ? modelConfigRules.providerModelRules : [];
|
|
69
|
+
modelConfigRules.providerModelRules = smart;
|
|
70
|
+
const manual = Array.isArray(modelConfigRules.manualProviderModelRules) ? modelConfigRules.manualProviderModelRules : [];
|
|
71
|
+
modelConfigRules.manualProviderModelRules = manual;
|
|
72
|
+
return { providers, smart, manual };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Model ids declared by BOTH rule arrays for one provider, in file order. */
|
|
76
|
+
function ruleModelIds(doc: Record<string, unknown>, providerId: string): string[] {
|
|
77
|
+
const { smart, manual } = ruleTables(doc);
|
|
78
|
+
const out: string[] = [];
|
|
79
|
+
for (const rule of [...smart, ...manual]) {
|
|
80
|
+
const entry = asRecord(rule);
|
|
81
|
+
if (ruleProviderId(entry) !== providerId) continue;
|
|
82
|
+
const modelId = typeof entry.modelId === 'string' ? entry.modelId : '';
|
|
83
|
+
if (!modelId || asRecord(entry.config).enabled === false) continue;
|
|
84
|
+
if (!out.includes(modelId)) out.push(modelId);
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Context windows a smart/manual model rule declares. */
|
|
90
|
+
function ruleContextWindows(doc: Record<string, unknown>): Record<string, number> {
|
|
91
|
+
const { smart, manual } = ruleTables(doc);
|
|
92
|
+
const out: Record<string, number> = {};
|
|
93
|
+
for (const rule of [...smart, ...manual]) {
|
|
94
|
+
const entry = asRecord(rule);
|
|
95
|
+
const providerId = ruleProviderId(entry);
|
|
96
|
+
const modelId = typeof entry.modelId === 'string' ? entry.modelId : '';
|
|
97
|
+
const size = asRecord(asRecord(entry.config).properties).contextWindow;
|
|
98
|
+
if (providerId && modelId && typeof size === 'number' && size > 0) out[`${providerId}/${modelId}`] = size;
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Every custom provider the file holds, credential-free.
|
|
105
|
+
*
|
|
106
|
+
* A malformed document yields nothing: this reader feeds a settings card, and
|
|
107
|
+
* refusing to draw the page over the agent's own broken file would hide the only
|
|
108
|
+
* place that can explain it.
|
|
109
|
+
*/
|
|
110
|
+
export function readZcodeProviders(text: string | null, source: ImportableProvider['source']): ImportableProvider[] {
|
|
111
|
+
if (!text) return [];
|
|
112
|
+
let doc: Record<string, unknown>;
|
|
113
|
+
try {
|
|
114
|
+
const parsed: unknown = JSON.parse(text);
|
|
115
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return [];
|
|
116
|
+
doc = parsed as Record<string, unknown>;
|
|
117
|
+
} catch {
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
const { providers } = ruleTables(doc);
|
|
121
|
+
const windows = ruleContextWindows(doc);
|
|
122
|
+
const out: ImportableProvider[] = [];
|
|
123
|
+
for (const raw of providers) {
|
|
124
|
+
const rule = asRecord(raw);
|
|
125
|
+
const id = ruleProviderId(rule);
|
|
126
|
+
if (!id || id.startsWith('builtin:') || id.startsWith('account:')) continue;
|
|
127
|
+
const config = asRecord(rule.config);
|
|
128
|
+
const access = asRecord(config.access);
|
|
129
|
+
const api = asRecord(config.api);
|
|
130
|
+
const dialect = typeof api.type === 'string' ? api.type : undefined;
|
|
131
|
+
const protocol = protocolOfSourceDialect(dialect);
|
|
132
|
+
const models = [...ruleModelIds(doc, id)];
|
|
133
|
+
for (const declared of stringList(config.personalModelIds)) {
|
|
134
|
+
if (!models.includes(declared)) models.push(declared);
|
|
135
|
+
}
|
|
136
|
+
const contextWindow = Object.fromEntries(
|
|
137
|
+
models.flatMap((modelId) => {
|
|
138
|
+
const size = windows[`${id}/${modelId}`];
|
|
139
|
+
return size ? [[modelId, size]] : [];
|
|
140
|
+
}),
|
|
141
|
+
);
|
|
142
|
+
out.push({
|
|
143
|
+
id,
|
|
144
|
+
name: typeof rule.providerName === 'string' && rule.providerName.trim() ? rule.providerName : id,
|
|
145
|
+
...(typeof api.baseUrl === 'string' && api.baseUrl ? { baseUrl: api.baseUrl } : {}),
|
|
146
|
+
...(dialect ? { dialect } : {}),
|
|
147
|
+
...(protocol ? { protocol } : {}),
|
|
148
|
+
models,
|
|
149
|
+
...(Object.keys(contextWindow).length > 0 ? { contextWindow } : {}),
|
|
150
|
+
source,
|
|
151
|
+
hasKey: typeof access.apiKey === 'string' && access.apiKey.length > 0,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** One provider's credential, read only by the request that writes a target. */
|
|
158
|
+
export function readZcodeProviderKey(text: string | null, providerId: string): string | null {
|
|
159
|
+
if (!text) return null;
|
|
160
|
+
try {
|
|
161
|
+
const parsed: unknown = JSON.parse(text);
|
|
162
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
163
|
+
const { providers } = ruleTables(parsed as Record<string, unknown>);
|
|
164
|
+
const rule = providers.map(asRecord).find((entry) => ruleProviderId(entry) === providerId);
|
|
165
|
+
const key = asRecord(asRecord(rule?.config).access).apiKey;
|
|
166
|
+
return typeof key === 'string' && key.length > 0 ? key : null;
|
|
167
|
+
} catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** An empty document in the file's canonical shape. */
|
|
173
|
+
function emptyDocument(): Record<string, unknown> {
|
|
174
|
+
const doc: Record<string, unknown> = { schemaVersion: 1 };
|
|
175
|
+
ruleTables(doc);
|
|
176
|
+
return doc;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function union(first: string[], second: string[]): string[] {
|
|
180
|
+
const out = [...first];
|
|
181
|
+
for (const entry of second) if (entry && !out.includes(entry)) out.push(entry);
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Merge ONE provider (and its model rules) into the personal provider file.
|
|
187
|
+
*
|
|
188
|
+
* Fields this writer does not own survive: headers, `apiKeyManagementUrl`,
|
|
189
|
+
* `logo`, `templateId`, a manual model rule's capability block, `providerOrder`
|
|
190
|
+
* and `defaultModelSelection`. A stored credential is kept when the draft brings
|
|
191
|
+
* none, the same rule every other writer follows.
|
|
192
|
+
*/
|
|
193
|
+
export async function writeZcodeProvider(input: {
|
|
194
|
+
path: string;
|
|
195
|
+
id: string;
|
|
196
|
+
draft: ProviderDraft;
|
|
197
|
+
dialect: string;
|
|
198
|
+
}): Promise<ProviderWriteResult> {
|
|
199
|
+
const { path, id, draft, dialect } = input;
|
|
200
|
+
// The runtime's own writer locks a DIRECTORY at `${path}.lock` (its
|
|
201
|
+
// `file-lock.ts`), so a file at that exact path would look like a lock it
|
|
202
|
+
// must reclaim. Kabmo serialises its own writers on a distinct lease and the
|
|
203
|
+
// final rename stays atomic; the app's poll picks the write up.
|
|
204
|
+
return withConfigLock(`${path}.kabmo`, async () => {
|
|
205
|
+
const file = Bun.file(path);
|
|
206
|
+
const raw = (await file.exists()) ? await file.text() : '';
|
|
207
|
+
let doc: Record<string, unknown>;
|
|
208
|
+
if (raw.trim()) {
|
|
209
|
+
try {
|
|
210
|
+
const parsed: unknown = JSON.parse(raw);
|
|
211
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not a document');
|
|
212
|
+
doc = parsed as Record<string, unknown>;
|
|
213
|
+
} catch (cause) {
|
|
214
|
+
throw new ProviderWriteError(`${path} could not be parsed, so it was left untouched: ${String(cause)}`);
|
|
215
|
+
}
|
|
216
|
+
} else {
|
|
217
|
+
doc = emptyDocument();
|
|
218
|
+
}
|
|
219
|
+
if (typeof doc.schemaVersion !== 'number') doc.schemaVersion = 1;
|
|
220
|
+
|
|
221
|
+
const { providers, smart, manual } = ruleTables(doc);
|
|
222
|
+
const index = providers.findIndex((rule) => ruleProviderId(asRecord(rule)) === id);
|
|
223
|
+
const existing = index >= 0 ? asRecord(providers[index]) : {};
|
|
224
|
+
const existingConfig = asRecord(existing.config);
|
|
225
|
+
const existingAccess = asRecord(existingConfig.access);
|
|
226
|
+
const existingApi = asRecord(existingConfig.api);
|
|
227
|
+
const baseUrl = draft.baseUrl?.trim() || (typeof existingApi.baseUrl === 'string' ? existingApi.baseUrl : '');
|
|
228
|
+
if (!baseUrl) {
|
|
229
|
+
throw new ProviderWriteError(
|
|
230
|
+
`ZCode needs a base URL for "${id}": a standalone personal provider has no inherited endpoint.`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
const apiKey = draft.apiKey?.trim();
|
|
234
|
+
const models = union(stringList(existingConfig.personalModelIds), draft.models);
|
|
235
|
+
const rule = {
|
|
236
|
+
...existing,
|
|
237
|
+
providerId: id,
|
|
238
|
+
providerName: draft.name || (typeof existing.providerName === 'string' ? existing.providerName : id),
|
|
239
|
+
enabled: true,
|
|
240
|
+
config: {
|
|
241
|
+
...existingConfig,
|
|
242
|
+
group: typeof existingConfig.group === 'string' ? existingConfig.group : 'standard-personal',
|
|
243
|
+
visibility: 'visible',
|
|
244
|
+
access: {
|
|
245
|
+
...existingAccess,
|
|
246
|
+
type: apiKey ? 'api-key' : (typeof existingAccess.type === 'string' ? existingAccess.type : 'api-key'),
|
|
247
|
+
...(apiKey ? { apiKey } : {}),
|
|
248
|
+
},
|
|
249
|
+
api: { ...existingApi, type: dialect, baseUrl },
|
|
250
|
+
personalModelIds: models,
|
|
251
|
+
modelOrder: union(stringList(existingConfig.modelOrder), models),
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
if (index >= 0) providers[index] = rule;
|
|
255
|
+
else providers.push(rule);
|
|
256
|
+
|
|
257
|
+
// One model rule per id: a provider rule with no model rule is invisible to
|
|
258
|
+
// the dropdown (see the module header). Existing rules are updated in place,
|
|
259
|
+
// and a MANUAL rule stays manual — moving it would drop the capability block
|
|
260
|
+
// the user configured by hand.
|
|
261
|
+
let addedRules = 0;
|
|
262
|
+
for (const modelId of models) {
|
|
263
|
+
const contextWindow = draft.contextWindow?.[modelId];
|
|
264
|
+
const manualIndex = manual.findIndex((entry) => {
|
|
265
|
+
const row = asRecord(entry);
|
|
266
|
+
return ruleProviderId(row) === id && row.modelId === modelId;
|
|
267
|
+
});
|
|
268
|
+
const smartIndex = smart.findIndex((entry) => {
|
|
269
|
+
const row = asRecord(entry);
|
|
270
|
+
return ruleProviderId(row) === id && row.modelId === modelId;
|
|
271
|
+
});
|
|
272
|
+
const target = manualIndex >= 0 ? manual : smartIndex >= 0 ? smart : null;
|
|
273
|
+
const at = manualIndex >= 0 ? manualIndex : smartIndex;
|
|
274
|
+
if (target) {
|
|
275
|
+
const row = asRecord(target[at]);
|
|
276
|
+
const config = asRecord(row.config);
|
|
277
|
+
const properties = asRecord(config.properties);
|
|
278
|
+
target[at] = {
|
|
279
|
+
...row,
|
|
280
|
+
config: {
|
|
281
|
+
...config,
|
|
282
|
+
enabled: true,
|
|
283
|
+
...(contextWindow && typeof properties.contextWindow !== 'number'
|
|
284
|
+
? { properties: { ...properties, contextWindow } }
|
|
285
|
+
: {}),
|
|
286
|
+
},
|
|
287
|
+
};
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
smart.push({
|
|
291
|
+
providerId: id,
|
|
292
|
+
modelId,
|
|
293
|
+
config: {
|
|
294
|
+
enabled: true,
|
|
295
|
+
...(contextWindow ? { properties: { contextWindow } } : {}),
|
|
296
|
+
// A custom model has no catalog entry, so WITHOUT an explicit map the
|
|
297
|
+
// runtime inherits a family rule (measured: a `qwen3-…` id inherited
|
|
298
|
+
// `enable_thinking` + `thinking` + `reasoning_effort`, and the gateway
|
|
299
|
+
// answered 400 for every turn). The catalog's own generic rule maps no
|
|
300
|
+
// reasoning parameters; copying it keeps an unknown endpoint usable and
|
|
301
|
+
// never sends a field the endpoint did not advertise.
|
|
302
|
+
optionSpecs: { reasoningLevel: { values: ['disabled', 'enabled'], map: '{}' } },
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
addedRules += 1;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const text = JSON.stringify(doc, null, 2);
|
|
309
|
+
await writeFileAtomic(path, text, { createMode: 0o600 });
|
|
310
|
+
const notes: string[] = [
|
|
311
|
+
`Wrote ${models.length} model rule${models.length === 1 ? '' : 's'} into provider_config.json — ZCode lists a custom provider’s models from that table, not from the provider rule alone.`,
|
|
312
|
+
];
|
|
313
|
+
if (draft.models.length === 0) {
|
|
314
|
+
notes.push('No model ids were given, so this provider serves nothing until one is added.');
|
|
315
|
+
}
|
|
316
|
+
if (addedRules > 0) {
|
|
317
|
+
notes.push('New model rules map NO reasoning parameters: the runtime otherwise inherits a catalog family mapping (measured: `enable_thinking`), which a custom endpoint can reject with 400. An existing rule keeps its own mapping.');
|
|
318
|
+
}
|
|
319
|
+
if (!apiKey && typeof existingAccess.apiKey === 'string' && existingAccess.apiKey) {
|
|
320
|
+
notes.push('Kept the stored API key — the draft carried none.');
|
|
321
|
+
}
|
|
322
|
+
return { id, replaced: index >= 0, path, dialect, env: {}, notes };
|
|
323
|
+
});
|
|
324
|
+
}
|
|
@@ -37,6 +37,9 @@ export interface AcpSpawnRequest {
|
|
|
37
37
|
/** On-disk transcript to resume; '' for a new chat. For ACP that is the
|
|
38
38
|
* agent's own session id, not a path — Kabmo stores it in `harness_sessions`. */
|
|
39
39
|
resumeAgentSessionId?: string;
|
|
40
|
+
/** Fork this agent session instead of starting a new one. Mutually exclusive
|
|
41
|
+
* with `resumeAgentSessionId`; the returned id is the child's own. */
|
|
42
|
+
forkAgentSessionId?: string;
|
|
40
43
|
cwd: string;
|
|
41
44
|
model?: SelectedModel | null;
|
|
42
45
|
thinkingLevel?: string | null;
|
|
@@ -44,6 +47,8 @@ export interface AcpSpawnRequest {
|
|
|
44
47
|
/** The composer's access pick, applied to the ACP session's own approval
|
|
45
48
|
* gate (this transport has no `--approval-mode` spawn flag). */
|
|
46
49
|
accessMode?: ApprovalMode | null;
|
|
50
|
+
/** Extra environment for this child only (the agent token and server URL). */
|
|
51
|
+
env?: Record<string, string>;
|
|
47
52
|
}
|
|
48
53
|
|
|
49
54
|
export class HarnessNotLaunchableError extends Error {
|
|
@@ -82,11 +87,12 @@ export async function startAcpSession(
|
|
|
82
87
|
// Built here rather than behind a factory in the session module: this is the
|
|
83
88
|
// only place a session is constructed, and the handshake it runs (load vs
|
|
84
89
|
// new) is decided by the request this function already holds.
|
|
90
|
+
const childEnv = { ...(launch.env ?? {}), ...(request.env ?? {}) };
|
|
85
91
|
const session = new AcpSession(
|
|
86
92
|
{
|
|
87
93
|
harness: request.harness,
|
|
88
94
|
command: sessionLaunchCommand(request.harness, launch.command),
|
|
89
|
-
...(
|
|
95
|
+
...(Object.keys(childEnv).length > 0 ? { env: childEnv } : {}),
|
|
90
96
|
model: startingModel,
|
|
91
97
|
thinkingLevel: request.thinkingLevel ?? configured.thinking ?? null,
|
|
92
98
|
mode: request.mode ?? configured.mode ?? null,
|
|
@@ -96,7 +102,10 @@ export async function startAcpSession(
|
|
|
96
102
|
);
|
|
97
103
|
let realSessionId: string;
|
|
98
104
|
try {
|
|
99
|
-
({ sessionId: realSessionId } = await session.start(
|
|
105
|
+
({ sessionId: realSessionId } = await session.start(
|
|
106
|
+
request.resumeAgentSessionId || undefined,
|
|
107
|
+
request.forkAgentSessionId,
|
|
108
|
+
));
|
|
100
109
|
} catch (error) {
|
|
101
110
|
// A refused handshake (an agent that will not `session/load`, a launch line
|
|
102
111
|
// that cannot run) must not leave the child it just spawned running with
|
|
@@ -105,6 +114,10 @@ export async function startAcpSession(
|
|
|
105
114
|
await session.destroyAndWait().catch(() => {});
|
|
106
115
|
throw error;
|
|
107
116
|
}
|
|
117
|
+
if (!realSessionId) {
|
|
118
|
+
await session.destroyAndWait().catch(() => {});
|
|
119
|
+
throw new Error(`${request.harness} started a session without an id`);
|
|
120
|
+
}
|
|
108
121
|
|
|
109
122
|
claimHarness(session, request.harness);
|
|
110
123
|
registerAcpSession(session, request.sessionId);
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The record a background harness update leaves on disk.
|
|
8
|
+
*
|
|
9
|
+
* The two questions these cases pin are the ones the dialog cannot answer for
|
|
10
|
+
* itself: is this run still going, and is a record that stopped moving a failure
|
|
11
|
+
* rather than something to poll forever.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
15
|
+
import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { tmpdir } from 'node:os';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
import {
|
|
19
|
+
jobInFlight,
|
|
20
|
+
pidAlive,
|
|
21
|
+
readUpdateJob,
|
|
22
|
+
settleDeadJob,
|
|
23
|
+
writeUpdateJob,
|
|
24
|
+
UPDATE_START_GRACE_MS,
|
|
25
|
+
} from '@/server/lib/harness/update-job-store';
|
|
26
|
+
import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
|
|
27
|
+
import type { HarnessUpdateJob } from '@/shared/types/harness-update';
|
|
28
|
+
|
|
29
|
+
let dir = '';
|
|
30
|
+
let originalDataDir: string | undefined;
|
|
31
|
+
|
|
32
|
+
beforeEach(() => {
|
|
33
|
+
originalDataDir = Bun.env.KABMO_DATA_DIR;
|
|
34
|
+
dir = mkdtempSync(join(tmpdir(), 'kabmo-update-job-'));
|
|
35
|
+
Bun.env.KABMO_DATA_DIR = dir;
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
afterEach(() => {
|
|
39
|
+
if (originalDataDir === undefined) delete Bun.env.KABMO_DATA_DIR;
|
|
40
|
+
else Bun.env.KABMO_DATA_DIR = originalDataDir;
|
|
41
|
+
rmSync(dir, { recursive: true, force: true });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
|
|
45
|
+
return {
|
|
46
|
+
harness: 'claude',
|
|
47
|
+
label: 'claude',
|
|
48
|
+
startedAt: Date.now(),
|
|
49
|
+
finishedAt: null,
|
|
50
|
+
pid: process.pid,
|
|
51
|
+
steps: [{ part: 'adapter', command: 'npm install -g x', argv: ['npm', 'install', '-g', 'x'], state: 'running', code: null }],
|
|
52
|
+
output: '',
|
|
53
|
+
ok: null,
|
|
54
|
+
message: null,
|
|
55
|
+
applied: false,
|
|
56
|
+
repointed: null,
|
|
57
|
+
...overrides,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
describe('the status record', () => {
|
|
62
|
+
test('round-trips, and leaves no temp file behind', async () => {
|
|
63
|
+
await writeUpdateJob(job({ output: 'installing' }));
|
|
64
|
+
const read = await readUpdateJob();
|
|
65
|
+
expect(read?.harness).toBe('claude');
|
|
66
|
+
expect(read?.output).toBe('installing');
|
|
67
|
+
// `tmp` + `rename`, so a reader never sees half a record and the temp name
|
|
68
|
+
// does not pile up.
|
|
69
|
+
const leftovers = readdirSync(join(dir, 'run')).filter((name) => name.endsWith('.tmp'));
|
|
70
|
+
expect(leftovers).toEqual([]);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('an absent record is null, not a throw', async () => {
|
|
74
|
+
expect(await readUpdateJob()).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('a foreign JSON file is not a job', async () => {
|
|
78
|
+
// A hand-written or half-written file must read as "nothing ran", not as a
|
|
79
|
+
// record whose missing fields crash the dialog.
|
|
80
|
+
writeFileSync(getHarnessUpdateStatusPath(), JSON.stringify({ hello: 'world' }));
|
|
81
|
+
expect(await readUpdateJob()).toBeNull();
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe('telling a live run from a dead one', () => {
|
|
86
|
+
test('a run with a live pid is in flight', () => {
|
|
87
|
+
expect(jobInFlight(job())).toBe(true);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('a finished run is not in flight', () => {
|
|
91
|
+
expect(jobInFlight(job({ finishedAt: Date.now(), ok: true }))).toBe(false);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test('a run whose worker is gone is settled by the next read', async () => {
|
|
95
|
+
const dead = job({ pid: 99_999_999, startedAt: Date.now() - UPDATE_START_GRACE_MS * 2 });
|
|
96
|
+
await writeUpdateJob(dead);
|
|
97
|
+
const settled = await settleDeadJob(await readUpdateJob());
|
|
98
|
+
expect(settled?.finishedAt).not.toBeNull();
|
|
99
|
+
expect(settled?.ok).toBe(false);
|
|
100
|
+
expect(settled?.message).toContain('without reporting a result');
|
|
101
|
+
expect(settled?.steps[0].state).toBe('failed');
|
|
102
|
+
// Settled once, and the settle itself is on disk for the next reader.
|
|
103
|
+
expect((await readUpdateJob())?.finishedAt).not.toBeNull();
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('the start grace covers the pid handshake', async () => {
|
|
107
|
+
// The record is written before the worker has a pid; reading that as dead
|
|
108
|
+
// would report failure over a run that is about to start.
|
|
109
|
+
const starting = job({ pid: null, startedAt: Date.now() });
|
|
110
|
+
await writeUpdateJob(starting);
|
|
111
|
+
expect(await settleDeadJob(await readUpdateJob())).toEqual(starting);
|
|
112
|
+
expect(jobInFlight(starting)).toBe(true);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('a finished run is left exactly as the worker wrote it', async () => {
|
|
116
|
+
const done = job({ pid: null, finishedAt: Date.now(), ok: true, message: 'claude updated (adapter)' });
|
|
117
|
+
await writeUpdateJob(done);
|
|
118
|
+
expect(await settleDeadJob(await readUpdateJob())).toEqual(done);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('an impossible pid is not alive', () => {
|
|
122
|
+
expect(pidAlive(null)).toBe(false);
|
|
123
|
+
expect(pidAlive(0)).toBe(false);
|
|
124
|
+
expect(pidAlive(process.pid)).toBe(true);
|
|
125
|
+
});
|
|
126
|
+
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The harness update record on disk: read it, write it atomically, and tell a
|
|
8
|
+
* live run from a dead one.
|
|
9
|
+
*
|
|
10
|
+
* Kept apart from `update-job.server.ts` because the DETACHED WORKER writes the
|
|
11
|
+
* same record (`update-worker.ts`) and must not import the server's database and
|
|
12
|
+
* config modules to do it. One writer, one file shape, two processes.
|
|
13
|
+
*
|
|
14
|
+
* **A run outlives the request that started it.** The POST answers in
|
|
15
|
+
* milliseconds while the install keeps going, so the state cannot live in a
|
|
16
|
+
* closure or a `Map`: a reloaded page, a second tab and a `bun --hot` reload all
|
|
17
|
+
* have to read the same answer. It is one JSON file, replaced atomically
|
|
18
|
+
* (`tmp` + `rename`), which is why a reader never sees half a record.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
|
|
23
|
+
import { isHarnessUpdateJob } from '@/shared/lib/harness/update-job';
|
|
24
|
+
import type { HarnessUpdateJob } from '@/shared/types/harness-update';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* How long a just-started job is trusted without a live pid.
|
|
28
|
+
*
|
|
29
|
+
* The server writes the record, then spawns the worker; for those first moments
|
|
30
|
+
* there is a `finishedAt: null` record and no worker pid yet. Reading that as "it
|
|
31
|
+
* died" would report a failure over a run that is about to start. Fifteen
|
|
32
|
+
* seconds is far longer than that handshake and far shorter than a human's
|
|
33
|
+
* patience for a stale row.
|
|
34
|
+
*/
|
|
35
|
+
export const UPDATE_START_GRACE_MS = 15_000;
|
|
36
|
+
|
|
37
|
+
/** The current record, or null when none was ever written (or it is unreadable).
|
|
38
|
+
* `path` is the record the caller owns: the server uses the install's run
|
|
39
|
+
* directory, the detached worker uses the one its spec names. */
|
|
40
|
+
export async function readUpdateJob(path = getHarnessUpdateStatusPath()): Promise<HarnessUpdateJob | null> {
|
|
41
|
+
try {
|
|
42
|
+
const parsed = (await Bun.file(path).json()) as unknown;
|
|
43
|
+
return isHarnessUpdateJob(parsed) ? parsed : null;
|
|
44
|
+
} catch {
|
|
45
|
+
// Absent (never run) and corrupt (a half-written record from an old build)
|
|
46
|
+
// are the same answer: there is nothing to report.
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Replace the record atomically. A reader sees the previous one or this one. */
|
|
52
|
+
export async function writeUpdateJob(job: HarnessUpdateJob, path = getHarnessUpdateStatusPath()): Promise<void> {
|
|
53
|
+
const target = path;
|
|
54
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
55
|
+
await Bun.write(temp, JSON.stringify(job, null, 2));
|
|
56
|
+
await fs.promises.rename(temp, target);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Is this pid a live process? `EPERM` means it exists and is not ours. */
|
|
60
|
+
export function pidAlive(pid: number | null): boolean {
|
|
61
|
+
if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
|
|
62
|
+
try {
|
|
63
|
+
process.kill(pid, 0);
|
|
64
|
+
return true;
|
|
65
|
+
} catch (cause) {
|
|
66
|
+
return (cause as NodeJS.ErrnoException).code === 'EPERM';
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Is this run still going?
|
|
72
|
+
*
|
|
73
|
+
* A known-live pid settles it. Without one the record is trusted only inside the
|
|
74
|
+
* start grace window; after that an absent worker means the run died without
|
|
75
|
+
* writing a result, and the caller reports that instead of polling forever.
|
|
76
|
+
*/
|
|
77
|
+
export function jobInFlight(job: HarnessUpdateJob | null, now = Date.now()): boolean {
|
|
78
|
+
if (!job || job.finishedAt !== null) return false;
|
|
79
|
+
if (pidAlive(job.pid)) return true;
|
|
80
|
+
return now - job.startedAt < UPDATE_START_GRACE_MS;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The record with a run that died without reporting turned into a failure.
|
|
85
|
+
*
|
|
86
|
+
* `finishedAt` is what every reader keys on, so settling here is what stops the
|
|
87
|
+
* dialog from spinning forever; the message says the install itself may have
|
|
88
|
+
* completed, because a killed reporter is not proof the commands failed.
|
|
89
|
+
*/
|
|
90
|
+
export async function settleDeadJob(
|
|
91
|
+
job: HarnessUpdateJob | null,
|
|
92
|
+
path = getHarnessUpdateStatusPath(),
|
|
93
|
+
): Promise<HarnessUpdateJob | null> {
|
|
94
|
+
// A record that already has a result is history, not a candidate: the worker
|
|
95
|
+
// wrote it, and rewriting it would turn a success into a "stopped without
|
|
96
|
+
// reporting" failure.
|
|
97
|
+
if (!job || job.finishedAt !== null || jobInFlight(job)) return job;
|
|
98
|
+
const settled: HarnessUpdateJob = {
|
|
99
|
+
...job,
|
|
100
|
+
finishedAt: Date.now(),
|
|
101
|
+
pid: null,
|
|
102
|
+
ok: false,
|
|
103
|
+
applied: true,
|
|
104
|
+
message: `${job.label} update stopped without reporting a result — check its status before trying again`,
|
|
105
|
+
steps: job.steps.map((step) => (step.state === 'running' ? { ...step, state: 'failed' } : step)),
|
|
106
|
+
};
|
|
107
|
+
await writeUpdateJob(settled, path);
|
|
108
|
+
return settled;
|
|
109
|
+
}
|