omnicell-router 0.8.2 → 0.10.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/README.md +26 -7
- package/README.zh-CN.md +18 -5
- package/backend/dist/auth/api-keys.js +11 -0
- package/backend/dist/auth/key-models.d.ts +36 -0
- package/backend/dist/auth/key-models.js +99 -0
- package/backend/dist/capture/recorder.d.ts +4 -10
- package/backend/dist/capture/recorder.js +6 -58
- package/backend/dist/cli/clients/activity.js +2 -0
- package/backend/dist/cli/clients/base.d.ts +36 -11
- package/backend/dist/cli/clients/base.js +31 -15
- package/backend/dist/cli/clients/claude.d.ts +9 -0
- package/backend/dist/cli/clients/claude.js +6 -0
- package/backend/dist/cli/clients/codex.d.ts +78 -0
- package/backend/dist/cli/clients/codex.js +475 -57
- package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
- package/backend/dist/cli/clients/core-adapters.js +1 -1
- package/backend/dist/cli/clients/dsh.d.ts +8 -0
- package/backend/dist/cli/clients/dsh.js +5 -0
- package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
- package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
- package/backend/dist/cli/clients/grok.d.ts +15 -1
- package/backend/dist/cli/clients/grok.js +16 -2
- package/backend/dist/cli/clients/index.d.ts +13 -1
- package/backend/dist/cli/clients/index.js +97 -19
- package/backend/dist/cli/clients/kimi.d.ts +6 -0
- package/backend/dist/cli/clients/kimi.js +3 -0
- package/backend/dist/cli/clients/launcher.d.ts +1 -1
- package/backend/dist/cli/clients/model-meta.js +6 -3
- package/backend/dist/cli/clients/omp.d.ts +6 -0
- package/backend/dist/cli/clients/omp.js +3 -0
- package/backend/dist/cli/clients/openclaw.d.ts +6 -0
- package/backend/dist/cli/clients/openclaw.js +3 -0
- package/backend/dist/cli/clients/opencode.d.ts +8 -0
- package/backend/dist/cli/clients/opencode.js +8 -2
- package/backend/dist/cli/clients/pi.d.ts +6 -0
- package/backend/dist/cli/clients/pi.js +3 -0
- package/backend/dist/cli/clients/reserved.js +2 -0
- package/backend/dist/cli/clients/update-check.d.ts +37 -0
- package/backend/dist/cli/clients/update-check.js +309 -0
- package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
- package/backend/dist/cli/clients/workbuddy.js +66 -0
- package/backend/dist/cli/index.js +5 -4
- package/backend/dist/cli/paths.js +8 -0
- package/backend/dist/cli/types.d.ts +101 -16
- package/backend/dist/config/comments-en.js +34 -25
- package/backend/dist/config/comments-zh.js +33 -24
- package/backend/dist/config/defaults.d.ts +280 -22
- package/backend/dist/config/defaults.js +279 -21
- package/backend/dist/config/env.d.ts +10 -0
- package/backend/dist/config/env.js +3 -2
- package/backend/dist/config/index.d.ts +22 -1
- package/backend/dist/config/index.js +218 -43
- package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
- package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
- package/backend/dist/config/migrations/v10-to-v11.js +43 -0
- package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
- package/backend/dist/config/migrations/v4-to-v5.js +42 -0
- package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
- package/backend/dist/config/migrations/v5-to-v6.js +29 -0
- package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
- package/backend/dist/config/migrations/v6-to-v7.js +97 -0
- package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
- package/backend/dist/config/migrations/v7-to-v8.js +43 -0
- package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
- package/backend/dist/config/migrations/v8-to-v9.js +43 -0
- package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
- package/backend/dist/config/migrations/v9-to-v10.js +71 -0
- package/backend/dist/config/runtime.js +1 -1
- package/backend/dist/config/schema.d.ts +3 -3
- package/backend/dist/config/schema.js +18 -4
- package/backend/dist/config/types.d.ts +221 -41
- package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
- package/backend/dist/egress-proxy/asset-download.js +420 -0
- package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
- package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
- package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
- package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
- package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
- package/backend/dist/egress-proxy/mihomo-client.js +308 -0
- package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
- package/backend/dist/egress-proxy/mihomo-config.js +161 -0
- package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
- package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
- package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
- package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
- package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
- package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
- package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
- package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
- package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
- package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
- package/backend/dist/forward-proxy/egress.d.ts +50 -11
- package/backend/dist/forward-proxy/egress.js +63 -17
- package/backend/dist/forward-proxy/h2-forward.js +42 -15
- package/backend/dist/forward-proxy/index.d.ts +11 -8
- package/backend/dist/forward-proxy/index.js +27 -60
- package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
- package/backend/dist/forward-proxy/interceptor.js +4 -4
- package/backend/dist/forward-proxy/relay.js +3 -3
- package/backend/dist/forward-proxy/rules.d.ts +4 -4
- package/backend/dist/forward-proxy/rules.js +25 -4
- package/backend/dist/forward-proxy/server.d.ts +12 -16
- package/backend/dist/forward-proxy/server.js +237 -171
- package/backend/dist/harness/host/hosts.js +3 -2
- package/backend/dist/index.js +59 -19
- package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
- package/backend/dist/ingress-proxy/access-log.js +774 -0
- package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
- package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
- package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
- package/backend/dist/ingress-proxy/ca-trust.js +315 -0
- package/backend/dist/ingress-proxy/ca.d.ts +104 -0
- package/backend/dist/ingress-proxy/ca.js +273 -0
- package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
- package/backend/dist/ingress-proxy/data-dir.js +45 -0
- package/backend/dist/ingress-proxy/egress.d.ts +151 -0
- package/backend/dist/ingress-proxy/egress.js +364 -0
- package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
- package/backend/dist/ingress-proxy/h2-forward.js +561 -0
- package/backend/dist/ingress-proxy/index.d.ts +24 -0
- package/backend/dist/ingress-proxy/index.js +144 -0
- package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
- package/backend/dist/ingress-proxy/interceptor.js +52 -0
- package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
- package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
- package/backend/dist/ingress-proxy/relay.d.ts +54 -0
- package/backend/dist/ingress-proxy/relay.js +188 -0
- package/backend/dist/ingress-proxy/rules.d.ts +195 -0
- package/backend/dist/ingress-proxy/rules.js +348 -0
- package/backend/dist/ingress-proxy/server.d.ts +153 -0
- package/backend/dist/ingress-proxy/server.js +2065 -0
- package/backend/dist/ingress-proxy/sni.d.ts +35 -0
- package/backend/dist/ingress-proxy/sni.js +124 -0
- package/backend/dist/ingress-proxy/status.d.ts +32 -0
- package/backend/dist/ingress-proxy/status.js +15 -0
- package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
- package/backend/dist/ingress-proxy/system-proxy.js +481 -0
- package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
- package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
- package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
- package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
- package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
- package/backend/dist/ingress-proxy/traffic-files.js +10 -0
- package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
- package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
- package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
- package/backend/dist/ingress-proxy/ws-frames.js +153 -0
- package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
- package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
- package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
- package/backend/dist/ir/adapters/google-gemini.js +5 -2
- package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
- package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
- package/backend/dist/ir/adapters/openai-chat.js +50 -6
- package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
- package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
- package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
- package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
- package/backend/dist/ir/adapters/openai-responses.d.ts +92 -1
- package/backend/dist/ir/adapters/openai-responses.js +163 -12
- package/backend/dist/ir/capabilities.js +4 -0
- package/backend/dist/ir/media.d.ts +20 -0
- package/backend/dist/ir/media.js +41 -0
- package/backend/dist/ir/tool-identity.d.ts +35 -0
- package/backend/dist/ir/tool-identity.js +40 -0
- package/backend/dist/ir/types.d.ts +9 -1
- package/backend/dist/ir/validate.d.ts +24 -0
- package/backend/dist/ir/validate.js +113 -63
- package/backend/dist/local/build-jobs.d.ts +66 -0
- package/backend/dist/local/build-jobs.js +243 -0
- package/backend/dist/local/detect.d.ts +32 -0
- package/backend/dist/local/detect.js +145 -0
- package/backend/dist/local/draft-match.d.ts +58 -0
- package/backend/dist/local/draft-match.js +124 -0
- package/backend/dist/local/engine-runtime.d.ts +522 -0
- package/backend/dist/local/engine-runtime.js +1 -0
- package/backend/dist/local/engines.d.ts +241 -0
- package/backend/dist/local/engines.js +651 -0
- package/backend/dist/local/gguf.d.ts +35 -0
- package/backend/dist/local/gguf.js +314 -0
- package/backend/dist/local/hf.d.ts +120 -0
- package/backend/dist/local/hf.js +304 -0
- package/backend/dist/local/install.d.ts +90 -0
- package/backend/dist/local/install.js +421 -0
- package/backend/dist/local/llamacpp.d.ts +55 -0
- package/backend/dist/local/llamacpp.js +177 -0
- package/backend/dist/local/local-provider.d.ts +81 -0
- package/backend/dist/local/local-provider.js +301 -0
- package/backend/dist/local/machine-stats.d.ts +87 -0
- package/backend/dist/local/machine-stats.js +332 -0
- package/backend/dist/local/model-store.d.ts +347 -0
- package/backend/dist/local/model-store.js +1215 -0
- package/backend/dist/local/part-sweep.d.ts +32 -0
- package/backend/dist/local/part-sweep.js +156 -0
- package/backend/dist/local/plan.d.ts +65 -0
- package/backend/dist/local/plan.js +146 -0
- package/backend/dist/local/resources.d.ts +49 -0
- package/backend/dist/local/resources.js +64 -0
- package/backend/dist/local/run-stats.d.ts +95 -0
- package/backend/dist/local/run-stats.js +195 -0
- package/backend/dist/local/runner.d.ts +235 -0
- package/backend/dist/local/runner.js +1392 -0
- package/backend/dist/local/settings.d.ts +79 -0
- package/backend/dist/local/settings.js +180 -0
- package/backend/dist/local/strata-catalog.d.ts +30 -0
- package/backend/dist/local/strata-catalog.js +511 -0
- package/backend/dist/local/strata-drafting.d.ts +46 -0
- package/backend/dist/local/strata-drafting.js +265 -0
- package/backend/dist/local/strata.d.ts +278 -0
- package/backend/dist/local/strata.js +1392 -0
- package/backend/dist/local/tar.d.ts +20 -0
- package/backend/dist/local/tar.js +367 -0
- package/backend/dist/local/transport.d.ts +35 -0
- package/backend/dist/local/transport.js +89 -0
- package/backend/dist/local/tune.d.ts +58 -0
- package/backend/dist/local/tune.js +324 -0
- package/backend/dist/observability/http-exchange.d.ts +2 -2
- package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
- package/backend/dist/opencode/catalog/auto-pull.js +284 -77
- package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
- package/backend/dist/opencode/catalog/ocr-store.js +4 -2
- package/backend/dist/opencode/catalog/overrides-store.d.ts +15 -4
- package/backend/dist/opencode/catalog/overrides-store.js +28 -19
- package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
- package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
- package/backend/dist/opencode/catalog/repository.js +28 -5
- package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
- package/backend/dist/opencode/catalog/sources/models-dev.js +42 -14
- package/backend/dist/opencode/catalog/types.d.ts +42 -12
- package/backend/dist/opencode/catalog/types.js +38 -1
- package/backend/dist/opencode/credentials/def-materialize.js +27 -21
- package/backend/dist/opencode/credentials/ocr-store.js +11 -2
- package/backend/dist/opencode/credentials/sync.js +12 -3
- package/backend/dist/opencode/credentials/types.d.ts +31 -4
- package/backend/dist/opencode/credentials/types.js +25 -0
- package/backend/dist/opencode/migrate/engine.d.ts +20 -0
- package/backend/dist/opencode/migrate/engine.js +71 -0
- package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
- package/backend/dist/opencode/migrate/migrator.js +6 -0
- package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
- package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
- package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
- package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
- package/backend/dist/opencode/probe.d.ts +21 -4
- package/backend/dist/opencode/probe.js +34 -10
- package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
- package/backend/dist/opencode/provider-def-adapters.js +43 -27
- package/backend/dist/opencode/provider-defs.d.ts +10 -16
- package/backend/dist/opencode/provider-defs.js +45 -45
- package/backend/dist/opencode/user-config.d.ts +23 -26
- package/backend/dist/opencode/user-config.js +95 -77
- package/backend/dist/pipeline/directives.d.ts +9 -4
- package/backend/dist/pipeline/directives.js +14 -10
- package/backend/dist/pipeline/orchestrator.d.ts +42 -13
- package/backend/dist/pipeline/orchestrator.js +514 -172
- package/backend/dist/plugins/builtin/model-gateway.js +38 -12
- package/backend/dist/plugins/environment-ack.d.ts +51 -0
- package/backend/dist/plugins/environment-ack.js +81 -0
- package/backend/dist/plugins/gateways.d.ts +6 -6
- package/backend/dist/plugins/gateways.js +2 -2
- package/backend/dist/plugins/host.d.ts +100 -16
- package/backend/dist/plugins/host.js +637 -99
- package/backend/dist/plugins/install-run.d.ts +27 -0
- package/backend/dist/plugins/install-run.js +99 -0
- package/backend/dist/plugins/manifest.d.ts +84 -32
- package/backend/dist/plugins/manifest.js +149 -45
- package/backend/dist/plugins/market-install.d.ts +18 -0
- package/backend/dist/plugins/market-install.js +111 -0
- package/backend/dist/plugins/market-source.d.ts +100 -0
- package/backend/dist/plugins/market-source.js +449 -0
- package/backend/dist/plugins/market-updates.d.ts +70 -0
- package/backend/dist/plugins/market-updates.js +97 -0
- package/backend/dist/plugins/market.d.ts +677 -0
- package/backend/dist/plugins/market.js +2113 -0
- package/backend/dist/plugins/source-index.d.ts +155 -0
- package/backend/dist/plugins/source-index.js +217 -0
- package/backend/dist/plugins/types.d.ts +402 -37
- package/backend/dist/projects/worktrees.d.ts +88 -0
- package/backend/dist/projects/worktrees.js +220 -0
- package/backend/dist/providers/boot-direct.d.ts +41 -7
- package/backend/dist/providers/boot-direct.js +284 -44
- package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
- package/backend/dist/providers/dial-wire.d.ts +17 -0
- package/backend/dist/providers/dial-wire.js +49 -0
- package/backend/dist/providers/executors/dispatch.d.ts +17 -7
- package/backend/dist/providers/executors/dispatch.js +28 -9
- package/backend/dist/providers/executors/openai-chat.js +14 -2
- package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
- package/backend/dist/providers/executors/plugin-adapter.js +59 -3
- package/backend/dist/providers/member-match.d.ts +32 -9
- package/backend/dist/providers/member-match.js +65 -21
- package/backend/dist/providers/model-resolution.d.ts +62 -0
- package/backend/dist/providers/model-resolution.js +62 -0
- package/backend/dist/providers/price-order.d.ts +51 -0
- package/backend/dist/providers/price-order.js +54 -0
- package/backend/dist/providers/protocols-field.d.ts +24 -0
- package/backend/dist/providers/protocols-field.js +66 -0
- package/backend/dist/providers/provider-takedown.d.ts +5 -2
- package/backend/dist/providers/registry.d.ts +87 -26
- package/backend/dist/providers/registry.js +232 -121
- package/backend/dist/providers/selection.d.ts +91 -0
- package/backend/dist/providers/selection.js +158 -0
- package/backend/dist/providers/virtual-meta.d.ts +33 -2
- package/backend/dist/providers/virtual-meta.js +74 -18
- package/backend/dist/quota/cli-login.d.ts +25 -4
- package/backend/dist/quota/cli-login.js +38 -6
- package/backend/dist/quota/coverage-generation.d.ts +24 -0
- package/backend/dist/quota/coverage-generation.js +29 -0
- package/backend/dist/quota/declarations.js +8 -4
- package/backend/dist/quota/engine.js +2 -2
- package/backend/dist/quota/prober.d.ts +43 -2
- package/backend/dist/quota/prober.js +97 -22
- package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
- package/backend/dist/resilience/error-classifier.js +29 -0
- package/backend/dist/router/index.d.ts +1 -1
- package/backend/dist/router/index.js +17 -1
- package/backend/dist/router/layer2-decision.d.ts +1 -1
- package/backend/dist/router/layer2-decision.js +2 -2
- package/backend/dist/routes/console.js +1043 -405
- package/backend/dist/routes/environments.js +1 -1
- package/backend/dist/routes/local-models.d.ts +2 -0
- package/backend/dist/routes/local-models.js +1414 -0
- package/backend/dist/routes/mihomo.d.ts +2 -2
- package/backend/dist/routes/mihomo.js +20 -11
- package/backend/dist/routes/projects.js +121 -0
- package/backend/dist/server.js +409 -15
- package/backend/dist/session/session-manager.d.ts +42 -5
- package/backend/dist/session/session-manager.js +64 -11
- package/backend/dist/session/session-row.d.ts +29 -8
- package/backend/dist/session/session-row.js +18 -13
- package/backend/dist/snapshot/bundle.d.ts +40 -0
- package/backend/dist/snapshot/bundle.js +177 -0
- package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
- package/backend/dist/snapshot/handoff/compress.js +77 -0
- package/backend/dist/snapshot/handoff/index.d.ts +119 -0
- package/backend/dist/snapshot/handoff/index.js +160 -0
- package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
- package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
- package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
- package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
- package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
- package/backend/dist/snapshot/handoff/summarize.js +118 -0
- package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
- package/backend/dist/snapshot/handoff/transcript.js +167 -0
- package/backend/dist/snapshot/media-fs.d.ts +10 -0
- package/backend/dist/snapshot/media-fs.js +50 -0
- package/backend/dist/snapshot/media.d.ts +32 -0
- package/backend/dist/snapshot/media.js +87 -0
- package/backend/dist/snapshot/store.d.ts +226 -0
- package/backend/dist/snapshot/store.js +887 -0
- package/backend/dist/snapshot/tree.d.ts +112 -0
- package/backend/dist/snapshot/tree.js +207 -0
- package/backend/dist/snapshot/types.d.ts +212 -0
- package/backend/dist/snapshot/types.js +14 -0
- package/backend/dist/snapshot/view.d.ts +19 -0
- package/backend/dist/snapshot/view.js +57 -0
- package/backend/dist/snapshot/write-worker.d.ts +67 -0
- package/backend/dist/snapshot/write-worker.js +129 -0
- package/backend/dist/surfaces/anthropic.js +4 -1
- package/backend/dist/surfaces/body-admission.d.ts +344 -0
- package/backend/dist/surfaces/body-admission.js +818 -0
- package/backend/dist/surfaces/chat-pipeline.js +8 -0
- package/backend/dist/surfaces/decision-pipeline.js +10 -7
- package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
- package/backend/dist/surfaces/gateway-catalog.js +202 -0
- package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
- package/backend/dist/surfaces/gateway-chat.js +50 -12
- package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
- package/backend/dist/surfaces/ocr-headers.js +11 -7
- package/backend/dist/surfaces/systemone.js +1 -1
- package/backend/dist/surfaces/transport-fastify.js +32 -5
- package/backend/dist/surfaces/transport-node-http.d.ts +51 -6
- package/backend/dist/surfaces/transport-node-http.js +76 -16
- package/backend/dist/surfaces/types.d.ts +11 -3
- package/backend/dist/trace/persist.js +21 -1
- package/backend/dist/trace/tracker.d.ts +35 -3
- package/backend/dist/trace/tracker.js +23 -0
- package/backend/dist/types/openai.d.ts +8 -0
- package/backend/dist/types/router.d.ts +17 -6
- package/backend/dist/types/router.js +14 -2
- package/backend/dist/utils/client-families.d.ts +66 -0
- package/backend/dist/utils/client-families.js +127 -0
- package/backend/dist/utils/event-ring.d.ts +1 -1
- package/backend/dist/utils/event-ring.js +1 -1
- package/backend/dist/utils/proxy-node.js +1 -1
- package/backend/dist/utils/proxy.d.ts +135 -11
- package/backend/dist/utils/proxy.js +144 -29
- package/backend/dist/utils/run-command.d.ts +21 -1
- package/backend/dist/utils/run-command.js +64 -4
- package/backend/dist/utils/server-liveness.d.ts +28 -0
- package/backend/dist/utils/server-liveness.js +32 -0
- package/backend/dist/utils/session-file.d.ts +28 -0
- package/backend/dist/utils/session-file.js +34 -0
- package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
- package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
- package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
- package/frontend/dist/assets/{index-DxZ9MHKB.css → index-CqDSOPQ0.css} +1 -1
- package/frontend/dist/index.html +2 -2
- package/package.json +3 -1
- package/frontend/dist/assets/index-55VVwfFQ.js +0 -1521
|
@@ -0,0 +1,1414 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin routes for local inference engines (the console's Local Models page).
|
|
3
|
+
*
|
|
4
|
+
* Mounted under /api/admin/local-models/*, so the console auth preHandler
|
|
5
|
+
* covers them. Install streams NDJSON like the mihomo core installer:
|
|
6
|
+
* `stage`/`progress` events, then exactly one `result`.
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { detectDependencies, summarizeDetect } from '../local/detect.js';
|
|
12
|
+
import { ENGINES, catalogModelGate, engineById, engineRuntimeInfo, installedEngineVersion, installedEngineFor, installedEnginesFor, launchableEngines, probeEngineAvailability, recommendTargets, } from '../local/engines.js';
|
|
13
|
+
import { fetchHfModelFiles, groupHfShards, hfEndpoint, isValidRepoId, resetHfCache, searchHfModels } from '../local/hf.js';
|
|
14
|
+
import { downloadCatalogModel, downloadHfModel, downloadHfModelGroup, importLocalModels, refreshDraftMatches, listInstalledModels, modelsDiskUsage, rescanInstalledModels, readInstalledModels, profileFor, removeHfModel, setEngineProfile, setModelEnabled, setModelName, } from '../local/model-store.js';
|
|
15
|
+
import { loadConfig } from '../config/index.js';
|
|
16
|
+
import { LOCAL_DEFAULT_CTX } from '../config/defaults.js';
|
|
17
|
+
import { localModelId } from '../local/local-provider.js';
|
|
18
|
+
import { requestPoolRefresh } from '../providers/pool-refresh.js';
|
|
19
|
+
import { installEngine, pruneSupersededInstall, uninstallEngine } from '../local/install.js';
|
|
20
|
+
import { engineDownloadPartBytes, modelPartBytes, startAbandonedPartSweep, } from '../local/part-sweep.js';
|
|
21
|
+
import { autoCtx, nglForPlan, planPlacement, CTX_LADDER, KV_ELEM_Q8_0 } from '../local/plan.js';
|
|
22
|
+
import { benchmarkLocalRun, deleteLocalRun, getLocalRun, listLocalRuns, pruneLocalRuns, restoreLocalRuns, runLogs, startLocalRun, stopLocalRun, activeRunFor, DEFAULT_RUN_OPTIONS, } from '../local/runner.js';
|
|
23
|
+
import { buildLogs, listBuildJobs, prepareAfterDownload, startBuildJob } from '../local/build-jobs.js';
|
|
24
|
+
import { cancelTuneJob, getTuneJob, listTuneJobs, startTuneJob } from '../local/tune.js';
|
|
25
|
+
import { cancelDrafterFetch, drafterStatus, startDrafterFetch } from '../local/strata-drafting.js';
|
|
26
|
+
import { dropStats, pruneStats, statsFor } from '../local/run-stats.js';
|
|
27
|
+
import { machineSnapshot, touchMachineSampler } from '../local/machine-stats.js';
|
|
28
|
+
import { HF_MIRROR_PRESETS_MAX, HF_MIRROR_PRESET_LABEL_MAX, defaultModelsDir, isMirrorUrl, normalizeMirrorUrl, readLocalModelSettings, resolveHfEndpoint, resolveHfToken, resolveLocalEgress, resolveModelsDir, writeLocalModelSettings, } from '../local/settings.js';
|
|
29
|
+
import { localProxyConfigured, localTransport } from '../local/transport.js';
|
|
30
|
+
/**
|
|
31
|
+
* Live installs keyed by leg (`engine:<id>`). A walked-away client fires no
|
|
32
|
+
* disconnect the hijacked NDJSON response can observe (same Bun behaviour the
|
|
33
|
+
* mihomo installer documents), so the console's explicit cancel call is the
|
|
34
|
+
* only reliable stop signal.
|
|
35
|
+
*/
|
|
36
|
+
const liveTransfers = new Map();
|
|
37
|
+
function startEngineTransfer(raw, leg) {
|
|
38
|
+
let closed = false;
|
|
39
|
+
const abort = new AbortController();
|
|
40
|
+
liveTransfers.set(leg, abort);
|
|
41
|
+
raw.on('close', () => {
|
|
42
|
+
closed = true;
|
|
43
|
+
if (!raw.writableEnded)
|
|
44
|
+
abort.abort(new Error('client disconnected'));
|
|
45
|
+
});
|
|
46
|
+
return {
|
|
47
|
+
signal: abort.signal,
|
|
48
|
+
send: (evt) => {
|
|
49
|
+
if (closed)
|
|
50
|
+
return;
|
|
51
|
+
try {
|
|
52
|
+
raw.write(`${JSON.stringify(evt)}\n`);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
closed = true;
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
finish: () => {
|
|
59
|
+
liveTransfers.delete(leg);
|
|
60
|
+
if (!raw.writableEnded)
|
|
61
|
+
raw.end();
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function installEventToPayload(event) {
|
|
66
|
+
return event;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Whether a run still pins a binary inside `dir`.
|
|
70
|
+
*
|
|
71
|
+
* A run records the ABSOLUTE binary path in `runs.json`, so both a live engine
|
|
72
|
+
* and a merely recorded one keep their build: deleting a running engine's
|
|
73
|
+
* binary fails on Windows and would leave an un-restartable process on POSIX.
|
|
74
|
+
*/
|
|
75
|
+
async function engineDirInUse(dir) {
|
|
76
|
+
try {
|
|
77
|
+
const runs = await listLocalRuns();
|
|
78
|
+
return runs.some((run) => (typeof run.binary === 'string'
|
|
79
|
+
&& run.binary.length > 0
|
|
80
|
+
&& path.resolve(run.binary).startsWith(dir + path.sep)));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// An unreadable run list must not license a delete.
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Whether a run that can still ANSWER is serving a binary inside `dir`.
|
|
89
|
+
*
|
|
90
|
+
* Only serving statuses count. `engineDirInUse` (the upgrade sweep) is stricter
|
|
91
|
+
* on purpose — a merely recorded build is kept there because a restart may still
|
|
92
|
+
* want it — but for an uninstall a stopped or failed record cannot be using the
|
|
93
|
+
* build, and refusing would leave the operator with a dead-end: stop the model,
|
|
94
|
+
* click uninstall, "in use". A run that is `starting` (including the gap before
|
|
95
|
+
* an automatic respawn), `ready` or `stopping` does hold it.
|
|
96
|
+
*/
|
|
97
|
+
async function engineBuildInUse(dir) {
|
|
98
|
+
const runs = await listLocalRuns().catch(() => null);
|
|
99
|
+
if (!runs)
|
|
100
|
+
return true; // an unreadable run list must not license a delete
|
|
101
|
+
return runs.some((run) => (run.status === 'starting' || run.status === 'ready' || run.status === 'stopping')
|
|
102
|
+
&& typeof run.binary === 'string'
|
|
103
|
+
&& run.binary.length > 0
|
|
104
|
+
&& path.resolve(run.binary).startsWith(dir + path.sep));
|
|
105
|
+
}
|
|
106
|
+
function modelEventToPayload(event) {
|
|
107
|
+
return event;
|
|
108
|
+
}
|
|
109
|
+
export function registerLocalModelRoutes(app) {
|
|
110
|
+
// Catalog + install state: everything the engine cards render in one read.
|
|
111
|
+
// `installs` carries EVERY build target installed for the engine (a CPU
|
|
112
|
+
// fallback beside the GPU build) — the run console picks among them.
|
|
113
|
+
app.get('/api/admin/local-models/engines', async () => {
|
|
114
|
+
return {
|
|
115
|
+
status: 'ok',
|
|
116
|
+
platform: process.platform,
|
|
117
|
+
arch: process.arch,
|
|
118
|
+
// Abandoned archives staged under `engines/downloads`, before the
|
|
119
|
+
// retention sweep reclaims them (ADR-0022).
|
|
120
|
+
partialBytes: engineDownloadPartBytes(),
|
|
121
|
+
engines: ENGINES.map((engine) => ({
|
|
122
|
+
id: engine.id,
|
|
123
|
+
name: engine.name,
|
|
124
|
+
repo: engine.repo,
|
|
125
|
+
description: engine.description,
|
|
126
|
+
...(engine.descriptionKey ? { descriptionKey: engine.descriptionKey } : {}),
|
|
127
|
+
binaryNames: engine.binaryNames,
|
|
128
|
+
targets: engine.targets(process.platform, process.arch),
|
|
129
|
+
installs: installedEnginesFor(engine.id),
|
|
130
|
+
// The console renders the run form FROM this block: placement owner,
|
|
131
|
+
// which shared controls the build takes, and the operator profile's
|
|
132
|
+
// field schema. A new engine needs no console change (ADR-0045).
|
|
133
|
+
runtime: engineRuntimeInfo(engine),
|
|
134
|
+
})),
|
|
135
|
+
};
|
|
136
|
+
});
|
|
137
|
+
// The placement plan needs the machine reading; the probe shells out to
|
|
138
|
+
// vendor CLIs (seconds), so it is cached briefly — the plan is advisory.
|
|
139
|
+
let detectCache = null;
|
|
140
|
+
const cachedDetect = async () => {
|
|
141
|
+
if (detectCache && Date.now() - detectCache.at < 60_000)
|
|
142
|
+
return detectCache.report;
|
|
143
|
+
const report = await detectDependencies();
|
|
144
|
+
detectCache = { at: Date.now(), report };
|
|
145
|
+
return report;
|
|
146
|
+
};
|
|
147
|
+
// Dependency probe + per-engine default target. Runs vendor CLIs with short
|
|
148
|
+
// timeouts; a missing tool is a failed check row, never an error. This IS the
|
|
149
|
+
// explicit probe, so it runs every time — and it FEEDS the cache above: the
|
|
150
|
+
// console probes, then reads the catalog, whose machine facts came from here.
|
|
151
|
+
// Without the write-back that read re-ran every vendor CLI a second time.
|
|
152
|
+
app.post('/api/admin/local-models/detect', async () => {
|
|
153
|
+
const report = await detectDependencies();
|
|
154
|
+
detectCache = { at: Date.now(), report };
|
|
155
|
+
// The recommendation is per-engine catalog data: adding an engine with a
|
|
156
|
+
// `recommendTarget` automatically extends this map (ADR-0045).
|
|
157
|
+
return { status: 'ok', report, recommended: recommendTargets(summarizeDetect(report)) };
|
|
158
|
+
});
|
|
159
|
+
// Release availability: which catalog targets the CURRENT release actually
|
|
160
|
+
// ships, per engine. The console disables the chips with no asset instead of
|
|
161
|
+
// letting the install click discover it. Cached briefly — GitHub rate limits
|
|
162
|
+
// are shared across every console on this host.
|
|
163
|
+
let availabilityCache = null;
|
|
164
|
+
app.get('/api/admin/local-models/engines/availability', async () => {
|
|
165
|
+
if (availabilityCache && Date.now() - availabilityCache.at < 600_000) {
|
|
166
|
+
return { status: 'ok', checkedAt: availabilityCache.at, engines: availabilityCache.rows };
|
|
167
|
+
}
|
|
168
|
+
const rows = await Promise.all(ENGINES.map((engine) => probeEngineAvailability(engine, localTransport())));
|
|
169
|
+
availabilityCache = { at: Date.now(), rows };
|
|
170
|
+
return { status: 'ok', checkedAt: availabilityCache.at, engines: rows };
|
|
171
|
+
});
|
|
172
|
+
// The engine's OWN model catalog (ADR-0045 §5). Strata ships its family table
|
|
173
|
+
// in the installed control bundle; an engine without one answers
|
|
174
|
+
// `catalog: null` and the console renders no catalog tab. The read runs the
|
|
175
|
+
// bundle's interpreter, so it is cached by the bundle's mtime inside the
|
|
176
|
+
// runtime — a reinstalled engine re-reads on the next request. `ramGb` /
|
|
177
|
+
// `vramGb` are the console's detected machine facts: the ENGINE projects its
|
|
178
|
+
// own VRAM use and fit verdict from them (the gateway never estimates).
|
|
179
|
+
app.get('/api/admin/local-models/engines/:id/catalog', async (req, reply) => {
|
|
180
|
+
const engine = engineById(String(req.params.id ?? ''));
|
|
181
|
+
if (!engine)
|
|
182
|
+
return reply.status(404).send({ status: 'error', message: 'unknown engine' });
|
|
183
|
+
const query = (req.query ?? {});
|
|
184
|
+
const num = (raw) => {
|
|
185
|
+
const value = Number(raw);
|
|
186
|
+
return raw != null && raw !== '' && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
187
|
+
};
|
|
188
|
+
const ramGb = num(query.ramGb);
|
|
189
|
+
const vramGb = num(query.vramGb);
|
|
190
|
+
let catalog = null;
|
|
191
|
+
try {
|
|
192
|
+
catalog = engine.runtime?.catalog?.({
|
|
193
|
+
...(ramGb != null ? { ramGb } : {}),
|
|
194
|
+
...(vramGb != null ? { vramGb } : {}),
|
|
195
|
+
}) ?? null;
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
return { status: 'ok', catalog: null, message: err instanceof Error ? err.message : 'catalog read failed' };
|
|
199
|
+
}
|
|
200
|
+
if (!catalog) {
|
|
201
|
+
// The catalog is read OUT of the installed engine bundle, so a machine
|
|
202
|
+
// that has not installed the engine yet has nothing to read. Say WHICH
|
|
203
|
+
// step is missing instead of "this engine ships no catalog" (the two
|
|
204
|
+
// states send the operator to different pages) — as a CODE, not prose:
|
|
205
|
+
// this reaches the console as a rendered sentence, and that sentence is
|
|
206
|
+
// translated there (`localModels.catalogNeedsInstall`).
|
|
207
|
+
const installed = installedEnginesFor(engine.id).length > 0;
|
|
208
|
+
return {
|
|
209
|
+
status: 'ok',
|
|
210
|
+
catalog: null,
|
|
211
|
+
...(installed ? {} : { code: 'engine-not-installed' }),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
// Per-entry installability, resolved HERE for the console: the engine's own
|
|
215
|
+
// catalog declares WHAT a size needs (`minEngine`, `requires`), the gateway
|
|
216
|
+
// checks it against this machine and this install. Kept out of `catalog`
|
|
217
|
+
// so the engine's declared data stays exactly what the engine said.
|
|
218
|
+
const machine = summarizeDetect(await cachedDetect());
|
|
219
|
+
const engineVersion = installedEngineVersion(engine.id);
|
|
220
|
+
const gates = {};
|
|
221
|
+
for (const family of catalog.families) {
|
|
222
|
+
const rows = {};
|
|
223
|
+
for (const model of family.models) {
|
|
224
|
+
const gate = catalogModelGate(model, { ...(engineVersion ? { engineVersion } : {}), machine });
|
|
225
|
+
if (!gate.ok)
|
|
226
|
+
rows[model.id] = gate;
|
|
227
|
+
}
|
|
228
|
+
if (Object.keys(rows).length > 0)
|
|
229
|
+
gates[family.id] = rows;
|
|
230
|
+
}
|
|
231
|
+
return { status: 'ok', catalog, gates };
|
|
232
|
+
});
|
|
233
|
+
// Install one catalog model: the engine's pinned files, at the engine's
|
|
234
|
+
// commit, verified against the engine's own digests. Streaming NDJSON, one leg
|
|
235
|
+
// per repo anchor file, so two sizes download side by side and the market's
|
|
236
|
+
// transfer strip can cancel either.
|
|
237
|
+
app.post('/api/admin/local-models/engines/:id/catalog/download', async (req, reply) => {
|
|
238
|
+
const engine = engineById(String(req.params.id ?? ''));
|
|
239
|
+
if (!engine)
|
|
240
|
+
return reply.status(404).send({ status: 'error', message: 'unknown engine' });
|
|
241
|
+
const catalog = engine.runtime?.catalog?.() ?? null;
|
|
242
|
+
if (!catalog) {
|
|
243
|
+
// Same distinction as the read route: "engine not installed yet" is a
|
|
244
|
+
// different fix from "this engine ships no catalog".
|
|
245
|
+
const installed = installedEnginesFor(engine.id).length > 0;
|
|
246
|
+
return installed
|
|
247
|
+
? reply.status(404).send({ status: 'error', code: 'no-catalog', message: 'this engine ships no model catalog' })
|
|
248
|
+
: reply.status(409).send({
|
|
249
|
+
status: 'error',
|
|
250
|
+
code: 'engine-not-installed',
|
|
251
|
+
message: `install ${engine.name} first: its catalog and its tooling come from the engine bundle`,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
const body = (req.body ?? {});
|
|
255
|
+
const familyId = typeof body.family === 'string' ? body.family : '';
|
|
256
|
+
const modelId = typeof body.model === 'string' ? body.model : '';
|
|
257
|
+
const family = catalog.families.find((row) => row.id === familyId);
|
|
258
|
+
if (!family)
|
|
259
|
+
return reply.status(400).send({ status: 'error', message: `unknown catalog family '${familyId}'` });
|
|
260
|
+
const model = family.models.find((row) => row.id === modelId);
|
|
261
|
+
if (!model)
|
|
262
|
+
return reply.status(400).send({ status: 'error', message: `unknown catalog model '${modelId}'` });
|
|
263
|
+
// Every layout is installable: a family the engine reads in place needs only
|
|
264
|
+
// its GGUF (the tokenizer is prepared by the build), a ready-pack family
|
|
265
|
+
// needs its pinned files in their roles (the download IS the placement), and
|
|
266
|
+
// `gguf-pack` downloads GGUF shards for the packer. What differs is the
|
|
267
|
+
// ANCHOR the registry row points at — resolved once by the catalog reader
|
|
268
|
+
// (`model.anchor`), so this route and the console cannot disagree.
|
|
269
|
+
const anchorPath = model.anchor ?? (model.files.find((file) => file.role === 'dense') ?? model.files[0]).path;
|
|
270
|
+
const anchor = model.files.find((file) => file.path === anchorPath) ?? model.files[0];
|
|
271
|
+
// What the size NEEDS is the catalog's declaration, checked against this
|
|
272
|
+
// machine and this install BEFORE the transfer starts: an NVFP4 size is a
|
|
273
|
+
// 129 GB download an AMD or outdated engine would refuse only at start.
|
|
274
|
+
const engineVersion = installedEngineVersion(engine.id);
|
|
275
|
+
const gate = catalogModelGate(model, {
|
|
276
|
+
...(engineVersion ? { engineVersion } : {}),
|
|
277
|
+
machine: summarizeDetect(await cachedDetect()),
|
|
278
|
+
});
|
|
279
|
+
if (!gate.ok) {
|
|
280
|
+
return reply.status(409).send({
|
|
281
|
+
status: 'error',
|
|
282
|
+
code: 'catalog-not-installable',
|
|
283
|
+
gate,
|
|
284
|
+
message: `this size cannot run on this machine or on the installed ${engine.name}: ${gate.code}${gate.param ? ` (${gate.param})` : ''}`,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
reply.hijack();
|
|
288
|
+
const raw = reply.raw;
|
|
289
|
+
raw.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store' });
|
|
290
|
+
const leg = `model:${model.repo}/${anchor.path}`;
|
|
291
|
+
const t = startEngineTransfer(raw, leg);
|
|
292
|
+
let lastProgress = 0;
|
|
293
|
+
try {
|
|
294
|
+
const onEvent = (event) => {
|
|
295
|
+
if (event.type === 'progress') {
|
|
296
|
+
const now = Date.now();
|
|
297
|
+
if (now - lastProgress < 100 && event.downloaded !== event.total)
|
|
298
|
+
return;
|
|
299
|
+
lastProgress = now;
|
|
300
|
+
}
|
|
301
|
+
t.send(modelEventToPayload(event));
|
|
302
|
+
};
|
|
303
|
+
const result = await downloadCatalogModel({
|
|
304
|
+
repo: model.repo,
|
|
305
|
+
...(model.revision ? { revision: model.revision } : {}),
|
|
306
|
+
files: model.files,
|
|
307
|
+
anchor: anchor.path,
|
|
308
|
+
...(model.mmproj ? { mmproj: model.mmproj } : {}),
|
|
309
|
+
signal: t.signal,
|
|
310
|
+
onEvent,
|
|
311
|
+
});
|
|
312
|
+
// Close the loop: "downloaded" is not "runnable". A model whose launch
|
|
313
|
+
// input the ENGINE derives (a pack, or the in-place tokenizer) is prepared
|
|
314
|
+
// right here, so download → prepare → run needs no third click. A refused
|
|
315
|
+
// start is REPORTED, never silent: the operator can always start it by hand
|
|
316
|
+
// (the model stays `buildable`, so its Pack button is still there), which is
|
|
317
|
+
// the retry path when a long pack dies halfway.
|
|
318
|
+
const prepare = result.ok
|
|
319
|
+
? await prepareAfterDownload({ id: result.installed.id, filePath: result.installed.filePath }, engine.id)
|
|
320
|
+
: undefined;
|
|
321
|
+
t.send({
|
|
322
|
+
type: 'result',
|
|
323
|
+
status: result.ok ? 'ok' : 'error',
|
|
324
|
+
...(result.ok
|
|
325
|
+
? { installed: result.installed, resumedFrom: result.resumedFrom, ...(prepare ? { prepare } : {}) }
|
|
326
|
+
: { code: result.code, error: result.error }),
|
|
327
|
+
});
|
|
328
|
+
if (result.ok)
|
|
329
|
+
requestPoolRefresh();
|
|
330
|
+
}
|
|
331
|
+
catch (err) {
|
|
332
|
+
const aborted = t.signal.aborted;
|
|
333
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
334
|
+
t.send({ type: 'result', status: 'error', code: aborted ? 'download-aborted' : 'install-failed', error: aborted ? 'download cancelled' : message });
|
|
335
|
+
}
|
|
336
|
+
t.finish();
|
|
337
|
+
});
|
|
338
|
+
// Recent release tags for the version picker. llama.cpp walks its prerelease
|
|
339
|
+
// stream; Strata has one stable channel, so a single tag comes back.
|
|
340
|
+
app.get('/api/admin/local-models/engines/:id/releases', async (req, reply) => {
|
|
341
|
+
const engine = engineById(String(req.params.id ?? ''));
|
|
342
|
+
if (!engine)
|
|
343
|
+
return reply.status(404).send({ status: 'error', message: 'unknown engine' });
|
|
344
|
+
try {
|
|
345
|
+
// Version choice is the engine's business: a nightly-tag engine ships
|
|
346
|
+
// `listTags`, a single-channel engine answers with its one release tag.
|
|
347
|
+
const tags = engine.listTags
|
|
348
|
+
? await engine.listTags(localTransport())
|
|
349
|
+
: [(await engine.resolveRelease(localTransport())).tag];
|
|
350
|
+
return { status: 'ok', tags };
|
|
351
|
+
}
|
|
352
|
+
catch (err) {
|
|
353
|
+
const message = err instanceof Error ? err.message : 'release lookup failed';
|
|
354
|
+
return { status: 'error', message };
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
// Streaming install. One NDJSON leg per engine, so a llama.cpp download and
|
|
358
|
+
// a Strata download can run side by side while two clicks on the SAME engine
|
|
359
|
+
// serialise inside the installer's lock.
|
|
360
|
+
app.post('/api/admin/local-models/engines/:id/install', async (req, reply) => {
|
|
361
|
+
const engineId = String(req.params.id ?? '');
|
|
362
|
+
const engine = engineById(engineId);
|
|
363
|
+
if (!engine) {
|
|
364
|
+
return reply.status(404).send({ status: 'error', message: 'unknown engine' });
|
|
365
|
+
}
|
|
366
|
+
const body = (req.body ?? {});
|
|
367
|
+
const target = typeof body.target === 'string' && body.target.trim() ? body.target.trim() : undefined;
|
|
368
|
+
const version = typeof body.version === 'string' && body.version.trim() ? body.version.trim() : undefined;
|
|
369
|
+
// A build the machine cannot run is a 500 MB download that dies at launch:
|
|
370
|
+
// the engine declares what each target needs (`requires`), the dependency
|
|
371
|
+
// probe answers it, and a mismatch is refused HERE. A probe that could not
|
|
372
|
+
// run at all is a soft failure — offline machines keep every chip usable
|
|
373
|
+
// (the same rule the release-availability probe follows).
|
|
374
|
+
const targets = engine.targets(process.platform, process.arch);
|
|
375
|
+
const wanted = targets.find((row) => row.id === (target ?? targets[0]?.id));
|
|
376
|
+
if (wanted && wanted.requires.length > 0) {
|
|
377
|
+
try {
|
|
378
|
+
const report = await cachedDetect();
|
|
379
|
+
const okDeps = new Set(report.checks.filter((check) => check.ok).map((check) => check.id));
|
|
380
|
+
// Only requirements the probe actually answered can veto: a check the
|
|
381
|
+
// platform never produces (`intel-sycl` on a machine without the tool)
|
|
382
|
+
// still reports `ok: false`, which IS an answer.
|
|
383
|
+
const missing = wanted.requires.filter((dep) => !okDeps.has(dep));
|
|
384
|
+
if (missing.length > 0) {
|
|
385
|
+
return reply.status(409).send({
|
|
386
|
+
status: 'error',
|
|
387
|
+
code: 'target-requirements-unmet',
|
|
388
|
+
missing,
|
|
389
|
+
message: `the ${wanted.label} build needs ${missing.join(', ')}, which this machine does not report — pick another target or install the runtime first`,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
// No probe answer: never block on an unknown.
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
reply.hijack();
|
|
398
|
+
const raw = reply.raw;
|
|
399
|
+
raw.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store' });
|
|
400
|
+
// The leg names the engine AND the build target: a CUDA install and a CPU
|
|
401
|
+
// install of the same engine are independent transfers.
|
|
402
|
+
const leg = `engine:${engineId}:${target ?? 'auto'}`;
|
|
403
|
+
const t = startEngineTransfer(raw, leg);
|
|
404
|
+
let lastProgress = 0;
|
|
405
|
+
try {
|
|
406
|
+
const result = await installEngine({
|
|
407
|
+
engineId,
|
|
408
|
+
...(target ? { target } : {}),
|
|
409
|
+
...(version ? { version } : {}),
|
|
410
|
+
signal: t.signal,
|
|
411
|
+
onEvent: (event) => {
|
|
412
|
+
// Coalesce byte ticks to one per 100ms; stage events always pass.
|
|
413
|
+
if (event.type === 'progress') {
|
|
414
|
+
const now = Date.now();
|
|
415
|
+
if (now - lastProgress < 100 && event.downloaded !== event.total)
|
|
416
|
+
return;
|
|
417
|
+
lastProgress = now;
|
|
418
|
+
}
|
|
419
|
+
t.send(installEventToPayload(event));
|
|
420
|
+
},
|
|
421
|
+
});
|
|
422
|
+
// The upgrade sweep runs BEFORE the result goes out, so a `refresh()`
|
|
423
|
+
// triggered by that result can never resurrect the old version row: by
|
|
424
|
+
// then the record and the directory agree.
|
|
425
|
+
// Verdicts read the runtime the install just wrote. A list that ran
|
|
426
|
+
// while `serve/server.py` was still absent stays on that refusal until
|
|
427
|
+
// something re-derives it (ADR-0045 §13).
|
|
428
|
+
if (result.ok)
|
|
429
|
+
rescanInstalledModels();
|
|
430
|
+
if (result.ok && result.supersededDir) {
|
|
431
|
+
// The usage probe is async (it health-checks live runs), so the
|
|
432
|
+
// decision is resolved here and handed over: the sweep itself stays
|
|
433
|
+
// synchronous and completes before the result is reported.
|
|
434
|
+
const keep = await engineDirInUse(path.resolve(result.supersededDir));
|
|
435
|
+
pruneSupersededInstall(result.supersededDir, () => keep);
|
|
436
|
+
}
|
|
437
|
+
// `supersededDir` is internal housekeeping (the console renders only
|
|
438
|
+
// `installed`), so it never rides the wire.
|
|
439
|
+
const payload = { ...result };
|
|
440
|
+
delete payload.supersededDir;
|
|
441
|
+
t.send({ type: 'result', status: result.ok ? 'ok' : 'error', ...payload });
|
|
442
|
+
}
|
|
443
|
+
catch (err) {
|
|
444
|
+
const aborted = t.signal.aborted;
|
|
445
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
446
|
+
t.send({ type: 'result', status: 'error', ok: false, code: aborted ? 'download-aborted' : 'install-failed', error: aborted ? 'download cancelled' : message });
|
|
447
|
+
}
|
|
448
|
+
t.finish();
|
|
449
|
+
});
|
|
450
|
+
// Cancel a transfer the operator walked away from (keepalive fetch on page
|
|
451
|
+
// leave). The .part files stay staged; the next click resumes.
|
|
452
|
+
app.post('/api/admin/local-models/engines/transfers/cancel', async (req) => {
|
|
453
|
+
const leg = typeof req.body?.leg === 'string'
|
|
454
|
+
? req.body.leg
|
|
455
|
+
: '';
|
|
456
|
+
const controller = liveTransfers.get(leg);
|
|
457
|
+
if (!controller)
|
|
458
|
+
return { status: 'ok', cancelled: false };
|
|
459
|
+
controller.abort(new Error('cancelled by the console'));
|
|
460
|
+
return { status: 'ok', cancelled: true };
|
|
461
|
+
});
|
|
462
|
+
app.delete('/api/admin/local-models/engines/:id', async (req, reply) => {
|
|
463
|
+
const engineId = String(req.params.id ?? '');
|
|
464
|
+
if (!engineById(engineId)) {
|
|
465
|
+
return reply.status(404).send({ status: 'error', message: 'unknown engine' });
|
|
466
|
+
}
|
|
467
|
+
const target = String(req.query.target ?? '').trim();
|
|
468
|
+
if (!target) {
|
|
469
|
+
return reply.status(400).send({ status: 'error', message: 'target is required (an engine may have several installs)' });
|
|
470
|
+
}
|
|
471
|
+
// A build a LIVE run is serving must not be deleted: its record names the
|
|
472
|
+
// ABSOLUTE binary path, so a run started from this directory would keep a
|
|
473
|
+
// process alive (POSIX: on an unlinked binary, unrestartable) while the
|
|
474
|
+
// console can no longer see the install it came from. Same rule the model
|
|
475
|
+
// delete applies to weights, and the same helper the upgrade sweep uses.
|
|
476
|
+
const record = installedEngineFor(engineId, target);
|
|
477
|
+
if (record && await engineBuildInUse(path.resolve(record.installDir))) {
|
|
478
|
+
return reply.status(409).send({
|
|
479
|
+
status: 'error',
|
|
480
|
+
code: 'engine-in-use',
|
|
481
|
+
message: 'a run is using this build; stop it before uninstalling the engine',
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
const result = uninstallEngine(engineId, target);
|
|
485
|
+
if (!result.ok)
|
|
486
|
+
return reply.status(400).send({ status: 'error', message: result.error ?? 'uninstall failed' });
|
|
487
|
+
return { status: 'ok' };
|
|
488
|
+
});
|
|
489
|
+
// ---- HuggingFace marketplace ------------------------------------------
|
|
490
|
+
// Model-card search (GGUF-serving repos, most-downloaded first). Failures
|
|
491
|
+
// degrade to an empty list + message instead of a 5xx: a rate-limited Hub
|
|
492
|
+
// must still render the rest of the page.
|
|
493
|
+
app.get('/api/admin/local-models/hf/search', async (req) => {
|
|
494
|
+
const query = String(req.query.q ?? '');
|
|
495
|
+
const limit = Number(req.query.limit ?? 24);
|
|
496
|
+
try {
|
|
497
|
+
const models = await searchHfModels(query, Number.isFinite(limit) ? limit : 24);
|
|
498
|
+
return { status: 'ok', models, endpoint: hfEndpoint() };
|
|
499
|
+
}
|
|
500
|
+
catch (err) {
|
|
501
|
+
return { status: 'ok', models: [], endpoint: hfEndpoint(), message: err instanceof Error ? err.message : 'search failed' };
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
// The file tree of one repo: every GGUF with real byte size + LFS sha256,
|
|
505
|
+
// which the quant picker and the download verifier both need. Split-weight
|
|
506
|
+
// shards collapse into ONE entry anchored at shard 1 (`shardCount` + the
|
|
507
|
+
// `parts` list the group download sends back) with the summed byte size —
|
|
508
|
+
// a shard is never a downloadable unit of its own.
|
|
509
|
+
app.get('/api/admin/local-models/hf/model', async (req, reply) => {
|
|
510
|
+
const repo = String(req.query.id ?? '');
|
|
511
|
+
if (!isValidRepoId(repo)) {
|
|
512
|
+
return reply.status(400).send({ status: 'error', message: 'invalid model id' });
|
|
513
|
+
}
|
|
514
|
+
try {
|
|
515
|
+
const files = await fetchHfModelFiles(repo);
|
|
516
|
+
const grouped = groupHfShards(files).map((group) => {
|
|
517
|
+
if (group.parts.length === 1)
|
|
518
|
+
return group.primary;
|
|
519
|
+
const { sha256: _shardSha, ...primary } = group.primary;
|
|
520
|
+
return {
|
|
521
|
+
...primary,
|
|
522
|
+
size: group.totalSize,
|
|
523
|
+
shardCount: group.parts.length,
|
|
524
|
+
parts: group.parts.map((part) => ({ path: part.path, size: part.size, ...(part.sha256 ? { sha256: part.sha256 } : {}) })),
|
|
525
|
+
};
|
|
526
|
+
});
|
|
527
|
+
return { status: 'ok', repo, files: grouped };
|
|
528
|
+
}
|
|
529
|
+
catch (err) {
|
|
530
|
+
return reply.status(502).send({ status: 'error', message: err instanceof Error ? err.message : 'tree lookup failed' });
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
// Installed model list + disk usage in one read (the management card).
|
|
534
|
+
// `diskUsageBytes` counts the whole tree (staged `.part` files included);
|
|
535
|
+
// `partialBytes` is the share an interrupted download staged and the
|
|
536
|
+
// retention sweep will reclaim.
|
|
537
|
+
app.get('/api/admin/local-models/models', async () => {
|
|
538
|
+
return {
|
|
539
|
+
status: 'ok',
|
|
540
|
+
models: listInstalledModels(),
|
|
541
|
+
diskUsageBytes: modelsDiskUsage(),
|
|
542
|
+
partialBytes: modelPartBytes(),
|
|
543
|
+
};
|
|
544
|
+
});
|
|
545
|
+
// Streaming model download. One NDJSON leg per file (`model:<repo>/<file>`)
|
|
546
|
+
// so several quant downloads run side by side; cancel goes through the
|
|
547
|
+
// shared transfers map (the /engines/transfers/cancel route above). The
|
|
548
|
+
// caller passes the tree API's size + LFS sha256 so a finished download is
|
|
549
|
+
// verified before it becomes a registry row (spliced resume is refused).
|
|
550
|
+
// A split-weight model arrives as `files` (every shard, shard 1 first) and
|
|
551
|
+
// registers ONE row anchored at shard 1; the leg names that anchor.
|
|
552
|
+
app.post('/api/admin/local-models/models/download', async (req, reply) => {
|
|
553
|
+
const body = (req.body ?? {});
|
|
554
|
+
const repo = typeof body.repo === 'string' ? body.repo : '';
|
|
555
|
+
const filename = typeof body.filename === 'string' ? body.filename : '';
|
|
556
|
+
const groupParts = Array.isArray(body.files)
|
|
557
|
+
? body.files
|
|
558
|
+
.map((part) => {
|
|
559
|
+
const row = (part ?? {});
|
|
560
|
+
return {
|
|
561
|
+
path: typeof row.path === 'string' ? row.path : '',
|
|
562
|
+
size: typeof row.size === 'number' && Number.isFinite(row.size) && row.size > 0 ? row.size : undefined,
|
|
563
|
+
sha256: typeof row.sha256 === 'string' && /^[0-9a-f]{64}$/i.test(row.sha256) ? row.sha256.toLowerCase() : undefined,
|
|
564
|
+
};
|
|
565
|
+
})
|
|
566
|
+
.filter((part) => part.path)
|
|
567
|
+
: [];
|
|
568
|
+
if (!repo || (groupParts.length < 2 && !filename)) {
|
|
569
|
+
return reply.status(400).send({ status: 'error', message: 'repo and filename (or files) are required' });
|
|
570
|
+
}
|
|
571
|
+
const size = typeof body.size === 'number' && Number.isFinite(body.size) && body.size > 0 ? body.size : undefined;
|
|
572
|
+
const sha256 = typeof body.sha256 === 'string' && /^[0-9a-f]{64}$/i.test(body.sha256) ? body.sha256.toLowerCase() : undefined;
|
|
573
|
+
reply.hijack();
|
|
574
|
+
const raw = reply.raw;
|
|
575
|
+
raw.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store' });
|
|
576
|
+
const anchor = groupParts.length >= 2 ? groupParts[0].path : filename;
|
|
577
|
+
const leg = `model:${repo}/${anchor}`;
|
|
578
|
+
const t = startEngineTransfer(raw, leg);
|
|
579
|
+
let lastProgress = 0;
|
|
580
|
+
try {
|
|
581
|
+
const onEvent = (event) => {
|
|
582
|
+
if (event.type === 'progress') {
|
|
583
|
+
const now = Date.now();
|
|
584
|
+
if (now - lastProgress < 100 && event.downloaded !== event.total)
|
|
585
|
+
return;
|
|
586
|
+
lastProgress = now;
|
|
587
|
+
}
|
|
588
|
+
t.send(modelEventToPayload(event));
|
|
589
|
+
};
|
|
590
|
+
const result = groupParts.length >= 2
|
|
591
|
+
? await downloadHfModelGroup({ repo, parts: groupParts, signal: t.signal, onEvent })
|
|
592
|
+
: await downloadHfModel({
|
|
593
|
+
repo,
|
|
594
|
+
filename,
|
|
595
|
+
...(size != null ? { size } : {}),
|
|
596
|
+
...(sha256 ? { sha256 } : {}),
|
|
597
|
+
signal: t.signal,
|
|
598
|
+
onEvent,
|
|
599
|
+
});
|
|
600
|
+
t.send({
|
|
601
|
+
type: 'result',
|
|
602
|
+
status: result.ok ? 'ok' : 'error',
|
|
603
|
+
...(result.ok
|
|
604
|
+
? { installed: result.installed, resumedFrom: result.resumedFrom }
|
|
605
|
+
: { code: result.code, error: result.error }),
|
|
606
|
+
});
|
|
607
|
+
// A new row is a new routable `local/<id>` (ADR-0044 §6) — resync now so
|
|
608
|
+
// /v1/models and the pool see it without a restart.
|
|
609
|
+
if (result.ok)
|
|
610
|
+
requestPoolRefresh();
|
|
611
|
+
}
|
|
612
|
+
catch (err) {
|
|
613
|
+
const aborted = t.signal.aborted;
|
|
614
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
615
|
+
t.send({ type: 'result', status: 'error', code: aborted ? 'download-aborted' : 'install-failed', error: aborted ? 'download cancelled' : message });
|
|
616
|
+
}
|
|
617
|
+
t.finish();
|
|
618
|
+
});
|
|
619
|
+
// Import .gguf files that already exist on this machine. `path` is one file
|
|
620
|
+
// or a directory (walked shallowly); records point at the original files —
|
|
621
|
+
// nothing is copied, and deleting an imported row keeps the file on disk.
|
|
622
|
+
app.post('/api/admin/local-models/models/import', async (req, reply) => {
|
|
623
|
+
const body = (req.body ?? {});
|
|
624
|
+
const target = typeof body.path === 'string' ? body.path.trim() : '';
|
|
625
|
+
if (!target) {
|
|
626
|
+
return reply.status(400).send({ status: 'error', message: 'path is required' });
|
|
627
|
+
}
|
|
628
|
+
const result = importLocalModels(target);
|
|
629
|
+
if (result.imported.length > 0)
|
|
630
|
+
requestPoolRefresh();
|
|
631
|
+
return {
|
|
632
|
+
status: 'ok',
|
|
633
|
+
imported: result.imported,
|
|
634
|
+
skipped: result.skipped,
|
|
635
|
+
errors: result.errors,
|
|
636
|
+
};
|
|
637
|
+
});
|
|
638
|
+
// Re-pair every installed model with the drafters on disk. Import and
|
|
639
|
+
// download already do this; the button repeats it after a draft file arrives.
|
|
640
|
+
app.post('/api/admin/local-models/models/drafts/detect', async () => ({
|
|
641
|
+
status: 'ok',
|
|
642
|
+
models: refreshDraftMatches(),
|
|
643
|
+
}));
|
|
644
|
+
app.delete('/api/admin/local-models/models/:id', async (req, reply) => {
|
|
645
|
+
const id = String(req.params.id ?? '');
|
|
646
|
+
// Deleting under a LIVE engine is worse than disabling under one: the
|
|
647
|
+
// process keeps running from weights this route is about to unlink (on
|
|
648
|
+
// Windows the delete fails with EBUSY; on POSIX it succeeds against an
|
|
649
|
+
// unlinked inode), and the run record is left pointing at a model that no
|
|
650
|
+
// longer exists — visible in the monitor, impossible to restart. The
|
|
651
|
+
// enable/disable switch already refuses this state for the same reason.
|
|
652
|
+
if (activeRunFor(id)) {
|
|
653
|
+
return reply.status(409).send({
|
|
654
|
+
status: 'error',
|
|
655
|
+
code: 'run-live',
|
|
656
|
+
message: 'the model has a live run; stop it before removing it',
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
const result = removeHfModel(id);
|
|
660
|
+
if (!result.ok) {
|
|
661
|
+
return { status: 'error', message: result.error ?? 'remove failed' };
|
|
662
|
+
}
|
|
663
|
+
// The model universe is part of the routable pool (ADR-0044 §6): drop the
|
|
664
|
+
// `local/<id>` registration now instead of at the next restart.
|
|
665
|
+
requestPoolRefresh();
|
|
666
|
+
return { status: 'ok' };
|
|
667
|
+
});
|
|
668
|
+
// ---- Operator launch profiles (ADR-0044 §4 → ADR-0045) ----------------
|
|
669
|
+
// Some engines' command lines need inputs no GGUF header carries (Strata: a
|
|
670
|
+
// compiled pack, the MTP draft head, optionally a PLE table and an expert
|
|
671
|
+
// binary), so the profile is operator data stored ON the model record, keyed
|
|
672
|
+
// by engine. The engine's runtime owns validation; this route is a transport.
|
|
673
|
+
// Setting one is what turns a family-matching engine from a badge into a
|
|
674
|
+
// runnable choice.
|
|
675
|
+
const putProfile = async (req, reply, engineId) => {
|
|
676
|
+
const id = String(req.params.id ?? '');
|
|
677
|
+
if (!engineById(engineId)) {
|
|
678
|
+
return reply.status(404).send({ status: 'error', message: `unknown engine '${engineId}'` });
|
|
679
|
+
}
|
|
680
|
+
const body = (req.body ?? {});
|
|
681
|
+
const raw = body.profile ?? req.body;
|
|
682
|
+
const result = setEngineProfile(id, engineId, raw);
|
|
683
|
+
if (!result.ok) {
|
|
684
|
+
return reply.status(400).send({ status: 'error', code: result.code, message: result.error });
|
|
685
|
+
}
|
|
686
|
+
requestPoolRefresh();
|
|
687
|
+
return { status: 'ok', model: result.model };
|
|
688
|
+
};
|
|
689
|
+
const deleteProfile = async (req, engineId) => {
|
|
690
|
+
const id = String(req.params.id ?? '');
|
|
691
|
+
const result = setEngineProfile(id, engineId, null);
|
|
692
|
+
if (!result.ok)
|
|
693
|
+
return { status: 'error', code: result.code, message: result.error };
|
|
694
|
+
requestPoolRefresh();
|
|
695
|
+
return { status: 'ok', model: result.model };
|
|
696
|
+
};
|
|
697
|
+
app.put('/api/admin/local-models/models/:id/profiles/:engine', async (req, reply) => putProfile(req, reply, String(req.params.engine ?? '')));
|
|
698
|
+
app.delete('/api/admin/local-models/models/:id/profiles/:engine', async (req) => deleteProfile(req, String(req.params.engine ?? '')));
|
|
699
|
+
// Strata's original spelling, kept so an older console build keeps working.
|
|
700
|
+
app.put('/api/admin/local-models/models/:id/strata', async (req, reply) => putProfile(req, reply, 'strata'));
|
|
701
|
+
app.delete('/api/admin/local-models/models/:id/strata', async (req) => deleteProfile(req, 'strata'));
|
|
702
|
+
// ---- Operator model name (ADR-0044 §7) ---------------------------------
|
|
703
|
+
// The name becomes the tail of the gateway id: `local/<name>` instead of
|
|
704
|
+
// `local/<repo>/<file>`. Renaming (or clearing) RETIRES the old id, so the
|
|
705
|
+
// answer names every config spot still pointing at it — tier member pins,
|
|
706
|
+
// combos, key policies, gateway-internal model picks. Nothing is rewritten:
|
|
707
|
+
// the operator moves those references deliberately (loud, never silent).
|
|
708
|
+
app.put('/api/admin/local-models/models/:id/name', async (req, reply) => {
|
|
709
|
+
const id = String(req.params.id ?? '');
|
|
710
|
+
const body = (req.body ?? {});
|
|
711
|
+
const before = readInstalledModels()[id];
|
|
712
|
+
if (!before)
|
|
713
|
+
return reply.status(404).send({ status: 'error', message: 'model is not installed' });
|
|
714
|
+
const previousGatewayId = localModelId(before);
|
|
715
|
+
const result = setModelName(id, body.name);
|
|
716
|
+
if (!result.ok) {
|
|
717
|
+
return reply.status(400).send({ status: 'error', code: result.code, message: result.error });
|
|
718
|
+
}
|
|
719
|
+
const gatewayId = localModelId(result.model);
|
|
720
|
+
const references = [];
|
|
721
|
+
if (gatewayId !== previousGatewayId) {
|
|
722
|
+
const config = loadConfig();
|
|
723
|
+
for (const tier of ['lite', 'plus', 'pro', 'ultra']) {
|
|
724
|
+
for (const rule of config.tiers?.[tier]?.members ?? []) {
|
|
725
|
+
if (rule.pattern === previousGatewayId)
|
|
726
|
+
references.push({ kind: 'tier', ref: `${tier}: ${rule.pattern}` });
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
for (const pattern of config.tiers?.exclude ?? []) {
|
|
730
|
+
if (pattern === previousGatewayId)
|
|
731
|
+
references.push({ kind: 'tier', ref: `exclude: ${pattern}` });
|
|
732
|
+
}
|
|
733
|
+
for (const combo of config.combos ?? []) {
|
|
734
|
+
const hit = combo.models.some((member) => (typeof member === 'string' ? member : member.id) === previousGatewayId);
|
|
735
|
+
if (hit)
|
|
736
|
+
references.push({ kind: 'combo', ref: combo.id });
|
|
737
|
+
}
|
|
738
|
+
for (const key of config.apiKeys ?? []) {
|
|
739
|
+
if (key.modelAccess?.models?.includes(previousGatewayId)) {
|
|
740
|
+
references.push({ kind: 'key', ref: `${key.name} (${key.id})` });
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
if (config.classifier?.layer2?.model === previousGatewayId)
|
|
744
|
+
references.push({ kind: 'setting', ref: 'classifier.layer2.model' });
|
|
745
|
+
if (config.systemone?.defaultModel === previousGatewayId)
|
|
746
|
+
references.push({ kind: 'setting', ref: 'systemone.defaultModel' });
|
|
747
|
+
if (config.defaultModels?.translation === previousGatewayId)
|
|
748
|
+
references.push({ kind: 'setting', ref: 'defaultModels.translation' });
|
|
749
|
+
}
|
|
750
|
+
// The registration id changed: the pool must re-list this model under the
|
|
751
|
+
// new `local/<name>` now, not at the next restart (ADR-0044 §6).
|
|
752
|
+
requestPoolRefresh();
|
|
753
|
+
return {
|
|
754
|
+
status: 'ok',
|
|
755
|
+
model: result.model,
|
|
756
|
+
gatewayId,
|
|
757
|
+
...(gatewayId !== previousGatewayId ? { previousGatewayId } : {}),
|
|
758
|
+
references,
|
|
759
|
+
};
|
|
760
|
+
});
|
|
761
|
+
// ---- Operator enable/disable switch ------------------------------------
|
|
762
|
+
// `enabled: false` retires the gateway id (`local/<…>`) but keeps the file
|
|
763
|
+
// and the registry row: /v1/models omits it, no client can address it, and
|
|
764
|
+
// the run page no longer offers it. A model with a LIVE run is refused —
|
|
765
|
+
// disabling would orphan an adopted engine the stop button then cannot see.
|
|
766
|
+
app.put('/api/admin/local-models/models/:id/enabled', async (req, reply) => {
|
|
767
|
+
const id = String(req.params.id ?? '');
|
|
768
|
+
const body = (req.body ?? {});
|
|
769
|
+
// Explicit boolean only: a typo (`{enabled: "false"}`, `{}`) must not read
|
|
770
|
+
// as `false` and silently unregister a model's gateway id.
|
|
771
|
+
if (typeof body.enabled !== 'boolean') {
|
|
772
|
+
return reply.status(400).send({ status: 'error', code: 'invalid-body', message: '`enabled` must be true or false' });
|
|
773
|
+
}
|
|
774
|
+
const enabled = body.enabled;
|
|
775
|
+
const record = readInstalledModels()[id];
|
|
776
|
+
if (!record)
|
|
777
|
+
return reply.status(404).send({ status: 'error', message: 'model is not installed' });
|
|
778
|
+
if (!enabled && activeRunFor(id)) {
|
|
779
|
+
return reply.status(409).send({
|
|
780
|
+
status: 'error',
|
|
781
|
+
code: 'run-live',
|
|
782
|
+
message: 'the model has a live run; stop it before disabling',
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
const result = setModelEnabled(id, enabled);
|
|
786
|
+
if (!result.ok) {
|
|
787
|
+
return reply.status(400).send({ status: 'error', code: result.code, message: result.error });
|
|
788
|
+
}
|
|
789
|
+
requestPoolRefresh();
|
|
790
|
+
return { status: 'ok', model: result.model };
|
|
791
|
+
});
|
|
792
|
+
// ---- Settings (mirror / token / storage dir) ---------------------------
|
|
793
|
+
// One read for the settings page: every effective value plus where it came
|
|
794
|
+
// from, so the UI can badge "page config / environment variable / default".
|
|
795
|
+
// The token is never returned in clear — just whether one is set and its last
|
|
796
|
+
// 4 chars.
|
|
797
|
+
app.get('/api/admin/local-models/settings', async () => {
|
|
798
|
+
const stored = readLocalModelSettings();
|
|
799
|
+
const endpoint = resolveHfEndpoint();
|
|
800
|
+
const token = resolveHfToken();
|
|
801
|
+
const dir = resolveModelsDir();
|
|
802
|
+
const egress = resolveLocalEgress();
|
|
803
|
+
return {
|
|
804
|
+
status: 'ok',
|
|
805
|
+
hfEndpoint: endpoint.url,
|
|
806
|
+
hfEndpointSource: endpoint.source,
|
|
807
|
+
hfEndpointStored: stored.hfEndpoint ?? '',
|
|
808
|
+
/** Operator-added mirror rows, shown beside the built-in presets. Picker
|
|
809
|
+
* data only: the effective mirror is `hfEndpoint` above. */
|
|
810
|
+
hfEndpointPresets: stored.hfEndpointPresets ?? [],
|
|
811
|
+
hfTokenSet: token.source !== 'none',
|
|
812
|
+
hfTokenSource: token.source,
|
|
813
|
+
hfTokenHint: token.token ? `••••${token.token.slice(-4)}` : '',
|
|
814
|
+
modelsDir: dir.dir,
|
|
815
|
+
modelsDirSource: dir.source,
|
|
816
|
+
defaultModelsDir: defaultModelsDir(),
|
|
817
|
+
/** The market's leg (ADR-0022 / ADR-0044) and where it came from. */
|
|
818
|
+
egress: egress.egress,
|
|
819
|
+
egressSource: egress.source,
|
|
820
|
+
/** `proxy` picked and an endpoint exists. False with `egress: 'proxy'`
|
|
821
|
+
* means every read will refuse — the console warns before that. */
|
|
822
|
+
proxyEndpointConfigured: localProxyConfigured(),
|
|
823
|
+
/** Engine-level setup values per engine id (ADR-0045 §10), validated on
|
|
824
|
+
* write by the owning engine's `setup.normalize`. */
|
|
825
|
+
engineSetup: stored.engineSetup ?? {},
|
|
826
|
+
/** The path each engine uses when nothing is pinned — the console shows
|
|
827
|
+
* these in the setup form, so the operator sees the directory a launch
|
|
828
|
+
* will use. Computed by each engine's own setup.resolve. */
|
|
829
|
+
engineSetupResolved: Object.fromEntries(ENGINES.flatMap((engine) => {
|
|
830
|
+
const resolve = engine.runtime?.setup?.resolve;
|
|
831
|
+
if (!resolve)
|
|
832
|
+
return [];
|
|
833
|
+
const resolved = resolve({ binary: installedEnginesFor(engine.id)[0]?.binaries[0] });
|
|
834
|
+
return Object.keys(resolved).length > 0 ? [[engine.id, resolved]] : [];
|
|
835
|
+
})),
|
|
836
|
+
};
|
|
837
|
+
});
|
|
838
|
+
// Partial update: omitted keys stay unchanged; an explicit empty string
|
|
839
|
+
// clears a field (falling back to env/default). The token field uses the
|
|
840
|
+
// same rule but the UI only ever sends it when the operator typed a new
|
|
841
|
+
// one, so an accidental clear means deliberately saving an empty field.
|
|
842
|
+
app.put('/api/admin/local-models/settings', async (req, reply) => {
|
|
843
|
+
const body = (req.body ?? {});
|
|
844
|
+
const stored = readLocalModelSettings();
|
|
845
|
+
const egressBefore = resolveLocalEgress().egress;
|
|
846
|
+
if (body.egress !== undefined) {
|
|
847
|
+
if (body.egress !== 'direct' && body.egress !== 'proxy') {
|
|
848
|
+
return reply.status(400).send({ status: 'error', message: "egress must be 'direct' or 'proxy'" });
|
|
849
|
+
}
|
|
850
|
+
// `direct` is the built-in default, so it is stored by ABSENCE — one
|
|
851
|
+
// spelling of the default, not two disk shapes that mean the same thing.
|
|
852
|
+
if (body.egress === 'proxy')
|
|
853
|
+
stored.egress = 'proxy';
|
|
854
|
+
else
|
|
855
|
+
delete stored.egress;
|
|
856
|
+
}
|
|
857
|
+
if (typeof body.hfEndpoint === 'string') {
|
|
858
|
+
const value = normalizeMirrorUrl(body.hfEndpoint);
|
|
859
|
+
if (value && !isMirrorUrl(value)) {
|
|
860
|
+
return reply.status(400).send({ status: 'error', message: 'mirror URL must start with http:// or https://' });
|
|
861
|
+
}
|
|
862
|
+
if (value)
|
|
863
|
+
stored.hfEndpoint = value;
|
|
864
|
+
else
|
|
865
|
+
delete stored.hfEndpoint;
|
|
866
|
+
}
|
|
867
|
+
// Operator-added mirror presets: the WHOLE list per call (add and remove
|
|
868
|
+
// are both a list replacement), validated so the picker never renders a
|
|
869
|
+
// row the market cannot dial or a row with no chip text. Built-in presets
|
|
870
|
+
// are not stored here. The console always sends objects (the add dialog
|
|
871
|
+
// collects URL + label); read-side tolerance for bare strings is for files
|
|
872
|
+
// this field briefly stored, not a second write contract.
|
|
873
|
+
if (body.hfEndpointPresets !== undefined) {
|
|
874
|
+
if (!Array.isArray(body.hfEndpointPresets)) {
|
|
875
|
+
return reply.status(400).send({ status: 'error', message: 'hfEndpointPresets must be an array of { url, label }' });
|
|
876
|
+
}
|
|
877
|
+
const presets = [];
|
|
878
|
+
for (const raw of body.hfEndpointPresets) {
|
|
879
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
880
|
+
return reply.status(400).send({ status: 'error', message: 'every mirror preset must be an object with url and label' });
|
|
881
|
+
}
|
|
882
|
+
const entry = raw;
|
|
883
|
+
if (typeof entry.url !== 'string' || typeof entry.label !== 'string') {
|
|
884
|
+
return reply.status(400).send({ status: 'error', message: 'every mirror preset needs a url and a label' });
|
|
885
|
+
}
|
|
886
|
+
const value = normalizeMirrorUrl(entry.url);
|
|
887
|
+
if (!value)
|
|
888
|
+
continue;
|
|
889
|
+
if (!isMirrorUrl(value)) {
|
|
890
|
+
return reply.status(400).send({ status: 'error', message: `mirror preset '${value}' must start with http:// or https://` });
|
|
891
|
+
}
|
|
892
|
+
const label = entry.label.trim();
|
|
893
|
+
if (!label) {
|
|
894
|
+
return reply.status(400).send({ status: 'error', message: `mirror preset '${value}' needs a label` });
|
|
895
|
+
}
|
|
896
|
+
if ([...label].length > HF_MIRROR_PRESET_LABEL_MAX) {
|
|
897
|
+
return reply.status(400).send({
|
|
898
|
+
status: 'error',
|
|
899
|
+
message: `mirror label '${label}' is longer than ${HF_MIRROR_PRESET_LABEL_MAX} characters`,
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
if (!presets.some((preset) => preset.url === value))
|
|
903
|
+
presets.push({ url: value, label });
|
|
904
|
+
}
|
|
905
|
+
if (presets.length > HF_MIRROR_PRESETS_MAX) {
|
|
906
|
+
return reply.status(400).send({ status: 'error', message: `at most ${HF_MIRROR_PRESETS_MAX} mirror presets` });
|
|
907
|
+
}
|
|
908
|
+
if (presets.length > 0)
|
|
909
|
+
stored.hfEndpointPresets = presets;
|
|
910
|
+
else
|
|
911
|
+
delete stored.hfEndpointPresets;
|
|
912
|
+
}
|
|
913
|
+
if (typeof body.hfToken === 'string') {
|
|
914
|
+
const value = body.hfToken.trim();
|
|
915
|
+
if (value)
|
|
916
|
+
stored.hfToken = value;
|
|
917
|
+
else
|
|
918
|
+
delete stored.hfToken;
|
|
919
|
+
}
|
|
920
|
+
if (typeof body.modelsDir === 'string') {
|
|
921
|
+
const value = body.modelsDir.trim();
|
|
922
|
+
if (value)
|
|
923
|
+
stored.modelsDir = value;
|
|
924
|
+
else
|
|
925
|
+
delete stored.modelsDir;
|
|
926
|
+
}
|
|
927
|
+
// Engine setup (ADR-0045 §10): per-engine string maps, validated by the
|
|
928
|
+
// OWNING engine's normalize — the route knows no field names. An empty
|
|
929
|
+
// object clears that engine's setup.
|
|
930
|
+
if (body.engineSetup !== undefined) {
|
|
931
|
+
if (!body.engineSetup || typeof body.engineSetup !== 'object' || Array.isArray(body.engineSetup)) {
|
|
932
|
+
return reply.status(400).send({ status: 'error', message: 'engineSetup must be an object keyed by engine id' });
|
|
933
|
+
}
|
|
934
|
+
const next = { ...(stored.engineSetup ?? {}) };
|
|
935
|
+
for (const [engineId, raw] of Object.entries(body.engineSetup)) {
|
|
936
|
+
const engine = engineById(engineId);
|
|
937
|
+
const spec = engine?.runtime?.setup;
|
|
938
|
+
if (!engine || !spec) {
|
|
939
|
+
return reply.status(400).send({ status: 'error', message: `engine '${engineId}' takes no setup` });
|
|
940
|
+
}
|
|
941
|
+
const normalized = spec.normalize(raw);
|
|
942
|
+
if (!normalized.ok) {
|
|
943
|
+
return reply.status(400).send({ status: 'error', message: normalized.error });
|
|
944
|
+
}
|
|
945
|
+
if (Object.keys(normalized.setup).length > 0)
|
|
946
|
+
next[engineId] = normalized.setup;
|
|
947
|
+
else
|
|
948
|
+
delete next[engineId];
|
|
949
|
+
}
|
|
950
|
+
if (Object.keys(next).length > 0)
|
|
951
|
+
stored.engineSetup = next;
|
|
952
|
+
else
|
|
953
|
+
delete stored.engineSetup;
|
|
954
|
+
}
|
|
955
|
+
try {
|
|
956
|
+
writeLocalModelSettings(stored);
|
|
957
|
+
}
|
|
958
|
+
catch (err) {
|
|
959
|
+
return reply.status(500).send({ status: 'error', message: err instanceof Error ? err.message : 'could not save settings' });
|
|
960
|
+
}
|
|
961
|
+
// A leg change makes the Hub reads held in the short window the OLD leg's
|
|
962
|
+
// answers; dropping them is what lets the console re-read over the new one
|
|
963
|
+
// instead of appearing to do nothing (the key carries the leg too, this is
|
|
964
|
+
// the memory bound's half of the same contract). The release-availability
|
|
965
|
+
// cache is the same story — its rows were probed over one leg — so a flip
|
|
966
|
+
// re-probes on the next console read instead of standing on old bytes.
|
|
967
|
+
if (resolveLocalEgress().egress !== egressBefore) {
|
|
968
|
+
resetHfCache();
|
|
969
|
+
availabilityCache = null;
|
|
970
|
+
}
|
|
971
|
+
return { status: 'ok' };
|
|
972
|
+
});
|
|
973
|
+
// The DFlash2 drafter (ADR-0045 §13). A start never downloads it; the Strata
|
|
974
|
+
// card on the engines page runs the control bundle's own fetch into the
|
|
975
|
+
// gateway data directory, through the mirror saved in local settings. The
|
|
976
|
+
// MTP draft layer is not this.
|
|
977
|
+
app.get('/api/admin/local-models/settings/drafter', async () => ({
|
|
978
|
+
status: 'ok',
|
|
979
|
+
...drafterStatus(),
|
|
980
|
+
}));
|
|
981
|
+
app.post('/api/admin/local-models/settings/drafter', async (_req, reply) => {
|
|
982
|
+
const result = startDrafterFetch();
|
|
983
|
+
if (!result.ok) {
|
|
984
|
+
return reply.status(409).send({ status: 'error', code: result.code, message: result.error });
|
|
985
|
+
}
|
|
986
|
+
return { status: 'ok', job: result.job };
|
|
987
|
+
});
|
|
988
|
+
app.delete('/api/admin/local-models/settings/drafter', async () => ({
|
|
989
|
+
status: 'ok',
|
|
990
|
+
job: cancelDrafterFetch(),
|
|
991
|
+
}));
|
|
992
|
+
// Latency probe for the mirror presets (and any custom URL): a HEAD to the
|
|
993
|
+
// base URL with a 4s cap. Server-side on purpose — a browser fetch would
|
|
994
|
+
// trip the mirrors' CORS; round-trip time is what the picker sorts by.
|
|
995
|
+
app.post('/api/admin/local-models/settings/mirrors/ping', async (req) => {
|
|
996
|
+
const raw = typeof req.body?.url === 'string'
|
|
997
|
+
? req.body.url.trim()
|
|
998
|
+
: '';
|
|
999
|
+
if (!/^https?:\/\//i.test(raw)) {
|
|
1000
|
+
return { status: 'error', message: 'invalid URL' };
|
|
1001
|
+
}
|
|
1002
|
+
const started = Date.now();
|
|
1003
|
+
try {
|
|
1004
|
+
// Probed over the market's OWN leg: a latency number measured on a
|
|
1005
|
+
// different path than the downloads take would be a lie the picker sorts by.
|
|
1006
|
+
const res = await localTransport()(raw, {
|
|
1007
|
+
method: 'HEAD',
|
|
1008
|
+
headers: { 'User-Agent': 'omnicell-router' },
|
|
1009
|
+
signal: AbortSignal.timeout(4000),
|
|
1010
|
+
});
|
|
1011
|
+
await res.body?.cancel().catch(() => undefined);
|
|
1012
|
+
return { status: 'ok', ok: true, ms: Date.now() - started, code: res.status };
|
|
1013
|
+
}
|
|
1014
|
+
catch (err) {
|
|
1015
|
+
return { status: 'ok', ok: false, ms: Date.now() - started, error: err instanceof Error ? err.message : 'ping failed' };
|
|
1016
|
+
}
|
|
1017
|
+
});
|
|
1018
|
+
// ---- Server-side directory browser (the console's folder picker) -------
|
|
1019
|
+
// One listing per call: dirs always, .gguf files when `files=1`. No path on
|
|
1020
|
+
// Windows enumerates drives (the picker's start screen); elsewhere it falls
|
|
1021
|
+
// back to the home directory. Read-only — names and types, nothing else.
|
|
1022
|
+
app.get('/api/admin/local-models/fs', async (req, reply) => {
|
|
1023
|
+
const raw = String(req.query.path ?? '').trim();
|
|
1024
|
+
const wantFiles = String(req.query.files ?? '') === '1';
|
|
1025
|
+
const listDir = (dir) => {
|
|
1026
|
+
let resolved;
|
|
1027
|
+
try {
|
|
1028
|
+
resolved = path.resolve(dir);
|
|
1029
|
+
}
|
|
1030
|
+
catch {
|
|
1031
|
+
return { status: 'error', message: 'invalid path' };
|
|
1032
|
+
}
|
|
1033
|
+
let dirents;
|
|
1034
|
+
try {
|
|
1035
|
+
dirents = fs.readdirSync(resolved, { withFileTypes: true });
|
|
1036
|
+
}
|
|
1037
|
+
catch (err) {
|
|
1038
|
+
return { status: 'error', message: err instanceof Error ? err.message : 'could not read the directory' };
|
|
1039
|
+
}
|
|
1040
|
+
const entries = [];
|
|
1041
|
+
for (const d of dirents) {
|
|
1042
|
+
try {
|
|
1043
|
+
if (d.isDirectory()) {
|
|
1044
|
+
entries.push({ name: d.name, path: path.join(resolved, d.name), type: 'dir' });
|
|
1045
|
+
}
|
|
1046
|
+
else if (wantFiles && d.isFile() && d.name.toLowerCase().endsWith('.gguf')) {
|
|
1047
|
+
entries.push({ name: d.name, path: path.join(resolved, d.name), type: 'file' });
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
catch {
|
|
1051
|
+
// A raced deletion or a permission oddity — skip the entry, keep the listing.
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
entries.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true }) : a.type === 'dir' ? -1 : 1));
|
|
1055
|
+
const parent = path.dirname(resolved);
|
|
1056
|
+
return { status: 'ok', path: resolved, parent: parent !== resolved ? parent : null, entries };
|
|
1057
|
+
};
|
|
1058
|
+
if (!raw) {
|
|
1059
|
+
if (process.platform === 'win32') {
|
|
1060
|
+
const drives = [];
|
|
1061
|
+
for (let code = 65; code <= 90; code++) {
|
|
1062
|
+
const drive = `${String.fromCharCode(code)}:\\`;
|
|
1063
|
+
try {
|
|
1064
|
+
if (fs.existsSync(drive))
|
|
1065
|
+
drives.push({ name: drive, path: drive, type: 'dir' });
|
|
1066
|
+
}
|
|
1067
|
+
catch {
|
|
1068
|
+
// Unreadable drive letter — skip it.
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return { status: 'ok', path: '', parent: null, entries: drives };
|
|
1072
|
+
}
|
|
1073
|
+
return listDir(os.homedir());
|
|
1074
|
+
}
|
|
1075
|
+
const result = listDir(raw);
|
|
1076
|
+
if (result.status === 'ok')
|
|
1077
|
+
return result;
|
|
1078
|
+
// The requested dir may not exist yet (a fresh models dir before the first
|
|
1079
|
+
// download, a renamed path) — climb to the nearest existing ancestor so
|
|
1080
|
+
// the picker still opens somewhere sensible instead of dead-ending.
|
|
1081
|
+
let cur = path.resolve(raw);
|
|
1082
|
+
for (;;) {
|
|
1083
|
+
const parent = path.dirname(cur);
|
|
1084
|
+
if (parent === cur)
|
|
1085
|
+
break;
|
|
1086
|
+
cur = parent;
|
|
1087
|
+
const attempt = listDir(cur);
|
|
1088
|
+
if (attempt.status === 'ok')
|
|
1089
|
+
return attempt;
|
|
1090
|
+
}
|
|
1091
|
+
return reply.status(400).send(result);
|
|
1092
|
+
});
|
|
1093
|
+
// ---- Runs (launch / stop / logs) ---------------------------------------
|
|
1094
|
+
// Adopt survivors of a previous gateway lifetime (fire-and-forget at route
|
|
1095
|
+
// registration = server boot).
|
|
1096
|
+
void restoreLocalRuns();
|
|
1097
|
+
// A part is only kept for the next RETRY; one whose model is never fetched
|
|
1098
|
+
// again has no registry row to delete (ADR-0022), so boot + an hourly pass
|
|
1099
|
+
// reclaim it.
|
|
1100
|
+
startAbandonedPartSweep();
|
|
1101
|
+
// The placement-plan panel (`localModels.runPlanTitle`): what a launch of this
|
|
1102
|
+
// model on this engine target would place where (and the ctx/ngl the runner
|
|
1103
|
+
// would resolve).
|
|
1104
|
+
app.get('/api/admin/local-models/plan', async (req, reply) => {
|
|
1105
|
+
const q = req.query;
|
|
1106
|
+
const modelId = String(q.modelId ?? '');
|
|
1107
|
+
const model = readInstalledModels()[modelId];
|
|
1108
|
+
if (!model)
|
|
1109
|
+
return reply.status(404).send({ status: 'error', message: 'unknown model' });
|
|
1110
|
+
// No engine named: the first launchable one that can serve this model,
|
|
1111
|
+
// else the registry's first launch target. Never a hardcoded engine id —
|
|
1112
|
+
// that would silently break the day llama.cpp is not installed.
|
|
1113
|
+
const engineId = String(q.engine ?? '') ||
|
|
1114
|
+
launchableEngines().find((candidate) => model.meta?.engines?.[candidate.id]?.serves)?.id ||
|
|
1115
|
+
launchableEngines()[0]?.id ||
|
|
1116
|
+
'';
|
|
1117
|
+
const engine = engineById(engineId);
|
|
1118
|
+
if (!engine)
|
|
1119
|
+
return reply.status(404).send({ status: 'error', message: 'unknown engine' });
|
|
1120
|
+
const installs = installedEnginesFor(engineId);
|
|
1121
|
+
const target = String(q.target ?? '') || installs.find((i) => i.target !== 'cpu')?.target || installs[0]?.target || '';
|
|
1122
|
+
const targetDef = engine.targets(process.platform, process.arch).find((t) => t.id === target);
|
|
1123
|
+
const kvq8 = String(q.kvq8 ?? '1') !== '0';
|
|
1124
|
+
// The resource switch ("leave room" vs "full performance"): one budget
|
|
1125
|
+
// input shared by the preview and the launch (preview ≠ launch is the bug
|
|
1126
|
+
// ADR-0043 names), inert for an engine-owned placement.
|
|
1127
|
+
const headroom = String(q.headroom ?? '1') !== '0';
|
|
1128
|
+
const meta = model.meta ?? null;
|
|
1129
|
+
const report = await cachedDetect();
|
|
1130
|
+
// The machine card's facts ride every plan response — the same cached
|
|
1131
|
+
// probe the planner's totals come from. Free memory is display-only.
|
|
1132
|
+
const machine = {
|
|
1133
|
+
gpus: report.gpus,
|
|
1134
|
+
vramMb: report.vramMb ?? null,
|
|
1135
|
+
vramFreeMb: report.vramFreeMb ?? null,
|
|
1136
|
+
ramBytes: os.totalmem(),
|
|
1137
|
+
ramFreeBytes: os.freemem(),
|
|
1138
|
+
};
|
|
1139
|
+
const input = {
|
|
1140
|
+
sizeBytes: model.size,
|
|
1141
|
+
meta: meta
|
|
1142
|
+
? {
|
|
1143
|
+
ok: true,
|
|
1144
|
+
...(meta.arch ? { arch: meta.arch } : {}),
|
|
1145
|
+
...(meta.layers != null ? { layers: meta.layers } : {}),
|
|
1146
|
+
...(meta.maxCtx != null ? { maxCtx: meta.maxCtx } : {}),
|
|
1147
|
+
...(meta.experts != null ? { experts: meta.experts } : {}),
|
|
1148
|
+
...(meta.expertsUsed != null ? { expertsUsed: meta.expertsUsed } : {}),
|
|
1149
|
+
...(meta.heads != null ? { heads: meta.heads } : {}),
|
|
1150
|
+
...(meta.kvHeads != null ? { kvHeads: meta.kvHeads } : {}),
|
|
1151
|
+
...(meta.headDim != null ? { headDim: meta.headDim } : {}),
|
|
1152
|
+
...(meta.embedding != null ? { embedding: meta.embedding } : {}),
|
|
1153
|
+
}
|
|
1154
|
+
: null,
|
|
1155
|
+
...(report.vramMb != null ? { vramMb: report.vramMb } : {}),
|
|
1156
|
+
ramBytes: os.totalmem(),
|
|
1157
|
+
backend: targetDef?.backend ?? 'cpu',
|
|
1158
|
+
kvElemBytes: kvq8 ? KV_ELEM_Q8_0 : 2,
|
|
1159
|
+
headroom,
|
|
1160
|
+
};
|
|
1161
|
+
const requestedCtx = Number(q.ctx ?? 0);
|
|
1162
|
+
// ADR-0044 §5 / ADR-0045: an engine that owns its own placement (Strata's
|
|
1163
|
+
// `--expert-cache`) has no `-ngl` to preview. Answering with layer bars
|
|
1164
|
+
// would be a preview of a decision the engine makes internally — the exact
|
|
1165
|
+
// "preview ≠ launch" bug ADR-0043 forbids. Such a plan is DECLARED.
|
|
1166
|
+
if (engine.runtime?.placement === 'engine') {
|
|
1167
|
+
const spec = engine.runtime.profile;
|
|
1168
|
+
const profile = spec ? profileFor(model, engine.id) : undefined;
|
|
1169
|
+
// No profile is the NORMAL case (ADR-0045 §8): an engine that derives its
|
|
1170
|
+
// own launch inputs gates on `serves()`, not on a stored record. A model
|
|
1171
|
+
// the engine cannot serve says so — in the engine's words, naming the
|
|
1172
|
+
// missing artefact instead of demanding a directory.
|
|
1173
|
+
const verdict = engine.runtime.serves({ modelPath: model.filePath, meta: input.meta, profile });
|
|
1174
|
+
if (!verdict.serves) {
|
|
1175
|
+
return reply.status(400).send({
|
|
1176
|
+
status: 'error',
|
|
1177
|
+
code: 'engine-cannot-serve',
|
|
1178
|
+
message: verdict.reason ?? `${engine.name} cannot serve this model`,
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
const ctx = engine.runtime.resolveCtx
|
|
1182
|
+
? engine.runtime.resolveCtx({ requested: requestedCtx, profile, meta: input.meta })
|
|
1183
|
+
: (Number.isFinite(requestedCtx) && requestedCtx >= 256 ? Math.floor(requestedCtx) : (meta?.maxCtx ?? LOCAL_DEFAULT_CTX));
|
|
1184
|
+
return {
|
|
1185
|
+
status: 'ok',
|
|
1186
|
+
mode: 'declared',
|
|
1187
|
+
plan: null,
|
|
1188
|
+
ngl: -1,
|
|
1189
|
+
ctx,
|
|
1190
|
+
autoCtx: null,
|
|
1191
|
+
target,
|
|
1192
|
+
backend: targetDef?.backend ?? 'cpu',
|
|
1193
|
+
...machine,
|
|
1194
|
+
// The context ladder the console renders (backend-owned — the page
|
|
1195
|
+
// mirrors nothing). The engine's own ceiling still applies.
|
|
1196
|
+
ctxLadder: [...CTX_LADDER],
|
|
1197
|
+
// The engine's own summary of what the launch will pass — the console
|
|
1198
|
+
// renders argv + feature rows generically (ADR-0045).
|
|
1199
|
+
declaration: spec
|
|
1200
|
+
? spec.describe(profile, ctx, kvq8, {
|
|
1201
|
+
modelPath: model.filePath,
|
|
1202
|
+
meta: input.meta,
|
|
1203
|
+
sizeBytes: model.size,
|
|
1204
|
+
headroom,
|
|
1205
|
+
...(report.vramMb != null ? { vramMb: report.vramMb } : {}),
|
|
1206
|
+
})
|
|
1207
|
+
: { argv: [], features: [] },
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
const ctx = Number.isFinite(requestedCtx) && requestedCtx >= 256 ? Math.floor(requestedCtx) : autoCtx(input);
|
|
1211
|
+
// ngl >= 0 pins the GPU layer count the operator typed on the console;
|
|
1212
|
+
// absent, the planner derives the split from the VRAM budget.
|
|
1213
|
+
const requestedNgl = Number(q.ngl ?? -1);
|
|
1214
|
+
const gpuLayersOverride = Number.isFinite(requestedNgl) && requestedNgl >= 0 ? Math.floor(requestedNgl) : undefined;
|
|
1215
|
+
const plan = planPlacement({ ...input, ctx, ...(gpuLayersOverride != null ? { gpuLayersOverride } : {}) });
|
|
1216
|
+
return {
|
|
1217
|
+
status: 'ok',
|
|
1218
|
+
plan,
|
|
1219
|
+
ngl: nglForPlan(plan),
|
|
1220
|
+
autoCtx: autoCtx(input),
|
|
1221
|
+
target,
|
|
1222
|
+
backend: targetDef?.backend ?? 'cpu',
|
|
1223
|
+
...machine,
|
|
1224
|
+
ctxLadder: [...CTX_LADDER],
|
|
1225
|
+
};
|
|
1226
|
+
});
|
|
1227
|
+
// Every run the gateway knows, live health applied. The console polls this.
|
|
1228
|
+
app.get('/api/admin/local-models/runs', async () => {
|
|
1229
|
+
return { status: 'ok', runs: await listLocalRuns() };
|
|
1230
|
+
});
|
|
1231
|
+
// The monitor board (ADR-0046): every known run with its gateway-side counters
|
|
1232
|
+
// merged in, plus a machine summary. One request serves the page — the launcher's
|
|
1233
|
+
// `/runs` poll stays launch-shaped and is not widened into a board payload.
|
|
1234
|
+
//
|
|
1235
|
+
// Counters are PROCESS-LOCAL (ADR-0046 §4): a gateway restart zeroes them while an
|
|
1236
|
+
// adopted run keeps serving, so the payload carries each row's `since` and the page
|
|
1237
|
+
// states the window instead of presenting a short window as a lifetime total.
|
|
1238
|
+
app.get('/api/admin/local-models/monitor', async () => {
|
|
1239
|
+
// This request is the sampler's only reason to exist: touch it now and the
|
|
1240
|
+
// background beat stops by itself once the console is closed.
|
|
1241
|
+
touchMachineSampler();
|
|
1242
|
+
const runs = await listLocalRuns();
|
|
1243
|
+
const rows = runs.map((run) => ({ run, stats: statsFor(run.id) }));
|
|
1244
|
+
// `live` counts what can actually answer right now; `inFlight` is the gauge
|
|
1245
|
+
// sum across every run, the number the whole board exists to show.
|
|
1246
|
+
const liveRows = runs.filter((run) => run.status === 'ready');
|
|
1247
|
+
const inFlight = rows.reduce((sum, row) => sum + row.stats.inFlight, 0);
|
|
1248
|
+
// Counters for runs the registry already pruned are dropped here — a
|
|
1249
|
+
// stopped-and-pruned run's traffic must not linger as phantom history. Via
|
|
1250
|
+
// the module's own pruner: a read route must not mutate state directly.
|
|
1251
|
+
pruneStats(new Set(runs.map((run) => run.id)));
|
|
1252
|
+
return {
|
|
1253
|
+
status: 'ok',
|
|
1254
|
+
runs: rows,
|
|
1255
|
+
summary: {
|
|
1256
|
+
totalRuns: runs.length,
|
|
1257
|
+
liveRuns: liveRows.length,
|
|
1258
|
+
inFlight,
|
|
1259
|
+
// The gateway's own port, so the board can say where clients point
|
|
1260
|
+
// (the same fact the ready-state snippet on /local-run renders).
|
|
1261
|
+
gatewayPort: loadConfig().port,
|
|
1262
|
+
now: Date.now(),
|
|
1263
|
+
},
|
|
1264
|
+
// Host-side readings: the "why" beside the counters' "how fast". Sampling
|
|
1265
|
+
// is process-local and reader-driven (see machine-stats.ts), never part of
|
|
1266
|
+
// this request's latency.
|
|
1267
|
+
machine: machineSnapshot(),
|
|
1268
|
+
};
|
|
1269
|
+
});
|
|
1270
|
+
// Launch a model on an installed engine target. The body carries the run
|
|
1271
|
+
// options; ctx 0 / ngl -1 mean the planner resolves them (the same numbers
|
|
1272
|
+
// the /plan preview showed).
|
|
1273
|
+
app.post('/api/admin/local-models/runs', async (req, reply) => {
|
|
1274
|
+
const body = (req.body ?? {});
|
|
1275
|
+
const modelId = typeof body.modelId === 'string' ? body.modelId : '';
|
|
1276
|
+
const engine = typeof body.engine === 'string' && body.engine.trim() ? body.engine.trim() : (launchableEngines()[0]?.id ?? '');
|
|
1277
|
+
const target = typeof body.target === 'string' && body.target.trim() ? body.target.trim() : undefined;
|
|
1278
|
+
if (!modelId)
|
|
1279
|
+
return reply.status(400).send({ status: 'error', message: 'modelId is required' });
|
|
1280
|
+
const num = (key, fallback, min, max) => {
|
|
1281
|
+
const v = Number(body[key]);
|
|
1282
|
+
return Number.isFinite(v) ? Math.min(max, Math.max(min, Math.floor(v))) : fallback;
|
|
1283
|
+
};
|
|
1284
|
+
const bool = (key, fallback) => typeof body[key] === 'boolean' ? body[key] : fallback;
|
|
1285
|
+
const extraArgs = Array.isArray(body.extraArgs)
|
|
1286
|
+
? body.extraArgs.filter((a) => typeof a === 'string' && a.trim().length > 0).slice(0, 32)
|
|
1287
|
+
: [];
|
|
1288
|
+
const options = {
|
|
1289
|
+
ctx: num('ctx', DEFAULT_RUN_OPTIONS.ctx, 0, 2_000_000),
|
|
1290
|
+
ngl: num('ngl', DEFAULT_RUN_OPTIONS.ngl, -1, 10_000),
|
|
1291
|
+
flashAttn: bool('flashAttn', DEFAULT_RUN_OPTIONS.flashAttn),
|
|
1292
|
+
kvCacheQ8: bool('kvCacheQ8', DEFAULT_RUN_OPTIONS.kvCacheQ8),
|
|
1293
|
+
reasoning: bool('reasoning', DEFAULT_RUN_OPTIONS.reasoning),
|
|
1294
|
+
autoRestart: bool('autoRestart', DEFAULT_RUN_OPTIONS.autoRestart),
|
|
1295
|
+
headroom: bool('headroom', DEFAULT_RUN_OPTIONS.headroom),
|
|
1296
|
+
threads: num('threads', DEFAULT_RUN_OPTIONS.threads, 0, 512),
|
|
1297
|
+
extraArgs,
|
|
1298
|
+
};
|
|
1299
|
+
const result = await startLocalRun({ modelId, engine, ...(target ? { target } : {}), options });
|
|
1300
|
+
if (!result.ok) {
|
|
1301
|
+
return reply.status(400).send({ status: 'error', code: result.code, message: result.error });
|
|
1302
|
+
}
|
|
1303
|
+
return { status: 'ok', run: result.run };
|
|
1304
|
+
});
|
|
1305
|
+
app.post('/api/admin/local-models/runs/:id/stop', async (req, reply) => {
|
|
1306
|
+
const id = String(req.params.id ?? '');
|
|
1307
|
+
const result = stopLocalRun(id);
|
|
1308
|
+
if (!result.ok)
|
|
1309
|
+
return reply.status(400).send({ status: 'error', message: result.error ?? 'stop failed' });
|
|
1310
|
+
return { status: 'ok' };
|
|
1311
|
+
});
|
|
1312
|
+
app.get('/api/admin/local-models/runs/:id', async (req, reply) => {
|
|
1313
|
+
const id = String(req.params.id ?? '');
|
|
1314
|
+
const run = await getLocalRun(id);
|
|
1315
|
+
if (!run)
|
|
1316
|
+
return reply.status(404).send({ status: 'error', message: 'unknown run' });
|
|
1317
|
+
return { status: 'ok', run };
|
|
1318
|
+
});
|
|
1319
|
+
// Measure one running model: a fixed prompt, the engine's own token count
|
|
1320
|
+
// over wall time. The console's "measure speed" button reads this so the
|
|
1321
|
+
// plan panel's ESTIMATE and a real reading can be compared.
|
|
1322
|
+
app.post('/api/admin/local-models/runs/:id/benchmark', async (req, reply) => {
|
|
1323
|
+
const id = String(req.params.id ?? '');
|
|
1324
|
+
const result = await benchmarkLocalRun(id);
|
|
1325
|
+
if (!result.ok) {
|
|
1326
|
+
return reply.status(result.code === 'unknown-run' ? 404 : 400).send({ status: 'error', code: result.code, message: result.error });
|
|
1327
|
+
}
|
|
1328
|
+
return { status: 'ok', result: result.result };
|
|
1329
|
+
});
|
|
1330
|
+
// Tune this model: try a few (context, resource mode) pairs, measure each
|
|
1331
|
+
// with the same fixed prompt the speed button uses, keep the fastest and save
|
|
1332
|
+
// it on the model. One job at a time per model; the console polls the job.
|
|
1333
|
+
app.post('/api/admin/local-models/tunes', async (req, reply) => {
|
|
1334
|
+
const body = (req.body ?? {});
|
|
1335
|
+
const modelId = typeof body.modelId === 'string' ? body.modelId : '';
|
|
1336
|
+
const engine = typeof body.engine === 'string' ? body.engine.trim() : '';
|
|
1337
|
+
if (!modelId || !engine)
|
|
1338
|
+
return reply.status(400).send({ status: 'error', message: 'modelId and engine are required' });
|
|
1339
|
+
const result = startTuneJob({ modelId, engine, headroom: body.headroom !== false });
|
|
1340
|
+
if (!result.ok)
|
|
1341
|
+
return reply.status(400).send({ status: 'error', code: result.code, message: result.error });
|
|
1342
|
+
return { status: 'ok', job: result.job };
|
|
1343
|
+
});
|
|
1344
|
+
app.get('/api/admin/local-models/tunes', async () => ({ status: 'ok', jobs: listTuneJobs() }));
|
|
1345
|
+
app.get('/api/admin/local-models/tunes/:id', async (req, reply) => {
|
|
1346
|
+
const job = getTuneJob(String(req.params.id ?? ''));
|
|
1347
|
+
if (!job)
|
|
1348
|
+
return reply.status(404).send({ status: 'error', message: 'unknown tune job' });
|
|
1349
|
+
return { status: 'ok', job };
|
|
1350
|
+
});
|
|
1351
|
+
app.post('/api/admin/local-models/tunes/:id/cancel', async (req, reply) => {
|
|
1352
|
+
const result = cancelTuneJob(String(req.params.id ?? ''));
|
|
1353
|
+
if (!result.ok)
|
|
1354
|
+
return reply.status(400).send({ status: 'error', message: result.error ?? 'cancel failed' });
|
|
1355
|
+
return { status: 'ok' };
|
|
1356
|
+
});
|
|
1357
|
+
// The run-log drawer (`localModels.runLogs`): the newest N lines of the run's
|
|
1358
|
+
// in-memory ring (engine stdout/stderr plus the gateway's own lifecycle
|
|
1359
|
+
// markers).
|
|
1360
|
+
app.get('/api/admin/local-models/runs/:id/logs', async (req) => {
|
|
1361
|
+
const id = String(req.params.id ?? '');
|
|
1362
|
+
const limit = Number(req.query.limit ?? 300);
|
|
1363
|
+
return { status: 'ok', lines: runLogs(id, Number.isFinite(limit) ? Math.min(Math.max(1, limit), 1000) : 300) };
|
|
1364
|
+
});
|
|
1365
|
+
// Engine build jobs (ADR-0045 §9): the engine builds the launch input it
|
|
1366
|
+
// derives — Strata's pack, by the workspace's own tooling — so the operator
|
|
1367
|
+
// never runs the packer by hand. A build is not a run: no port, no health
|
|
1368
|
+
// probe; the console polls the job list and the per-job log ring.
|
|
1369
|
+
app.post('/api/admin/local-models/builds', async (req, reply) => {
|
|
1370
|
+
const body = (req.body ?? {});
|
|
1371
|
+
const modelId = typeof body.modelId === 'string' ? body.modelId : '';
|
|
1372
|
+
const engine = typeof body.engine === 'string' ? body.engine.trim() : '';
|
|
1373
|
+
if (!modelId || !engine) {
|
|
1374
|
+
return reply.status(400).send({ status: 'error', message: 'modelId and engine are required' });
|
|
1375
|
+
}
|
|
1376
|
+
const result = await startBuildJob({ modelId, engine });
|
|
1377
|
+
if (!result.ok) {
|
|
1378
|
+
return reply.status(400).send({ status: 'error', code: result.code, message: result.error });
|
|
1379
|
+
}
|
|
1380
|
+
return { status: 'ok', job: result.job };
|
|
1381
|
+
});
|
|
1382
|
+
app.get('/api/admin/local-models/builds', async () => {
|
|
1383
|
+
return { status: 'ok', jobs: listBuildJobs() };
|
|
1384
|
+
});
|
|
1385
|
+
// The build-log drawer: the newest N lines of the job's in-memory ring.
|
|
1386
|
+
app.get('/api/admin/local-models/builds/:id/logs', async (req) => {
|
|
1387
|
+
const id = String(req.params.id ?? '');
|
|
1388
|
+
const limit = Number(req.query.limit ?? 300);
|
|
1389
|
+
return { status: 'ok', lines: buildLogs(id, Number.isFinite(limit) ? Math.min(Math.max(1, limit), 1000) : 300) };
|
|
1390
|
+
});
|
|
1391
|
+
// Drop ended run records from the registry (history hygiene; never touches
|
|
1392
|
+
// a live run). Counters are dropped with their record — a pruned run's
|
|
1393
|
+
// traffic must not linger on the monitor board (ADR-0046 §4).
|
|
1394
|
+
app.delete('/api/admin/local-models/runs', async () => {
|
|
1395
|
+
const pruned = pruneLocalRuns();
|
|
1396
|
+
if (pruned > 0) {
|
|
1397
|
+
pruneStats(new Set((await listLocalRuns()).map((run) => run.id)));
|
|
1398
|
+
}
|
|
1399
|
+
return { status: 'ok', pruned };
|
|
1400
|
+
});
|
|
1401
|
+
// Drop ONE ended run record. A live run is refused by `deleteLocalRun`, and
|
|
1402
|
+
// its counters go with the record — a deleted run's traffic must not linger
|
|
1403
|
+
// as phantom history (same rule as the bulk prune above, ADR-0046 §4).
|
|
1404
|
+
app.delete('/api/admin/local-models/runs/:id', async (req, reply) => {
|
|
1405
|
+
const id = String(req.params.id ?? '');
|
|
1406
|
+
const result = deleteLocalRun(id);
|
|
1407
|
+
if (!result.ok) {
|
|
1408
|
+
const code = result.code === 'not-found' ? 404 : result.code === 'run-live' ? 409 : 500;
|
|
1409
|
+
return reply.code(code).send({ status: 'error', code: result.code, error: result.error });
|
|
1410
|
+
}
|
|
1411
|
+
dropStats(id);
|
|
1412
|
+
return { status: 'ok' };
|
|
1413
|
+
});
|
|
1414
|
+
}
|