omnicell-router 0.8.4 → 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/capture/recorder.d.ts +4 -10
- package/backend/dist/capture/recorder.js +6 -58
- 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 +8 -0
- package/backend/dist/cli/clients/codex.js +5 -0
- 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/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 +5 -0
- package/backend/dist/cli/clients/pi.d.ts +6 -0
- package/backend/dist/cli/clients/pi.js +3 -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 +92 -16
- package/backend/dist/config/comments-en.js +31 -26
- package/backend/dist/config/comments-zh.js +29 -24
- package/backend/dist/config/defaults.d.ts +194 -33
- package/backend/dist/config/defaults.js +193 -32
- package/backend/dist/config/env.d.ts +10 -0
- package/backend/dist/config/env.js +3 -2
- package/backend/dist/config/index.d.ts +7 -0
- package/backend/dist/config/index.js +184 -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/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 +14 -4
- package/backend/dist/config/types.d.ts +167 -38
- 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 +50 -17
- package/backend/dist/forward-proxy/h2-forward.js +36 -10
- package/backend/dist/forward-proxy/index.d.ts +11 -8
- package/backend/dist/forward-proxy/index.js +22 -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 +0 -16
- package/backend/dist/forward-proxy/server.js +124 -156
- package/backend/dist/harness/host/hosts.js +3 -2
- package/backend/dist/index.js +53 -18
- 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 +45 -3
- 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 +82 -24
- package/backend/dist/ir/adapters/openai-responses.js +146 -37
- 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/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 +276 -70
- package/backend/dist/opencode/catalog/ocr-store.js +3 -1
- package/backend/dist/opencode/catalog/overrides-store.d.ts +10 -1
- package/backend/dist/opencode/catalog/overrides-store.js +6 -0
- 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 +25 -2
- package/backend/dist/opencode/catalog/sources/models-dev.js +13 -3
- package/backend/dist/opencode/catalog/types.d.ts +35 -3
- package/backend/dist/opencode/catalog/types.js +38 -1
- 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/probe.d.ts +21 -4
- package/backend/dist/opencode/probe.js +34 -10
- 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 +497 -165
- 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 +98 -14
- package/backend/dist/plugins/host.js +622 -87
- 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 +252 -36
- package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
- 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/provider-takedown.d.ts +5 -2
- package/backend/dist/providers/registry.d.ts +84 -25
- package/backend/dist/providers/registry.js +209 -114
- 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 +35 -5
- 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 +928 -310
- 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 +318 -13
- 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/body-admission.d.ts +67 -2
- package/backend/dist/surfaces/body-admission.js +218 -13
- 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 +9 -3
- package/backend/dist/surfaces/transport-node-http.js +6 -19
- 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 +3 -2
- package/backend/dist/utils/server-liveness.js +3 -2
- 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-KI1OW5x6.css → index-CqDSOPQ0.css} +1 -1
- package/frontend/dist/index.html +2 -2
- package/package.json +3 -1
- package/frontend/dist/assets/index-Dk76uc7e.js +0 -1522
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { getAllClientStatuses, setupClient, teardownClient } from '../cli/clients/index.js';
|
|
3
|
+
import { getAllClientStatuses, setupClient, teardownClient, checkClientUpdatesNow } from '../cli/clients/index.js';
|
|
4
4
|
import { clientActivitySnapshot } from '../cli/clients/activity.js';
|
|
5
5
|
import { VIRTUAL_AUTO_IDS } from '../cli/types.js';
|
|
6
6
|
import { MEMBER_TIER_ORDER } from '../providers/member-match.js';
|
|
7
|
+
import { normalizeSelectionStrategy } from '../providers/selection.js';
|
|
7
8
|
import { refreshDirectPool } from '../providers/boot-direct.js';
|
|
8
|
-
import { TIER_PURPOSE } from '../providers/virtual-meta.js';
|
|
9
|
+
import { TIER_PURPOSE, VIRTUAL_CONTEXT_WINDOWS, findMemberCatalogRecords } from '../providers/virtual-meta.js';
|
|
9
10
|
import { getProviderTakedownStore } from '../providers/provider-takedown.js';
|
|
10
11
|
import { protocolVocabulary } from '../providers/vocabulary.js';
|
|
11
12
|
import { pluginPackageZip, pluginProviderOrigins } from '../plugins/host.js';
|
|
@@ -23,26 +24,30 @@ import { appendRoutingLedger } from '../router/routing-ledger.js';
|
|
|
23
24
|
import { Layer2Decision } from '../router/layer2-decision.js';
|
|
24
25
|
import { EFFORT_LADDER, modelSupportsEfforts } from '../types/router.js';
|
|
25
26
|
import { runSystemoneDecision } from '../protocols/systemone/decide.js';
|
|
26
|
-
import { SMART_ASSIGN_TIMEOUT_MS, DEFAULT_REPLAY_TIMEOUT_MS, CREDENTIAL_WEIGHT_MAX,
|
|
27
|
+
import { SMART_ASSIGN_TIMEOUT_MS, DEFAULT_REPLAY_TIMEOUT_MS, CREDENTIAL_WEIGHT_MAX, DEFAULT_INGRESS_PROXY_PORT, DEFAULT_INGRESS_PROXY_RULES, DEFAULT_INGRESS_PROXY_INTERCEPT, DEFAULT_MIHOMO_MIXED_PORT, PLUGIN_PACKAGE_MAX_BYTES, DEFAULT_TRAFFIC_DISSECT_WINDOW_BYTES, DEFAULT_QUOTA_CACHE_TTL_MS } from '../config/defaults.js';
|
|
27
28
|
import { initProxyConfig, proxiedFetch } from '../utils/proxy.js';
|
|
28
29
|
import { registerMihomoRoutes } from './mihomo.js';
|
|
29
|
-
import {
|
|
30
|
+
import { registerLocalModelRoutes } from './local-models.js';
|
|
31
|
+
import { reconcileMihomoSidecar, getMihomoStatus } from '../egress-proxy/mihomo-sidecar.js';
|
|
30
32
|
import { getOcrHomeDir } from '../cli/paths.js';
|
|
31
33
|
import { getHeadroomSidecarStatus, startHeadroomSidecar, stopHeadroomSidecar } from '../compression/headroom-sidecar.js';
|
|
32
34
|
import { APP_VERSION } from '../version.js';
|
|
33
35
|
import { getUpdateChecker } from '../update/check.js';
|
|
34
36
|
import { isSyncClientId } from '../opencode/credentials/sync.js';
|
|
35
|
-
import { caCertPath, describeCa, ensureCa, resolveCaDir } from '../
|
|
36
|
-
import { probeCaTrustedCached } from '../
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
37
|
+
import { caCertPath, describeCa, ensureCa, resolveCaDir } from '../ingress-proxy/ca.js';
|
|
38
|
+
import { probeCaTrustedCached } from '../ingress-proxy/ca-trust.js';
|
|
39
|
+
import { listInstalledOcrCas } from '../ingress-proxy/ca-inventory.js';
|
|
40
|
+
import { getIngressProxyStatus } from '../ingress-proxy/status.js';
|
|
41
|
+
import { lintRules, normalizeRules, osBypassHosts, resolveHost, } from '../ingress-proxy/rules.js';
|
|
39
42
|
import { listGatewayHosts, listClaimedEgress, claimEgressFor, WILDCARD_HOST_CLAIM } from '../plugins/gateways.js';
|
|
40
|
-
import { listProxyAccessEvents, readProxyAccessHistory, clearProxyAccessLog,
|
|
43
|
+
import { listProxyAccessEvents, readProxyAccessHistory, clearProxyAccessLog, forgetProxyAccessRingEvents, flushProxyAccessLogPersistence, proxyAccessLogSettings, proxyAccessBodyPath, proxyAccessLogPersistDir } from '../ingress-proxy/access-log.js';
|
|
44
|
+
import { startHistoryDelete, historyDeleteStatus } from '../ingress-proxy/traffic-delete.js';
|
|
45
|
+
import { PLUGIN_DAY_FILE_RE } from '../ingress-proxy/traffic-files.js';
|
|
41
46
|
import { hideLiveEvents, liveHiddenProxyIds, liveHiddenPluginKeys } from '../observability/traffic-live-hidden.js';
|
|
42
|
-
import { getSystemProxyStatus, enableSystemProxy, disableSystemProxy, buildOverride, lanBypassHosts } from '../
|
|
43
|
-
import { pacUrlFor } from '../proxy/mihomo-pac.js';
|
|
44
|
-
import { keyHashPrefix } from '../opencode/credentials/types.js';
|
|
45
|
-
import { CLI_LOGIN_QUOTA_PREFIX, providerUsesCliLogin } from '../quota/cli-login.js';
|
|
47
|
+
import { getSystemProxyStatus, enableSystemProxy, disableSystemProxy, buildOverride, lanBypassHosts } from '../ingress-proxy/system-proxy.js';
|
|
48
|
+
import { pacUrlFor } from '../egress-proxy/mihomo-pac.js';
|
|
49
|
+
import { isMachineLoginValue, keyHashPrefix } from '../opencode/credentials/types.js';
|
|
50
|
+
import { CLI_LOGIN_QUOTA_PREFIX, providerMayUseLocalLogin, providerUsesCliLogin } from '../quota/cli-login.js';
|
|
46
51
|
import { CLASSIFIER_TAXONOMY } from '../resilience/index.js';
|
|
47
52
|
import { maskSecret, isValidProviderId, PROVIDER_ID_RULE, getProviderNodeById } from '../opencode/user-config.js';
|
|
48
53
|
import { listOpenCodeAgentsLive } from '../opencode/agents.js';
|
|
@@ -190,10 +195,14 @@ function bodyToModelDef(body) {
|
|
|
190
195
|
else if (body?.reasoning === null)
|
|
191
196
|
def.reasoning = null;
|
|
192
197
|
// supported thinking levels (def top level, models.dev `reasoningOptions`
|
|
193
|
-
// shape): non-empty → effort list
|
|
198
|
+
// shape): non-empty → effort list; empty list → NO explicit level control.
|
|
199
|
+
// A bare `{type:'toggle'}` here would be the exact lie ADR-0035 exists to
|
|
200
|
+
// stop: `effortLadderFor` resolves a level-less toggle to `[]` and every ask
|
|
201
|
+
// collapses to `none`. An empty array is the honest "reasons, no caller
|
|
202
|
+
// levels" declaration, so it is written verbatim.
|
|
194
203
|
if (Array.isArray(body?.reasoningEfforts)) {
|
|
195
204
|
const vals = body.reasoningEfforts.map((x) => String(x)).filter(Boolean);
|
|
196
|
-
def.reasoningOptions = vals.length > 0 ? [{ type: 'effort', values: vals }] : [
|
|
205
|
+
def.reasoningOptions = vals.length > 0 ? [{ type: 'effort', values: vals }] : [];
|
|
197
206
|
}
|
|
198
207
|
// headers: { Name: Value } map or "Name: Value" lines (presence = full replace)
|
|
199
208
|
if (body?.headers && typeof body.headers === 'object' && !Array.isArray(body.headers)) {
|
|
@@ -412,7 +421,30 @@ cb, registry) {
|
|
|
412
421
|
// The chain is boot-baked otherwise — without this swap a newly connected key
|
|
413
422
|
// stays invisible to the per-request spread until the next gateway restart.
|
|
414
423
|
await refreshProviderCredentialChain(registry, store, providerId);
|
|
415
|
-
|
|
424
|
+
// NEW key material on a taken-down provider is the operator asking for it to
|
|
425
|
+
// serve again, so the provider-level takedown lifts here — the ONE automatic
|
|
426
|
+
// path in the ledger's lifecycle (ADR-0010). An idempotent reconnect (same
|
|
427
|
+
// key, `deduped`) returned above, so re-pasting the parked key never clears a
|
|
428
|
+
// deliberate takedown.
|
|
429
|
+
const providerReEnabled = getProviderTakedownStore().enable(providerId);
|
|
430
|
+
return {
|
|
431
|
+
credential,
|
|
432
|
+
deduped: false,
|
|
433
|
+
...(providerReEnabled ? { providerReEnabled } : {}),
|
|
434
|
+
...(headPreserved ? { headPreserved } : {}),
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* A plugin-supplied account name is advisory input to a NEW row, not an
|
|
439
|
+
* operator-set label (ADR-0006 amendment): trim it the way the rename route
|
|
440
|
+
* does and enforce the same 80-character ceiling. An empty or non-string value
|
|
441
|
+
* means "no name" — the row stays unnamed rather than carrying a placeholder.
|
|
442
|
+
*/
|
|
443
|
+
function webLoginCredentialLabel(value) {
|
|
444
|
+
if (typeof value !== 'string')
|
|
445
|
+
return undefined;
|
|
446
|
+
const label = value.replace(/\s+/g, ' ').trim();
|
|
447
|
+
return label ? label.slice(0, 80) : undefined;
|
|
416
448
|
}
|
|
417
449
|
/**
|
|
418
450
|
* Provider defs have ONE generation and ONE slot: the v2 shape in `providers`.
|
|
@@ -469,7 +501,7 @@ function quotaViewFor(providerId, keyHashPrefix) {
|
|
|
469
501
|
// the tooltip names its origin), never a badge promising a future probe.
|
|
470
502
|
if (ttlMs === undefined && !snap)
|
|
471
503
|
return undefined;
|
|
472
|
-
const ttl = ttlMs ??
|
|
504
|
+
const ttl = ttlMs ?? DEFAULT_QUOTA_CACHE_TTL_MS;
|
|
473
505
|
if (!snap) {
|
|
474
506
|
// Covered but no numbers yet: `unverified` is the provenance state; the
|
|
475
507
|
// failure verdict (when present) says WHY — `unverified` alone would read
|
|
@@ -496,7 +528,9 @@ function quotaViewFor(providerId, keyHashPrefix) {
|
|
|
496
528
|
}
|
|
497
529
|
async function buildQuotaPairRows(registry, traceTracker) {
|
|
498
530
|
const pairs = new Map();
|
|
499
|
-
const add = (providerId, keyHashPrefix, label, maskedKey
|
|
531
|
+
const add = (providerId, keyHashPrefix, label, maskedKey,
|
|
532
|
+
/** The pair IS the provider's own CLI login (no stored row, no name of its own). */
|
|
533
|
+
machineLogin = false) => {
|
|
500
534
|
const id = `${providerId}#${keyHashPrefix}`;
|
|
501
535
|
if (pairs.has(id))
|
|
502
536
|
return;
|
|
@@ -505,6 +539,7 @@ async function buildQuotaPairRows(registry, traceTracker) {
|
|
|
505
539
|
keyHashPrefix,
|
|
506
540
|
...(label ? { label } : {}),
|
|
507
541
|
...(maskedKey ? { maskedKey } : {}),
|
|
542
|
+
...(machineLogin ? { machineLogin: true } : {}),
|
|
508
543
|
covered: getQuotaProber()?.getPlan().byProvider.has(providerId) ?? false,
|
|
509
544
|
quota: quotaViewFor(providerId, keyHashPrefix),
|
|
510
545
|
});
|
|
@@ -524,10 +559,13 @@ async function buildQuotaPairRows(registry, traceTracker) {
|
|
|
524
559
|
overview = [];
|
|
525
560
|
}
|
|
526
561
|
for (const o of overview) {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
562
|
+
// The login the plugin owns is a quota subject whether or not this provider
|
|
563
|
+
// also takes OCR keys; a plugin that ignores keys stops here.
|
|
564
|
+
if (providerMayUseLocalLogin(o.providerId)) {
|
|
565
|
+
add(o.providerId, CLI_LOGIN_QUOTA_PREFIX, undefined, undefined, true);
|
|
530
566
|
}
|
|
567
|
+
if (providerUsesCliLogin(o.providerId))
|
|
568
|
+
continue;
|
|
531
569
|
let metas = [];
|
|
532
570
|
try {
|
|
533
571
|
metas = store.listCredentials(o.providerId);
|
|
@@ -538,6 +576,10 @@ async function buildQuotaPairRows(registry, traceTracker) {
|
|
|
538
576
|
for (const m of metas) {
|
|
539
577
|
if (!m.keyHashPrefix)
|
|
540
578
|
continue;
|
|
579
|
+
// The machine-login marker is NOT a second account: the `cli-login` pair above
|
|
580
|
+
// already represents it, and probing it would send a marker as a token.
|
|
581
|
+
if (m.machineLogin)
|
|
582
|
+
continue;
|
|
541
583
|
add(o.providerId, m.keyHashPrefix, m.label, m.maskedKey);
|
|
542
584
|
}
|
|
543
585
|
}
|
|
@@ -549,17 +591,25 @@ async function buildQuotaPairRows(registry, traceTracker) {
|
|
|
549
591
|
// when a provider registered no chain (the chain-less degeneracy). Union
|
|
550
592
|
// with (1) — `add` dedupes by pair id, so a store row keeps its identity.
|
|
551
593
|
for (const m of registry.getAllModels()) {
|
|
552
|
-
if (
|
|
553
|
-
add(m.provider, CLI_LOGIN_QUOTA_PREFIX, undefined, undefined);
|
|
554
|
-
continue;
|
|
594
|
+
if (providerMayUseLocalLogin(m.provider)) {
|
|
595
|
+
add(m.provider, CLI_LOGIN_QUOTA_PREFIX, undefined, undefined, true);
|
|
555
596
|
}
|
|
597
|
+
if (providerUsesCliLogin(m.provider))
|
|
598
|
+
continue;
|
|
556
599
|
const chain = registry.getCredentialChain(m.provider) ?? [];
|
|
557
|
-
|
|
600
|
+
// The machine-login marker is not a probeable credential and not a second account:
|
|
601
|
+
// `cli-login` above already stands for it, and probing it would send a marker as a
|
|
602
|
+
// token. Skip it here exactly as the store view above does.
|
|
603
|
+
for (const c of chain) {
|
|
604
|
+
if (isMachineLoginValue(c.key))
|
|
605
|
+
continue;
|
|
558
606
|
add(m.provider, c.keyHashPrefix, c.label, maskSecret(c.key));
|
|
607
|
+
}
|
|
559
608
|
if (chain.length === 0) {
|
|
560
609
|
const baked = registry.getProviderConfig(m.provider)?.apiKey;
|
|
561
|
-
if (baked)
|
|
610
|
+
if (baked && !isMachineLoginValue(baked)) {
|
|
562
611
|
add(m.provider, keyHashPrefix(baked), undefined, maskSecret(baked));
|
|
612
|
+
}
|
|
563
613
|
}
|
|
564
614
|
}
|
|
565
615
|
// Per-pair usage join (trace ring GROUP BY provider×prefix — the step-1
|
|
@@ -642,12 +692,6 @@ async function guardStoreCredential(store, providerId, credentialId) {
|
|
|
642
692
|
return { ok: false, status: 404, body: credentialNotFoundBody(credentialId, providerId) };
|
|
643
693
|
return { ok: true, meta };
|
|
644
694
|
}
|
|
645
|
-
/**
|
|
646
|
-
* Shared catch for the three credential-write routes — Decision 3: writes fail
|
|
647
|
-
* LOUD, never fall back to OcrStore. CredentialNotFoundError is the race edge
|
|
648
|
-
* (row vanished between guard and write) → 404; everything else keeps the
|
|
649
|
-
* mapStoreWriteFailure vocabulary, with `status: 'error'` merged additively.
|
|
650
|
-
*/
|
|
651
695
|
async function mapCredentialWriteFailure(err, providerId, credentialId) {
|
|
652
696
|
const m = await import('../opencode/credentials/index.js');
|
|
653
697
|
if (err instanceof m.CredentialNotFoundError) {
|
|
@@ -658,6 +702,17 @@ async function mapCredentialWriteFailure(err, providerId, credentialId) {
|
|
|
658
702
|
return { status: failure.status, body: { status: 'error', ...failure.body } };
|
|
659
703
|
return { status: 500, body: { status: 'error', success: false, error: errMessage(err) } };
|
|
660
704
|
}
|
|
705
|
+
/**
|
|
706
|
+
* Does this text describe a CREDENTIAL refusal (rather than any other failure)?
|
|
707
|
+
*
|
|
708
|
+
* `connect-local` closes the door only on evidence of a dead login. A transport
|
|
709
|
+
* fault must not be read as one: judging it "not connected" would strand an
|
|
710
|
+
* operator whose lane is actually fine, and the def is already written — the
|
|
711
|
+
* cheaper mistake is to let them through. Erring toward false-negative (a broken
|
|
712
|
+
* lane reported as connected) is the documented preference: a working provider
|
|
713
|
+
* wrongly refused has no escape hatch, a broken one can be retried or disconnected.
|
|
714
|
+
*/
|
|
715
|
+
const UNAUTH_REFUSAL_RE = /not logged in|log\s?in|unauthoriz|\b401\b|\b403\b|access[_\s-]?token|invalid[_\s-]?token|token[_\s-]?(?:expired|invalid|rejected)|credential/i;
|
|
661
716
|
/**
|
|
662
717
|
* Masked provider views from the BOUND store (listProviders for every
|
|
663
718
|
* non-opencode-v1-sink binding): config providers from the defs file ∪ store
|
|
@@ -1007,15 +1062,15 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1007
1062
|
circuitBreakers: cbSummary,
|
|
1008
1063
|
credentialHashes,
|
|
1009
1064
|
registeredModelsCount: registry.getAllModels().length,
|
|
1010
|
-
// Inbound
|
|
1065
|
+
// Inbound ingress-proxy runtime status (see ingress-proxy/status.ts) —
|
|
1011
1066
|
// the Proxy Access page polls this to show running / failed / pending.
|
|
1012
|
-
|
|
1013
|
-
enabled: Boolean(config.
|
|
1067
|
+
ingressProxy: {
|
|
1068
|
+
enabled: Boolean(config.ingressProxy?.enabled),
|
|
1014
1069
|
// ADR-0019: a disabled upstream verification is a standing risk, so the
|
|
1015
1070
|
// console states it next to the runtime status instead of hiding it in
|
|
1016
1071
|
// a YAML comment.
|
|
1017
|
-
upstreamInsecure: config.
|
|
1018
|
-
...
|
|
1072
|
+
upstreamInsecure: config.ingressProxy?.upstreamTls?.insecure === true,
|
|
1073
|
+
...getIngressProxyStatus(),
|
|
1019
1074
|
},
|
|
1020
1075
|
};
|
|
1021
1076
|
};
|
|
@@ -1056,6 +1111,14 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1056
1111
|
}),
|
|
1057
1112
|
};
|
|
1058
1113
|
});
|
|
1114
|
+
// Manual "check for new client versions" — the background queue already
|
|
1115
|
+
// refreshes stale entries on every roster read; this is the one call that
|
|
1116
|
+
// bypasses the TTL because the button says NOW. Display-only: it never
|
|
1117
|
+
// installs or upgrades anything, it only asks the declared sources.
|
|
1118
|
+
app.post('/api/admin/clients/update-check', async () => ({
|
|
1119
|
+
status: 'ok',
|
|
1120
|
+
updates: await checkClientUpdatesNow(),
|
|
1121
|
+
}));
|
|
1059
1122
|
app.get('/api/admin/clients/follow-catalog-sync', async () => ({
|
|
1060
1123
|
status: 'ok',
|
|
1061
1124
|
...getFollowCatalogSyncState(),
|
|
@@ -1107,7 +1170,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1107
1170
|
/** Timestamp of a timeline row in ms — proxy rows carry epoch ms, plugin
|
|
1108
1171
|
* rows an ISO string; 0 when unparsable (sorts to the oldest end). */
|
|
1109
1172
|
const tsOf = (r) => 'ev' in r ? r.ev.ts ?? 0 : Date.parse(r.ex.ts ?? '') || 0;
|
|
1110
|
-
app.get('/api/admin/proxy
|
|
1173
|
+
app.get('/api/admin/proxy/ingress/log', async (req) => {
|
|
1111
1174
|
const q = req.query;
|
|
1112
1175
|
if (q.scope === 'history') {
|
|
1113
1176
|
const limit = Math.min(Math.max(Number(q.limit) || 50, 1), 500);
|
|
@@ -1117,7 +1180,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1117
1180
|
const statusF = q.status ?? '';
|
|
1118
1181
|
const hostF = (q.host ?? '').toLowerCase();
|
|
1119
1182
|
const rows = [];
|
|
1120
|
-
for (const ev of readProxyAccessHistory({
|
|
1183
|
+
for (const ev of await readProxyAccessHistory({
|
|
1121
1184
|
kind: kindF || undefined,
|
|
1122
1185
|
method: methodF || undefined,
|
|
1123
1186
|
status: statusF || undefined,
|
|
@@ -1129,7 +1192,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1129
1192
|
const dir = path.join(trafficRoot(), id);
|
|
1130
1193
|
let files = [];
|
|
1131
1194
|
try {
|
|
1132
|
-
files = fs.readdirSync(dir).filter((f) =>
|
|
1195
|
+
files = fs.readdirSync(dir).filter((f) => PLUGIN_DAY_FILE_RE.test(f)).sort().reverse();
|
|
1133
1196
|
}
|
|
1134
1197
|
catch {
|
|
1135
1198
|
continue; // fresh plugin / unreadable feed dir — no history from it
|
|
@@ -1204,7 +1267,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1204
1267
|
const events = [];
|
|
1205
1268
|
try {
|
|
1206
1269
|
if (fs.existsSync(dir)) {
|
|
1207
|
-
const files = fs.readdirSync(dir).filter((f) =>
|
|
1270
|
+
const files = fs.readdirSync(dir).filter((f) => PLUGIN_DAY_FILE_RE.test(f)).sort().reverse();
|
|
1208
1271
|
for (const f of files) {
|
|
1209
1272
|
if (events.length >= TRAFFIC_TAIL)
|
|
1210
1273
|
break;
|
|
@@ -1240,7 +1303,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1240
1303
|
total: rows.length,
|
|
1241
1304
|
};
|
|
1242
1305
|
});
|
|
1243
|
-
app.post('/api/admin/proxy
|
|
1306
|
+
app.post('/api/admin/proxy/ingress/log/clear', async () => {
|
|
1307
|
+
// Drain first: a queued row must not resurrect a file this wipe deletes.
|
|
1308
|
+
await flushProxyAccessLogPersistence();
|
|
1244
1309
|
clearProxyAccessLog();
|
|
1245
1310
|
return { status: 'ok' };
|
|
1246
1311
|
});
|
|
@@ -1251,124 +1316,40 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1251
1316
|
// The console only holds ONE page of the persisted federation at a time, so
|
|
1252
1317
|
// "what I see" and "what I asked to delete" would diverge; the console sends
|
|
1253
1318
|
// the SAME filter vocabulary it queries with and the backend deletes every
|
|
1254
|
-
// matching persisted row across ALL sources.
|
|
1255
|
-
//
|
|
1256
|
-
|
|
1319
|
+
// matching persisted row across ALL sources.
|
|
1320
|
+
//
|
|
1321
|
+
// The rewrite parses and rewrites every retained day file, so it runs in a
|
|
1322
|
+
// worker thread behind ONE single-flight task — never on the event loop, and
|
|
1323
|
+
// never twice: a submit while one runs is 409 busy (there is no job id; one
|
|
1324
|
+
// status record is the whole contract). The GET below reports progress and
|
|
1325
|
+
// the per-source counts the confirm toast shows.
|
|
1326
|
+
app.post('/api/admin/proxy/ingress/log/history/delete', async (req, reply) => {
|
|
1257
1327
|
const b = (req.body ?? {});
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
const
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
// filter cannot match them, but the default `http` filter must — the
|
|
1275
|
-
// history table renders those rows, so refusing every kind filter left
|
|
1276
|
-
// them behind after a clear (the "clear is not clean" bug).
|
|
1277
|
-
if (kindF && kindF !== 'http')
|
|
1278
|
-
continue;
|
|
1279
|
-
const dir = path.join(trafficRoot(), id);
|
|
1280
|
-
let files = [];
|
|
1281
|
-
try {
|
|
1282
|
-
files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f));
|
|
1283
|
-
}
|
|
1284
|
-
catch {
|
|
1285
|
-
continue;
|
|
1286
|
-
}
|
|
1287
|
-
let removed = 0;
|
|
1288
|
-
const bodyIds = new Set();
|
|
1289
|
-
for (const f of files) {
|
|
1290
|
-
const abs = path.join(dir, f);
|
|
1291
|
-
let kept = [];
|
|
1292
|
-
try {
|
|
1293
|
-
kept = fs.readFileSync(abs, 'utf8').split('\n').filter(Boolean);
|
|
1294
|
-
}
|
|
1295
|
-
catch {
|
|
1296
|
-
continue;
|
|
1297
|
-
}
|
|
1298
|
-
let touched = false;
|
|
1299
|
-
const keptOut = [];
|
|
1300
|
-
for (const line of kept) {
|
|
1301
|
-
let ex;
|
|
1302
|
-
try {
|
|
1303
|
-
ex = JSON.parse(line);
|
|
1304
|
-
}
|
|
1305
|
-
catch {
|
|
1306
|
-
keptOut.push(line); // a torn line survives deletion round-trips
|
|
1307
|
-
continue;
|
|
1308
|
-
}
|
|
1309
|
-
const hit = (!methodF || ex.method === methodF) &&
|
|
1310
|
-
(!hostF || (ex.authority ?? '').toLowerCase() === hostF) &&
|
|
1311
|
-
(!statusF || String(ex.status ?? '') === statusF);
|
|
1312
|
-
if (hit) {
|
|
1313
|
-
touched = true;
|
|
1314
|
-
removed++;
|
|
1315
|
-
if (typeof ex.id === 'string')
|
|
1316
|
-
bodyIds.add(ex.id);
|
|
1317
|
-
continue;
|
|
1318
|
-
}
|
|
1319
|
-
keptOut.push(line);
|
|
1320
|
-
}
|
|
1321
|
-
if (!touched)
|
|
1322
|
-
continue;
|
|
1323
|
-
try {
|
|
1324
|
-
if (keptOut.length === 0)
|
|
1325
|
-
fs.unlinkSync(abs);
|
|
1326
|
-
else
|
|
1327
|
-
fs.writeFileSync(abs, keptOut.join('\n') + '\n');
|
|
1328
|
-
}
|
|
1329
|
-
catch {
|
|
1330
|
-
// Best effort — the row is gone from the feed view either way.
|
|
1331
|
-
}
|
|
1332
|
-
}
|
|
1333
|
-
// Sidecar bytes are named `<day>/<id>-<side>.bin`: drop only the ones
|
|
1334
|
-
// whose row just went away, never a neighbour's.
|
|
1335
|
-
if (bodyIds.size > 0) {
|
|
1336
|
-
const bodiesRoot = path.join(dir, 'bodies');
|
|
1337
|
-
if (fs.existsSync(bodiesRoot)) {
|
|
1338
|
-
for (const day of fs.readdirSync(bodiesRoot)) {
|
|
1339
|
-
const dayDir = path.join(bodiesRoot, day);
|
|
1340
|
-
let names = [];
|
|
1341
|
-
try {
|
|
1342
|
-
names = fs.readdirSync(dayDir);
|
|
1343
|
-
}
|
|
1344
|
-
catch {
|
|
1345
|
-
continue;
|
|
1346
|
-
}
|
|
1347
|
-
for (const name of names) {
|
|
1348
|
-
const owner = name.replace(/-(?:req|res)\.bin$/, '');
|
|
1349
|
-
if (!bodyIds.has(owner))
|
|
1350
|
-
continue;
|
|
1351
|
-
try {
|
|
1352
|
-
fs.unlinkSync(path.join(dayDir, name));
|
|
1353
|
-
}
|
|
1354
|
-
catch {
|
|
1355
|
-
// Locked file (Windows) — the row is gone, the blob is orphaned.
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
}
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
if (removed > 0)
|
|
1362
|
-
deletedPlugins[id] = removed;
|
|
1363
|
-
}
|
|
1364
|
-
return { status: 'ok', deleted: { proxy: proxyDeleted, plugins: deletedPlugins } };
|
|
1328
|
+
// Queued proxy rows must land before the worker enumerates day files, or
|
|
1329
|
+
// a matching row enqueued before the click would survive the rewrite.
|
|
1330
|
+
await flushProxyAccessLogPersistence();
|
|
1331
|
+
const started = startHistoryDelete({
|
|
1332
|
+
proxyDir: proxyAccessLogPersistDir(),
|
|
1333
|
+
pluginDirs: trafficDecoders().map(({ id }) => ({ id, dir: path.join(trafficRoot(), id) })),
|
|
1334
|
+
filters: {
|
|
1335
|
+
kind: b.kind || undefined,
|
|
1336
|
+
method: b.method || undefined,
|
|
1337
|
+
status: b.status || undefined,
|
|
1338
|
+
host: b.host ? b.host.toLowerCase() : undefined,
|
|
1339
|
+
},
|
|
1340
|
+
});
|
|
1341
|
+
if (!started)
|
|
1342
|
+
return reply.code(409).send({ status: 'busy', task: historyDeleteStatus() });
|
|
1343
|
+
return reply.code(202).send({ status: 'started', task: historyDeleteStatus() });
|
|
1365
1344
|
});
|
|
1345
|
+
app.get('/api/admin/proxy/ingress/log/history/delete', async () => ({ status: 'ok', task: historyDeleteStatus() }));
|
|
1366
1346
|
// 3A1b. Explicit FULL wipe across BOTH scopes — ring, proxy day files +
|
|
1367
1347
|
// bodies, and every plugin feed dir. This is an admin API, not either
|
|
1368
1348
|
// console button: live clear hides only, history delete rewrites only
|
|
1369
1349
|
// (ADR-0017 §5). Gateway feeds are console-owned artifacts on disk, so they
|
|
1370
1350
|
// are removed here rather than through the plugin.
|
|
1371
1351
|
app.post('/api/admin/traffic-clear', async () => {
|
|
1352
|
+
await flushProxyAccessLogPersistence();
|
|
1372
1353
|
clearProxyAccessLog();
|
|
1373
1354
|
const cleared = [];
|
|
1374
1355
|
for (const [id, gw] of listGateways()) {
|
|
@@ -1543,7 +1524,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1543
1524
|
let days = 0;
|
|
1544
1525
|
try {
|
|
1545
1526
|
if (fs.existsSync(dir)) {
|
|
1546
|
-
const files = fs.readdirSync(dir).filter((f) =>
|
|
1527
|
+
const files = fs.readdirSync(dir).filter((f) => PLUGIN_DAY_FILE_RE.test(f)).sort().reverse();
|
|
1547
1528
|
for (const f of files) {
|
|
1548
1529
|
if (events.length >= TRAFFIC_TAIL)
|
|
1549
1530
|
break;
|
|
@@ -1588,13 +1569,13 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1588
1569
|
return reply.send(fs.createReadStream(abs));
|
|
1589
1570
|
});
|
|
1590
1571
|
// 3A3. OS system proxy ownership — ONE snapshot, TWO endpoints: the inbound
|
|
1591
|
-
//
|
|
1572
|
+
// ingress proxy (default) or the Clash core's mixed port. A target switch
|
|
1592
1573
|
// rewrites the OS pointer without re-reading the pre-OCR snapshot; restore
|
|
1593
1574
|
// always returns what the OS held before OCR first took ownership.
|
|
1594
1575
|
const systemProxyPayload = async (req) => {
|
|
1595
1576
|
const live = getRuntimeConfigRef();
|
|
1596
|
-
const fp = live?.
|
|
1597
|
-
const port = fp?.port ??
|
|
1577
|
+
const fp = live?.ingressProxy;
|
|
1578
|
+
const port = fp?.port ?? DEFAULT_INGRESS_PROXY_PORT;
|
|
1598
1579
|
const mixedPort = live?.proxy?.mihomo?.mixedPort ?? DEFAULT_MIHOMO_MIXED_PORT;
|
|
1599
1580
|
const sys = await getSystemProxyStatus(port, osBypassHosts(fp?.rules));
|
|
1600
1581
|
const clashBypass = lanBypassHosts(process.platform);
|
|
@@ -1613,8 +1594,8 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1613
1594
|
pacUrl: pacUrlFor(req.headers.host, req.protocol, live?.port),
|
|
1614
1595
|
};
|
|
1615
1596
|
};
|
|
1616
|
-
app.get('/api/admin/system
|
|
1617
|
-
app.post('/api/admin/
|
|
1597
|
+
app.get('/api/admin/proxy/system', async (req) => systemProxyPayload(req));
|
|
1598
|
+
app.post('/api/admin/proxy/system/enable', async (req, reply) => {
|
|
1618
1599
|
const body = (req.body ?? {});
|
|
1619
1600
|
const live = getRuntimeConfigRef();
|
|
1620
1601
|
if (body.target === 'clash') {
|
|
@@ -1628,26 +1609,26 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1628
1609
|
await enableSystemProxy(mixedPort, lanBypassHosts(process.platform), 'clash');
|
|
1629
1610
|
return systemProxyPayload(req);
|
|
1630
1611
|
}
|
|
1631
|
-
const fp = live?.
|
|
1632
|
-
const port = fp?.port ??
|
|
1612
|
+
const fp = live?.ingressProxy;
|
|
1613
|
+
const port = fp?.port ?? DEFAULT_INGRESS_PROXY_PORT;
|
|
1633
1614
|
await enableSystemProxy(port, osBypassHosts(fp?.rules), 'forward');
|
|
1634
1615
|
return systemProxyPayload(req);
|
|
1635
1616
|
});
|
|
1636
|
-
app.post('/api/admin/
|
|
1637
|
-
const fp = getRuntimeConfigRef()?.
|
|
1638
|
-
const port = fp?.port ??
|
|
1617
|
+
app.post('/api/admin/proxy/system/disable', async (req) => {
|
|
1618
|
+
const fp = getRuntimeConfigRef()?.ingressProxy;
|
|
1619
|
+
const port = fp?.port ?? DEFAULT_INGRESS_PROXY_PORT;
|
|
1639
1620
|
await disableSystemProxy(port, osBypassHosts(fp?.rules));
|
|
1640
1621
|
return systemProxyPayload(req);
|
|
1641
1622
|
});
|
|
1642
|
-
// 3A4.
|
|
1623
|
+
// 3A4. Ingress-proxy rule table (ADR-0018): lint + dry-run resolution. The
|
|
1643
1624
|
// console renders the warning CODES through i18n and shows which rule a probe
|
|
1644
1625
|
// host hits, so an ordered table is never a black box. `rules` in the body =
|
|
1645
1626
|
// the UNSAVED table being edited; omitted = the live one. `intercept` in the
|
|
1646
1627
|
// body = the UNSAVED posture toggle (same reason); omitted = the live one.
|
|
1647
|
-
app.post('/api/admin/
|
|
1628
|
+
app.post('/api/admin/proxy/ingress/rules/resolve', async (req) => {
|
|
1648
1629
|
const body = (req.body ?? {});
|
|
1649
1630
|
const live = getRuntimeConfigRef();
|
|
1650
|
-
const rawRules = Array.isArray(body.rules) ? body.rules : live?.
|
|
1631
|
+
const rawRules = Array.isArray(body.rules) ? body.rules : live?.ingressProxy?.rules;
|
|
1651
1632
|
const proxyEnabled = live?.proxy?.enabled === true;
|
|
1652
1633
|
const rules = normalizeRules(rawRules);
|
|
1653
1634
|
// ADR-0018 Revision 4: the posture and the claim set are part of the answer,
|
|
@@ -1657,7 +1638,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1657
1638
|
// the live decision.
|
|
1658
1639
|
const intercept = body.intercept === 'all' || body.intercept === 'claims'
|
|
1659
1640
|
? body.intercept
|
|
1660
|
-
: live?.
|
|
1641
|
+
: live?.ingressProxy?.intercept ?? DEFAULT_INGRESS_PROXY_INTERCEPT;
|
|
1661
1642
|
// A wildcard gateway claims EVERY host through `match()`, so a literal `'*'`
|
|
1662
1643
|
// in this list would print as a host name. The set is exact claims only;
|
|
1663
1644
|
// the wildcard's own attribution stays visible through `claimSources`.
|
|
@@ -1720,12 +1701,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1720
1701
|
// its egress) and pins the posture to `claims` — through the SAME save path
|
|
1721
1702
|
// the console's Save button uses (config.yaml write + hot-apply), and ONLY
|
|
1722
1703
|
// when the operator clicked: nothing here runs on boot.
|
|
1723
|
-
app.post('/api/admin/
|
|
1704
|
+
app.post('/api/admin/proxy/ingress/tighten', async (_req, reply) => {
|
|
1724
1705
|
const live = getRuntimeConfigRef();
|
|
1725
|
-
const current = live?.
|
|
1706
|
+
const current = live?.ingressProxy ?? loadConfig().ingressProxy ?? {};
|
|
1726
1707
|
const currentRules = current.rules ?? [];
|
|
1727
1708
|
const catchAll = currentRules.find((r) => r?.match === '*');
|
|
1728
|
-
const egress = catchAll?.egress ??
|
|
1709
|
+
const egress = catchAll?.egress ?? DEFAULT_INGRESS_PROXY_RULES[0].egress;
|
|
1729
1710
|
// Rewrite ONLY the catch-all's ingress. Specific `intercept` rows are
|
|
1730
1711
|
// explicit operator intent (they keep decrypting under `claims`) and every
|
|
1731
1712
|
// other row stays exactly as written — tightening must never be a way to
|
|
@@ -1733,16 +1714,16 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1733
1714
|
const rules = catchAll
|
|
1734
1715
|
? currentRules.map((r) => r?.match === '*' && r.ingress === 'intercept' ? { ...r, ingress: 'passthrough' } : r)
|
|
1735
1716
|
: [...currentRules, { match: '*', ingress: 'passthrough', egress }];
|
|
1736
|
-
const saved = saveConfig({
|
|
1717
|
+
const saved = saveConfig({ ingressProxy: { ...current, rules, intercept: DEFAULT_INGRESS_PROXY_INTERCEPT } });
|
|
1737
1718
|
if (!saved.success)
|
|
1738
1719
|
return reply.status(400).send(saved);
|
|
1739
|
-
// Hot-apply: saveConfig's auth-view sync replaces `live.
|
|
1720
|
+
// Hot-apply: saveConfig's auth-view sync replaces `live.ingressProxy` and
|
|
1740
1721
|
// every proxy leg re-reads it per request, so no restart is involved.
|
|
1741
1722
|
return {
|
|
1742
1723
|
status: 'ok',
|
|
1743
1724
|
rules,
|
|
1744
|
-
intercept:
|
|
1745
|
-
warnings: lintRules(rules, live?.proxy?.enabled === true,
|
|
1725
|
+
intercept: DEFAULT_INGRESS_PROXY_INTERCEPT,
|
|
1726
|
+
warnings: lintRules(rules, live?.proxy?.enabled === true, DEFAULT_INGRESS_PROXY_INTERCEPT, listClaimedEgress()),
|
|
1746
1727
|
};
|
|
1747
1728
|
});
|
|
1748
1729
|
// 3B. Token usage aggregation from the trace ring: windowed totals plus
|
|
@@ -1800,6 +1781,13 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1800
1781
|
success: !report.disabled && !report.busy,
|
|
1801
1782
|
...(report.disabled ? { reasonCode: 'quota_disabled', error: 'quota prober is disabled' } : {}),
|
|
1802
1783
|
...(report.busy ? { reasonCode: 'busy', error: 'another probe cycle is still running' } : {}),
|
|
1784
|
+
...(report.cooldown
|
|
1785
|
+
? {
|
|
1786
|
+
reasonCode: 'cooldown',
|
|
1787
|
+
error: 'this scope was refreshed moments ago — showing the snapshot',
|
|
1788
|
+
nextAllowedAt: report.nextAllowedAt,
|
|
1789
|
+
}
|
|
1790
|
+
: {}),
|
|
1803
1791
|
probed: report.probed,
|
|
1804
1792
|
pending: report.pending,
|
|
1805
1793
|
rateLimited: report.rateLimited,
|
|
@@ -2414,6 +2402,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2414
2402
|
console.warn(`[Clash] reconcile after config save failed: ${message}`);
|
|
2415
2403
|
});
|
|
2416
2404
|
orchestrator.getCaptureRecorder().applyConfig(loadConfig().requestCapture);
|
|
2405
|
+
orchestrator.getSnapshotStore().applyConfig(loadConfig().sessionSnapshots);
|
|
2417
2406
|
applyDecisionCaptureConfig(loadConfig().classifier?.layer2); // L2 dataset sampling: single-key gate classifier.layer2.collectEnabled, hot too
|
|
2418
2407
|
applyRouteEntriesConfig(loadConfig().routeEntries); // experience-table gate: hot-applies lookup/writes
|
|
2419
2408
|
applyDirectivesConfig(loadConfig().directives); // directive gate: hot-applies the reserved namespace + kill switch
|
|
@@ -2451,6 +2440,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2451
2440
|
console.warn(`[Clash] reconcile after config save failed: ${message}`);
|
|
2452
2441
|
});
|
|
2453
2442
|
orchestrator.getCaptureRecorder().applyConfig(loadConfig().requestCapture); // hot-apply capture too
|
|
2443
|
+
orchestrator.getSnapshotStore().applyConfig(loadConfig().sessionSnapshots); // hot-apply the handoff store too
|
|
2454
2444
|
applyDecisionCaptureConfig(loadConfig().classifier?.layer2); // hot-apply the L2 dataset-sampling gate too (classifier.layer2.collectEnabled)
|
|
2455
2445
|
applyRouteEntriesConfig(loadConfig().routeEntries); // hot-apply the experience-table gate too
|
|
2456
2446
|
applyDirectivesConfig(loadConfig().directives); // hot-apply the directive namespace too
|
|
@@ -2487,30 +2477,30 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2487
2477
|
fields: zh ? YAML_FIELD_COMMENTS_ZH : YAML_FIELD_COMMENTS_EN,
|
|
2488
2478
|
};
|
|
2489
2479
|
});
|
|
2490
|
-
// 6a.
|
|
2480
|
+
// 6a. Ingress-proxy MITM CA export — clients using the inbound forward
|
|
2491
2481
|
// proxy must trust this CA. Generated on first request when absent (the
|
|
2492
2482
|
// same idempotent ensureCa the proxy itself uses).
|
|
2493
|
-
const
|
|
2483
|
+
const handleIngressProxyCa = async (_req, reply) => {
|
|
2494
2484
|
const cfg = loadConfig();
|
|
2495
|
-
const caDir = resolveCaDir(cfg.
|
|
2485
|
+
const caDir = resolveCaDir(cfg.ingressProxy?.caDir);
|
|
2496
2486
|
try {
|
|
2497
2487
|
const ca = ensureCa(caDir);
|
|
2498
2488
|
reply.header('content-type', 'application/x-pem-file');
|
|
2499
|
-
reply.header('content-disposition', 'attachment; filename="ocr-
|
|
2489
|
+
reply.header('content-disposition', 'attachment; filename="ocr-proxy-ca.pem"');
|
|
2500
2490
|
return reply.send(ca.caCertPem);
|
|
2501
2491
|
}
|
|
2502
2492
|
catch (err) {
|
|
2503
2493
|
return reply.status(500).send({ status: 'error', message: err?.message || 'Failed to load CA' });
|
|
2504
2494
|
}
|
|
2505
2495
|
};
|
|
2506
|
-
app.get('/api/admin/proxy/ca',
|
|
2496
|
+
app.get('/api/admin/proxy/ingress/ca', handleIngressProxyCa);
|
|
2507
2497
|
// 6a-bis. CA identity for the console card: absolute path, SHA-256
|
|
2508
2498
|
// fingerprint and validity. Never key material — clients use it to check
|
|
2509
2499
|
// that the root they installed is the root this proxy signs with.
|
|
2510
|
-
app.get('/api/admin/proxy/ca/meta', async (_req, reply) => {
|
|
2500
|
+
app.get('/api/admin/proxy/ingress/ca/meta', async (_req, reply) => {
|
|
2511
2501
|
const cfg = loadConfig();
|
|
2512
2502
|
try {
|
|
2513
|
-
return { status: 'ok', ...describeCa(cfg.
|
|
2503
|
+
return { status: 'ok', ...describeCa(cfg.ingressProxy?.caDir) };
|
|
2514
2504
|
}
|
|
2515
2505
|
catch (err) {
|
|
2516
2506
|
return reply.status(500).send({ status: 'error', message: err?.message || 'Failed to load CA' });
|
|
@@ -2521,9 +2511,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2521
2511
|
// the probe could not run, never "not trusted". Cached 60s (the probe spawns
|
|
2522
2512
|
// platform tools); `force=1` bypasses the TTL for an operator re-check after
|
|
2523
2513
|
// an install.
|
|
2524
|
-
app.get('/api/admin/proxy/ca/trust', async (req) => {
|
|
2514
|
+
app.get('/api/admin/proxy/ingress/ca/trust', async (req) => {
|
|
2525
2515
|
const cfg = loadConfig();
|
|
2526
|
-
const caPath = caCertPath(cfg.
|
|
2516
|
+
const caPath = caCertPath(cfg.ingressProxy?.caDir);
|
|
2527
2517
|
const force = String(req.query?.force ?? '') === '1';
|
|
2528
2518
|
// Fail SOFT: the console renders a tri-state chip, so a probe that cannot
|
|
2529
2519
|
// run is `unknown`, never a 500 that makes the chip silently disappear.
|
|
@@ -2537,6 +2527,22 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2537
2527
|
return { status: 'ok', trusted: 'unknown', caPath };
|
|
2538
2528
|
}
|
|
2539
2529
|
});
|
|
2530
|
+
// 6a-quater. Installed-root DETECTION (on demand, read-only): which OCR roots
|
|
2531
|
+
// do this machine's trust stores actually hold? The trust route above answers
|
|
2532
|
+
// "is OUR CA trusted" and cannot see leftovers — a rotated root stays trusted
|
|
2533
|
+
// by every verifier while the chip shows green. Detection, not monitoring: no
|
|
2534
|
+
// cache, no timer, no persisted state (trust is machine state, ADR-0008).
|
|
2535
|
+
// `state: 'unknown'` means no store could be read — the console must render
|
|
2536
|
+
// that as "could not check", never as "nothing installed".
|
|
2537
|
+
app.get('/api/admin/proxy/ingress/ca/installed', async (_req, reply) => {
|
|
2538
|
+
const cfg = loadConfig();
|
|
2539
|
+
try {
|
|
2540
|
+
return { status: 'ok', ...(await listInstalledOcrCas({ caDir: cfg.ingressProxy?.caDir })) };
|
|
2541
|
+
}
|
|
2542
|
+
catch (err) {
|
|
2543
|
+
return reply.status(500).send({ status: 'error', message: err?.message || 'Failed to enumerate installed CAs' });
|
|
2544
|
+
}
|
|
2545
|
+
});
|
|
2540
2546
|
// 6b. Tier member lists — candidate pool snapshots (console preview).
|
|
2541
2547
|
// membership is a PURE projection of (model id × tiers.members);
|
|
2542
2548
|
// PREVIEW never mutates live pools — real membership is committed ONLY by
|
|
@@ -2645,9 +2651,15 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2645
2651
|
};
|
|
2646
2652
|
app.post('/api/admin/tier-pools/preview', handleTierPoolsPreview);
|
|
2647
2653
|
// Check: dry-run validation of a DRAFT tiers config — non-blocking warnings:
|
|
2648
|
-
// orphan
|
|
2649
|
-
// deadCombo
|
|
2650
|
-
//
|
|
2654
|
+
// orphan — a rule matching no registered model (rename / typo / removed)
|
|
2655
|
+
// deadCombo — a combo:<id> ref contributing nothing (unknown / disabled /
|
|
2656
|
+
// shadowed / zero registered members)
|
|
2657
|
+
// windowBelowRung — a member whose real prompt window is smaller than its
|
|
2658
|
+
// tier's DECLARED virtual window (ADR-0041). Membership is
|
|
2659
|
+
// rule-driven, so a small model can join a wide rung at any
|
|
2660
|
+
// save; the gateway publishes the declared window and never
|
|
2661
|
+
// truncates, so the mismatch would surface as an upstream
|
|
2662
|
+
// overflow. Advisory only — the operator decides.
|
|
2651
2663
|
// Cross-tier overlap is NOT warned: membership is a per-tier projection, a
|
|
2652
2664
|
// model (or combo ref) joining several tiers is legal by contract.
|
|
2653
2665
|
const handleTiersCheck = async (req) => {
|
|
@@ -2671,11 +2683,41 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2671
2683
|
orphans.push({ tier, pattern: rule.pattern });
|
|
2672
2684
|
}
|
|
2673
2685
|
}
|
|
2686
|
+
// Rule 2 of ADR-0041: compare each member's REAL catalog window against the
|
|
2687
|
+
// rung's declared window. Best effort — an unreadable catalog or an id
|
|
2688
|
+
// without a record is "not stated", never a warning.
|
|
2689
|
+
const belowRung = [];
|
|
2690
|
+
try {
|
|
2691
|
+
const listCatalog = async () => (await import('../opencode/catalog/repository.js')).catalogRepository.list();
|
|
2692
|
+
const allIds = registry.getAllModels().map((m) => m.id);
|
|
2693
|
+
const { lookup } = await findMemberCatalogRecords(allIds, listCatalog);
|
|
2694
|
+
const seen = new Set();
|
|
2695
|
+
for (const tier of MEMBER_TIER_ORDER) {
|
|
2696
|
+
const rung = VIRTUAL_CONTEXT_WINDOWS[tier];
|
|
2697
|
+
for (const rule of members[tier]) {
|
|
2698
|
+
const matched = rule.exact ? [rule.pattern] : allIds.filter((id) => globMatchAny([rule.pattern], id));
|
|
2699
|
+
for (const id of matched) {
|
|
2700
|
+
const window = lookup(id)?.limit?.context;
|
|
2701
|
+
if (typeof window !== 'number' || window <= 0 || window >= rung)
|
|
2702
|
+
continue;
|
|
2703
|
+
const key = `${tier}:${id}`;
|
|
2704
|
+
if (seen.has(key))
|
|
2705
|
+
continue;
|
|
2706
|
+
seen.add(key);
|
|
2707
|
+
belowRung.push({ tier, model: id, window, rung });
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
catch {
|
|
2713
|
+
/* catalog unavailable — the advisory is best-effort */
|
|
2714
|
+
}
|
|
2674
2715
|
return {
|
|
2675
2716
|
status: 'ok',
|
|
2676
2717
|
warnings: [
|
|
2677
2718
|
...orphans.map((o) => ({ kind: 'orphan', tier: o.tier, pattern: o.pattern })),
|
|
2678
2719
|
...expanded.dead.map((d) => ({ kind: 'deadCombo', tier: d.tier, pattern: d.ref })),
|
|
2720
|
+
...belowRung.map((b) => ({ kind: 'windowBelowRung', ...b })),
|
|
2679
2721
|
],
|
|
2680
2722
|
};
|
|
2681
2723
|
};
|
|
@@ -2684,7 +2726,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2684
2726
|
// the bare tier alias: the same force_tier path a client's
|
|
2685
2727
|
// `model: "pro"` request takes (tier aliases are reserved gateway ids,
|
|
2686
2728
|
// never pool-routed). One run only
|
|
2687
|
-
// exercises the SELECTED member (the default credential, or the
|
|
2729
|
+
// exercises the SELECTED member (the default credential, or the round-robin
|
|
2688
2730
|
// pick), never the whole pool — deep per-model checks stay on the providers
|
|
2689
2731
|
// page. An EMPTY tier degrades inside getModelForTier (the session-pin birth
|
|
2690
2732
|
// representative falls down the escalate→plus→lite chain, server-warned with
|
|
@@ -2960,13 +3002,18 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2960
3002
|
active: registry.isCombo(c.id) && !registry.getModel(c.id),
|
|
2961
3003
|
// Operator takedown flag (hidden from catalogs, calls rejected).
|
|
2962
3004
|
disabled: c.disabled === true,
|
|
2963
|
-
selection: c.selection
|
|
3005
|
+
selection: normalizeSelectionStrategy(c.selection),
|
|
3006
|
+
// Per-member thinking-level tables (ADR-0003) live on each member ref;
|
|
3007
|
+
// the console edits them per model, never a block-wide table.
|
|
2964
3008
|
members: (c.models || []).map((entry) => {
|
|
2965
|
-
const ref = typeof entry === 'string'
|
|
3009
|
+
const ref = typeof entry === 'string'
|
|
3010
|
+
? { id: entry, weight: 1, effortMap: undefined }
|
|
3011
|
+
: { id: entry.id, weight: entry.weight ?? 1, effortMap: entry.effortMap };
|
|
2966
3012
|
const model = registry.getModel(ref.id);
|
|
2967
3013
|
return {
|
|
2968
3014
|
id: ref.id,
|
|
2969
3015
|
weight: ref.weight,
|
|
3016
|
+
effortMap: ref.effortMap,
|
|
2970
3017
|
registered: Boolean(model),
|
|
2971
3018
|
provider: model?.provider,
|
|
2972
3019
|
tier: model?.tier,
|
|
@@ -3266,6 +3313,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3266
3313
|
const providerFilter = query.provider?.trim().toLowerCase();
|
|
3267
3314
|
const connectedOnly = query.connected === '1' || query.connected === 'true';
|
|
3268
3315
|
const maintainedOnly = query.maintained === '1' || query.maintained === 'true';
|
|
3316
|
+
const typeFilter = query.type?.trim();
|
|
3269
3317
|
// Raw file read once — the aggregate is already built from the normalized
|
|
3270
3318
|
// view, so a retired-shape node here contributes no rows anyway.
|
|
3271
3319
|
const rawNodes = readProviderDefsFile()?.providers ?? {};
|
|
@@ -3276,6 +3324,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3276
3324
|
return models && typeof models === 'object' ? models : {};
|
|
3277
3325
|
};
|
|
3278
3326
|
const unified = await catalogRepository.list();
|
|
3327
|
+
// The AGGREGATE is the base: it is the only source that carries the whole
|
|
3328
|
+
// fact set per model (`type`, `modalities`, cost, overrides), and it is
|
|
3329
|
+
// keyed by the BARE def id. Registrations cannot be the base — their id is
|
|
3330
|
+
// `provider/upstreamModel`, which differs from the def id whenever a def
|
|
3331
|
+
// renames its upstream (`modelID`), so a registration-first list silently
|
|
3332
|
+
// dropped those rows.
|
|
3279
3333
|
const models = unified
|
|
3280
3334
|
.filter((p) => (!providerFilter || p.id.toLowerCase() === providerFilter) &&
|
|
3281
3335
|
(!connectedOnly || p.connected))
|
|
@@ -3294,7 +3348,8 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3294
3348
|
providerDisabled: takedowns.isDisabled(p.id),
|
|
3295
3349
|
maintained: Object.prototype.hasOwnProperty.call(defs, m.id),
|
|
3296
3350
|
}))
|
|
3297
|
-
.filter((m) => !maintainedOnly || m.maintained)
|
|
3351
|
+
.filter((m) => !maintainedOnly || m.maintained)
|
|
3352
|
+
.filter((m) => !typeFilter || (m.type ?? 'chat') === typeFilter);
|
|
3298
3353
|
});
|
|
3299
3354
|
return { status: 'ok', source: catalogRepository.lastSyncOrigin, total: models.length, models };
|
|
3300
3355
|
},
|
|
@@ -3394,9 +3449,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3394
3449
|
// registry snapshot (a false refusal would grey the button for up to the TTL).
|
|
3395
3450
|
store.invalidate();
|
|
3396
3451
|
let keyMeta;
|
|
3452
|
+
let providerReEnabled = false;
|
|
3397
3453
|
if (keyToStore) {
|
|
3398
3454
|
try {
|
|
3399
|
-
|
|
3455
|
+
const connected = await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager(), registry);
|
|
3456
|
+
keyMeta = connected.credential;
|
|
3457
|
+
providerReEnabled = connected.providerReEnabled === true;
|
|
3400
3458
|
}
|
|
3401
3459
|
catch (err) {
|
|
3402
3460
|
// Roll back only a node THIS request created — with ONE exception: the
|
|
@@ -3441,7 +3499,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3441
3499
|
.catch((err) => app.log.warn({ err, providerId: id }, 'post-create model pull errored (swallowed by design)'));
|
|
3442
3500
|
}
|
|
3443
3501
|
}
|
|
3444
|
-
return { status: 'ok', ...result };
|
|
3502
|
+
return { status: 'ok', ...result, ...(providerReEnabled ? { providerReEnabled } : {}) };
|
|
3445
3503
|
},
|
|
3446
3504
|
update: async (req, reply) => {
|
|
3447
3505
|
const { id } = req.params;
|
|
@@ -3481,9 +3539,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3481
3539
|
const inline = body.apiKeyInline ?? Boolean(existing.options?.apiKey);
|
|
3482
3540
|
const keyToStore = Boolean(body?.apiKey) && !inline;
|
|
3483
3541
|
let keyMeta;
|
|
3542
|
+
let providerReEnabled = false;
|
|
3484
3543
|
if (keyToStore) {
|
|
3485
3544
|
try {
|
|
3486
|
-
|
|
3545
|
+
const connected = await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager(), registry);
|
|
3546
|
+
keyMeta = connected.credential;
|
|
3547
|
+
providerReEnabled = connected.providerReEnabled === true;
|
|
3487
3548
|
}
|
|
3488
3549
|
catch (err) {
|
|
3489
3550
|
const failure = await mapStoreWriteFailure(err);
|
|
@@ -3524,7 +3585,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3524
3585
|
store.invalidate();
|
|
3525
3586
|
if (keyToStore)
|
|
3526
3587
|
clearSuspectForCredential(registry.getCircuitBreakerManager(), id, keyMeta?.keyHashPrefix);
|
|
3527
|
-
return { status: 'ok', ...result };
|
|
3588
|
+
return { status: 'ok', ...result, ...(providerReEnabled ? { providerReEnabled } : {}) };
|
|
3528
3589
|
},
|
|
3529
3590
|
connect: async (req, reply) => {
|
|
3530
3591
|
const { id } = req.params;
|
|
@@ -3544,7 +3605,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3544
3605
|
// A WriteFailedError maps to 5xx and NEVER falls back to OcrStore
|
|
3545
3606
|
// (Decision 3: read degrades with a badge, write refuses).
|
|
3546
3607
|
const store = await getCredentialStore();
|
|
3547
|
-
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
3608
|
+
const { credential: keyMeta, deduped, headPreserved, providerReEnabled } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
3548
3609
|
// Optional baseURL override — merge with the existing definition so we
|
|
3549
3610
|
// never wipe name/npm/models of a config-defined custom provider.
|
|
3550
3611
|
// No apiKey field → no implicit credential write on any binding.
|
|
@@ -3594,9 +3655,16 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3594
3655
|
// Non-null when the sink auto-activated the new key and this surface put
|
|
3595
3656
|
// the previous head back: the row the operator must be told is still head.
|
|
3596
3657
|
headPreserved,
|
|
3658
|
+
// Additive: a NEW credential lifted this provider's takedown (a deduped
|
|
3659
|
+
// reconnect never does) — the console says the models are back in routing.
|
|
3660
|
+
...(providerReEnabled ? { providerReEnabled } : {}),
|
|
3597
3661
|
// ADDITIVE: model auto-fill outcome (defs node created / models written).
|
|
3598
3662
|
nodeCreated: fill.nodeCreated,
|
|
3599
3663
|
modelsFilled: fill.pulled,
|
|
3664
|
+
// The reason when the fill could not run (an unauthenticated lane, an
|
|
3665
|
+
// unreachable upstream). Without it the console could only say "0 models"
|
|
3666
|
+
// and the operator had no next step.
|
|
3667
|
+
...(fill.fillError ? { fillError: fill.fillError } : {}),
|
|
3600
3668
|
message: `Provider '${id}' connected via ${credentialSinkLabel(store)}`,
|
|
3601
3669
|
};
|
|
3602
3670
|
}
|
|
@@ -3608,17 +3676,145 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3608
3676
|
}
|
|
3609
3677
|
},
|
|
3610
3678
|
/** Connect a preset whose plugin owns login. Materializes the def and
|
|
3611
|
-
* lifts a deletion tombstone. Refuses a provider that
|
|
3679
|
+
* lifts a deletion tombstone. Refuses a provider that cannot run without a key.
|
|
3680
|
+
*
|
|
3681
|
+
* Unlike the key and browser doors, this one has no fallback: the ONLY
|
|
3682
|
+
* credential is the login this machine's CLI already holds, so a failed model
|
|
3683
|
+
* read here means the door itself is shut. Reporting `connected: true` beside
|
|
3684
|
+
* that error told the operator a provider was serving when every request
|
|
3685
|
+
* would answer 401 — the card has to say NOT connected, with the reason. */
|
|
3612
3686
|
connectLocal: async (req, reply) => {
|
|
3613
3687
|
const { id } = req.params;
|
|
3614
|
-
const {
|
|
3615
|
-
if (!
|
|
3688
|
+
const { providerRunsCredentialless: runsLocal, ensurePresetProvider } = await import('../plugins/host.js');
|
|
3689
|
+
if (!runsLocal(id)) {
|
|
3616
3690
|
return reply.status(400).send({ success: false, error: `Provider '${id}' takes a credential` });
|
|
3617
3691
|
}
|
|
3692
|
+
// Did the node exist BEFORE this call? Asked before `ensurePresetProvider`
|
|
3693
|
+
// writes it, because afterwards the answer is always yes and the rollback
|
|
3694
|
+
// below could not tell its own write from operator state.
|
|
3695
|
+
//
|
|
3696
|
+
// Read the RAW providers map, not `getProviderNodeById`: that view DROPS a
|
|
3697
|
+
// node in the retired shape (Decision 9), so a legacy node would report
|
|
3698
|
+
// "absent" and the refusal would delete a file entry this call never
|
|
3699
|
+
// created. What matters here is whether the id is present at all.
|
|
3700
|
+
const { getProviderModelDefs } = await import('../opencode/user-config.js');
|
|
3701
|
+
const { readProviderDefsFile } = await import('../opencode/provider-defs.js');
|
|
3702
|
+
const nodeExisted = Object.hasOwn(readProviderDefsFile()?.providers ?? {}, id);
|
|
3618
3703
|
if (!(await ensurePresetProvider(id))) {
|
|
3619
3704
|
return reply.status(404).send({ success: false, error: `Provider '${id}' is not a plugin preset` });
|
|
3620
3705
|
}
|
|
3621
|
-
|
|
3706
|
+
const { ensureConnectedProviderBook } = await import('../opencode/catalog/auto-pull.js');
|
|
3707
|
+
const fill = await ensureConnectedProviderBook(id).catch((e) => ({
|
|
3708
|
+
nodeCreated: false,
|
|
3709
|
+
pulled: 0,
|
|
3710
|
+
fillError: String(e?.message ?? e),
|
|
3711
|
+
}));
|
|
3712
|
+
// A book that already holds models is a usable lane even when this run pulled
|
|
3713
|
+
// nothing new: `pulled === 0` is only fatal when the book is EMPTY.
|
|
3714
|
+
const hasModels = Object.keys(getProviderModelDefs(id) ?? {}).length > 0;
|
|
3715
|
+
// Only a CREDENTIAL verdict closes this door. A transport fault (a proxy that
|
|
3716
|
+
// is down, a DNS hiccup) says nothing about the login, and judging it "not
|
|
3717
|
+
// connected" would strand an operator whose lane is actually fine — the def is
|
|
3718
|
+
// written either way, so the wrong answer here costs them a working provider.
|
|
3719
|
+
// Lean toward letting them through: this check must never manufacture a
|
|
3720
|
+
// refusal it cannot prove.
|
|
3721
|
+
const looksUnauthenticated = fill.fillError !== undefined && UNAUTH_REFUSAL_RE.test(fill.fillError);
|
|
3722
|
+
if (looksUnauthenticated && !hasModels) {
|
|
3723
|
+
// Undo the node THIS call created. The preset card counts a
|
|
3724
|
+
// credentialless plugin as connected when its def exists, so a refused
|
|
3725
|
+
// connect that left the node behind would paint a card saying
|
|
3726
|
+
// "connected" beside a dialog saying "login missing". A node that was
|
|
3727
|
+
// already there is left alone — the refusal did not create it.
|
|
3728
|
+
let rolledBack = false;
|
|
3729
|
+
if (!nodeExisted) {
|
|
3730
|
+
try {
|
|
3731
|
+
const { deleteProviderDef } = await import('../opencode/user-config.js');
|
|
3732
|
+
rolledBack = deleteProviderDef(id).success;
|
|
3733
|
+
}
|
|
3734
|
+
catch {
|
|
3735
|
+
// Best effort: a leftover node is a cosmetic mismatch, not a reason
|
|
3736
|
+
// to answer the connect differently.
|
|
3737
|
+
}
|
|
3738
|
+
}
|
|
3739
|
+
app.log.warn({ providerId: id, fillError: fill.fillError }, 'connect-local refused: the machine login is not usable');
|
|
3740
|
+
return reply.status(409).send({
|
|
3741
|
+
status: 'error',
|
|
3742
|
+
success: false,
|
|
3743
|
+
connected: false,
|
|
3744
|
+
reasonCode: 'local_login_unavailable',
|
|
3745
|
+
// The plugin's own advice names a shell command; the console speaks about
|
|
3746
|
+
// the dialog the operator is looking at, and offers the doors they can
|
|
3747
|
+
// actually click instead.
|
|
3748
|
+
error: fill.fillError,
|
|
3749
|
+
nodeCreated: !nodeExisted && !rolledBack,
|
|
3750
|
+
modelsFilled: fill.pulled,
|
|
3751
|
+
});
|
|
3752
|
+
}
|
|
3753
|
+
// Success: record this machine's login as an ordinary credential ROW. That is
|
|
3754
|
+
// what makes the door visible and closable — the operator disables or deletes it
|
|
3755
|
+
// through the same routes as any key. Best-effort: a sink that refuses the row
|
|
3756
|
+
// (opencode v2) changes nothing about the connect that already succeeded.
|
|
3757
|
+
try {
|
|
3758
|
+
const { MACHINE_LOGIN_VALUE } = await import('../opencode/credentials/types.js');
|
|
3759
|
+
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
3760
|
+
const store = await getCredentialStore();
|
|
3761
|
+
if (!store.listCredentials(id).some((c) => c.machineLogin === true)) {
|
|
3762
|
+
await store.connectKey(id, MACHINE_LOGIN_VALUE);
|
|
3763
|
+
store.invalidate();
|
|
3764
|
+
}
|
|
3765
|
+
}
|
|
3766
|
+
catch (err) {
|
|
3767
|
+
app.log.warn({ providerId: id, err: String(err) }, 'connect-local: could not record the machine-login row (the provider still works)');
|
|
3768
|
+
}
|
|
3769
|
+
return {
|
|
3770
|
+
status: 'ok',
|
|
3771
|
+
success: true,
|
|
3772
|
+
connected: true,
|
|
3773
|
+
nodeCreated: fill.nodeCreated,
|
|
3774
|
+
modelsFilled: fill.pulled,
|
|
3775
|
+
// A fill that failed for a NON-credential reason (transport, 5xx, timeout)
|
|
3776
|
+
// still connects: the def is written and the models can be pulled later. The
|
|
3777
|
+
// reason rides along so the console can say why the book is empty without
|
|
3778
|
+
// claiming the provider is unusable.
|
|
3779
|
+
...(fill.fillError ? { fillWarning: fill.fillError } : {}),
|
|
3780
|
+
};
|
|
3781
|
+
},
|
|
3782
|
+
/**
|
|
3783
|
+
* Is the plugin's OWN login usable here? Asked BEFORE offering its `none` door,
|
|
3784
|
+
* so an unusable login is stated instead of discovered by a failed connect.
|
|
3785
|
+
* Cheap by contract (a stat, never a probe): the answer rides on
|
|
3786
|
+
* `ModelServicePlugin.localLogin`, and a plugin without it answers "unknown".
|
|
3787
|
+
*/
|
|
3788
|
+
localLoginStatus: async (req) => {
|
|
3789
|
+
const { id } = req.params;
|
|
3790
|
+
const { getModelServicePlugin, presetServicePlugin } = await import('../plugins/host.js');
|
|
3791
|
+
const { getProviderNodeById } = await import('../opencode/user-config.js');
|
|
3792
|
+
const def = getProviderNodeById(id);
|
|
3793
|
+
// Resolve through the def's WIRE when a node exists (a custom def can name
|
|
3794
|
+
// a plugin wire without being a preset), then through the plugin PRESETS:
|
|
3795
|
+
// the console asks this BEFORE the connect writes the node, so a
|
|
3796
|
+
// first-time connect has no def at all and the preset map is the answer.
|
|
3797
|
+
let plugin;
|
|
3798
|
+
if (def) {
|
|
3799
|
+
const { primaryProtocol, normalizeProtocols } = await import('../providers/protocols-field.js');
|
|
3800
|
+
const { wireFor } = await import('../providers/wire.js');
|
|
3801
|
+
const protocols = normalizeProtocols(def.protocols);
|
|
3802
|
+
plugin = getModelServicePlugin(wireFor(primaryProtocol(protocols)));
|
|
3803
|
+
}
|
|
3804
|
+
plugin ??= presetServicePlugin(id);
|
|
3805
|
+
if (!plugin?.localLogin) {
|
|
3806
|
+
// No declared self-login: this provider takes a credential, so the door the
|
|
3807
|
+
// caller is about to offer is not this one.
|
|
3808
|
+
return { status: 'ok', supported: false };
|
|
3809
|
+
}
|
|
3810
|
+
try {
|
|
3811
|
+
const state = plugin.localLogin(id);
|
|
3812
|
+
return { status: 'ok', supported: true, available: state.available, ...(state.command ? { command: state.command } : {}) };
|
|
3813
|
+
}
|
|
3814
|
+
catch (err) {
|
|
3815
|
+
// A check that cannot answer must not block the door.
|
|
3816
|
+
return { status: 'ok', supported: false, error: err instanceof Error ? err.message : String(err) };
|
|
3817
|
+
}
|
|
3622
3818
|
},
|
|
3623
3819
|
/** Resolve the model-service plugin serving a provider def's wire
|
|
3624
3820
|
* (plugin wires only — the vendor protocol stays in the plugin). */
|
|
@@ -3681,7 +3877,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3681
3877
|
return { status: 'ok', done: true, connected: false, error: 'login finished without a token' };
|
|
3682
3878
|
}
|
|
3683
3879
|
const credentialStore = await (await import('../opencode/credentials/index.js')).getCredentialStore();
|
|
3684
|
-
const { credential: keyMeta } = await connectKeyIdempotent(credentialStore, id, result.token,
|
|
3880
|
+
const { credential: keyMeta, providerReEnabled } = await connectKeyIdempotent(credentialStore, id, result.token, webLoginCredentialLabel(result.label), registry.getCircuitBreakerManager(), registry);
|
|
3685
3881
|
const { ensureConnectedProviderBook } = await import('../opencode/catalog/auto-pull.js');
|
|
3686
3882
|
const fill = await ensureConnectedProviderBook(id, { baseURL: r.baseURL }).catch((e) => ({
|
|
3687
3883
|
nodeCreated: false,
|
|
@@ -3691,7 +3887,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3691
3887
|
if (fill.fillError) {
|
|
3692
3888
|
app.log.warn({ providerId: id, fillError: fill.fillError }, 'web-login connect-time model auto-fill failed (swallowed by design)');
|
|
3693
3889
|
}
|
|
3694
|
-
return {
|
|
3890
|
+
return {
|
|
3891
|
+
status: 'ok', done: true, connected: true, credential: keyMeta,
|
|
3892
|
+
...(providerReEnabled ? { providerReEnabled } : {}),
|
|
3893
|
+
nodeCreated: fill.nodeCreated, modelsFilled: fill.pulled,
|
|
3894
|
+
...(fill.fillError ? { fillError: fill.fillError } : {}),
|
|
3895
|
+
};
|
|
3695
3896
|
}
|
|
3696
3897
|
catch (err) {
|
|
3697
3898
|
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
@@ -3721,7 +3922,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3721
3922
|
return { status: 'ok', connected: false, error: 'submit finished without a token' };
|
|
3722
3923
|
}
|
|
3723
3924
|
const credentialStore = await (await import('../opencode/credentials/index.js')).getCredentialStore();
|
|
3724
|
-
const { credential: keyMeta } = await connectKeyIdempotent(credentialStore, id, result.token,
|
|
3925
|
+
const { credential: keyMeta, providerReEnabled } = await connectKeyIdempotent(credentialStore, id, result.token, webLoginCredentialLabel(result.label), registry.getCircuitBreakerManager(), registry);
|
|
3725
3926
|
const { ensureConnectedProviderBook } = await import('../opencode/catalog/auto-pull.js');
|
|
3726
3927
|
const fill = await ensureConnectedProviderBook(id, { baseURL: r.baseURL }).catch((e) => ({
|
|
3727
3928
|
nodeCreated: false,
|
|
@@ -3731,7 +3932,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3731
3932
|
if (fill.fillError) {
|
|
3732
3933
|
app.log.warn({ providerId: id, fillError: fill.fillError }, 'web-login submit connect-time model auto-fill failed (swallowed by design)');
|
|
3733
3934
|
}
|
|
3734
|
-
return {
|
|
3935
|
+
return {
|
|
3936
|
+
status: 'ok', connected: true, credential: keyMeta,
|
|
3937
|
+
...(providerReEnabled ? { providerReEnabled } : {}),
|
|
3938
|
+
nodeCreated: fill.nodeCreated, modelsFilled: fill.pulled,
|
|
3939
|
+
...(fill.fillError ? { fillError: fill.fillError } : {}),
|
|
3940
|
+
};
|
|
3735
3941
|
}
|
|
3736
3942
|
catch (err) {
|
|
3737
3943
|
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
@@ -3838,7 +4044,11 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3838
4044
|
const inlineKey = expandEnvTemplate(def?.options?.apiKey);
|
|
3839
4045
|
const probeAttempts = [];
|
|
3840
4046
|
if (addressed) {
|
|
3841
|
-
|
|
4047
|
+
// A pinned machine-login row has no secret to test: the probe that makes sense
|
|
4048
|
+
// for it is the plugin's own login, i.e. the empty key.
|
|
4049
|
+
probeAttempts.push(isMachineLoginValue(addressed.key)
|
|
4050
|
+
? { key: '', credentialId: addressed.credentialId }
|
|
4051
|
+
: { key: addressed.key, credentialId: addressed.credentialId });
|
|
3842
4052
|
}
|
|
3843
4053
|
else if (body.apiKey) {
|
|
3844
4054
|
probeAttempts.push({ key: body.apiKey });
|
|
@@ -3847,14 +4057,18 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3847
4057
|
probeAttempts.push({ key: inlineKey });
|
|
3848
4058
|
}
|
|
3849
4059
|
else {
|
|
3850
|
-
|
|
4060
|
+
// Skip the marker: handing it to a transport would send `ocr:machine` as a
|
|
4061
|
+
// token and guarantee a 401 before the real keys are tried.
|
|
4062
|
+
for (const c of enabledChain) {
|
|
4063
|
+
if (isMachineLoginValue(c.key))
|
|
4064
|
+
continue;
|
|
3851
4065
|
probeAttempts.push({ key: c.key, credentialId: c.credentialId });
|
|
4066
|
+
}
|
|
3852
4067
|
}
|
|
3853
4068
|
if (probeAttempts.length === 0) {
|
|
3854
|
-
//
|
|
3855
|
-
// lets
|
|
3856
|
-
|
|
3857
|
-
if (providerDeclinesCredentials(id))
|
|
4069
|
+
// A plugin that can run on its own login probes it outside the credential
|
|
4070
|
+
// store. One empty attempt lets that probe run; a missing key is not a failure.
|
|
4071
|
+
if (providerMayUseLocalLogin(id))
|
|
3858
4072
|
probeAttempts.push({ key: '' });
|
|
3859
4073
|
}
|
|
3860
4074
|
if (probeAttempts.length === 0) {
|
|
@@ -4064,7 +4278,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4064
4278
|
// same key is deduped, never doubled) and ocr writes the local file. No
|
|
4065
4279
|
// auth.json write exists on any binding.
|
|
4066
4280
|
const store = await getCredentialStore();
|
|
4067
|
-
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
4281
|
+
const { credential: keyMeta, deduped, headPreserved, providerReEnabled } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
4068
4282
|
store.invalidate();
|
|
4069
4283
|
// Decision 6: a key rotation handed to the store is a reconnect — clear SUSPECT.
|
|
4070
4284
|
clearSuspectForCredential(registry.getCircuitBreakerManager(), id, keyMeta?.keyHashPrefix);
|
|
@@ -4074,6 +4288,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4074
4288
|
deduped,
|
|
4075
4289
|
credential: keyMeta,
|
|
4076
4290
|
headPreserved,
|
|
4291
|
+
...(providerReEnabled ? { providerReEnabled } : {}),
|
|
4077
4292
|
message: `Credential updated for '${id}'`,
|
|
4078
4293
|
};
|
|
4079
4294
|
}
|
|
@@ -4220,6 +4435,17 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4220
4435
|
// opencode v2 composite fields (capabilities/settings/headers/body/compatibility/
|
|
4221
4436
|
// variants): the form is a full-definition editor — values present in the
|
|
4222
4437
|
// payload (even {}) replace wholesale; absent keys keep their old values.
|
|
4438
|
+
// Exception: `compatibility.suppressReasoningEffort` is not editable in
|
|
4439
|
+
// the form, so a "full replace" of the block must carry it over — else
|
|
4440
|
+
// any console save erases a wire quirk only the defs file can declare.
|
|
4441
|
+
if (patch.compatibility) {
|
|
4442
|
+
next.compatibility = {
|
|
4443
|
+
...(existing.compatibility?.suppressReasoningEffort === true
|
|
4444
|
+
? { suppressReasoningEffort: true }
|
|
4445
|
+
: {}),
|
|
4446
|
+
...patch.compatibility,
|
|
4447
|
+
};
|
|
4448
|
+
}
|
|
4223
4449
|
const result = upsertProviderModel(id, targetId, next);
|
|
4224
4450
|
if (!result.success)
|
|
4225
4451
|
return reply.status(400).send(result);
|
|
@@ -4568,6 +4794,17 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4568
4794
|
const guard = await guardStoreCredential(store, id, credentialId);
|
|
4569
4795
|
if (!guard.ok)
|
|
4570
4796
|
return reply.status(guard.status).send(guard.body);
|
|
4797
|
+
// The machine-login row's name is FIXED — it comes from the console's own
|
|
4798
|
+
// vocabulary, not from a label, so there is nothing for a rename to change.
|
|
4799
|
+
// Accepting one would create a second authority for what the row is called.
|
|
4800
|
+
if (guard.meta.machineLogin) {
|
|
4801
|
+
return reply.status(409).send({
|
|
4802
|
+
status: 'error',
|
|
4803
|
+
success: false,
|
|
4804
|
+
reasonCode: 'fixed_credential_name',
|
|
4805
|
+
error: `credential '${credentialId}' is this machine's login — its name is fixed and cannot be renamed`,
|
|
4806
|
+
});
|
|
4807
|
+
}
|
|
4571
4808
|
try {
|
|
4572
4809
|
const credential = await store.rename(credentialId, label);
|
|
4573
4810
|
store.invalidate();
|
|
@@ -4619,7 +4856,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4619
4856
|
// as disable), so a re-import lands parked with its badge and one-click
|
|
4620
4857
|
// restore; SUSPECT keeps its opposite lifecycle (reconnect clears it).
|
|
4621
4858
|
let takedownAnchored = false;
|
|
4622
|
-
|
|
4859
|
+
// A real key is anchored: the read sync would re-import it from the client as
|
|
4860
|
+
// clean, undoing the delete. The machine-login marker has no client copy and is
|
|
4861
|
+
// re-created only by `connect-local`, so anchoring it would make a later
|
|
4862
|
+
// connect silently land DISABLED — the operator would "delete then reconnect"
|
|
4863
|
+
// and get a parked row. Delete it plainly: the row is the whole record.
|
|
4864
|
+
if (prefix && !guard.meta.machineLogin) {
|
|
4623
4865
|
const state = registry.getCircuitBreakerManager().getCredentialStateStore();
|
|
4624
4866
|
// An ALREADY-parked key material keeps its own note: `disable()` rewrites
|
|
4625
4867
|
// `reason` when it differs, and a delete must not launder the operator's
|
|
@@ -4739,7 +4981,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4739
4981
|
* (`buildDirectPool` → `operator_disabled`), so `/v1/models` omits it and
|
|
4740
4982
|
* direct ids 404. State lives in the GLOBAL takedown ledger, never in
|
|
4741
4983
|
* providers.json (that file is connection truth + the sync materializer's
|
|
4742
|
-
* source, ADR-0010).
|
|
4984
|
+
* source, ADR-0010). Operator lifecycle: `/enable` lifts it, and so does
|
|
4985
|
+
* connecting NEW key material (`connectKeyIdempotent`); an idempotent
|
|
4986
|
+
* reconnect, cooldown, breaker reset or Push never does.
|
|
4743
4987
|
*/
|
|
4744
4988
|
providerSetDisabled: async (req, reply, disabled) => {
|
|
4745
4989
|
const { id } = req.params;
|
|
@@ -4874,6 +5118,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4874
5118
|
app.patch(`${prefix}/opencode/providers/:id`, withPoolSync(registry, ocHandlers.update));
|
|
4875
5119
|
app.post(`${prefix}/opencode/providers/:id/connect`, withPoolSync(registry, ocHandlers.connect));
|
|
4876
5120
|
app.post(`${prefix}/opencode/providers/:id/connect-local`, withPoolSync(registry, ocHandlers.connectLocal));
|
|
5121
|
+
// Cheap "is the plugin's own login usable?" check — asked BEFORE the `none`
|
|
5122
|
+
// door is offered, so an unusable login is stated, not discovered by failure.
|
|
5123
|
+
app.get(`${prefix}/opencode/providers/:id/local-login`, ocHandlers.localLoginStatus);
|
|
4877
5124
|
// Generic plugin web-authorization seam (device flow): start opens the
|
|
4878
5125
|
// vendor login page; poll returns done+token and wires the fresh token
|
|
4879
5126
|
// into the credential store. The plugin owns the whole protocol.
|
|
@@ -4901,8 +5148,65 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
4901
5148
|
app.get(`${prefix}/plugins`, async () => {
|
|
4902
5149
|
// views only — a read route must not clear+rebuild the live registry
|
|
4903
5150
|
// (in-flight dispatch/probe would see an empty plugin set mid-rebuild)
|
|
4904
|
-
const {
|
|
4905
|
-
return { status: 'ok', plugins:
|
|
5151
|
+
const { listInstalledPluginsWithEnvironment } = await import('../plugins/host.js');
|
|
5152
|
+
return { status: 'ok', plugins: listInstalledPluginsWithEnvironment() };
|
|
5153
|
+
});
|
|
5154
|
+
/**
|
|
5155
|
+
* Environment preflight for the loaded packages (ADR-0042).
|
|
5156
|
+
*
|
|
5157
|
+
* ONE route, and NOT folded into `GET /plugins`: that listing is polled from
|
|
5158
|
+
* the page, so folding a subprocess-spawning probe into it would run every
|
|
5159
|
+
* package's check on every poll. `fresh` is the console's explicit re-check
|
|
5160
|
+
* button; without it a report inside the TTL is served from cache (stale-
|
|
5161
|
+
* while-revalidate), which is what makes "I just installed the CLI" fixable
|
|
5162
|
+
* with one click instead of a restart.
|
|
5163
|
+
*
|
|
5164
|
+
* The engine decides nothing here. Each answer is the package's own verdict
|
|
5165
|
+
* in its own vocabulary, resolved by the console through that package's
|
|
5166
|
+
* `warningLabels`; core holds no vendor knowledge and no minimum versions.
|
|
5167
|
+
*/
|
|
5168
|
+
app.get(`${prefix}/plugins/environment`, async (req) => {
|
|
5169
|
+
const query = req.query;
|
|
5170
|
+
const ids = typeof query.id === 'string' && query.id.trim() !== '' ? [query.id.trim()] : undefined;
|
|
5171
|
+
const { refreshPluginEnvironment } = await import('../plugins/host.js');
|
|
5172
|
+
const environment = await refreshPluginEnvironment({
|
|
5173
|
+
...(ids ? { ids } : {}),
|
|
5174
|
+
fresh: query.fresh === '1' || query.fresh === 'true',
|
|
5175
|
+
});
|
|
5176
|
+
return { status: 'ok', environment };
|
|
5177
|
+
});
|
|
5178
|
+
/**
|
|
5179
|
+
* Dismiss (or re-arm) one package's environment advisories (ADR-0042).
|
|
5180
|
+
*
|
|
5181
|
+
* The escape hatch a SOFT warning requires: the verdict comes from the
|
|
5182
|
+
* package's own probe, and a package can be wrong. Acknowledging changes NO
|
|
5183
|
+
* lifecycle state — the package stays loaded, enabled and routable; it only
|
|
5184
|
+
* stops the dismissed codes from counting toward the badge. Records are
|
|
5185
|
+
* scoped to the installed VERSION, so a new build re-arms them.
|
|
5186
|
+
*
|
|
5187
|
+
* `codes` omitted/empty clears the package's record (the console's "show
|
|
5188
|
+
* these again"); a non-empty list adds to it.
|
|
5189
|
+
*/
|
|
5190
|
+
app.post(`${prefix}/plugins/environment/ack`, async (req, reply) => {
|
|
5191
|
+
const body = req.body;
|
|
5192
|
+
const id = typeof body?.id === 'string' ? body.id.trim() : '';
|
|
5193
|
+
if (!id)
|
|
5194
|
+
return reply.code(400).send({ status: 'error', error: 'id is required' });
|
|
5195
|
+
const codes = Array.isArray(body?.codes)
|
|
5196
|
+
? body.codes.filter((c) => typeof c === 'string' && c !== '')
|
|
5197
|
+
: [];
|
|
5198
|
+
const { acknowledgePluginEnvironment, clearPluginEnvironmentAcks, listPluginEnvironmentAcks } = await import('../plugins/host.js');
|
|
5199
|
+
try {
|
|
5200
|
+
if (codes.length === 0) {
|
|
5201
|
+
clearPluginEnvironmentAcks(id);
|
|
5202
|
+
return { status: 'ok', acknowledged: [], acks: listPluginEnvironmentAcks() };
|
|
5203
|
+
}
|
|
5204
|
+
const result = acknowledgePluginEnvironment(id, codes);
|
|
5205
|
+
return { status: 'ok', ...result, acks: listPluginEnvironmentAcks() };
|
|
5206
|
+
}
|
|
5207
|
+
catch (err) {
|
|
5208
|
+
return reply.code(404).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
5209
|
+
}
|
|
4906
5210
|
});
|
|
4907
5211
|
app.post(`${prefix}/plugins/reload`, async () => {
|
|
4908
5212
|
const { loadInstalledPlugins, syncPluginPresets, listInstalledPlugins } = await import('../plugins/host.js');
|
|
@@ -5015,13 +5319,26 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
5015
5319
|
});
|
|
5016
5320
|
app.delete(`${prefix}/plugins/:id/uninstall`, async (req, reply) => {
|
|
5017
5321
|
const { id } = req.params;
|
|
5322
|
+
// The operator's second choice in the same confirmation dialog: whether the
|
|
5323
|
+
// plugin's SETTINGS go too. Absent = keep them (a reinstall resumes the
|
|
5324
|
+
// operator's values); `?purgeConfig=1` = the clean slate.
|
|
5325
|
+
const query = req.query;
|
|
5326
|
+
const purgeConfig = query.purgeConfig === '1' || query.purgeConfig === 'true';
|
|
5018
5327
|
try {
|
|
5019
5328
|
const { uninstallPlugin, loadInstalledPlugins, listInstalledPlugins } = await import('../plugins/host.js');
|
|
5020
|
-
const result = await uninstallPlugin(id);
|
|
5329
|
+
const result = await uninstallPlugin(id, { purgeConfig });
|
|
5021
5330
|
await loadInstalledPlugins();
|
|
5022
5331
|
const plugins = listInstalledPlugins();
|
|
5023
5332
|
await refreshDirectPool(registry);
|
|
5024
|
-
return {
|
|
5333
|
+
return {
|
|
5334
|
+
status: 'ok',
|
|
5335
|
+
removed: result.removed,
|
|
5336
|
+
providersRemoved: result.providersRemoved,
|
|
5337
|
+
// What uninstall deliberately did NOT delete, so the console can say
|
|
5338
|
+
// it instead of the operator discovering a kept artifact later.
|
|
5339
|
+
kept: result.kept,
|
|
5340
|
+
plugins,
|
|
5341
|
+
};
|
|
5025
5342
|
}
|
|
5026
5343
|
catch (err) {
|
|
5027
5344
|
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
@@ -5068,96 +5385,363 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
5068
5385
|
return reply.code(413).send({ status: 'error', error: 'package exceeds 64 MiB' });
|
|
5069
5386
|
}
|
|
5070
5387
|
try {
|
|
5071
|
-
|
|
5072
|
-
//
|
|
5073
|
-
//
|
|
5074
|
-
//
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5078
|
-
|
|
5079
|
-
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5388
|
+
// ONE pipeline for every package an operator installs, whether it
|
|
5389
|
+
// arrived as an upload or from the market (ADR-0037): the version
|
|
5390
|
+
// gate, engine parking, discard-and-roll-back, preset registration and
|
|
5391
|
+
// pool refresh live in `installPluginBytes`.
|
|
5392
|
+
const { installPluginBytes } = await import('../plugins/install-run.js');
|
|
5393
|
+
const outcome = await installPluginBytes(new Uint8Array(bytes), registry);
|
|
5394
|
+
return reply.code(outcome.statusCode).send(outcome.body);
|
|
5395
|
+
}
|
|
5396
|
+
catch (err) {
|
|
5397
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
5398
|
+
}
|
|
5399
|
+
});
|
|
5400
|
+
/* ---------------------------------------------------------------------
|
|
5401
|
+
* Plugin MARKETPLACE (ADR-0037).
|
|
5402
|
+
*
|
|
5403
|
+
* `plugins/registry.json` names GitHub repositories; the market reads each
|
|
5404
|
+
* one's `plugin.json` and logo once, caches them under the plugins root,
|
|
5405
|
+
* and offers an install that downloads the package the repository publishes
|
|
5406
|
+
* and hands it to the SAME pipeline the upload verb uses. Nothing here
|
|
5407
|
+
* changes routing state — installing is the only write, and it writes
|
|
5408
|
+
* through `installPluginBytes`.
|
|
5409
|
+
* ------------------------------------------------------------------- */
|
|
5410
|
+
app.get(`${prefix}/plugins/market`, async (req) => {
|
|
5411
|
+
const { refresh } = req.query;
|
|
5412
|
+
const { loadMarket } = await import('../plugins/market.js');
|
|
5413
|
+
const snapshot = await loadMarket({ refresh: refresh === '1' || refresh === 'true' });
|
|
5414
|
+
return { status: 'ok', ...snapshot };
|
|
5415
|
+
});
|
|
5416
|
+
// VERSION MONITORING (ADR-0037 §7): every installed plugin that a registry
|
|
5417
|
+
// entry describes, compared against the repository's current manifest.
|
|
5418
|
+
// Same read path as the market (one cache, one registry), projected onto
|
|
5419
|
+
// "what did I install, and has its repository moved?".
|
|
5420
|
+
app.get(`${prefix}/plugins/updates`, async (req) => {
|
|
5421
|
+
const { refresh } = req.query;
|
|
5422
|
+
const { checkPluginUpdates } = await import('../plugins/market-updates.js');
|
|
5423
|
+
const snapshot = await checkPluginUpdates({ refresh: refresh === '1' || refresh === 'true' });
|
|
5424
|
+
return { status: 'ok', ...snapshot };
|
|
5425
|
+
});
|
|
5426
|
+
// The SOURCES the private scan unions (ADR-0037 §10). A source is a scope
|
|
5427
|
+
// first (`owner`, `owner/repo`, `owner/pattern*`) and a credential second —
|
|
5428
|
+
// the token is a FIELD, optional, and empty means "public repositories only".
|
|
5429
|
+
// Every answer goes through `describeMarketSources`: the VALUE never leaves
|
|
5430
|
+
// the backend, and the STORED shape that carries it never sits in a response
|
|
5431
|
+
// body just because it happened to be in the object being returned.
|
|
5432
|
+
app.get(`${prefix}/plugins/market/sources`, async () => {
|
|
5433
|
+
const { readMarketSettings, describeMarketSources } = await import('../plugins/market.js');
|
|
5434
|
+
const { sources } = readMarketSettings();
|
|
5435
|
+
return { status: 'ok', sources: describeMarketSources(sources) };
|
|
5436
|
+
});
|
|
5437
|
+
app.post(`${prefix}/plugins/market/sources`, async (req, reply) => {
|
|
5438
|
+
const body = (req.body ?? {});
|
|
5439
|
+
if (typeof body.target !== 'string' || !body.target.trim()) {
|
|
5440
|
+
return reply
|
|
5441
|
+
.code(400)
|
|
5442
|
+
.send({ status: 'error', error: 'body.target is required (owner, owner/repo or owner/pattern*)' });
|
|
5443
|
+
}
|
|
5444
|
+
// The label is REQUIRED (ADR-0037 §9): it names the source on every card
|
|
5445
|
+
// the scan produces, and it is what a later rename matches on. A missing
|
|
5446
|
+
// or blank one is a 400 here, not a row the console has to guess at.
|
|
5447
|
+
if (typeof body.label !== 'string' || !body.label.trim()) {
|
|
5448
|
+
return reply.code(400).send({ status: 'error', error: 'body.label is required — give this source a name' });
|
|
5449
|
+
}
|
|
5450
|
+
const { addMarketSource, describeMarketSources } = await import('../plugins/market.js');
|
|
5451
|
+
try {
|
|
5452
|
+
const settings = addMarketSource({
|
|
5453
|
+
target: body.target,
|
|
5454
|
+
label: body.label,
|
|
5455
|
+
...(typeof body.token === 'string' && body.token.trim() ? { token: body.token } : {}),
|
|
5456
|
+
});
|
|
5457
|
+
return { status: 'ok', sources: describeMarketSources(settings.sources) };
|
|
5458
|
+
}
|
|
5459
|
+
catch (err) {
|
|
5460
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
5461
|
+
}
|
|
5462
|
+
});
|
|
5463
|
+
// EDIT one row in place, its SCOPE included. `target` identifies the row and
|
|
5464
|
+
// `nextTarget` (optional) is the scope it should carry afterwards — a rename
|
|
5465
|
+
// is one field away from the row instead of a delete + add that would lose
|
|
5466
|
+
// `addedAt` and a token the console can no longer read.
|
|
5467
|
+
//
|
|
5468
|
+
// `label` is REQUIRED (ADR-0037 §9): absent or blank is a 400, because it
|
|
5469
|
+
// is the name every card of this source prints. `token` takes `undefined` =
|
|
5470
|
+
// keep, `null` or `''` = clear, a string = replace. The console never
|
|
5471
|
+
// received the token, so "blank" can only mean "keep" — an edit that
|
|
5472
|
+
// silently dropped a credential because the form could not show it would
|
|
5473
|
+
// break a private source on an unrelated label change.
|
|
5474
|
+
app.patch(`${prefix}/plugins/market/sources`, async (req, reply) => {
|
|
5475
|
+
const body = (req.body ?? {});
|
|
5476
|
+
if (typeof body.target !== 'string' || !body.target.trim()) {
|
|
5477
|
+
return reply.code(400).send({ status: 'error', error: 'body.target is required' });
|
|
5478
|
+
}
|
|
5479
|
+
if (typeof body.label !== 'string' || !body.label.trim()) {
|
|
5480
|
+
return reply.code(400).send({ status: 'error', error: 'body.label is required — give this source a name' });
|
|
5481
|
+
}
|
|
5482
|
+
for (const field of ['token', 'nextTarget']) {
|
|
5483
|
+
const value = body[field];
|
|
5484
|
+
if (value !== undefined && value !== null && typeof value !== 'string') {
|
|
5485
|
+
return reply.code(400).send({ status: 'error', error: `body.${field} must be a string or null` });
|
|
5087
5486
|
}
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5091
|
-
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
//
|
|
5105
|
-
//
|
|
5106
|
-
//
|
|
5107
|
-
|
|
5108
|
-
const
|
|
5109
|
-
if (
|
|
5110
|
-
|
|
5111
|
-
|
|
5112
|
-
|
|
5113
|
-
|
|
5114
|
-
|
|
5115
|
-
|
|
5116
|
-
|
|
5117
|
-
|
|
5118
|
-
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
|
|
5122
|
-
|
|
5123
|
-
|
|
5124
|
-
status: 'error',
|
|
5125
|
-
error: `package rejected and discarded (${view?.error ?? 'unknown error'}); rolled back to the previously installed version`,
|
|
5126
|
-
plugins: listInstalledPlugins(),
|
|
5127
|
-
});
|
|
5128
|
-
}
|
|
5129
|
-
// Reload AFTER the discard: otherwise the response would hand the
|
|
5130
|
-
// console a row for a package that is no longer on disk (the list is
|
|
5131
|
-
// the disk's truth, not the last failed import's).
|
|
5132
|
-
await loadInstalledPlugins();
|
|
5133
|
-
return reply
|
|
5134
|
-
.code(422)
|
|
5135
|
-
.send({ status: 'error', error: `package installed but failed to load (discarded): ${view?.error ?? 'unknown error'}`, plugins: listInstalledPlugins() });
|
|
5487
|
+
}
|
|
5488
|
+
const { normalizeSourceTarget, readMarketSettings, updateMarketSource, describeMarketSources } = await import('../plugins/market.js');
|
|
5489
|
+
const oldTarget = body.target.trim();
|
|
5490
|
+
const before = readMarketSettings().sources.find((row) => row.target.toLowerCase() === oldTarget.toLowerCase());
|
|
5491
|
+
// The scope this row will carry afterwards, so the rename can be seen
|
|
5492
|
+
// without diffing two arrays by heuristic.
|
|
5493
|
+
const intended = body.nextTarget === undefined ? before?.target : (normalizeSourceTarget(body.nextTarget) ?? undefined);
|
|
5494
|
+
const renamed = Boolean(before && intended && intended.toLowerCase() !== before.target.toLowerCase());
|
|
5495
|
+
try {
|
|
5496
|
+
const settings = updateMarketSource({
|
|
5497
|
+
target: body.target,
|
|
5498
|
+
label: body.label,
|
|
5499
|
+
...(typeof body.nextTarget === 'string' ? { nextTarget: body.nextTarget } : {}),
|
|
5500
|
+
...(body.token !== undefined ? { token: body.token } : {}),
|
|
5501
|
+
});
|
|
5502
|
+
const { forgetSourceOutcome, relabelSourceEntries } = await import('../plugins/source-index.js');
|
|
5503
|
+
// The stored verdict described the OLD credential or scope: drop it, or
|
|
5504
|
+
// the row would claim a credential/scope that is gone works. A
|
|
5505
|
+
// LABEL-only edit changes neither, so its verdict is still the truth
|
|
5506
|
+
// about the fields the scan actually ran with and must survive.
|
|
5507
|
+
const credentialsChanged = body.token !== undefined;
|
|
5508
|
+
if (renamed || credentialsChanged)
|
|
5509
|
+
forgetSourceOutcome(body.target);
|
|
5510
|
+
// A row's DISPLAY NAME is what the console prints on each of its cards
|
|
5511
|
+
// (`via`), so any change to it — the label ALONE or a scope rename — must
|
|
5512
|
+
// travel to the index. Rewriting only on a rename left a label-only edit
|
|
5513
|
+
// showing the old name for the whole row cache TTL. Skipped when the OLD
|
|
5514
|
+
// name was ambiguous: with two rows sharing it the index cannot say which
|
|
5515
|
+
// one claimed an entry, and the next Sync re-derives `via` anyway.
|
|
5516
|
+
if (before && intended) {
|
|
5517
|
+
const beforeName = before.label ?? before.target;
|
|
5518
|
+
const afterRow = settings.sources.find((row) => row.target === intended);
|
|
5519
|
+
const afterName = afterRow ? (afterRow.label ?? afterRow.target) : undefined;
|
|
5520
|
+
const shared = settings.sources.some((row) => row.target !== intended && (row.label ?? row.target) === beforeName);
|
|
5521
|
+
if (afterName && afterName !== beforeName && !shared)
|
|
5522
|
+
relabelSourceEntries(beforeName, afterName);
|
|
5136
5523
|
}
|
|
5137
|
-
|
|
5138
|
-
// after a verified successful load, BEFORE the pool refresh so the
|
|
5139
|
-
// defs are routable immediately on the next dispatch. An engine-refused
|
|
5140
|
-
// package reaches this line too: it loaded nothing, so `syncPluginPresets`
|
|
5141
|
-
// has nothing of it to register, and its row stays DISABLED in `plugins`.
|
|
5142
|
-
const registered = await syncPluginPresets();
|
|
5143
|
-
await refreshDirectPool(registry);
|
|
5144
|
-
return {
|
|
5145
|
-
status: 'ok',
|
|
5146
|
-
id: installed,
|
|
5147
|
-
version: installedVersion,
|
|
5148
|
-
replacedVersion,
|
|
5149
|
-
plugins,
|
|
5150
|
-
registered,
|
|
5151
|
-
// Kept in the 200 body so the console can toast the honest outcome:
|
|
5152
|
-
// the bytes landed, but the package answers nothing until one side
|
|
5153
|
-
// is updated. A green "installed" toast over a red row is the one
|
|
5154
|
-
// reading an operator must not be left with.
|
|
5155
|
-
...(incompatible ? { incompatible: true, error: view.error } : {}),
|
|
5156
|
-
};
|
|
5524
|
+
return { status: 'ok', sources: describeMarketSources(settings.sources) };
|
|
5157
5525
|
}
|
|
5158
5526
|
catch (err) {
|
|
5159
|
-
|
|
5527
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
5528
|
+
return reply.code(message.includes('is not a configured source') ? 404 : 400).send({ status: 'error', error: message });
|
|
5529
|
+
}
|
|
5530
|
+
});
|
|
5531
|
+
app.delete(`${prefix}/plugins/market/sources`, async (req, reply) => {
|
|
5532
|
+
const target = req.query.target ?? '';
|
|
5533
|
+
if (!target.trim())
|
|
5534
|
+
return reply.code(400).send({ status: 'error', error: 'query.target is required' });
|
|
5535
|
+
const { removeMarketSource, describeMarketSources, pruneSourceIndexForRemovedSource } = await import('../plugins/market.js');
|
|
5536
|
+
const settings = removeMarketSource(target);
|
|
5537
|
+
// A removed row has no verdict to keep — and a later re-add must not
|
|
5538
|
+
// inherit the deleted credential's answer.
|
|
5539
|
+
const { forgetSourceOutcome } = await import('../plugins/source-index.js');
|
|
5540
|
+
forgetSourceOutcome(target);
|
|
5541
|
+
// And no card should outlive it either: an entry only this row's scope
|
|
5542
|
+
// could reach is backed by nothing once the row is gone. Remaining
|
|
5543
|
+
// sources keep their own cards.
|
|
5544
|
+
pruneSourceIndexForRemovedSource(settings.sources);
|
|
5545
|
+
return { status: 'ok', egress: settings.egress, sources: describeMarketSources(settings.sources) };
|
|
5546
|
+
});
|
|
5547
|
+
// The SOURCE half of the market (ADR-0037 §9): the index a scan produced.
|
|
5548
|
+
// It is a SECOND registry the market merges with the committed one, never a
|
|
5549
|
+
// replacement — the committed rows are official, these are "found by source".
|
|
5550
|
+
app.get(`${prefix}/plugins/market/source-index`, async () => {
|
|
5551
|
+
const { sourceIndexState, readSourceIndex } = await import('../plugins/source-index.js');
|
|
5552
|
+
const state = sourceIndexState();
|
|
5553
|
+
// The rows the index contributes, so the console can show what was found
|
|
5554
|
+
// without a second round trip through the whole market.
|
|
5555
|
+
const index = readSourceIndex();
|
|
5556
|
+
return {
|
|
5557
|
+
status: 'ok',
|
|
5558
|
+
...state,
|
|
5559
|
+
entries: (index?.entries ?? []).filter((entry) => entry.ok),
|
|
5560
|
+
};
|
|
5561
|
+
});
|
|
5562
|
+
// Build (or REBUILD) the index from the configured SOURCES. One listing plus
|
|
5563
|
+
// one manifest read per candidate — expensive by construction, so this is an
|
|
5564
|
+
// explicit operator verb and never runs on a page load.
|
|
5565
|
+
app.post(`${prefix}/plugins/market/source-index/refresh`, async (_req, reply) => {
|
|
5566
|
+
const { discoverFromSources } = await import('../plugins/market.js');
|
|
5567
|
+
const result = await discoverFromSources();
|
|
5568
|
+
// A refused run carries its per-source outcomes too: "no source could be
|
|
5569
|
+
// read" is one sentence, but WHICH row is broken and why is the only thing
|
|
5570
|
+
// the operator can act on.
|
|
5571
|
+
if (result.error) {
|
|
5572
|
+
return reply
|
|
5573
|
+
.code(422)
|
|
5574
|
+
.send({ status: 'error', error: result.error, sources: result.perSource ?? [] });
|
|
5575
|
+
}
|
|
5576
|
+
const { sourceIndexState } = await import('../plugins/source-index.js');
|
|
5577
|
+
return { status: 'ok', ...sourceIndexState(), entries: (result.index?.entries ?? []).filter((entry) => entry.ok) };
|
|
5578
|
+
});
|
|
5579
|
+
// The market's own setting (`<ocrHome>/plugins/market.json`, ADR-0037): the
|
|
5580
|
+
// leg a market read and install take. Deliberately NOT `config.yaml` — the
|
|
5581
|
+
// config schema is versioned and frozen (ADR-0016) and this is one enum
|
|
5582
|
+
// owned entirely by the market, so a schema migration would be pure cost.
|
|
5583
|
+
//
|
|
5584
|
+
// `sources` answers MASKED (ADR-0037 §8): the stored shape carries the token
|
|
5585
|
+
// value, and a setting-read is not a reason for a secret to reach the console.
|
|
5586
|
+
app.get(`${prefix}/plugins/market/settings`, async () => {
|
|
5587
|
+
const { readMarketSettings, marketSettingsPath, describeMarketSources, registrySyncState, registryFilePath, OFFICIAL_REGISTRY_URL, } = await import('../plugins/market.js');
|
|
5588
|
+
const settings = readMarketSettings();
|
|
5589
|
+
return {
|
|
5590
|
+
status: 'ok',
|
|
5591
|
+
egress: settings.egress,
|
|
5592
|
+
sources: describeMarketSources(settings.sources),
|
|
5593
|
+
// The URL is a CONSTANT, not a setting: the console shows it so the
|
|
5594
|
+
// operator can see what is being fetched, and never accepts a value.
|
|
5595
|
+
officialRegistryUrl: OFFICIAL_REGISTRY_URL,
|
|
5596
|
+
registrySyncEnabled: settings.registrySync,
|
|
5597
|
+
registryFile: registryFilePath(),
|
|
5598
|
+
registrySync: registrySyncState(),
|
|
5599
|
+
path: marketSettingsPath(),
|
|
5600
|
+
};
|
|
5601
|
+
});
|
|
5602
|
+
app.put(`${prefix}/plugins/market/settings`, async (req, reply) => {
|
|
5603
|
+
const body = (req.body ?? {});
|
|
5604
|
+
if (body.egress !== undefined && body.egress !== 'direct' && body.egress !== 'proxy') {
|
|
5605
|
+
return reply.code(400).send({ status: 'error', error: "body.egress must be 'direct' or 'proxy'" });
|
|
5606
|
+
}
|
|
5607
|
+
if (body.discoveryOrgs !== undefined && !Array.isArray(body.discoveryOrgs)) {
|
|
5608
|
+
return reply.code(400).send({ status: 'error', error: 'body.discoveryOrgs must be an array of org names' });
|
|
5609
|
+
}
|
|
5610
|
+
// A switch. A non-boolean is REFUSED rather than coerced: silently reading
|
|
5611
|
+
// `"false"` as truthy would leave the pull on when the operator turned it
|
|
5612
|
+
// off, which is the one direction that costs them privacy instead of bytes.
|
|
5613
|
+
if (body.registrySync !== undefined && typeof body.registrySync !== 'boolean') {
|
|
5614
|
+
return reply.code(400).send({ status: 'error', error: 'body.registrySync must be a boolean' });
|
|
5615
|
+
}
|
|
5616
|
+
// `sources` is READ here and written through `/market/sources` — add,
|
|
5617
|
+
// PATCH and DELETE. Accepting a whole list on this route would make a
|
|
5618
|
+
// malformed row vanish silently (`normalizeSourceRow` drops what it cannot
|
|
5619
|
+
// read), which is the opposite of the org check right below.
|
|
5620
|
+
if (body.sources !== undefined) {
|
|
5621
|
+
return reply
|
|
5622
|
+
.code(400)
|
|
5623
|
+
.send({ status: 'error', error: 'body.sources is not writable here — use POST/PATCH/DELETE /plugins/market/sources' });
|
|
5624
|
+
}
|
|
5625
|
+
const { writeMarketSettings, marketSettingsPath, normalizeOrgName, describeMarketSources, syncRemoteRegistry, startRegistrySyncScheduler, registrySyncState, registryFilePath, OFFICIAL_REGISTRY_URL, } = await import('../plugins/market.js');
|
|
5626
|
+
// Refuse an unusable org HERE rather than silently dropping it: the org
|
|
5627
|
+
// name is joined into an API URL, and a typo that vanished would make the
|
|
5628
|
+
// scan quietly cover something else than the operator asked for.
|
|
5629
|
+
if (Array.isArray(body.discoveryOrgs)) {
|
|
5630
|
+
const bad = body.discoveryOrgs.filter((org) => normalizeOrgName(org) === undefined);
|
|
5631
|
+
if (bad.length > 0) {
|
|
5632
|
+
return reply.code(400).send({ status: 'error', error: `not a GitHub org name: ${bad.join(', ')}` });
|
|
5633
|
+
}
|
|
5634
|
+
}
|
|
5635
|
+
const saved = writeMarketSettings(body);
|
|
5636
|
+
// Arm/disarm the background pull to match what was just stored. Turning it
|
|
5637
|
+
// ON pulls once immediately — the operator asked for the list, so they
|
|
5638
|
+
// should see it without waiting for the next tick or reopening the page.
|
|
5639
|
+
startRegistrySyncScheduler().reconcile();
|
|
5640
|
+
if (saved.registrySync)
|
|
5641
|
+
await syncRemoteRegistry({ force: true });
|
|
5642
|
+
// Same mask rule as the GET: a setting write answers what is stored, and
|
|
5643
|
+
// what is stored carries the token value.
|
|
5644
|
+
return {
|
|
5645
|
+
status: 'ok',
|
|
5646
|
+
egress: saved.egress,
|
|
5647
|
+
sources: describeMarketSources(saved.sources),
|
|
5648
|
+
officialRegistryUrl: OFFICIAL_REGISTRY_URL,
|
|
5649
|
+
registrySyncEnabled: saved.registrySync,
|
|
5650
|
+
registryFile: registryFilePath(),
|
|
5651
|
+
registrySync: registrySyncState(),
|
|
5652
|
+
path: marketSettingsPath(),
|
|
5653
|
+
};
|
|
5654
|
+
});
|
|
5655
|
+
// Card logos: cached bytes from the market's own disk cache. Same lockdown
|
|
5656
|
+
// as the installed-plugin logo route — an operator-installed package's asset
|
|
5657
|
+
// is untrusted content, and so is a repository's.
|
|
5658
|
+
app.get(`${prefix}/plugins/market/logo`, async (req, reply) => {
|
|
5659
|
+
const key = req.query.key;
|
|
5660
|
+
if (!key)
|
|
5661
|
+
return reply.code(400).send({ status: 'error', error: 'key is required' });
|
|
5662
|
+
const { cachedLogoForKey } = await import('../plugins/market.js');
|
|
5663
|
+
const logo = cachedLogoForKey(key);
|
|
5664
|
+
if (!logo)
|
|
5665
|
+
return reply.code(404).send({ status: 'error', error: 'no cached logo' });
|
|
5666
|
+
reply.header('X-Content-Type-Options', 'nosniff');
|
|
5667
|
+
reply.header('Content-Security-Policy', "default-src 'none'");
|
|
5668
|
+
reply.header('Cache-Control', 'public, max-age=86400');
|
|
5669
|
+
return reply.type(logo.mime).send(logo.bytes);
|
|
5670
|
+
});
|
|
5671
|
+
// Install from the market. Body: `{ repo }` — the repository the card names.
|
|
5672
|
+
// The download is the backend's (the gateway may hold the egress proxy and
|
|
5673
|
+
// the token), and the bytes land only after the zip's manifest id is
|
|
5674
|
+
// verified against the row that was shown, so a swapped asset cannot become
|
|
5675
|
+
// a different install.
|
|
5676
|
+
app.post(`${prefix}/plugins/market/install`, async (req, reply) => {
|
|
5677
|
+
const body = (req.body ?? {});
|
|
5678
|
+
const repo = typeof body.repo === 'string' ? body.repo : '';
|
|
5679
|
+
if (!repo)
|
|
5680
|
+
return reply.code(400).send({ status: 'error', error: 'body.repo is required (owner/repo)' });
|
|
5681
|
+
const ref = typeof body.ref === 'string' && body.ref.trim() ? body.ref.trim() : undefined;
|
|
5682
|
+
const { installFromMarket } = await import('../plugins/market-install.js');
|
|
5683
|
+
const outcome = await installFromMarket(repo, ref ? { ref } : {}, registry);
|
|
5684
|
+
return reply.code(outcome.statusCode).send(outcome.body);
|
|
5685
|
+
});
|
|
5686
|
+
// ONE plugin's upgrade: resolve the row that describes it (provenance first,
|
|
5687
|
+
// then manifest id), and install that row through the same market path.
|
|
5688
|
+
// `?ref=` pins a `code` rebuild to a tag, which also makes a DOWNGRADE an
|
|
5689
|
+
// explicit, operator-stated choice.
|
|
5690
|
+
app.post(`${prefix}/plugins/:id/upgrade`, async (req, reply) => {
|
|
5691
|
+
const { id } = req.params;
|
|
5692
|
+
const { ref } = req.query;
|
|
5693
|
+
const { installFromMarket } = await import('../plugins/market-install.js');
|
|
5694
|
+
const { loadMarket, readPluginSources } = await import('../plugins/market.js');
|
|
5695
|
+
const { rowForInstalled } = await import('../plugins/market-updates.js');
|
|
5696
|
+
const { listInstalledPlugins } = await import('../plugins/host.js');
|
|
5697
|
+
const view = listInstalledPlugins().find((plugin) => plugin.id === id);
|
|
5698
|
+
if (!view)
|
|
5699
|
+
return reply.code(404).send({ status: 'error', error: `plugin '${id}' is not installed` });
|
|
5700
|
+
// The ledger is the only evidence of WHERE an install came from, so it
|
|
5701
|
+
// wins — and it needs no market read. A package installed by HAND (an
|
|
5702
|
+
// uploaded zip carries no provenance) falls back to the manifest id, the
|
|
5703
|
+
// same two-fact identity the updates monitor uses; without the fallback
|
|
5704
|
+
// the page offers an upgrade this verb could never run.
|
|
5705
|
+
const sources = readPluginSources();
|
|
5706
|
+
let repo = sources[id]?.repo;
|
|
5707
|
+
if (!repo) {
|
|
5708
|
+
const { rows } = await loadMarket();
|
|
5709
|
+
repo = rowForInstalled(view, rows, sources)?.repo;
|
|
5710
|
+
}
|
|
5711
|
+
if (!repo) {
|
|
5712
|
+
return reply
|
|
5713
|
+
.code(422)
|
|
5714
|
+
.send({ status: 'error', error: `plugin '${id}' matches no repository in the market — nothing to upgrade from` });
|
|
5715
|
+
}
|
|
5716
|
+
// A pinned rebuild of the SAME or an OLDER version is a deliberate choice;
|
|
5717
|
+
// an unpinned upgrade moves to the repository's tip (the version gate
|
|
5718
|
+
// stays on, so it can only move forward).
|
|
5719
|
+
const outcome = await installFromMarket(repo, ref ? { ref, allowDowngrade: true } : { upgrade: true }, registry);
|
|
5720
|
+
return reply.code(outcome.statusCode).send(outcome.body);
|
|
5721
|
+
});
|
|
5722
|
+
// Upgrade EVERY plugin whose registry row is newer. Sequential on purpose:
|
|
5723
|
+
// one reload/pool refresh per package, so a failure in the middle leaves
|
|
5724
|
+
// exactly the packages before it upgraded and names the one that failed.
|
|
5725
|
+
app.post(`${prefix}/plugins/upgrades/run`, async () => {
|
|
5726
|
+
const { checkPluginUpdates } = await import('../plugins/market-updates.js');
|
|
5727
|
+
const { installFromMarket } = await import('../plugins/market-install.js');
|
|
5728
|
+
const { listInstalledPlugins } = await import('../plugins/host.js');
|
|
5729
|
+
const before = await checkPluginUpdates({ refresh: true });
|
|
5730
|
+
const results = [];
|
|
5731
|
+
for (const update of before.updates) {
|
|
5732
|
+
// `upgrade: true` for an unpinned run: a `code` entry moves to the
|
|
5733
|
+
// repository's tip rather than rebuilding the pin the card describes.
|
|
5734
|
+
const outcome = await installFromMarket(update.repo, update.ref ? { ref: update.ref } : { upgrade: true }, registry);
|
|
5735
|
+
const body = outcome.body;
|
|
5736
|
+
results.push({
|
|
5737
|
+
id: update.id,
|
|
5738
|
+
ok: outcome.statusCode === 200,
|
|
5739
|
+
from: update.installedVersion,
|
|
5740
|
+
to: body.version ?? update.availableVersion,
|
|
5741
|
+
...(outcome.statusCode === 200 ? {} : { error: body.error ?? `HTTP ${outcome.statusCode}` }),
|
|
5742
|
+
});
|
|
5160
5743
|
}
|
|
5744
|
+
return { status: 'ok', results, plugins: listInstalledPlugins() };
|
|
5161
5745
|
});
|
|
5162
5746
|
// Per-credential credential writes (reorder / rename / disconnect).
|
|
5163
5747
|
// Decision 8 double-confirm lives in the console UI; these honor the call.
|
|
@@ -5337,6 +5921,31 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
5337
5921
|
// `tiers` is the model's FULL membership set (pools are a per-tier
|
|
5338
5922
|
// projection — a model may belong to several tiers, or none): no single
|
|
5339
5923
|
// fixed tier is reported for any row.
|
|
5924
|
+
//
|
|
5925
|
+
// `name` is the def's human label (ADR-0010: `<ocrHome>/providers.json` is
|
|
5926
|
+
// the single def truth), reported VERBATIM — including the id-derived
|
|
5927
|
+
// fallback `catalogModelToDef` writes for a bare /v1/models row. Deciding
|
|
5928
|
+
// whether a name says anything the id does not belongs to the ONE display
|
|
5929
|
+
// rule in the console (`lib/model-options.ts` `modelOption`), not to every
|
|
5930
|
+
// read path. It is display metadata only: never addressable, never matched
|
|
5931
|
+
// by the request `model` field.
|
|
5932
|
+
const { readProviderDefsFile } = await import('../opencode/provider-defs.js');
|
|
5933
|
+
const defNodes = readProviderDefsFile()?.providers ?? {};
|
|
5934
|
+
const defName = (id, provider) => {
|
|
5935
|
+
const models = defNodes[provider]?.models;
|
|
5936
|
+
if (!models || typeof models !== 'object')
|
|
5937
|
+
return undefined;
|
|
5938
|
+
// Registered ids are `${provider}/${mid}` and `mid` is the defs key
|
|
5939
|
+
// (model ids may themselves contain '/', so strip the provider prefix
|
|
5940
|
+
// rather than taking the last segment).
|
|
5941
|
+
const mid = id.startsWith(`${provider}/`) ? id.slice(provider.length + 1) : id;
|
|
5942
|
+
const raw = models[mid]?.name;
|
|
5943
|
+
return typeof raw === 'string' ? raw : undefined;
|
|
5944
|
+
};
|
|
5945
|
+
const withName = (row) => {
|
|
5946
|
+
const name = defName(row.id, row.owned_by);
|
|
5947
|
+
return name !== undefined ? { ...row, name } : row;
|
|
5948
|
+
};
|
|
5340
5949
|
const models = [
|
|
5341
5950
|
...['auto', 'lite', 'plus', 'pro', 'ultra'].map((id) => ({
|
|
5342
5951
|
id,
|
|
@@ -5358,7 +5967,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
5358
5967
|
// console pickers show it as the combo row's meta.
|
|
5359
5968
|
members: registry.resolveCombo(c.id).length,
|
|
5360
5969
|
})),
|
|
5361
|
-
...registry.getAllModels().map((m) => ({
|
|
5970
|
+
...registry.getAllModels().map((m) => withName({
|
|
5362
5971
|
id: m.id,
|
|
5363
5972
|
kind: 'model',
|
|
5364
5973
|
owned_by: m.provider,
|
|
@@ -5375,14 +5984,20 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
5375
5984
|
// decision-wire model, which no chat surface can address (ADR-0008 §7).
|
|
5376
5985
|
...(m.wire ? { wire: m.wire } : {}),
|
|
5377
5986
|
})),
|
|
5378
|
-
...registry.getVariantExposures().map(({ id, base }) =>
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5987
|
+
...registry.getVariantExposures().map(({ id, base }) => {
|
|
5988
|
+
// A variant IS its base model with a pinned effort, so it carries the
|
|
5989
|
+
// base def's label; the id on the picker's second line names the pin.
|
|
5990
|
+
const name = defName(base.id, base.provider);
|
|
5991
|
+
return {
|
|
5992
|
+
id,
|
|
5993
|
+
kind: 'variant',
|
|
5994
|
+
owned_by: base.provider,
|
|
5995
|
+
tiers: registry.tiersOf(base),
|
|
5996
|
+
...(name !== undefined ? { name } : {}),
|
|
5997
|
+
// A variant is served by its base model's upstream → same wire.
|
|
5998
|
+
...(base.wire ? { wire: base.wire } : {}),
|
|
5999
|
+
};
|
|
6000
|
+
}),
|
|
5386
6001
|
];
|
|
5387
6002
|
return { status: 'ok', models };
|
|
5388
6003
|
};
|
|
@@ -5547,6 +6162,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
5547
6162
|
return { status: r.ok ? 'ok' : 'error', ...r };
|
|
5548
6163
|
});
|
|
5549
6164
|
registerMihomoRoutes(app);
|
|
6165
|
+
// Local inference engines (llama.cpp / Strata): catalog, dependency probe,
|
|
6166
|
+
// streaming install, uninstall. Under /api/admin/* → covered by webAuth.
|
|
6167
|
+
registerLocalModelRoutes(app);
|
|
5550
6168
|
/* ---------------------------------------------------------------------- *
|
|
5551
6169
|
* 12b. Request-capture archive browser (CaptureRecorder; opt-in audit log)
|
|
5552
6170
|
* Bodies may contain sensitive data — these endpoints sit under /api/admin/*
|