omnicell-router 0.3.1 → 0.8.1
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 +70 -10
- package/README.zh-CN.md +57 -8
- package/RELEASING.md +6 -0
- package/RELEASING.zh-CN.md +5 -0
- package/backend/dist/auth/api-keys.d.ts +14 -2
- package/backend/dist/auth/api-keys.js +26 -14
- package/backend/dist/auth/model-access.d.ts +27 -10
- package/backend/dist/auth/model-access.js +34 -17
- package/backend/dist/capture/migrate/engine.d.ts +38 -0
- package/backend/dist/capture/migrate/engine.js +307 -0
- package/backend/dist/capture/migrate/index.d.ts +18 -0
- package/backend/dist/capture/migrate/index.js +18 -0
- package/backend/dist/capture/migrate/migrator.d.ts +113 -0
- package/backend/dist/capture/migrate/migrator.js +16 -0
- package/backend/dist/capture/migrate/registry.d.ts +16 -0
- package/backend/dist/capture/migrate/registry.js +19 -0
- package/backend/dist/capture/migrate/steps/v1-to-v2.d.ts +86 -0
- package/backend/dist/capture/migrate/steps/v1-to-v2.js +396 -0
- package/backend/dist/capture/recorder.d.ts +422 -272
- package/backend/dist/capture/recorder.js +873 -417
- package/backend/dist/capture/turn-boundary.d.ts +17 -0
- package/backend/dist/capture/turn-boundary.js +31 -0
- package/backend/dist/cli/clients/base.d.ts +172 -26
- package/backend/dist/cli/clients/base.js +150 -4
- package/backend/dist/cli/clients/claude.d.ts +2 -1
- package/backend/dist/cli/clients/claude.js +4 -3
- package/backend/dist/cli/clients/codex.d.ts +2 -1
- package/backend/dist/cli/clients/codex.js +4 -3
- package/backend/dist/cli/clients/core-adapters.d.ts +24 -0
- package/backend/dist/cli/clients/core-adapters.js +43 -0
- package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
- package/backend/dist/cli/clients/cursor-proxy.js +421 -0
- package/backend/dist/cli/clients/dsh.d.ts +4 -2
- package/backend/dist/cli/clients/dsh.js +29 -18
- package/backend/dist/cli/clients/grok.d.ts +53 -0
- package/backend/dist/cli/clients/grok.js +249 -0
- package/backend/dist/cli/clients/index.d.ts +35 -19
- package/backend/dist/cli/clients/index.js +196 -72
- package/backend/dist/cli/clients/kimi.d.ts +75 -0
- package/backend/dist/cli/clients/kimi.js +316 -0
- package/backend/dist/cli/clients/launcher.d.ts +56 -0
- package/backend/dist/cli/clients/launcher.js +41 -0
- package/backend/dist/cli/clients/model-meta.js +1 -1
- package/backend/dist/cli/clients/omp.d.ts +9 -19
- package/backend/dist/cli/clients/omp.js +28 -155
- package/backend/dist/cli/clients/openclaw.d.ts +55 -0
- package/backend/dist/cli/clients/openclaw.js +525 -0
- package/backend/dist/cli/clients/opencode-proxy.d.ts +5 -10
- package/backend/dist/cli/clients/opencode-proxy.js +37 -58
- package/backend/dist/cli/clients/opencode.d.ts +6 -19
- package/backend/dist/cli/clients/opencode.js +32 -159
- package/backend/dist/cli/clients/pi.d.ts +6 -20
- package/backend/dist/cli/clients/pi.js +32 -221
- package/backend/dist/cli/clients/plugin-adapters.d.ts +22 -0
- package/backend/dist/cli/clients/plugin-adapters.js +65 -0
- package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
- package/backend/dist/cli/clients/qoder-proxy.js +497 -0
- package/backend/dist/cli/clients/reserved.d.ts +47 -0
- package/backend/dist/cli/clients/reserved.js +55 -0
- package/backend/dist/cli/clients/workbuddy.d.ts +31 -0
- package/backend/dist/cli/clients/workbuddy.js +259 -0
- package/backend/dist/cli/daemon.d.ts +105 -27
- package/backend/dist/cli/daemon.js +509 -151
- package/backend/dist/cli/index.d.ts +6 -1
- package/backend/dist/cli/index.js +289 -22
- package/backend/dist/cli/paths.d.ts +86 -0
- package/backend/dist/cli/paths.js +269 -0
- package/backend/dist/cli/shim.d.ts +47 -1
- package/backend/dist/cli/shim.js +180 -13
- package/backend/dist/cli/types.d.ts +114 -16
- package/backend/dist/cli/types.js +5 -4
- package/backend/dist/compression/caveman.d.ts +2 -16
- package/backend/dist/compression/caveman.js +25 -37
- package/backend/dist/compression/headroom.d.ts +4 -3
- package/backend/dist/compression/headroom.js +2 -2
- package/backend/dist/compression/index.d.ts +5 -26
- package/backend/dist/compression/index.js +79 -17
- package/backend/dist/compression/tool-output.d.ts +2 -20
- package/backend/dist/compression/tool-output.js +40 -47
- package/backend/dist/config/comments-en.d.ts +17 -0
- package/backend/dist/config/comments-en.js +226 -0
- package/backend/dist/config/comments-zh.d.ts +10 -0
- package/backend/dist/config/comments-zh.js +211 -0
- package/backend/dist/config/defaults.d.ts +245 -2
- package/backend/dist/config/defaults.js +259 -2
- package/backend/dist/config/env-archive.js +77 -38
- package/backend/dist/config/env.d.ts +4 -0
- package/backend/dist/config/env.js +16 -0
- package/backend/dist/config/index.d.ts +55 -12
- package/backend/dist/config/index.js +817 -368
- package/backend/dist/config/layout.d.ts +29 -0
- package/backend/dist/config/layout.js +86 -0
- package/backend/dist/config/migrations/v0-to-v1.d.ts +105 -0
- package/backend/dist/config/migrations/v0-to-v1.js +78 -0
- package/backend/dist/config/migrations/v1-to-v2.d.ts +14 -0
- package/backend/dist/config/migrations/v1-to-v2.js +41 -0
- package/backend/dist/config/migrations/v2-to-v3.d.ts +34 -0
- package/backend/dist/config/migrations/v2-to-v3.js +66 -0
- package/backend/dist/config/migrations/v3-to-v4.d.ts +34 -0
- package/backend/dist/config/migrations/v3-to-v4.js +61 -0
- package/backend/dist/config/runtime.d.ts +13 -0
- package/backend/dist/config/runtime.js +26 -0
- package/backend/dist/config/schema.d.ts +28 -0
- package/backend/dist/config/schema.js +98 -0
- package/backend/dist/config/types.d.ts +540 -121
- package/backend/dist/forward-proxy/access-log.d.ts +173 -0
- package/backend/dist/forward-proxy/access-log.js +657 -0
- package/backend/dist/forward-proxy/ca-trust.d.ts +42 -0
- package/backend/dist/forward-proxy/ca-trust.js +242 -0
- package/backend/dist/forward-proxy/ca.d.ts +66 -2
- package/backend/dist/forward-proxy/ca.js +146 -11
- package/backend/dist/forward-proxy/caller-context.d.ts +18 -0
- package/backend/dist/forward-proxy/caller-context.js +20 -0
- package/backend/dist/forward-proxy/egress.d.ts +112 -0
- package/backend/dist/forward-proxy/egress.js +318 -0
- package/backend/dist/forward-proxy/h2-forward.d.ts +66 -0
- package/backend/dist/forward-proxy/h2-forward.js +526 -0
- package/backend/dist/forward-proxy/index.d.ts +13 -1
- package/backend/dist/forward-proxy/index.js +148 -7
- package/backend/dist/forward-proxy/interceptor.d.ts +16 -13
- package/backend/dist/forward-proxy/interceptor.js +35 -57
- package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
- package/backend/dist/forward-proxy/ordered-relay.js +46 -0
- package/backend/dist/forward-proxy/relay.d.ts +21 -1
- package/backend/dist/forward-proxy/relay.js +48 -1
- package/backend/dist/forward-proxy/rules.d.ts +195 -0
- package/backend/dist/forward-proxy/rules.js +327 -0
- package/backend/dist/forward-proxy/server.d.ts +102 -9
- package/backend/dist/forward-proxy/server.js +1504 -350
- package/backend/dist/forward-proxy/sni.d.ts +29 -7
- package/backend/dist/forward-proxy/sni.js +109 -47
- package/backend/dist/forward-proxy/system-proxy.d.ts +112 -0
- package/backend/dist/forward-proxy/system-proxy.js +480 -0
- package/backend/dist/forward-proxy/upstream-tls.d.ts +46 -0
- package/backend/dist/forward-proxy/upstream-tls.js +105 -0
- package/backend/dist/forward-proxy/ws-frames.d.ts +45 -0
- package/backend/dist/forward-proxy/ws-frames.js +153 -0
- package/backend/dist/harness/common/catalog-registry.d.ts +63 -0
- package/backend/dist/harness/common/catalog-registry.js +77 -0
- package/backend/dist/harness/common/github.d.ts +6 -0
- package/backend/dist/harness/common/github.js +13 -0
- package/backend/dist/harness/common/market.d.ts +590 -0
- package/backend/dist/harness/common/market.js +1079 -0
- package/backend/dist/harness/common/marketplace-rescan-scheduler.d.ts +24 -0
- package/backend/dist/harness/common/marketplace-rescan-scheduler.js +62 -0
- package/backend/dist/harness/{catalog-npm.d.ts → common/npm-catalog.d.ts} +5 -5
- package/backend/dist/harness/{catalog-npm.js → common/npm-catalog.js} +7 -7
- package/backend/dist/harness/common/npm-source.d.ts +29 -0
- package/backend/dist/harness/common/npm-source.js +121 -0
- package/backend/dist/harness/common/pypi-source.d.ts +28 -0
- package/backend/dist/harness/common/pypi-source.js +71 -0
- package/backend/dist/harness/common/source-views.d.ts +22 -0
- package/backend/dist/harness/common/source-views.js +25 -0
- package/backend/dist/harness/{stars.d.ts → common/stars.d.ts} +1 -1
- package/backend/dist/harness/{stars.js → common/stars.js} +2 -2
- package/backend/dist/harness/common/text.d.ts +11 -0
- package/backend/dist/harness/common/text.js +18 -0
- package/backend/dist/harness/config-file.d.ts +14 -1
- package/backend/dist/harness/config-file.js +38 -0
- package/backend/dist/harness/db-probe.d.ts +29 -0
- package/backend/dist/harness/db-probe.js +270 -0
- package/backend/dist/harness/detail.d.ts +10 -1
- package/backend/dist/harness/detail.js +144 -7
- package/backend/dist/harness/host/adapters/amp.d.ts +19 -0
- package/backend/dist/harness/host/adapters/amp.js +21 -0
- package/backend/dist/harness/host/adapters/antigravity.d.ts +18 -0
- package/backend/dist/harness/host/adapters/antigravity.js +21 -0
- package/backend/dist/harness/host/adapters/base.d.ts +225 -0
- package/backend/dist/harness/host/adapters/base.js +521 -0
- package/backend/dist/harness/host/adapters/claude.d.ts +54 -0
- package/backend/dist/harness/host/adapters/claude.js +145 -0
- package/backend/dist/harness/host/adapters/cline.d.ts +18 -0
- package/backend/dist/harness/host/adapters/cline.js +20 -0
- package/backend/dist/harness/host/adapters/codex.d.ts +54 -0
- package/backend/dist/harness/host/adapters/codex.js +133 -0
- package/backend/dist/harness/host/adapters/cursor.d.ts +18 -0
- package/backend/dist/harness/host/adapters/cursor.js +24 -0
- package/backend/dist/harness/host/adapters/declarative.d.ts +22 -0
- package/backend/dist/harness/host/adapters/declarative.js +38 -0
- package/backend/dist/harness/host/adapters/dsh.d.ts +76 -0
- package/backend/dist/harness/host/adapters/dsh.js +253 -0
- package/backend/dist/harness/host/adapters/factory.d.ts +36 -0
- package/backend/dist/harness/host/adapters/factory.js +34 -0
- package/backend/dist/harness/host/adapters/gemini-cli.d.ts +17 -0
- package/backend/dist/harness/host/adapters/gemini-cli.js +19 -0
- package/backend/dist/harness/host/adapters/grok.d.ts +66 -0
- package/backend/dist/harness/host/adapters/grok.js +136 -0
- package/backend/dist/harness/{adapters → host/adapters}/index.d.ts +9 -4
- package/backend/dist/harness/{adapters → host/adapters}/index.js +31 -10
- package/backend/dist/harness/host/adapters/kimi.d.ts +30 -0
- package/backend/dist/harness/host/adapters/kimi.js +59 -0
- package/backend/dist/harness/host/adapters/omp.d.ts +55 -0
- package/backend/dist/harness/host/adapters/omp.js +90 -0
- package/backend/dist/harness/host/adapters/openclaw.d.ts +54 -0
- package/backend/dist/harness/host/adapters/openclaw.js +141 -0
- package/backend/dist/harness/host/adapters/opencode.d.ts +24 -0
- package/backend/dist/harness/host/adapters/opencode.js +48 -0
- package/backend/dist/harness/host/adapters/pi.d.ts +27 -0
- package/backend/dist/harness/host/adapters/pi.js +58 -0
- package/backend/dist/harness/host/adapters/types.d.ts +395 -0
- package/backend/dist/harness/host/adapters/types.js +17 -0
- package/backend/dist/harness/host/adapters/universal.d.ts +14 -0
- package/backend/dist/harness/host/adapters/universal.js +18 -0
- package/backend/dist/harness/host/adapters/windsurf.d.ts +20 -0
- package/backend/dist/harness/host/adapters/windsurf.js +22 -0
- package/backend/dist/harness/host/adapters/zed.d.ts +12 -0
- package/backend/dist/harness/host/adapters/zed.js +14 -0
- package/backend/dist/harness/host/claude-mcp-runtime.d.ts +6 -0
- package/backend/dist/harness/host/claude-mcp-runtime.js +56 -0
- package/backend/dist/harness/{discover.d.ts → host/discover.d.ts} +54 -18
- package/backend/dist/harness/{discover.js → host/discover.js} +314 -53
- package/backend/dist/harness/{drift.d.ts → host/drift.d.ts} +1 -1
- package/backend/dist/harness/{drift.js → host/drift.js} +1 -1
- package/backend/dist/harness/host/grok-mcp-runtime.d.ts +6 -0
- package/backend/dist/harness/host/grok-mcp-runtime.js +56 -0
- package/backend/dist/harness/{hosts.d.ts → host/hosts.d.ts} +3 -3
- package/backend/dist/harness/{hosts.js → host/hosts.js} +7 -3
- package/backend/dist/harness/host/index.d.ts +10 -0
- package/backend/dist/harness/host/index.js +12 -0
- package/backend/dist/harness/host/install-log.d.ts +22 -0
- package/backend/dist/harness/host/install-log.js +106 -0
- package/backend/dist/harness/{install.d.ts → host/install.d.ts} +32 -13
- package/backend/dist/harness/{install.js → host/install.js} +133 -50
- package/backend/dist/harness/host/inventory.d.ts +30 -0
- package/backend/dist/harness/{inventory.js → host/inventory.js} +107 -16
- package/backend/dist/harness/host/kimi-mcp-runtime.d.ts +6 -0
- package/backend/dist/harness/host/kimi-mcp-runtime.js +84 -0
- package/backend/dist/harness/{ledger.d.ts → host/ledger.d.ts} +1 -1
- package/backend/dist/harness/{ledger.js → host/ledger.js} +3 -3
- package/backend/dist/harness/{maintenance.d.ts → host/maintenance.d.ts} +23 -6
- package/backend/dist/harness/{maintenance.js → host/maintenance.js} +355 -63
- package/backend/dist/harness/{manifest.d.ts → host/manifest.d.ts} +11 -2
- package/backend/dist/harness/{manifest.js → host/manifest.js} +76 -15
- package/backend/dist/harness/host/marketplace-sync.d.ts +64 -0
- package/backend/dist/harness/host/marketplace-sync.js +231 -0
- package/backend/dist/harness/host/mcp-cli.d.ts +44 -0
- package/backend/dist/harness/host/mcp-cli.js +545 -0
- package/backend/dist/harness/host/mcp-edit.d.ts +89 -0
- package/backend/dist/harness/host/mcp-edit.js +342 -0
- package/backend/dist/harness/host/mcp-entry.d.ts +100 -0
- package/backend/dist/harness/host/mcp-entry.js +435 -0
- package/backend/dist/harness/host/mcp-inspector.d.ts +125 -0
- package/backend/dist/harness/host/mcp-inspector.js +634 -0
- package/backend/dist/harness/host/mcp-registry.d.ts +66 -0
- package/backend/dist/harness/host/mcp-registry.js +331 -0
- package/backend/dist/harness/host/mcp-runtime.d.ts +19 -0
- package/backend/dist/harness/host/mcp-runtime.js +22 -0
- package/backend/dist/harness/host/opencode-mcp-runtime.d.ts +7 -0
- package/backend/dist/harness/host/opencode-mcp-runtime.js +73 -0
- package/backend/dist/harness/{probe.d.ts → host/probe.d.ts} +4 -4
- package/backend/dist/harness/{probe.js → host/probe.js} +8 -8
- package/backend/dist/harness/{registry.d.ts → host/registry.d.ts} +1 -1
- package/backend/dist/harness/host/registry.js +28 -0
- package/backend/dist/harness/host/request.d.ts +56 -0
- package/backend/dist/harness/host/request.js +1 -0
- package/backend/dist/harness/{sources → host/resolvers}/clawhub.d.ts +1 -1
- package/backend/dist/harness/{sources → host/resolvers}/clawhub.js +1 -1
- package/backend/dist/harness/host/resolvers/git-marketplace.d.ts +16 -0
- package/backend/dist/harness/host/resolvers/git-marketplace.js +53 -0
- package/backend/dist/harness/{sources → host/resolvers}/github.d.ts +1 -1
- package/backend/dist/harness/{sources → host/resolvers}/github.js +2 -2
- package/backend/dist/harness/host/resolvers/npm.d.ts +2 -0
- package/backend/dist/harness/{sources → host/resolvers}/npm.js +16 -10
- package/backend/dist/harness/host/resolvers/pypi.d.ts +2 -0
- package/backend/dist/harness/host/resolvers/pypi.js +100 -0
- package/backend/dist/harness/host/scopes.d.ts +11 -0
- package/backend/dist/harness/host/scopes.js +12 -0
- package/backend/dist/harness/host/timeouts.d.ts +8 -0
- package/backend/dist/harness/host/timeouts.js +8 -0
- package/backend/dist/harness/host/writers/kimi-web.d.ts +70 -0
- package/backend/dist/harness/host/writers/kimi-web.js +222 -0
- package/backend/dist/harness/host/writers/mcp.d.ts +119 -0
- package/backend/dist/harness/host/writers/mcp.js +359 -0
- package/backend/dist/harness/host/writers/plugin.d.ts +176 -0
- package/backend/dist/harness/host/writers/plugin.js +528 -0
- package/backend/dist/harness/{writers → host/writers}/skill.d.ts +3 -3
- package/backend/dist/harness/{writers → host/writers}/skill.js +6 -3
- package/backend/dist/harness/lang.d.ts +14 -0
- package/backend/dist/harness/lang.js +33 -0
- package/backend/dist/harness/net.d.ts +33 -0
- package/backend/dist/harness/net.js +63 -0
- package/backend/dist/harness/plugin/adapters/antigravity.d.ts +11 -0
- package/backend/dist/harness/plugin/adapters/antigravity.js +14 -0
- package/backend/dist/harness/plugin/adapters/base.d.ts +107 -0
- package/backend/dist/harness/plugin/adapters/base.js +454 -0
- package/backend/dist/harness/plugin/adapters/claude.d.ts +28 -0
- package/backend/dist/harness/plugin/adapters/claude.js +63 -0
- package/backend/dist/harness/plugin/adapters/codex.d.ts +13 -0
- package/backend/dist/harness/plugin/adapters/codex.js +16 -0
- package/backend/dist/harness/plugin/adapters/cursor.d.ts +13 -0
- package/backend/dist/harness/plugin/adapters/cursor.js +16 -0
- package/backend/dist/harness/plugin/adapters/dsh-plugin-net.d.ts +20 -0
- package/backend/dist/harness/plugin/adapters/dsh-plugin-net.js +371 -0
- package/backend/dist/harness/plugin/adapters/dsh.d.ts +22 -0
- package/backend/dist/harness/plugin/adapters/dsh.js +50 -0
- package/backend/dist/harness/plugin/adapters/factory.d.ts +11 -0
- package/backend/dist/harness/plugin/adapters/factory.js +19 -0
- package/backend/dist/harness/plugin/adapters/gemini.d.ts +12 -0
- package/backend/dist/harness/plugin/adapters/gemini.js +22 -0
- package/backend/dist/harness/plugin/adapters/grok.d.ts +15 -0
- package/backend/dist/harness/plugin/adapters/grok.js +23 -0
- package/backend/dist/harness/plugin/adapters/index.d.ts +41 -0
- package/backend/dist/harness/plugin/adapters/index.js +143 -0
- package/backend/dist/harness/plugin/adapters/kimi.d.ts +6 -0
- package/backend/dist/harness/plugin/adapters/kimi.js +35 -0
- package/backend/dist/harness/plugin/adapters/omp.d.ts +19 -0
- package/backend/dist/harness/plugin/adapters/omp.js +26 -0
- package/backend/dist/harness/plugin/adapters/openclaw.d.ts +20 -0
- package/backend/dist/harness/plugin/adapters/openclaw.js +36 -0
- package/backend/dist/harness/plugin/adapters/pi-dev.d.ts +124 -0
- package/backend/dist/harness/plugin/adapters/pi-dev.js +420 -0
- package/backend/dist/harness/plugin/adapters/pi-github.d.ts +18 -0
- package/backend/dist/harness/plugin/adapters/pi-github.js +27 -0
- package/backend/dist/harness/plugin/adapters/universal.d.ts +11 -0
- package/backend/dist/harness/plugin/adapters/universal.js +18 -0
- package/backend/dist/harness/plugin/builtin.d.ts +13 -0
- package/backend/dist/harness/plugin/builtin.js +34 -0
- package/backend/dist/harness/plugin/catalog.d.ts +30 -0
- package/backend/dist/harness/plugin/catalog.js +200 -0
- package/backend/dist/harness/plugin/index.d.ts +9 -0
- package/backend/dist/harness/plugin/index.js +9 -0
- package/backend/dist/harness/plugin/types.d.ts +164 -0
- package/backend/dist/harness/plugin/types.js +1 -0
- package/backend/dist/harness/{clawhub.d.ts → skill/clawhub.d.ts} +28 -5
- package/backend/dist/harness/{clawhub.js → skill/clawhub.js} +170 -5
- package/backend/dist/harness/skill/skills-sh.d.ts +47 -0
- package/backend/dist/harness/skill/skills-sh.js +270 -0
- package/backend/dist/harness/skill/sources.d.ts +41 -0
- package/backend/dist/harness/skill/sources.js +131 -0
- package/backend/dist/harness/spi.d.ts +11 -7
- package/backend/dist/harness/tcp-reach.d.ts +30 -0
- package/backend/dist/harness/tcp-reach.js +61 -0
- package/backend/dist/harness/translation.d.ts +31 -13
- package/backend/dist/harness/translation.js +265 -80
- package/backend/dist/harness/types.d.ts +62 -17
- package/backend/dist/harness/types.js +1 -1
- package/backend/dist/index.js +183 -16
- package/backend/dist/ir/adapters/anthropic-messages-stream.d.ts +18 -0
- package/backend/dist/ir/adapters/anthropic-messages-stream.js +266 -0
- package/backend/dist/ir/adapters/anthropic-messages.d.ts +30 -0
- package/backend/dist/ir/adapters/anthropic-messages.js +870 -0
- package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
- package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
- package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
- package/backend/dist/ir/adapters/anthropic.js +788 -0
- package/backend/dist/ir/adapters/chat.d.ts +15 -0
- package/backend/dist/ir/adapters/chat.js +602 -0
- package/backend/dist/ir/adapters/google-gemini-stream.d.ts +22 -0
- package/backend/dist/ir/adapters/google-gemini-stream.js +246 -0
- package/backend/dist/ir/adapters/google-gemini.d.ts +9 -0
- package/backend/dist/ir/adapters/google-gemini.js +450 -0
- package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
- package/backend/dist/ir/adapters/google-stream.js +242 -0
- package/backend/dist/ir/adapters/google.d.ts +9 -0
- package/backend/dist/ir/adapters/google.js +317 -0
- package/backend/dist/ir/adapters/openai-chat-stream.d.ts +41 -0
- package/backend/dist/ir/adapters/openai-chat-stream.js +369 -0
- package/backend/dist/ir/adapters/openai-chat.d.ts +17 -0
- package/backend/dist/ir/adapters/openai-chat.js +670 -0
- package/backend/dist/ir/adapters/openai-responses-output.d.ts +50 -0
- package/backend/dist/ir/adapters/openai-responses-output.js +356 -0
- package/backend/dist/ir/adapters/openai-responses-stream.d.ts +12 -0
- package/backend/dist/ir/adapters/openai-responses-stream.js +193 -0
- package/backend/dist/ir/adapters/openai-responses.d.ts +29 -0
- package/backend/dist/ir/adapters/openai-responses.js +695 -0
- package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
- package/backend/dist/ir/adapters/responses-output.js +348 -0
- package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
- package/backend/dist/ir/adapters/responses-stream.js +178 -0
- package/backend/dist/ir/adapters/responses.d.ts +14 -0
- package/backend/dist/ir/adapters/responses.js +646 -0
- package/backend/dist/ir/capabilities.d.ts +41 -0
- package/backend/dist/ir/capabilities.js +147 -0
- package/backend/dist/ir/errors.d.ts +23 -0
- package/backend/dist/ir/errors.js +31 -0
- package/backend/dist/ir/index.d.ts +5 -0
- package/backend/dist/ir/index.js +5 -0
- package/backend/dist/ir/media.d.ts +2 -0
- package/backend/dist/ir/media.js +2 -0
- package/backend/dist/ir/stream.d.ts +17 -0
- package/backend/dist/ir/stream.js +250 -0
- package/backend/dist/ir/types.d.ts +524 -0
- package/backend/dist/ir/types.js +19 -0
- package/backend/dist/ir/validate.d.ts +18 -0
- package/backend/dist/ir/validate.js +272 -0
- package/backend/dist/metrics/request-cost.d.ts +11 -10
- package/backend/dist/metrics/request-cost.js +18 -27
- package/backend/dist/observability/failure-events.d.ts +20 -4
- package/backend/dist/observability/failure-events.js +9 -1
- package/backend/dist/observability/http-exchange.d.ts +75 -27
- package/backend/dist/observability/http-exchange.js +136 -39
- package/backend/dist/observability/request-identity.d.ts +40 -0
- package/backend/dist/observability/request-identity.js +102 -0
- package/backend/dist/observability/traffic-live-hidden.d.ts +24 -0
- package/backend/dist/observability/traffic-live-hidden.js +82 -0
- package/backend/dist/observability/upstream-body-redaction.d.ts +23 -0
- package/backend/dist/observability/upstream-body-redaction.js +72 -0
- package/backend/dist/observability/upstream-events.d.ts +90 -62
- package/backend/dist/observability/upstream-events.js +145 -64
- package/backend/dist/opencode/agents.d.ts +3 -2
- package/backend/dist/opencode/catalog/auto-pull.d.ts +35 -1
- package/backend/dist/opencode/catalog/auto-pull.js +169 -33
- package/backend/dist/opencode/catalog/ocr-store.d.ts +6 -6
- package/backend/dist/opencode/catalog/ocr-store.js +2 -2
- package/backend/dist/opencode/catalog/overrides-store.d.ts +6 -5
- package/backend/dist/opencode/catalog/overrides-store.js +28 -3
- package/backend/dist/opencode/catalog/repository.d.ts +4 -0
- package/backend/dist/opencode/catalog/repository.js +19 -0
- package/backend/dist/opencode/catalog/sources/models-dev.d.ts +4 -0
- package/backend/dist/opencode/catalog/sources/models-dev.js +15 -4
- package/backend/dist/opencode/catalog/types.d.ts +19 -7
- package/backend/dist/opencode/connector.d.ts +2 -2
- package/backend/dist/opencode/connector.js +2 -2
- package/backend/dist/opencode/credentials/def-materialize.d.ts +0 -5
- package/backend/dist/opencode/credentials/def-materialize.js +149 -11
- package/backend/dist/opencode/credentials/ocr-store.d.ts +18 -0
- package/backend/dist/opencode/credentials/ocr-store.js +88 -7
- package/backend/dist/opencode/credentials/opencode-v2-store.d.ts +24 -13
- package/backend/dist/opencode/credentials/opencode-v2-store.js +70 -29
- package/backend/dist/opencode/credentials/paths.d.ts +8 -0
- package/backend/dist/opencode/credentials/paths.js +10 -0
- package/backend/dist/opencode/credentials/sync.d.ts +1 -1
- package/backend/dist/opencode/credentials/sync.js +4 -4
- package/backend/dist/opencode/credentials/types.d.ts +38 -2
- package/backend/dist/opencode/probe.d.ts +33 -6
- package/backend/dist/opencode/probe.js +96 -19
- package/backend/dist/opencode/provider-defs.js +59 -2
- package/backend/dist/opencode/provider-package.d.ts +31 -0
- package/backend/dist/opencode/provider-package.js +70 -0
- package/backend/dist/opencode/user-config.d.ts +16 -17
- package/backend/dist/opencode/user-config.js +42 -66
- package/backend/dist/pipeline/credential-selection.d.ts +13 -0
- package/backend/dist/pipeline/credential-selection.js +29 -1
- package/backend/dist/pipeline/directives.d.ts +18 -22
- package/backend/dist/pipeline/directives.js +129 -71
- package/backend/dist/pipeline/orchestrator.d.ts +70 -34
- package/backend/dist/pipeline/orchestrator.js +901 -405
- package/backend/dist/pipeline/prompt-optimizer.d.ts +6 -13
- package/backend/dist/pipeline/prompt-optimizer.js +9 -52
- package/backend/dist/pipeline/streaming-posture.d.ts +29 -0
- package/backend/dist/pipeline/streaming-posture.js +27 -0
- package/backend/dist/pipeline/tool-pairing.d.ts +10 -0
- package/backend/dist/pipeline/tool-pairing.js +90 -0
- package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
- package/backend/dist/pipeline/unresolved-model.js +43 -0
- package/backend/dist/plugins/builtin/model-gateway.d.ts +30 -0
- package/backend/dist/plugins/builtin/model-gateway.js +98 -0
- package/backend/dist/plugins/catalog-def.d.ts +143 -0
- package/backend/dist/plugins/catalog-def.js +177 -0
- package/backend/dist/plugins/config.d.ts +41 -0
- package/backend/dist/plugins/config.js +113 -0
- package/backend/dist/plugins/gateways.d.ts +157 -0
- package/backend/dist/plugins/gateways.js +288 -0
- package/backend/dist/plugins/host.d.ts +240 -0
- package/backend/dist/plugins/host.js +1726 -0
- package/backend/dist/plugins/manifest.d.ts +152 -0
- package/backend/dist/plugins/manifest.js +713 -0
- package/backend/dist/plugins/pack.d.ts +32 -0
- package/backend/dist/plugins/pack.js +248 -0
- package/backend/dist/plugins/seed.d.ts +53 -0
- package/backend/dist/plugins/seed.js +136 -0
- package/backend/dist/plugins/types.d.ts +887 -0
- package/backend/dist/plugins/types.js +1 -0
- package/backend/dist/projects/store.d.ts +56 -0
- package/backend/dist/projects/store.js +194 -0
- package/backend/dist/projects/types.d.ts +12 -0
- package/backend/dist/projects/types.js +1 -0
- package/backend/dist/protocols/chat-compat.d.ts +2 -0
- package/backend/dist/protocols/chat-compat.js +137 -0
- package/backend/dist/protocols/systemone/convert.d.ts +6 -4
- package/backend/dist/protocols/systemone/convert.js +78 -27
- package/backend/dist/protocols/systemone/decide.js +144 -57
- package/backend/dist/protocols/systemone/native.d.ts +1 -1
- package/backend/dist/protocols/systemone/native.js +6 -6
- package/backend/dist/providers/anthropic-messages.d.ts +12 -0
- package/backend/dist/providers/anthropic-messages.js +53 -0
- package/backend/dist/providers/anthropic.d.ts +7 -8
- package/backend/dist/providers/anthropic.js +36 -324
- package/backend/dist/providers/base.d.ts +18 -45
- package/backend/dist/providers/boot-direct.d.ts +20 -2
- package/backend/dist/providers/boot-direct.js +140 -61
- package/backend/dist/providers/compat/tool-markup-leak.d.ts +41 -0
- package/backend/dist/providers/compat/tool-markup-leak.js +57 -0
- package/backend/dist/providers/compat/tool-markup-recovery.d.ts +27 -0
- package/backend/dist/providers/compat/tool-markup-recovery.js +831 -0
- package/backend/dist/providers/dispatch.d.ts +5 -22
- package/backend/dist/providers/dispatch.js +49 -55
- package/backend/dist/providers/executors/anthropic-messages.d.ts +13 -0
- package/backend/dist/providers/executors/anthropic-messages.js +59 -0
- package/backend/dist/providers/executors/dispatch.d.ts +28 -0
- package/backend/dist/providers/executors/dispatch.js +101 -0
- package/backend/dist/providers/executors/google-gemini.d.ts +13 -0
- package/backend/dist/providers/executors/google-gemini.js +56 -0
- package/backend/dist/providers/executors/http-json.d.ts +19 -0
- package/backend/dist/providers/executors/http-json.js +125 -0
- package/backend/dist/providers/executors/http-stream.d.ts +53 -0
- package/backend/dist/providers/executors/http-stream.js +485 -0
- package/backend/dist/providers/executors/openai-chat.d.ts +14 -0
- package/backend/dist/providers/executors/openai-chat.js +92 -0
- package/backend/dist/providers/executors/openai-responses.d.ts +13 -0
- package/backend/dist/providers/executors/openai-responses.js +74 -0
- package/backend/dist/providers/executors/plugin-adapter.d.ts +9 -0
- package/backend/dist/providers/executors/plugin-adapter.js +31 -0
- package/backend/dist/providers/google-gemini.d.ts +12 -0
- package/backend/dist/providers/google-gemini.js +50 -0
- package/backend/dist/providers/google.d.ts +7 -8
- package/backend/dist/providers/google.js +35 -308
- package/backend/dist/providers/http-json.d.ts +19 -0
- package/backend/dist/providers/http-json.js +104 -0
- package/backend/dist/providers/http-stream.d.ts +52 -0
- package/backend/dist/providers/http-stream.js +423 -0
- package/backend/dist/providers/member-match.d.ts +4 -5
- package/backend/dist/providers/member-match.js +4 -5
- package/backend/dist/providers/openai-chat.d.ts +13 -0
- package/backend/dist/providers/openai-chat.js +99 -0
- package/backend/dist/providers/openai-compatible.d.ts +7 -4
- package/backend/dist/providers/openai-compatible.js +71 -368
- package/backend/dist/providers/openai-responses.d.ts +12 -0
- package/backend/dist/providers/openai-responses.js +68 -0
- package/backend/dist/providers/opencode-proxy.d.ts +5 -5
- package/backend/dist/providers/opencode-proxy.js +49 -125
- package/backend/dist/providers/plugin-adapter.d.ts +9 -0
- package/backend/dist/providers/plugin-adapter.js +31 -0
- package/backend/dist/providers/plugin-wires.d.ts +34 -0
- package/backend/dist/providers/plugin-wires.js +82 -0
- package/backend/dist/providers/pool-refresh.d.ts +14 -0
- package/backend/dist/providers/pool-refresh.js +13 -0
- package/backend/dist/providers/protocol.d.ts +4 -0
- package/backend/dist/providers/protocol.js +61 -0
- package/backend/dist/providers/provider-takedown.d.ts +59 -0
- package/backend/dist/providers/provider-takedown.js +135 -0
- package/backend/dist/providers/registry.d.ts +85 -44
- package/backend/dist/providers/registry.js +299 -162
- package/backend/dist/providers/responses.d.ts +7 -26
- package/backend/dist/providers/responses.js +45 -250
- package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
- package/backend/dist/providers/tool-markup-leak.js +57 -0
- package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
- package/backend/dist/providers/tool-markup-recovery.js +786 -0
- package/backend/dist/providers/virtual-meta.d.ts +21 -2
- package/backend/dist/providers/virtual-meta.js +49 -9
- package/backend/dist/providers/vocabulary.d.ts +24 -6
- package/backend/dist/providers/vocabulary.js +75 -33
- package/backend/dist/providers/wire.d.ts +12 -17
- package/backend/dist/providers/wire.js +43 -91
- package/backend/dist/proxy/asset-download.d.ts +54 -0
- package/backend/dist/proxy/asset-download.js +420 -0
- package/backend/dist/proxy/manual-node-spec.d.ts +92 -0
- package/backend/dist/proxy/manual-node-spec.js +408 -0
- package/backend/dist/proxy/mihomo-binary.d.ts +54 -0
- package/backend/dist/proxy/mihomo-binary.js +278 -0
- package/backend/dist/proxy/mihomo-client.d.ts +94 -0
- package/backend/dist/proxy/mihomo-client.js +308 -0
- package/backend/dist/proxy/mihomo-config.d.ts +40 -0
- package/backend/dist/proxy/mihomo-config.js +161 -0
- package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
- package/backend/dist/proxy/mihomo-geo.js +213 -0
- package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
- package/backend/dist/proxy/mihomo-logs.js +70 -0
- package/backend/dist/proxy/mihomo-pac.d.ts +37 -0
- package/backend/dist/proxy/mihomo-pac.js +75 -0
- package/backend/dist/proxy/mihomo-rules-import.d.ts +43 -0
- package/backend/dist/proxy/mihomo-rules-import.js +193 -0
- package/backend/dist/proxy/mihomo-sidecar.d.ts +81 -0
- package/backend/dist/proxy/mihomo-sidecar.js +637 -0
- package/backend/dist/quota/adapters/minimax.js +36 -13
- package/backend/dist/quota/cli-login.d.ts +8 -0
- package/backend/dist/quota/cli-login.js +18 -0
- package/backend/dist/quota/declarations.js +10 -0
- package/backend/dist/quota/dsl.js +18 -5
- package/backend/dist/quota/engine.d.ts +31 -3
- package/backend/dist/quota/engine.js +189 -30
- package/backend/dist/quota/prober.d.ts +13 -4
- package/backend/dist/quota/prober.js +20 -12
- package/backend/dist/quota/types.d.ts +87 -8
- package/backend/dist/quota/verdict.d.ts +35 -0
- package/backend/dist/quota/verdict.js +135 -0
- package/backend/dist/ratelimit/admission.d.ts +131 -0
- package/backend/dist/ratelimit/admission.js +233 -0
- package/backend/dist/ratelimit/rate-limiter.d.ts +119 -6
- package/backend/dist/ratelimit/rate-limiter.js +364 -20
- package/backend/dist/ratelimit/window-store.d.ts +34 -0
- package/backend/dist/ratelimit/window-store.js +70 -0
- package/backend/dist/resilience/breaker-state.js +8 -1
- package/backend/dist/resilience/circuit-breaker-manager.d.ts +229 -132
- package/backend/dist/resilience/circuit-breaker-manager.js +566 -297
- package/backend/dist/resilience/circuit-breaker.d.ts +11 -0
- package/backend/dist/resilience/circuit-breaker.js +39 -7
- package/backend/dist/resilience/error-classifier.d.ts +31 -3
- package/backend/dist/resilience/error-classifier.js +159 -31
- package/backend/dist/resilience/health-prober.d.ts +21 -4
- package/backend/dist/resilience/health-prober.js +100 -18
- package/backend/dist/resilience/types.d.ts +54 -7
- package/backend/dist/resilience/types.js +1 -1
- package/backend/dist/router/index.d.ts +6 -29
- package/backend/dist/router/index.js +15 -61
- package/backend/dist/router/layer2-decision.d.ts +3 -3
- package/backend/dist/router/layer2-decision.js +26 -26
- package/backend/dist/router/request-traits.d.ts +4 -11
- package/backend/dist/router/request-traits.js +5 -13
- package/backend/dist/routes/console.js +2145 -259
- package/backend/dist/routes/environments.d.ts +3 -2
- package/backend/dist/routes/environments.js +8 -4
- package/backend/dist/routes/harness.d.ts +3 -1
- package/backend/dist/routes/harness.js +1162 -356
- package/backend/dist/routes/mihomo.d.ts +7 -0
- package/backend/dist/routes/mihomo.js +1187 -0
- package/backend/dist/routes/projects.d.ts +2 -0
- package/backend/dist/routes/projects.js +90 -0
- package/backend/dist/routes/responses.d.ts +107 -9
- package/backend/dist/routes/responses.js +378 -35
- package/backend/dist/routes/translation.d.ts +9 -0
- package/backend/dist/routes/translation.js +155 -0
- package/backend/dist/server.js +379 -73
- package/backend/dist/session/resp-store.d.ts +18 -49
- package/backend/dist/session/resp-store.js +114 -122
- package/backend/dist/session/session-manager.d.ts +228 -81
- package/backend/dist/session/session-manager.js +449 -190
- package/backend/dist/session/session-row.d.ts +81 -2
- package/backend/dist/session/session-row.js +69 -1
- package/backend/dist/surfaces/anthropic.d.ts +1 -15
- package/backend/dist/surfaces/anthropic.js +63 -44
- package/backend/dist/surfaces/chat-pipeline.d.ts +10 -6
- package/backend/dist/surfaces/chat-pipeline.js +119 -42
- package/backend/dist/surfaces/chat.d.ts +1 -9
- package/backend/dist/surfaces/chat.js +67 -29
- package/backend/dist/surfaces/decision-pipeline.js +32 -27
- package/backend/dist/surfaces/direct-forward.d.ts +3 -0
- package/backend/dist/surfaces/direct-forward.js +206 -0
- package/backend/dist/surfaces/gateway-chat.d.ts +53 -0
- package/backend/dist/surfaces/gateway-chat.js +204 -0
- package/backend/dist/surfaces/ocr-headers.d.ts +25 -4
- package/backend/dist/surfaces/ocr-headers.js +52 -6
- package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
- package/backend/dist/surfaces/rate-limit-response.js +57 -0
- package/backend/dist/surfaces/responses.d.ts +9 -1
- package/backend/dist/surfaces/responses.js +141 -141
- package/backend/dist/surfaces/systemone-probe.js +1 -1
- package/backend/dist/surfaces/systemone.d.ts +1 -1
- package/backend/dist/surfaces/systemone.js +1 -1
- package/backend/dist/surfaces/table.d.ts +15 -0
- package/backend/dist/surfaces/table.js +15 -0
- package/backend/dist/surfaces/transport-backpressure.d.ts +46 -0
- package/backend/dist/surfaces/transport-backpressure.js +122 -0
- package/backend/dist/surfaces/transport-fastify.js +92 -21
- package/backend/dist/surfaces/transport-node-http.js +92 -18
- package/backend/dist/surfaces/types.d.ts +85 -12
- package/backend/dist/trace/persist.d.ts +5 -0
- package/backend/dist/trace/persist.js +185 -24
- package/backend/dist/trace/tracker.d.ts +185 -17
- package/backend/dist/trace/tracker.js +106 -31
- package/backend/dist/translation/index.d.ts +151 -0
- package/backend/dist/translation/index.js +735 -0
- package/backend/dist/types/openai.d.ts +82 -1
- package/backend/dist/types/router.d.ts +104 -17
- package/backend/dist/types/router.js +68 -7
- package/backend/dist/update/check.d.ts +43 -0
- package/backend/dist/update/check.js +126 -0
- package/backend/dist/utils/chat-sse.d.ts +2 -22
- package/backend/dist/utils/chat-sse.js +1 -69
- package/backend/dist/utils/chat-stream.d.ts +23 -9
- package/backend/dist/utils/chat-stream.js +46 -9
- package/backend/dist/utils/client-envelope.d.ts +108 -0
- package/backend/dist/utils/client-envelope.js +305 -0
- package/backend/dist/utils/event-ring.d.ts +12 -1
- package/backend/dist/utils/event-ring.js +17 -5
- package/backend/dist/utils/harness-profiles.d.ts +51 -0
- package/backend/dist/utils/harness-profiles.js +70 -0
- package/backend/dist/utils/percentile.d.ts +16 -0
- package/backend/dist/utils/percentile.js +29 -0
- package/backend/dist/utils/popularity.d.ts +4 -0
- package/backend/dist/utils/popularity.js +58 -0
- package/backend/dist/utils/probe-interval.d.ts +12 -0
- package/backend/dist/utils/probe-interval.js +16 -0
- package/backend/dist/utils/proxy-node.d.ts +13 -0
- package/backend/dist/utils/proxy-node.js +471 -0
- package/backend/dist/utils/proxy.d.ts +19 -0
- package/backend/dist/utils/proxy.js +79 -14
- package/backend/dist/utils/retry-after.d.ts +21 -0
- package/backend/dist/utils/retry-after.js +36 -0
- package/backend/dist/utils/run-command.d.ts +42 -0
- package/backend/dist/utils/run-command.js +93 -0
- package/backend/dist/utils/self-url.d.ts +13 -0
- package/backend/dist/utils/self-url.js +90 -2
- package/backend/dist/utils/semver.d.ts +22 -0
- package/backend/dist/utils/semver.js +75 -0
- package/backend/dist/utils/stream-relay.d.ts +35 -0
- package/backend/dist/utils/stream-relay.js +1 -0
- package/backend/dist/utils/upstream-url-guard.d.ts +15 -0
- package/backend/dist/utils/upstream-url-guard.js +107 -0
- package/backend/dist/validator/parser.d.ts +2 -5
- package/backend/dist/validator/parser.js +12 -16
- package/backend/dist/validator/schema-assertion.d.ts +3 -2
- package/backend/dist/validator/schema-assertion.js +53 -8
- package/bin/ocr.js +2 -2
- package/frontend/dist/assets/index-Cn3QMOQx.js +1487 -0
- package/frontend/dist/assets/index-DxZ9MHKB.css +1 -0
- package/frontend/dist/assets/qoder.color-tVX5GCcD.svg +5 -0
- package/frontend/dist/index.html +2 -2
- package/frontend/dist/provider-logos/302ai.svg +7 -0
- package/frontend/dist/provider-logos/NOTICE.txt +39 -0
- package/frontend/dist/provider-logos/abacus.svg +14 -0
- package/frontend/dist/provider-logos/abliteration-ai.svg +6 -0
- package/frontend/dist/provider-logos/above.svg +3 -0
- package/frontend/dist/provider-logos/agentrouter.svg +4 -0
- package/frontend/dist/provider-logos/agnes.svg +1 -0
- package/frontend/dist/provider-logos/ai-router.svg +5 -0
- package/frontend/dist/provider-logos/ai21.svg +3 -0
- package/frontend/dist/provider-logos/aiand.svg +4 -0
- package/frontend/dist/provider-logos/aihubmix.svg +3 -0
- package/frontend/dist/provider-logos/aimlapi.svg +3 -0
- package/frontend/dist/provider-logos/ainetcafe.svg +1 -0
- package/frontend/dist/provider-logos/aixy.svg +4 -0
- package/frontend/dist/provider-logos/aki-io.svg +8 -0
- package/frontend/dist/provider-logos/alibaba-cn.svg +3 -0
- package/frontend/dist/provider-logos/alibaba-coding-plan-cn.svg +3 -0
- package/frontend/dist/provider-logos/alibaba-coding-plan.svg +3 -0
- package/frontend/dist/provider-logos/alibaba-token-plan-cn.svg +1 -0
- package/frontend/dist/provider-logos/alibaba-token-plan.svg +1 -0
- package/frontend/dist/provider-logos/alibaba.svg +3 -0
- package/frontend/dist/provider-logos/amazon-bedrock.svg +3 -0
- package/frontend/dist/provider-logos/ambient.svg +3 -0
- package/frontend/dist/provider-logos/amd.svg +3 -0
- package/frontend/dist/provider-logos/anthropic.svg +3 -0
- package/frontend/dist/provider-logos/anyapi.svg +3 -0
- package/frontend/dist/provider-logos/arcee.svg +3 -0
- package/frontend/dist/provider-logos/atomic-chat.svg +1 -0
- package/frontend/dist/provider-logos/auriko.svg +6 -0
- package/frontend/dist/provider-logos/azure-cognitive-services.svg +3 -0
- package/frontend/dist/provider-logos/azure.svg +3 -0
- package/frontend/dist/provider-logos/bailing.svg +3 -0
- package/frontend/dist/provider-logos/baseten.svg +3 -0
- package/frontend/dist/provider-logos/bee.svg +1 -0
- package/frontend/dist/provider-logos/berget.svg +3 -0
- package/frontend/dist/provider-logos/blueclaw.svg +3 -0
- package/frontend/dist/provider-logos/bothub.svg +33 -0
- package/frontend/dist/provider-logos/boundless.svg +12 -0
- package/frontend/dist/provider-logos/cerebras.svg +4 -0
- package/frontend/dist/provider-logos/chutes.svg +24 -0
- package/frontend/dist/provider-logos/clarifai.svg +3 -0
- package/frontend/dist/provider-logos/claudinio.svg +19 -0
- package/frontend/dist/provider-logos/cline-pass.svg +24 -0
- package/frontend/dist/provider-logos/cloudferro-sherlock.svg +5 -0
- package/frontend/dist/provider-logos/cloudflare-ai-gateway.svg +4 -0
- package/frontend/dist/provider-logos/cloudflare-workers-ai.svg +4 -0
- package/frontend/dist/provider-logos/cohere.svg +5 -0
- package/frontend/dist/provider-logos/commandcode.svg +11 -0
- package/frontend/dist/provider-logos/coralbricks.svg +6 -0
- package/frontend/dist/provider-logos/cortecs.svg +24 -0
- package/frontend/dist/provider-logos/crossmodel.svg +5 -0
- package/frontend/dist/provider-logos/crusoe.svg +23 -0
- package/frontend/dist/provider-logos/daoxe.svg +3 -0
- package/frontend/dist/provider-logos/databricks.svg +3 -0
- package/frontend/dist/provider-logos/deepinfra.svg +4 -0
- package/frontend/dist/provider-logos/deepseek.svg +3 -0
- package/frontend/dist/provider-logos/digitalocean.svg +6 -0
- package/frontend/dist/provider-logos/dinference.svg +1 -0
- package/frontend/dist/provider-logos/drun.svg +8 -0
- package/frontend/dist/provider-logos/ebcloud.svg +8 -0
- package/frontend/dist/provider-logos/echo.svg +7 -0
- package/frontend/dist/provider-logos/edenai.svg +8 -0
- package/frontend/dist/provider-logos/empiriolabs.svg +1 -0
- package/frontend/dist/provider-logos/engy.svg +1 -0
- package/frontend/dist/provider-logos/evroc.svg +3 -0
- package/frontend/dist/provider-logos/fastrouter.svg +3 -0
- package/frontend/dist/provider-logos/fireworks-ai.svg +3 -0
- package/frontend/dist/provider-logos/freemodel.svg +3 -0
- package/frontend/dist/provider-logos/friendli.svg +3 -0
- package/frontend/dist/provider-logos/frogbot.svg +36 -0
- package/frontend/dist/provider-logos/github-copilot.svg +3 -0
- package/frontend/dist/provider-logos/gitlab.svg +3 -0
- package/frontend/dist/provider-logos/gmicloud.svg +24 -0
- package/frontend/dist/provider-logos/google-vertex-anthropic.svg +10 -0
- package/frontend/dist/provider-logos/google-vertex.svg +10 -0
- package/frontend/dist/provider-logos/google.svg +3 -0
- package/frontend/dist/provider-logos/greenpt.svg +6 -0
- package/frontend/dist/provider-logos/groq.svg +3 -0
- package/frontend/dist/provider-logos/helicone.svg +6 -0
- package/frontend/dist/provider-logos/hetzner.svg +3 -0
- package/frontend/dist/provider-logos/hopper.svg +4 -0
- package/frontend/dist/provider-logos/hpc-ai.svg +446 -0
- package/frontend/dist/provider-logos/huggingface.svg +3 -0
- package/frontend/dist/provider-logos/hyper.svg +20 -0
- package/frontend/dist/provider-logos/impossibl.svg +3 -0
- package/frontend/dist/provider-logos/inception.svg +14 -0
- package/frontend/dist/provider-logos/inceptron.svg +14 -0
- package/frontend/dist/provider-logos/inco.svg +3 -0
- package/frontend/dist/provider-logos/infer.svg +4 -0
- package/frontend/dist/provider-logos/inference.svg +3 -0
- package/frontend/dist/provider-logos/inferx.svg +5 -0
- package/frontend/dist/provider-logos/infomaniak.svg +3 -0
- package/frontend/dist/provider-logos/io-net.svg +5 -0
- package/frontend/dist/provider-logos/iteracompute.svg +7 -0
- package/frontend/dist/provider-logos/jalapeno.svg +8 -0
- package/frontend/dist/provider-logos/jiekou.svg +4 -0
- package/frontend/dist/provider-logos/kenari.svg +4 -0
- package/frontend/dist/provider-logos/kilo.svg +4 -0
- package/frontend/dist/provider-logos/kimi-code-plan-cn.svg +3 -0
- package/frontend/dist/provider-logos/kimi-code-plan-global.svg +3 -0
- package/frontend/dist/provider-logos/klokintegration.svg +11 -0
- package/frontend/dist/provider-logos/kosmik.svg +28 -0
- package/frontend/dist/provider-logos/kuae-cloud-coding-plan.svg +3 -0
- package/frontend/dist/provider-logos/lilac.svg +6 -0
- package/frontend/dist/provider-logos/liquid.svg +1 -0
- package/frontend/dist/provider-logos/llmgateway-providers.svg +6 -0
- package/frontend/dist/provider-logos/llmgateway.svg +6 -0
- package/frontend/dist/provider-logos/llmtech.svg +6 -0
- package/frontend/dist/provider-logos/llmtr.svg +12 -0
- package/frontend/dist/provider-logos/lmstudio.svg +3 -0
- package/frontend/dist/provider-logos/longcat.svg +6 -0
- package/frontend/dist/provider-logos/lowrouter.svg +8 -0
- package/frontend/dist/provider-logos/lucidquery.svg +3 -0
- package/frontend/dist/provider-logos/lynkr.svg +1 -0
- package/frontend/dist/provider-logos/meganova.svg +3 -0
- package/frontend/dist/provider-logos/melious.svg +3 -0
- package/frontend/dist/provider-logos/merge-gateway.svg +4 -0
- package/frontend/dist/provider-logos/meta.svg +3 -0
- package/frontend/dist/provider-logos/minimax-cn-coding-plan.svg +3 -0
- package/frontend/dist/provider-logos/minimax-cn.svg +3 -0
- package/frontend/dist/provider-logos/minimax-coding-plan.svg +3 -0
- package/frontend/dist/provider-logos/minimax.svg +3 -0
- package/frontend/dist/provider-logos/mistral.svg +3 -0
- package/frontend/dist/provider-logos/mixlayer.svg +9 -0
- package/frontend/dist/provider-logos/moark.svg +3 -0
- package/frontend/dist/provider-logos/modal.svg +3 -0
- package/frontend/dist/provider-logos/model-oracle-ai.svg +11 -0
- package/frontend/dist/provider-logos/modelis.svg +1 -0
- package/frontend/dist/provider-logos/modelscope.svg +5 -0
- package/frontend/dist/provider-logos/modular.svg +3 -0
- package/frontend/dist/provider-logos/moonshotai-cn.svg +3 -0
- package/frontend/dist/provider-logos/moonshotai.svg +3 -0
- package/frontend/dist/provider-logos/morph.svg +24 -0
- package/frontend/dist/provider-logos/munito-eu.svg +1 -0
- package/frontend/dist/provider-logos/munito.svg +1 -0
- package/frontend/dist/provider-logos/nan.svg +1 -0
- package/frontend/dist/provider-logos/nano-gpt.svg +3 -0
- package/frontend/dist/provider-logos/nearai.svg +1 -0
- package/frontend/dist/provider-logos/nebius.svg +4 -0
- package/frontend/dist/provider-logos/neon.svg +3 -0
- package/frontend/dist/provider-logos/neosmith.svg +6 -0
- package/frontend/dist/provider-logos/neuralwatt.svg +27 -0
- package/frontend/dist/provider-logos/nova.svg +3 -0
- package/frontend/dist/provider-logos/novita-ai.svg +10 -0
- package/frontend/dist/provider-logos/nvidia.svg +3 -0
- package/frontend/dist/provider-logos/oci.svg +3 -0
- package/frontend/dist/provider-logos/ofox.svg +5 -0
- package/frontend/dist/provider-logos/ollama-cloud.svg +7 -0
- package/frontend/dist/provider-logos/openai.svg +3 -0
- package/frontend/dist/provider-logos/opencode-go.svg +4 -0
- package/frontend/dist/provider-logos/opencode.svg +4 -0
- package/frontend/dist/provider-logos/openreason.svg +8 -0
- package/frontend/dist/provider-logos/openrouter.svg +5 -0
- package/frontend/dist/provider-logos/opper.svg +3 -0
- package/frontend/dist/provider-logos/orcarouter.svg +2 -0
- package/frontend/dist/provider-logos/ovhcloud.svg +3 -0
- package/frontend/dist/provider-logos/pareto.svg +5 -0
- package/frontend/dist/provider-logos/pendra.svg +10 -0
- package/frontend/dist/provider-logos/perplexity-agent.svg +3 -0
- package/frontend/dist/provider-logos/perplexity.svg +3 -0
- package/frontend/dist/provider-logos/pioneer.svg +3 -0
- package/frontend/dist/provider-logos/poe.svg +7 -0
- package/frontend/dist/provider-logos/poolside.svg +3 -0
- package/frontend/dist/provider-logos/prime.svg +7 -0
- package/frontend/dist/provider-logos/privatemode-ai.svg +5 -0
- package/frontend/dist/provider-logos/qihang-ai.svg +9 -0
- package/frontend/dist/provider-logos/qiniu-ai.svg +7 -0
- package/frontend/dist/provider-logos/qvac.svg +6 -0
- package/frontend/dist/provider-logos/reflection.svg +3 -0
- package/frontend/dist/provider-logos/regolo-ai.svg +46 -0
- package/frontend/dist/provider-logos/requesty.svg +24 -0
- package/frontend/dist/provider-logos/routing-run.svg +4 -0
- package/frontend/dist/provider-logos/runinfra.svg +10 -0
- package/frontend/dist/provider-logos/sakana.svg +24 -0
- package/frontend/dist/provider-logos/salad-cloud.svg +15 -0
- package/frontend/dist/provider-logos/sambanova.svg +26 -0
- package/frontend/dist/provider-logos/sap-ai-core.svg +24 -0
- package/frontend/dist/provider-logos/sarvam.svg +24 -0
- package/frontend/dist/provider-logos/scaleway.svg +5 -0
- package/frontend/dist/provider-logos/scnet-token-plan.svg +8 -0
- package/frontend/dist/provider-logos/scx-ai.svg +1 -0
- package/frontend/dist/provider-logos/sensenova.svg +18 -0
- package/frontend/dist/provider-logos/siliconflow-cn.svg +3 -0
- package/frontend/dist/provider-logos/siliconflow.svg +3 -0
- package/frontend/dist/provider-logos/snowflake-cortex.svg +3 -0
- package/frontend/dist/provider-logos/stackit.svg +4 -0
- package/frontend/dist/provider-logos/standardcompute.svg +5 -0
- package/frontend/dist/provider-logos/stepfun-ai-step-plan.svg +16 -0
- package/frontend/dist/provider-logos/stepfun-ai.svg +16 -0
- package/frontend/dist/provider-logos/stepfun-step-plan.svg +16 -0
- package/frontend/dist/provider-logos/stepfun.svg +16 -0
- package/frontend/dist/provider-logos/subconscious.svg +3 -0
- package/frontend/dist/provider-logos/submodel.svg +3 -0
- package/frontend/dist/provider-logos/synthetic.svg +24 -0
- package/frontend/dist/provider-logos/tempr.svg +4 -0
- package/frontend/dist/provider-logos/tencent-coding-plan.svg +5 -0
- package/frontend/dist/provider-logos/tencent-token-plan.svg +3 -0
- package/frontend/dist/provider-logos/tencent-tokenhub.svg +3 -0
- package/frontend/dist/provider-logos/tensorx.svg +6 -0
- package/frontend/dist/provider-logos/the-grid-ai.svg +14 -0
- package/frontend/dist/provider-logos/thinkingmachines.svg +3 -0
- package/frontend/dist/provider-logos/tinfoil.svg +3 -0
- package/frontend/dist/provider-logos/togetherai.svg +4 -0
- package/frontend/dist/provider-logos/tokengo.svg +3 -0
- package/frontend/dist/provider-logos/tokenrouter.svg +4 -0
- package/frontend/dist/provider-logos/trustedrouter.svg +4 -0
- package/frontend/dist/provider-logos/umans-ai-coding-plan.svg +29 -0
- package/frontend/dist/provider-logos/umans-ai.svg +29 -0
- package/frontend/dist/provider-logos/unorouter.svg +7 -0
- package/frontend/dist/provider-logos/upstage.svg +24 -0
- package/frontend/dist/provider-logos/vancine.svg +6 -0
- package/frontend/dist/provider-logos/venice.svg +4 -0
- package/frontend/dist/provider-logos/vercel.svg +3 -0
- package/frontend/dist/provider-logos/vispark.svg +3 -0
- package/frontend/dist/provider-logos/vivgrid.svg +4 -0
- package/frontend/dist/provider-logos/volcengine-coding-plan.svg +1 -0
- package/frontend/dist/provider-logos/volcengine.svg +1 -0
- package/frontend/dist/provider-logos/vultr.svg +6 -0
- package/frontend/dist/provider-logos/wafer.ai.svg +3 -0
- package/frontend/dist/provider-logos/wallaby.svg +4 -0
- package/frontend/dist/provider-logos/wally.svg +1 -0
- package/frontend/dist/provider-logos/wandb.svg +6 -0
- package/frontend/dist/provider-logos/watsonx.svg +5 -0
- package/frontend/dist/provider-logos/xai.svg +3 -0
- package/frontend/dist/provider-logos/xiaomi-token-plan-ams.svg +3 -0
- package/frontend/dist/provider-logos/xiaomi-token-plan-cn.svg +3 -0
- package/frontend/dist/provider-logos/xiaomi-token-plan-sgp.svg +3 -0
- package/frontend/dist/provider-logos/xiaomi.svg +3 -0
- package/frontend/dist/provider-logos/xpersona.svg +8 -0
- package/frontend/dist/provider-logos/zai-coding-plan.svg +3 -0
- package/frontend/dist/provider-logos/zai.svg +3 -0
- package/frontend/dist/provider-logos/zeldoc.svg +3 -0
- package/frontend/dist/provider-logos/zenifra.svg +4 -0
- package/frontend/dist/provider-logos/zenmux.svg +4 -0
- package/frontend/dist/provider-logos/zhipuai-coding-plan.svg +3 -0
- package/frontend/dist/provider-logos/zhipuai.svg +3 -0
- package/package.json +13 -5
- package/backend/dist/budget/budget-manager.d.ts +0 -25
- package/backend/dist/budget/budget-manager.js +0 -54
- package/backend/dist/config/governance-limits.d.ts +0 -68
- package/backend/dist/config/governance-limits.js +0 -261
- package/backend/dist/flywheel/collector.d.ts +0 -74
- package/backend/dist/flywheel/collector.js +0 -235
- package/backend/dist/flywheel/dataset.d.ts +0 -130
- package/backend/dist/flywheel/dataset.js +0 -638
- package/backend/dist/flywheel/decision-capture.d.ts +0 -68
- package/backend/dist/flywheel/decision-capture.js +0 -85
- package/backend/dist/flywheel/prune.d.ts +0 -133
- package/backend/dist/flywheel/prune.js +0 -495
- package/backend/dist/flywheel/schema.d.ts +0 -108
- package/backend/dist/flywheel/schema.js +0 -117
- package/backend/dist/flywheel/trainer.d.ts +0 -84
- package/backend/dist/flywheel/trainer.js +0 -198
- package/backend/dist/forward-proxy/bypass.d.ts +0 -20
- package/backend/dist/forward-proxy/bypass.js +0 -28
- package/backend/dist/harness/adapters/amp.d.ts +0 -2
- package/backend/dist/harness/adapters/amp.js +0 -8
- package/backend/dist/harness/adapters/claude.d.ts +0 -2
- package/backend/dist/harness/adapters/claude.js +0 -8
- package/backend/dist/harness/adapters/cline.d.ts +0 -2
- package/backend/dist/harness/adapters/cline.js +0 -8
- package/backend/dist/harness/adapters/codex.d.ts +0 -2
- package/backend/dist/harness/adapters/codex.js +0 -8
- package/backend/dist/harness/adapters/cursor.d.ts +0 -5
- package/backend/dist/harness/adapters/cursor.js +0 -11
- package/backend/dist/harness/adapters/declarative.d.ts +0 -64
- package/backend/dist/harness/adapters/declarative.js +0 -216
- package/backend/dist/harness/adapters/dsh.d.ts +0 -5
- package/backend/dist/harness/adapters/dsh.js +0 -6
- package/backend/dist/harness/adapters/gemini-cli.d.ts +0 -2
- package/backend/dist/harness/adapters/gemini-cli.js +0 -8
- package/backend/dist/harness/adapters/github-copilot.d.ts +0 -5
- package/backend/dist/harness/adapters/github-copilot.js +0 -11
- package/backend/dist/harness/adapters/omp.d.ts +0 -11
- package/backend/dist/harness/adapters/omp.js +0 -22
- package/backend/dist/harness/adapters/opencode.d.ts +0 -2
- package/backend/dist/harness/adapters/opencode.js +0 -56
- package/backend/dist/harness/adapters/pi.d.ts +0 -1
- package/backend/dist/harness/adapters/pi.js +0 -23
- package/backend/dist/harness/adapters/types.d.ts +0 -189
- package/backend/dist/harness/adapters/types.js +0 -12
- package/backend/dist/harness/adapters/universal.d.ts +0 -6
- package/backend/dist/harness/adapters/universal.js +0 -10
- package/backend/dist/harness/adapters/windsurf.d.ts +0 -2
- package/backend/dist/harness/adapters/windsurf.js +0 -11
- package/backend/dist/harness/adapters/zed.d.ts +0 -2
- package/backend/dist/harness/adapters/zed.js +0 -8
- package/backend/dist/harness/awesome-opencode.d.ts +0 -40
- package/backend/dist/harness/awesome-opencode.js +0 -75
- package/backend/dist/harness/browse.d.ts +0 -202
- package/backend/dist/harness/browse.js +0 -1214
- package/backend/dist/harness/inventory.d.ts +0 -10
- package/backend/dist/harness/opencode-cafe.d.ts +0 -40
- package/backend/dist/harness/opencode-cafe.js +0 -85
- package/backend/dist/harness/opencode-ecosystem.d.ts +0 -34
- package/backend/dist/harness/opencode-ecosystem.js +0 -246
- package/backend/dist/harness/pi-dev.d.ts +0 -81
- package/backend/dist/harness/pi-dev.js +0 -187
- package/backend/dist/harness/registry.js +0 -26
- package/backend/dist/harness/scopes.d.ts +0 -21
- package/backend/dist/harness/scopes.js +0 -22
- package/backend/dist/harness/skills-sh.d.ts +0 -109
- package/backend/dist/harness/skills-sh.js +0 -178
- package/backend/dist/harness/smithery.d.ts +0 -64
- package/backend/dist/harness/smithery.js +0 -146
- package/backend/dist/harness/sources/awesome-opencode.d.ts +0 -11
- package/backend/dist/harness/sources/awesome-opencode.js +0 -39
- package/backend/dist/harness/sources/mcp-official.d.ts +0 -2
- package/backend/dist/harness/sources/mcp-official.js +0 -110
- package/backend/dist/harness/sources/npm.d.ts +0 -2
- package/backend/dist/harness/sources/opencode-cafe.d.ts +0 -11
- package/backend/dist/harness/sources/opencode-cafe.js +0 -41
- package/backend/dist/harness/sources/smithery.d.ts +0 -2
- package/backend/dist/harness/sources/smithery.js +0 -81
- package/backend/dist/harness/writers/extension.d.ts +0 -116
- package/backend/dist/harness/writers/extension.js +0 -219
- package/backend/dist/harness/writers/mcp.d.ts +0 -72
- package/backend/dist/harness/writers/mcp.js +0 -195
- package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
- package/backend/dist/opencode/catalog/custom-store.js +0 -144
- package/backend/dist/opencode/credentials/push.d.ts +0 -38
- package/backend/dist/opencode/credentials/push.js +0 -116
- package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
- package/backend/dist/opencode/credentials/reconcile.js +0 -216
- package/backend/dist/opencode/sync.d.ts +0 -29
- package/backend/dist/opencode/sync.js +0 -186
- package/backend/dist/pipeline/account-selection.d.ts +0 -101
- package/backend/dist/pipeline/account-selection.js +0 -112
- package/backend/dist/providers/systemone.d.ts +0 -29
- package/backend/dist/providers/systemone.js +0 -170
- package/backend/dist/ratelimit/duration.d.ts +0 -24
- package/backend/dist/ratelimit/duration.js +0 -43
- package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
- package/backend/dist/ratelimit/governance-runtime.js +0 -183
- package/backend/dist/ratelimit/index.d.ts +0 -4
- package/backend/dist/ratelimit/index.js +0 -4
- package/backend/dist/ratelimit/limiter.d.ts +0 -157
- package/backend/dist/ratelimit/limiter.js +0 -244
- package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
- package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
- package/backend/dist/ratelimit/subject.d.ts +0 -26
- package/backend/dist/ratelimit/subject.js +0 -28
- package/backend/dist/resilience/account-state.d.ts +0 -84
- package/backend/dist/resilience/account-state.js +0 -228
- package/backend/dist/router/layer1-classifier.d.ts +0 -111
- package/backend/dist/router/layer1-classifier.js +0 -467
- package/backend/dist/router/layer2-judge.d.ts +0 -111
- package/backend/dist/router/layer2-judge.js +0 -373
- package/backend/dist/router/retry-escalation.d.ts +0 -89
- package/backend/dist/router/retry-escalation.js +0 -99
- package/backend/dist/routes/flywheel.d.ts +0 -3
- package/backend/dist/routes/flywheel.js +0 -268
- package/backend/dist/routes/systemone.d.ts +0 -3
- package/backend/dist/routes/systemone.js +0 -90
- package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
- package/backend/dist/surfaces/governance-envelope.js +0 -47
- package/backend/dist/utils/token-estimator.d.ts +0 -7
- package/backend/dist/utils/token-estimator.js +0 -20
- package/frontend/dist/assets/index-B7GKsUyU.js +0 -982
- package/frontend/dist/assets/index-DLKLOkQJ.css +0 -1
- package/frontend/dist/assets/inter-cyrillic-800-normal-C7MGvYyJ.woff2 +0 -0
- package/frontend/dist/assets/inter-cyrillic-800-normal-CCHyn08d.woff +0 -0
- package/frontend/dist/assets/inter-cyrillic-ext-800-normal-BZOjs1Xv.woff2 +0 -0
- package/frontend/dist/assets/inter-cyrillic-ext-800-normal-Ca-gJeZY.woff +0 -0
- package/frontend/dist/assets/inter-greek-800-normal-BU00tryP.woff +0 -0
- package/frontend/dist/assets/inter-greek-800-normal-CLIouy3y.woff2 +0 -0
- package/frontend/dist/assets/inter-greek-ext-800-normal-B--PVpEC.woff2 +0 -0
- package/frontend/dist/assets/inter-greek-ext-800-normal-DUe57HfS.woff +0 -0
- package/frontend/dist/assets/inter-latin-800-normal-BYj_oED-.woff2 +0 -0
- package/frontend/dist/assets/inter-latin-800-normal-D1mf63XC.woff +0 -0
- package/frontend/dist/assets/inter-latin-ext-800-normal-BOMpwxm3.woff +0 -0
- package/frontend/dist/assets/inter-latin-ext-800-normal-DZJjya6U.woff2 +0 -0
- package/frontend/dist/assets/inter-vietnamese-800-normal-Cm7tD1pz.woff2 +0 -0
- package/frontend/dist/assets/inter-vietnamese-800-normal-DDlpr_Ee.woff +0 -0
- /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.d.ts +0 -0
- /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.js +0 -0
- /package/backend/dist/harness/{skill-md.d.ts → skill/skill-md.d.ts} +0 -0
- /package/backend/dist/harness/{skill-md.js → skill/skill-md.js} +0 -0
|
@@ -1,37 +1,64 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { getAllClientStatuses,
|
|
3
|
+
import { getAllClientStatuses, setupClient, teardownClient } from '../cli/clients/index.js';
|
|
4
|
+
import { VIRTUAL_AUTO_IDS } from '../cli/types.js';
|
|
4
5
|
import { MEMBER_TIER_ORDER } from '../providers/member-match.js';
|
|
6
|
+
import { refreshDirectPool } from '../providers/boot-direct.js';
|
|
5
7
|
import { TIER_PURPOSE } from '../providers/virtual-meta.js';
|
|
8
|
+
import { getProviderTakedownStore } from '../providers/provider-takedown.js';
|
|
9
|
+
import { protocolVocabulary } from '../providers/vocabulary.js';
|
|
10
|
+
import { pluginPackageZip, pluginProviderOrigins } from '../plugins/host.js';
|
|
11
|
+
import { listGateways, getGatewayById } from '../plugins/gateways.js';
|
|
6
12
|
import { globMatchAny } from '../utils/glob.js';
|
|
7
|
-
import { getRawConfig, loadConfig, saveConfig, saveRawConfig, getRuntimeConfigRef } from '../config/index.js';
|
|
13
|
+
import { getRawConfig, loadConfig, saveConfig, saveRawConfig, getRuntimeConfigRef, getConfigPath } from '../config/index.js';
|
|
14
|
+
import { YAML_FILE_HEADER_ZH, YAML_FIELD_COMMENTS_ZH } from '../config/comments-zh.js';
|
|
15
|
+
import { YAML_FILE_HEADER_EN, YAML_FIELD_COMMENTS_EN } from '../config/comments-en.js';
|
|
8
16
|
import { getEnvPaths, resolveEnvName } from '../config/env.js';
|
|
9
17
|
import { applyConfig as applyDecisionCaptureConfig } from '../capture/decision-capture.js';
|
|
10
18
|
import { applyRouteEntriesConfig, getRouteEntryStore, routeEntriesGate } from '../router/route-entries.js';
|
|
11
19
|
import { applyDirectivesConfig } from '../pipeline/directive-gate.js';
|
|
20
|
+
import { applyStreamingPosture } from '../pipeline/streaming-posture.js';
|
|
12
21
|
import { appendRoutingLedger } from '../router/routing-ledger.js';
|
|
13
22
|
import { Layer2Decision } from '../router/layer2-decision.js';
|
|
14
|
-
import { EFFORT_LADDER } from '../types/router.js';
|
|
23
|
+
import { EFFORT_LADDER, modelSupportsEfforts } from '../types/router.js';
|
|
15
24
|
import { runSystemoneDecision } from '../protocols/systemone/decide.js';
|
|
16
|
-
import { SMART_ASSIGN_TIMEOUT_MS } from '../config/defaults.js';
|
|
17
|
-
import { initProxyConfig } from '../utils/proxy.js';
|
|
25
|
+
import { SMART_ASSIGN_TIMEOUT_MS, DEFAULT_REPLAY_TIMEOUT_MS, CREDENTIAL_WEIGHT_MAX, DEFAULT_FORWARD_PROXY_PORT, DEFAULT_FORWARD_PROXY_RULES, DEFAULT_FORWARD_PROXY_INTERCEPT, DEFAULT_MIHOMO_MIXED_PORT, PLUGIN_PACKAGE_MAX_BYTES, DEFAULT_TRAFFIC_DISSECT_WINDOW_BYTES } from '../config/defaults.js';
|
|
26
|
+
import { initProxyConfig, proxiedFetch } from '../utils/proxy.js';
|
|
27
|
+
import { registerMihomoRoutes } from './mihomo.js';
|
|
28
|
+
import { reconcileMihomoSidecar, getMihomoStatus } from '../proxy/mihomo-sidecar.js';
|
|
18
29
|
import { getOcrHomeDir } from '../cli/paths.js';
|
|
19
30
|
import { getHeadroomSidecarStatus, startHeadroomSidecar, stopHeadroomSidecar } from '../compression/headroom-sidecar.js';
|
|
20
31
|
import { APP_VERSION } from '../version.js';
|
|
32
|
+
import { getUpdateChecker } from '../update/check.js';
|
|
21
33
|
import { isSyncClientId } from '../opencode/credentials/sync.js';
|
|
22
|
-
import { ensureCa } from '../forward-proxy/ca.js';
|
|
34
|
+
import { caCertPath, describeCa, ensureCa, resolveCaDir } from '../forward-proxy/ca.js';
|
|
35
|
+
import { probeCaTrustedCached } from '../forward-proxy/ca-trust.js';
|
|
23
36
|
import { getForwardProxyStatus } from '../forward-proxy/status.js';
|
|
37
|
+
import { lintRules, normalizeRules, osBypassHosts, resolveHost, } from '../forward-proxy/rules.js';
|
|
38
|
+
import { listGatewayHosts, listClaimedEgress, claimEgressFor, WILDCARD_HOST_CLAIM } from '../plugins/gateways.js';
|
|
39
|
+
import { listProxyAccessEvents, readProxyAccessHistory, clearProxyAccessLog, deletePersistedProxyEvents, forgetProxyAccessRingEvents, proxyAccessLogSettings, proxyAccessBodyPath } from '../forward-proxy/access-log.js';
|
|
40
|
+
import { hideLiveEvents, liveHiddenProxyIds, liveHiddenPluginKeys } from '../observability/traffic-live-hidden.js';
|
|
41
|
+
import { getSystemProxyStatus, enableSystemProxy, disableSystemProxy, buildOverride, lanBypassHosts } from '../forward-proxy/system-proxy.js';
|
|
42
|
+
import { pacUrlFor } from '../proxy/mihomo-pac.js';
|
|
24
43
|
import { keyHashPrefix } from '../opencode/credentials/types.js';
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
44
|
+
import { CLI_LOGIN_QUOTA_PREFIX, providerUsesCliLogin } from '../quota/cli-login.js';
|
|
45
|
+
import { CLASSIFIER_TAXONOMY } from '../resilience/index.js';
|
|
46
|
+
import { maskSecret, isValidProviderId, PROVIDER_ID_RULE, getProviderNodeById } from '../opencode/user-config.js';
|
|
27
47
|
import { listOpenCodeAgentsLive } from '../opencode/agents.js';
|
|
28
48
|
import { listApiKeys, createApiKey, updateApiKey, deleteApiKey, validateApiKey, validateModelAccess, } from '../auth/api-keys.js';
|
|
49
|
+
import { toCallCredential } from '../providers/boot-direct.js';
|
|
29
50
|
import { getModelAccessPolicy, isAutoEntryUsable, isModelAllowed, isModelAllowedInTiers, tierFromVirtualEntry } from '../auth/model-access.js';
|
|
30
51
|
import { validateRateLimitRules, getRateLimiter, credentialSubject } from '../ratelimit/rate-limiter.js';
|
|
31
52
|
import { getQuotaProber } from '../quota/prober.js';
|
|
32
53
|
import { getQuotaStore } from '../quota/store.js';
|
|
33
54
|
import { getQuotaEventLog } from '../quota/events.js';
|
|
34
55
|
import { checkLoginAllowed, createSessionToken, hashPassword, hasWebAuthCredentials, isLoopbackHost, isWebAuthActive, parseSessionCookie, recordLoginFailure, recordLoginSuccess, sessionClearCookie, sessionSetCookie, verifyPassword, verifySessionToken, } from '../auth/web-auth.js';
|
|
56
|
+
/**
|
|
57
|
+
* Comment language for GET /api/admin/config/comments (the console's dynamic
|
|
58
|
+
* comment panel; config.yaml itself is ZERO-COMMENT on disk, ADR-0016).
|
|
59
|
+
* Anything else falls back to zh-CN.
|
|
60
|
+
*/
|
|
61
|
+
const commentLangFromQuery = (q) => (q === 'en' ? 'en' : 'zh-CN');
|
|
35
62
|
export { validateApiKey };
|
|
36
63
|
/* ------------------------------------------------------------------------ *
|
|
37
64
|
* Process-log tail helpers (for GET /api/admin/logs).
|
|
@@ -260,6 +287,49 @@ function clearSuspectForCredential(cb, providerId, keyHashPrefix) {
|
|
|
260
287
|
return;
|
|
261
288
|
cb.getCredentialStateStore().clear(providerId, keyHashPrefix);
|
|
262
289
|
}
|
|
290
|
+
/**
|
|
291
|
+
* Hot credential-chain rebuild for ONE provider — the runtime twin of the
|
|
292
|
+
* boot pool's chain. The routing chain (`registry.credentialChains`) is
|
|
293
|
+
* otherwise written ONLY at process boot, so a console connect/disconnect/
|
|
294
|
+
* activate or a credential sync would leave the live chain stale (new keys
|
|
295
|
+
* invisible to the spread, removed keys still routable) until the next
|
|
296
|
+
* restart. Reads the bound store's ordered chain (active head first) and
|
|
297
|
+
* swaps it in via `registry.refreshCredentialChain`; a store read failure is
|
|
298
|
+
* swallowed — the boot-baked chain keeps serving (fail-open, same doctrine as
|
|
299
|
+
* every observability write). RAW KEYS stay in memory (registry-only).
|
|
300
|
+
*/
|
|
301
|
+
async function refreshProviderCredentialChain(registry, store, providerId) {
|
|
302
|
+
try {
|
|
303
|
+
registry.refreshCredentialChain(providerId, store.resolveKeyChain(providerId).map((c) => toCallCredential(c.key, c.label, c.weight)));
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
// keep the existing chain — a refresh failure must never take routing down
|
|
307
|
+
}
|
|
308
|
+
// Chain-only by design: the pool rebuild stays behind the mutation-route
|
|
309
|
+
// wrapper (`withPoolSync`) or the config-save seams — a credential-sync
|
|
310
|
+
// run over P providers must not trigger P+1 full rebuilds.
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Wrap an admin mutation handler with a post-run POOL RESYNC: every def /
|
|
314
|
+
* credential / override write lands in the live registry the same way a boot
|
|
315
|
+
* rebuild would (ADR-0010 §3 amendment) — no restart. Fail-open: a rebuild
|
|
316
|
+
* error keeps the existing registry serving. Handlers that already replied
|
|
317
|
+
* (error paths) skip the resync.
|
|
318
|
+
*/
|
|
319
|
+
const withPoolSync = (registry, handler) => async (req, reply) => {
|
|
320
|
+
const result = await handler(req, reply);
|
|
321
|
+
if (!reply.sent) {
|
|
322
|
+
try {
|
|
323
|
+
await refreshDirectPool(registry);
|
|
324
|
+
}
|
|
325
|
+
catch (err) {
|
|
326
|
+
// Fail-open: the registry keeps serving, but a silent drift hides a
|
|
327
|
+
// failed mutation — log it so an operator can see it landed nowhere.
|
|
328
|
+
console.warn(`[console] pool resync after a def/credential mutation failed (registry may drift): ${err.message}`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return result;
|
|
332
|
+
};
|
|
263
333
|
/**
|
|
264
334
|
* Idempotent connect (identity at the write seam): handing the store a
|
|
265
335
|
* key it ALREADY holds for this provider is idempotent — the existing credential is
|
|
@@ -288,7 +358,7 @@ function clearSuspectForCredential(cb, providerId, keyHashPrefix) {
|
|
|
288
358
|
async function connectKeyIdempotent(store, providerId, key, label,
|
|
289
359
|
// Credential flags live in the resilience state file, reached through the manager
|
|
290
360
|
// so the write seam never re-derives its own view of "is this head still good".
|
|
291
|
-
cb) {
|
|
361
|
+
cb, registry) {
|
|
292
362
|
const { keyHashPrefix } = await import('../opencode/credentials/index.js');
|
|
293
363
|
const prefix = keyHashPrefix(key);
|
|
294
364
|
const before = store.listCredentials(providerId);
|
|
@@ -315,7 +385,7 @@ cb) {
|
|
|
315
385
|
* silently repointing the operator's terminal sessions is a hijack, not a
|
|
316
386
|
* default. When a USEABLE head already existed, put it back: the new key joins
|
|
317
387
|
* the chain as an extra credential, and promoting it stays a deliberate second
|
|
318
|
-
* action (the row's own
|
|
388
|
+
* action (the row's own pin-as-default button). A prior head that is SUSPECT or
|
|
319
389
|
* operator-disabled is NOT defended — there, the new key taking over IS the
|
|
320
390
|
* rotation the operator was reaching for.
|
|
321
391
|
*/
|
|
@@ -337,6 +407,9 @@ cb) {
|
|
|
337
407
|
}
|
|
338
408
|
}
|
|
339
409
|
}
|
|
410
|
+
// The chain is boot-baked otherwise — without this swap a newly connected key
|
|
411
|
+
// stays invisible to the per-request spread until the next gateway restart.
|
|
412
|
+
await refreshProviderCredentialChain(registry, store, providerId);
|
|
340
413
|
return { credential, deduped: false, ...(headPreserved ? { headPreserved } : {}) };
|
|
341
414
|
}
|
|
342
415
|
/**
|
|
@@ -449,6 +522,10 @@ async function buildQuotaPairRows(registry, traceTracker) {
|
|
|
449
522
|
overview = [];
|
|
450
523
|
}
|
|
451
524
|
for (const o of overview) {
|
|
525
|
+
if (providerUsesCliLogin(o.providerId)) {
|
|
526
|
+
add(o.providerId, CLI_LOGIN_QUOTA_PREFIX, undefined, undefined);
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
452
529
|
let metas = [];
|
|
453
530
|
try {
|
|
454
531
|
metas = store.listCredentials(o.providerId);
|
|
@@ -470,6 +547,10 @@ async function buildQuotaPairRows(registry, traceTracker) {
|
|
|
470
547
|
// when a provider registered no chain (the chain-less degeneracy). Union
|
|
471
548
|
// with (1) — `add` dedupes by pair id, so a store row keeps its identity.
|
|
472
549
|
for (const m of registry.getAllModels()) {
|
|
550
|
+
if (providerUsesCliLogin(m.provider)) {
|
|
551
|
+
add(m.provider, CLI_LOGIN_QUOTA_PREFIX, undefined, undefined);
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
473
554
|
const chain = registry.getCredentialChain(m.provider) ?? [];
|
|
474
555
|
for (const c of chain)
|
|
475
556
|
add(m.provider, c.keyHashPrefix, c.label, maskSecret(c.key));
|
|
@@ -491,6 +572,7 @@ async function buildQuotaPairRows(registry, traceTracker) {
|
|
|
491
572
|
outputTokens: row.outputTokens,
|
|
492
573
|
cachedTokens: row.cachedTokens,
|
|
493
574
|
costUsd: row.costUsd,
|
|
575
|
+
unpricedRequests: row.unpricedRequests,
|
|
494
576
|
};
|
|
495
577
|
}
|
|
496
578
|
}
|
|
@@ -581,7 +663,7 @@ async function mapCredentialWriteFailure(err, providerId, credentialId) {
|
|
|
581
663
|
* Raw keys never enter the view (CredentialMeta is masked by interface
|
|
582
664
|
* contract; Decision 1 risk limb).
|
|
583
665
|
*/
|
|
584
|
-
async function storeProviderViews(store) {
|
|
666
|
+
async function storeProviderViews(store, lang) {
|
|
585
667
|
const { listConfigProviders } = await import('../opencode/user-config.js');
|
|
586
668
|
const views = listConfigProviders();
|
|
587
669
|
// Per-provider auto-pull whitelist rides the view (edit dialog prefills from it).
|
|
@@ -623,6 +705,29 @@ async function storeProviderViews(store) {
|
|
|
623
705
|
});
|
|
624
706
|
}
|
|
625
707
|
}
|
|
708
|
+
// Plugin-preset overlay: the def's stored name is a single localeless string,
|
|
709
|
+
// so the localized display name (+logo) comes from the owning plugin manifest.
|
|
710
|
+
{
|
|
711
|
+
const { pluginPresetCatalogEntries } = await import('../plugins/host.js');
|
|
712
|
+
for (const preset of await pluginPresetCatalogEntries(lang)) {
|
|
713
|
+
const v = byId.get(preset.id);
|
|
714
|
+
if (v) {
|
|
715
|
+
// localize only the name the preset itself registered — an operator
|
|
716
|
+
// rename (providers.json is operator-owned, ADR-0010) stays untouched
|
|
717
|
+
if (!v.name || v.name === preset.defaultName || v.name === preset.name)
|
|
718
|
+
v.name = preset.name;
|
|
719
|
+
if (preset.logo && !v.logo)
|
|
720
|
+
v.logo = preset.logo;
|
|
721
|
+
v.authTypes = preset.authTypes;
|
|
722
|
+
v.keyHint = preset.keyHint;
|
|
723
|
+
// Credential-less preset: the def is the connection. Drop any stored
|
|
724
|
+
// key from the card summary so the console does not offer another one.
|
|
725
|
+
if (Array.isArray(preset.authTypes) && preset.authTypes.includes('none') && !preset.authTypes.some((t) => t === 'key' || t === 'webLogin')) {
|
|
726
|
+
v.auth = { connected: true };
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
626
731
|
return [...byId.values()].sort((a, b) => {
|
|
627
732
|
// DETERMINISTIC grid order. `store.credentialsOverview()` yields credential-table
|
|
628
733
|
// order (`active DESC, time_updated DESC`), so appending store-only providers
|
|
@@ -684,6 +789,21 @@ async function purgeProviderCredentials(store, id) {
|
|
|
684
789
|
store.invalidate();
|
|
685
790
|
return { attempted: metas.length, removed, failed };
|
|
686
791
|
}
|
|
792
|
+
/**
|
|
793
|
+
* Provider takedown lifecycle terminus: once NOTHING remains for the id (no
|
|
794
|
+
* defs node, no credential), drop the ledger row — a later connect reuses the
|
|
795
|
+
* id enabled. A partial state (either side still present) keeps the takedown.
|
|
796
|
+
*/
|
|
797
|
+
function dropTakedownWhenProviderGone(providerId, store) {
|
|
798
|
+
try {
|
|
799
|
+
if (!getProviderNodeById(providerId) && store.listCredentials(providerId).length === 0) {
|
|
800
|
+
getProviderTakedownStore().enable(providerId);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
catch {
|
|
804
|
+
// unreadable store: keep the takedown (safer than a silent re-enable)
|
|
805
|
+
}
|
|
806
|
+
}
|
|
687
807
|
/**
|
|
688
808
|
* P1-3 outcome flip: whenever the purge ATTEMPTED credentials but did not
|
|
689
809
|
* remove them all, the response must NOT claim success. HTTP stays 200 (the
|
|
@@ -752,6 +872,34 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
752
872
|
}
|
|
753
873
|
return reply.status(404).send('Not Found');
|
|
754
874
|
});
|
|
875
|
+
// 1b. Public assets copied verbatim from frontend/public (Vite emits them at
|
|
876
|
+
// the dist root). The hashed `assets/` handler above covers bundles only —
|
|
877
|
+
// without this route the SPA wildcard below answers `/admin/provider-logos/*`
|
|
878
|
+
// with index.html, so every bundled logo silently fell back to the remote
|
|
879
|
+
// catalog (or a monogram) in production/desktop builds. Names are stable (not
|
|
880
|
+
// content-hashed), so the response revalidates instead of caching immutably.
|
|
881
|
+
const PUBLIC_MIME = {
|
|
882
|
+
'.svg': 'image/svg+xml',
|
|
883
|
+
'.png': 'image/png',
|
|
884
|
+
'.ico': 'image/x-icon',
|
|
885
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
886
|
+
'.webmanifest': 'application/manifest+json',
|
|
887
|
+
};
|
|
888
|
+
app.get('/admin/provider-logos/:file', async (req, reply) => {
|
|
889
|
+
const file = req.params.file;
|
|
890
|
+
if (!file || file.includes('/') || file.includes('\\') || file.includes('..') || file.includes('\0')) {
|
|
891
|
+
return reply.status(400).send('Bad Request');
|
|
892
|
+
}
|
|
893
|
+
const dir = path.join(FRONTEND_DIST, 'provider-logos');
|
|
894
|
+
const filePath = path.join(dir, file);
|
|
895
|
+
if (!path.resolve(filePath).startsWith(path.resolve(dir) + path.sep)) {
|
|
896
|
+
return reply.status(400).send('Bad Request');
|
|
897
|
+
}
|
|
898
|
+
const mime = PUBLIC_MIME[path.extname(file).toLowerCase()];
|
|
899
|
+
if (!mime || !fs.existsSync(filePath))
|
|
900
|
+
return reply.status(404).send('Not Found');
|
|
901
|
+
return reply.header('Cache-Control', 'no-cache').type(mime).send(fs.readFileSync(filePath));
|
|
902
|
+
});
|
|
755
903
|
// 2. React SPA HTML Handler
|
|
756
904
|
const handleHtml = async (_req, reply) => {
|
|
757
905
|
const indexHtmlPath = path.join(FRONTEND_DIST, 'index.html');
|
|
@@ -796,13 +944,18 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
796
944
|
...cbManager.getSummary(),
|
|
797
945
|
pairs: cbManager.getPairSummary(),
|
|
798
946
|
rules: cbManager.getRulesStatus(),
|
|
947
|
+
// Static read-only reference: the classifier's fixed error-class mapping
|
|
948
|
+
// (ADR-0004 §1), single-sourced from CLASSIFIER_TAXONOMY. The console's
|
|
949
|
+
// breaker-rules page renders it to explain what each rule's `auto` scope
|
|
950
|
+
// resolves to and why e.g. 415 never trips while 403 counts. Additive:
|
|
951
|
+
// older gateways omit it and the panel stays hidden.
|
|
952
|
+
classifier: CLASSIFIER_TAXONOMY,
|
|
799
953
|
};
|
|
800
954
|
const metrics = orchestrator.getTracker().getStats();
|
|
801
|
-
const clients = await getAllClientStatuses();
|
|
802
955
|
const config = loadConfig();
|
|
803
956
|
// Runtime credential directory (hash prefixes ONLY — the same display-safe
|
|
804
957
|
// form pair snapshots already carry): lets the guardrails view name an
|
|
805
|
-
// orphan breaker's owner (e.g. the inline config-baked
|
|
958
|
+
// orphan breaker's owner (e.g. the inline config-baked default credential, which
|
|
806
959
|
// lives outside the store roster) instead of a bare #hash. Union of the
|
|
807
960
|
// bound store (the connected roster — independent of model registration)
|
|
808
961
|
// and the registry chains, so a connected-but-model-less provider is named
|
|
@@ -847,21 +1000,715 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
847
1000
|
},
|
|
848
1001
|
// Actual listening port (config.yaml `port` is the single source of truth)
|
|
849
1002
|
// so the console header shows the real gateway port instead of a literal.
|
|
850
|
-
port: config.port,
|
|
851
1003
|
metrics,
|
|
1004
|
+
port: config.port,
|
|
852
1005
|
circuitBreakers: cbSummary,
|
|
853
|
-
clients,
|
|
854
1006
|
credentialHashes,
|
|
855
1007
|
registeredModelsCount: registry.getAllModels().length,
|
|
856
1008
|
// Inbound forward-proxy runtime status (see forward-proxy/status.ts) —
|
|
857
1009
|
// the Proxy Access page polls this to show running / failed / pending.
|
|
858
1010
|
forwardProxy: {
|
|
859
1011
|
enabled: Boolean(config.forwardProxy?.enabled),
|
|
1012
|
+
// ADR-0019: a disabled upstream verification is a standing risk, so the
|
|
1013
|
+
// console states it next to the runtime status instead of hiding it in
|
|
1014
|
+
// a YAML comment.
|
|
1015
|
+
upstreamInsecure: config.forwardProxy?.upstreamTls?.insecure === true,
|
|
860
1016
|
...getForwardProxyStatus(),
|
|
861
1017
|
},
|
|
862
1018
|
};
|
|
863
1019
|
};
|
|
864
1020
|
app.get('/api/admin/status', handleStatus);
|
|
1021
|
+
// 3'. Client roster — split from /api/admin/status so the console's 3s
|
|
1022
|
+
// status poll never runs the roster's subprocess version probes (kimi /
|
|
1023
|
+
// openclaw `--version`, worst-case 5s timeout each). Only the Clients page
|
|
1024
|
+
// and the Overview card fetch this, on demand.
|
|
1025
|
+
// `?refresh=1` bypasses the roster SWR cache — the Clients page's manual
|
|
1026
|
+
// "Refresh Status" button must never serve a stale snapshot.
|
|
1027
|
+
app.get('/api/admin/clients', async (req) => {
|
|
1028
|
+
const refresh = req.query.refresh === '1';
|
|
1029
|
+
return {
|
|
1030
|
+
status: 'ok',
|
|
1031
|
+
clients: await getAllClientStatuses({ refresh }),
|
|
1032
|
+
};
|
|
1033
|
+
});
|
|
1034
|
+
// 3A1'. Release update check — display-only and cached in-process. The
|
|
1035
|
+
// first console read starts the GitHub call in the background and answers
|
|
1036
|
+
// `checking: true`; the console polls until the snapshot settles. A stale
|
|
1037
|
+
// entry (success or failure TTL) triggers the next background refresh here,
|
|
1038
|
+
// so every console load is an opportunity to learn about a new release
|
|
1039
|
+
// without any request ever waiting on api.github.com.
|
|
1040
|
+
app.get('/api/admin/update-check', async () => ({ status: 'ok', ...getUpdateChecker().status() }));
|
|
1041
|
+
const mintBodyToken = (t) => Buffer.from(JSON.stringify(t), 'utf8').toString('base64url');
|
|
1042
|
+
const bodyTokenOf = (ref, decoder) => typeof ref === 'string' && ref !== ''
|
|
1043
|
+
? mintBodyToken(decoder ? { k: 'g', r: ref, d: decoder } : { k: 'p', r: ref })
|
|
1044
|
+
: undefined;
|
|
1045
|
+
const resolveBodyPath = (token) => {
|
|
1046
|
+
let t;
|
|
1047
|
+
try {
|
|
1048
|
+
t = JSON.parse(Buffer.from(token, 'base64url').toString('utf8'));
|
|
1049
|
+
}
|
|
1050
|
+
catch {
|
|
1051
|
+
return null;
|
|
1052
|
+
}
|
|
1053
|
+
if (t?.k === 'p' && typeof t.r === 'string')
|
|
1054
|
+
return proxyAccessBodyPath(t.r);
|
|
1055
|
+
if (t?.k === 'g' && typeof t.r === 'string' && typeof t.d === 'string' && getGatewayById(t.d)) {
|
|
1056
|
+
return bodyPath(t.d, t.r);
|
|
1057
|
+
}
|
|
1058
|
+
return null;
|
|
1059
|
+
};
|
|
1060
|
+
// 3A2. THE ONE traffic-timeline endpoint — the console never addresses a
|
|
1061
|
+
// subsystem, it declares a SCOPE and the backend federates:
|
|
1062
|
+
// scope=live → memory ring (proxy access log) + every plugin gateway's
|
|
1063
|
+
// tail feed, interleaved by timestamp, newest first.
|
|
1064
|
+
// scope=history → the PERSISTED federated scan: proxy day JSONL
|
|
1065
|
+
// (`persistDays` retention) + each plugin feed's day
|
|
1066
|
+
// JSONL, merged, paged — one exact total across sources.
|
|
1067
|
+
// Both scopes share one row shape (a discriminated union on `source`), so
|
|
1068
|
+
// the console renders one table and one pager whatever the scope. Filters
|
|
1069
|
+
// (kind/method/status/host) bind history server-side; live filters stay in
|
|
1070
|
+
// the console (the ring is already fully resident there).
|
|
1071
|
+
/** Timestamp of a timeline row in ms — proxy rows carry epoch ms, plugin
|
|
1072
|
+
* rows an ISO string; 0 when unparsable (sorts to the oldest end). */
|
|
1073
|
+
const tsOf = (r) => 'ev' in r ? r.ev.ts ?? 0 : Date.parse(r.ex.ts ?? '') || 0;
|
|
1074
|
+
app.get('/api/admin/proxy-log', async (req) => {
|
|
1075
|
+
const q = req.query;
|
|
1076
|
+
if (q.scope === 'history') {
|
|
1077
|
+
const limit = Math.min(Math.max(Number(q.limit) || 50, 1), 500);
|
|
1078
|
+
const pageNo = Math.max(Number(q.page) || 1, 1);
|
|
1079
|
+
const kindF = q.kind ?? '';
|
|
1080
|
+
const methodF = q.method ?? '';
|
|
1081
|
+
const statusF = q.status ?? '';
|
|
1082
|
+
const hostF = (q.host ?? '').toLowerCase();
|
|
1083
|
+
const rows = [];
|
|
1084
|
+
for (const ev of readProxyAccessHistory({
|
|
1085
|
+
kind: kindF || undefined,
|
|
1086
|
+
method: methodF || undefined,
|
|
1087
|
+
status: statusF || undefined,
|
|
1088
|
+
host: hostF || undefined,
|
|
1089
|
+
})) {
|
|
1090
|
+
rows.push({ source: 'proxy', tsMs: ev.ts, ev });
|
|
1091
|
+
}
|
|
1092
|
+
for (const { id } of trafficDecoders()) {
|
|
1093
|
+
const dir = path.join(trafficRoot(), id);
|
|
1094
|
+
let files = [];
|
|
1095
|
+
try {
|
|
1096
|
+
files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().reverse();
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
continue; // fresh plugin / unreadable feed dir — no history from it
|
|
1100
|
+
}
|
|
1101
|
+
for (const f of files) {
|
|
1102
|
+
let lines = [];
|
|
1103
|
+
try {
|
|
1104
|
+
lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n');
|
|
1105
|
+
}
|
|
1106
|
+
catch {
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
for (const line of lines) {
|
|
1110
|
+
if (!line)
|
|
1111
|
+
continue;
|
|
1112
|
+
let ex;
|
|
1113
|
+
try {
|
|
1114
|
+
ex = JSON.parse(line);
|
|
1115
|
+
}
|
|
1116
|
+
catch {
|
|
1117
|
+
continue; // torn final line (crash mid-append) skips one row
|
|
1118
|
+
}
|
|
1119
|
+
if (methodF && ex.method !== methodF)
|
|
1120
|
+
continue;
|
|
1121
|
+
if (hostF && (ex.authority ?? '').toLowerCase() !== hostF)
|
|
1122
|
+
continue;
|
|
1123
|
+
// Plugin rows are HTTP by definition (the console's `kindOf`):
|
|
1124
|
+
// a CONNECT/WS filter excludes them, and a status filter prunes
|
|
1125
|
+
// them — otherwise the federated total counts rows the delete
|
|
1126
|
+
// path (and the rendered table) never includes.
|
|
1127
|
+
if (kindF && kindF !== 'http')
|
|
1128
|
+
continue;
|
|
1129
|
+
if (statusF && String(ex.status ?? '') !== statusF)
|
|
1130
|
+
continue;
|
|
1131
|
+
rows.push({ source: id, tsMs: Date.parse(ex.ts ?? '') || 0, ex });
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
rows.sort((a, b) => b.tsMs - a.tsMs);
|
|
1136
|
+
const total = rows.length;
|
|
1137
|
+
const pages = Math.max(Math.ceil(total / limit), 1);
|
|
1138
|
+
const slice = rows.slice((pageNo - 1) * limit, (pageNo - 1) * limit + limit);
|
|
1139
|
+
// Read-time decode is PAGE-scoped: dissect + hex previews only for the
|
|
1140
|
+
// rows actually returned, never for the whole scan.
|
|
1141
|
+
return {
|
|
1142
|
+
status: 'ok',
|
|
1143
|
+
rows: slice.map((r) => 'ev' in r
|
|
1144
|
+
? {
|
|
1145
|
+
source: 'proxy',
|
|
1146
|
+
ev: { ...r.ev, reqBodyToken: bodyTokenOf(r.ev.reqBodyFile), resBodyToken: bodyTokenOf(r.ev.resBodyFile) },
|
|
1147
|
+
}
|
|
1148
|
+
: { source: r.source, ex: decoratePluginRow(r.source, r.ex) }),
|
|
1149
|
+
total,
|
|
1150
|
+
page: pageNo,
|
|
1151
|
+
pages,
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1154
|
+
// scope=live (default) — the merged tail: ring + every plugin feed tail.
|
|
1155
|
+
const s = proxyAccessLogSettings();
|
|
1156
|
+
const rows = [];
|
|
1157
|
+
const hiddenProxy = liveHiddenProxyIds();
|
|
1158
|
+
for (const e of listProxyAccessEvents()) {
|
|
1159
|
+
if (hiddenProxy.has(e.id))
|
|
1160
|
+
continue;
|
|
1161
|
+
rows.push({ source: 'proxy', ev: { ...e, reqBodyToken: bodyTokenOf(e.reqBodyFile), resBodyToken: bodyTokenOf(e.resBodyFile) } });
|
|
1162
|
+
}
|
|
1163
|
+
for (const { id } of trafficDecoders()) {
|
|
1164
|
+
const gw = getGatewayById(id);
|
|
1165
|
+
if (!gw || typeof gw.dissect !== 'function')
|
|
1166
|
+
continue;
|
|
1167
|
+
const dir = path.join(trafficRoot(), id);
|
|
1168
|
+
const events = [];
|
|
1169
|
+
try {
|
|
1170
|
+
if (fs.existsSync(dir)) {
|
|
1171
|
+
const files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().reverse();
|
|
1172
|
+
for (const f of files) {
|
|
1173
|
+
if (events.length >= TRAFFIC_TAIL)
|
|
1174
|
+
break;
|
|
1175
|
+
const lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n').filter(Boolean);
|
|
1176
|
+
for (let i = lines.length - 1; i >= 0 && events.length < TRAFFIC_TAIL; i--) {
|
|
1177
|
+
try {
|
|
1178
|
+
events.push(JSON.parse(lines[i]));
|
|
1179
|
+
}
|
|
1180
|
+
catch {
|
|
1181
|
+
continue; // a torn final line (crash mid-append) skips one row
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
catch {
|
|
1188
|
+
// Unreadable feed dir = empty feed.
|
|
1189
|
+
}
|
|
1190
|
+
const hiddenPlugin = liveHiddenPluginKeys(id);
|
|
1191
|
+
for (const ex of events) {
|
|
1192
|
+
const key = typeof ex.id === 'string' ? ex.id : ex.ts;
|
|
1193
|
+
if (key && hiddenPlugin.has(key))
|
|
1194
|
+
continue;
|
|
1195
|
+
rows.push({ source: id, ex: decoratePluginRow(id, ex) });
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
rows.sort((a, b) => (tsOf(a) || 0) - (tsOf(b) || 0));
|
|
1199
|
+
return {
|
|
1200
|
+
status: 'ok',
|
|
1201
|
+
enabled: s.enabled,
|
|
1202
|
+
bodyBytes: s.bodyBytes,
|
|
1203
|
+
rows: rows.reverse(),
|
|
1204
|
+
total: rows.length,
|
|
1205
|
+
};
|
|
1206
|
+
});
|
|
1207
|
+
app.post('/api/admin/proxy-log/clear', async () => {
|
|
1208
|
+
clearProxyAccessLog();
|
|
1209
|
+
return { status: 'ok' };
|
|
1210
|
+
});
|
|
1211
|
+
// 3A2c. HISTORY delete by FILTER — the history-mode counterpart of the
|
|
1212
|
+
// clear button. History is the PERSISTED scope, so this rewrite touches the
|
|
1213
|
+
// day JSONL + body sidecars only and leaves the live ring alone (ADR-0017
|
|
1214
|
+
// §5: the same row may still be listed in the live view until it ages out).
|
|
1215
|
+
// The console only holds ONE page of the persisted federation at a time, so
|
|
1216
|
+
// "what I see" and "what I asked to delete" would diverge; the console sends
|
|
1217
|
+
// the SAME filter vocabulary it queries with and the backend deletes every
|
|
1218
|
+
// matching persisted row across ALL sources. The response reports per-source
|
|
1219
|
+
// counts so the confirm toast is never a guess.
|
|
1220
|
+
app.post('/api/admin/proxy-log/history/delete', async (req) => {
|
|
1221
|
+
const b = (req.body ?? {});
|
|
1222
|
+
const kindF = b.kind ?? '';
|
|
1223
|
+
const methodF = b.method ?? '';
|
|
1224
|
+
const statusF = b.status ?? '';
|
|
1225
|
+
const hostF = (b.host ?? '').toLowerCase();
|
|
1226
|
+
// Proxy side: ids → the persisted-row deleter (day files + body sidecars).
|
|
1227
|
+
const ids = readProxyAccessHistory({
|
|
1228
|
+
kind: kindF || undefined,
|
|
1229
|
+
method: methodF || undefined,
|
|
1230
|
+
status: statusF || undefined,
|
|
1231
|
+
host: hostF || undefined,
|
|
1232
|
+
}).map((e) => e.id);
|
|
1233
|
+
const proxyDeleted = ids.length > 0 ? deletePersistedProxyEvents(ids) : 0;
|
|
1234
|
+
// Plugin side: rewrite each feed's day files without the matching lines.
|
|
1235
|
+
const deletedPlugins = {};
|
|
1236
|
+
for (const { id } of trafficDecoders()) {
|
|
1237
|
+
// Plugin rows are ALWAYS `http` (the console's `kindOf`): a CONNECT/WS
|
|
1238
|
+
// filter cannot match them, but the default `http` filter must — the
|
|
1239
|
+
// history table renders those rows, so refusing every kind filter left
|
|
1240
|
+
// them behind after a clear (the "clear is not clean" bug).
|
|
1241
|
+
if (kindF && kindF !== 'http')
|
|
1242
|
+
continue;
|
|
1243
|
+
const dir = path.join(trafficRoot(), id);
|
|
1244
|
+
let files = [];
|
|
1245
|
+
try {
|
|
1246
|
+
files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f));
|
|
1247
|
+
}
|
|
1248
|
+
catch {
|
|
1249
|
+
continue;
|
|
1250
|
+
}
|
|
1251
|
+
let removed = 0;
|
|
1252
|
+
const bodyIds = new Set();
|
|
1253
|
+
for (const f of files) {
|
|
1254
|
+
const abs = path.join(dir, f);
|
|
1255
|
+
let kept = [];
|
|
1256
|
+
try {
|
|
1257
|
+
kept = fs.readFileSync(abs, 'utf8').split('\n').filter(Boolean);
|
|
1258
|
+
}
|
|
1259
|
+
catch {
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
let touched = false;
|
|
1263
|
+
const keptOut = [];
|
|
1264
|
+
for (const line of kept) {
|
|
1265
|
+
let ex;
|
|
1266
|
+
try {
|
|
1267
|
+
ex = JSON.parse(line);
|
|
1268
|
+
}
|
|
1269
|
+
catch {
|
|
1270
|
+
keptOut.push(line); // a torn line survives deletion round-trips
|
|
1271
|
+
continue;
|
|
1272
|
+
}
|
|
1273
|
+
const hit = (!methodF || ex.method === methodF) &&
|
|
1274
|
+
(!hostF || (ex.authority ?? '').toLowerCase() === hostF) &&
|
|
1275
|
+
(!statusF || String(ex.status ?? '') === statusF);
|
|
1276
|
+
if (hit) {
|
|
1277
|
+
touched = true;
|
|
1278
|
+
removed++;
|
|
1279
|
+
if (typeof ex.id === 'string')
|
|
1280
|
+
bodyIds.add(ex.id);
|
|
1281
|
+
continue;
|
|
1282
|
+
}
|
|
1283
|
+
keptOut.push(line);
|
|
1284
|
+
}
|
|
1285
|
+
if (!touched)
|
|
1286
|
+
continue;
|
|
1287
|
+
try {
|
|
1288
|
+
if (keptOut.length === 0)
|
|
1289
|
+
fs.unlinkSync(abs);
|
|
1290
|
+
else
|
|
1291
|
+
fs.writeFileSync(abs, keptOut.join('\n') + '\n');
|
|
1292
|
+
}
|
|
1293
|
+
catch {
|
|
1294
|
+
// Best effort — the row is gone from the feed view either way.
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
// Sidecar bytes are named `<day>/<id>-<side>.bin`: drop only the ones
|
|
1298
|
+
// whose row just went away, never a neighbour's.
|
|
1299
|
+
if (bodyIds.size > 0) {
|
|
1300
|
+
const bodiesRoot = path.join(dir, 'bodies');
|
|
1301
|
+
if (fs.existsSync(bodiesRoot)) {
|
|
1302
|
+
for (const day of fs.readdirSync(bodiesRoot)) {
|
|
1303
|
+
const dayDir = path.join(bodiesRoot, day);
|
|
1304
|
+
let names = [];
|
|
1305
|
+
try {
|
|
1306
|
+
names = fs.readdirSync(dayDir);
|
|
1307
|
+
}
|
|
1308
|
+
catch {
|
|
1309
|
+
continue;
|
|
1310
|
+
}
|
|
1311
|
+
for (const name of names) {
|
|
1312
|
+
const owner = name.replace(/-(?:req|res)\.bin$/, '');
|
|
1313
|
+
if (!bodyIds.has(owner))
|
|
1314
|
+
continue;
|
|
1315
|
+
try {
|
|
1316
|
+
fs.unlinkSync(path.join(dayDir, name));
|
|
1317
|
+
}
|
|
1318
|
+
catch {
|
|
1319
|
+
// Locked file (Windows) — the row is gone, the blob is orphaned.
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
if (removed > 0)
|
|
1326
|
+
deletedPlugins[id] = removed;
|
|
1327
|
+
}
|
|
1328
|
+
return { status: 'ok', deleted: { proxy: proxyDeleted, plugins: deletedPlugins } };
|
|
1329
|
+
});
|
|
1330
|
+
// 3A1b. Explicit FULL wipe across BOTH scopes — ring, proxy day files +
|
|
1331
|
+
// bodies, and every plugin feed dir. This is an admin API, not either
|
|
1332
|
+
// console button: live clear hides only, history delete rewrites only
|
|
1333
|
+
// (ADR-0017 §5). Gateway feeds are console-owned artifacts on disk, so they
|
|
1334
|
+
// are removed here rather than through the plugin.
|
|
1335
|
+
app.post('/api/admin/traffic-clear', async () => {
|
|
1336
|
+
clearProxyAccessLog();
|
|
1337
|
+
const cleared = [];
|
|
1338
|
+
for (const [id, gw] of listGateways()) {
|
|
1339
|
+
if (typeof gw.dissect !== 'function')
|
|
1340
|
+
continue;
|
|
1341
|
+
const dir = path.join(trafficRoot(), id);
|
|
1342
|
+
try {
|
|
1343
|
+
if (fs.existsSync(dir))
|
|
1344
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
1345
|
+
cleared.push(id);
|
|
1346
|
+
}
|
|
1347
|
+
catch {
|
|
1348
|
+
// A locked feed (Windows handle) must not fail the whole clear.
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
return { status: 'ok', cleared };
|
|
1352
|
+
});
|
|
1353
|
+
/**
|
|
1354
|
+
* 3A1c. Hide EXACTLY the rows the LIVE view is showing — the live-scope
|
|
1355
|
+
* counterpart of the history delete. Live and history are scopes over the
|
|
1356
|
+
* same feeds, not separate stores (ADR-0017 §5), so this route never touches
|
|
1357
|
+
* a file: proxy rows leave the ring, and plugin rows are recorded in a
|
|
1358
|
+
* live-only tombstone overlay that the live read applies and history
|
|
1359
|
+
* ignores. The persisted day JSONL and body sidecars stay intact and remain
|
|
1360
|
+
* listed/deletable from History mode.
|
|
1361
|
+
*
|
|
1362
|
+
* The console sends row keys (`id`, else the legacy feed `ts`) with their
|
|
1363
|
+
* timestamps, never a predicate: the filter lives in one place (the page)
|
|
1364
|
+
* and a backend copy would drift into hiding more than the operator sees.
|
|
1365
|
+
*/
|
|
1366
|
+
app.post('/api/admin/traffic-live-clear', async (req) => {
|
|
1367
|
+
const body = (req.body ?? {});
|
|
1368
|
+
const asLiveKeys = (v) => {
|
|
1369
|
+
if (!Array.isArray(v))
|
|
1370
|
+
return [];
|
|
1371
|
+
const out = [];
|
|
1372
|
+
for (const x of v) {
|
|
1373
|
+
if (!x || typeof x !== 'object' || !('key' in x) || !('ts' in x))
|
|
1374
|
+
continue;
|
|
1375
|
+
if (typeof x.key === 'string' && x.key.length > 0 && typeof x.ts === 'number' && Number.isFinite(x.ts)) {
|
|
1376
|
+
out.push({ key: x.key, ts: x.ts });
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
return out;
|
|
1380
|
+
};
|
|
1381
|
+
// Only ids the ring actually holds are part of the live view right now;
|
|
1382
|
+
// the tombstones cover the plugin tail rows (history ignores them).
|
|
1383
|
+
const ringIds = new Set(listProxyAccessEvents().map((e) => e.id));
|
|
1384
|
+
const liveProxy = asLiveKeys(body.proxy).filter((k) => ringIds.has(k.key));
|
|
1385
|
+
const plugins = {};
|
|
1386
|
+
if (body.plugins && typeof body.plugins === 'object' && !Array.isArray(body.plugins)) {
|
|
1387
|
+
for (const [decoderId, raw] of Object.entries(body.plugins)) {
|
|
1388
|
+
plugins[decoderId] = asLiveKeys(raw);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
forgetProxyAccessRingEvents(liveProxy.map((k) => k.key));
|
|
1392
|
+
const hidden = hideLiveEvents(liveProxy, plugins);
|
|
1393
|
+
return { status: 'ok', hidden };
|
|
1394
|
+
});
|
|
1395
|
+
// 3A2b. Generic plugin-traffic feed (Wireshark dissector model, ADR-0017
|
|
1396
|
+
// client gateways): each gateway that declares `dissect` owns a protocol
|
|
1397
|
+
// decoder AND a raw day-JSONL feed under
|
|
1398
|
+
// <ocrHome>/plugins/traffic/<pluginId>/. The console tab lists the decoder
|
|
1399
|
+
// registry and reads a feed, applying the plugin's dissector at READ time.
|
|
1400
|
+
// The plugin stays self-contained — the route only owns the feed layout and
|
|
1401
|
+
// tail discipline (newest first, capped).
|
|
1402
|
+
// Resolved per call, never captured at registration: OCR_HOME is the
|
|
1403
|
+
// environment-book-set switch (ADR-0007) and may change under a live server.
|
|
1404
|
+
const trafficRoot = () => path.join(getOcrHomeDir(), 'plugins', 'traffic');
|
|
1405
|
+
const TRAFFIC_TAIL = 500;
|
|
1406
|
+
/** Per-side DISPLAY window handed to the dissector. Capture is full fidelity
|
|
1407
|
+
* on disk; only this read is bounded, per row on every poll — the drawer's
|
|
1408
|
+
* own render cap is DEFAULT_TRAFFIC_BODY_PREVIEW_BYTES. */
|
|
1409
|
+
const TRAFFIC_DISSECT_WINDOW = DEFAULT_TRAFFIC_DISSECT_WINDOW_BYTES;
|
|
1410
|
+
/** Inline hex preview length — first paint only. The drawer replaces it with
|
|
1411
|
+
* the token-addressed body, so keeping it small keeps every poll cheap. */
|
|
1412
|
+
const TRAFFIC_HEX_PREVIEW = 1024;
|
|
1413
|
+
/** Strict sidecar ref: `<YYYYMMDD>/<id>-<side>.bin`, no traversal. */
|
|
1414
|
+
const TRAFFIC_BODY_REF_RE = /^\d{8}\/[A-Za-z0-9._-]+\.bin$/;
|
|
1415
|
+
/** Resolve a feed body ref to an absolute path inside that decoder's dir. */
|
|
1416
|
+
const bodyPath = (decoderId, ref) => {
|
|
1417
|
+
if (!TRAFFIC_BODY_REF_RE.test(ref))
|
|
1418
|
+
return null;
|
|
1419
|
+
const root = path.join(trafficRoot(), decoderId, 'bodies');
|
|
1420
|
+
const abs = path.join(root, ref);
|
|
1421
|
+
return abs.startsWith(root + path.sep) ? abs : null;
|
|
1422
|
+
};
|
|
1423
|
+
const trafficDecoders = () => {
|
|
1424
|
+
const out = [];
|
|
1425
|
+
for (const [id, gw] of listGateways()) {
|
|
1426
|
+
if (typeof gw.dissect !== 'function')
|
|
1427
|
+
continue;
|
|
1428
|
+
out.push({ id, label: gw.hosts.join(', ') });
|
|
1429
|
+
}
|
|
1430
|
+
return out;
|
|
1431
|
+
};
|
|
1432
|
+
/** Read-time wire decoration for ONE plugin feed row: body windows for the
|
|
1433
|
+
* dissector + hex preview, dissect layers, body tokens, bodies stripped.
|
|
1434
|
+
* Shared by the live tail route and the federated history scan — one
|
|
1435
|
+
* decoration path, never two. */
|
|
1436
|
+
const decoratePluginRow = (decoderId, ex) => {
|
|
1437
|
+
const windowOf = (ref) => {
|
|
1438
|
+
if (typeof ref !== 'string')
|
|
1439
|
+
return undefined;
|
|
1440
|
+
const abs = bodyPath(decoderId, ref);
|
|
1441
|
+
if (!abs)
|
|
1442
|
+
return undefined;
|
|
1443
|
+
try {
|
|
1444
|
+
const fd = fs.openSync(abs, 'r');
|
|
1445
|
+
try {
|
|
1446
|
+
// Allocate the bytes the file actually has, not the window: a
|
|
1447
|
+
// 500-row tail decorates ~1000 sides per poll, and a full-window
|
|
1448
|
+
// buffer per side is the dominant cost (window × rows), while most
|
|
1449
|
+
// bodies are kilobytes.
|
|
1450
|
+
const take = Math.min(fs.fstatSync(fd).size, TRAFFIC_DISSECT_WINDOW);
|
|
1451
|
+
const buf = Buffer.allocUnsafe(take);
|
|
1452
|
+
const read = fs.readSync(fd, buf, 0, take, 0);
|
|
1453
|
+
return buf.subarray(0, read);
|
|
1454
|
+
}
|
|
1455
|
+
finally {
|
|
1456
|
+
fs.closeSync(fd);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
catch {
|
|
1460
|
+
return undefined;
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
const reqWin = windowOf(ex.reqBodyFile);
|
|
1464
|
+
const resWin = windowOf(ex.resBodyFile);
|
|
1465
|
+
// Legacy rows (inline base64 body) still decode: the window is the
|
|
1466
|
+
// inline body itself, so both feed generations share one path.
|
|
1467
|
+
const reqBytes = reqWin ?? (typeof ex.reqBody === 'string' ? Buffer.from(ex.reqBody, 'base64') : undefined);
|
|
1468
|
+
const resBytes = resWin ?? (typeof ex.resBody === 'string' ? Buffer.from(ex.resBody, 'base64') : undefined);
|
|
1469
|
+
let dissected;
|
|
1470
|
+
try {
|
|
1471
|
+
dissected = getGatewayById(decoderId)?.dissect?.({ ...ex, reqBody: reqBytes?.toString('base64'), resBody: resBytes?.toString('base64') });
|
|
1472
|
+
}
|
|
1473
|
+
catch {
|
|
1474
|
+
dissected = undefined; // a decoder bug degrades to the raw view only
|
|
1475
|
+
}
|
|
1476
|
+
// Strip bodies from the wire view: the console gets byte counts,
|
|
1477
|
+
// file refs and a small hex preview, never the payload itself.
|
|
1478
|
+
const { reqBody: _rq, resBody: _rs, ...meta } = ex;
|
|
1479
|
+
void _rq;
|
|
1480
|
+
void _rs;
|
|
1481
|
+
const hexPreview = (b) => {
|
|
1482
|
+
if (!b || b.length === 0)
|
|
1483
|
+
return undefined;
|
|
1484
|
+
return b.subarray(0, TRAFFIC_HEX_PREVIEW).toString('hex');
|
|
1485
|
+
};
|
|
1486
|
+
return {
|
|
1487
|
+
...meta,
|
|
1488
|
+
reqBodyToken: bodyTokenOf(ex.reqBodyFile, decoderId),
|
|
1489
|
+
resBodyToken: bodyTokenOf(ex.resBodyFile, decoderId),
|
|
1490
|
+
reqHex: hexPreview(reqBytes),
|
|
1491
|
+
resHex: hexPreview(resBytes),
|
|
1492
|
+
decoded: dissected,
|
|
1493
|
+
};
|
|
1494
|
+
};
|
|
1495
|
+
app.get('/api/admin/plugin-traffic', async () => {
|
|
1496
|
+
return { status: 'ok', decoders: trafficDecoders() };
|
|
1497
|
+
});
|
|
1498
|
+
app.get('/api/admin/plugin-traffic/:decoder', async (req, reply) => {
|
|
1499
|
+
const decoderId = String(req.params.decoder ?? '');
|
|
1500
|
+
const gw = getGatewayById(decoderId);
|
|
1501
|
+
if (!gw || typeof gw.dissect !== 'function') {
|
|
1502
|
+
reply.code(404);
|
|
1503
|
+
return { status: 'error', message: `no traffic decoder registered for '${decoderId}'` };
|
|
1504
|
+
}
|
|
1505
|
+
const dir = path.join(trafficRoot(), decoderId);
|
|
1506
|
+
const events = [];
|
|
1507
|
+
let days = 0;
|
|
1508
|
+
try {
|
|
1509
|
+
if (fs.existsSync(dir)) {
|
|
1510
|
+
const files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().reverse();
|
|
1511
|
+
for (const f of files) {
|
|
1512
|
+
if (events.length >= TRAFFIC_TAIL)
|
|
1513
|
+
break;
|
|
1514
|
+
days++;
|
|
1515
|
+
const lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n').filter(Boolean);
|
|
1516
|
+
for (let i = lines.length - 1; i >= 0 && events.length < TRAFFIC_TAIL; i--) {
|
|
1517
|
+
let raw;
|
|
1518
|
+
try {
|
|
1519
|
+
raw = JSON.parse(lines[i]);
|
|
1520
|
+
}
|
|
1521
|
+
catch {
|
|
1522
|
+
continue; // a torn final line (crash mid-append) skips one row
|
|
1523
|
+
}
|
|
1524
|
+
const ex = raw;
|
|
1525
|
+
events.push(decoratePluginRow(decoderId, ex));
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
catch {
|
|
1531
|
+
// Unreadable feed dir (fresh plugin, permissions) = empty feed.
|
|
1532
|
+
}
|
|
1533
|
+
return { status: 'ok', days, truncated: events.length >= TRAFFIC_TAIL, events };
|
|
1534
|
+
});
|
|
1535
|
+
// Raw persisted binary body (ref format `<day>/pa-...-<side>.bin`, validated
|
|
1536
|
+
// inside readProxyAccessBodyFile — no traversal).
|
|
1537
|
+
// 3A2c. THE body download — one neutral endpoint for every captured body,
|
|
1538
|
+
// whatever stored it. The console never learns which subsystem owns the
|
|
1539
|
+
// bytes (or which plugin captured them): the row carries an opaque token and
|
|
1540
|
+
// only this route resolves it. Validation happens AFTER decoding the token,
|
|
1541
|
+
// so a hand-crafted token is no stronger than the refs the feeds already
|
|
1542
|
+
// expose (strict grammar + containment inside the resolved root).
|
|
1543
|
+
app.get('/api/admin/traffic-body/:token', async (req, reply) => {
|
|
1544
|
+
const token = String(req.params.token ?? '');
|
|
1545
|
+
const abs = resolveBodyPath(token);
|
|
1546
|
+
if (!abs || !fs.existsSync(abs)) {
|
|
1547
|
+
reply.code(404);
|
|
1548
|
+
return { status: 'error', message: 'body not found' };
|
|
1549
|
+
}
|
|
1550
|
+
reply.header('content-type', 'application/octet-stream');
|
|
1551
|
+
reply.header('content-disposition', `attachment; filename="${path.basename(abs)}"`);
|
|
1552
|
+
return reply.send(fs.createReadStream(abs));
|
|
1553
|
+
});
|
|
1554
|
+
// 3A3. OS system proxy ownership — ONE snapshot, TWO endpoints: the inbound
|
|
1555
|
+
// forward proxy (default) or the Clash core's mixed port. A target switch
|
|
1556
|
+
// rewrites the OS pointer without re-reading the pre-OCR snapshot; restore
|
|
1557
|
+
// always returns what the OS held before OCR first took ownership.
|
|
1558
|
+
const systemProxyPayload = async (req) => {
|
|
1559
|
+
const live = getRuntimeConfigRef();
|
|
1560
|
+
const fp = live?.forwardProxy;
|
|
1561
|
+
const port = fp?.port ?? DEFAULT_FORWARD_PROXY_PORT;
|
|
1562
|
+
const mixedPort = live?.proxy?.mihomo?.mixedPort ?? DEFAULT_MIHOMO_MIXED_PORT;
|
|
1563
|
+
const sys = await getSystemProxyStatus(port, osBypassHosts(fp?.rules));
|
|
1564
|
+
const clashBypass = lanBypassHosts(process.platform);
|
|
1565
|
+
const clashRunning = (await getMihomoStatus()).running;
|
|
1566
|
+
return {
|
|
1567
|
+
status: 'ok',
|
|
1568
|
+
...sys,
|
|
1569
|
+
proxyEnabled: Boolean(fp?.enabled),
|
|
1570
|
+
forward: { port, enabled: Boolean(fp?.enabled) },
|
|
1571
|
+
// The clash card names the bypass ITS target would write (LAN ranges),
|
|
1572
|
+
// not the inbound one on `override` (loopback + literal direct rows).
|
|
1573
|
+
clash: { mixedPort, running: clashRunning, override: buildOverride(clashBypass, process.platform) },
|
|
1574
|
+
// The PAC URL follows the origin THIS request reached, never the console
|
|
1575
|
+
// document's origin (a dev console on Vite would advertise a URL that
|
|
1576
|
+
// dies with its dev server).
|
|
1577
|
+
pacUrl: pacUrlFor(req.headers.host, req.protocol, live?.port),
|
|
1578
|
+
};
|
|
1579
|
+
};
|
|
1580
|
+
app.get('/api/admin/system-proxy', async (req) => systemProxyPayload(req));
|
|
1581
|
+
app.post('/api/admin/system-proxy/enable', async (req, reply) => {
|
|
1582
|
+
const body = (req.body ?? {});
|
|
1583
|
+
const live = getRuntimeConfigRef();
|
|
1584
|
+
if (body.target === 'clash') {
|
|
1585
|
+
// Pointing the OS at a dead port is one click away from a dead network:
|
|
1586
|
+
// the core must answer before it owns the OS proxy.
|
|
1587
|
+
if (!(await getMihomoStatus()).running) {
|
|
1588
|
+
reply.code(409);
|
|
1589
|
+
return { status: 'error', code: 'not-running' };
|
|
1590
|
+
}
|
|
1591
|
+
const mixedPort = live?.proxy?.mihomo?.mixedPort ?? DEFAULT_MIHOMO_MIXED_PORT;
|
|
1592
|
+
await enableSystemProxy(mixedPort, lanBypassHosts(process.platform), 'clash');
|
|
1593
|
+
return systemProxyPayload(req);
|
|
1594
|
+
}
|
|
1595
|
+
const fp = live?.forwardProxy;
|
|
1596
|
+
const port = fp?.port ?? DEFAULT_FORWARD_PROXY_PORT;
|
|
1597
|
+
await enableSystemProxy(port, osBypassHosts(fp?.rules), 'forward');
|
|
1598
|
+
return systemProxyPayload(req);
|
|
1599
|
+
});
|
|
1600
|
+
app.post('/api/admin/system-proxy/disable', async (req) => {
|
|
1601
|
+
const fp = getRuntimeConfigRef()?.forwardProxy;
|
|
1602
|
+
const port = fp?.port ?? DEFAULT_FORWARD_PROXY_PORT;
|
|
1603
|
+
await disableSystemProxy(port, osBypassHosts(fp?.rules));
|
|
1604
|
+
return systemProxyPayload(req);
|
|
1605
|
+
});
|
|
1606
|
+
// 3A4. Forward-proxy rule table (ADR-0018): lint + dry-run resolution. The
|
|
1607
|
+
// console renders the warning CODES through i18n and shows which rule a probe
|
|
1608
|
+
// host hits, so an ordered table is never a black box. `rules` in the body =
|
|
1609
|
+
// the UNSAVED table being edited; omitted = the live one. `intercept` in the
|
|
1610
|
+
// body = the UNSAVED posture toggle (same reason); omitted = the live one.
|
|
1611
|
+
app.post('/api/admin/forward-proxy/rules/resolve', async (req) => {
|
|
1612
|
+
const body = (req.body ?? {});
|
|
1613
|
+
const live = getRuntimeConfigRef();
|
|
1614
|
+
const rawRules = Array.isArray(body.rules) ? body.rules : live?.forwardProxy?.rules;
|
|
1615
|
+
const proxyEnabled = live?.proxy?.enabled === true;
|
|
1616
|
+
const rules = normalizeRules(rawRules);
|
|
1617
|
+
// ADR-0018 Revision 4: the posture and the claim set are part of the answer,
|
|
1618
|
+
// because they decide `tunnel` for every host no specific row names. The
|
|
1619
|
+
// preview reads the SAME registry the proxy legs do (`listGatewayHosts()`)
|
|
1620
|
+
// and takes an unsaved toggle from the body, so it can never disagree with
|
|
1621
|
+
// the live decision.
|
|
1622
|
+
const intercept = body.intercept === 'all' || body.intercept === 'claims'
|
|
1623
|
+
? body.intercept
|
|
1624
|
+
: live?.forwardProxy?.intercept ?? DEFAULT_FORWARD_PROXY_INTERCEPT;
|
|
1625
|
+
// A wildcard gateway claims EVERY host through `match()`, so a literal `'*'`
|
|
1626
|
+
// in this list would print as a host name. The set is exact claims only;
|
|
1627
|
+
// the wildcard's own attribution stays visible through `claimSources`.
|
|
1628
|
+
const claimed = [...listGatewayHosts()].filter((h) => h !== WILDCARD_HOST_CLAIM).sort();
|
|
1629
|
+
// Per-plugin attribution for the console's "decrypted without a rule" list:
|
|
1630
|
+
// the SAME live registry the proxy legs read, so the two can never disagree —
|
|
1631
|
+
// one is the host set, the other says who claimed it and what leg that claim
|
|
1632
|
+
// owns (ADR-0018 Revision 5). The preview asks `claimEgressFor` — the very callback
|
|
1633
|
+
// the relay injects into `resolveHost` — because the tier that answers can be
|
|
1634
|
+
// the plugin's code, and a preview of a snapshot would be a second opinion.
|
|
1635
|
+
const claimOutcomes = (hosts) => hosts.map((host) => {
|
|
1636
|
+
const d = resolveHost(host, rules, {
|
|
1637
|
+
claimed: new Set(claimed), claimEgress: claimEgressFor, intercept,
|
|
1638
|
+
});
|
|
1639
|
+
return {
|
|
1640
|
+
host,
|
|
1641
|
+
action: d.action,
|
|
1642
|
+
tunnel: d.tunnel,
|
|
1643
|
+
reason: d.reason,
|
|
1644
|
+
egressClaim: d.egressClaim,
|
|
1645
|
+
ruleIndex: d.ruleIndex,
|
|
1646
|
+
};
|
|
1647
|
+
});
|
|
1648
|
+
const claimSources = [...listGateways().entries()]
|
|
1649
|
+
.map(([pluginId, gw]) => {
|
|
1650
|
+
const hosts = [...new Set(gw.hosts.filter((h) => h !== WILDCARD_HOST_CLAIM))].sort();
|
|
1651
|
+
// The DISTINCT legs this plugin's claims ask for. One package normally
|
|
1652
|
+
// answers once — but a per-host hook may split, and a host two gateways
|
|
1653
|
+
// answer oppositely drops out entirely (no winner), which the dialog has
|
|
1654
|
+
// to be able to show rather than invent.
|
|
1655
|
+
const egress = [...new Set(hosts.map((h) => claimEgressFor(h)?.action))]
|
|
1656
|
+
.filter((e) => e !== undefined)
|
|
1657
|
+
.sort();
|
|
1658
|
+
return { pluginId, hosts, egress, outcomes: claimOutcomes(hosts) };
|
|
1659
|
+
})
|
|
1660
|
+
.filter((s) => s.hosts.length > 0)
|
|
1661
|
+
.sort((a, b) => a.pluginId.localeCompare(b.pluginId));
|
|
1662
|
+
const host = typeof body.host === 'string' ? body.host.trim() : '';
|
|
1663
|
+
return {
|
|
1664
|
+
status: 'ok',
|
|
1665
|
+
rules,
|
|
1666
|
+
warnings: lintRules(rawRules, proxyEnabled, intercept, listClaimedEgress()),
|
|
1667
|
+
proxyEnabled,
|
|
1668
|
+
intercept,
|
|
1669
|
+
claimed,
|
|
1670
|
+
claimSources,
|
|
1671
|
+
// The resolver is the SAME function the proxy legs call, so the preview
|
|
1672
|
+
// can never disagree with the live decision — which is why the claim legs
|
|
1673
|
+
// ride in here too: omitting them would make an unsaved table preview as
|
|
1674
|
+
// `direct` while the relay already goes `proxy`.
|
|
1675
|
+
decision: host
|
|
1676
|
+
? resolveHost(host, rules, { claimed: new Set(claimed), claimEgress: claimEgressFor, intercept })
|
|
1677
|
+
: null,
|
|
1678
|
+
};
|
|
1679
|
+
});
|
|
1680
|
+
// 3A5. One-click "tighten to allowlist" (ADR-0018 Revision 4). An install
|
|
1681
|
+
// that predates the claims posture still carries the old `* → intercept`
|
|
1682
|
+
// catch-all, which now decrypts nothing extra yet reads as "decrypt
|
|
1683
|
+
// everything". Tightening rewrites the catch-all to a blind tunnel (keeping
|
|
1684
|
+
// its egress) and pins the posture to `claims` — through the SAME save path
|
|
1685
|
+
// the console's Save button uses (config.yaml write + hot-apply), and ONLY
|
|
1686
|
+
// when the operator clicked: nothing here runs on boot.
|
|
1687
|
+
app.post('/api/admin/forward-proxy/tighten', async (_req, reply) => {
|
|
1688
|
+
const live = getRuntimeConfigRef();
|
|
1689
|
+
const current = live?.forwardProxy ?? loadConfig().forwardProxy ?? {};
|
|
1690
|
+
const currentRules = current.rules ?? [];
|
|
1691
|
+
const catchAll = currentRules.find((r) => r?.match === '*');
|
|
1692
|
+
const egress = catchAll?.egress ?? DEFAULT_FORWARD_PROXY_RULES[0].egress;
|
|
1693
|
+
// Rewrite ONLY the catch-all's ingress. Specific `intercept` rows are
|
|
1694
|
+
// explicit operator intent (they keep decrypting under `claims`) and every
|
|
1695
|
+
// other row stays exactly as written — tightening must never be a way to
|
|
1696
|
+
// lose rules the operator typed.
|
|
1697
|
+
const rules = catchAll
|
|
1698
|
+
? currentRules.map((r) => r?.match === '*' && r.ingress === 'intercept' ? { ...r, ingress: 'passthrough' } : r)
|
|
1699
|
+
: [...currentRules, { match: '*', ingress: 'passthrough', egress }];
|
|
1700
|
+
const saved = saveConfig({ forwardProxy: { ...current, rules, intercept: DEFAULT_FORWARD_PROXY_INTERCEPT } });
|
|
1701
|
+
if (!saved.success)
|
|
1702
|
+
return reply.status(400).send(saved);
|
|
1703
|
+
// Hot-apply: saveConfig's auth-view sync replaces `live.forwardProxy` and
|
|
1704
|
+
// every proxy leg re-reads it per request, so no restart is involved.
|
|
1705
|
+
return {
|
|
1706
|
+
status: 'ok',
|
|
1707
|
+
rules,
|
|
1708
|
+
intercept: DEFAULT_FORWARD_PROXY_INTERCEPT,
|
|
1709
|
+
warnings: lintRules(rules, live?.proxy?.enabled === true, DEFAULT_FORWARD_PROXY_INTERCEPT, listClaimedEgress()),
|
|
1710
|
+
};
|
|
1711
|
+
});
|
|
865
1712
|
// 3B. Token usage aggregation from the trace ring: windowed totals plus
|
|
866
1713
|
// per-API-key rows (raw counts only — no cost accounting). Optional
|
|
867
1714
|
// `?since=<epoch-ms>` narrows to traces with `timestamp >= since`;
|
|
@@ -1006,21 +1853,23 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1006
1853
|
// 4. Client Interception Setup / Teardown
|
|
1007
1854
|
const handleSetup = async (req, reply) => {
|
|
1008
1855
|
const { client } = req.params;
|
|
1009
|
-
const { models, apiKey, contextWindow, extraModels, agentModels,
|
|
1856
|
+
const { models, apiKey, contextWindow, extraModels, virtualModels, agentModels, product, acknowledgeRunning } = (req.body || {});
|
|
1010
1857
|
const cleaned = models && typeof models === 'object'
|
|
1011
1858
|
? Object.fromEntries(Object.entries(models).map(([k, v]) => [k, String(v ?? 'auto').trim() || 'auto']))
|
|
1012
1859
|
: undefined;
|
|
1013
1860
|
const cleanedExtra = Array.isArray(extraModels)
|
|
1014
1861
|
? extraModels.map(s => String(s || '').trim()).filter(Boolean)
|
|
1015
1862
|
: undefined;
|
|
1863
|
+
// Follow-mode virtual block: clamp to the known tier aliases in canonical
|
|
1864
|
+
// order — the field carries the key policy's allowed verdicts, never
|
|
1865
|
+
// arbitrary ids (concrete pins ride in extraModels).
|
|
1866
|
+
const cleanedVirtual = Array.isArray(virtualModels)
|
|
1867
|
+
? [...VIRTUAL_AUTO_IDS].filter(id => virtualModels.map(s => String(s || '').trim()).includes(id))
|
|
1868
|
+
: undefined;
|
|
1016
1869
|
const cw = Number(contextWindow);
|
|
1017
|
-
// Agent-binding
|
|
1018
|
-
//
|
|
1019
|
-
//
|
|
1020
|
-
// resolved here against the saved profile's slots; slots the profile
|
|
1021
|
-
// no longer defines drop out (the row falls back to inherit).
|
|
1022
|
-
// A wrong write to opencode.jsonc is harder to undo than a refused
|
|
1023
|
-
// setup, so every merged ref must be routable (fail-fast).
|
|
1870
|
+
// Agent-binding payload (opencode hook): manual rows — agent name →
|
|
1871
|
+
// modelRef (''/'auto' dropped). A wrong write to opencode.jsonc is harder
|
|
1872
|
+
// to undo than a refused setup, so every ref must be routable (fail-fast).
|
|
1024
1873
|
const allowedRefs = new Set([
|
|
1025
1874
|
// 'auto' is a legal slot ref (inherit-the-default): the adapter skips it.
|
|
1026
1875
|
'auto', 'lite', 'plus', 'pro', 'ultra',
|
|
@@ -1046,59 +1895,24 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1046
1895
|
manual[agentName] = ref;
|
|
1047
1896
|
}
|
|
1048
1897
|
}
|
|
1049
|
-
|
|
1050
|
-
const
|
|
1051
|
-
let profileEcho;
|
|
1052
|
-
if (profile !== undefined) {
|
|
1053
|
-
const profileId = (profile.id || '').trim();
|
|
1054
|
-
if (!profileId) {
|
|
1055
|
-
// Empty id = explicit un-link: sweep router-owned agent overrides + clear echo
|
|
1056
|
-
profileEcho = { id: '', bindings: {} };
|
|
1057
|
-
}
|
|
1058
|
-
else {
|
|
1059
|
-
const p = (loadConfig().modelProfiles || []).find(x => x.id === profileId);
|
|
1060
|
-
if (!p) {
|
|
1061
|
-
return reply.status(400).send({ success: false, message: `Model profile '${profileId}' not found in config` });
|
|
1062
|
-
}
|
|
1063
|
-
const bindingsIn = profile.bindings;
|
|
1064
|
-
if (bindingsIn && (typeof bindingsIn !== 'object' || Array.isArray(bindingsIn))) {
|
|
1065
|
-
return reply.status(400).send({ success: false, message: 'profile.bindings must be an object of agent name → slot key' });
|
|
1066
|
-
}
|
|
1067
|
-
const bindingEntries = Object.entries(bindingsIn || {});
|
|
1068
|
-
if (bindingEntries.length > 100) {
|
|
1069
|
-
return reply.status(400).send({ success: false, message: 'profile.bindings exceeds 100 entries' });
|
|
1070
|
-
}
|
|
1071
|
-
for (const [agentName, slotRaw] of bindingEntries) {
|
|
1072
|
-
const slotKey = String(slotRaw || '').trim();
|
|
1073
|
-
if (!slotKey)
|
|
1074
|
-
continue; // unlinked
|
|
1075
|
-
const ref = (p.slots || {})[slotKey];
|
|
1076
|
-
if (!ref)
|
|
1077
|
-
continue; // slot gone from the profile — row falls back to inherit
|
|
1078
|
-
resolvedTags[agentName] = slotKey;
|
|
1079
|
-
resolvedRefs[agentName] = ref;
|
|
1080
|
-
}
|
|
1081
|
-
profileEcho = { id: profileId, bindings: resolvedTags };
|
|
1082
|
-
}
|
|
1083
|
-
}
|
|
1084
|
-
// Merge both sources (disjoint per row; manual wins defensively) and
|
|
1085
|
-
// fail-fast on any ref the gateway cannot resolve.
|
|
1086
|
-
const merged = { ...resolvedRefs, ...manual };
|
|
1087
|
-
const invalid = Object.entries(merged).filter(([, ref]) => !allowedRefs.has(ref)).map(([name, ref]) => `${name}→${ref}`);
|
|
1898
|
+
// Fail-fast on any ref the gateway cannot resolve.
|
|
1899
|
+
const invalid = Object.entries(manual).filter(([, ref]) => !allowedRefs.has(ref)).map(([name, ref]) => `${name}→${ref}`);
|
|
1088
1900
|
if (invalid.length > 0) {
|
|
1089
1901
|
return reply.status(400).send({
|
|
1090
1902
|
success: false,
|
|
1091
1903
|
message: `Agent model refs not routable: ${invalid.join(', ')} — register the model / combo first`,
|
|
1092
1904
|
});
|
|
1093
1905
|
}
|
|
1094
|
-
const agentModelsPayload = agentModels !== undefined
|
|
1906
|
+
const agentModelsPayload = agentModels !== undefined ? manual : undefined;
|
|
1095
1907
|
const result = await setupClient(client, {
|
|
1096
1908
|
...(cleaned ? { models: cleaned } : {}),
|
|
1097
1909
|
...(apiKey?.trim() ? { apiKey: apiKey.trim() } : {}),
|
|
1098
1910
|
...(Number.isFinite(cw) && cw > 0 ? { contextWindow: Math.floor(cw) } : {}),
|
|
1099
1911
|
...(cleanedExtra ? { extraModels: cleanedExtra } : {}),
|
|
1912
|
+
...(cleanedVirtual !== undefined ? { virtualModels: cleanedVirtual } : {}),
|
|
1100
1913
|
...(agentModelsPayload ? { agentModels: agentModelsPayload } : {}),
|
|
1101
|
-
...(
|
|
1914
|
+
...(typeof product === 'string' && product.trim() ? { product: product.trim() } : {}),
|
|
1915
|
+
...(acknowledgeRunning === true ? { acknowledgeRunning: true } : {}),
|
|
1102
1916
|
});
|
|
1103
1917
|
if (!result.success)
|
|
1104
1918
|
return reply.status(400).send(result);
|
|
@@ -1106,7 +1920,11 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1106
1920
|
};
|
|
1107
1921
|
const handleTeardown = async (req, reply) => {
|
|
1108
1922
|
const { client } = req.params;
|
|
1109
|
-
const
|
|
1923
|
+
const { product, acknowledgeRunning } = (req.body || {});
|
|
1924
|
+
const result = await teardownClient(client, {
|
|
1925
|
+
...(typeof product === 'string' && product.trim() ? { product: product.trim() } : {}),
|
|
1926
|
+
...(acknowledgeRunning === true ? { acknowledgeRunning: true } : {}),
|
|
1927
|
+
});
|
|
1110
1928
|
if (!result.success)
|
|
1111
1929
|
return reply.status(400).send(result);
|
|
1112
1930
|
return result;
|
|
@@ -1118,7 +1936,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1118
1936
|
* Deliberately the SAME cascade the /v1/systemone surface applies (ADR-0008),
|
|
1119
1937
|
* so a name means one thing console-wide: a registered id, or a combo (its
|
|
1120
1938
|
* leader member answers — the same leader pick the routing path uses), is
|
|
1121
|
-
* used as-is; a bare tier alias projects onto the
|
|
1939
|
+
* used as-is; a bare tier alias projects onto the leading model of its healthy
|
|
1122
1940
|
* DECISION-SURFACE pool (the read that keeps systemone-wire models in view);
|
|
1123
1941
|
* bare `auto` means `systemone.defaultModel`. Undefined = nothing routable
|
|
1124
1942
|
* behind the name (unknown id, combo without members, empty/all-unhealthy
|
|
@@ -1141,25 +1959,63 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1141
1959
|
}
|
|
1142
1960
|
return undefined;
|
|
1143
1961
|
};
|
|
1962
|
+
/** Compact context window: 200000 → '200k', 1_048_576 → '1M'. */
|
|
1963
|
+
const fmtContext = (n) => n >= 1_000_000 ? `${+((n / 1_000_000).toFixed(1))}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
|
|
1964
|
+
/**
|
|
1965
|
+
* Catalog enrichment tokens — decision-relevant facts the registry
|
|
1966
|
+
* registration does not carry, appended to a registered model's (or
|
|
1967
|
+
* variant's) description. Conditional by design: majority-true facts
|
|
1968
|
+
* (tool_call=yes, no image support on a text-only fleet) stay SILENT so the
|
|
1969
|
+
* per-question criteria repetition does not bloat the prompt — a token
|
|
1970
|
+
* appears only when it distinguishes the candidate or warns about it.
|
|
1971
|
+
*/
|
|
1972
|
+
const catalogTokens = (cat) => {
|
|
1973
|
+
if (!cat)
|
|
1974
|
+
return [];
|
|
1975
|
+
const tokens = [];
|
|
1976
|
+
const ctx = cat.limit?.context;
|
|
1977
|
+
if (typeof ctx === 'number' && Number.isFinite(ctx) && ctx > 0)
|
|
1978
|
+
tokens.push(`context=${fmtContext(ctx)}`);
|
|
1979
|
+
const inMods = cat.modalities?.input;
|
|
1980
|
+
if (Array.isArray(inMods) && inMods.includes('image'))
|
|
1981
|
+
tokens.push('vision=yes (accepts image input)');
|
|
1982
|
+
if (cat.tool_call === false)
|
|
1983
|
+
tokens.push('tools=NO — cannot call tools, unsuitable for agent roles');
|
|
1984
|
+
if (cat.status === 'deprecated')
|
|
1985
|
+
tokens.push('status=deprecated — avoid unless no alternative');
|
|
1986
|
+
return tokens;
|
|
1987
|
+
};
|
|
1144
1988
|
/**
|
|
1145
1989
|
* One-line, model-readable description of a candidate — `criteria` values are
|
|
1146
1990
|
* the ONLY per-option context the decision prompt carries (the whole
|
|
1147
1991
|
* questions document is serialized verbatim by convert.ts
|
|
1148
1992
|
* buildDecisionChatRequest). Registry data is the objective half (tier
|
|
1149
|
-
* membership, price, reasoning support, wire);
|
|
1150
|
-
*
|
|
1151
|
-
*
|
|
1152
|
-
*
|
|
1153
|
-
*
|
|
1993
|
+
* membership, price, reasoning support, wire); catalog enrichment adds the
|
|
1994
|
+
* capability/context/lifecycle facts the registration does not carry
|
|
1995
|
+
* (context window, vision, tool calling, deprecated status) — see
|
|
1996
|
+
* catalogTokens. The frontend-supplied note carries what neither source can
|
|
1997
|
+
* know (caller context). Virtual ids resolve to no entity and are described
|
|
1998
|
+
* by what they MEAN, since "assign `lite`" is a legitimate pick. Deliberately
|
|
1999
|
+
* NO tier ladder here: writing "ultra = broadest" made every role land on
|
|
2000
|
+
* `ultra`.
|
|
2001
|
+
*/
|
|
2002
|
+
/**
|
|
2003
|
+
* Price sentence for the decision prompt. An UNPRICED model must not render
|
|
2004
|
+
* as `$0/$0`: the LLM reads these lines when choosing a candidate, so a
|
|
2005
|
+
* fabricated zero is an active instruction to prefer it as "free".
|
|
1154
2006
|
*/
|
|
1155
|
-
const
|
|
2007
|
+
const priceLine = (p) => p
|
|
2008
|
+
? `price $${p.input}/$${p.output} per 1M tokens in/out`
|
|
2009
|
+
: 'price unknown (no published dollar price — do NOT read this as free)';
|
|
2010
|
+
const describeCandidate = (rawId, note, cat) => {
|
|
1156
2011
|
const m = registry.getModel(rawId);
|
|
1157
2012
|
let body;
|
|
1158
2013
|
if (m) {
|
|
1159
2014
|
const tiers = registry.tiersOf(m);
|
|
1160
2015
|
const parts = [
|
|
1161
2016
|
`registered model; tiers=${tiers.length > 0 ? tiers.join('|') : 'none'}`,
|
|
1162
|
-
|
|
2017
|
+
priceLine(m.pricing),
|
|
2018
|
+
...catalogTokens(cat),
|
|
1163
2019
|
];
|
|
1164
2020
|
if (m.wire === 'systemone') {
|
|
1165
2021
|
parts.push('wire=systemone — decision protocol ONLY, cannot serve chat, never assign it to a chat role');
|
|
@@ -1178,14 +2034,17 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1178
2034
|
// Variant sibling id (`<baseId>-<variantId>`): not a registry entry of its
|
|
1179
2035
|
// own — the base model plus a pinned reasoning level (orchestrator
|
|
1180
2036
|
// resolves it the same way). Calling it unregistered would steer the
|
|
1181
|
-
// decider away from a perfectly legal pick.
|
|
2037
|
+
// decider away from a perfectly legal pick. The caller looks the catalog
|
|
2038
|
+
// record up by the BASE id and passes it in.
|
|
1182
2039
|
const { base, variant } = registry.resolveVariantRef(rawId);
|
|
1183
2040
|
const tiers = registry.tiersOf(base);
|
|
2041
|
+
const catTokens = catalogTokens(cat);
|
|
1184
2042
|
body =
|
|
1185
2043
|
`variant of ${base.id} (pins reasoning_effort '${variant.reasoningEffort}'); ` +
|
|
1186
2044
|
`tiers=${tiers.length > 0 ? tiers.join('|') : 'none'}; ` +
|
|
1187
|
-
|
|
1188
|
-
|
|
2045
|
+
priceLine(base.pricing) +
|
|
2046
|
+
(catTokens.length > 0 ? `; ${catTokens.join('; ')}` : '') +
|
|
2047
|
+
`; wire=${base.wire ?? 'unknown'}`;
|
|
1189
2048
|
}
|
|
1190
2049
|
else if (registry.isCombo(rawId)) {
|
|
1191
2050
|
body = `combo; members=${registry.resolveCombo(rawId).length} (the router picks a healthy member per request)`;
|
|
@@ -1217,8 +2076,8 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1217
2076
|
const body = (req.body || {});
|
|
1218
2077
|
const decider = (body.deciderModel || '').trim();
|
|
1219
2078
|
const targets = Array.isArray(body.targets) ? body.targets.filter((t) => t && t.key) : [];
|
|
1220
|
-
// Candidates are plain ids or { id, note } — the note (
|
|
1221
|
-
//
|
|
2079
|
+
// Candidates are plain ids or { id, note } — the note (caller-supplied
|
|
2080
|
+
// context) contextualizes the choice but only `id` is a
|
|
1222
2081
|
// legal assignment value.
|
|
1223
2082
|
const rawCandidates = Array.isArray(body.candidates) ? body.candidates : [];
|
|
1224
2083
|
const candidates = rawCandidates
|
|
@@ -1244,7 +2103,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1244
2103
|
// Tier PURPOSE (what each rung is for), never a ranking: a ladder reads
|
|
1245
2104
|
// as "ultra is the most/broadest" and then every role lands on it.
|
|
1246
2105
|
tierPurpose: TIER_PURPOSE,
|
|
1247
|
-
task: 'Assign each role/slot the MOST suitable candidate id. Every candidate is described with its objective profile (tier membership, price per 1M tokens, reasoning support, wire); use that — never guess from the model name alone.',
|
|
2106
|
+
task: 'Assign each role/slot the MOST suitable candidate id. Every candidate is described with its objective profile (tier membership, price per 1M tokens, context window, capability flags such as vision and tool calling where they distinguish the candidate, reasoning support, wire, lifecycle warnings); use that — never guess from the model name alone.',
|
|
1248
2107
|
roles: targets.map((t) => ({
|
|
1249
2108
|
key: t.key,
|
|
1250
2109
|
name: t.label || t.key,
|
|
@@ -1256,13 +2115,37 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1256
2115
|
...(t.current ? { current: t.current } : {}),
|
|
1257
2116
|
})),
|
|
1258
2117
|
};
|
|
2118
|
+
// Catalog enrichment, loaded ONCE per request: capability/context/lifecycle
|
|
2119
|
+
// facts the registry registration does not carry (see catalogTokens).
|
|
2120
|
+
// Lookup key is the provider-qualified registration id (`<provider>/<model>`
|
|
2121
|
+
// — exactly how boot-direct names registrations), so a plain Map.get per
|
|
2122
|
+
// candidate; variants resolve through their BASE id. Failure degrades
|
|
2123
|
+
// gracefully: candidates fall back to the registry-only description.
|
|
2124
|
+
const { catalogRepository } = await import('../opencode/catalog/repository.js');
|
|
2125
|
+
const catalogModels = new Map();
|
|
2126
|
+
try {
|
|
2127
|
+
for (const rec of await catalogRepository.list()) {
|
|
2128
|
+
for (const cm of rec.models)
|
|
2129
|
+
catalogModels.set(`${rec.id}/${cm.id}`, cm);
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
catch {
|
|
2133
|
+
// catalog unavailable — describeCandidate simply receives undefined
|
|
2134
|
+
}
|
|
2135
|
+
const catalogOf = (rawId) => {
|
|
2136
|
+
const m = registry.getModel(rawId);
|
|
2137
|
+
if (m)
|
|
2138
|
+
return catalogModels.get(m.id);
|
|
2139
|
+
const v = registry.resolveVariantRef(rawId);
|
|
2140
|
+
return v ? catalogModels.get(v.base.id) : undefined;
|
|
2141
|
+
};
|
|
1259
2142
|
const rubric = 'Pick exactly one candidate id per question. Match the role\'s WORK to the tier whose PURPOSE describes it (see tierPurpose), then weigh that candidate\'s described profile (capability needs, cost, latency). Do not default every role to one "best" model — the four tiers exist to separate that work. A candidate marked unable to serve chat is never a valid answer.';
|
|
1260
2143
|
const questions = {};
|
|
1261
2144
|
for (const t of targets) {
|
|
1262
2145
|
questions[t.key] = {
|
|
1263
2146
|
type: 'choice',
|
|
1264
2147
|
instructions: rubric,
|
|
1265
|
-
criteria: Object.fromEntries(candidates.map((c) => [c.id, describeCandidate(c.id, c.note)])),
|
|
2148
|
+
criteria: Object.fromEntries(candidates.map((c) => [c.id, describeCandidate(c.id, c.note, catalogOf(c.id))])),
|
|
1266
2149
|
};
|
|
1267
2150
|
}
|
|
1268
2151
|
const params = req.params;
|
|
@@ -1305,7 +2188,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1305
2188
|
targets: targets.length,
|
|
1306
2189
|
candidates: candidates.length,
|
|
1307
2190
|
criteriaChars: JSON.stringify(questions).length,
|
|
1308
|
-
criteriaSample: candidates[0] ? describeCandidate(candidates[0].id, candidates[0].note) : '',
|
|
2191
|
+
criteriaSample: candidates[0] ? describeCandidate(candidates[0].id, candidates[0].note, catalogOf(candidates[0].id)) : '',
|
|
1309
2192
|
state,
|
|
1310
2193
|
answers: Object.fromEntries(Object.entries((response?.answers || {})).map(([k, v]) => [k, v?.choice])),
|
|
1311
2194
|
usage: response?.usage,
|
|
@@ -1346,14 +2229,13 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1346
2229
|
}
|
|
1347
2230
|
return { success: true, model: raw, resolved: model.id };
|
|
1348
2231
|
});
|
|
1349
|
-
// 4a. OpenCode agent inventory (model-
|
|
2232
|
+
// 4a. OpenCode agent inventory (agent model-binding UI): live v2 service
|
|
1350
2233
|
// roster (`GET /api/agent`, plugins included) with the file scan
|
|
1351
2234
|
// (built-ins + agent(s)/*.md + config nodes) as offline fallback.
|
|
1352
2235
|
app.get('/api/admin/opencode/agents', async () => ({ status: 'ok', agents: await listOpenCodeAgentsLive() }));
|
|
1353
2236
|
// 4b. Console webAuth — login/logout/session probes + credential management.
|
|
1354
2237
|
// login/logout/session stay reachable pre-login (server.ts gate whitelist);
|
|
1355
|
-
// the two config endpoints ride the normal console gate (session cookie
|
|
1356
|
-
// master adminApiKey Bearer).
|
|
2238
|
+
// the two config endpoints ride the normal console gate (session cookie).
|
|
1357
2239
|
app.get('/api/admin/auth/session', async (req) => {
|
|
1358
2240
|
const disk = getRuntimeConfigRef() || loadConfig(); // runtime snapshot (see gate comment)
|
|
1359
2241
|
const active = isWebAuthActive(disk);
|
|
@@ -1475,27 +2357,34 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1475
2357
|
// invariant 6). Within circuitBreaker only persistence.debounceMs still
|
|
1476
2358
|
// needs a restart — the state store binds its debounce at boot.
|
|
1477
2359
|
initProxyConfig(loadConfig().proxy);
|
|
2360
|
+
void reconcileMihomoSidecar(loadConfig().proxy).catch((err) => {
|
|
2361
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2362
|
+
console.warn(`[Clash] reconcile after config save failed: ${message}`);
|
|
2363
|
+
});
|
|
1478
2364
|
orchestrator.getCaptureRecorder().applyConfig(loadConfig().requestCapture);
|
|
1479
2365
|
applyDecisionCaptureConfig(loadConfig().classifier?.layer2); // L2 dataset sampling: single-key gate classifier.layer2.collectEnabled, hot too
|
|
1480
2366
|
applyRouteEntriesConfig(loadConfig().routeEntries); // experience-table gate: hot-applies lookup/writes
|
|
1481
2367
|
applyDirectivesConfig(loadConfig().directives); // directive gate: hot-applies the reserved namespace + kill switch
|
|
2368
|
+
applyStreamingPosture(loadConfig().streaming); // streaming posture: both axes are read per request, so a save lands immediately
|
|
1482
2369
|
orchestrator.getRegistry().applyCombos(loadConfig().combos);
|
|
1483
2370
|
orchestrator.getRegistry().applyTierConfigNow(); // tier member lists commit immediately (no restart)
|
|
2371
|
+
try {
|
|
2372
|
+
await refreshDirectPool(orchestrator.getRegistry()); // provider-def sync: models/wires/chains match the defs file (no restart)
|
|
2373
|
+
}
|
|
2374
|
+
catch (err) {
|
|
2375
|
+
// Fail-open, but never silent: the registry keeps serving and may drift.
|
|
2376
|
+
console.warn(`[console] pool resync after config save failed (registry may drift): ${err.message}`);
|
|
2377
|
+
}
|
|
1484
2378
|
warnOnEmptyTierPools(); // no residual tier → an empty pool is now possible
|
|
1485
2379
|
orchestrator
|
|
1486
2380
|
.getRegistry()
|
|
1487
2381
|
.getCircuitBreakerManager()
|
|
1488
2382
|
.applyConfig(loadConfig().circuitBreaker, loadConfig().retry); // breaker rules hot-apply (next-decision-point semantics)
|
|
1489
|
-
// Profile-link write-through: an edited profile re-resolves into every
|
|
1490
|
-
// hooked client linked to it (diff-guarded — no-op when unchanged).
|
|
1491
|
-
const profileNote = await refreshClientProfileBindings(loadConfig().modelProfiles || []);
|
|
1492
|
-
if (profileNote)
|
|
1493
|
-
return { ...result, message: `Saved. ${profileNote.trim().replace(/^; /, '')}` };
|
|
1494
2383
|
return result;
|
|
1495
2384
|
};
|
|
1496
2385
|
app.post('/api/admin/config', handleSaveConfig);
|
|
1497
2386
|
// 6. Raw YAML Configuration
|
|
1498
|
-
app.get('/api/admin/config/raw', async () => ({ status: 'ok', yaml: getRawConfig() }));
|
|
2387
|
+
app.get('/api/admin/config/raw', async () => ({ status: 'ok', yaml: getRawConfig(), path: getConfigPath() }));
|
|
1499
2388
|
const handleSaveRawYaml = async (req, reply) => {
|
|
1500
2389
|
const body = req.body;
|
|
1501
2390
|
if (!body?.yaml || typeof body.yaml !== 'string') {
|
|
@@ -1505,10 +2394,15 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1505
2394
|
if (!result.success)
|
|
1506
2395
|
return reply.status(400).send(result);
|
|
1507
2396
|
initProxyConfig(loadConfig().proxy); // hot-apply proxy policy (see handleSaveConfig)
|
|
2397
|
+
void reconcileMihomoSidecar(loadConfig().proxy).catch((err) => {
|
|
2398
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2399
|
+
console.warn(`[Clash] reconcile after config save failed: ${message}`);
|
|
2400
|
+
});
|
|
1508
2401
|
orchestrator.getCaptureRecorder().applyConfig(loadConfig().requestCapture); // hot-apply capture too
|
|
1509
2402
|
applyDecisionCaptureConfig(loadConfig().classifier?.layer2); // hot-apply the L2 dataset-sampling gate too (classifier.layer2.collectEnabled)
|
|
1510
2403
|
applyRouteEntriesConfig(loadConfig().routeEntries); // hot-apply the experience-table gate too
|
|
1511
2404
|
applyDirectivesConfig(loadConfig().directives); // hot-apply the directive namespace too
|
|
2405
|
+
applyStreamingPosture(loadConfig().streaming); // hot-apply the streaming posture too (two axes, per-request reads)
|
|
1512
2406
|
orchestrator.getRegistry().applyCombos(loadConfig().combos); // hot-apply combos too
|
|
1513
2407
|
orchestrator.getRegistry().applyTierConfigNow(); // hot-commit tier member lists too
|
|
1514
2408
|
warnOnEmptyTierPools(); // no residual tier → an empty pool is now possible
|
|
@@ -1516,19 +2410,37 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1516
2410
|
.getRegistry()
|
|
1517
2411
|
.getCircuitBreakerManager()
|
|
1518
2412
|
.applyConfig(loadConfig().circuitBreaker, loadConfig().retry); // hot-apply breaker rules too (see handleSaveConfig)
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
2413
|
+
try {
|
|
2414
|
+
await refreshDirectPool(orchestrator.getRegistry()); // provider-def sync on the raw path too (no restart)
|
|
2415
|
+
}
|
|
2416
|
+
catch (err) {
|
|
2417
|
+
// Fail-open, but never silent: the registry keeps serving and may drift.
|
|
2418
|
+
console.warn(`[console] pool resync after config save failed (registry may drift): ${err.message}`);
|
|
2419
|
+
}
|
|
1523
2420
|
return result;
|
|
1524
2421
|
};
|
|
1525
2422
|
app.post('/api/admin/config/raw', handleSaveRawYaml);
|
|
2423
|
+
// 6b. Dynamic comment panel data — config.yaml is ZERO-COMMENT on disk
|
|
2424
|
+
// (ADR-0016); the Config File page renders per-field comments from these
|
|
2425
|
+
// dictionaries in the operator's language. Runtime-path keyed; the panel
|
|
2426
|
+
// walks the flat runtime shape the same way loadConfig expands it.
|
|
2427
|
+
app.get('/api/admin/config/comments', async (req) => {
|
|
2428
|
+
const query = req.query;
|
|
2429
|
+
const lang = commentLangFromQuery(query.lang);
|
|
2430
|
+
const zh = lang === 'zh-CN';
|
|
2431
|
+
return {
|
|
2432
|
+
status: 'ok',
|
|
2433
|
+
lang,
|
|
2434
|
+
header: zh ? YAML_FILE_HEADER_ZH : YAML_FILE_HEADER_EN,
|
|
2435
|
+
fields: zh ? YAML_FIELD_COMMENTS_ZH : YAML_FIELD_COMMENTS_EN,
|
|
2436
|
+
};
|
|
2437
|
+
});
|
|
1526
2438
|
// 6a. Forward-proxy MITM CA export — clients using the inbound forward
|
|
1527
2439
|
// proxy must trust this CA. Generated on first request when absent (the
|
|
1528
2440
|
// same idempotent ensureCa the proxy itself uses).
|
|
1529
2441
|
const handleForwardProxyCa = async (_req, reply) => {
|
|
1530
2442
|
const cfg = loadConfig();
|
|
1531
|
-
const caDir = cfg.forwardProxy?.caDir
|
|
2443
|
+
const caDir = resolveCaDir(cfg.forwardProxy?.caDir);
|
|
1532
2444
|
try {
|
|
1533
2445
|
const ca = ensureCa(caDir);
|
|
1534
2446
|
reply.header('content-type', 'application/x-pem-file');
|
|
@@ -1540,6 +2452,39 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1540
2452
|
}
|
|
1541
2453
|
};
|
|
1542
2454
|
app.get('/api/admin/proxy/ca', handleForwardProxyCa);
|
|
2455
|
+
// 6a-bis. CA identity for the console card: absolute path, SHA-256
|
|
2456
|
+
// fingerprint and validity. Never key material — clients use it to check
|
|
2457
|
+
// that the root they installed is the root this proxy signs with.
|
|
2458
|
+
app.get('/api/admin/proxy/ca/meta', async (_req, reply) => {
|
|
2459
|
+
const cfg = loadConfig();
|
|
2460
|
+
try {
|
|
2461
|
+
return { status: 'ok', ...describeCa(cfg.forwardProxy?.caDir) };
|
|
2462
|
+
}
|
|
2463
|
+
catch (err) {
|
|
2464
|
+
return reply.status(500).send({ status: 'error', message: err?.message || 'Failed to load CA' });
|
|
2465
|
+
}
|
|
2466
|
+
});
|
|
2467
|
+
// 6a-ter. Trust state for the console card: does the platform store that
|
|
2468
|
+
// clients verify against hold THIS CA? Tri-state on purpose — `unknown` means
|
|
2469
|
+
// the probe could not run, never "not trusted". Cached 60s (the probe spawns
|
|
2470
|
+
// platform tools); `force=1` bypasses the TTL for an operator re-check after
|
|
2471
|
+
// an install.
|
|
2472
|
+
app.get('/api/admin/proxy/ca/trust', async (req) => {
|
|
2473
|
+
const cfg = loadConfig();
|
|
2474
|
+
const caPath = caCertPath(cfg.forwardProxy?.caDir);
|
|
2475
|
+
const force = String(req.query?.force ?? '') === '1';
|
|
2476
|
+
// Fail SOFT: the console renders a tri-state chip, so a probe that cannot
|
|
2477
|
+
// run is `unknown`, never a 500 that makes the chip silently disappear.
|
|
2478
|
+
// `checkedAt` stays absent while no probe ran (no PEM to identify).
|
|
2479
|
+
if (!fs.existsSync(caPath))
|
|
2480
|
+
return { status: 'ok', trusted: 'unknown', caPath };
|
|
2481
|
+
try {
|
|
2482
|
+
return { status: 'ok', ...(await probeCaTrustedCached(caPath, { force })), caPath };
|
|
2483
|
+
}
|
|
2484
|
+
catch {
|
|
2485
|
+
return { status: 'ok', trusted: 'unknown', caPath };
|
|
2486
|
+
}
|
|
2487
|
+
});
|
|
1543
2488
|
// 6b. Tier member lists — candidate pool snapshots (console preview).
|
|
1544
2489
|
// membership is a PURE projection of (model id × tiers.members);
|
|
1545
2490
|
// PREVIEW never mutates live pools — real membership is committed ONLY by
|
|
@@ -1555,9 +2500,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1555
2500
|
isDefaultInTier: Boolean(model.isDefaultInTier),
|
|
1556
2501
|
inputPrice: model.pricing?.input,
|
|
1557
2502
|
outputPrice: model.pricing?.output,
|
|
1558
|
-
// Decision 6 aggregate: healthy iff
|
|
1559
|
-
// a
|
|
1560
|
-
//
|
|
2503
|
+
// Decision 6 aggregate: healthy iff at least one credential tuple serves —
|
|
2504
|
+
// a model whose every credential is cooling shows down here exactly as it
|
|
2505
|
+
// does to the pool builders.
|
|
1561
2506
|
healthy: registry.modelAvailable(model).available,
|
|
1562
2507
|
weight,
|
|
1563
2508
|
}));
|
|
@@ -1603,8 +2548,8 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1603
2548
|
// tiers.exclude filter. No preview; what the runtime would actually use.
|
|
1604
2549
|
//
|
|
1605
2550
|
// Read-only on purpose: the previous version called applyTierConfigNow()
|
|
1606
|
-
// here as a "force-commit view" trick, but that mutated m.tier
|
|
1607
|
-
//
|
|
2551
|
+
// here as a "force-commit view" trick, but that mutated m.tier on every
|
|
2552
|
+
// Live tab open — a stealth commit with no save event behind it.
|
|
1608
2553
|
// The console must NEVER write routing state from a GET. Out-of-band file
|
|
1609
2554
|
// edits get picked up on the next save commit (the console already triggers
|
|
1610
2555
|
// applyTierConfigNow in handleSaveConfig / handleSaveRawYaml).
|
|
@@ -1622,9 +2567,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1622
2567
|
isDefaultInTier: Boolean(model.isDefaultInTier),
|
|
1623
2568
|
inputPrice: model.pricing?.input,
|
|
1624
2569
|
outputPrice: model.pricing?.output,
|
|
1625
|
-
// Decision 6 aggregate: healthy iff
|
|
1626
|
-
// a
|
|
1627
|
-
//
|
|
2570
|
+
// Decision 6 aggregate: healthy iff at least one credential tuple serves —
|
|
2571
|
+
// a model whose every credential is cooling shows down here exactly as it
|
|
2572
|
+
// does to the pool builders.
|
|
1628
2573
|
healthy: registry.modelAvailable(model).available,
|
|
1629
2574
|
weight,
|
|
1630
2575
|
})),
|
|
@@ -1660,13 +2605,13 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1660
2605
|
const members = expanded.tiers;
|
|
1661
2606
|
const modelIds = registry
|
|
1662
2607
|
.getAllModels()
|
|
1663
|
-
.filter((m) => m.
|
|
2608
|
+
.filter((m) => m.autoTier)
|
|
1664
2609
|
.map((m) => m.id);
|
|
1665
2610
|
const orphans = [];
|
|
1666
2611
|
for (const tier of MEMBER_TIER_ORDER) {
|
|
1667
2612
|
for (const rule of members[tier]) {
|
|
1668
2613
|
// exact rules = combo-expanded ids: registered by construction, and a
|
|
1669
|
-
// hand-configured member (no
|
|
2614
|
+
// hand-configured member (no autoTier stamp) is not in modelIds — flagging
|
|
1670
2615
|
// them here would be a false positive; ref liveness is deadCombo's job
|
|
1671
2616
|
if (rule.exact)
|
|
1672
2617
|
continue;
|
|
@@ -1686,8 +2631,8 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1686
2631
|
// End-to-end tier test — one REAL minimal completion pinned to the tier via
|
|
1687
2632
|
// the bare tier alias: the same force_tier path a client's
|
|
1688
2633
|
// `model: "pro"` request takes (tier aliases are reserved gateway ids,
|
|
1689
|
-
// never
|
|
1690
|
-
// exercises the SELECTED member (the
|
|
2634
|
+
// never pool-routed). One run only
|
|
2635
|
+
// exercises the SELECTED member (the default credential, or the weighted/round-robin
|
|
1691
2636
|
// pick), never the whole pool — deep per-model checks stay on the providers
|
|
1692
2637
|
// page. An EMPTY tier degrades inside getModelForTier (the session-pin birth
|
|
1693
2638
|
// representative falls down the escalate→plus→lite chain, server-warned with
|
|
@@ -1703,9 +2648,10 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1703
2648
|
try {
|
|
1704
2649
|
const result = await orchestrator.process({
|
|
1705
2650
|
model: tier,
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
2651
|
+
stream: false,
|
|
2652
|
+
input: [{ type: 'message', role: 'user', content: [{ type: 'text', text: 'ping' }] }],
|
|
2653
|
+
generation: { maxOutputTokens: 1 },
|
|
2654
|
+
}, { wire: 'openai-chat', clientIp: req.ip, headers: req.headers, fastifyRequest: req });
|
|
1709
2655
|
return {
|
|
1710
2656
|
status: 'ok',
|
|
1711
2657
|
ok: true,
|
|
@@ -1930,18 +2876,20 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1930
2876
|
};
|
|
1931
2877
|
for (const prefix of ['/api/admin']) {
|
|
1932
2878
|
app.get(`${prefix}/catalog/sources`, listCatalogSources);
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
app.post(`${prefix}/catalog/sources
|
|
1936
|
-
app.
|
|
1937
|
-
app.
|
|
2879
|
+
// Source mutations change the catalog universe the pool builder consumes —
|
|
2880
|
+
// resync the pool so pricing/modality/tier inputs cannot drift.
|
|
2881
|
+
app.post(`${prefix}/catalog/sources`, withPoolSync(registry, handleAddCatalogSource));
|
|
2882
|
+
app.post(`${prefix}/catalog/sources/refresh`, withPoolSync(registry, handleRefreshCatalogSources));
|
|
2883
|
+
app.post(`${prefix}/catalog/sources/:id/refresh`, withPoolSync(registry, handleRefreshCatalogSource));
|
|
2884
|
+
app.put(`${prefix}/catalog/sources/:id`, withPoolSync(registry, handleToggleCatalogSource));
|
|
2885
|
+
app.delete(`${prefix}/catalog/sources/:id`, withPoolSync(registry, handleRemoveCatalogSource));
|
|
1938
2886
|
app.get(`${prefix}/catalog/sources/:id/data`, getCatalogSourceData);
|
|
1939
2887
|
app.get(`${prefix}/catalog/locked-models`, listLockedCatalogModels);
|
|
1940
|
-
app.post(`${prefix}/catalog/locked-models`, handleLockCatalogModel);
|
|
2888
|
+
app.post(`${prefix}/catalog/locked-models`, withPoolSync(registry, handleLockCatalogModel));
|
|
1941
2889
|
app.get(`${prefix}/catalog/ocr`, getCatalogOcr);
|
|
1942
2890
|
app.get(`${prefix}/catalog/override`, handleGetCatalogOverride);
|
|
1943
|
-
app.put(`${prefix}/catalog/override`, handlePutCatalogOverride);
|
|
1944
|
-
app.delete(`${prefix}/catalog/override`, handleDeleteCatalogOverride);
|
|
2891
|
+
app.put(`${prefix}/catalog/override`, withPoolSync(registry, handlePutCatalogOverride));
|
|
2892
|
+
app.delete(`${prefix}/catalog/override`, withPoolSync(registry, handleDeleteCatalogOverride));
|
|
1945
2893
|
app.post(`${prefix}/catalog/sync-interval`, handleSetCatalogSyncInterval);
|
|
1946
2894
|
}
|
|
1947
2895
|
// 6c. Custom model combos — resolved member view for the /combos console
|
|
@@ -1972,7 +2920,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1972
2920
|
tier: model?.tier,
|
|
1973
2921
|
inputPrice: model?.pricing?.input,
|
|
1974
2922
|
outputPrice: model?.pricing?.output,
|
|
1975
|
-
breakerState: model ? cb.
|
|
2923
|
+
breakerState: model ? cb.getSnapshot(model.id)?.state ?? 'CLOSED' : undefined,
|
|
1976
2924
|
};
|
|
1977
2925
|
}),
|
|
1978
2926
|
}));
|
|
@@ -2001,9 +2949,10 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2001
2949
|
try {
|
|
2002
2950
|
const result = await orchestrator.process({
|
|
2003
2951
|
model: id,
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2952
|
+
stream: false,
|
|
2953
|
+
input: [{ type: 'message', role: 'user', content: [{ type: 'text', text: 'ping' }] }],
|
|
2954
|
+
generation: { maxOutputTokens: 1 },
|
|
2955
|
+
}, { wire: 'openai-chat', clientIp: req.ip, headers: req.headers, fastifyRequest: req });
|
|
2007
2956
|
return {
|
|
2008
2957
|
status: 'ok',
|
|
2009
2958
|
ok: true,
|
|
@@ -2097,24 +3046,31 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2097
3046
|
});
|
|
2098
3047
|
};
|
|
2099
3048
|
const ocHandlers = {
|
|
2100
|
-
/** The
|
|
2101
|
-
* served to every UI surface that renders
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
3049
|
+
/** The OCR protocol vocabulary — ONE backend-owned table (providers/vocabulary.ts)
|
|
3050
|
+
* served to every UI surface that renders protocol choices or display names. */
|
|
3051
|
+
protocolVocabulary: async () => {
|
|
3052
|
+
// Plugin-owned protocols are listed only while a loaded plugin claims the
|
|
3053
|
+
// wire — the table derives that half from the plugin registry, so this
|
|
3054
|
+
// handler never filters by vendor name (providers/vocabulary.ts).
|
|
3055
|
+
return { status: 'ok', entries: protocolVocabulary() };
|
|
2105
3056
|
},
|
|
2106
|
-
list: async () => {
|
|
3057
|
+
list: async (req) => {
|
|
2107
3058
|
const { getProviderNodeById } = await import('../opencode/user-config.js');
|
|
2108
3059
|
const { getProviderDefsPath } = await import('../opencode/provider-defs.js');
|
|
2109
3060
|
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
2110
3061
|
const { catalogRepository } = await import('../opencode/catalog/repository.js');
|
|
3062
|
+
const takedowns = getProviderTakedownStore();
|
|
2111
3063
|
const store = await getCredentialStore();
|
|
2112
3064
|
// B4: credentials come from the BOUND store on every binding — the masked store
|
|
2113
3065
|
// credentials merge into the config views, so a stale auth.json entry can never
|
|
2114
3066
|
// masquerade as a connected provider.
|
|
2115
|
-
const
|
|
3067
|
+
const lang = typeof req.query?.lang === 'string' ? req.query.lang : undefined;
|
|
3068
|
+
const views = await storeProviderViews(store, lang);
|
|
2116
3069
|
const unified = await catalogRepository.list();
|
|
2117
3070
|
const byId = new Map(unified.map((p) => [p.id, p]));
|
|
3071
|
+
// Plugin-origin provenance for the Connected-tab origin filter — same
|
|
3072
|
+
// ledger join as the catalog endpoint (ADR-0010: never written to providers.json).
|
|
3073
|
+
const origins = pluginProviderOrigins();
|
|
2118
3074
|
return {
|
|
2119
3075
|
status: 'ok',
|
|
2120
3076
|
configPath: getProviderDefsPath(),
|
|
@@ -2123,6 +3079,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2123
3079
|
const u = byId.get(v.id);
|
|
2124
3080
|
const defNode = getProviderNodeById(v.id);
|
|
2125
3081
|
const hasDefNode = defNode !== undefined;
|
|
3082
|
+
const takedown = takedowns.get(v.id);
|
|
2126
3083
|
return {
|
|
2127
3084
|
...v,
|
|
2128
3085
|
// Precise delete-branch signal: an explicit defs-file node is the
|
|
@@ -2138,8 +3095,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2138
3095
|
// builtin-catalog coverage; an aggregated-unknown id (no catalog row
|
|
2139
3096
|
// at all) is by definition custom.
|
|
2140
3097
|
custom: u ? u.custom : true,
|
|
2141
|
-
logo: u?.logo,
|
|
3098
|
+
logo: u?.logo ?? v.logo,
|
|
2142
3099
|
npm: v.npm ?? u?.npm,
|
|
3100
|
+
// Operator takedown: routing state, never a defs-file field (ADR-0010).
|
|
3101
|
+
// The card stays listed so the operator can restore it with one click.
|
|
3102
|
+
disabled: takedown !== undefined,
|
|
3103
|
+
...(takedown?.reason ? { disabledReason: takedown.reason } : {}),
|
|
2143
3104
|
// Def-level custom headers (non-secret metadata — the edit dialog
|
|
2144
3105
|
// prefills from this; secrets live in the bound store, never here).
|
|
2145
3106
|
headers: defNode?.headers ?? defNode?.options?.headers,
|
|
@@ -2148,14 +3109,21 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2148
3109
|
// wire-base chain (def baseURL > models.dev `api` > live service
|
|
2149
3110
|
// hint) so the card shows the SAME endpoint inference routes to.
|
|
2150
3111
|
baseURL: v.baseURL || u?.baseURL || u?.api,
|
|
3112
|
+
// Owning plugin id when the def was registered by a plugin preset —
|
|
3113
|
+
// the Connected tab mirrors the catalog's origin filter on it.
|
|
3114
|
+
pluginOrigin: origins[v.id],
|
|
2151
3115
|
priceFrom: u ? catalogRepository.minInputPrice(u) : undefined,
|
|
2152
3116
|
modelsCount: u?.models.length ?? v.models.length,
|
|
2153
3117
|
};
|
|
2154
3118
|
}),
|
|
2155
3119
|
};
|
|
2156
3120
|
},
|
|
2157
|
-
catalog: async () => {
|
|
3121
|
+
catalog: async (req) => {
|
|
3122
|
+
const lang = typeof req.query?.lang === 'string' ? req.query.lang : undefined;
|
|
2158
3123
|
const { catalogRepository } = await import('../opencode/catalog/repository.js');
|
|
3124
|
+
// Plugin-origin provenance for the console tag/filter — ledger join only,
|
|
3125
|
+
// never a field written into providers.json (ADR-0010).
|
|
3126
|
+
const origins = pluginProviderOrigins();
|
|
2159
3127
|
const unified = await catalogRepository.list();
|
|
2160
3128
|
// Trim model arrays from the list payload (detail endpoint can serve them later)
|
|
2161
3129
|
const providers = unified.map((p) => ({
|
|
@@ -2169,11 +3137,68 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2169
3137
|
env: p.env,
|
|
2170
3138
|
custom: p.custom,
|
|
2171
3139
|
connected: p.connected,
|
|
3140
|
+
// Plugin merges below may forward a preset's web-authorization
|
|
3141
|
+
// capability onto this row.
|
|
3142
|
+
webLogin: undefined,
|
|
3143
|
+
webLoginSubmit: undefined,
|
|
3144
|
+
authTypes: undefined,
|
|
3145
|
+
keyHint: undefined,
|
|
3146
|
+
// Owning plugin id when the def was registered by a plugin preset.
|
|
3147
|
+
pluginOrigin: origins[p.id],
|
|
2172
3148
|
sources: p.sources,
|
|
2173
3149
|
modelCount: p.models.length,
|
|
2174
3150
|
priceFrom: catalogRepository.minInputPrice(p),
|
|
2175
3151
|
}));
|
|
2176
|
-
|
|
3152
|
+
// Plugin presets join the connect catalog (logo + one-click credential),
|
|
3153
|
+
// deduped against repository entries that already carry the same id.
|
|
3154
|
+
// Pure config-source rows are dropped: a defs-file node is already fully
|
|
3155
|
+
// presented on the Connected tab — the connect catalog is a DISCOVERY
|
|
3156
|
+
// surface (remote catalog sources + plugin presets), not a mirror of the
|
|
3157
|
+
// operator's own declared relays.
|
|
3158
|
+
try {
|
|
3159
|
+
const { pluginPresetCatalogEntries } = await import('../plugins/host.js');
|
|
3160
|
+
for (const preset of await pluginPresetCatalogEntries(lang)) {
|
|
3161
|
+
const idx = providers.findIndex((p) => p.id === preset.id);
|
|
3162
|
+
if (idx >= 0) {
|
|
3163
|
+
const existing = providers[idx];
|
|
3164
|
+
if (preset.connected || existing.sources.some((s) => s !== 'config')) {
|
|
3165
|
+
// Connected preset: the config entry IS the live row (its models
|
|
3166
|
+
// ride along) — keep it, just attach the plugin logo if missing.
|
|
3167
|
+
// Catalog-covered preset: the catalog entry is the richer record.
|
|
3168
|
+
if (!existing.logo && preset.logo)
|
|
3169
|
+
existing.logo = preset.logo;
|
|
3170
|
+
existing.name = preset.name; // the stored def name is localeless — show the manifest's localized one
|
|
3171
|
+
// Forward the web-authorization capability, or the connect card
|
|
3172
|
+
// never offers the plugin's device-login button.
|
|
3173
|
+
existing.webLogin = preset.webLogin;
|
|
3174
|
+
existing.pluginOrigin = existing.pluginOrigin ?? origins[preset.id];
|
|
3175
|
+
existing.webLoginSubmit = preset.webLoginSubmit;
|
|
3176
|
+
existing.authTypes = preset.authTypes;
|
|
3177
|
+
existing.keyHint = preset.keyHint;
|
|
3178
|
+
// Tag the plugin origin, or the trailing pure-config-source drop
|
|
3179
|
+
// below removes the row we just decided to keep.
|
|
3180
|
+
if (!existing.sources.includes('service'))
|
|
3181
|
+
existing.sources = [...existing.sources, 'service'];
|
|
3182
|
+
continue;
|
|
3183
|
+
}
|
|
3184
|
+
// Unconnected preset materialized only as a pure config-source row
|
|
3185
|
+
// (syncPluginPresets upserts the def at install): swap in the
|
|
3186
|
+
// preset row — plugin logo, displayName, connectable via the
|
|
3187
|
+
// preset's own baseURL/npm.
|
|
3188
|
+
providers.splice(idx, 1);
|
|
3189
|
+
}
|
|
3190
|
+
providers.push({ id: preset.id, name: preset.name, logo: preset.logo, npm: preset.npm, api: undefined, baseURL: preset.baseURL, doc: undefined, env: undefined, custom: preset.custom, connected: preset.connected, webLogin: preset.webLogin, webLoginSubmit: preset.webLoginSubmit, authTypes: preset.authTypes, keyHint: preset.keyHint, pluginOrigin: origins[preset.id], sources: preset.sources, modelCount: 0, priceFrom: undefined });
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
catch {
|
|
3194
|
+
// catalog must survive a broken plugin host
|
|
3195
|
+
}
|
|
3196
|
+
// Pure config-source rows are dropped: a self-declared defs node is
|
|
3197
|
+
// already fully presented on the Connected tab — the connect catalog is
|
|
3198
|
+
// a DISCOVERY surface (remote catalog sources + plugin presets), not a
|
|
3199
|
+
// mirror of the operator's own declared relays.
|
|
3200
|
+
const connectable = providers.filter((p) => !(p.sources.length === 1 && p.sources[0] === 'config'));
|
|
3201
|
+
return { status: 'ok', source: catalogRepository.lastSyncOrigin, providers: connectable };
|
|
2177
3202
|
},
|
|
2178
3203
|
/** Flat model view across providers. `?maintained=1` narrows it to the
|
|
2179
3204
|
* physical models a defs node actually maintains (the /models page
|
|
@@ -2190,6 +3215,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2190
3215
|
// Raw file read once — the aggregate is already built from the normalized
|
|
2191
3216
|
// view, so a retired-shape node here contributes no rows anyway.
|
|
2192
3217
|
const rawNodes = readProviderDefsFile()?.providers ?? {};
|
|
3218
|
+
const takedowns = getProviderTakedownStore();
|
|
2193
3219
|
const nodeModels = (pid) => {
|
|
2194
3220
|
const node = rawNodes[pid];
|
|
2195
3221
|
const models = node && typeof node === 'object' ? node.models : undefined;
|
|
@@ -2209,6 +3235,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2209
3235
|
logo: p.logo,
|
|
2210
3236
|
custom: p.custom,
|
|
2211
3237
|
connected: p.connected,
|
|
3238
|
+
// Provider-level takedown: the row stays on the maintenance page
|
|
3239
|
+
// (aggregate truth), but the badge says it cannot route.
|
|
3240
|
+
providerDisabled: takedowns.isDisabled(p.id),
|
|
2212
3241
|
maintained: Object.prototype.hasOwnProperty.call(defs, m.id),
|
|
2213
3242
|
}))
|
|
2214
3243
|
.filter((m) => !maintainedOnly || m.maintained);
|
|
@@ -2228,22 +3257,34 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2228
3257
|
// namespace (the form normalizes input live; direct API callers get the
|
|
2229
3258
|
// rule stated back). Also keeps the catalog-shadow guard below exact:
|
|
2230
3259
|
// 'OpenAI' can no longer bypass a covered 'openai' id.
|
|
2231
|
-
const { isValidProviderId, PROVIDER_ID_RULE, upsertProviderDef, getProviderNodeById } = await import('../opencode/user-config.js');
|
|
3260
|
+
const { isValidProviderId, PROVIDER_ID_RULE, upsertProviderDef, getProviderNodeById, expandEnvTemplate } = await import('../opencode/user-config.js');
|
|
2232
3261
|
if (!isValidProviderId(id)) {
|
|
2233
3262
|
return reply.status(400).send({
|
|
2234
3263
|
success: false,
|
|
2235
3264
|
error: `Invalid provider id '${id}' - ${PROVIDER_ID_RULE}`,
|
|
2236
3265
|
});
|
|
2237
3266
|
}
|
|
2238
|
-
//
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
3267
|
+
// Upstream URL admission (self-loop / metadata / insecure public http).
|
|
3268
|
+
if (body.baseURL) {
|
|
3269
|
+
try {
|
|
3270
|
+
const { assertAllowedUpstream } = await import('../utils/upstream-url-guard.js');
|
|
3271
|
+
const expandedBaseURL = expandEnvTemplate(String(body.baseURL)) || String(body.baseURL);
|
|
3272
|
+
assertAllowedUpstream(expandedBaseURL, loadConfig().port);
|
|
3273
|
+
}
|
|
3274
|
+
catch (err) {
|
|
3275
|
+
return reply.status(409).send({
|
|
3276
|
+
success: false,
|
|
3277
|
+
reasonCode: err?.reasonCode || 'invalid_upstream_url',
|
|
3278
|
+
error: err?.message || String(err),
|
|
3279
|
+
});
|
|
3280
|
+
}
|
|
3281
|
+
}
|
|
3282
|
+
// ADR-0006: credentials live in the bound store, never inline in defs.
|
|
3283
|
+
if (body.apiKeyInline) {
|
|
3284
|
+
return reply.status(400).send({
|
|
2245
3285
|
success: false,
|
|
2246
|
-
|
|
3286
|
+
reasonCode: 'api_key_inline_forbidden',
|
|
3287
|
+
error: 'apiKeyInline is disabled — connect the key through the bound credential store.',
|
|
2247
3288
|
});
|
|
2248
3289
|
}
|
|
2249
3290
|
// An id covered by the remote catalog (opencode / models-dev) may NOT be
|
|
@@ -2301,7 +3342,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2301
3342
|
let keyMeta;
|
|
2302
3343
|
if (keyToStore) {
|
|
2303
3344
|
try {
|
|
2304
|
-
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager())).credential;
|
|
3345
|
+
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager(), registry)).credential;
|
|
2305
3346
|
}
|
|
2306
3347
|
catch (err) {
|
|
2307
3348
|
// Roll back only a node THIS request created — with ONE exception: the
|
|
@@ -2351,20 +3392,32 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2351
3392
|
update: async (req, reply) => {
|
|
2352
3393
|
const { id } = req.params;
|
|
2353
3394
|
const body = req.body;
|
|
2354
|
-
const { upsertProviderDef, getProviderNodeById } = await import('../opencode/user-config.js');
|
|
3395
|
+
const { upsertProviderDef, getProviderNodeById, expandEnvTemplate } = await import('../opencode/user-config.js');
|
|
2355
3396
|
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
2356
3397
|
const existing = getProviderNodeById(id);
|
|
2357
3398
|
if (!existing) {
|
|
2358
3399
|
return reply.status(404).send({ success: false, error: `Provider '${id}' not found in the provider defs file` });
|
|
2359
3400
|
}
|
|
2360
|
-
// Same door-guard as create: an update may SET a baseURL — or keep the
|
|
2361
|
-
// existing one — pointing at the gateway itself. The fallback mirrors
|
|
2362
|
-
// the upsert's `body.baseURL ?? existing.options?.baseURL` below.
|
|
2363
3401
|
const effectiveBaseURL = body.baseURL ?? existing.options?.baseURL ?? '';
|
|
2364
|
-
if (
|
|
2365
|
-
|
|
3402
|
+
if (effectiveBaseURL) {
|
|
3403
|
+
try {
|
|
3404
|
+
const { assertAllowedUpstream } = await import('../utils/upstream-url-guard.js');
|
|
3405
|
+
const expandedBaseURL = expandEnvTemplate(String(effectiveBaseURL)) || String(effectiveBaseURL);
|
|
3406
|
+
assertAllowedUpstream(expandedBaseURL, loadConfig().port);
|
|
3407
|
+
}
|
|
3408
|
+
catch (err) {
|
|
3409
|
+
return reply.status(409).send({
|
|
3410
|
+
success: false,
|
|
3411
|
+
reasonCode: err?.reasonCode || 'invalid_upstream_url',
|
|
3412
|
+
error: err?.message || String(err),
|
|
3413
|
+
});
|
|
3414
|
+
}
|
|
3415
|
+
}
|
|
3416
|
+
if (body.apiKeyInline === true) {
|
|
3417
|
+
return reply.status(400).send({
|
|
2366
3418
|
success: false,
|
|
2367
|
-
|
|
3419
|
+
reasonCode: 'api_key_inline_forbidden',
|
|
3420
|
+
error: 'apiKeyInline is disabled — connect the key through the bound credential store.',
|
|
2368
3421
|
});
|
|
2369
3422
|
}
|
|
2370
3423
|
// B4: same implicit auth.json side-write as create (apiKey + !inline) —
|
|
@@ -2376,7 +3429,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2376
3429
|
let keyMeta;
|
|
2377
3430
|
if (keyToStore) {
|
|
2378
3431
|
try {
|
|
2379
|
-
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager())).credential;
|
|
3432
|
+
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager(), registry)).credential;
|
|
2380
3433
|
}
|
|
2381
3434
|
catch (err) {
|
|
2382
3435
|
const failure = await mapStoreWriteFailure(err);
|
|
@@ -2435,7 +3488,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2435
3488
|
// A WriteFailedError maps to 5xx and NEVER falls back to OcrStore
|
|
2436
3489
|
// (Decision 3: read degrades with a badge, write refuses).
|
|
2437
3490
|
const store = await getCredentialStore();
|
|
2438
|
-
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager());
|
|
3491
|
+
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
2439
3492
|
// Optional baseURL override — merge with the existing definition so we
|
|
2440
3493
|
// never wipe name/npm/models of a config-defined custom provider.
|
|
2441
3494
|
// No apiKey field → no implicit credential write on any binding.
|
|
@@ -2496,6 +3549,133 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2496
3549
|
return reply.status(400).send({ success: false, error: err.message });
|
|
2497
3550
|
}
|
|
2498
3551
|
},
|
|
3552
|
+
/** Connect a preset whose plugin owns login. Materializes the def and
|
|
3553
|
+
* lifts a deletion tombstone. Refuses a provider that still takes a key. */
|
|
3554
|
+
connectLocal: async (req, reply) => {
|
|
3555
|
+
const { id } = req.params;
|
|
3556
|
+
const { providerDeclinesCredentials, ensurePresetProvider } = await import('../plugins/host.js');
|
|
3557
|
+
if (!providerDeclinesCredentials(id)) {
|
|
3558
|
+
return reply.status(400).send({ success: false, error: `Provider '${id}' takes a credential` });
|
|
3559
|
+
}
|
|
3560
|
+
if (!(await ensurePresetProvider(id))) {
|
|
3561
|
+
return reply.status(404).send({ success: false, error: `Provider '${id}' is not a plugin preset` });
|
|
3562
|
+
}
|
|
3563
|
+
return { status: 'ok', success: true, connected: true };
|
|
3564
|
+
},
|
|
3565
|
+
/** Resolve the model-service plugin serving a provider def's wire
|
|
3566
|
+
* (plugin wires only — the vendor protocol stays in the plugin). */
|
|
3567
|
+
webLoginPluginFor: async (id) => {
|
|
3568
|
+
const { getProviderNodeById } = await import('../opencode/user-config.js');
|
|
3569
|
+
const { wireFor } = await import('../providers/wire.js');
|
|
3570
|
+
let def = getProviderNodeById(id);
|
|
3571
|
+
if (!def) {
|
|
3572
|
+
// The catalog row comes from the manifest, so the login button stays
|
|
3573
|
+
// offered even for a provider the operator deleted. A click IS connect
|
|
3574
|
+
// intent: materialize the preset (and lift its deletion tombstone).
|
|
3575
|
+
const { ensurePresetProvider } = await import('../plugins/host.js');
|
|
3576
|
+
if (await ensurePresetProvider(id))
|
|
3577
|
+
def = getProviderNodeById(id);
|
|
3578
|
+
}
|
|
3579
|
+
if (!def)
|
|
3580
|
+
return { error: `provider '${id}' not found` };
|
|
3581
|
+
const node = def;
|
|
3582
|
+
const baseURL = (node.options?.baseURL ?? node.baseURL ?? '').replace(/\/+$/, '');
|
|
3583
|
+
const npm = node.npm || node.package || '';
|
|
3584
|
+
const wire = npm ? wireFor(npm) : baseURL ? wireFor(undefined, baseURL) : 'unroutable';
|
|
3585
|
+
const plugin = (await import('../plugins/host.js')).getModelServicePlugin(wire);
|
|
3586
|
+
if (!plugin?.webLogin) {
|
|
3587
|
+
return { error: `provider '${id}' is not on a plugin wire with a web-login capability` };
|
|
3588
|
+
}
|
|
3589
|
+
return { plugin, baseURL };
|
|
3590
|
+
},
|
|
3591
|
+
webLoginStart: async (req, reply) => {
|
|
3592
|
+
const { id } = req.params;
|
|
3593
|
+
const r = await ocHandlers.webLoginPluginFor(id);
|
|
3594
|
+
if ('error' in r)
|
|
3595
|
+
return reply.code(404).send({ success: false, error: r.error });
|
|
3596
|
+
try {
|
|
3597
|
+
// `provider: id` lets the plugin hand this call to `host.fetch` and have
|
|
3598
|
+
// the operator's proxy split govern sign-in too (ADR-0022).
|
|
3599
|
+
const { authUrl } = await r.plugin.webLogin.start({ baseURL: r.baseURL, provider: id });
|
|
3600
|
+
return { status: 'ok', authUrl };
|
|
3601
|
+
}
|
|
3602
|
+
catch (err) {
|
|
3603
|
+
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
3604
|
+
}
|
|
3605
|
+
},
|
|
3606
|
+
webLoginPoll: async (req, reply) => {
|
|
3607
|
+
const { id } = req.params;
|
|
3608
|
+
const r = await ocHandlers.webLoginPluginFor(id);
|
|
3609
|
+
if ('error' in r)
|
|
3610
|
+
return reply.code(404).send({ success: false, error: r.error });
|
|
3611
|
+
try {
|
|
3612
|
+
const result = await r.plugin.webLogin.poll({ baseURL: r.baseURL, provider: id });
|
|
3613
|
+
if (!result.done) {
|
|
3614
|
+
return { status: 'ok', done: false, error: result.error };
|
|
3615
|
+
}
|
|
3616
|
+
// Login finished — wire the fresh token into the credential store
|
|
3617
|
+
// (same write path as a manual connect), then connect-time model
|
|
3618
|
+
// auto-fill so the card shows as connected with models.
|
|
3619
|
+
if (!result.token) {
|
|
3620
|
+
return { status: 'ok', done: true, connected: false, error: 'login finished without a token' };
|
|
3621
|
+
}
|
|
3622
|
+
const credentialStore = await (await import('../opencode/credentials/index.js')).getCredentialStore();
|
|
3623
|
+
const { credential: keyMeta } = await connectKeyIdempotent(credentialStore, id, result.token, undefined, registry.getCircuitBreakerManager(), registry);
|
|
3624
|
+
const { ensureConnectedProviderBook } = await import('../opencode/catalog/auto-pull.js');
|
|
3625
|
+
const fill = await ensureConnectedProviderBook(id, { baseURL: r.baseURL }).catch((e) => ({
|
|
3626
|
+
nodeCreated: false,
|
|
3627
|
+
pulled: 0,
|
|
3628
|
+
fillError: String(e?.message ?? e),
|
|
3629
|
+
}));
|
|
3630
|
+
if (fill.fillError) {
|
|
3631
|
+
app.log.warn({ providerId: id, fillError: fill.fillError }, 'web-login connect-time model auto-fill failed (swallowed by design)');
|
|
3632
|
+
}
|
|
3633
|
+
return { status: 'ok', done: true, connected: true, credential: keyMeta };
|
|
3634
|
+
}
|
|
3635
|
+
catch (err) {
|
|
3636
|
+
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
3637
|
+
}
|
|
3638
|
+
},
|
|
3639
|
+
webLoginSubmit: async (req, reply) => {
|
|
3640
|
+
const { id } = req.params;
|
|
3641
|
+
const code = String((req.body || {}).code ?? '').trim();
|
|
3642
|
+
if (!code)
|
|
3643
|
+
return reply.code(400).send({ success: false, error: 'missing code' });
|
|
3644
|
+
const r = await ocHandlers.webLoginPluginFor(id);
|
|
3645
|
+
if ('error' in r)
|
|
3646
|
+
return reply.code(404).send({ success: false, error: r.error });
|
|
3647
|
+
if (!r.plugin.webLogin.submit) {
|
|
3648
|
+
return reply.code(404).send({ success: false, error: `provider '${id}' web-login has no manual token submission` });
|
|
3649
|
+
}
|
|
3650
|
+
try {
|
|
3651
|
+
const result = await r.plugin.webLogin.submit({ baseURL: r.baseURL, code, provider: id });
|
|
3652
|
+
if (!result.ok)
|
|
3653
|
+
return { status: 'ok', connected: false, error: result.error };
|
|
3654
|
+
// Same wiring as a finished poll: credential-store write + connect-time
|
|
3655
|
+
// model auto-fill so the card flips to connected. A submit that
|
|
3656
|
+
// consumed the code without returning a token is a plugin bug — refuse
|
|
3657
|
+
// to persist the (likely expired) raw code as the credential, exactly
|
|
3658
|
+
// like the poll path's 'login finished without a token' guard.
|
|
3659
|
+
if (!result.token) {
|
|
3660
|
+
return { status: 'ok', connected: false, error: 'submit finished without a token' };
|
|
3661
|
+
}
|
|
3662
|
+
const credentialStore = await (await import('../opencode/credentials/index.js')).getCredentialStore();
|
|
3663
|
+
const { credential: keyMeta } = await connectKeyIdempotent(credentialStore, id, result.token, undefined, registry.getCircuitBreakerManager(), registry);
|
|
3664
|
+
const { ensureConnectedProviderBook } = await import('../opencode/catalog/auto-pull.js');
|
|
3665
|
+
const fill = await ensureConnectedProviderBook(id, { baseURL: r.baseURL }).catch((e) => ({
|
|
3666
|
+
nodeCreated: false,
|
|
3667
|
+
pulled: 0,
|
|
3668
|
+
fillError: String(e?.message ?? e),
|
|
3669
|
+
}));
|
|
3670
|
+
if (fill.fillError) {
|
|
3671
|
+
app.log.warn({ providerId: id, fillError: fill.fillError }, 'web-login submit connect-time model auto-fill failed (swallowed by design)');
|
|
3672
|
+
}
|
|
3673
|
+
return { status: 'ok', connected: true, credential: keyMeta };
|
|
3674
|
+
}
|
|
3675
|
+
catch (err) {
|
|
3676
|
+
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
3677
|
+
}
|
|
3678
|
+
},
|
|
2499
3679
|
/**
|
|
2500
3680
|
* One-shot upstream connectivity probe behind the console "Test" buttons.
|
|
2501
3681
|
* Resolves baseURL/key/model from body overrides (test-before-save) or
|
|
@@ -2515,7 +3695,16 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2515
3695
|
// upstream probe header (its whole purpose), never in the response.
|
|
2516
3696
|
// Inline {env:VAR}/options.apiKey keep priority ABOVE the store (Decision 1).
|
|
2517
3697
|
const store = await getCredentialStore();
|
|
2518
|
-
|
|
3698
|
+
// Provider-level probes honor the operator takedown overlay: a disabled
|
|
3699
|
+
// credential is parked from routing, so probing with it would report a
|
|
3700
|
+
// provider as healthy while inference refuses that key. The store does
|
|
3701
|
+
// not carry the flag (it lives in the breaker state store's overlay), so
|
|
3702
|
+
// the chain is filtered with the same keyHashPrefix identity routing
|
|
3703
|
+
// uses — and probed IN ORDER below (first key that answers wins). An
|
|
3704
|
+
// addressed credentialId below deliberately bypasses this.
|
|
3705
|
+
const credentialState = registry.getCircuitBreakerManager().getCredentialStateStore();
|
|
3706
|
+
const storeChain = store.resolveKeyChain(id);
|
|
3707
|
+
const enabledChain = storeChain.filter((c) => c.key && !credentialState.isDisabled(id, keyHashPrefix(c.key)));
|
|
2519
3708
|
// Per-credential probe: the operator pinned ONE credential row (KeysPage
|
|
2520
3709
|
// credential list). resolveKeyChain is a sanctioned raw read on this route
|
|
2521
3710
|
// — same contract as resolveKey above: the key leaves only as the
|
|
@@ -2585,55 +3774,168 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2585
3774
|
if (modelCandidates.length === 0) {
|
|
2586
3775
|
return reply.status(400).send({ success: false, reasonCode: 'no_testable_model', provider: id });
|
|
2587
3776
|
}
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
3777
|
+
const inlineKey = expandEnvTemplate(def?.options?.apiKey);
|
|
3778
|
+
const probeAttempts = [];
|
|
3779
|
+
if (addressed) {
|
|
3780
|
+
probeAttempts.push({ key: addressed.key, credentialId: addressed.credentialId });
|
|
3781
|
+
}
|
|
3782
|
+
else if (body.apiKey) {
|
|
3783
|
+
probeAttempts.push({ key: body.apiKey });
|
|
3784
|
+
}
|
|
3785
|
+
else if (inlineKey) {
|
|
3786
|
+
probeAttempts.push({ key: inlineKey });
|
|
3787
|
+
}
|
|
3788
|
+
else {
|
|
3789
|
+
for (const c of enabledChain)
|
|
3790
|
+
probeAttempts.push({ key: c.key, credentialId: c.credentialId });
|
|
3791
|
+
}
|
|
3792
|
+
if (probeAttempts.length === 0) {
|
|
3793
|
+
// `none` owns login outside the credential store. One empty attempt
|
|
3794
|
+
// lets the plugin probe run; a missing key is not a failure.
|
|
3795
|
+
const { providerDeclinesCredentials } = await import('../plugins/host.js');
|
|
3796
|
+
if (providerDeclinesCredentials(id))
|
|
3797
|
+
probeAttempts.push({ key: '' });
|
|
3798
|
+
}
|
|
3799
|
+
if (probeAttempts.length === 0) {
|
|
3800
|
+
// Every stored key parked: say THAT, not the misleading no-key/OAuth
|
|
3801
|
+
// hint (the operator must know a takedown is the cause). Reaching this
|
|
3802
|
+
// point already proves there is no addressed row, no request-body key,
|
|
3803
|
+
// no inline key and no enabled store row — the disabled chain is the
|
|
3804
|
+
// only thing left to explain.
|
|
3805
|
+
if (storeChain.some((c) => c.key)) {
|
|
3806
|
+
return reply.status(400).send({
|
|
3807
|
+
success: false,
|
|
3808
|
+
reasonCode: 'no_enabled_credential',
|
|
3809
|
+
provider: id,
|
|
3810
|
+
error: `Every credential stored for '${id}' is disabled — enable one before testing.`,
|
|
3811
|
+
});
|
|
3812
|
+
}
|
|
2596
3813
|
return reply.status(400).send({
|
|
2597
3814
|
success: false,
|
|
2598
3815
|
oauthHint: true,
|
|
2599
3816
|
error: `No API key for '${id}' (credential store or inline). For OAuth-based providers run: opencode auth login ${id}`,
|
|
2600
3817
|
});
|
|
2601
3818
|
}
|
|
2602
|
-
//
|
|
2603
|
-
//
|
|
2604
|
-
|
|
3819
|
+
// Security S-03: refuse request-body baseURL overrides — a caller with
|
|
3820
|
+
// only a credentialId could otherwise exfiltrate the stored key to an
|
|
3821
|
+
// attacker URL. Test hits the same URL inference uses.
|
|
3822
|
+
if (body.baseURL) {
|
|
3823
|
+
return reply.status(400).send({
|
|
3824
|
+
success: false,
|
|
3825
|
+
reasonCode: 'base_url_override_forbidden',
|
|
3826
|
+
provider: id,
|
|
3827
|
+
error: 'body.baseURL is not accepted on test; configure the provider def (or catalog) baseURL instead.',
|
|
3828
|
+
});
|
|
3829
|
+
}
|
|
3830
|
+
const rawBaseURL = def?.options?.baseURL || cat?.api || cat?.baseURL;
|
|
3831
|
+
const baseURL = rawBaseURL ? expandEnvTemplate(String(rawBaseURL)) || String(rawBaseURL) : '';
|
|
2605
3832
|
if (!baseURL) {
|
|
2606
3833
|
return reply.status(400).send({ success: false, reasonCode: 'no_base_url', provider: id });
|
|
2607
3834
|
}
|
|
3835
|
+
try {
|
|
3836
|
+
const { assertAllowedUpstream } = await import('../utils/upstream-url-guard.js');
|
|
3837
|
+
assertAllowedUpstream(String(baseURL), loadConfig().port);
|
|
3838
|
+
}
|
|
3839
|
+
catch (err) {
|
|
3840
|
+
return reply.status(400).send({
|
|
3841
|
+
success: false,
|
|
3842
|
+
reasonCode: err?.reasonCode || 'invalid_upstream_url',
|
|
3843
|
+
provider: id,
|
|
3844
|
+
error: err?.message || String(err),
|
|
3845
|
+
});
|
|
3846
|
+
}
|
|
2608
3847
|
const { probeProvider, probeKindFor } = await import('../opencode/probe.js');
|
|
3848
|
+
// The verdict's egress (ADR-0018 / ADR-0022 vocabulary) is taken from the
|
|
3849
|
+
// attempt that produced it and rides on the reply, so "Test" answers "did
|
|
3850
|
+
// my model-scoped split apply" — the include/exclude page can only state
|
|
3851
|
+
// intent, never what this provider actually dialed.
|
|
3852
|
+
let egress;
|
|
3853
|
+
let egressProxy;
|
|
2609
3854
|
const { baseForWire } = await import('../providers/wire.js');
|
|
2610
3855
|
const { sanitizeExtraHeaders } = await import('../utils/http-headers.js');
|
|
2611
|
-
//
|
|
2612
|
-
//
|
|
2613
|
-
//
|
|
2614
|
-
//
|
|
3856
|
+
// Two nested rotation loops, both stopping on one green:
|
|
3857
|
+
// · models — a MODEL-SCOPED failure (upstream ANSWERED and rejected
|
|
3858
|
+
// only that model) advances to the next candidate model;
|
|
3859
|
+
// · credentials — the rotation the operator asked for: a key that is
|
|
3860
|
+
// revoked (401/403) or out of quota (429) says nothing about its
|
|
3861
|
+
// siblings, so the next credential takes over and the model list
|
|
3862
|
+
// restarts from the top for it.
|
|
3863
|
+
// Only a MOUNT failure ends the probe early: transport errors, unroutable
|
|
3864
|
+
// packages, 5xx and HTML gateways are properties of the baseURL, which
|
|
3865
|
+
// every credential of the provider shares — rotating would just repeat
|
|
3866
|
+
// the same error with a different key attached.
|
|
2615
3867
|
let result;
|
|
2616
3868
|
const tried = [];
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
3869
|
+
const triedCredentialIds = [];
|
|
3870
|
+
let answered;
|
|
3871
|
+
probes: for (const attempt of probeAttempts) {
|
|
3872
|
+
if (attempt.credentialId)
|
|
3873
|
+
triedCredentialIds.push(attempt.credentialId);
|
|
3874
|
+
// Tracks the row the FINAL verdict belongs to: reassigned per attempt,
|
|
3875
|
+
// so a green probe is credited to the key that answered while an
|
|
3876
|
+
// all-red one is credited to the key tried last.
|
|
3877
|
+
answered = attempt;
|
|
3878
|
+
for (const modelId of modelCandidates) {
|
|
3879
|
+
if (!tried.includes(modelId))
|
|
3880
|
+
tried.push(modelId);
|
|
3881
|
+
// Model-level npm override (e.g. Zen gpt-6-luna → @ai-sdk/openai =
|
|
3882
|
+
// Responses API) beats provider-level npm when picking the wire shape.
|
|
3883
|
+
const modelNpm = cat?.models.find((mm) => mm.id === modelId)?.npm;
|
|
3884
|
+
const kind = probeKindFor(cat?.api, modelNpm || def?.npm || cat?.npm);
|
|
3885
|
+
// The model's own capability flags, read from the def the console
|
|
3886
|
+
// holds — a plugin probe builds a REAL request, so guessing
|
|
3887
|
+
// "not a reasoning model" makes it send thinking-off to a model that
|
|
3888
|
+
// always thinks and report 400 for a model inference serves fine.
|
|
3889
|
+
const modelDef = defs?.[modelId];
|
|
3890
|
+
const catModel = cat?.models.find((mm) => mm.id === modelId);
|
|
3891
|
+
result = await probeProvider({
|
|
3892
|
+
baseURL: baseForWire(kind, baseURL),
|
|
3893
|
+
apiKey: attempt.key,
|
|
3894
|
+
model: modelId,
|
|
3895
|
+
provider: id,
|
|
3896
|
+
kind,
|
|
3897
|
+
capabilities: {
|
|
3898
|
+
reasoning: modelDef?.reasoning === true || Array.isArray(modelDef?.reasoningOptions) && modelDef.reasoningOptions.length > 0 || catModel?.reasoning === true,
|
|
3899
|
+
vision: modelDef?.attachment === true || catModel?.modalities?.input?.includes('image') === true,
|
|
3900
|
+
},
|
|
3901
|
+
headers: sanitizeExtraHeaders(def?.options?.headers
|
|
3902
|
+
? Object.fromEntries(Object.entries(def.options.headers).map(([k, v]) => [k, expandEnvTemplate(String(v))]))
|
|
3903
|
+
: undefined),
|
|
3904
|
+
});
|
|
3905
|
+
// Stamp the egress the MOMENT the probe answers, before any break:
|
|
3906
|
+
// `break probes` (a green verdict, or a mount failure) skips the rest
|
|
3907
|
+
// of the loop body, and the operator's question — did MY split apply
|
|
3908
|
+
// to this call — must be answered on success too, not only when the
|
|
3909
|
+
// rotation happens to fall through. Assign UNCONDITIONALLY: the
|
|
3910
|
+
// verdict belongs to the attempt that produced it, so its egress is
|
|
3911
|
+
// the answer even when that attempt reports UNKNOWN (a pre-dial
|
|
3912
|
+
// failure) — keeping a prior attempt's stamp would describe a dial
|
|
3913
|
+
// the verdict never made (model rotation can switch the wire/baseURL).
|
|
3914
|
+
egress = result.egress;
|
|
3915
|
+
egressProxy = result.egressProxy;
|
|
3916
|
+
if (result.ok)
|
|
3917
|
+
break probes;
|
|
3918
|
+
// Key-scoped refusal → this key is done, hand over to the next one.
|
|
3919
|
+
if (result.hintCode === 'authFailed' || result.hintCode === 'rateLimited')
|
|
3920
|
+
break;
|
|
3921
|
+
// Reached the upstream and got refused for THIS model → another key
|
|
3922
|
+
// may have it open; anything else (transport, 5xx) is the mount's
|
|
3923
|
+
// problem, and a mount is shared by every key of the provider.
|
|
3924
|
+
if (!result.modelScoped)
|
|
3925
|
+
break probes;
|
|
3926
|
+
}
|
|
2633
3927
|
}
|
|
2634
|
-
// Masked echo of the
|
|
2635
|
-
//
|
|
2636
|
-
|
|
3928
|
+
// Masked echo of the row that produced the verdict (never raw material):
|
|
3929
|
+
// the row that ANSWERED on success, the row tried last on failure — the UI
|
|
3930
|
+
// can confirm WHICH credential the verdict belongs to, not just the
|
|
3931
|
+
// provider.
|
|
3932
|
+
const credentialMetas = store.listCredentials(id);
|
|
3933
|
+
const credentialMeta = answered?.credentialId
|
|
3934
|
+
? credentialMetas.find((a) => a.id === answered.credentialId)
|
|
3935
|
+
: undefined;
|
|
3936
|
+
const triedCredentials = triedCredentialIds
|
|
3937
|
+
.map((cid) => credentialMetas.find((a) => a.id === cid))
|
|
3938
|
+
.filter((a) => !!a);
|
|
2637
3939
|
return {
|
|
2638
3940
|
status: 'ok',
|
|
2639
3941
|
provider: id,
|
|
@@ -2641,7 +3943,10 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2641
3943
|
// Rotation evidence (machine data, localized by the console): which
|
|
2642
3944
|
// candidates were tried, in order. Only meaningful when > 1.
|
|
2643
3945
|
...(tried.length > 1 ? { triedModels: tried } : {}),
|
|
3946
|
+
...(triedCredentials.length > 1 ? { triedCredentials } : {}),
|
|
2644
3947
|
...(credentialMeta ? { credential: credentialMeta } : {}),
|
|
3948
|
+
...(egress ? { egress } : {}),
|
|
3949
|
+
...(egressProxy ? { egressProxy } : {}),
|
|
2645
3950
|
...result,
|
|
2646
3951
|
};
|
|
2647
3952
|
},
|
|
@@ -2658,7 +3963,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2658
3963
|
// same key is deduped, never doubled) and ocr writes the local file. No
|
|
2659
3964
|
// auth.json write exists on any binding.
|
|
2660
3965
|
const store = await getCredentialStore();
|
|
2661
|
-
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager());
|
|
3966
|
+
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
2662
3967
|
store.invalidate();
|
|
2663
3968
|
// Decision 6: a key rotation handed to the store is a reconnect — clear SUSPECT.
|
|
2664
3969
|
clearSuspectForCredential(registry.getCircuitBreakerManager(), id, keyMeta?.keyHashPrefix);
|
|
@@ -2693,9 +3998,16 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2693
3998
|
const result = deleteProviderDef(id);
|
|
2694
3999
|
if (!result.success)
|
|
2695
4000
|
return reply.status(400).send(result);
|
|
4001
|
+
// Delete is intent: without this, the next plugin reload/install sees
|
|
4002
|
+
// the preset's def missing and re-creates it (the row reappears on the
|
|
4003
|
+
// Connected surface). A surviving credential still re-creates a node
|
|
4004
|
+
// through the boot bind sweep — credential truth outranks the def.
|
|
4005
|
+
const { forgetProviderRegistration } = await import('../plugins/host.js');
|
|
4006
|
+
forgetProviderRegistration(id);
|
|
2696
4007
|
// Decision 8 double confirmation is enforced by the console UI
|
|
2697
4008
|
// (purgeAuth opt-in) — server-side the loop reports honestly.
|
|
2698
4009
|
const purge = purgeAuth ? await purgeProviderCredentials(store, id) : null;
|
|
4010
|
+
dropTakedownWhenProviderGone(id, store);
|
|
2699
4011
|
const outcome = purge ? purgeOutcomeMessage(purge, id, true) : null;
|
|
2700
4012
|
// Clean purge (or no purge requested): legacy response bytes kept.
|
|
2701
4013
|
// defRemoved is the runtime truth — the console success toast follows
|
|
@@ -2709,6 +4021,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2709
4021
|
// Credential-only entry: provider-wide disconnect = the UI-level
|
|
2710
4022
|
// credential loop (Decision 1), never a direct upstream-file edit.
|
|
2711
4023
|
const purge = await purgeProviderCredentials(store, id);
|
|
4024
|
+
dropTakedownWhenProviderGone(id, store);
|
|
2712
4025
|
return { status: 'ok', defRemoved: false, ...purgeOutcomeMessage(purge, id, false), purge };
|
|
2713
4026
|
}
|
|
2714
4027
|
catch (err) {
|
|
@@ -2859,15 +4172,24 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2859
4172
|
* Pull models into the provider's config definition. Data source is chosen
|
|
2860
4173
|
* automatically: providers with baseURL + credential are pulled LIVE from
|
|
2861
4174
|
* their own /v1/models (failures surface real errors); providers without a
|
|
2862
|
-
* usable baseURL/key fall back to the static merged catalog.
|
|
2863
|
-
*
|
|
4175
|
+
* usable baseURL/key fall back to the static merged catalog. Builtin
|
|
4176
|
+
* (first-party catalog) providers take the MERGED path — catalog sets the
|
|
4177
|
+
* metadata-authoritative base, a live /v1/models pass only tops up ids the
|
|
4178
|
+
* catalog lacks. The same engine powers the periodic auto-pull
|
|
4179
|
+
* (catalog.autoPullModels).
|
|
2864
4180
|
*/
|
|
2865
4181
|
modelsPull: async (req, reply) => {
|
|
2866
4182
|
const { id } = req.params;
|
|
2867
4183
|
const body = req.body;
|
|
2868
4184
|
const { autoPullProvider } = await import('../opencode/catalog/auto-pull.js');
|
|
2869
4185
|
const result = await autoPullProvider(id, body ?? {});
|
|
2870
|
-
|
|
4186
|
+
// withPoolSync keys on reply.sent. A dry run is a read-only preview and
|
|
4187
|
+
// must not rebuild the live registry; a real pull returns the body so
|
|
4188
|
+
// the wrapper can apply the new defs without a restart.
|
|
4189
|
+
if (body?.dryRun)
|
|
4190
|
+
return reply.status(result.httpStatus).send(result.body);
|
|
4191
|
+
reply.status(result.httpStatus);
|
|
4192
|
+
return result.body;
|
|
2871
4193
|
},
|
|
2872
4194
|
/** Clear models — whole node without a pattern, matching ids only with one. */
|
|
2873
4195
|
modelsClear: async (req, reply) => {
|
|
@@ -3002,6 +4324,11 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3002
4324
|
const cb = registry.getCircuitBreakerManager();
|
|
3003
4325
|
for (const k of result.write?.pushedKeys ?? [])
|
|
3004
4326
|
clearSuspectForCredential(cb, k.provider, k.keyHashPrefix);
|
|
4327
|
+
// A sync pull/import can land keys on MANY providers — refresh every
|
|
4328
|
+
// connected provider's runtime chain (cheap: one store read per provider).
|
|
4329
|
+
for (const o of store.credentialsOverview()) {
|
|
4330
|
+
await refreshProviderCredentialChain(registry, store, o.providerId);
|
|
4331
|
+
}
|
|
3005
4332
|
return { status: 'ok', direction, ...result };
|
|
3006
4333
|
}
|
|
3007
4334
|
catch (err) {
|
|
@@ -3013,26 +4340,93 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3013
4340
|
}
|
|
3014
4341
|
},
|
|
3015
4342
|
/**
|
|
3016
|
-
*
|
|
3017
|
-
*
|
|
3018
|
-
*
|
|
3019
|
-
*
|
|
3020
|
-
*
|
|
3021
|
-
*
|
|
3022
|
-
*
|
|
4343
|
+
* REORDER a provider's credential chain (the Keys page's drag/ordering
|
|
4344
|
+
* action; replaces the retired operator activate route — `store.activate`
|
|
4345
|
+
* stays the internal head primitive for sync/connect headPreserved).
|
|
4346
|
+
* Body: { ids: string[] } — a permutation of the provider's credential
|
|
4347
|
+
* ids; the default credential becomes ids[0]. Gated on capabilities.reorder
|
|
4348
|
+
* (Decision 1). Response mirrors the old activate reply: the head
|
|
4349
|
+
* credential plus the refreshed masked credential list so the UI
|
|
4350
|
+
* repaints without a second fetch.
|
|
3023
4351
|
*/
|
|
3024
|
-
|
|
4352
|
+
credentialReorder: async (req, reply) => {
|
|
4353
|
+
const { id } = req.params;
|
|
4354
|
+
const body = req.body;
|
|
4355
|
+
const ids = body?.ids;
|
|
4356
|
+
if (!Array.isArray(ids) || ids.length === 0 || ids.some((x) => typeof x !== 'string')) {
|
|
4357
|
+
return reply.status(400).send({
|
|
4358
|
+
status: 'error',
|
|
4359
|
+
success: false,
|
|
4360
|
+
reasonCode: 'invalid_ids',
|
|
4361
|
+
error: 'ids must be a non-empty array of credential id strings',
|
|
4362
|
+
});
|
|
4363
|
+
}
|
|
4364
|
+
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
4365
|
+
const store = await getCredentialStore();
|
|
4366
|
+
if (!store.capabilities.reorder)
|
|
4367
|
+
return reply.status(400).send(capabilityRefusalBody('reorder'));
|
|
4368
|
+
// Guard-light: verify the provider has rows before the store call (the
|
|
4369
|
+
// store's own reorder validates the id permutation and 404s unknown ids).
|
|
4370
|
+
try {
|
|
4371
|
+
if (store.listCredentials(id).length === 0) {
|
|
4372
|
+
return reply.status(404).send(credentialNotFoundBody(ids[0], id));
|
|
4373
|
+
}
|
|
4374
|
+
}
|
|
4375
|
+
catch (err) {
|
|
4376
|
+
const failure = await mapStoreWriteFailure(err);
|
|
4377
|
+
if (failure)
|
|
4378
|
+
return reply.status(failure.status).send({ status: 'error', ...failure.body });
|
|
4379
|
+
return reply.status(500).send({ status: 'error', success: false, error: errMessage(err) });
|
|
4380
|
+
}
|
|
4381
|
+
try {
|
|
4382
|
+
const reordered = await store.reorder(id, ids);
|
|
4383
|
+
store.invalidate(); // Decision 3: console action invalidates the store view
|
|
4384
|
+
// Reorder IS the chain order — swap the runtime chain so the new head
|
|
4385
|
+
// serves without a restart.
|
|
4386
|
+
await refreshProviderCredentialChain(registry, store, id);
|
|
4387
|
+
const credential = reordered[0];
|
|
4388
|
+
return { status: 'ok', success: true, credential, credentials: withCredentialHealth(id, store.listCredentials(id)) };
|
|
4389
|
+
}
|
|
4390
|
+
catch (err) {
|
|
4391
|
+
const failure = await mapCredentialWriteFailure(err, id, String(ids[0]));
|
|
4392
|
+
return reply.status(failure.status).send(failure.body);
|
|
4393
|
+
}
|
|
4394
|
+
},
|
|
4395
|
+
/**
|
|
4396
|
+
* SET the spread weight of ONE credential (operator lever for unequal
|
|
4397
|
+
* quotas: a credential weighing w occupies w slots of the deterministic
|
|
4398
|
+
* new-session spread). Body: { weight: number } — an INTEGER in
|
|
4399
|
+
* [1, CREDENTIAL_WEIGHT_MAX]; anything else is a 400 invalid_weight.
|
|
4400
|
+
* Gated on capabilities.weight (opencode v2 rows have no weight field and
|
|
4401
|
+
* refuse, exactly like reorder). The chain is hot-refreshed so the new
|
|
4402
|
+
* weight shapes the very next placement — no restart.
|
|
4403
|
+
*/
|
|
4404
|
+
credentialSetWeight: async (req, reply) => {
|
|
3025
4405
|
const { id, credentialId } = req.params;
|
|
4406
|
+
const body = req.body;
|
|
4407
|
+
const raw = body?.weight;
|
|
4408
|
+
const weight = typeof raw === 'number' && Number.isInteger(raw) ? raw : NaN;
|
|
4409
|
+
if (!Number.isFinite(weight) || weight < 1 || weight > CREDENTIAL_WEIGHT_MAX) {
|
|
4410
|
+
return reply.status(400).send({
|
|
4411
|
+
status: 'error',
|
|
4412
|
+
success: false,
|
|
4413
|
+
reasonCode: 'invalid_weight',
|
|
4414
|
+
error: `weight must be an integer between 1 and ${CREDENTIAL_WEIGHT_MAX}`,
|
|
4415
|
+
});
|
|
4416
|
+
}
|
|
3026
4417
|
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
3027
4418
|
const store = await getCredentialStore();
|
|
3028
|
-
if (!store.capabilities.
|
|
3029
|
-
return reply.status(400).send(capabilityRefusalBody('
|
|
4419
|
+
if (!store.capabilities.weight)
|
|
4420
|
+
return reply.status(400).send(capabilityRefusalBody('weight'));
|
|
3030
4421
|
const guard = await guardStoreCredential(store, id, credentialId);
|
|
3031
4422
|
if (!guard.ok)
|
|
3032
4423
|
return reply.status(guard.status).send(guard.body);
|
|
3033
4424
|
try {
|
|
3034
|
-
const credential = await store.
|
|
4425
|
+
const credential = await store.setWeight(credentialId, weight);
|
|
3035
4426
|
store.invalidate(); // Decision 3: console action invalidates the store view
|
|
4427
|
+
// The weight rides the runtime chain — swap it in so the next
|
|
4428
|
+
// new-session placement sees the new proportions immediately.
|
|
4429
|
+
await refreshProviderCredentialChain(registry, store, id);
|
|
3036
4430
|
return { status: 'ok', success: true, credential, credentials: withCredentialHealth(id, store.listCredentials(id)) };
|
|
3037
4431
|
}
|
|
3038
4432
|
catch (err) {
|
|
@@ -3112,7 +4506,11 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3112
4506
|
try {
|
|
3113
4507
|
await store.disconnect(credentialId);
|
|
3114
4508
|
store.invalidate();
|
|
4509
|
+
await refreshProviderCredentialChain(registry, store, id); // removed key must leave the live chain
|
|
3115
4510
|
clearSuspectForCredential(registry.getCircuitBreakerManager(), id, prefix);
|
|
4511
|
+
// The last credential of a def-less provider removes the row entirely;
|
|
4512
|
+
// a takedown must not outlive the thing it targeted.
|
|
4513
|
+
dropTakedownWhenProviderGone(id, store);
|
|
3116
4514
|
// DELETE is a REVOCATION, so it must be as durable as a takedown: anchor
|
|
3117
4515
|
// the key MATERIAL as disabled. Otherwise the read sync would re-import
|
|
3118
4516
|
// the key from the client as a clean, routable credential — the delete
|
|
@@ -3233,6 +4631,71 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3233
4631
|
return reply.status(failure.status).send(failure.body);
|
|
3234
4632
|
}
|
|
3235
4633
|
},
|
|
4634
|
+
/**
|
|
4635
|
+
* Operator DISABLE / ENABLE one WHOLE provider — the coarse counterpart of
|
|
4636
|
+
* the credential takedown below. The provider keeps its defs node, models,
|
|
4637
|
+
* credentials and console card; only the routing pool drops it
|
|
4638
|
+
* (`buildDirectPool` → `operator_disabled`), so `/v1/models` omits it and
|
|
4639
|
+
* direct ids 404. State lives in the GLOBAL takedown ledger, never in
|
|
4640
|
+
* providers.json (that file is connection truth + the sync materializer's
|
|
4641
|
+
* source, ADR-0010). Manual-only lifecycle: nothing auto-clears it.
|
|
4642
|
+
*/
|
|
4643
|
+
providerSetDisabled: async (req, reply, disabled) => {
|
|
4644
|
+
const { id } = req.params;
|
|
4645
|
+
const body = req.body ?? {};
|
|
4646
|
+
if (!isValidProviderId(id)) {
|
|
4647
|
+
return reply.status(400).send({
|
|
4648
|
+
status: 'error',
|
|
4649
|
+
success: false,
|
|
4650
|
+
reasonCode: 'invalid_provider_id',
|
|
4651
|
+
error: `Invalid provider id '${id}' - ${PROVIDER_ID_RULE}`,
|
|
4652
|
+
});
|
|
4653
|
+
}
|
|
4654
|
+
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
4655
|
+
const store = await getCredentialStore();
|
|
4656
|
+
let hasCredential = false;
|
|
4657
|
+
try {
|
|
4658
|
+
hasCredential = store.listCredentials(id).length > 0;
|
|
4659
|
+
}
|
|
4660
|
+
catch {
|
|
4661
|
+
// unreadable per-provider detail: a defs node still proves the provider exists
|
|
4662
|
+
}
|
|
4663
|
+
if (!getProviderNodeById(id) && !hasCredential) {
|
|
4664
|
+
return reply.status(404).send({
|
|
4665
|
+
status: 'error',
|
|
4666
|
+
success: false,
|
|
4667
|
+
reasonCode: 'provider_not_found',
|
|
4668
|
+
error: `Provider '${id}' is neither defined in providers.json nor connected with a credential`,
|
|
4669
|
+
});
|
|
4670
|
+
}
|
|
4671
|
+
const takedowns = getProviderTakedownStore();
|
|
4672
|
+
if (disabled) {
|
|
4673
|
+
const raw = typeof body.reason === 'string' ? body.reason.trim() : '';
|
|
4674
|
+
if (raw.length > 200) {
|
|
4675
|
+
return reply
|
|
4676
|
+
.status(400)
|
|
4677
|
+
.send({ status: 'error', success: false, reasonCode: 'invalid_reason', error: 'reason too long (max 200 characters)' });
|
|
4678
|
+
}
|
|
4679
|
+
takedowns.disable(id, raw);
|
|
4680
|
+
return {
|
|
4681
|
+
status: 'ok',
|
|
4682
|
+
success: true,
|
|
4683
|
+
disabled: true,
|
|
4684
|
+
provider: id,
|
|
4685
|
+
message: `Provider '${id}' taken down (no model routes through it)`,
|
|
4686
|
+
};
|
|
4687
|
+
}
|
|
4688
|
+
takedowns.enable(id);
|
|
4689
|
+
return {
|
|
4690
|
+
status: 'ok',
|
|
4691
|
+
success: true,
|
|
4692
|
+
disabled: false,
|
|
4693
|
+
provider: id,
|
|
4694
|
+
message: `Provider '${id}' restored to routing`,
|
|
4695
|
+
};
|
|
4696
|
+
},
|
|
4697
|
+
providerDisable: (req, reply) => ocHandlers.providerSetDisabled(req, reply, true),
|
|
4698
|
+
providerEnable: (req, reply) => ocHandlers.providerSetDisabled(req, reply, false),
|
|
3236
4699
|
/**
|
|
3237
4700
|
* Operator DISABLE / ENABLE one credential — a durable takedown that never
|
|
3238
4701
|
* auto-returns (cooldown expiry, reconnect, Push and breaker resets all leave
|
|
@@ -3301,34 +4764,310 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3301
4764
|
app.get(`${prefix}/credential-store`, ocHandlers.credentialStore);
|
|
3302
4765
|
app.get(`${prefix}/credential-sync`, ocHandlers.credentialSyncStatus);
|
|
3303
4766
|
app.post(`${prefix}/credential-sync/toggle`, ocHandlers.credentialSyncToggle);
|
|
3304
|
-
app.post(`${prefix}/credential-sync/run`, ocHandlers.credentialSyncRun);
|
|
3305
|
-
app.get(`${prefix}/opencode/
|
|
4767
|
+
app.post(`${prefix}/credential-sync/run`, withPoolSync(registry, ocHandlers.credentialSyncRun));
|
|
4768
|
+
app.get(`${prefix}/opencode/protocol-vocabulary`, ocHandlers.protocolVocabulary);
|
|
3306
4769
|
app.get(`${prefix}/opencode/providers`, ocHandlers.list);
|
|
3307
4770
|
app.get(`${prefix}/opencode/catalog`, ocHandlers.catalog);
|
|
3308
4771
|
app.get(`${prefix}/opencode/models`, ocHandlers.models);
|
|
3309
|
-
app.post(`${prefix}/opencode/providers`, ocHandlers.create);
|
|
3310
|
-
app.patch(`${prefix}/opencode/providers/:id`, ocHandlers.update);
|
|
3311
|
-
app.post(`${prefix}/opencode/providers/:id/connect`, ocHandlers.connect);
|
|
3312
|
-
app.post(`${prefix}/opencode/providers/:id/
|
|
4772
|
+
app.post(`${prefix}/opencode/providers`, withPoolSync(registry, ocHandlers.create));
|
|
4773
|
+
app.patch(`${prefix}/opencode/providers/:id`, withPoolSync(registry, ocHandlers.update));
|
|
4774
|
+
app.post(`${prefix}/opencode/providers/:id/connect`, withPoolSync(registry, ocHandlers.connect));
|
|
4775
|
+
app.post(`${prefix}/opencode/providers/:id/connect-local`, withPoolSync(registry, ocHandlers.connectLocal));
|
|
4776
|
+
// Generic plugin web-authorization seam (device flow): start opens the
|
|
4777
|
+
// vendor login page; poll returns done+token and wires the fresh token
|
|
4778
|
+
// into the credential store. The plugin owns the whole protocol.
|
|
4779
|
+
app.post(`${prefix}/opencode/providers/:id/web-login/start`, ocHandlers.webLoginStart);
|
|
4780
|
+
// Both terminal paths write the fresh credential into the store, so both
|
|
4781
|
+
// must trigger a credential re-sync (same contract as the key route).
|
|
4782
|
+
app.get(`${prefix}/opencode/providers/:id/web-login/poll`, withPoolSync(registry, ocHandlers.webLoginPoll));
|
|
4783
|
+
app.post(`${prefix}/opencode/providers/:id/web-login/submit`, withPoolSync(registry, ocHandlers.webLoginSubmit));
|
|
4784
|
+
app.post(`${prefix}/opencode/providers/:id/key`, withPoolSync(registry, ocHandlers.setKey));
|
|
3313
4785
|
app.post(`${prefix}/opencode/providers/:id/test`, ocHandlers.test);
|
|
3314
|
-
app.delete(`${prefix}/opencode/providers/:id`, ocHandlers.remove);
|
|
4786
|
+
app.delete(`${prefix}/opencode/providers/:id`, withPoolSync(registry, ocHandlers.remove));
|
|
4787
|
+
// Provider-level operator takedown: routing state, not a defs write — the
|
|
4788
|
+
// pool resync drops (or restores) every model of the provider (ADR-0010).
|
|
4789
|
+
app.post(`${prefix}/opencode/providers/:id/disable`, withPoolSync(registry, ocHandlers.providerDisable));
|
|
4790
|
+
app.post(`${prefix}/opencode/providers/:id/enable`, withPoolSync(registry, ocHandlers.providerEnable));
|
|
3315
4791
|
// Per-provider model maintenance (config-defined providers only)
|
|
3316
4792
|
app.get(`${prefix}/opencode/providers/:id/models`, ocHandlers.modelsGet);
|
|
3317
|
-
app.post(`${prefix}/opencode/providers/:id/models`, ocHandlers.modelAdd);
|
|
3318
|
-
app.patch(`${prefix}/opencode/providers/:id/models/:modelId`, ocHandlers.modelUpdate);
|
|
3319
|
-
app.delete(`${prefix}/opencode/providers/:id/models/:modelId`, ocHandlers.modelRemove);
|
|
3320
|
-
app.post(`${prefix}/opencode/providers/:id/models/pull`, ocHandlers.modelsPull);
|
|
3321
|
-
app.post(`${prefix}/opencode/providers/:id/models/reorder`, ocHandlers.modelReorder);
|
|
3322
|
-
app.post(`${prefix}/opencode/providers/:id/models/clear`, ocHandlers.modelsClear);
|
|
3323
|
-
//
|
|
4793
|
+
app.post(`${prefix}/opencode/providers/:id/models`, withPoolSync(registry, ocHandlers.modelAdd));
|
|
4794
|
+
app.patch(`${prefix}/opencode/providers/:id/models/:modelId`, withPoolSync(registry, ocHandlers.modelUpdate));
|
|
4795
|
+
app.delete(`${prefix}/opencode/providers/:id/models/:modelId`, withPoolSync(registry, ocHandlers.modelRemove));
|
|
4796
|
+
app.post(`${prefix}/opencode/providers/:id/models/pull`, withPoolSync(registry, ocHandlers.modelsPull));
|
|
4797
|
+
app.post(`${prefix}/opencode/providers/:id/models/reorder`, withPoolSync(registry, ocHandlers.modelReorder));
|
|
4798
|
+
app.post(`${prefix}/opencode/providers/:id/models/clear`, withPoolSync(registry, ocHandlers.modelsClear));
|
|
4799
|
+
// Plugin host: read-only views + hot reload of the plugin dir.
|
|
4800
|
+
app.get(`${prefix}/plugins`, async () => {
|
|
4801
|
+
// views only — a read route must not clear+rebuild the live registry
|
|
4802
|
+
// (in-flight dispatch/probe would see an empty plugin set mid-rebuild)
|
|
4803
|
+
const { listInstalledPlugins } = await import('../plugins/host.js');
|
|
4804
|
+
return { status: 'ok', plugins: listInstalledPlugins() };
|
|
4805
|
+
});
|
|
4806
|
+
app.post(`${prefix}/plugins/reload`, async () => {
|
|
4807
|
+
const { loadInstalledPlugins, syncPluginPresets, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4808
|
+
await loadInstalledPlugins();
|
|
4809
|
+
const plugins = listInstalledPlugins();
|
|
4810
|
+
const registered = await syncPluginPresets();
|
|
4811
|
+
await refreshDirectPool(registry);
|
|
4812
|
+
return { status: 'ok', plugins, registered };
|
|
4813
|
+
});
|
|
4814
|
+
// Upload-install: raw zip bytes (application/octet-stream), id in the query.
|
|
4815
|
+
app.get(`${prefix}/plugins/:id/logo`, async (req, reply) => {
|
|
4816
|
+
const { id } = req.params;
|
|
4817
|
+
const { pluginLogoFile } = await import('../plugins/host.js');
|
|
4818
|
+
const file = pluginLogoFile(id);
|
|
4819
|
+
if (!file)
|
|
4820
|
+
return reply.code(404).send({ status: 'error', error: 'no logo' });
|
|
4821
|
+
const ext = file.split('.').pop()?.toLowerCase();
|
|
4822
|
+
const mime = ext === 'png' ? 'image/png'
|
|
4823
|
+
: ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg'
|
|
4824
|
+
: ext === 'webp' ? 'image/webp'
|
|
4825
|
+
: ext === 'svg' ? 'image/svg+xml'
|
|
4826
|
+
: undefined;
|
|
4827
|
+
if (!mime)
|
|
4828
|
+
return reply.code(415).send({ status: 'error', error: 'unsupported logo format' });
|
|
4829
|
+
// Logos ship inside operator-installed packages: treat them as untrusted
|
|
4830
|
+
// content. SVG can carry scripts on direct navigation — lock it down;
|
|
4831
|
+
// buffered send also avoids the uninstall race between check and stream.
|
|
4832
|
+
reply.header('X-Content-Type-Options', 'nosniff');
|
|
4833
|
+
reply.header('Content-Security-Policy', "default-src 'none'");
|
|
4834
|
+
return reply.type(mime).send(await fs.promises.readFile(file));
|
|
4835
|
+
});
|
|
4836
|
+
// Package export: a packaged plugin returns its installed zip verbatim; a
|
|
4837
|
+
// dev-tree plugin is bundled and zipped on the fly with the same
|
|
4838
|
+
// deterministic packer `plugins:build` uses, so a download round-trips
|
|
4839
|
+
// through Install. A bundle failure is the operator's signal that the
|
|
4840
|
+
// plugin cannot be packaged self-contained — surface the reason.
|
|
4841
|
+
app.get(`${prefix}/plugins/:id/package`, async (req, reply) => {
|
|
4842
|
+
const { id } = req.params;
|
|
4843
|
+
let zip;
|
|
4844
|
+
try {
|
|
4845
|
+
zip = await pluginPackageZip(id);
|
|
4846
|
+
}
|
|
4847
|
+
catch (err) {
|
|
4848
|
+
return reply.code(500).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4849
|
+
}
|
|
4850
|
+
if (!zip)
|
|
4851
|
+
return reply.code(404).send({ status: 'error', error: 'unknown plugin or package not found' });
|
|
4852
|
+
if (zip.length > PLUGIN_PACKAGE_MAX_BYTES) {
|
|
4853
|
+
return reply.code(413).send({ status: 'error', error: 'package exceeds 64 MiB' });
|
|
4854
|
+
}
|
|
4855
|
+
// Operator-installed bytes: lock the response down (same rule as logo).
|
|
4856
|
+
reply.header('X-Content-Type-Options', 'nosniff');
|
|
4857
|
+
reply.header('Content-Disposition', `attachment; filename="${id}.zip"`);
|
|
4858
|
+
return reply.type('application/zip').send(Buffer.from(zip));
|
|
4859
|
+
});
|
|
4860
|
+
/**
|
|
4861
|
+
* Re-materialize every client model surface a gateway plugin owns.
|
|
4862
|
+
*
|
|
4863
|
+
* A gateway's catalog config (list mode, followed key ids) is persisted in
|
|
4864
|
+
* its own artifact, but the clients it feeds MATERIALIZE that list into
|
|
4865
|
+
* their own files — those must be rewritten on save, or the picker keeps
|
|
4866
|
+
* whatever it held at hook time. A failed refresh never fails the save (the
|
|
4867
|
+
* config is already persisted); it is reported next to the values instead.
|
|
4868
|
+
*/
|
|
4869
|
+
const refreshOwnedModelSurfaces = async (pluginId) => {
|
|
4870
|
+
const { getAllClientAdapters } = await import('../cli/clients/index.js');
|
|
4871
|
+
const rows = [];
|
|
4872
|
+
for (const adapter of getAllClientAdapters()) {
|
|
4873
|
+
if (adapter.catalogPlugin !== pluginId || !adapter.refreshModelSurface)
|
|
4874
|
+
continue;
|
|
4875
|
+
try {
|
|
4876
|
+
const result = await adapter.refreshModelSurface();
|
|
4877
|
+
rows.push({ client: adapter.name, ok: result.success, message: result.message });
|
|
4878
|
+
}
|
|
4879
|
+
catch (err) {
|
|
4880
|
+
rows.push({ client: adapter.name, ok: false, message: err instanceof Error ? err.message : String(err) });
|
|
4881
|
+
}
|
|
4882
|
+
}
|
|
4883
|
+
return rows;
|
|
4884
|
+
};
|
|
4885
|
+
// Plugin-level configuration (ADR-0017): schema declared in plugin.json,
|
|
4886
|
+
// values stored as a plugin artifact — never in config.yaml.
|
|
4887
|
+
app.get(`${prefix}/plugins/:id/config`, async (req, reply) => {
|
|
4888
|
+
const { id } = req.params;
|
|
4889
|
+
const { getPluginConfig } = await import('../plugins/host.js');
|
|
4890
|
+
const cfg = getPluginConfig(id);
|
|
4891
|
+
if (!cfg)
|
|
4892
|
+
return reply.code(404).send({ status: 'error', error: 'unknown or unloaded plugin' });
|
|
4893
|
+
return { status: 'ok', schema: cfg.schema, sections: cfg.sections, values: cfg.values };
|
|
4894
|
+
});
|
|
4895
|
+
app.put(`${prefix}/plugins/:id/config`, async (req, reply) => {
|
|
4896
|
+
const { id } = req.params;
|
|
4897
|
+
const body = (req.body ?? {});
|
|
4898
|
+
if (!body.values || typeof body.values !== 'object' || Array.isArray(body.values)) {
|
|
4899
|
+
return reply.code(400).send({ status: 'error', error: 'body.values must be an object' });
|
|
4900
|
+
}
|
|
4901
|
+
try {
|
|
4902
|
+
const { applyPluginConfig } = await import('../plugins/host.js');
|
|
4903
|
+
const result = await applyPluginConfig(id, body.values);
|
|
4904
|
+
const surfaces = await refreshOwnedModelSurfaces(id);
|
|
4905
|
+
return { status: 'ok', values: result.values, warnings: result.warnings, surfaces };
|
|
4906
|
+
}
|
|
4907
|
+
catch (err) {
|
|
4908
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
4909
|
+
// Unknown/unloaded plugin = 404 (same as GET); schema/value problems = 400.
|
|
4910
|
+
if (message === 'unknown or unloaded plugin')
|
|
4911
|
+
return reply.code(404).send({ status: 'error', error: message });
|
|
4912
|
+
return reply.code(400).send({ status: 'error', error: message });
|
|
4913
|
+
}
|
|
4914
|
+
});
|
|
4915
|
+
app.delete(`${prefix}/plugins/:id/uninstall`, async (req, reply) => {
|
|
4916
|
+
const { id } = req.params;
|
|
4917
|
+
try {
|
|
4918
|
+
const { uninstallPlugin, loadInstalledPlugins, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4919
|
+
const result = await uninstallPlugin(id);
|
|
4920
|
+
await loadInstalledPlugins();
|
|
4921
|
+
const plugins = listInstalledPlugins();
|
|
4922
|
+
await refreshDirectPool(registry);
|
|
4923
|
+
return { status: 'ok', removed: result.removed, providersRemoved: result.providersRemoved, plugins };
|
|
4924
|
+
}
|
|
4925
|
+
catch (err) {
|
|
4926
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4927
|
+
}
|
|
4928
|
+
});
|
|
4929
|
+
// Toggle a plugin without deleting anything (works for dev-tree plugins
|
|
4930
|
+
// too): disabled.json skips it at discovery; enable + reload restores it.
|
|
4931
|
+
app.post(`${prefix}/plugins/:id/disable`, async (req, reply) => {
|
|
4932
|
+
const { id } = req.params;
|
|
4933
|
+
try {
|
|
4934
|
+
const { setPluginDisabled, loadInstalledPlugins, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4935
|
+
const result = await setPluginDisabled(id, true);
|
|
4936
|
+
await loadInstalledPlugins();
|
|
4937
|
+
const plugins = listInstalledPlugins();
|
|
4938
|
+
await refreshDirectPool(registry);
|
|
4939
|
+
return { status: 'ok', providersRemoved: result.providersRemoved, plugins };
|
|
4940
|
+
}
|
|
4941
|
+
catch (err) {
|
|
4942
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4943
|
+
}
|
|
4944
|
+
});
|
|
4945
|
+
app.post(`${prefix}/plugins/:id/enable`, async (req, reply) => {
|
|
4946
|
+
const { id } = req.params;
|
|
4947
|
+
try {
|
|
4948
|
+
const { setPluginDisabled, loadInstalledPlugins, listInstalledPlugins, syncPluginPresets } = await import('../plugins/host.js');
|
|
4949
|
+
await setPluginDisabled(id, false);
|
|
4950
|
+
await loadInstalledPlugins();
|
|
4951
|
+
const plugins = listInstalledPlugins();
|
|
4952
|
+
const registered = await syncPluginPresets();
|
|
4953
|
+
await refreshDirectPool(registry);
|
|
4954
|
+
return { status: 'ok', registered, plugins };
|
|
4955
|
+
}
|
|
4956
|
+
catch (err) {
|
|
4957
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4958
|
+
}
|
|
4959
|
+
});
|
|
4960
|
+
app.post(`${prefix}/plugins/install`, { bodyLimit: PLUGIN_PACKAGE_MAX_BYTES }, async (req, reply) => {
|
|
4961
|
+
const body = req.body;
|
|
4962
|
+
const bytes = typeof body === 'string' ? Buffer.from(body, 'binary') : body;
|
|
4963
|
+
if (!bytes || bytes.length === 0) {
|
|
4964
|
+
return reply.code(400).send({ status: 'error', error: 'empty body — send the plugin zip as application/octet-stream' });
|
|
4965
|
+
}
|
|
4966
|
+
if (bytes.length > PLUGIN_PACKAGE_MAX_BYTES) {
|
|
4967
|
+
return reply.code(413).send({ status: 'error', error: 'package exceeds 64 MiB' });
|
|
4968
|
+
}
|
|
4969
|
+
try {
|
|
4970
|
+
const { installPluginPackage, packageIdOf, pluginPackageZip, listInstalledPlugins: listing } = await import('../plugins/host.js');
|
|
4971
|
+
// Snapshot the version this upload is about to REPLACE (a packaged one
|
|
4972
|
+
// — a dev-tree plugin is not ours to materialize here). A failed upgrade
|
|
4973
|
+
// must not delete a working install. `disabled` does NOT disqualify the
|
|
4974
|
+
// snapshot: a switched-off package is still an install the operator
|
|
4975
|
+
// owns, and a broken upload over it would otherwise leave them with
|
|
4976
|
+
// nothing to roll back to.
|
|
4977
|
+
let previous;
|
|
4978
|
+
try {
|
|
4979
|
+
const target = packageIdOf(new Uint8Array(bytes));
|
|
4980
|
+
const existing = listing().find((p) => p.id === target);
|
|
4981
|
+
if (existing?.source === 'packaged')
|
|
4982
|
+
previous = await pluginPackageZip(target);
|
|
4983
|
+
}
|
|
4984
|
+
catch {
|
|
4985
|
+
// unreadable upload: installPluginPackage below reports it properly
|
|
4986
|
+
}
|
|
4987
|
+
const { id: installed, version: installedVersion, replacedVersion } = installPluginPackage(new Uint8Array(bytes));
|
|
4988
|
+
const { loadInstalledPlugins, syncPluginPresets, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4989
|
+
await loadInstalledPlugins();
|
|
4990
|
+
const plugins = listInstalledPlugins();
|
|
4991
|
+
// An engine-INCOMPATIBLE package is not a broken one: it is on disk,
|
|
4992
|
+
// it is listed as disabled, and it becomes usable in place once the
|
|
4993
|
+
// matching side is updated. Discarding it would only make the operator
|
|
4994
|
+
// upload the same file again after that update, so the discard /
|
|
4995
|
+
// rollback path below stays reserved for packages that genuinely fail
|
|
4996
|
+
// to load. The test is the ROW'S OWN flag, never `disabled && !loaded`
|
|
4997
|
+
// — an operator-disabled package satisfies that shape too, and a
|
|
4998
|
+
// failed load of one must still be discarded and rolled back.
|
|
4999
|
+
//
|
|
5000
|
+
// An UPLOAD is normally refused before it ever lands
|
|
5001
|
+
// (`installPluginPackage` → `assertSupportedPluginApi`), so a 400 with
|
|
5002
|
+
// the core sentence is the common answer. This branch covers the case
|
|
5003
|
+
// that reaches the disk anyway (a package that became incompatible
|
|
5004
|
+
// under a downgraded gateway), where the refusal must be reported and
|
|
5005
|
+
// NOT followed by a discard.
|
|
5006
|
+
const view = plugins.find((p) => p.id === installed);
|
|
5007
|
+
const incompatible = view?.incompatible === true;
|
|
5008
|
+
if (!view?.loaded && !incompatible) {
|
|
5009
|
+
// a package that cannot load would re-fail every boot — discard it;
|
|
5010
|
+
// discard BEFORE preset sync / pool refresh so a broken package
|
|
5011
|
+
// registers nothing
|
|
5012
|
+
const { discardPluginPackage } = await import('../plugins/host.js');
|
|
5013
|
+
discardPluginPackage(installed);
|
|
5014
|
+
// Roll BACK to the version that was working until this upload, so a
|
|
5015
|
+
// bad upgrade is a no-op instead of a lost plugin.
|
|
5016
|
+
if (previous) {
|
|
5017
|
+
// A ROLLBACK is the one legitimate downgrade: the caller did not
|
|
5018
|
+
// ask for it, the loader did — the version guard exists for
|
|
5019
|
+
// uploads, and it must not block the recovery path.
|
|
5020
|
+
installPluginPackage(previous, { allowDowngrade: true });
|
|
5021
|
+
await loadInstalledPlugins();
|
|
5022
|
+
return reply.code(422).send({
|
|
5023
|
+
status: 'error',
|
|
5024
|
+
error: `package rejected and discarded (${view?.error ?? 'unknown error'}); rolled back to the previously installed version`,
|
|
5025
|
+
plugins: listInstalledPlugins(),
|
|
5026
|
+
});
|
|
5027
|
+
}
|
|
5028
|
+
// Reload AFTER the discard: otherwise the response would hand the
|
|
5029
|
+
// console a row for a package that is no longer on disk (the list is
|
|
5030
|
+
// the disk's truth, not the last failed import's).
|
|
5031
|
+
await loadInstalledPlugins();
|
|
5032
|
+
return reply
|
|
5033
|
+
.code(422)
|
|
5034
|
+
.send({ status: 'error', error: `package installed but failed to load (discarded): ${view?.error ?? 'unknown error'}`, plugins: listInstalledPlugins() });
|
|
5035
|
+
}
|
|
5036
|
+
// presets register at install time (same contract as boot/reload) —
|
|
5037
|
+
// after a verified successful load, BEFORE the pool refresh so the
|
|
5038
|
+
// defs are routable immediately on the next dispatch. An engine-refused
|
|
5039
|
+
// package reaches this line too: it loaded nothing, so `syncPluginPresets`
|
|
5040
|
+
// has nothing of it to register, and its row stays DISABLED in `plugins`.
|
|
5041
|
+
const registered = await syncPluginPresets();
|
|
5042
|
+
await refreshDirectPool(registry);
|
|
5043
|
+
return {
|
|
5044
|
+
status: 'ok',
|
|
5045
|
+
id: installed,
|
|
5046
|
+
version: installedVersion,
|
|
5047
|
+
replacedVersion,
|
|
5048
|
+
plugins,
|
|
5049
|
+
registered,
|
|
5050
|
+
// Kept in the 200 body so the console can toast the honest outcome:
|
|
5051
|
+
// the bytes landed, but the package answers nothing until one side
|
|
5052
|
+
// is updated. A green "installed" toast over a red row is the one
|
|
5053
|
+
// reading an operator must not be left with.
|
|
5054
|
+
...(incompatible ? { incompatible: true, error: view.error } : {}),
|
|
5055
|
+
};
|
|
5056
|
+
}
|
|
5057
|
+
catch (err) {
|
|
5058
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
5059
|
+
}
|
|
5060
|
+
});
|
|
5061
|
+
// Per-credential credential writes (reorder / rename / disconnect).
|
|
3324
5062
|
// Decision 8 double-confirm lives in the console UI; these honor the call.
|
|
3325
|
-
app.post(`${prefix}/opencode/providers/:id/credentials
|
|
5063
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/reorder`, withPoolSync(registry, ocHandlers.credentialReorder));
|
|
5064
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/weight`, withPoolSync(registry, ocHandlers.credentialSetWeight));
|
|
3326
5065
|
// Operator takedown (OCR credential state, NOT the credential store — survives
|
|
3327
5066
|
// cooldown/reconnect/Push and is lifted only here).
|
|
3328
|
-
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/disable`, ocHandlers.credentialDisable);
|
|
3329
|
-
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/enable`, ocHandlers.credentialEnable);
|
|
3330
|
-
app.patch(`${prefix}/opencode/providers/:id/credentials/:credentialId`, ocHandlers.credentialRename);
|
|
3331
|
-
app.delete(`${prefix}/opencode/providers/:id/credentials/:credentialId`, ocHandlers.credentialDisconnect);
|
|
5067
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/disable`, withPoolSync(registry, ocHandlers.credentialDisable));
|
|
5068
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/enable`, withPoolSync(registry, ocHandlers.credentialEnable));
|
|
5069
|
+
app.patch(`${prefix}/opencode/providers/:id/credentials/:credentialId`, withPoolSync(registry, ocHandlers.credentialRename));
|
|
5070
|
+
app.delete(`${prefix}/opencode/providers/:id/credentials/:credentialId`, withPoolSync(registry, ocHandlers.credentialDisconnect));
|
|
3332
5071
|
// password-gated raw-key export (controlled exception).
|
|
3333
5072
|
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/reveal`, ocHandlers.credentialReveal);
|
|
3334
5073
|
}
|
|
@@ -3345,10 +5084,21 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3345
5084
|
};
|
|
3346
5085
|
app.get('/api/admin/catalog/logo', handleCatalogLogo);
|
|
3347
5086
|
// 9. Client API Keys Management (for external client access)
|
|
5087
|
+
// List is always masked — plaintext leaves only via the reveal endpoint
|
|
5088
|
+
// (Playground / copy flows). Defense in depth on top of the CORS tighten.
|
|
3348
5089
|
const handleListApiKeys = async () => {
|
|
3349
|
-
return { status: 'ok', keys: listApiKeys(
|
|
5090
|
+
return { status: 'ok', keys: listApiKeys(true) };
|
|
3350
5091
|
};
|
|
3351
5092
|
app.get('/api/admin/api-keys', handleListApiKeys);
|
|
5093
|
+
const handleRevealApiKey = async (req, reply) => {
|
|
5094
|
+
const { id } = req.params;
|
|
5095
|
+
const key = listApiKeys(false).find((k) => k.id === id);
|
|
5096
|
+
if (!key)
|
|
5097
|
+
return reply.status(404).send({ success: false, error: `API key '${id}' not found` });
|
|
5098
|
+
reply.header('Cache-Control', 'no-store');
|
|
5099
|
+
return { status: 'ok', id: key.id, key: key.key };
|
|
5100
|
+
};
|
|
5101
|
+
app.post('/api/admin/api-keys/:id/reveal', handleRevealApiKey);
|
|
3352
5102
|
const handleCreateApiKey = async (req, reply) => {
|
|
3353
5103
|
const body = req.body;
|
|
3354
5104
|
if (!body?.name) {
|
|
@@ -3588,6 +5338,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3588
5338
|
kind: 'model',
|
|
3589
5339
|
owned_by: m.provider,
|
|
3590
5340
|
tiers: registry.tiersOf(m),
|
|
5341
|
+
// Declared thinking levels (ADR-0003 vocabulary). Console pickers that
|
|
5342
|
+
// write a level into a config field (tier effort maps, variant pins)
|
|
5343
|
+
// offer ONLY these — anything else would be clamped right back by
|
|
5344
|
+
// downgradeReasoning. `[]` is a REAL answer ("no explicit level
|
|
5345
|
+
// control", e.g. a toggle-only model), never "unknown".
|
|
5346
|
+
efforts: modelSupportsEfforts(m.supportedReasoningEfforts, m.supportsReasoningEffort, m.reasoningDisableable) ?? [],
|
|
3591
5347
|
// Resolved upstream wire (model-level npm beats provider npm, see
|
|
3592
5348
|
// providers/wire.ts). Console pickers MUST read it from here instead of
|
|
3593
5349
|
// re-deriving it from the provider's npm string — `systemone` marks a
|
|
@@ -3606,26 +5362,45 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3606
5362
|
return { status: 'ok', models };
|
|
3607
5363
|
};
|
|
3608
5364
|
app.get('/api/admin/gateway-models', handleGatewayModels);
|
|
3609
|
-
// 10. Remote restart trigger from UI — spawn a detached
|
|
3610
|
-
// first
|
|
3611
|
-
//
|
|
3612
|
-
//
|
|
5365
|
+
// 10. Remote restart trigger from UI — spawn a detached restart SUPERVISOR
|
|
5366
|
+
// first, then exit. The supervisor waits for this process to die (and
|
|
5367
|
+
// force-kills it if stuck), spawns the replacement gateway, verifies
|
|
5368
|
+
// `/health` (retrying a crashed child), and records the verdict in
|
|
5369
|
+
// ocr.restart.json. Without the spawn we would just stop and nothing
|
|
5370
|
+
// would bring the gateway back (there is no resident supervisor).
|
|
5371
|
+
// One handover at a time: this process exits 500 ms after acknowledging, so
|
|
5372
|
+
// a second POST inside that window would spawn a SECOND supervisor and two
|
|
5373
|
+
// replacements would race for the listen port. Idempotent answer instead.
|
|
5374
|
+
let restartInFlight = false;
|
|
3613
5375
|
const handleRestart = async () => {
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
|
|
5376
|
+
if (restartInFlight) {
|
|
5377
|
+
return { status: 'restarting', message: 'Gateway restart is already in progress' };
|
|
5378
|
+
}
|
|
5379
|
+
restartInFlight = true;
|
|
5380
|
+
try {
|
|
5381
|
+
const { spawnDetachedRestartChild } = await import('../cli/daemon.js');
|
|
5382
|
+
const cfg = loadConfig();
|
|
5383
|
+
const addr = app.server.address();
|
|
5384
|
+
const port = typeof addr === 'object' && addr ? addr.port : cfg.port;
|
|
5385
|
+
const spawned = spawnDetachedRestartChild({ port, host: cfg.host });
|
|
5386
|
+
if (!spawned) {
|
|
5387
|
+
restartInFlight = false;
|
|
5388
|
+
// Fault-tolerance: NEVER stop the gateway without a replacement — keep
|
|
5389
|
+
// serving and surface the failure to the UI instead of exiting.
|
|
5390
|
+
return {
|
|
5391
|
+
status: 'failed',
|
|
5392
|
+
message: 'Could not spawn a replacement process — gateway keeps running. Restart it manually when convenient.',
|
|
5393
|
+
};
|
|
5394
|
+
}
|
|
5395
|
+
setTimeout(() => process.exit(0), 500);
|
|
5396
|
+
return { status: 'restarting', message: 'Gateway restart signal acknowledged — the detached supervisor is booting the replacement' };
|
|
5397
|
+
}
|
|
5398
|
+
catch (err) {
|
|
5399
|
+
// Un-stick the guard: a thrown spawn/config error must not make every
|
|
5400
|
+
// later restart answer "already in progress" forever.
|
|
5401
|
+
restartInFlight = false;
|
|
5402
|
+
return { status: 'failed', message: `Restart failed: ${err.message}` };
|
|
3626
5403
|
}
|
|
3627
|
-
setTimeout(() => process.exit(0), 500);
|
|
3628
|
-
return { status: 'restarting', message: 'Gateway restart signal acknowledged — replacement process is booting' };
|
|
3629
5404
|
};
|
|
3630
5405
|
app.post('/api/admin/restart', handleRestart);
|
|
3631
5406
|
// 11. Process-log tail viewer — reads ~/.omnicell-router/ocr.log (only
|
|
@@ -3746,6 +5521,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3746
5521
|
const r = await stopHeadroomSidecar({ url: headroomSidecarCfg()?.url });
|
|
3747
5522
|
return { status: r.ok ? 'ok' : 'error', ...r };
|
|
3748
5523
|
});
|
|
5524
|
+
registerMihomoRoutes(app);
|
|
3749
5525
|
/* ---------------------------------------------------------------------- *
|
|
3750
5526
|
* 12b. Request-capture archive browser (CaptureRecorder; opt-in audit log)
|
|
3751
5527
|
* Bodies may contain sensitive data — these endpoints sit under /api/admin/*
|
|
@@ -3829,40 +5605,65 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3829
5605
|
return { status: 'ok', date, file, ...result };
|
|
3830
5606
|
});
|
|
3831
5607
|
/**
|
|
3832
|
-
* Read the HTTP exchange events written by the capture pipeline
|
|
3833
|
-
*
|
|
3834
|
-
*
|
|
3835
|
-
*
|
|
5608
|
+
* Read the HTTP exchange events written by the capture pipeline and
|
|
5609
|
+
* project them into REQUESTS. Every event carries its `requestId`,
|
|
5610
|
+
* `exchangeId` and write-time turn identity; the recorder groups all
|
|
5611
|
+
* exchanges of one request into `requests[].exchanges[]`.
|
|
3836
5612
|
*/
|
|
3837
5613
|
app.get('/api/admin/capture/:date/:file/events', async (req, reply) => {
|
|
3838
5614
|
const { date, file } = req.params;
|
|
3839
5615
|
if (!CAPTURE_DATE_RE.test(date)) {
|
|
3840
5616
|
return reply.status(400).send({ status: 'error', message: 'date must be YYYY-MM-DD' });
|
|
3841
5617
|
}
|
|
3842
|
-
|
|
5618
|
+
// `limit` is REQUESTS per page (every exchange of a request always
|
|
5619
|
+
// travels with it), so the pager counts the same unit as the header.
|
|
5620
|
+
// 50 requests is the console default.
|
|
5621
|
+
const limit = Math.min(Math.max(parseInt(req.query?.limit || '50', 10) || 50, 1), 500);
|
|
3843
5622
|
// Metadata-first console reads: bodies=none strips the wire bodies (KB
|
|
3844
|
-
// payload, instant paint); full bodies come back per
|
|
3845
|
-
// bodies=full re-read.
|
|
3846
|
-
|
|
5623
|
+
// payload, instant paint); full bodies come back per request via
|
|
5624
|
+
// /request or a bodies=full re-read. bodies=chat keeps prompt-start
|
|
5625
|
+
// request bodies + response bodies only — the replay's bounded footprint.
|
|
5626
|
+
const bodiesParam = req.query?.bodies;
|
|
5627
|
+
const bodies = bodiesParam === 'none' ? 'none' : bodiesParam === 'chat' ? 'chat' : 'full';
|
|
3847
5628
|
// stitched=1: merge the session's fragments from every date dir (a
|
|
3848
5629
|
// conversation that crossed midnight — or whose session id churned) into
|
|
3849
5630
|
// one chronological timeline. Response carries the per-fragment breakdown.
|
|
3850
5631
|
const stitched = req.query?.stitched === '1';
|
|
5632
|
+
// page=1 is the NEWEST window page; older pages count up from there.
|
|
5633
|
+
// Pages are REQUEST pages (a page never splits a request's events),
|
|
5634
|
+
// bounded by the read window — older history is export-only.
|
|
5635
|
+
const page = Math.min(Math.max(parseInt(req.query?.page || '1', 10) || 1, 1), 100000);
|
|
3851
5636
|
const result = stitched
|
|
3852
|
-
? await captureRecorder.readEventsStitched(date, file, limit, bodies)
|
|
3853
|
-
: await captureRecorder.readEvents(date, file, limit, bodies);
|
|
5637
|
+
? await captureRecorder.readEventsStitched(date, file, limit, bodies, page)
|
|
5638
|
+
: await captureRecorder.readEvents(date, file, limit, bodies, page);
|
|
3854
5639
|
if (result.totalLines === 0 && !captureRecorder.listSessions(date).some(s => s.file === file)) {
|
|
3855
5640
|
return reply.status(404).send({ status: 'error', message: 'Capture archive not found' });
|
|
3856
5641
|
}
|
|
3857
5642
|
return { status: 'ok', date, file, ...result };
|
|
3858
5643
|
});
|
|
3859
5644
|
/**
|
|
3860
|
-
*
|
|
3861
|
-
*
|
|
3862
|
-
*
|
|
3863
|
-
*
|
|
5645
|
+
* EXACT whole-archive summary: the request count and the WRITE-TIME TURN
|
|
5646
|
+
* INDEX (one entry per `turnIndex`, with its request range) for the turn
|
|
5647
|
+
* selector. The events window only knows the tail; this metadata scan is
|
|
5648
|
+
* streamed and never parses request bodies.
|
|
5649
|
+
* Display-only: pagination still follows a bounded read window.
|
|
5650
|
+
*/
|
|
5651
|
+
app.get('/api/admin/capture/:date/:file/summary', async (req) => {
|
|
5652
|
+
const { date, file } = req.params;
|
|
5653
|
+
const stitched = req.query?.stitched === '1';
|
|
5654
|
+
const summary = stitched
|
|
5655
|
+
? await captureRecorder.captureSummaryStitched(date, file)
|
|
5656
|
+
: await captureRecorder.captureSummary(date, file);
|
|
5657
|
+
return { status: 'ok', date, file, ...summary };
|
|
5658
|
+
});
|
|
5659
|
+
/**
|
|
5660
|
+
* Full wire bodies for ONE REQUEST (keyed by its `requestId`; an event id
|
|
5661
|
+
* is accepted too for deep links). The metadata-first events read strips
|
|
5662
|
+
* bodies; the drawer fetches them here when a request is opened. Bounded
|
|
5663
|
+
* by the same read window as /events — a request archived beyond the
|
|
5664
|
+
* window answers 404.
|
|
3864
5665
|
*/
|
|
3865
|
-
app.get('/api/admin/capture/:date/:file/
|
|
5666
|
+
app.get('/api/admin/capture/:date/:file/request', async (req, reply) => {
|
|
3866
5667
|
const { date, file } = req.params;
|
|
3867
5668
|
if (!CAPTURE_DATE_RE.test(date)) {
|
|
3868
5669
|
return reply.status(400).send({ status: 'error', message: 'date must be YYYY-MM-DD' });
|
|
@@ -3872,13 +5673,13 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3872
5673
|
return reply.status(400).send({ status: 'error', message: 'id query param required' });
|
|
3873
5674
|
}
|
|
3874
5675
|
// stitched=1: also search the session's other date-dir fragments — a
|
|
3875
|
-
// cross-midnight
|
|
5676
|
+
// cross-midnight request's bodies live in the shard its events landed in.
|
|
3876
5677
|
const stitched = req.query?.stitched === '1';
|
|
3877
5678
|
const result = stitched
|
|
3878
|
-
? await captureRecorder.
|
|
3879
|
-
: await captureRecorder.
|
|
5679
|
+
? await captureRecorder.readRequestStitched(date, file, id)
|
|
5680
|
+
: await captureRecorder.readRequest(date, file, id);
|
|
3880
5681
|
if (!result) {
|
|
3881
|
-
return reply.status(404).send({ status: 'error', message: '
|
|
5682
|
+
return reply.status(404).send({ status: 'error', message: 'Request not found in read window' });
|
|
3882
5683
|
}
|
|
3883
5684
|
return { status: 'ok', date, file, ...result };
|
|
3884
5685
|
});
|
|
@@ -3927,10 +5728,95 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3927
5728
|
}
|
|
3928
5729
|
return { status: 'ok', message: `Capture archive ${date} deleted` };
|
|
3929
5730
|
});
|
|
5731
|
+
/* ---------------------------------------------------------------------- *
|
|
5732
|
+
* One-shot upstream-request replay (capture drawer debug button).
|
|
5733
|
+
* Re-sends a captured upstream request verbatim — NO pipeline, NO session
|
|
5734
|
+
* machinery, NO capture recording: the fetch here is a bare console-side
|
|
5735
|
+
* HTTP call, invisible to the observation ledgers. Debugging aid only.
|
|
5736
|
+
* ---------------------------------------------------------------------- */
|
|
5737
|
+
app.post('/api/admin/capture/replay', async (req, reply) => {
|
|
5738
|
+
const { url, method, headers, body, provider, model } = (req.body || {});
|
|
5739
|
+
if (!url || !/^https?:\/\//i.test(url)) {
|
|
5740
|
+
return reply.status(400).send({ status: 'error', message: 'an absolute http(s) "url" is required' });
|
|
5741
|
+
}
|
|
5742
|
+
if (!method || !/^[A-Z]+$/.test(method)) {
|
|
5743
|
+
return reply.status(400).send({ status: 'error', message: '"method" must be an upper-case HTTP verb' });
|
|
5744
|
+
}
|
|
5745
|
+
if (body !== undefined && typeof body !== 'string') {
|
|
5746
|
+
return reply.status(400).send({ status: 'error', message: '"body" must be a UTF-8 string (hex/binary bodies are not replayable)' });
|
|
5747
|
+
}
|
|
5748
|
+
// Hop-by-hop / recomputed-by-fetch headers: replaying them verbatim
|
|
5749
|
+
// corrupts the request (stale length, wrong authority).
|
|
5750
|
+
const SKIP_HEADERS = {
|
|
5751
|
+
host: true,
|
|
5752
|
+
'content-length': true,
|
|
5753
|
+
connection: true,
|
|
5754
|
+
'transfer-encoding': true,
|
|
5755
|
+
};
|
|
5756
|
+
const outHeaders = {};
|
|
5757
|
+
for (const [name, value] of Object.entries(headers || {})) {
|
|
5758
|
+
if (!SKIP_HEADERS[name.toLowerCase()] && typeof value === 'string')
|
|
5759
|
+
outHeaders[name] = value;
|
|
5760
|
+
}
|
|
5761
|
+
// Stream the result as NDJSON so the console can render the body
|
|
5762
|
+
// incrementally (SSE replays become live): one JSON event per line —
|
|
5763
|
+
// status (status line + headers), chunk (body piece), end (terminal cap
|
|
5764
|
+
// flag), error (transport failure). The call is console-side only —
|
|
5765
|
+
// nothing is recorded anywhere.
|
|
5766
|
+
reply.hijack();
|
|
5767
|
+
const raw = reply.raw;
|
|
5768
|
+
raw.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-store' });
|
|
5769
|
+
const send = (evt) => raw.write(`${JSON.stringify(evt)}\n`);
|
|
5770
|
+
try {
|
|
5771
|
+
// Honor the outbound proxy policy for fidelity with the original call;
|
|
5772
|
+
// provider/model are the policy's glob keys (absent → direct).
|
|
5773
|
+
const res = await proxiedFetch(url, {
|
|
5774
|
+
method,
|
|
5775
|
+
headers: outHeaders,
|
|
5776
|
+
body: body || undefined,
|
|
5777
|
+
signal: AbortSignal.timeout(DEFAULT_REPLAY_TIMEOUT_MS),
|
|
5778
|
+
}, { provider, model });
|
|
5779
|
+
const resHeaders = {};
|
|
5780
|
+
res.headers.forEach((value, key) => {
|
|
5781
|
+
resHeaders[key] = value;
|
|
5782
|
+
});
|
|
5783
|
+
send({ type: 'status', statusLine: `HTTP/1.1 ${res.status} ${res.statusText}`.trimEnd(), headers: resHeaders });
|
|
5784
|
+
// Cap the streamed echo — the replay result is console UI text, not an
|
|
5785
|
+
// archive record; huge streams surface their head then get cancelled.
|
|
5786
|
+
const REPLAY_BODY_CAP = 512 * 1024;
|
|
5787
|
+
const reader = res.body?.getReader();
|
|
5788
|
+
let total = 0;
|
|
5789
|
+
let truncated = false;
|
|
5790
|
+
if (reader) {
|
|
5791
|
+
const dec = new TextDecoder();
|
|
5792
|
+
for (;;) {
|
|
5793
|
+
const { done, value } = await reader.read();
|
|
5794
|
+
if (done)
|
|
5795
|
+
break;
|
|
5796
|
+
total += value.byteLength;
|
|
5797
|
+
if (total >= REPLAY_BODY_CAP) {
|
|
5798
|
+
truncated = true;
|
|
5799
|
+
send({ type: 'chunk', text: dec.decode(value.subarray(0, value.byteLength - (total - REPLAY_BODY_CAP))) });
|
|
5800
|
+
break;
|
|
5801
|
+
}
|
|
5802
|
+
send({ type: 'chunk', text: dec.decode(value, { stream: true }) });
|
|
5803
|
+
}
|
|
5804
|
+
await reader.cancel().catch(() => undefined);
|
|
5805
|
+
}
|
|
5806
|
+
send({ type: 'end', truncated });
|
|
5807
|
+
raw.end();
|
|
5808
|
+
}
|
|
5809
|
+
catch (err) {
|
|
5810
|
+
// Hijacked reply: transport errors must flow through the stream too.
|
|
5811
|
+
const cause = err?.cause?.code || err?.code;
|
|
5812
|
+
raw.write(`${JSON.stringify({ type: 'error', message: cause ? `${err.message} (${cause})` : String(err?.message || err) })}\n`);
|
|
5813
|
+
raw.end();
|
|
5814
|
+
}
|
|
5815
|
+
});
|
|
3930
5816
|
/* ---------------------------------------------------------------------- *
|
|
3931
5817
|
* Session observation maintenance (console /sessions page cleanup).
|
|
3932
5818
|
* Console pages cannot present API keys, so destructive session ops live
|
|
3933
|
-
* under /api/admin — same trust surface as the capture
|
|
5819
|
+
* under /api/admin — same trust surface as the capture archive deletes
|
|
3934
5820
|
* above. (DELETE /api/admin/sessions/:id is registered in server.ts together
|
|
3935
5821
|
* with the rest of the sessions* surface.)
|
|
3936
5822
|
* ---------------------------------------------------------------------- */
|