omnicell-router 0.2.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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 +158 -23
- package/backend/dist/cli/clients/base.js +150 -4
- package/backend/dist/cli/clients/claude.d.ts +3 -2
- package/backend/dist/cli/clients/claude.js +4 -3
- package/backend/dist/cli/clients/codex.d.ts +3 -2
- package/backend/dist/cli/clients/codex.js +4 -3
- package/backend/dist/cli/clients/core-adapters.d.ts +25 -0
- package/backend/dist/cli/clients/core-adapters.js +44 -0
- package/backend/dist/cli/clients/dsh.d.ts +5 -3
- 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 +28 -19
- package/backend/dist/cli/clients/index.js +156 -58
- 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 +48 -0
- package/backend/dist/cli/clients/launcher.js +41 -0
- package/backend/dist/cli/clients/omp.d.ts +43 -0
- package/backend/dist/cli/clients/omp.js +537 -0
- 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.d.ts +7 -20
- package/backend/dist/cli/clients/opencode.js +32 -159
- package/backend/dist/cli/clients/pi.d.ts +7 -21
- package/backend/dist/cli/clients/pi.js +87 -229
- package/backend/dist/cli/clients/plugin-adapters.d.ts +20 -0
- package/backend/dist/cli/clients/plugin-adapters.js +88 -0
- package/backend/dist/cli/clients/reserved.d.ts +51 -0
- package/backend/dist/cli/clients/reserved.js +53 -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 +238 -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 +102 -16
- package/backend/dist/cli/types.js +5 -4
- package/backend/dist/compression/caveman-prompts.d.ts +1 -1
- 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 +232 -0
- package/backend/dist/config/comments-zh.d.ts +10 -0
- package/backend/dist/config/comments-zh.js +217 -0
- package/backend/dist/config/defaults.d.ts +190 -2
- package/backend/dist/config/defaults.js +191 -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 +48 -12
- package/backend/dist/config/index.js +794 -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 +501 -84
- 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 +104 -0
- package/backend/dist/forward-proxy/egress.js +280 -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/relay.d.ts +21 -1
- package/backend/dist/forward-proxy/relay.js +48 -1
- package/backend/dist/forward-proxy/rules.d.ts +148 -0
- package/backend/dist/forward-proxy/rules.js +280 -0
- package/backend/dist/forward-proxy/server.d.ts +102 -9
- package/backend/dist/forward-proxy/server.js +1310 -305
- 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 +72 -0
- package/backend/dist/forward-proxy/system-proxy.js +303 -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 +18 -5
- package/backend/dist/harness/{adapters → host/adapters}/index.js +73 -5
- 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 -2
- 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 +212 -62
- package/backend/dist/harness/types.d.ts +61 -16
- package/backend/dist/index.js +170 -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/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/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 +353 -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 +14 -0
- package/backend/dist/ir/adapters/openai-responses.js +670 -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 +523 -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 +3 -11
- package/backend/dist/metrics/request-cost.js +9 -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 +16 -10
- package/backend/dist/observability/upstream-events.js +17 -11
- package/backend/dist/opencode/agents.d.ts +10 -2
- package/backend/dist/opencode/agents.js +22 -3
- 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 +10 -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 +40 -4
- package/backend/dist/opencode/probe.d.ts +9 -5
- package/backend/dist/opencode/probe.js +68 -15
- 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 +11 -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 +14 -22
- package/backend/dist/pipeline/directives.js +122 -68
- package/backend/dist/pipeline/orchestrator.d.ts +42 -7
- package/backend/dist/pipeline/orchestrator.js +736 -235
- 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/plugins/builtin/model-gateway.d.ts +30 -0
- package/backend/dist/plugins/builtin/model-gateway.js +98 -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 +98 -0
- package/backend/dist/plugins/gateways.js +151 -0
- package/backend/dist/plugins/host.d.ts +203 -0
- package/backend/dist/plugins/host.js +1310 -0
- package/backend/dist/plugins/manifest.d.ts +43 -0
- package/backend/dist/plugins/manifest.js +462 -0
- package/backend/dist/plugins/pack.d.ts +32 -0
- package/backend/dist/plugins/pack.js +222 -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 +721 -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 +5 -4
- package/backend/dist/protocols/systemone/convert.js +72 -26
- package/backend/dist/protocols/systemone/decide.js +128 -51
- package/backend/dist/protocols/systemone/native.d.ts +1 -1
- package/backend/dist/protocols/systemone/native.js +6 -6
- package/backend/dist/providers/anthropic.js +6 -6
- package/backend/dist/providers/base.d.ts +8 -47
- package/backend/dist/providers/boot-direct.d.ts +20 -2
- package/backend/dist/providers/boot-direct.js +72 -23
- 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 -8
- package/backend/dist/providers/dispatch.js +18 -12
- package/backend/dist/providers/executors/anthropic-messages.d.ts +12 -0
- package/backend/dist/providers/executors/anthropic-messages.js +56 -0
- package/backend/dist/providers/executors/dispatch.d.ts +14 -0
- package/backend/dist/providers/executors/dispatch.js +71 -0
- package/backend/dist/providers/executors/google-gemini.d.ts +12 -0
- package/backend/dist/providers/executors/google-gemini.js +53 -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 +472 -0
- package/backend/dist/providers/executors/openai-chat.d.ts +13 -0
- package/backend/dist/providers/executors/openai-chat.js +89 -0
- package/backend/dist/providers/executors/openai-responses.d.ts +12 -0
- package/backend/dist/providers/executors/openai-responses.js +71 -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.js +6 -6
- package/backend/dist/providers/openai-compatible.js +13 -13
- package/backend/dist/providers/opencode-proxy.js +6 -6
- 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 +37 -21
- package/backend/dist/providers/registry.js +204 -109
- package/backend/dist/providers/responses.d.ts +4 -2
- package/backend/dist/providers/responses.js +12 -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/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 +39 -0
- package/backend/dist/proxy/mihomo-binary.js +267 -0
- package/backend/dist/proxy/mihomo-client.d.ts +94 -0
- package/backend/dist/proxy/mihomo-client.js +294 -0
- package/backend/dist/proxy/mihomo-config.d.ts +40 -0
- package/backend/dist/proxy/mihomo-config.js +152 -0
- package/backend/dist/proxy/mihomo-pac.d.ts +26 -0
- package/backend/dist/proxy/mihomo-pac.js +60 -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 +65 -0
- package/backend/dist/proxy/mihomo-sidecar.js +515 -0
- package/backend/dist/quota/engine.d.ts +9 -2
- package/backend/dist/quota/engine.js +19 -1
- package/backend/dist/quota/prober.d.ts +8 -4
- package/backend/dist/quota/prober.js +9 -10
- package/backend/dist/ratelimit/rate-limiter.d.ts +119 -6
- package/backend/dist/ratelimit/rate-limiter.js +358 -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 +56 -9
- 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 +2 -2
- package/backend/dist/router/layer2-decision.js +22 -19
- 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 +1948 -253
- 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 +1164 -355
- package/backend/dist/routes/mihomo.d.ts +5 -0
- package/backend/dist/routes/mihomo.js +882 -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 +20 -1
- package/backend/dist/routes/responses.js +65 -3
- package/backend/dist/routes/translation.d.ts +9 -0
- package/backend/dist/routes/translation.js +155 -0
- package/backend/dist/server.d.ts +0 -15
- package/backend/dist/server.js +388 -105
- 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 +237 -81
- package/backend/dist/session/session-manager.js +445 -180
- package/backend/dist/session/session-row.d.ts +157 -0
- package/backend/dist/session/session-row.js +120 -0
- 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 +8 -4
- package/backend/dist/surfaces/chat-pipeline.js +102 -35
- package/backend/dist/surfaces/chat.d.ts +1 -9
- package/backend/dist/surfaces/chat.js +52 -29
- package/backend/dist/surfaces/decision-pipeline.js +26 -18
- 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/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 +74 -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 +153 -16
- package/backend/dist/trace/tracker.js +77 -27
- 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 +71 -6
- package/backend/dist/types/router.js +33 -1
- 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 +2 -1
- 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 +8 -1
- package/backend/dist/utils/event-ring.js +13 -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 +33 -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 +12 -0
- package/backend/dist/utils/proxy.js +44 -4
- 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-CLvxJjp_.js +1476 -0
- package/frontend/dist/assets/index-CQSLGFTV.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/cli/clients/opencode-proxy.d.ts +0 -16
- package/backend/dist/cli/clients/opencode-proxy.js +0 -372
- 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 -7
- package/backend/dist/harness/adapters/claude.d.ts +0 -2
- package/backend/dist/harness/adapters/claude.js +0 -7
- package/backend/dist/harness/adapters/cline.d.ts +0 -2
- package/backend/dist/harness/adapters/cline.js +0 -6
- package/backend/dist/harness/adapters/codex.d.ts +0 -2
- package/backend/dist/harness/adapters/codex.js +0 -6
- package/backend/dist/harness/adapters/cursor.d.ts +0 -5
- package/backend/dist/harness/adapters/cursor.js +0 -10
- package/backend/dist/harness/adapters/declarative.d.ts +0 -62
- package/backend/dist/harness/adapters/declarative.js +0 -202
- 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 -7
- package/backend/dist/harness/adapters/github-copilot.d.ts +0 -5
- package/backend/dist/harness/adapters/github-copilot.js +0 -10
- package/backend/dist/harness/adapters/opencode.d.ts +0 -2
- package/backend/dist/harness/adapters/opencode.js +0 -55
- package/backend/dist/harness/adapters/pi.d.ts +0 -1
- package/backend/dist/harness/adapters/pi.js +0 -22
- package/backend/dist/harness/adapters/types.d.ts +0 -174
- 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 -10
- package/backend/dist/harness/adapters/zed.d.ts +0 -2
- package/backend/dist/harness/adapters/zed.js +0 -6
- 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/observability/trace-id.d.ts +0 -40
- package/backend/dist/observability/trace-id.js +0 -134
- package/frontend/dist/assets/index-1o7qI-KJ.css +0 -1
- package/frontend/dist/assets/index-DvXKvNxl.js +0 -962
- 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,62 @@
|
|
|
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, PLUGIN_PACKAGE_MAX_BYTES } from '../config/defaults.js';
|
|
26
|
+
import { initProxyConfig, proxiedFetch } from '../utils/proxy.js';
|
|
27
|
+
import { registerMihomoRoutes } from './mihomo.js';
|
|
28
|
+
import { reconcileMihomoSidecar } 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, 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 } from '../forward-proxy/system-proxy.js';
|
|
24
42
|
import { keyHashPrefix } from '../opencode/credentials/types.js';
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
43
|
+
import { CLASSIFIER_TAXONOMY } from '../resilience/index.js';
|
|
44
|
+
import { maskSecret, isValidProviderId, PROVIDER_ID_RULE, getProviderNodeById } from '../opencode/user-config.js';
|
|
27
45
|
import { listOpenCodeAgentsLive } from '../opencode/agents.js';
|
|
28
46
|
import { listApiKeys, createApiKey, updateApiKey, deleteApiKey, validateApiKey, validateModelAccess, } from '../auth/api-keys.js';
|
|
47
|
+
import { toCallCredential } from '../providers/boot-direct.js';
|
|
29
48
|
import { getModelAccessPolicy, isAutoEntryUsable, isModelAllowed, isModelAllowedInTiers, tierFromVirtualEntry } from '../auth/model-access.js';
|
|
30
49
|
import { validateRateLimitRules, getRateLimiter, credentialSubject } from '../ratelimit/rate-limiter.js';
|
|
31
50
|
import { getQuotaProber } from '../quota/prober.js';
|
|
32
51
|
import { getQuotaStore } from '../quota/store.js';
|
|
33
52
|
import { getQuotaEventLog } from '../quota/events.js';
|
|
34
53
|
import { checkLoginAllowed, createSessionToken, hashPassword, hasWebAuthCredentials, isLoopbackHost, isWebAuthActive, parseSessionCookie, recordLoginFailure, recordLoginSuccess, sessionClearCookie, sessionSetCookie, verifyPassword, verifySessionToken, } from '../auth/web-auth.js';
|
|
54
|
+
/**
|
|
55
|
+
* Comment language for GET /api/admin/config/comments (the console's dynamic
|
|
56
|
+
* comment panel; config.yaml itself is ZERO-COMMENT on disk, ADR-0016).
|
|
57
|
+
* Anything else falls back to zh-CN.
|
|
58
|
+
*/
|
|
59
|
+
const commentLangFromQuery = (q) => (q === 'en' ? 'en' : 'zh-CN');
|
|
35
60
|
export { validateApiKey };
|
|
36
61
|
/* ------------------------------------------------------------------------ *
|
|
37
62
|
* Process-log tail helpers (for GET /api/admin/logs).
|
|
@@ -260,6 +285,49 @@ function clearSuspectForCredential(cb, providerId, keyHashPrefix) {
|
|
|
260
285
|
return;
|
|
261
286
|
cb.getCredentialStateStore().clear(providerId, keyHashPrefix);
|
|
262
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Hot credential-chain rebuild for ONE provider — the runtime twin of the
|
|
290
|
+
* boot pool's chain. The routing chain (`registry.credentialChains`) is
|
|
291
|
+
* otherwise written ONLY at process boot, so a console connect/disconnect/
|
|
292
|
+
* activate or a credential sync would leave the live chain stale (new keys
|
|
293
|
+
* invisible to the spread, removed keys still routable) until the next
|
|
294
|
+
* restart. Reads the bound store's ordered chain (active head first) and
|
|
295
|
+
* swaps it in via `registry.refreshCredentialChain`; a store read failure is
|
|
296
|
+
* swallowed — the boot-baked chain keeps serving (fail-open, same doctrine as
|
|
297
|
+
* every observability write). RAW KEYS stay in memory (registry-only).
|
|
298
|
+
*/
|
|
299
|
+
async function refreshProviderCredentialChain(registry, store, providerId) {
|
|
300
|
+
try {
|
|
301
|
+
registry.refreshCredentialChain(providerId, store.resolveKeyChain(providerId).map((c) => toCallCredential(c.key, c.label, c.weight)));
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
// keep the existing chain — a refresh failure must never take routing down
|
|
305
|
+
}
|
|
306
|
+
// Chain-only by design: the pool rebuild stays behind the mutation-route
|
|
307
|
+
// wrapper (`withPoolSync`) or the config-save seams — a credential-sync
|
|
308
|
+
// run over P providers must not trigger P+1 full rebuilds.
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Wrap an admin mutation handler with a post-run POOL RESYNC: every def /
|
|
312
|
+
* credential / override write lands in the live registry the same way a boot
|
|
313
|
+
* rebuild would (ADR-0010 §3 amendment) — no restart. Fail-open: a rebuild
|
|
314
|
+
* error keeps the existing registry serving. Handlers that already replied
|
|
315
|
+
* (error paths) skip the resync.
|
|
316
|
+
*/
|
|
317
|
+
const withPoolSync = (registry, handler) => async (req, reply) => {
|
|
318
|
+
const result = await handler(req, reply);
|
|
319
|
+
if (!reply.sent) {
|
|
320
|
+
try {
|
|
321
|
+
await refreshDirectPool(registry);
|
|
322
|
+
}
|
|
323
|
+
catch (err) {
|
|
324
|
+
// Fail-open: the registry keeps serving, but a silent drift hides a
|
|
325
|
+
// failed mutation — log it so an operator can see it landed nowhere.
|
|
326
|
+
console.warn(`[console] pool resync after a def/credential mutation failed (registry may drift): ${err.message}`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return result;
|
|
330
|
+
};
|
|
263
331
|
/**
|
|
264
332
|
* Idempotent connect (identity at the write seam): handing the store a
|
|
265
333
|
* key it ALREADY holds for this provider is idempotent — the existing credential is
|
|
@@ -288,7 +356,7 @@ function clearSuspectForCredential(cb, providerId, keyHashPrefix) {
|
|
|
288
356
|
async function connectKeyIdempotent(store, providerId, key, label,
|
|
289
357
|
// Credential flags live in the resilience state file, reached through the manager
|
|
290
358
|
// so the write seam never re-derives its own view of "is this head still good".
|
|
291
|
-
cb) {
|
|
359
|
+
cb, registry) {
|
|
292
360
|
const { keyHashPrefix } = await import('../opencode/credentials/index.js');
|
|
293
361
|
const prefix = keyHashPrefix(key);
|
|
294
362
|
const before = store.listCredentials(providerId);
|
|
@@ -315,7 +383,7 @@ cb) {
|
|
|
315
383
|
* silently repointing the operator's terminal sessions is a hijack, not a
|
|
316
384
|
* default. When a USEABLE head already existed, put it back: the new key joins
|
|
317
385
|
* the chain as an extra credential, and promoting it stays a deliberate second
|
|
318
|
-
* action (the row's own
|
|
386
|
+
* action (the row's own pin-as-default button). A prior head that is SUSPECT or
|
|
319
387
|
* operator-disabled is NOT defended — there, the new key taking over IS the
|
|
320
388
|
* rotation the operator was reaching for.
|
|
321
389
|
*/
|
|
@@ -337,6 +405,9 @@ cb) {
|
|
|
337
405
|
}
|
|
338
406
|
}
|
|
339
407
|
}
|
|
408
|
+
// The chain is boot-baked otherwise — without this swap a newly connected key
|
|
409
|
+
// stays invisible to the per-request spread until the next gateway restart.
|
|
410
|
+
await refreshProviderCredentialChain(registry, store, providerId);
|
|
340
411
|
return { credential, deduped: false, ...(headPreserved ? { headPreserved } : {}) };
|
|
341
412
|
}
|
|
342
413
|
/**
|
|
@@ -581,7 +652,7 @@ async function mapCredentialWriteFailure(err, providerId, credentialId) {
|
|
|
581
652
|
* Raw keys never enter the view (CredentialMeta is masked by interface
|
|
582
653
|
* contract; Decision 1 risk limb).
|
|
583
654
|
*/
|
|
584
|
-
async function storeProviderViews(store) {
|
|
655
|
+
async function storeProviderViews(store, lang) {
|
|
585
656
|
const { listConfigProviders } = await import('../opencode/user-config.js');
|
|
586
657
|
const views = listConfigProviders();
|
|
587
658
|
// Per-provider auto-pull whitelist rides the view (edit dialog prefills from it).
|
|
@@ -623,6 +694,22 @@ async function storeProviderViews(store) {
|
|
|
623
694
|
});
|
|
624
695
|
}
|
|
625
696
|
}
|
|
697
|
+
// Plugin-preset overlay: the def's stored name is a single localeless string,
|
|
698
|
+
// so the localized display name (+logo) comes from the owning plugin manifest.
|
|
699
|
+
{
|
|
700
|
+
const { pluginPresetCatalogEntries } = await import('../plugins/host.js');
|
|
701
|
+
for (const preset of await pluginPresetCatalogEntries(lang)) {
|
|
702
|
+
const v = byId.get(preset.id);
|
|
703
|
+
if (v) {
|
|
704
|
+
// localize only the name the preset itself registered — an operator
|
|
705
|
+
// rename (providers.json is operator-owned, ADR-0010) stays untouched
|
|
706
|
+
if (!v.name || v.name === preset.defaultName || v.name === preset.name)
|
|
707
|
+
v.name = preset.name;
|
|
708
|
+
if (preset.logo && !v.logo)
|
|
709
|
+
v.logo = preset.logo;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
626
713
|
return [...byId.values()].sort((a, b) => {
|
|
627
714
|
// DETERMINISTIC grid order. `store.credentialsOverview()` yields credential-table
|
|
628
715
|
// order (`active DESC, time_updated DESC`), so appending store-only providers
|
|
@@ -684,6 +771,21 @@ async function purgeProviderCredentials(store, id) {
|
|
|
684
771
|
store.invalidate();
|
|
685
772
|
return { attempted: metas.length, removed, failed };
|
|
686
773
|
}
|
|
774
|
+
/**
|
|
775
|
+
* Provider takedown lifecycle terminus: once NOTHING remains for the id (no
|
|
776
|
+
* defs node, no credential), drop the ledger row — a later connect reuses the
|
|
777
|
+
* id enabled. A partial state (either side still present) keeps the takedown.
|
|
778
|
+
*/
|
|
779
|
+
function dropTakedownWhenProviderGone(providerId, store) {
|
|
780
|
+
try {
|
|
781
|
+
if (!getProviderNodeById(providerId) && store.listCredentials(providerId).length === 0) {
|
|
782
|
+
getProviderTakedownStore().enable(providerId);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
catch {
|
|
786
|
+
// unreadable store: keep the takedown (safer than a silent re-enable)
|
|
787
|
+
}
|
|
788
|
+
}
|
|
687
789
|
/**
|
|
688
790
|
* P1-3 outcome flip: whenever the purge ATTEMPTED credentials but did not
|
|
689
791
|
* remove them all, the response must NOT claim success. HTTP stays 200 (the
|
|
@@ -752,6 +854,34 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
752
854
|
}
|
|
753
855
|
return reply.status(404).send('Not Found');
|
|
754
856
|
});
|
|
857
|
+
// 1b. Public assets copied verbatim from frontend/public (Vite emits them at
|
|
858
|
+
// the dist root). The hashed `assets/` handler above covers bundles only —
|
|
859
|
+
// without this route the SPA wildcard below answers `/admin/provider-logos/*`
|
|
860
|
+
// with index.html, so every bundled logo silently fell back to the remote
|
|
861
|
+
// catalog (or a monogram) in production/desktop builds. Names are stable (not
|
|
862
|
+
// content-hashed), so the response revalidates instead of caching immutably.
|
|
863
|
+
const PUBLIC_MIME = {
|
|
864
|
+
'.svg': 'image/svg+xml',
|
|
865
|
+
'.png': 'image/png',
|
|
866
|
+
'.ico': 'image/x-icon',
|
|
867
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
868
|
+
'.webmanifest': 'application/manifest+json',
|
|
869
|
+
};
|
|
870
|
+
app.get('/admin/provider-logos/:file', async (req, reply) => {
|
|
871
|
+
const file = req.params.file;
|
|
872
|
+
if (!file || file.includes('/') || file.includes('\\') || file.includes('..') || file.includes('\0')) {
|
|
873
|
+
return reply.status(400).send('Bad Request');
|
|
874
|
+
}
|
|
875
|
+
const dir = path.join(FRONTEND_DIST, 'provider-logos');
|
|
876
|
+
const filePath = path.join(dir, file);
|
|
877
|
+
if (!path.resolve(filePath).startsWith(path.resolve(dir) + path.sep)) {
|
|
878
|
+
return reply.status(400).send('Bad Request');
|
|
879
|
+
}
|
|
880
|
+
const mime = PUBLIC_MIME[path.extname(file).toLowerCase()];
|
|
881
|
+
if (!mime || !fs.existsSync(filePath))
|
|
882
|
+
return reply.status(404).send('Not Found');
|
|
883
|
+
return reply.header('Cache-Control', 'no-cache').type(mime).send(fs.readFileSync(filePath));
|
|
884
|
+
});
|
|
755
885
|
// 2. React SPA HTML Handler
|
|
756
886
|
const handleHtml = async (_req, reply) => {
|
|
757
887
|
const indexHtmlPath = path.join(FRONTEND_DIST, 'index.html');
|
|
@@ -796,13 +926,18 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
796
926
|
...cbManager.getSummary(),
|
|
797
927
|
pairs: cbManager.getPairSummary(),
|
|
798
928
|
rules: cbManager.getRulesStatus(),
|
|
929
|
+
// Static read-only reference: the classifier's fixed error-class mapping
|
|
930
|
+
// (ADR-0004 §1), single-sourced from CLASSIFIER_TAXONOMY. The console's
|
|
931
|
+
// breaker-rules page renders it to explain what each rule's `auto` scope
|
|
932
|
+
// resolves to and why e.g. 415 never trips while 403 counts. Additive:
|
|
933
|
+
// older gateways omit it and the panel stays hidden.
|
|
934
|
+
classifier: CLASSIFIER_TAXONOMY,
|
|
799
935
|
};
|
|
800
936
|
const metrics = orchestrator.getTracker().getStats();
|
|
801
|
-
const clients = await getAllClientStatuses();
|
|
802
937
|
const config = loadConfig();
|
|
803
938
|
// Runtime credential directory (hash prefixes ONLY — the same display-safe
|
|
804
939
|
// form pair snapshots already carry): lets the guardrails view name an
|
|
805
|
-
// orphan breaker's owner (e.g. the inline config-baked
|
|
940
|
+
// orphan breaker's owner (e.g. the inline config-baked default credential, which
|
|
806
941
|
// lives outside the store roster) instead of a bare #hash. Union of the
|
|
807
942
|
// bound store (the connected roster — independent of model registration)
|
|
808
943
|
// and the registry chains, so a connected-but-model-less provider is named
|
|
@@ -847,21 +982,649 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
847
982
|
},
|
|
848
983
|
// Actual listening port (config.yaml `port` is the single source of truth)
|
|
849
984
|
// so the console header shows the real gateway port instead of a literal.
|
|
850
|
-
port: config.port,
|
|
851
985
|
metrics,
|
|
986
|
+
port: config.port,
|
|
852
987
|
circuitBreakers: cbSummary,
|
|
853
|
-
clients,
|
|
854
988
|
credentialHashes,
|
|
855
989
|
registeredModelsCount: registry.getAllModels().length,
|
|
856
990
|
// Inbound forward-proxy runtime status (see forward-proxy/status.ts) —
|
|
857
991
|
// the Proxy Access page polls this to show running / failed / pending.
|
|
858
992
|
forwardProxy: {
|
|
859
993
|
enabled: Boolean(config.forwardProxy?.enabled),
|
|
994
|
+
// ADR-0019: a disabled upstream verification is a standing risk, so the
|
|
995
|
+
// console states it next to the runtime status instead of hiding it in
|
|
996
|
+
// a YAML comment.
|
|
997
|
+
upstreamInsecure: config.forwardProxy?.upstreamTls?.insecure === true,
|
|
860
998
|
...getForwardProxyStatus(),
|
|
861
999
|
},
|
|
862
1000
|
};
|
|
863
1001
|
};
|
|
864
1002
|
app.get('/api/admin/status', handleStatus);
|
|
1003
|
+
// 3'. Client roster — split from /api/admin/status so the console's 3s
|
|
1004
|
+
// status poll never runs the roster's subprocess version probes (kimi /
|
|
1005
|
+
// openclaw `--version`, worst-case 5s timeout each). Only the Clients page
|
|
1006
|
+
// and the Overview card fetch this, on demand.
|
|
1007
|
+
// `?refresh=1` bypasses the roster SWR cache — the Clients page's manual
|
|
1008
|
+
// "Refresh Status" button must never serve a stale snapshot.
|
|
1009
|
+
app.get('/api/admin/clients', async (req) => {
|
|
1010
|
+
const refresh = req.query.refresh === '1';
|
|
1011
|
+
return {
|
|
1012
|
+
status: 'ok',
|
|
1013
|
+
clients: await getAllClientStatuses({ refresh }),
|
|
1014
|
+
};
|
|
1015
|
+
});
|
|
1016
|
+
// 3A1'. Release update check — display-only and cached in-process. The
|
|
1017
|
+
// first console read starts the GitHub call in the background and answers
|
|
1018
|
+
// `checking: true`; the console polls until the snapshot settles. A stale
|
|
1019
|
+
// entry (success or failure TTL) triggers the next background refresh here,
|
|
1020
|
+
// so every console load is an opportunity to learn about a new release
|
|
1021
|
+
// without any request ever waiting on api.github.com.
|
|
1022
|
+
app.get('/api/admin/update-check', async () => ({ status: 'ok', ...getUpdateChecker().status() }));
|
|
1023
|
+
const mintBodyToken = (t) => Buffer.from(JSON.stringify(t), 'utf8').toString('base64url');
|
|
1024
|
+
const bodyTokenOf = (ref, decoder) => typeof ref === 'string' && ref !== ''
|
|
1025
|
+
? mintBodyToken(decoder ? { k: 'g', r: ref, d: decoder } : { k: 'p', r: ref })
|
|
1026
|
+
: undefined;
|
|
1027
|
+
const resolveBodyPath = (token) => {
|
|
1028
|
+
let t;
|
|
1029
|
+
try {
|
|
1030
|
+
t = JSON.parse(Buffer.from(token, 'base64url').toString('utf8'));
|
|
1031
|
+
}
|
|
1032
|
+
catch {
|
|
1033
|
+
return null;
|
|
1034
|
+
}
|
|
1035
|
+
if (t?.k === 'p' && typeof t.r === 'string')
|
|
1036
|
+
return proxyAccessBodyPath(t.r);
|
|
1037
|
+
if (t?.k === 'g' && typeof t.r === 'string' && typeof t.d === 'string' && getGatewayById(t.d)) {
|
|
1038
|
+
return bodyPath(t.d, t.r);
|
|
1039
|
+
}
|
|
1040
|
+
return null;
|
|
1041
|
+
};
|
|
1042
|
+
// 3A2. THE ONE traffic-timeline endpoint — the console never addresses a
|
|
1043
|
+
// subsystem, it declares a SCOPE and the backend federates:
|
|
1044
|
+
// scope=live → memory ring (proxy access log) + every plugin gateway's
|
|
1045
|
+
// tail feed, interleaved by timestamp, newest first.
|
|
1046
|
+
// scope=history → the PERSISTED federated scan: proxy day JSONL
|
|
1047
|
+
// (`persistDays` retention) + each plugin feed's day
|
|
1048
|
+
// JSONL, merged, paged — one exact total across sources.
|
|
1049
|
+
// Both scopes share one row shape (a discriminated union on `source`), so
|
|
1050
|
+
// the console renders one table and one pager whatever the scope. Filters
|
|
1051
|
+
// (kind/method/status/host) bind history server-side; live filters stay in
|
|
1052
|
+
// the console (the ring is already fully resident there).
|
|
1053
|
+
/** Timestamp of a timeline row in ms — proxy rows carry epoch ms, plugin
|
|
1054
|
+
* rows an ISO string; 0 when unparsable (sorts to the oldest end). */
|
|
1055
|
+
const tsOf = (r) => 'ev' in r ? r.ev.ts ?? 0 : Date.parse(r.ex.ts ?? '') || 0;
|
|
1056
|
+
app.get('/api/admin/proxy-log', async (req) => {
|
|
1057
|
+
const q = req.query;
|
|
1058
|
+
if (q.scope === 'history') {
|
|
1059
|
+
const limit = Math.min(Math.max(Number(q.limit) || 50, 1), 500);
|
|
1060
|
+
const pageNo = Math.max(Number(q.page) || 1, 1);
|
|
1061
|
+
const kindF = q.kind ?? '';
|
|
1062
|
+
const methodF = q.method ?? '';
|
|
1063
|
+
const statusF = q.status ?? '';
|
|
1064
|
+
const hostF = (q.host ?? '').toLowerCase();
|
|
1065
|
+
const rows = [];
|
|
1066
|
+
for (const ev of readProxyAccessHistory({
|
|
1067
|
+
kind: kindF || undefined,
|
|
1068
|
+
method: methodF || undefined,
|
|
1069
|
+
status: statusF || undefined,
|
|
1070
|
+
host: hostF || undefined,
|
|
1071
|
+
})) {
|
|
1072
|
+
rows.push({ source: 'proxy', tsMs: ev.ts, ev });
|
|
1073
|
+
}
|
|
1074
|
+
for (const { id } of trafficDecoders()) {
|
|
1075
|
+
const dir = path.join(trafficRoot(), id);
|
|
1076
|
+
let files = [];
|
|
1077
|
+
try {
|
|
1078
|
+
files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().reverse();
|
|
1079
|
+
}
|
|
1080
|
+
catch {
|
|
1081
|
+
continue; // fresh plugin / unreadable feed dir — no history from it
|
|
1082
|
+
}
|
|
1083
|
+
for (const f of files) {
|
|
1084
|
+
let lines = [];
|
|
1085
|
+
try {
|
|
1086
|
+
lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n');
|
|
1087
|
+
}
|
|
1088
|
+
catch {
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
for (const line of lines) {
|
|
1092
|
+
if (!line)
|
|
1093
|
+
continue;
|
|
1094
|
+
let ex;
|
|
1095
|
+
try {
|
|
1096
|
+
ex = JSON.parse(line);
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
continue; // torn final line (crash mid-append) skips one row
|
|
1100
|
+
}
|
|
1101
|
+
if (methodF && ex.method !== methodF)
|
|
1102
|
+
continue;
|
|
1103
|
+
if (hostF && (ex.authority ?? '').toLowerCase() !== hostF)
|
|
1104
|
+
continue;
|
|
1105
|
+
// Plugin rows are HTTP by definition (the console's `kindOf`):
|
|
1106
|
+
// a CONNECT/WS filter excludes them, and a status filter prunes
|
|
1107
|
+
// them — otherwise the federated total counts rows the delete
|
|
1108
|
+
// path (and the rendered table) never includes.
|
|
1109
|
+
if (kindF && kindF !== 'http')
|
|
1110
|
+
continue;
|
|
1111
|
+
if (statusF && String(ex.status ?? '') !== statusF)
|
|
1112
|
+
continue;
|
|
1113
|
+
rows.push({ source: id, tsMs: Date.parse(ex.ts ?? '') || 0, ex });
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
rows.sort((a, b) => b.tsMs - a.tsMs);
|
|
1118
|
+
const total = rows.length;
|
|
1119
|
+
const pages = Math.max(Math.ceil(total / limit), 1);
|
|
1120
|
+
const slice = rows.slice((pageNo - 1) * limit, (pageNo - 1) * limit + limit);
|
|
1121
|
+
// Read-time decode is PAGE-scoped: dissect + hex previews only for the
|
|
1122
|
+
// rows actually returned, never for the whole scan.
|
|
1123
|
+
return {
|
|
1124
|
+
status: 'ok',
|
|
1125
|
+
rows: slice.map((r) => 'ev' in r
|
|
1126
|
+
? {
|
|
1127
|
+
source: 'proxy',
|
|
1128
|
+
ev: { ...r.ev, reqBodyToken: bodyTokenOf(r.ev.reqBodyFile), resBodyToken: bodyTokenOf(r.ev.resBodyFile) },
|
|
1129
|
+
}
|
|
1130
|
+
: { source: r.source, ex: decoratePluginRow(r.source, r.ex) }),
|
|
1131
|
+
total,
|
|
1132
|
+
page: pageNo,
|
|
1133
|
+
pages,
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
// scope=live (default) — the merged tail: ring + every plugin feed tail.
|
|
1137
|
+
const s = proxyAccessLogSettings();
|
|
1138
|
+
const rows = [];
|
|
1139
|
+
const hiddenProxy = liveHiddenProxyIds();
|
|
1140
|
+
for (const e of listProxyAccessEvents()) {
|
|
1141
|
+
if (hiddenProxy.has(e.id))
|
|
1142
|
+
continue;
|
|
1143
|
+
rows.push({ source: 'proxy', ev: { ...e, reqBodyToken: bodyTokenOf(e.reqBodyFile), resBodyToken: bodyTokenOf(e.resBodyFile) } });
|
|
1144
|
+
}
|
|
1145
|
+
for (const { id } of trafficDecoders()) {
|
|
1146
|
+
const gw = getGatewayById(id);
|
|
1147
|
+
if (!gw || typeof gw.dissect !== 'function')
|
|
1148
|
+
continue;
|
|
1149
|
+
const dir = path.join(trafficRoot(), id);
|
|
1150
|
+
const events = [];
|
|
1151
|
+
try {
|
|
1152
|
+
if (fs.existsSync(dir)) {
|
|
1153
|
+
const files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().reverse();
|
|
1154
|
+
for (const f of files) {
|
|
1155
|
+
if (events.length >= TRAFFIC_TAIL)
|
|
1156
|
+
break;
|
|
1157
|
+
const lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n').filter(Boolean);
|
|
1158
|
+
for (let i = lines.length - 1; i >= 0 && events.length < TRAFFIC_TAIL; i--) {
|
|
1159
|
+
try {
|
|
1160
|
+
events.push(JSON.parse(lines[i]));
|
|
1161
|
+
}
|
|
1162
|
+
catch {
|
|
1163
|
+
continue; // a torn final line (crash mid-append) skips one row
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
catch {
|
|
1170
|
+
// Unreadable feed dir = empty feed.
|
|
1171
|
+
}
|
|
1172
|
+
const hiddenPlugin = liveHiddenPluginKeys(id);
|
|
1173
|
+
for (const ex of events) {
|
|
1174
|
+
const key = typeof ex.id === 'string' ? ex.id : ex.ts;
|
|
1175
|
+
if (key && hiddenPlugin.has(key))
|
|
1176
|
+
continue;
|
|
1177
|
+
rows.push({ source: id, ex: decoratePluginRow(id, ex) });
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
rows.sort((a, b) => (tsOf(a) || 0) - (tsOf(b) || 0));
|
|
1181
|
+
return {
|
|
1182
|
+
status: 'ok',
|
|
1183
|
+
enabled: s.enabled,
|
|
1184
|
+
bodyBytes: s.bodyBytes,
|
|
1185
|
+
rows: rows.reverse(),
|
|
1186
|
+
total: rows.length,
|
|
1187
|
+
};
|
|
1188
|
+
});
|
|
1189
|
+
app.post('/api/admin/proxy-log/clear', async () => {
|
|
1190
|
+
clearProxyAccessLog();
|
|
1191
|
+
return { status: 'ok' };
|
|
1192
|
+
});
|
|
1193
|
+
// 3A2c. HISTORY delete by FILTER — the history-mode counterpart of the
|
|
1194
|
+
// clear button. History is the PERSISTED scope, so this rewrite touches the
|
|
1195
|
+
// day JSONL + body sidecars only and leaves the live ring alone (ADR-0017
|
|
1196
|
+
// §5: the same row may still be listed in the live view until it ages out).
|
|
1197
|
+
// The console only holds ONE page of the persisted federation at a time, so
|
|
1198
|
+
// "what I see" and "what I asked to delete" would diverge; the console sends
|
|
1199
|
+
// the SAME filter vocabulary it queries with and the backend deletes every
|
|
1200
|
+
// matching persisted row across ALL sources. The response reports per-source
|
|
1201
|
+
// counts so the confirm toast is never a guess.
|
|
1202
|
+
app.post('/api/admin/proxy-log/history/delete', async (req) => {
|
|
1203
|
+
const b = (req.body ?? {});
|
|
1204
|
+
const kindF = b.kind ?? '';
|
|
1205
|
+
const methodF = b.method ?? '';
|
|
1206
|
+
const statusF = b.status ?? '';
|
|
1207
|
+
const hostF = (b.host ?? '').toLowerCase();
|
|
1208
|
+
// Proxy side: ids → the persisted-row deleter (day files + body sidecars).
|
|
1209
|
+
const ids = readProxyAccessHistory({
|
|
1210
|
+
kind: kindF || undefined,
|
|
1211
|
+
method: methodF || undefined,
|
|
1212
|
+
status: statusF || undefined,
|
|
1213
|
+
host: hostF || undefined,
|
|
1214
|
+
}).map((e) => e.id);
|
|
1215
|
+
const proxyDeleted = ids.length > 0 ? deletePersistedProxyEvents(ids) : 0;
|
|
1216
|
+
// Plugin side: rewrite each feed's day files without the matching lines.
|
|
1217
|
+
const deletedPlugins = {};
|
|
1218
|
+
for (const { id } of trafficDecoders()) {
|
|
1219
|
+
// Plugin rows are ALWAYS `http` (the console's `kindOf`): a CONNECT/WS
|
|
1220
|
+
// filter cannot match them, but the default `http` filter must — the
|
|
1221
|
+
// history table renders those rows, so refusing every kind filter left
|
|
1222
|
+
// them behind after a clear (the "clear is not clean" bug).
|
|
1223
|
+
if (kindF && kindF !== 'http')
|
|
1224
|
+
continue;
|
|
1225
|
+
const dir = path.join(trafficRoot(), id);
|
|
1226
|
+
let files = [];
|
|
1227
|
+
try {
|
|
1228
|
+
files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f));
|
|
1229
|
+
}
|
|
1230
|
+
catch {
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
let removed = 0;
|
|
1234
|
+
const bodyIds = new Set();
|
|
1235
|
+
for (const f of files) {
|
|
1236
|
+
const abs = path.join(dir, f);
|
|
1237
|
+
let kept = [];
|
|
1238
|
+
try {
|
|
1239
|
+
kept = fs.readFileSync(abs, 'utf8').split('\n').filter(Boolean);
|
|
1240
|
+
}
|
|
1241
|
+
catch {
|
|
1242
|
+
continue;
|
|
1243
|
+
}
|
|
1244
|
+
let touched = false;
|
|
1245
|
+
const keptOut = [];
|
|
1246
|
+
for (const line of kept) {
|
|
1247
|
+
let ex;
|
|
1248
|
+
try {
|
|
1249
|
+
ex = JSON.parse(line);
|
|
1250
|
+
}
|
|
1251
|
+
catch {
|
|
1252
|
+
keptOut.push(line); // a torn line survives deletion round-trips
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
const hit = (!methodF || ex.method === methodF) &&
|
|
1256
|
+
(!hostF || (ex.authority ?? '').toLowerCase() === hostF) &&
|
|
1257
|
+
(!statusF || String(ex.status ?? '') === statusF);
|
|
1258
|
+
if (hit) {
|
|
1259
|
+
touched = true;
|
|
1260
|
+
removed++;
|
|
1261
|
+
if (typeof ex.id === 'string')
|
|
1262
|
+
bodyIds.add(ex.id);
|
|
1263
|
+
continue;
|
|
1264
|
+
}
|
|
1265
|
+
keptOut.push(line);
|
|
1266
|
+
}
|
|
1267
|
+
if (!touched)
|
|
1268
|
+
continue;
|
|
1269
|
+
try {
|
|
1270
|
+
if (keptOut.length === 0)
|
|
1271
|
+
fs.unlinkSync(abs);
|
|
1272
|
+
else
|
|
1273
|
+
fs.writeFileSync(abs, keptOut.join('\n') + '\n');
|
|
1274
|
+
}
|
|
1275
|
+
catch {
|
|
1276
|
+
// Best effort — the row is gone from the feed view either way.
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
// Sidecar bytes are named `<day>/<id>-<side>.bin`: drop only the ones
|
|
1280
|
+
// whose row just went away, never a neighbour's.
|
|
1281
|
+
if (bodyIds.size > 0) {
|
|
1282
|
+
const bodiesRoot = path.join(dir, 'bodies');
|
|
1283
|
+
if (fs.existsSync(bodiesRoot)) {
|
|
1284
|
+
for (const day of fs.readdirSync(bodiesRoot)) {
|
|
1285
|
+
const dayDir = path.join(bodiesRoot, day);
|
|
1286
|
+
let names = [];
|
|
1287
|
+
try {
|
|
1288
|
+
names = fs.readdirSync(dayDir);
|
|
1289
|
+
}
|
|
1290
|
+
catch {
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
for (const name of names) {
|
|
1294
|
+
const owner = name.replace(/-(?:req|res)\.bin$/, '');
|
|
1295
|
+
if (!bodyIds.has(owner))
|
|
1296
|
+
continue;
|
|
1297
|
+
try {
|
|
1298
|
+
fs.unlinkSync(path.join(dayDir, name));
|
|
1299
|
+
}
|
|
1300
|
+
catch {
|
|
1301
|
+
// Locked file (Windows) — the row is gone, the blob is orphaned.
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
if (removed > 0)
|
|
1308
|
+
deletedPlugins[id] = removed;
|
|
1309
|
+
}
|
|
1310
|
+
return { status: 'ok', deleted: { proxy: proxyDeleted, plugins: deletedPlugins } };
|
|
1311
|
+
});
|
|
1312
|
+
// 3A1b. Explicit FULL wipe across BOTH scopes — ring, proxy day files +
|
|
1313
|
+
// bodies, and every plugin feed dir. This is an admin API, not either
|
|
1314
|
+
// console button: live clear hides only, history delete rewrites only
|
|
1315
|
+
// (ADR-0017 §5). Gateway feeds are console-owned artifacts on disk, so they
|
|
1316
|
+
// are removed here rather than through the plugin.
|
|
1317
|
+
app.post('/api/admin/traffic-clear', async () => {
|
|
1318
|
+
clearProxyAccessLog();
|
|
1319
|
+
const cleared = [];
|
|
1320
|
+
for (const [id, gw] of listGateways()) {
|
|
1321
|
+
if (typeof gw.dissect !== 'function')
|
|
1322
|
+
continue;
|
|
1323
|
+
const dir = path.join(trafficRoot(), id);
|
|
1324
|
+
try {
|
|
1325
|
+
if (fs.existsSync(dir))
|
|
1326
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
1327
|
+
cleared.push(id);
|
|
1328
|
+
}
|
|
1329
|
+
catch {
|
|
1330
|
+
// A locked feed (Windows handle) must not fail the whole clear.
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
return { status: 'ok', cleared };
|
|
1334
|
+
});
|
|
1335
|
+
/**
|
|
1336
|
+
* 3A1c. Hide EXACTLY the rows the LIVE view is showing — the live-scope
|
|
1337
|
+
* counterpart of the history delete. Live and history are scopes over the
|
|
1338
|
+
* same feeds, not separate stores (ADR-0017 §5), so this route never touches
|
|
1339
|
+
* a file: proxy rows leave the ring, and plugin rows are recorded in a
|
|
1340
|
+
* live-only tombstone overlay that the live read applies and history
|
|
1341
|
+
* ignores. The persisted day JSONL and body sidecars stay intact and remain
|
|
1342
|
+
* listed/deletable from History mode.
|
|
1343
|
+
*
|
|
1344
|
+
* The console sends row keys (`id`, else the legacy feed `ts`) with their
|
|
1345
|
+
* timestamps, never a predicate: the filter lives in one place (the page)
|
|
1346
|
+
* and a backend copy would drift into hiding more than the operator sees.
|
|
1347
|
+
*/
|
|
1348
|
+
app.post('/api/admin/traffic-live-clear', async (req) => {
|
|
1349
|
+
const body = (req.body ?? {});
|
|
1350
|
+
const asLiveKeys = (v) => {
|
|
1351
|
+
if (!Array.isArray(v))
|
|
1352
|
+
return [];
|
|
1353
|
+
const out = [];
|
|
1354
|
+
for (const x of v) {
|
|
1355
|
+
if (!x || typeof x !== 'object' || !('key' in x) || !('ts' in x))
|
|
1356
|
+
continue;
|
|
1357
|
+
if (typeof x.key === 'string' && x.key.length > 0 && typeof x.ts === 'number' && Number.isFinite(x.ts)) {
|
|
1358
|
+
out.push({ key: x.key, ts: x.ts });
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
return out;
|
|
1362
|
+
};
|
|
1363
|
+
// Only ids the ring actually holds are part of the live view right now;
|
|
1364
|
+
// the tombstones cover the plugin tail rows (history ignores them).
|
|
1365
|
+
const ringIds = new Set(listProxyAccessEvents().map((e) => e.id));
|
|
1366
|
+
const liveProxy = asLiveKeys(body.proxy).filter((k) => ringIds.has(k.key));
|
|
1367
|
+
const plugins = {};
|
|
1368
|
+
if (body.plugins && typeof body.plugins === 'object' && !Array.isArray(body.plugins)) {
|
|
1369
|
+
for (const [decoderId, raw] of Object.entries(body.plugins)) {
|
|
1370
|
+
plugins[decoderId] = asLiveKeys(raw);
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
forgetProxyAccessRingEvents(liveProxy.map((k) => k.key));
|
|
1374
|
+
const hidden = hideLiveEvents(liveProxy, plugins);
|
|
1375
|
+
return { status: 'ok', hidden };
|
|
1376
|
+
});
|
|
1377
|
+
// 3A2b. Generic plugin-traffic feed (Wireshark dissector model, ADR-0017
|
|
1378
|
+
// client gateways): each gateway that declares `dissect` owns a protocol
|
|
1379
|
+
// decoder AND a raw day-JSONL feed under
|
|
1380
|
+
// <ocrHome>/plugins/traffic/<pluginId>/. The console tab lists the decoder
|
|
1381
|
+
// registry and reads a feed, applying the plugin's dissector at READ time.
|
|
1382
|
+
// The plugin stays self-contained — the route only owns the feed layout and
|
|
1383
|
+
// tail discipline (newest first, capped).
|
|
1384
|
+
// Resolved per call, never captured at registration: OCR_HOME is the
|
|
1385
|
+
// environment-book-set switch (ADR-0007) and may change under a live server.
|
|
1386
|
+
const trafficRoot = () => path.join(getOcrHomeDir(), 'plugins', 'traffic');
|
|
1387
|
+
const TRAFFIC_TAIL = 500;
|
|
1388
|
+
/** Per-side DISPLAY window handed to the dissector (and the hex preview).
|
|
1389
|
+
* Capture is full fidelity on disk; only this read is bounded. */
|
|
1390
|
+
const TRAFFIC_DISSECT_WINDOW = 32 * 1024;
|
|
1391
|
+
/** Inline hex preview length (the drawer's hex fallback). */
|
|
1392
|
+
const TRAFFIC_HEX_PREVIEW = 1024;
|
|
1393
|
+
/** Strict sidecar ref: `<YYYYMMDD>/<id>-<side>.bin`, no traversal. */
|
|
1394
|
+
const TRAFFIC_BODY_REF_RE = /^\d{8}\/[A-Za-z0-9._-]+\.bin$/;
|
|
1395
|
+
/** Resolve a feed body ref to an absolute path inside that decoder's dir. */
|
|
1396
|
+
const bodyPath = (decoderId, ref) => {
|
|
1397
|
+
if (!TRAFFIC_BODY_REF_RE.test(ref))
|
|
1398
|
+
return null;
|
|
1399
|
+
const root = path.join(trafficRoot(), decoderId, 'bodies');
|
|
1400
|
+
const abs = path.join(root, ref);
|
|
1401
|
+
return abs.startsWith(root + path.sep) ? abs : null;
|
|
1402
|
+
};
|
|
1403
|
+
const trafficDecoders = () => {
|
|
1404
|
+
const out = [];
|
|
1405
|
+
for (const [id, gw] of listGateways()) {
|
|
1406
|
+
if (typeof gw.dissect !== 'function')
|
|
1407
|
+
continue;
|
|
1408
|
+
out.push({ id, label: gw.hosts.join(', ') });
|
|
1409
|
+
}
|
|
1410
|
+
return out;
|
|
1411
|
+
};
|
|
1412
|
+
/** Read-time wire decoration for ONE plugin feed row: body windows for the
|
|
1413
|
+
* dissector + hex preview, dissect layers, body tokens, bodies stripped.
|
|
1414
|
+
* Shared by the live tail route and the federated history scan — one
|
|
1415
|
+
* decoration path, never two. */
|
|
1416
|
+
const decoratePluginRow = (decoderId, ex) => {
|
|
1417
|
+
const windowOf = (ref) => {
|
|
1418
|
+
if (typeof ref !== 'string')
|
|
1419
|
+
return undefined;
|
|
1420
|
+
const abs = bodyPath(decoderId, ref);
|
|
1421
|
+
if (!abs)
|
|
1422
|
+
return undefined;
|
|
1423
|
+
try {
|
|
1424
|
+
const fd = fs.openSync(abs, 'r');
|
|
1425
|
+
try {
|
|
1426
|
+
const buf = Buffer.alloc(TRAFFIC_DISSECT_WINDOW);
|
|
1427
|
+
const read = fs.readSync(fd, buf, 0, TRAFFIC_DISSECT_WINDOW, 0);
|
|
1428
|
+
return buf.subarray(0, read);
|
|
1429
|
+
}
|
|
1430
|
+
finally {
|
|
1431
|
+
fs.closeSync(fd);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
catch {
|
|
1435
|
+
return undefined;
|
|
1436
|
+
}
|
|
1437
|
+
};
|
|
1438
|
+
const reqWin = windowOf(ex.reqBodyFile);
|
|
1439
|
+
const resWin = windowOf(ex.resBodyFile);
|
|
1440
|
+
// Legacy rows (inline base64 body) still decode: the window is the
|
|
1441
|
+
// inline body itself, so both feed generations share one path.
|
|
1442
|
+
const reqBytes = reqWin ?? (typeof ex.reqBody === 'string' ? Buffer.from(ex.reqBody, 'base64') : undefined);
|
|
1443
|
+
const resBytes = resWin ?? (typeof ex.resBody === 'string' ? Buffer.from(ex.resBody, 'base64') : undefined);
|
|
1444
|
+
let dissected;
|
|
1445
|
+
try {
|
|
1446
|
+
dissected = getGatewayById(decoderId)?.dissect?.({ ...ex, reqBody: reqBytes?.toString('base64'), resBody: resBytes?.toString('base64') });
|
|
1447
|
+
}
|
|
1448
|
+
catch {
|
|
1449
|
+
dissected = undefined; // a decoder bug degrades to the raw view only
|
|
1450
|
+
}
|
|
1451
|
+
// Strip bodies from the wire view: the console gets byte counts,
|
|
1452
|
+
// file refs and a small hex preview, never the payload itself.
|
|
1453
|
+
const { reqBody: _rq, resBody: _rs, ...meta } = ex;
|
|
1454
|
+
void _rq;
|
|
1455
|
+
void _rs;
|
|
1456
|
+
const hexPreview = (b) => {
|
|
1457
|
+
if (!b || b.length === 0)
|
|
1458
|
+
return undefined;
|
|
1459
|
+
return b.subarray(0, TRAFFIC_HEX_PREVIEW).toString('hex');
|
|
1460
|
+
};
|
|
1461
|
+
return {
|
|
1462
|
+
...meta,
|
|
1463
|
+
reqBodyToken: bodyTokenOf(ex.reqBodyFile, decoderId),
|
|
1464
|
+
resBodyToken: bodyTokenOf(ex.resBodyFile, decoderId),
|
|
1465
|
+
reqHex: hexPreview(reqBytes),
|
|
1466
|
+
resHex: hexPreview(resBytes),
|
|
1467
|
+
decoded: dissected,
|
|
1468
|
+
};
|
|
1469
|
+
};
|
|
1470
|
+
app.get('/api/admin/plugin-traffic', async () => {
|
|
1471
|
+
return { status: 'ok', decoders: trafficDecoders() };
|
|
1472
|
+
});
|
|
1473
|
+
app.get('/api/admin/plugin-traffic/:decoder', async (req, reply) => {
|
|
1474
|
+
const decoderId = String(req.params.decoder ?? '');
|
|
1475
|
+
const gw = getGatewayById(decoderId);
|
|
1476
|
+
if (!gw || typeof gw.dissect !== 'function') {
|
|
1477
|
+
reply.code(404);
|
|
1478
|
+
return { status: 'error', message: `no traffic decoder registered for '${decoderId}'` };
|
|
1479
|
+
}
|
|
1480
|
+
const dir = path.join(trafficRoot(), decoderId);
|
|
1481
|
+
const events = [];
|
|
1482
|
+
let days = 0;
|
|
1483
|
+
try {
|
|
1484
|
+
if (fs.existsSync(dir)) {
|
|
1485
|
+
const files = fs.readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().reverse();
|
|
1486
|
+
for (const f of files) {
|
|
1487
|
+
if (events.length >= TRAFFIC_TAIL)
|
|
1488
|
+
break;
|
|
1489
|
+
days++;
|
|
1490
|
+
const lines = fs.readFileSync(path.join(dir, f), 'utf8').split('\n').filter(Boolean);
|
|
1491
|
+
for (let i = lines.length - 1; i >= 0 && events.length < TRAFFIC_TAIL; i--) {
|
|
1492
|
+
let raw;
|
|
1493
|
+
try {
|
|
1494
|
+
raw = JSON.parse(lines[i]);
|
|
1495
|
+
}
|
|
1496
|
+
catch {
|
|
1497
|
+
continue; // a torn final line (crash mid-append) skips one row
|
|
1498
|
+
}
|
|
1499
|
+
const ex = raw;
|
|
1500
|
+
events.push(decoratePluginRow(decoderId, ex));
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
catch {
|
|
1506
|
+
// Unreadable feed dir (fresh plugin, permissions) = empty feed.
|
|
1507
|
+
}
|
|
1508
|
+
return { status: 'ok', days, truncated: events.length >= TRAFFIC_TAIL, events };
|
|
1509
|
+
});
|
|
1510
|
+
// Raw persisted binary body (ref format `<day>/pa-...-<side>.bin`, validated
|
|
1511
|
+
// inside readProxyAccessBodyFile — no traversal).
|
|
1512
|
+
// 3A2c. THE body download — one neutral endpoint for every captured body,
|
|
1513
|
+
// whatever stored it. The console never learns which subsystem owns the
|
|
1514
|
+
// bytes (or which plugin captured them): the row carries an opaque token and
|
|
1515
|
+
// only this route resolves it. Validation happens AFTER decoding the token,
|
|
1516
|
+
// so a hand-crafted token is no stronger than the refs the feeds already
|
|
1517
|
+
// expose (strict grammar + containment inside the resolved root).
|
|
1518
|
+
app.get('/api/admin/traffic-body/:token', async (req, reply) => {
|
|
1519
|
+
const token = String(req.params.token ?? '');
|
|
1520
|
+
const abs = resolveBodyPath(token);
|
|
1521
|
+
if (!abs || !fs.existsSync(abs)) {
|
|
1522
|
+
reply.code(404);
|
|
1523
|
+
return { status: 'error', message: 'body not found' };
|
|
1524
|
+
}
|
|
1525
|
+
reply.header('content-type', 'application/octet-stream');
|
|
1526
|
+
reply.header('content-disposition', `attachment; filename="${path.basename(abs)}"`);
|
|
1527
|
+
return reply.send(fs.createReadStream(abs));
|
|
1528
|
+
});
|
|
1529
|
+
// 3A3. OS system proxy ownership for the inbound forward proxy: snapshot →
|
|
1530
|
+
// point at 127.0.0.1:<port> → one-click restore (forward-proxy/system-proxy.ts).
|
|
1531
|
+
app.get('/api/admin/system-proxy', async () => {
|
|
1532
|
+
const fp = getRuntimeConfigRef()?.forwardProxy;
|
|
1533
|
+
const port = fp?.port ?? DEFAULT_FORWARD_PROXY_PORT;
|
|
1534
|
+
const sys = await getSystemProxyStatus(port, osBypassHosts(fp?.rules));
|
|
1535
|
+
return { status: 'ok', ...sys, proxyEnabled: Boolean(fp?.enabled) };
|
|
1536
|
+
});
|
|
1537
|
+
app.post('/api/admin/system-proxy/enable', async () => {
|
|
1538
|
+
const fp = getRuntimeConfigRef()?.forwardProxy;
|
|
1539
|
+
const port = fp?.port ?? DEFAULT_FORWARD_PROXY_PORT;
|
|
1540
|
+
const sys = await enableSystemProxy(port, osBypassHosts(fp?.rules));
|
|
1541
|
+
return { status: 'ok', ...sys };
|
|
1542
|
+
});
|
|
1543
|
+
app.post('/api/admin/system-proxy/disable', async () => {
|
|
1544
|
+
const fp = getRuntimeConfigRef()?.forwardProxy;
|
|
1545
|
+
const port = fp?.port ?? DEFAULT_FORWARD_PROXY_PORT;
|
|
1546
|
+
const sys = await disableSystemProxy(port, osBypassHosts(fp?.rules));
|
|
1547
|
+
return { status: 'ok', ...sys };
|
|
1548
|
+
});
|
|
1549
|
+
// 3A4. Forward-proxy rule table (ADR-0018): lint + dry-run resolution. The
|
|
1550
|
+
// console renders the warning CODES through i18n and shows which rule a probe
|
|
1551
|
+
// host hits, so an ordered table is never a black box. `rules` in the body =
|
|
1552
|
+
// the UNSAVED table being edited; omitted = the live one. `intercept` in the
|
|
1553
|
+
// body = the UNSAVED posture toggle (same reason); omitted = the live one.
|
|
1554
|
+
app.post('/api/admin/forward-proxy/rules/resolve', async (req) => {
|
|
1555
|
+
const body = (req.body ?? {});
|
|
1556
|
+
const live = getRuntimeConfigRef();
|
|
1557
|
+
const rawRules = Array.isArray(body.rules) ? body.rules : live?.forwardProxy?.rules;
|
|
1558
|
+
const proxyEnabled = live?.proxy?.enabled === true;
|
|
1559
|
+
const rules = normalizeRules(rawRules);
|
|
1560
|
+
// ADR-0018 Revision 4: the posture and the claim set are part of the answer,
|
|
1561
|
+
// because they decide `tunnel` for every host no specific row names. The
|
|
1562
|
+
// preview reads the SAME registry the proxy legs do (`listGatewayHosts()`)
|
|
1563
|
+
// and takes an unsaved toggle from the body, so it can never disagree with
|
|
1564
|
+
// the live decision.
|
|
1565
|
+
const intercept = body.intercept === 'all' || body.intercept === 'claims'
|
|
1566
|
+
? body.intercept
|
|
1567
|
+
: live?.forwardProxy?.intercept ?? DEFAULT_FORWARD_PROXY_INTERCEPT;
|
|
1568
|
+
// A wildcard gateway claims EVERY host through `match()`, so a literal `'*'`
|
|
1569
|
+
// in this list would print as a host name. The set is exact claims only;
|
|
1570
|
+
// the wildcard's own attribution stays visible through `claimSources`.
|
|
1571
|
+
const claimed = [...listGatewayHosts()].filter((h) => h !== WILDCARD_HOST_CLAIM).sort();
|
|
1572
|
+
// Per-plugin attribution for the console's "decrypted without a rule" list:
|
|
1573
|
+
// the SAME live registry `listGatewayHosts()` unions, so the two can never
|
|
1574
|
+
// disagree — one is the host set, the other says who claimed it.
|
|
1575
|
+
const claimSources = [...listGateways().entries()]
|
|
1576
|
+
.map(([pluginId, gw]) => ({
|
|
1577
|
+
pluginId,
|
|
1578
|
+
hosts: [...new Set(gw.hosts.filter((h) => h !== WILDCARD_HOST_CLAIM))].sort(),
|
|
1579
|
+
}))
|
|
1580
|
+
.filter((s) => s.hosts.length > 0)
|
|
1581
|
+
.sort((a, b) => a.pluginId.localeCompare(b.pluginId));
|
|
1582
|
+
const host = typeof body.host === 'string' ? body.host.trim() : '';
|
|
1583
|
+
return {
|
|
1584
|
+
status: 'ok',
|
|
1585
|
+
rules,
|
|
1586
|
+
warnings: lintRules(rawRules, proxyEnabled, intercept),
|
|
1587
|
+
proxyEnabled,
|
|
1588
|
+
intercept,
|
|
1589
|
+
claimed,
|
|
1590
|
+
claimSources,
|
|
1591
|
+
// The resolver is the SAME function the proxy legs call, so the preview
|
|
1592
|
+
// can never disagree with the live decision.
|
|
1593
|
+
decision: host ? resolveHost(host, rules, { claimed: new Set(claimed), intercept }) : null,
|
|
1594
|
+
};
|
|
1595
|
+
});
|
|
1596
|
+
// 3A5. One-click "tighten to allowlist" (ADR-0018 Revision 4). An install
|
|
1597
|
+
// that predates the claims posture still carries the old `* → intercept`
|
|
1598
|
+
// catch-all, which now decrypts nothing extra yet reads as "decrypt
|
|
1599
|
+
// everything". Tightening rewrites the catch-all to a blind tunnel (keeping
|
|
1600
|
+
// its egress) and pins the posture to `claims` — through the SAME save path
|
|
1601
|
+
// the console's Save button uses (config.yaml write + hot-apply), and ONLY
|
|
1602
|
+
// when the operator clicked: nothing here runs on boot.
|
|
1603
|
+
app.post('/api/admin/forward-proxy/tighten', async (_req, reply) => {
|
|
1604
|
+
const live = getRuntimeConfigRef();
|
|
1605
|
+
const current = live?.forwardProxy ?? loadConfig().forwardProxy ?? {};
|
|
1606
|
+
const currentRules = current.rules ?? [];
|
|
1607
|
+
const catchAll = currentRules.find((r) => r?.match === '*');
|
|
1608
|
+
const egress = catchAll?.egress ?? DEFAULT_FORWARD_PROXY_RULES[0].egress;
|
|
1609
|
+
// Rewrite ONLY the catch-all's ingress. Specific `intercept` rows are
|
|
1610
|
+
// explicit operator intent (they keep decrypting under `claims`) and every
|
|
1611
|
+
// other row stays exactly as written — tightening must never be a way to
|
|
1612
|
+
// lose rules the operator typed.
|
|
1613
|
+
const rules = catchAll
|
|
1614
|
+
? currentRules.map((r) => r?.match === '*' && r.ingress === 'intercept' ? { ...r, ingress: 'passthrough' } : r)
|
|
1615
|
+
: [...currentRules, { match: '*', ingress: 'passthrough', egress }];
|
|
1616
|
+
const saved = saveConfig({ forwardProxy: { ...current, rules, intercept: DEFAULT_FORWARD_PROXY_INTERCEPT } });
|
|
1617
|
+
if (!saved.success)
|
|
1618
|
+
return reply.status(400).send(saved);
|
|
1619
|
+
// Hot-apply: saveConfig's auth-view sync replaces `live.forwardProxy` and
|
|
1620
|
+
// every proxy leg re-reads it per request, so no restart is involved.
|
|
1621
|
+
return {
|
|
1622
|
+
status: 'ok',
|
|
1623
|
+
rules,
|
|
1624
|
+
intercept: DEFAULT_FORWARD_PROXY_INTERCEPT,
|
|
1625
|
+
warnings: lintRules(rules, live?.proxy?.enabled === true, DEFAULT_FORWARD_PROXY_INTERCEPT),
|
|
1626
|
+
};
|
|
1627
|
+
});
|
|
865
1628
|
// 3B. Token usage aggregation from the trace ring: windowed totals plus
|
|
866
1629
|
// per-API-key rows (raw counts only — no cost accounting). Optional
|
|
867
1630
|
// `?since=<epoch-ms>` narrows to traces with `timestamp >= since`;
|
|
@@ -1006,21 +1769,23 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1006
1769
|
// 4. Client Interception Setup / Teardown
|
|
1007
1770
|
const handleSetup = async (req, reply) => {
|
|
1008
1771
|
const { client } = req.params;
|
|
1009
|
-
const { models, apiKey, contextWindow, extraModels, agentModels,
|
|
1772
|
+
const { models, apiKey, contextWindow, extraModels, virtualModels, agentModels, product, acknowledgeRunning } = (req.body || {});
|
|
1010
1773
|
const cleaned = models && typeof models === 'object'
|
|
1011
1774
|
? Object.fromEntries(Object.entries(models).map(([k, v]) => [k, String(v ?? 'auto').trim() || 'auto']))
|
|
1012
1775
|
: undefined;
|
|
1013
1776
|
const cleanedExtra = Array.isArray(extraModels)
|
|
1014
1777
|
? extraModels.map(s => String(s || '').trim()).filter(Boolean)
|
|
1015
1778
|
: undefined;
|
|
1779
|
+
// Follow-mode virtual block: clamp to the known tier aliases in canonical
|
|
1780
|
+
// order — the field carries the key policy's allowed verdicts, never
|
|
1781
|
+
// arbitrary ids (concrete pins ride in extraModels).
|
|
1782
|
+
const cleanedVirtual = Array.isArray(virtualModels)
|
|
1783
|
+
? [...VIRTUAL_AUTO_IDS].filter(id => virtualModels.map(s => String(s || '').trim()).includes(id))
|
|
1784
|
+
: undefined;
|
|
1016
1785
|
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).
|
|
1786
|
+
// Agent-binding payload (opencode hook): manual rows — agent name →
|
|
1787
|
+
// modelRef (''/'auto' dropped). A wrong write to opencode.jsonc is harder
|
|
1788
|
+
// to undo than a refused setup, so every ref must be routable (fail-fast).
|
|
1024
1789
|
const allowedRefs = new Set([
|
|
1025
1790
|
// 'auto' is a legal slot ref (inherit-the-default): the adapter skips it.
|
|
1026
1791
|
'auto', 'lite', 'plus', 'pro', 'ultra',
|
|
@@ -1046,59 +1811,24 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1046
1811
|
manual[agentName] = ref;
|
|
1047
1812
|
}
|
|
1048
1813
|
}
|
|
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}`);
|
|
1814
|
+
// Fail-fast on any ref the gateway cannot resolve.
|
|
1815
|
+
const invalid = Object.entries(manual).filter(([, ref]) => !allowedRefs.has(ref)).map(([name, ref]) => `${name}→${ref}`);
|
|
1088
1816
|
if (invalid.length > 0) {
|
|
1089
1817
|
return reply.status(400).send({
|
|
1090
1818
|
success: false,
|
|
1091
1819
|
message: `Agent model refs not routable: ${invalid.join(', ')} — register the model / combo first`,
|
|
1092
1820
|
});
|
|
1093
1821
|
}
|
|
1094
|
-
const agentModelsPayload = agentModels !== undefined
|
|
1822
|
+
const agentModelsPayload = agentModels !== undefined ? manual : undefined;
|
|
1095
1823
|
const result = await setupClient(client, {
|
|
1096
1824
|
...(cleaned ? { models: cleaned } : {}),
|
|
1097
1825
|
...(apiKey?.trim() ? { apiKey: apiKey.trim() } : {}),
|
|
1098
1826
|
...(Number.isFinite(cw) && cw > 0 ? { contextWindow: Math.floor(cw) } : {}),
|
|
1099
1827
|
...(cleanedExtra ? { extraModels: cleanedExtra } : {}),
|
|
1828
|
+
...(cleanedVirtual !== undefined ? { virtualModels: cleanedVirtual } : {}),
|
|
1100
1829
|
...(agentModelsPayload ? { agentModels: agentModelsPayload } : {}),
|
|
1101
|
-
...(
|
|
1830
|
+
...(typeof product === 'string' && product.trim() ? { product: product.trim() } : {}),
|
|
1831
|
+
...(acknowledgeRunning === true ? { acknowledgeRunning: true } : {}),
|
|
1102
1832
|
});
|
|
1103
1833
|
if (!result.success)
|
|
1104
1834
|
return reply.status(400).send(result);
|
|
@@ -1106,7 +1836,11 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1106
1836
|
};
|
|
1107
1837
|
const handleTeardown = async (req, reply) => {
|
|
1108
1838
|
const { client } = req.params;
|
|
1109
|
-
const
|
|
1839
|
+
const { product, acknowledgeRunning } = (req.body || {});
|
|
1840
|
+
const result = await teardownClient(client, {
|
|
1841
|
+
...(typeof product === 'string' && product.trim() ? { product: product.trim() } : {}),
|
|
1842
|
+
...(acknowledgeRunning === true ? { acknowledgeRunning: true } : {}),
|
|
1843
|
+
});
|
|
1110
1844
|
if (!result.success)
|
|
1111
1845
|
return reply.status(400).send(result);
|
|
1112
1846
|
return result;
|
|
@@ -1118,7 +1852,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1118
1852
|
* Deliberately the SAME cascade the /v1/systemone surface applies (ADR-0008),
|
|
1119
1853
|
* so a name means one thing console-wide: a registered id, or a combo (its
|
|
1120
1854
|
* leader member answers — the same leader pick the routing path uses), is
|
|
1121
|
-
* used as-is; a bare tier alias projects onto the
|
|
1855
|
+
* used as-is; a bare tier alias projects onto the leading model of its healthy
|
|
1122
1856
|
* DECISION-SURFACE pool (the read that keeps systemone-wire models in view);
|
|
1123
1857
|
* bare `auto` means `systemone.defaultModel`. Undefined = nothing routable
|
|
1124
1858
|
* behind the name (unknown id, combo without members, empty/all-unhealthy
|
|
@@ -1141,18 +1875,47 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1141
1875
|
}
|
|
1142
1876
|
return undefined;
|
|
1143
1877
|
};
|
|
1878
|
+
/** Compact context window: 200000 → '200k', 1_048_576 → '1M'. */
|
|
1879
|
+
const fmtContext = (n) => n >= 1_000_000 ? `${+((n / 1_000_000).toFixed(1))}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
|
|
1880
|
+
/**
|
|
1881
|
+
* Catalog enrichment tokens — decision-relevant facts the registry
|
|
1882
|
+
* registration does not carry, appended to a registered model's (or
|
|
1883
|
+
* variant's) description. Conditional by design: majority-true facts
|
|
1884
|
+
* (tool_call=yes, no image support on a text-only fleet) stay SILENT so the
|
|
1885
|
+
* per-question criteria repetition does not bloat the prompt — a token
|
|
1886
|
+
* appears only when it distinguishes the candidate or warns about it.
|
|
1887
|
+
*/
|
|
1888
|
+
const catalogTokens = (cat) => {
|
|
1889
|
+
if (!cat)
|
|
1890
|
+
return [];
|
|
1891
|
+
const tokens = [];
|
|
1892
|
+
const ctx = cat.limit?.context;
|
|
1893
|
+
if (typeof ctx === 'number' && Number.isFinite(ctx) && ctx > 0)
|
|
1894
|
+
tokens.push(`context=${fmtContext(ctx)}`);
|
|
1895
|
+
const inMods = cat.modalities?.input;
|
|
1896
|
+
if (Array.isArray(inMods) && inMods.includes('image'))
|
|
1897
|
+
tokens.push('vision=yes (accepts image input)');
|
|
1898
|
+
if (cat.tool_call === false)
|
|
1899
|
+
tokens.push('tools=NO — cannot call tools, unsuitable for agent roles');
|
|
1900
|
+
if (cat.status === 'deprecated')
|
|
1901
|
+
tokens.push('status=deprecated — avoid unless no alternative');
|
|
1902
|
+
return tokens;
|
|
1903
|
+
};
|
|
1144
1904
|
/**
|
|
1145
1905
|
* One-line, model-readable description of a candidate — `criteria` values are
|
|
1146
1906
|
* the ONLY per-option context the decision prompt carries (the whole
|
|
1147
1907
|
* questions document is serialized verbatim by convert.ts
|
|
1148
1908
|
* buildDecisionChatRequest). Registry data is the objective half (tier
|
|
1149
|
-
* membership, price, reasoning support, wire);
|
|
1150
|
-
*
|
|
1151
|
-
*
|
|
1152
|
-
*
|
|
1153
|
-
*
|
|
1909
|
+
* membership, price, reasoning support, wire); catalog enrichment adds the
|
|
1910
|
+
* capability/context/lifecycle facts the registration does not carry
|
|
1911
|
+
* (context window, vision, tool calling, deprecated status) — see
|
|
1912
|
+
* catalogTokens. The frontend-supplied note carries what neither source can
|
|
1913
|
+
* know (caller context). Virtual ids resolve to no entity and are described
|
|
1914
|
+
* by what they MEAN, since "assign `lite`" is a legitimate pick. Deliberately
|
|
1915
|
+
* NO tier ladder here: writing "ultra = broadest" made every role land on
|
|
1916
|
+
* `ultra`.
|
|
1154
1917
|
*/
|
|
1155
|
-
const describeCandidate = (rawId, note) => {
|
|
1918
|
+
const describeCandidate = (rawId, note, cat) => {
|
|
1156
1919
|
const m = registry.getModel(rawId);
|
|
1157
1920
|
let body;
|
|
1158
1921
|
if (m) {
|
|
@@ -1160,6 +1923,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1160
1923
|
const parts = [
|
|
1161
1924
|
`registered model; tiers=${tiers.length > 0 ? tiers.join('|') : 'none'}`,
|
|
1162
1925
|
`price $${m.pricing?.input ?? 0}/$${m.pricing?.output ?? 0} per 1M tokens in/out`,
|
|
1926
|
+
...catalogTokens(cat),
|
|
1163
1927
|
];
|
|
1164
1928
|
if (m.wire === 'systemone') {
|
|
1165
1929
|
parts.push('wire=systemone — decision protocol ONLY, cannot serve chat, never assign it to a chat role');
|
|
@@ -1178,14 +1942,17 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1178
1942
|
// Variant sibling id (`<baseId>-<variantId>`): not a registry entry of its
|
|
1179
1943
|
// own — the base model plus a pinned reasoning level (orchestrator
|
|
1180
1944
|
// resolves it the same way). Calling it unregistered would steer the
|
|
1181
|
-
// decider away from a perfectly legal pick.
|
|
1945
|
+
// decider away from a perfectly legal pick. The caller looks the catalog
|
|
1946
|
+
// record up by the BASE id and passes it in.
|
|
1182
1947
|
const { base, variant } = registry.resolveVariantRef(rawId);
|
|
1183
1948
|
const tiers = registry.tiersOf(base);
|
|
1949
|
+
const catTokens = catalogTokens(cat);
|
|
1184
1950
|
body =
|
|
1185
1951
|
`variant of ${base.id} (pins reasoning_effort '${variant.reasoningEffort}'); ` +
|
|
1186
1952
|
`tiers=${tiers.length > 0 ? tiers.join('|') : 'none'}; ` +
|
|
1187
|
-
`price $${base.pricing?.input ?? 0}/$${base.pricing?.output ?? 0} per 1M tokens in/out
|
|
1188
|
-
|
|
1953
|
+
`price $${base.pricing?.input ?? 0}/$${base.pricing?.output ?? 0} per 1M tokens in/out` +
|
|
1954
|
+
(catTokens.length > 0 ? `; ${catTokens.join('; ')}` : '') +
|
|
1955
|
+
`; wire=${base.wire ?? 'unknown'}`;
|
|
1189
1956
|
}
|
|
1190
1957
|
else if (registry.isCombo(rawId)) {
|
|
1191
1958
|
body = `combo; members=${registry.resolveCombo(rawId).length} (the router picks a healthy member per request)`;
|
|
@@ -1217,8 +1984,8 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1217
1984
|
const body = (req.body || {});
|
|
1218
1985
|
const decider = (body.deciderModel || '').trim();
|
|
1219
1986
|
const targets = Array.isArray(body.targets) ? body.targets.filter((t) => t && t.key) : [];
|
|
1220
|
-
// Candidates are plain ids or { id, note } — the note (
|
|
1221
|
-
//
|
|
1987
|
+
// Candidates are plain ids or { id, note } — the note (caller-supplied
|
|
1988
|
+
// context) contextualizes the choice but only `id` is a
|
|
1222
1989
|
// legal assignment value.
|
|
1223
1990
|
const rawCandidates = Array.isArray(body.candidates) ? body.candidates : [];
|
|
1224
1991
|
const candidates = rawCandidates
|
|
@@ -1244,7 +2011,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1244
2011
|
// Tier PURPOSE (what each rung is for), never a ranking: a ladder reads
|
|
1245
2012
|
// as "ultra is the most/broadest" and then every role lands on it.
|
|
1246
2013
|
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.',
|
|
2014
|
+
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
2015
|
roles: targets.map((t) => ({
|
|
1249
2016
|
key: t.key,
|
|
1250
2017
|
name: t.label || t.key,
|
|
@@ -1256,13 +2023,37 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1256
2023
|
...(t.current ? { current: t.current } : {}),
|
|
1257
2024
|
})),
|
|
1258
2025
|
};
|
|
2026
|
+
// Catalog enrichment, loaded ONCE per request: capability/context/lifecycle
|
|
2027
|
+
// facts the registry registration does not carry (see catalogTokens).
|
|
2028
|
+
// Lookup key is the provider-qualified registration id (`<provider>/<model>`
|
|
2029
|
+
// — exactly how boot-direct names registrations), so a plain Map.get per
|
|
2030
|
+
// candidate; variants resolve through their BASE id. Failure degrades
|
|
2031
|
+
// gracefully: candidates fall back to the registry-only description.
|
|
2032
|
+
const { catalogRepository } = await import('../opencode/catalog/repository.js');
|
|
2033
|
+
const catalogModels = new Map();
|
|
2034
|
+
try {
|
|
2035
|
+
for (const rec of await catalogRepository.list()) {
|
|
2036
|
+
for (const cm of rec.models)
|
|
2037
|
+
catalogModels.set(`${rec.id}/${cm.id}`, cm);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
catch {
|
|
2041
|
+
// catalog unavailable — describeCandidate simply receives undefined
|
|
2042
|
+
}
|
|
2043
|
+
const catalogOf = (rawId) => {
|
|
2044
|
+
const m = registry.getModel(rawId);
|
|
2045
|
+
if (m)
|
|
2046
|
+
return catalogModels.get(m.id);
|
|
2047
|
+
const v = registry.resolveVariantRef(rawId);
|
|
2048
|
+
return v ? catalogModels.get(v.base.id) : undefined;
|
|
2049
|
+
};
|
|
1259
2050
|
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
2051
|
const questions = {};
|
|
1261
2052
|
for (const t of targets) {
|
|
1262
2053
|
questions[t.key] = {
|
|
1263
2054
|
type: 'choice',
|
|
1264
2055
|
instructions: rubric,
|
|
1265
|
-
criteria: Object.fromEntries(candidates.map((c) => [c.id, describeCandidate(c.id, c.note)])),
|
|
2056
|
+
criteria: Object.fromEntries(candidates.map((c) => [c.id, describeCandidate(c.id, c.note, catalogOf(c.id))])),
|
|
1266
2057
|
};
|
|
1267
2058
|
}
|
|
1268
2059
|
const params = req.params;
|
|
@@ -1305,7 +2096,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1305
2096
|
targets: targets.length,
|
|
1306
2097
|
candidates: candidates.length,
|
|
1307
2098
|
criteriaChars: JSON.stringify(questions).length,
|
|
1308
|
-
criteriaSample: candidates[0] ? describeCandidate(candidates[0].id, candidates[0].note) : '',
|
|
2099
|
+
criteriaSample: candidates[0] ? describeCandidate(candidates[0].id, candidates[0].note, catalogOf(candidates[0].id)) : '',
|
|
1309
2100
|
state,
|
|
1310
2101
|
answers: Object.fromEntries(Object.entries((response?.answers || {})).map(([k, v]) => [k, v?.choice])),
|
|
1311
2102
|
usage: response?.usage,
|
|
@@ -1346,14 +2137,13 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1346
2137
|
}
|
|
1347
2138
|
return { success: true, model: raw, resolved: model.id };
|
|
1348
2139
|
});
|
|
1349
|
-
// 4a. OpenCode agent inventory (model-
|
|
2140
|
+
// 4a. OpenCode agent inventory (agent model-binding UI): live v2 service
|
|
1350
2141
|
// roster (`GET /api/agent`, plugins included) with the file scan
|
|
1351
2142
|
// (built-ins + agent(s)/*.md + config nodes) as offline fallback.
|
|
1352
2143
|
app.get('/api/admin/opencode/agents', async () => ({ status: 'ok', agents: await listOpenCodeAgentsLive() }));
|
|
1353
2144
|
// 4b. Console webAuth — login/logout/session probes + credential management.
|
|
1354
2145
|
// 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).
|
|
2146
|
+
// the two config endpoints ride the normal console gate (session cookie).
|
|
1357
2147
|
app.get('/api/admin/auth/session', async (req) => {
|
|
1358
2148
|
const disk = getRuntimeConfigRef() || loadConfig(); // runtime snapshot (see gate comment)
|
|
1359
2149
|
const active = isWebAuthActive(disk);
|
|
@@ -1475,27 +2265,34 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1475
2265
|
// invariant 6). Within circuitBreaker only persistence.debounceMs still
|
|
1476
2266
|
// needs a restart — the state store binds its debounce at boot.
|
|
1477
2267
|
initProxyConfig(loadConfig().proxy);
|
|
2268
|
+
void reconcileMihomoSidecar(loadConfig().proxy).catch((err) => {
|
|
2269
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2270
|
+
console.warn(`[Clash] reconcile after config save failed: ${message}`);
|
|
2271
|
+
});
|
|
1478
2272
|
orchestrator.getCaptureRecorder().applyConfig(loadConfig().requestCapture);
|
|
1479
2273
|
applyDecisionCaptureConfig(loadConfig().classifier?.layer2); // L2 dataset sampling: single-key gate classifier.layer2.collectEnabled, hot too
|
|
1480
2274
|
applyRouteEntriesConfig(loadConfig().routeEntries); // experience-table gate: hot-applies lookup/writes
|
|
1481
2275
|
applyDirectivesConfig(loadConfig().directives); // directive gate: hot-applies the reserved namespace + kill switch
|
|
2276
|
+
applyStreamingPosture(loadConfig().streaming); // streaming posture: both axes are read per request, so a save lands immediately
|
|
1482
2277
|
orchestrator.getRegistry().applyCombos(loadConfig().combos);
|
|
1483
2278
|
orchestrator.getRegistry().applyTierConfigNow(); // tier member lists commit immediately (no restart)
|
|
2279
|
+
try {
|
|
2280
|
+
await refreshDirectPool(orchestrator.getRegistry()); // provider-def sync: models/wires/chains match the defs file (no restart)
|
|
2281
|
+
}
|
|
2282
|
+
catch (err) {
|
|
2283
|
+
// Fail-open, but never silent: the registry keeps serving and may drift.
|
|
2284
|
+
console.warn(`[console] pool resync after config save failed (registry may drift): ${err.message}`);
|
|
2285
|
+
}
|
|
1484
2286
|
warnOnEmptyTierPools(); // no residual tier → an empty pool is now possible
|
|
1485
2287
|
orchestrator
|
|
1486
2288
|
.getRegistry()
|
|
1487
2289
|
.getCircuitBreakerManager()
|
|
1488
2290
|
.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
2291
|
return result;
|
|
1495
2292
|
};
|
|
1496
2293
|
app.post('/api/admin/config', handleSaveConfig);
|
|
1497
2294
|
// 6. Raw YAML Configuration
|
|
1498
|
-
app.get('/api/admin/config/raw', async () => ({ status: 'ok', yaml: getRawConfig() }));
|
|
2295
|
+
app.get('/api/admin/config/raw', async () => ({ status: 'ok', yaml: getRawConfig(), path: getConfigPath() }));
|
|
1499
2296
|
const handleSaveRawYaml = async (req, reply) => {
|
|
1500
2297
|
const body = req.body;
|
|
1501
2298
|
if (!body?.yaml || typeof body.yaml !== 'string') {
|
|
@@ -1505,10 +2302,15 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1505
2302
|
if (!result.success)
|
|
1506
2303
|
return reply.status(400).send(result);
|
|
1507
2304
|
initProxyConfig(loadConfig().proxy); // hot-apply proxy policy (see handleSaveConfig)
|
|
2305
|
+
void reconcileMihomoSidecar(loadConfig().proxy).catch((err) => {
|
|
2306
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2307
|
+
console.warn(`[Clash] reconcile after config save failed: ${message}`);
|
|
2308
|
+
});
|
|
1508
2309
|
orchestrator.getCaptureRecorder().applyConfig(loadConfig().requestCapture); // hot-apply capture too
|
|
1509
2310
|
applyDecisionCaptureConfig(loadConfig().classifier?.layer2); // hot-apply the L2 dataset-sampling gate too (classifier.layer2.collectEnabled)
|
|
1510
2311
|
applyRouteEntriesConfig(loadConfig().routeEntries); // hot-apply the experience-table gate too
|
|
1511
2312
|
applyDirectivesConfig(loadConfig().directives); // hot-apply the directive namespace too
|
|
2313
|
+
applyStreamingPosture(loadConfig().streaming); // hot-apply the streaming posture too (two axes, per-request reads)
|
|
1512
2314
|
orchestrator.getRegistry().applyCombos(loadConfig().combos); // hot-apply combos too
|
|
1513
2315
|
orchestrator.getRegistry().applyTierConfigNow(); // hot-commit tier member lists too
|
|
1514
2316
|
warnOnEmptyTierPools(); // no residual tier → an empty pool is now possible
|
|
@@ -1516,19 +2318,37 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1516
2318
|
.getRegistry()
|
|
1517
2319
|
.getCircuitBreakerManager()
|
|
1518
2320
|
.applyConfig(loadConfig().circuitBreaker, loadConfig().retry); // hot-apply breaker rules too (see handleSaveConfig)
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
2321
|
+
try {
|
|
2322
|
+
await refreshDirectPool(orchestrator.getRegistry()); // provider-def sync on the raw path too (no restart)
|
|
2323
|
+
}
|
|
2324
|
+
catch (err) {
|
|
2325
|
+
// Fail-open, but never silent: the registry keeps serving and may drift.
|
|
2326
|
+
console.warn(`[console] pool resync after config save failed (registry may drift): ${err.message}`);
|
|
2327
|
+
}
|
|
1523
2328
|
return result;
|
|
1524
2329
|
};
|
|
1525
2330
|
app.post('/api/admin/config/raw', handleSaveRawYaml);
|
|
2331
|
+
// 6b. Dynamic comment panel data — config.yaml is ZERO-COMMENT on disk
|
|
2332
|
+
// (ADR-0016); the Config File page renders per-field comments from these
|
|
2333
|
+
// dictionaries in the operator's language. Runtime-path keyed; the panel
|
|
2334
|
+
// walks the flat runtime shape the same way loadConfig expands it.
|
|
2335
|
+
app.get('/api/admin/config/comments', async (req) => {
|
|
2336
|
+
const query = req.query;
|
|
2337
|
+
const lang = commentLangFromQuery(query.lang);
|
|
2338
|
+
const zh = lang === 'zh-CN';
|
|
2339
|
+
return {
|
|
2340
|
+
status: 'ok',
|
|
2341
|
+
lang,
|
|
2342
|
+
header: zh ? YAML_FILE_HEADER_ZH : YAML_FILE_HEADER_EN,
|
|
2343
|
+
fields: zh ? YAML_FIELD_COMMENTS_ZH : YAML_FIELD_COMMENTS_EN,
|
|
2344
|
+
};
|
|
2345
|
+
});
|
|
1526
2346
|
// 6a. Forward-proxy MITM CA export — clients using the inbound forward
|
|
1527
2347
|
// proxy must trust this CA. Generated on first request when absent (the
|
|
1528
2348
|
// same idempotent ensureCa the proxy itself uses).
|
|
1529
2349
|
const handleForwardProxyCa = async (_req, reply) => {
|
|
1530
2350
|
const cfg = loadConfig();
|
|
1531
|
-
const caDir = cfg.forwardProxy?.caDir
|
|
2351
|
+
const caDir = resolveCaDir(cfg.forwardProxy?.caDir);
|
|
1532
2352
|
try {
|
|
1533
2353
|
const ca = ensureCa(caDir);
|
|
1534
2354
|
reply.header('content-type', 'application/x-pem-file');
|
|
@@ -1540,6 +2360,39 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1540
2360
|
}
|
|
1541
2361
|
};
|
|
1542
2362
|
app.get('/api/admin/proxy/ca', handleForwardProxyCa);
|
|
2363
|
+
// 6a-bis. CA identity for the console card: absolute path, SHA-256
|
|
2364
|
+
// fingerprint and validity. Never key material — clients use it to check
|
|
2365
|
+
// that the root they installed is the root this proxy signs with.
|
|
2366
|
+
app.get('/api/admin/proxy/ca/meta', async (_req, reply) => {
|
|
2367
|
+
const cfg = loadConfig();
|
|
2368
|
+
try {
|
|
2369
|
+
return { status: 'ok', ...describeCa(cfg.forwardProxy?.caDir) };
|
|
2370
|
+
}
|
|
2371
|
+
catch (err) {
|
|
2372
|
+
return reply.status(500).send({ status: 'error', message: err?.message || 'Failed to load CA' });
|
|
2373
|
+
}
|
|
2374
|
+
});
|
|
2375
|
+
// 6a-ter. Trust state for the console card: does the platform store that
|
|
2376
|
+
// clients verify against hold THIS CA? Tri-state on purpose — `unknown` means
|
|
2377
|
+
// the probe could not run, never "not trusted". Cached 60s (the probe spawns
|
|
2378
|
+
// platform tools); `force=1` bypasses the TTL for an operator re-check after
|
|
2379
|
+
// an install.
|
|
2380
|
+
app.get('/api/admin/proxy/ca/trust', async (req) => {
|
|
2381
|
+
const cfg = loadConfig();
|
|
2382
|
+
const caPath = caCertPath(cfg.forwardProxy?.caDir);
|
|
2383
|
+
const force = String(req.query?.force ?? '') === '1';
|
|
2384
|
+
// Fail SOFT: the console renders a tri-state chip, so a probe that cannot
|
|
2385
|
+
// run is `unknown`, never a 500 that makes the chip silently disappear.
|
|
2386
|
+
// `checkedAt` stays absent while no probe ran (no PEM to identify).
|
|
2387
|
+
if (!fs.existsSync(caPath))
|
|
2388
|
+
return { status: 'ok', trusted: 'unknown', caPath };
|
|
2389
|
+
try {
|
|
2390
|
+
return { status: 'ok', ...(await probeCaTrustedCached(caPath, { force })), caPath };
|
|
2391
|
+
}
|
|
2392
|
+
catch {
|
|
2393
|
+
return { status: 'ok', trusted: 'unknown', caPath };
|
|
2394
|
+
}
|
|
2395
|
+
});
|
|
1543
2396
|
// 6b. Tier member lists — candidate pool snapshots (console preview).
|
|
1544
2397
|
// membership is a PURE projection of (model id × tiers.members);
|
|
1545
2398
|
// PREVIEW never mutates live pools — real membership is committed ONLY by
|
|
@@ -1555,9 +2408,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1555
2408
|
isDefaultInTier: Boolean(model.isDefaultInTier),
|
|
1556
2409
|
inputPrice: model.pricing?.input,
|
|
1557
2410
|
outputPrice: model.pricing?.output,
|
|
1558
|
-
// Decision 6 aggregate: healthy iff
|
|
1559
|
-
// a
|
|
1560
|
-
//
|
|
2411
|
+
// Decision 6 aggregate: healthy iff at least one credential tuple serves —
|
|
2412
|
+
// a model whose every credential is cooling shows down here exactly as it
|
|
2413
|
+
// does to the pool builders.
|
|
1561
2414
|
healthy: registry.modelAvailable(model).available,
|
|
1562
2415
|
weight,
|
|
1563
2416
|
}));
|
|
@@ -1622,9 +2475,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1622
2475
|
isDefaultInTier: Boolean(model.isDefaultInTier),
|
|
1623
2476
|
inputPrice: model.pricing?.input,
|
|
1624
2477
|
outputPrice: model.pricing?.output,
|
|
1625
|
-
// Decision 6 aggregate: healthy iff
|
|
1626
|
-
// a
|
|
1627
|
-
//
|
|
2478
|
+
// Decision 6 aggregate: healthy iff at least one credential tuple serves —
|
|
2479
|
+
// a model whose every credential is cooling shows down here exactly as it
|
|
2480
|
+
// does to the pool builders.
|
|
1628
2481
|
healthy: registry.modelAvailable(model).available,
|
|
1629
2482
|
weight,
|
|
1630
2483
|
})),
|
|
@@ -1687,7 +2540,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1687
2540
|
// the bare tier alias: the same force_tier path a client's
|
|
1688
2541
|
// `model: "pro"` request takes (tier aliases are reserved gateway ids,
|
|
1689
2542
|
// never classifier-routed). One run only
|
|
1690
|
-
// exercises the SELECTED member (the
|
|
2543
|
+
// exercises the SELECTED member (the default credential, or the weighted/round-robin
|
|
1691
2544
|
// pick), never the whole pool — deep per-model checks stay on the providers
|
|
1692
2545
|
// page. An EMPTY tier degrades inside getModelForTier (the session-pin birth
|
|
1693
2546
|
// representative falls down the escalate→plus→lite chain, server-warned with
|
|
@@ -1703,9 +2556,10 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1703
2556
|
try {
|
|
1704
2557
|
const result = await orchestrator.process({
|
|
1705
2558
|
model: tier,
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
2559
|
+
stream: false,
|
|
2560
|
+
input: [{ type: 'message', role: 'user', content: [{ type: 'text', text: 'ping' }] }],
|
|
2561
|
+
generation: { maxOutputTokens: 1 },
|
|
2562
|
+
}, { wire: 'openai-chat', clientIp: req.ip, headers: req.headers, fastifyRequest: req });
|
|
1709
2563
|
return {
|
|
1710
2564
|
status: 'ok',
|
|
1711
2565
|
ok: true,
|
|
@@ -1930,18 +2784,20 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1930
2784
|
};
|
|
1931
2785
|
for (const prefix of ['/api/admin']) {
|
|
1932
2786
|
app.get(`${prefix}/catalog/sources`, listCatalogSources);
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
app.post(`${prefix}/catalog/sources
|
|
1936
|
-
app.
|
|
1937
|
-
app.
|
|
2787
|
+
// Source mutations change the catalog universe the pool builder consumes —
|
|
2788
|
+
// resync the pool so pricing/modality/tier inputs cannot drift.
|
|
2789
|
+
app.post(`${prefix}/catalog/sources`, withPoolSync(registry, handleAddCatalogSource));
|
|
2790
|
+
app.post(`${prefix}/catalog/sources/refresh`, withPoolSync(registry, handleRefreshCatalogSources));
|
|
2791
|
+
app.post(`${prefix}/catalog/sources/:id/refresh`, withPoolSync(registry, handleRefreshCatalogSource));
|
|
2792
|
+
app.put(`${prefix}/catalog/sources/:id`, withPoolSync(registry, handleToggleCatalogSource));
|
|
2793
|
+
app.delete(`${prefix}/catalog/sources/:id`, withPoolSync(registry, handleRemoveCatalogSource));
|
|
1938
2794
|
app.get(`${prefix}/catalog/sources/:id/data`, getCatalogSourceData);
|
|
1939
2795
|
app.get(`${prefix}/catalog/locked-models`, listLockedCatalogModels);
|
|
1940
|
-
app.post(`${prefix}/catalog/locked-models`, handleLockCatalogModel);
|
|
2796
|
+
app.post(`${prefix}/catalog/locked-models`, withPoolSync(registry, handleLockCatalogModel));
|
|
1941
2797
|
app.get(`${prefix}/catalog/ocr`, getCatalogOcr);
|
|
1942
2798
|
app.get(`${prefix}/catalog/override`, handleGetCatalogOverride);
|
|
1943
|
-
app.put(`${prefix}/catalog/override`, handlePutCatalogOverride);
|
|
1944
|
-
app.delete(`${prefix}/catalog/override`, handleDeleteCatalogOverride);
|
|
2799
|
+
app.put(`${prefix}/catalog/override`, withPoolSync(registry, handlePutCatalogOverride));
|
|
2800
|
+
app.delete(`${prefix}/catalog/override`, withPoolSync(registry, handleDeleteCatalogOverride));
|
|
1945
2801
|
app.post(`${prefix}/catalog/sync-interval`, handleSetCatalogSyncInterval);
|
|
1946
2802
|
}
|
|
1947
2803
|
// 6c. Custom model combos — resolved member view for the /combos console
|
|
@@ -1972,7 +2828,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
1972
2828
|
tier: model?.tier,
|
|
1973
2829
|
inputPrice: model?.pricing?.input,
|
|
1974
2830
|
outputPrice: model?.pricing?.output,
|
|
1975
|
-
breakerState: model ? cb.
|
|
2831
|
+
breakerState: model ? cb.getSnapshot(model.id)?.state ?? 'CLOSED' : undefined,
|
|
1976
2832
|
};
|
|
1977
2833
|
}),
|
|
1978
2834
|
}));
|
|
@@ -2001,9 +2857,10 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2001
2857
|
try {
|
|
2002
2858
|
const result = await orchestrator.process({
|
|
2003
2859
|
model: id,
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2860
|
+
stream: false,
|
|
2861
|
+
input: [{ type: 'message', role: 'user', content: [{ type: 'text', text: 'ping' }] }],
|
|
2862
|
+
generation: { maxOutputTokens: 1 },
|
|
2863
|
+
}, { wire: 'openai-chat', clientIp: req.ip, headers: req.headers, fastifyRequest: req });
|
|
2007
2864
|
return {
|
|
2008
2865
|
status: 'ok',
|
|
2009
2866
|
ok: true,
|
|
@@ -2097,24 +2954,31 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2097
2954
|
});
|
|
2098
2955
|
};
|
|
2099
2956
|
const ocHandlers = {
|
|
2100
|
-
/** The
|
|
2101
|
-
* served to every UI surface that renders
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2957
|
+
/** The OCR protocol vocabulary — ONE backend-owned table (providers/vocabulary.ts)
|
|
2958
|
+
* served to every UI surface that renders protocol choices or display names. */
|
|
2959
|
+
protocolVocabulary: async () => {
|
|
2960
|
+
// Plugin-owned protocols are listed only while a loaded plugin claims the
|
|
2961
|
+
// wire — the table derives that half from the plugin registry, so this
|
|
2962
|
+
// handler never filters by vendor name (providers/vocabulary.ts).
|
|
2963
|
+
return { status: 'ok', entries: protocolVocabulary() };
|
|
2105
2964
|
},
|
|
2106
|
-
list: async () => {
|
|
2965
|
+
list: async (req) => {
|
|
2107
2966
|
const { getProviderNodeById } = await import('../opencode/user-config.js');
|
|
2108
2967
|
const { getProviderDefsPath } = await import('../opencode/provider-defs.js');
|
|
2109
2968
|
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
2110
2969
|
const { catalogRepository } = await import('../opencode/catalog/repository.js');
|
|
2970
|
+
const takedowns = getProviderTakedownStore();
|
|
2111
2971
|
const store = await getCredentialStore();
|
|
2112
2972
|
// B4: credentials come from the BOUND store on every binding — the masked store
|
|
2113
2973
|
// credentials merge into the config views, so a stale auth.json entry can never
|
|
2114
2974
|
// masquerade as a connected provider.
|
|
2115
|
-
const
|
|
2975
|
+
const lang = typeof req.query?.lang === 'string' ? req.query.lang : undefined;
|
|
2976
|
+
const views = await storeProviderViews(store, lang);
|
|
2116
2977
|
const unified = await catalogRepository.list();
|
|
2117
2978
|
const byId = new Map(unified.map((p) => [p.id, p]));
|
|
2979
|
+
// Plugin-origin provenance for the Connected-tab origin filter — same
|
|
2980
|
+
// ledger join as the catalog endpoint (ADR-0010: never written to providers.json).
|
|
2981
|
+
const origins = pluginProviderOrigins();
|
|
2118
2982
|
return {
|
|
2119
2983
|
status: 'ok',
|
|
2120
2984
|
configPath: getProviderDefsPath(),
|
|
@@ -2123,6 +2987,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2123
2987
|
const u = byId.get(v.id);
|
|
2124
2988
|
const defNode = getProviderNodeById(v.id);
|
|
2125
2989
|
const hasDefNode = defNode !== undefined;
|
|
2990
|
+
const takedown = takedowns.get(v.id);
|
|
2126
2991
|
return {
|
|
2127
2992
|
...v,
|
|
2128
2993
|
// Precise delete-branch signal: an explicit defs-file node is the
|
|
@@ -2138,8 +3003,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2138
3003
|
// builtin-catalog coverage; an aggregated-unknown id (no catalog row
|
|
2139
3004
|
// at all) is by definition custom.
|
|
2140
3005
|
custom: u ? u.custom : true,
|
|
2141
|
-
logo: u?.logo,
|
|
3006
|
+
logo: u?.logo ?? v.logo,
|
|
2142
3007
|
npm: v.npm ?? u?.npm,
|
|
3008
|
+
// Operator takedown: routing state, never a defs-file field (ADR-0010).
|
|
3009
|
+
// The card stays listed so the operator can restore it with one click.
|
|
3010
|
+
disabled: takedown !== undefined,
|
|
3011
|
+
...(takedown?.reason ? { disabledReason: takedown.reason } : {}),
|
|
2143
3012
|
// Def-level custom headers (non-secret metadata — the edit dialog
|
|
2144
3013
|
// prefills from this; secrets live in the bound store, never here).
|
|
2145
3014
|
headers: defNode?.headers ?? defNode?.options?.headers,
|
|
@@ -2148,14 +3017,21 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2148
3017
|
// wire-base chain (def baseURL > models.dev `api` > live service
|
|
2149
3018
|
// hint) so the card shows the SAME endpoint inference routes to.
|
|
2150
3019
|
baseURL: v.baseURL || u?.baseURL || u?.api,
|
|
3020
|
+
// Owning plugin id when the def was registered by a plugin preset —
|
|
3021
|
+
// the Connected tab mirrors the catalog's origin filter on it.
|
|
3022
|
+
pluginOrigin: origins[v.id],
|
|
2151
3023
|
priceFrom: u ? catalogRepository.minInputPrice(u) : undefined,
|
|
2152
3024
|
modelsCount: u?.models.length ?? v.models.length,
|
|
2153
3025
|
};
|
|
2154
3026
|
}),
|
|
2155
3027
|
};
|
|
2156
3028
|
},
|
|
2157
|
-
catalog: async () => {
|
|
3029
|
+
catalog: async (req) => {
|
|
3030
|
+
const lang = typeof req.query?.lang === 'string' ? req.query.lang : undefined;
|
|
2158
3031
|
const { catalogRepository } = await import('../opencode/catalog/repository.js');
|
|
3032
|
+
// Plugin-origin provenance for the console tag/filter — ledger join only,
|
|
3033
|
+
// never a field written into providers.json (ADR-0010).
|
|
3034
|
+
const origins = pluginProviderOrigins();
|
|
2159
3035
|
const unified = await catalogRepository.list();
|
|
2160
3036
|
// Trim model arrays from the list payload (detail endpoint can serve them later)
|
|
2161
3037
|
const providers = unified.map((p) => ({
|
|
@@ -2169,11 +3045,68 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2169
3045
|
env: p.env,
|
|
2170
3046
|
custom: p.custom,
|
|
2171
3047
|
connected: p.connected,
|
|
3048
|
+
// Plugin merges below may forward a preset's web-authorization
|
|
3049
|
+
// capability onto this row.
|
|
3050
|
+
webLogin: undefined,
|
|
3051
|
+
webLoginSubmit: undefined,
|
|
3052
|
+
authTypes: undefined,
|
|
3053
|
+
keyHint: undefined,
|
|
3054
|
+
// Owning plugin id when the def was registered by a plugin preset.
|
|
3055
|
+
pluginOrigin: origins[p.id],
|
|
2172
3056
|
sources: p.sources,
|
|
2173
3057
|
modelCount: p.models.length,
|
|
2174
3058
|
priceFrom: catalogRepository.minInputPrice(p),
|
|
2175
3059
|
}));
|
|
2176
|
-
|
|
3060
|
+
// Plugin presets join the connect catalog (logo + one-click credential),
|
|
3061
|
+
// deduped against repository entries that already carry the same id.
|
|
3062
|
+
// Pure config-source rows are dropped: a defs-file node is already fully
|
|
3063
|
+
// presented on the Connected tab — the connect catalog is a DISCOVERY
|
|
3064
|
+
// surface (remote catalog sources + plugin presets), not a mirror of the
|
|
3065
|
+
// operator's own declared relays.
|
|
3066
|
+
try {
|
|
3067
|
+
const { pluginPresetCatalogEntries } = await import('../plugins/host.js');
|
|
3068
|
+
for (const preset of await pluginPresetCatalogEntries(lang)) {
|
|
3069
|
+
const idx = providers.findIndex((p) => p.id === preset.id);
|
|
3070
|
+
if (idx >= 0) {
|
|
3071
|
+
const existing = providers[idx];
|
|
3072
|
+
if (preset.connected || existing.sources.some((s) => s !== 'config')) {
|
|
3073
|
+
// Connected preset: the config entry IS the live row (its models
|
|
3074
|
+
// ride along) — keep it, just attach the plugin logo if missing.
|
|
3075
|
+
// Catalog-covered preset: the catalog entry is the richer record.
|
|
3076
|
+
if (!existing.logo && preset.logo)
|
|
3077
|
+
existing.logo = preset.logo;
|
|
3078
|
+
existing.name = preset.name; // the stored def name is localeless — show the manifest's localized one
|
|
3079
|
+
// Forward the web-authorization capability, or the connect card
|
|
3080
|
+
// never offers the plugin's device-login button.
|
|
3081
|
+
existing.webLogin = preset.webLogin;
|
|
3082
|
+
existing.pluginOrigin = existing.pluginOrigin ?? origins[preset.id];
|
|
3083
|
+
existing.webLoginSubmit = preset.webLoginSubmit;
|
|
3084
|
+
existing.authTypes = preset.authTypes;
|
|
3085
|
+
existing.keyHint = preset.keyHint;
|
|
3086
|
+
// Tag the plugin origin, or the trailing pure-config-source drop
|
|
3087
|
+
// below removes the row we just decided to keep.
|
|
3088
|
+
if (!existing.sources.includes('service'))
|
|
3089
|
+
existing.sources = [...existing.sources, 'service'];
|
|
3090
|
+
continue;
|
|
3091
|
+
}
|
|
3092
|
+
// Unconnected preset materialized only as a pure config-source row
|
|
3093
|
+
// (syncPluginPresets upserts the def at install): swap in the
|
|
3094
|
+
// preset row — plugin logo, displayName, connectable via the
|
|
3095
|
+
// preset's own baseURL/npm.
|
|
3096
|
+
providers.splice(idx, 1);
|
|
3097
|
+
}
|
|
3098
|
+
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 });
|
|
3099
|
+
}
|
|
3100
|
+
}
|
|
3101
|
+
catch {
|
|
3102
|
+
// catalog must survive a broken plugin host
|
|
3103
|
+
}
|
|
3104
|
+
// Pure config-source rows are dropped: a self-declared defs node is
|
|
3105
|
+
// already fully presented on the Connected tab — the connect catalog is
|
|
3106
|
+
// a DISCOVERY surface (remote catalog sources + plugin presets), not a
|
|
3107
|
+
// mirror of the operator's own declared relays.
|
|
3108
|
+
const connectable = providers.filter((p) => !(p.sources.length === 1 && p.sources[0] === 'config'));
|
|
3109
|
+
return { status: 'ok', source: catalogRepository.lastSyncOrigin, providers: connectable };
|
|
2177
3110
|
},
|
|
2178
3111
|
/** Flat model view across providers. `?maintained=1` narrows it to the
|
|
2179
3112
|
* physical models a defs node actually maintains (the /models page
|
|
@@ -2190,6 +3123,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2190
3123
|
// Raw file read once — the aggregate is already built from the normalized
|
|
2191
3124
|
// view, so a retired-shape node here contributes no rows anyway.
|
|
2192
3125
|
const rawNodes = readProviderDefsFile()?.providers ?? {};
|
|
3126
|
+
const takedowns = getProviderTakedownStore();
|
|
2193
3127
|
const nodeModels = (pid) => {
|
|
2194
3128
|
const node = rawNodes[pid];
|
|
2195
3129
|
const models = node && typeof node === 'object' ? node.models : undefined;
|
|
@@ -2209,6 +3143,9 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2209
3143
|
logo: p.logo,
|
|
2210
3144
|
custom: p.custom,
|
|
2211
3145
|
connected: p.connected,
|
|
3146
|
+
// Provider-level takedown: the row stays on the maintenance page
|
|
3147
|
+
// (aggregate truth), but the badge says it cannot route.
|
|
3148
|
+
providerDisabled: takedowns.isDisabled(p.id),
|
|
2212
3149
|
maintained: Object.prototype.hasOwnProperty.call(defs, m.id),
|
|
2213
3150
|
}))
|
|
2214
3151
|
.filter((m) => !maintainedOnly || m.maintained);
|
|
@@ -2228,22 +3165,34 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2228
3165
|
// namespace (the form normalizes input live; direct API callers get the
|
|
2229
3166
|
// rule stated back). Also keeps the catalog-shadow guard below exact:
|
|
2230
3167
|
// 'OpenAI' can no longer bypass a covered 'openai' id.
|
|
2231
|
-
const { isValidProviderId, PROVIDER_ID_RULE, upsertProviderDef, getProviderNodeById } = await import('../opencode/user-config.js');
|
|
3168
|
+
const { isValidProviderId, PROVIDER_ID_RULE, upsertProviderDef, getProviderNodeById, expandEnvTemplate } = await import('../opencode/user-config.js');
|
|
2232
3169
|
if (!isValidProviderId(id)) {
|
|
2233
3170
|
return reply.status(400).send({
|
|
2234
3171
|
success: false,
|
|
2235
3172
|
error: `Invalid provider id '${id}' - ${PROVIDER_ID_RULE}`,
|
|
2236
3173
|
});
|
|
2237
3174
|
}
|
|
2238
|
-
//
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
3175
|
+
// Upstream URL admission (self-loop / metadata / insecure public http).
|
|
3176
|
+
if (body.baseURL) {
|
|
3177
|
+
try {
|
|
3178
|
+
const { assertAllowedUpstream } = await import('../utils/upstream-url-guard.js');
|
|
3179
|
+
const expandedBaseURL = expandEnvTemplate(String(body.baseURL)) || String(body.baseURL);
|
|
3180
|
+
assertAllowedUpstream(expandedBaseURL, loadConfig().port);
|
|
3181
|
+
}
|
|
3182
|
+
catch (err) {
|
|
3183
|
+
return reply.status(409).send({
|
|
3184
|
+
success: false,
|
|
3185
|
+
reasonCode: err?.reasonCode || 'invalid_upstream_url',
|
|
3186
|
+
error: err?.message || String(err),
|
|
3187
|
+
});
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
// ADR-0006: credentials live in the bound store, never inline in defs.
|
|
3191
|
+
if (body.apiKeyInline) {
|
|
3192
|
+
return reply.status(400).send({
|
|
2245
3193
|
success: false,
|
|
2246
|
-
|
|
3194
|
+
reasonCode: 'api_key_inline_forbidden',
|
|
3195
|
+
error: 'apiKeyInline is disabled — connect the key through the bound credential store.',
|
|
2247
3196
|
});
|
|
2248
3197
|
}
|
|
2249
3198
|
// An id covered by the remote catalog (opencode / models-dev) may NOT be
|
|
@@ -2301,7 +3250,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2301
3250
|
let keyMeta;
|
|
2302
3251
|
if (keyToStore) {
|
|
2303
3252
|
try {
|
|
2304
|
-
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager())).credential;
|
|
3253
|
+
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager(), registry)).credential;
|
|
2305
3254
|
}
|
|
2306
3255
|
catch (err) {
|
|
2307
3256
|
// Roll back only a node THIS request created — with ONE exception: the
|
|
@@ -2351,20 +3300,32 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2351
3300
|
update: async (req, reply) => {
|
|
2352
3301
|
const { id } = req.params;
|
|
2353
3302
|
const body = req.body;
|
|
2354
|
-
const { upsertProviderDef, getProviderNodeById } = await import('../opencode/user-config.js');
|
|
3303
|
+
const { upsertProviderDef, getProviderNodeById, expandEnvTemplate } = await import('../opencode/user-config.js');
|
|
2355
3304
|
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
2356
3305
|
const existing = getProviderNodeById(id);
|
|
2357
3306
|
if (!existing) {
|
|
2358
3307
|
return reply.status(404).send({ success: false, error: `Provider '${id}' not found in the provider defs file` });
|
|
2359
3308
|
}
|
|
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
3309
|
const effectiveBaseURL = body.baseURL ?? existing.options?.baseURL ?? '';
|
|
2364
|
-
if (
|
|
2365
|
-
|
|
3310
|
+
if (effectiveBaseURL) {
|
|
3311
|
+
try {
|
|
3312
|
+
const { assertAllowedUpstream } = await import('../utils/upstream-url-guard.js');
|
|
3313
|
+
const expandedBaseURL = expandEnvTemplate(String(effectiveBaseURL)) || String(effectiveBaseURL);
|
|
3314
|
+
assertAllowedUpstream(expandedBaseURL, loadConfig().port);
|
|
3315
|
+
}
|
|
3316
|
+
catch (err) {
|
|
3317
|
+
return reply.status(409).send({
|
|
3318
|
+
success: false,
|
|
3319
|
+
reasonCode: err?.reasonCode || 'invalid_upstream_url',
|
|
3320
|
+
error: err?.message || String(err),
|
|
3321
|
+
});
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
if (body.apiKeyInline === true) {
|
|
3325
|
+
return reply.status(400).send({
|
|
2366
3326
|
success: false,
|
|
2367
|
-
|
|
3327
|
+
reasonCode: 'api_key_inline_forbidden',
|
|
3328
|
+
error: 'apiKeyInline is disabled — connect the key through the bound credential store.',
|
|
2368
3329
|
});
|
|
2369
3330
|
}
|
|
2370
3331
|
// B4: same implicit auth.json side-write as create (apiKey + !inline) —
|
|
@@ -2376,7 +3337,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2376
3337
|
let keyMeta;
|
|
2377
3338
|
if (keyToStore) {
|
|
2378
3339
|
try {
|
|
2379
|
-
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager())).credential;
|
|
3340
|
+
keyMeta = (await connectKeyIdempotent(store, id, String(body.apiKey), undefined, registry.getCircuitBreakerManager(), registry)).credential;
|
|
2380
3341
|
}
|
|
2381
3342
|
catch (err) {
|
|
2382
3343
|
const failure = await mapStoreWriteFailure(err);
|
|
@@ -2435,7 +3396,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2435
3396
|
// A WriteFailedError maps to 5xx and NEVER falls back to OcrStore
|
|
2436
3397
|
// (Decision 3: read degrades with a badge, write refuses).
|
|
2437
3398
|
const store = await getCredentialStore();
|
|
2438
|
-
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager());
|
|
3399
|
+
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
2439
3400
|
// Optional baseURL override — merge with the existing definition so we
|
|
2440
3401
|
// never wipe name/npm/models of a config-defined custom provider.
|
|
2441
3402
|
// No apiKey field → no implicit credential write on any binding.
|
|
@@ -2496,6 +3457,110 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2496
3457
|
return reply.status(400).send({ success: false, error: err.message });
|
|
2497
3458
|
}
|
|
2498
3459
|
},
|
|
3460
|
+
/** Resolve the model-service plugin serving a provider def's wire
|
|
3461
|
+
* (plugin wires only — the vendor protocol stays in the plugin). */
|
|
3462
|
+
webLoginPluginFor: async (id) => {
|
|
3463
|
+
const { getProviderNodeById } = await import('../opencode/user-config.js');
|
|
3464
|
+
const { wireFor } = await import('../providers/wire.js');
|
|
3465
|
+
const def = getProviderNodeById(id);
|
|
3466
|
+
if (!def)
|
|
3467
|
+
return { error: `provider '${id}' not found` };
|
|
3468
|
+
const node = def;
|
|
3469
|
+
const baseURL = (node.options?.baseURL ?? node.baseURL ?? '').replace(/\/+$/, '');
|
|
3470
|
+
const npm = node.npm || node.package || '';
|
|
3471
|
+
const wire = npm ? wireFor(npm) : baseURL ? wireFor(undefined, baseURL) : 'unroutable';
|
|
3472
|
+
const plugin = (await import('../plugins/host.js')).getModelServicePlugin(wire);
|
|
3473
|
+
if (!plugin?.webLogin) {
|
|
3474
|
+
return { error: `provider '${id}' is not on a plugin wire with a web-login capability` };
|
|
3475
|
+
}
|
|
3476
|
+
return { plugin, baseURL };
|
|
3477
|
+
},
|
|
3478
|
+
webLoginStart: async (req, reply) => {
|
|
3479
|
+
const { id } = req.params;
|
|
3480
|
+
const r = await ocHandlers.webLoginPluginFor(id);
|
|
3481
|
+
if ('error' in r)
|
|
3482
|
+
return reply.code(404).send({ success: false, error: r.error });
|
|
3483
|
+
try {
|
|
3484
|
+
const { authUrl } = await r.plugin.webLogin.start({ baseURL: r.baseURL });
|
|
3485
|
+
return { status: 'ok', authUrl };
|
|
3486
|
+
}
|
|
3487
|
+
catch (err) {
|
|
3488
|
+
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
3489
|
+
}
|
|
3490
|
+
},
|
|
3491
|
+
webLoginPoll: async (req, reply) => {
|
|
3492
|
+
const { id } = req.params;
|
|
3493
|
+
const r = await ocHandlers.webLoginPluginFor(id);
|
|
3494
|
+
if ('error' in r)
|
|
3495
|
+
return reply.code(404).send({ success: false, error: r.error });
|
|
3496
|
+
try {
|
|
3497
|
+
const result = await r.plugin.webLogin.poll({ baseURL: r.baseURL });
|
|
3498
|
+
if (!result.done) {
|
|
3499
|
+
return { status: 'ok', done: false, error: result.error };
|
|
3500
|
+
}
|
|
3501
|
+
// Login finished — wire the fresh token into the credential store
|
|
3502
|
+
// (same write path as a manual connect), then connect-time model
|
|
3503
|
+
// auto-fill so the card shows as connected with models.
|
|
3504
|
+
if (!result.token) {
|
|
3505
|
+
return { status: 'ok', done: true, connected: false, error: 'login finished without a token' };
|
|
3506
|
+
}
|
|
3507
|
+
const credentialStore = await (await import('../opencode/credentials/index.js')).getCredentialStore();
|
|
3508
|
+
const { credential: keyMeta } = await connectKeyIdempotent(credentialStore, id, result.token, undefined, registry.getCircuitBreakerManager(), registry);
|
|
3509
|
+
const { ensureConnectedProviderBook } = await import('../opencode/catalog/auto-pull.js');
|
|
3510
|
+
const fill = await ensureConnectedProviderBook(id, { baseURL: r.baseURL }).catch((e) => ({
|
|
3511
|
+
nodeCreated: false,
|
|
3512
|
+
pulled: 0,
|
|
3513
|
+
fillError: String(e?.message ?? e),
|
|
3514
|
+
}));
|
|
3515
|
+
if (fill.fillError) {
|
|
3516
|
+
app.log.warn({ providerId: id, fillError: fill.fillError }, 'web-login connect-time model auto-fill failed (swallowed by design)');
|
|
3517
|
+
}
|
|
3518
|
+
return { status: 'ok', done: true, connected: true, credential: keyMeta };
|
|
3519
|
+
}
|
|
3520
|
+
catch (err) {
|
|
3521
|
+
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
3522
|
+
}
|
|
3523
|
+
},
|
|
3524
|
+
webLoginSubmit: async (req, reply) => {
|
|
3525
|
+
const { id } = req.params;
|
|
3526
|
+
const code = String((req.body || {}).code ?? '').trim();
|
|
3527
|
+
if (!code)
|
|
3528
|
+
return reply.code(400).send({ success: false, error: 'missing code' });
|
|
3529
|
+
const r = await ocHandlers.webLoginPluginFor(id);
|
|
3530
|
+
if ('error' in r)
|
|
3531
|
+
return reply.code(404).send({ success: false, error: r.error });
|
|
3532
|
+
if (!r.plugin.webLogin.submit) {
|
|
3533
|
+
return reply.code(404).send({ success: false, error: `provider '${id}' web-login has no manual token submission` });
|
|
3534
|
+
}
|
|
3535
|
+
try {
|
|
3536
|
+
const result = await r.plugin.webLogin.submit({ baseURL: r.baseURL, code });
|
|
3537
|
+
if (!result.ok)
|
|
3538
|
+
return { status: 'ok', connected: false, error: result.error };
|
|
3539
|
+
// Same wiring as a finished poll: credential-store write + connect-time
|
|
3540
|
+
// model auto-fill so the card flips to connected. A submit that
|
|
3541
|
+
// consumed the code without returning a token is a plugin bug — refuse
|
|
3542
|
+
// to persist the (likely expired) raw code as the credential, exactly
|
|
3543
|
+
// like the poll path's 'login finished without a token' guard.
|
|
3544
|
+
if (!result.token) {
|
|
3545
|
+
return { status: 'ok', connected: false, error: 'submit finished without a token' };
|
|
3546
|
+
}
|
|
3547
|
+
const credentialStore = await (await import('../opencode/credentials/index.js')).getCredentialStore();
|
|
3548
|
+
const { credential: keyMeta } = await connectKeyIdempotent(credentialStore, id, result.token, undefined, registry.getCircuitBreakerManager(), registry);
|
|
3549
|
+
const { ensureConnectedProviderBook } = await import('../opencode/catalog/auto-pull.js');
|
|
3550
|
+
const fill = await ensureConnectedProviderBook(id, { baseURL: r.baseURL }).catch((e) => ({
|
|
3551
|
+
nodeCreated: false,
|
|
3552
|
+
pulled: 0,
|
|
3553
|
+
fillError: String(e?.message ?? e),
|
|
3554
|
+
}));
|
|
3555
|
+
if (fill.fillError) {
|
|
3556
|
+
app.log.warn({ providerId: id, fillError: fill.fillError }, 'web-login submit connect-time model auto-fill failed (swallowed by design)');
|
|
3557
|
+
}
|
|
3558
|
+
return { status: 'ok', connected: true, credential: keyMeta };
|
|
3559
|
+
}
|
|
3560
|
+
catch (err) {
|
|
3561
|
+
return reply.code(502).send({ success: false, error: err instanceof Error ? err.message : String(err) });
|
|
3562
|
+
}
|
|
3563
|
+
},
|
|
2499
3564
|
/**
|
|
2500
3565
|
* One-shot upstream connectivity probe behind the console "Test" buttons.
|
|
2501
3566
|
* Resolves baseURL/key/model from body overrides (test-before-save) or
|
|
@@ -2515,7 +3580,16 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2515
3580
|
// upstream probe header (its whole purpose), never in the response.
|
|
2516
3581
|
// Inline {env:VAR}/options.apiKey keep priority ABOVE the store (Decision 1).
|
|
2517
3582
|
const store = await getCredentialStore();
|
|
2518
|
-
|
|
3583
|
+
// Provider-level probes honor the operator takedown overlay: a disabled
|
|
3584
|
+
// credential is parked from routing, so probing with it would report a
|
|
3585
|
+
// provider as healthy while inference refuses that key. The store does
|
|
3586
|
+
// not carry the flag (it lives in the breaker state store's overlay), so
|
|
3587
|
+
// the chain is filtered with the same keyHashPrefix identity routing
|
|
3588
|
+
// uses — and probed IN ORDER below (first key that answers wins). An
|
|
3589
|
+
// addressed credentialId below deliberately bypasses this.
|
|
3590
|
+
const credentialState = registry.getCircuitBreakerManager().getCredentialStateStore();
|
|
3591
|
+
const storeChain = store.resolveKeyChain(id);
|
|
3592
|
+
const enabledChain = storeChain.filter((c) => c.key && !credentialState.isDisabled(id, keyHashPrefix(c.key)));
|
|
2519
3593
|
// Per-credential probe: the operator pinned ONE credential row (KeysPage
|
|
2520
3594
|
// credential list). resolveKeyChain is a sanctioned raw read on this route
|
|
2521
3595
|
// — same contract as resolveKey above: the key leaves only as the
|
|
@@ -2585,55 +3659,134 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2585
3659
|
if (modelCandidates.length === 0) {
|
|
2586
3660
|
return reply.status(400).send({ success: false, reasonCode: 'no_testable_model', provider: id });
|
|
2587
3661
|
}
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
3662
|
+
const inlineKey = expandEnvTemplate(def?.options?.apiKey);
|
|
3663
|
+
const probeAttempts = [];
|
|
3664
|
+
if (addressed) {
|
|
3665
|
+
probeAttempts.push({ key: addressed.key, credentialId: addressed.credentialId });
|
|
3666
|
+
}
|
|
3667
|
+
else if (body.apiKey) {
|
|
3668
|
+
probeAttempts.push({ key: body.apiKey });
|
|
3669
|
+
}
|
|
3670
|
+
else if (inlineKey) {
|
|
3671
|
+
probeAttempts.push({ key: inlineKey });
|
|
3672
|
+
}
|
|
3673
|
+
else {
|
|
3674
|
+
for (const c of enabledChain)
|
|
3675
|
+
probeAttempts.push({ key: c.key, credentialId: c.credentialId });
|
|
3676
|
+
}
|
|
3677
|
+
if (probeAttempts.length === 0) {
|
|
3678
|
+
// Every stored key parked: say THAT, not the misleading no-key/OAuth
|
|
3679
|
+
// hint (the operator must know a takedown is the cause). Reaching this
|
|
3680
|
+
// point already proves there is no addressed row, no request-body key,
|
|
3681
|
+
// no inline key and no enabled store row — the disabled chain is the
|
|
3682
|
+
// only thing left to explain.
|
|
3683
|
+
if (storeChain.some((c) => c.key)) {
|
|
3684
|
+
return reply.status(400).send({
|
|
3685
|
+
success: false,
|
|
3686
|
+
reasonCode: 'no_enabled_credential',
|
|
3687
|
+
provider: id,
|
|
3688
|
+
error: `Every credential stored for '${id}' is disabled — enable one before testing.`,
|
|
3689
|
+
});
|
|
3690
|
+
}
|
|
2596
3691
|
return reply.status(400).send({
|
|
2597
3692
|
success: false,
|
|
2598
3693
|
oauthHint: true,
|
|
2599
3694
|
error: `No API key for '${id}' (credential store or inline). For OAuth-based providers run: opencode auth login ${id}`,
|
|
2600
3695
|
});
|
|
2601
3696
|
}
|
|
2602
|
-
//
|
|
2603
|
-
//
|
|
2604
|
-
|
|
3697
|
+
// Security S-03: refuse request-body baseURL overrides — a caller with
|
|
3698
|
+
// only a credentialId could otherwise exfiltrate the stored key to an
|
|
3699
|
+
// attacker URL. Test hits the same URL inference uses.
|
|
3700
|
+
if (body.baseURL) {
|
|
3701
|
+
return reply.status(400).send({
|
|
3702
|
+
success: false,
|
|
3703
|
+
reasonCode: 'base_url_override_forbidden',
|
|
3704
|
+
provider: id,
|
|
3705
|
+
error: 'body.baseURL is not accepted on test; configure the provider def (or catalog) baseURL instead.',
|
|
3706
|
+
});
|
|
3707
|
+
}
|
|
3708
|
+
const rawBaseURL = def?.options?.baseURL || cat?.api || cat?.baseURL;
|
|
3709
|
+
const baseURL = rawBaseURL ? expandEnvTemplate(String(rawBaseURL)) || String(rawBaseURL) : '';
|
|
2605
3710
|
if (!baseURL) {
|
|
2606
3711
|
return reply.status(400).send({ success: false, reasonCode: 'no_base_url', provider: id });
|
|
2607
3712
|
}
|
|
3713
|
+
try {
|
|
3714
|
+
const { assertAllowedUpstream } = await import('../utils/upstream-url-guard.js');
|
|
3715
|
+
assertAllowedUpstream(String(baseURL), loadConfig().port);
|
|
3716
|
+
}
|
|
3717
|
+
catch (err) {
|
|
3718
|
+
return reply.status(400).send({
|
|
3719
|
+
success: false,
|
|
3720
|
+
reasonCode: err?.reasonCode || 'invalid_upstream_url',
|
|
3721
|
+
provider: id,
|
|
3722
|
+
error: err?.message || String(err),
|
|
3723
|
+
});
|
|
3724
|
+
}
|
|
2608
3725
|
const { probeProvider, probeKindFor } = await import('../opencode/probe.js');
|
|
2609
3726
|
const { baseForWire } = await import('../providers/wire.js');
|
|
2610
3727
|
const { sanitizeExtraHeaders } = await import('../utils/http-headers.js');
|
|
2611
|
-
//
|
|
2612
|
-
//
|
|
2613
|
-
//
|
|
2614
|
-
//
|
|
3728
|
+
// Two nested rotation loops, both stopping on one green:
|
|
3729
|
+
// · models — a MODEL-SCOPED failure (upstream ANSWERED and rejected
|
|
3730
|
+
// only that model) advances to the next candidate model;
|
|
3731
|
+
// · credentials — the rotation the operator asked for: a key that is
|
|
3732
|
+
// revoked (401/403) or out of quota (429) says nothing about its
|
|
3733
|
+
// siblings, so the next credential takes over and the model list
|
|
3734
|
+
// restarts from the top for it.
|
|
3735
|
+
// Only a MOUNT failure ends the probe early: transport errors, unroutable
|
|
3736
|
+
// packages, 5xx and HTML gateways are properties of the baseURL, which
|
|
3737
|
+
// every credential of the provider shares — rotating would just repeat
|
|
3738
|
+
// the same error with a different key attached.
|
|
2615
3739
|
let result;
|
|
2616
3740
|
const tried = [];
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
3741
|
+
const triedCredentialIds = [];
|
|
3742
|
+
let answered;
|
|
3743
|
+
probes: for (const attempt of probeAttempts) {
|
|
3744
|
+
if (attempt.credentialId)
|
|
3745
|
+
triedCredentialIds.push(attempt.credentialId);
|
|
3746
|
+
// Tracks the row the FINAL verdict belongs to: reassigned per attempt,
|
|
3747
|
+
// so a green probe is credited to the key that answered while an
|
|
3748
|
+
// all-red one is credited to the key tried last.
|
|
3749
|
+
answered = attempt;
|
|
3750
|
+
for (const modelId of modelCandidates) {
|
|
3751
|
+
if (!tried.includes(modelId))
|
|
3752
|
+
tried.push(modelId);
|
|
3753
|
+
// Model-level npm override (e.g. Zen gpt-6-luna → @ai-sdk/openai =
|
|
3754
|
+
// Responses API) beats provider-level npm when picking the wire shape.
|
|
3755
|
+
const modelNpm = cat?.models.find((mm) => mm.id === modelId)?.npm;
|
|
3756
|
+
const kind = probeKindFor(cat?.api, modelNpm || def?.npm || cat?.npm);
|
|
3757
|
+
result = await probeProvider({
|
|
3758
|
+
baseURL: baseForWire(kind, baseURL),
|
|
3759
|
+
apiKey: attempt.key,
|
|
3760
|
+
model: modelId,
|
|
3761
|
+
provider: id,
|
|
3762
|
+
kind,
|
|
3763
|
+
headers: sanitizeExtraHeaders(def?.options?.headers
|
|
3764
|
+
? Object.fromEntries(Object.entries(def.options.headers).map(([k, v]) => [k, expandEnvTemplate(String(v))]))
|
|
3765
|
+
: undefined),
|
|
3766
|
+
});
|
|
3767
|
+
if (result.ok)
|
|
3768
|
+
break probes;
|
|
3769
|
+
// Key-scoped refusal → this key is done, hand over to the next one.
|
|
3770
|
+
if (result.hintCode === 'authFailed' || result.hintCode === 'rateLimited')
|
|
3771
|
+
break;
|
|
3772
|
+
// Reached the upstream and got refused for THIS model → another key
|
|
3773
|
+
// may have it open; anything else (transport, 5xx) is the mount's
|
|
3774
|
+
// problem, and a mount is shared by every key of the provider.
|
|
3775
|
+
if (!result.modelScoped)
|
|
3776
|
+
break probes;
|
|
3777
|
+
}
|
|
2633
3778
|
}
|
|
2634
|
-
// Masked echo of the
|
|
2635
|
-
//
|
|
2636
|
-
|
|
3779
|
+
// Masked echo of the row that produced the verdict (never raw material):
|
|
3780
|
+
// the row that ANSWERED on success, the row tried last on failure — the UI
|
|
3781
|
+
// can confirm WHICH credential the verdict belongs to, not just the
|
|
3782
|
+
// provider.
|
|
3783
|
+
const credentialMetas = store.listCredentials(id);
|
|
3784
|
+
const credentialMeta = answered?.credentialId
|
|
3785
|
+
? credentialMetas.find((a) => a.id === answered.credentialId)
|
|
3786
|
+
: undefined;
|
|
3787
|
+
const triedCredentials = triedCredentialIds
|
|
3788
|
+
.map((cid) => credentialMetas.find((a) => a.id === cid))
|
|
3789
|
+
.filter((a) => !!a);
|
|
2637
3790
|
return {
|
|
2638
3791
|
status: 'ok',
|
|
2639
3792
|
provider: id,
|
|
@@ -2641,6 +3794,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2641
3794
|
// Rotation evidence (machine data, localized by the console): which
|
|
2642
3795
|
// candidates were tried, in order. Only meaningful when > 1.
|
|
2643
3796
|
...(tried.length > 1 ? { triedModels: tried } : {}),
|
|
3797
|
+
...(triedCredentials.length > 1 ? { triedCredentials } : {}),
|
|
2644
3798
|
...(credentialMeta ? { credential: credentialMeta } : {}),
|
|
2645
3799
|
...result,
|
|
2646
3800
|
};
|
|
@@ -2658,7 +3812,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2658
3812
|
// same key is deduped, never doubled) and ocr writes the local file. No
|
|
2659
3813
|
// auth.json write exists on any binding.
|
|
2660
3814
|
const store = await getCredentialStore();
|
|
2661
|
-
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager());
|
|
3815
|
+
const { credential: keyMeta, deduped, headPreserved } = await connectKeyIdempotent(store, id, body.apiKey, undefined, registry.getCircuitBreakerManager(), registry);
|
|
2662
3816
|
store.invalidate();
|
|
2663
3817
|
// Decision 6: a key rotation handed to the store is a reconnect — clear SUSPECT.
|
|
2664
3818
|
clearSuspectForCredential(registry.getCircuitBreakerManager(), id, keyMeta?.keyHashPrefix);
|
|
@@ -2696,6 +3850,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2696
3850
|
// Decision 8 double confirmation is enforced by the console UI
|
|
2697
3851
|
// (purgeAuth opt-in) — server-side the loop reports honestly.
|
|
2698
3852
|
const purge = purgeAuth ? await purgeProviderCredentials(store, id) : null;
|
|
3853
|
+
dropTakedownWhenProviderGone(id, store);
|
|
2699
3854
|
const outcome = purge ? purgeOutcomeMessage(purge, id, true) : null;
|
|
2700
3855
|
// Clean purge (or no purge requested): legacy response bytes kept.
|
|
2701
3856
|
// defRemoved is the runtime truth — the console success toast follows
|
|
@@ -2709,6 +3864,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2709
3864
|
// Credential-only entry: provider-wide disconnect = the UI-level
|
|
2710
3865
|
// credential loop (Decision 1), never a direct upstream-file edit.
|
|
2711
3866
|
const purge = await purgeProviderCredentials(store, id);
|
|
3867
|
+
dropTakedownWhenProviderGone(id, store);
|
|
2712
3868
|
return { status: 'ok', defRemoved: false, ...purgeOutcomeMessage(purge, id, false), purge };
|
|
2713
3869
|
}
|
|
2714
3870
|
catch (err) {
|
|
@@ -2859,15 +4015,24 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
2859
4015
|
* Pull models into the provider's config definition. Data source is chosen
|
|
2860
4016
|
* automatically: providers with baseURL + credential are pulled LIVE from
|
|
2861
4017
|
* their own /v1/models (failures surface real errors); providers without a
|
|
2862
|
-
* usable baseURL/key fall back to the static merged catalog.
|
|
2863
|
-
*
|
|
4018
|
+
* usable baseURL/key fall back to the static merged catalog. Builtin
|
|
4019
|
+
* (first-party catalog) providers take the MERGED path — catalog sets the
|
|
4020
|
+
* metadata-authoritative base, a live /v1/models pass only tops up ids the
|
|
4021
|
+
* catalog lacks. The same engine powers the periodic auto-pull
|
|
4022
|
+
* (catalog.autoPullModels).
|
|
2864
4023
|
*/
|
|
2865
4024
|
modelsPull: async (req, reply) => {
|
|
2866
4025
|
const { id } = req.params;
|
|
2867
4026
|
const body = req.body;
|
|
2868
4027
|
const { autoPullProvider } = await import('../opencode/catalog/auto-pull.js');
|
|
2869
4028
|
const result = await autoPullProvider(id, body ?? {});
|
|
2870
|
-
|
|
4029
|
+
// withPoolSync keys on reply.sent. A dry run is a read-only preview and
|
|
4030
|
+
// must not rebuild the live registry; a real pull returns the body so
|
|
4031
|
+
// the wrapper can apply the new defs without a restart.
|
|
4032
|
+
if (body?.dryRun)
|
|
4033
|
+
return reply.status(result.httpStatus).send(result.body);
|
|
4034
|
+
reply.status(result.httpStatus);
|
|
4035
|
+
return result.body;
|
|
2871
4036
|
},
|
|
2872
4037
|
/** Clear models — whole node without a pattern, matching ids only with one. */
|
|
2873
4038
|
modelsClear: async (req, reply) => {
|
|
@@ -3002,6 +4167,11 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3002
4167
|
const cb = registry.getCircuitBreakerManager();
|
|
3003
4168
|
for (const k of result.write?.pushedKeys ?? [])
|
|
3004
4169
|
clearSuspectForCredential(cb, k.provider, k.keyHashPrefix);
|
|
4170
|
+
// A sync pull/import can land keys on MANY providers — refresh every
|
|
4171
|
+
// connected provider's runtime chain (cheap: one store read per provider).
|
|
4172
|
+
for (const o of store.credentialsOverview()) {
|
|
4173
|
+
await refreshProviderCredentialChain(registry, store, o.providerId);
|
|
4174
|
+
}
|
|
3005
4175
|
return { status: 'ok', direction, ...result };
|
|
3006
4176
|
}
|
|
3007
4177
|
catch (err) {
|
|
@@ -3013,26 +4183,93 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3013
4183
|
}
|
|
3014
4184
|
},
|
|
3015
4185
|
/**
|
|
3016
|
-
*
|
|
3017
|
-
*
|
|
3018
|
-
*
|
|
3019
|
-
*
|
|
3020
|
-
*
|
|
3021
|
-
*
|
|
3022
|
-
*
|
|
4186
|
+
* REORDER a provider's credential chain (the Keys page's drag/ordering
|
|
4187
|
+
* action; replaces the retired operator activate route — `store.activate`
|
|
4188
|
+
* stays the internal head primitive for sync/connect headPreserved).
|
|
4189
|
+
* Body: { ids: string[] } — a permutation of the provider's credential
|
|
4190
|
+
* ids; the default credential becomes ids[0]. Gated on capabilities.reorder
|
|
4191
|
+
* (Decision 1). Response mirrors the old activate reply: the head
|
|
4192
|
+
* credential plus the refreshed masked credential list so the UI
|
|
4193
|
+
* repaints without a second fetch.
|
|
4194
|
+
*/
|
|
4195
|
+
credentialReorder: async (req, reply) => {
|
|
4196
|
+
const { id } = req.params;
|
|
4197
|
+
const body = req.body;
|
|
4198
|
+
const ids = body?.ids;
|
|
4199
|
+
if (!Array.isArray(ids) || ids.length === 0 || ids.some((x) => typeof x !== 'string')) {
|
|
4200
|
+
return reply.status(400).send({
|
|
4201
|
+
status: 'error',
|
|
4202
|
+
success: false,
|
|
4203
|
+
reasonCode: 'invalid_ids',
|
|
4204
|
+
error: 'ids must be a non-empty array of credential id strings',
|
|
4205
|
+
});
|
|
4206
|
+
}
|
|
4207
|
+
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
4208
|
+
const store = await getCredentialStore();
|
|
4209
|
+
if (!store.capabilities.reorder)
|
|
4210
|
+
return reply.status(400).send(capabilityRefusalBody('reorder'));
|
|
4211
|
+
// Guard-light: verify the provider has rows before the store call (the
|
|
4212
|
+
// store's own reorder validates the id permutation and 404s unknown ids).
|
|
4213
|
+
try {
|
|
4214
|
+
if (store.listCredentials(id).length === 0) {
|
|
4215
|
+
return reply.status(404).send(credentialNotFoundBody(ids[0], id));
|
|
4216
|
+
}
|
|
4217
|
+
}
|
|
4218
|
+
catch (err) {
|
|
4219
|
+
const failure = await mapStoreWriteFailure(err);
|
|
4220
|
+
if (failure)
|
|
4221
|
+
return reply.status(failure.status).send({ status: 'error', ...failure.body });
|
|
4222
|
+
return reply.status(500).send({ status: 'error', success: false, error: errMessage(err) });
|
|
4223
|
+
}
|
|
4224
|
+
try {
|
|
4225
|
+
const reordered = await store.reorder(id, ids);
|
|
4226
|
+
store.invalidate(); // Decision 3: console action invalidates the store view
|
|
4227
|
+
// Reorder IS the chain order — swap the runtime chain so the new head
|
|
4228
|
+
// serves without a restart.
|
|
4229
|
+
await refreshProviderCredentialChain(registry, store, id);
|
|
4230
|
+
const credential = reordered[0];
|
|
4231
|
+
return { status: 'ok', success: true, credential, credentials: withCredentialHealth(id, store.listCredentials(id)) };
|
|
4232
|
+
}
|
|
4233
|
+
catch (err) {
|
|
4234
|
+
const failure = await mapCredentialWriteFailure(err, id, String(ids[0]));
|
|
4235
|
+
return reply.status(failure.status).send(failure.body);
|
|
4236
|
+
}
|
|
4237
|
+
},
|
|
4238
|
+
/**
|
|
4239
|
+
* SET the spread weight of ONE credential (operator lever for unequal
|
|
4240
|
+
* quotas: a credential weighing w occupies w slots of the deterministic
|
|
4241
|
+
* new-session spread). Body: { weight: number } — an INTEGER in
|
|
4242
|
+
* [1, CREDENTIAL_WEIGHT_MAX]; anything else is a 400 invalid_weight.
|
|
4243
|
+
* Gated on capabilities.weight (opencode v2 rows have no weight field and
|
|
4244
|
+
* refuse, exactly like reorder). The chain is hot-refreshed so the new
|
|
4245
|
+
* weight shapes the very next placement — no restart.
|
|
3023
4246
|
*/
|
|
3024
|
-
|
|
4247
|
+
credentialSetWeight: async (req, reply) => {
|
|
3025
4248
|
const { id, credentialId } = req.params;
|
|
4249
|
+
const body = req.body;
|
|
4250
|
+
const raw = body?.weight;
|
|
4251
|
+
const weight = typeof raw === 'number' && Number.isInteger(raw) ? raw : NaN;
|
|
4252
|
+
if (!Number.isFinite(weight) || weight < 1 || weight > CREDENTIAL_WEIGHT_MAX) {
|
|
4253
|
+
return reply.status(400).send({
|
|
4254
|
+
status: 'error',
|
|
4255
|
+
success: false,
|
|
4256
|
+
reasonCode: 'invalid_weight',
|
|
4257
|
+
error: `weight must be an integer between 1 and ${CREDENTIAL_WEIGHT_MAX}`,
|
|
4258
|
+
});
|
|
4259
|
+
}
|
|
3026
4260
|
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
3027
4261
|
const store = await getCredentialStore();
|
|
3028
|
-
if (!store.capabilities.
|
|
3029
|
-
return reply.status(400).send(capabilityRefusalBody('
|
|
4262
|
+
if (!store.capabilities.weight)
|
|
4263
|
+
return reply.status(400).send(capabilityRefusalBody('weight'));
|
|
3030
4264
|
const guard = await guardStoreCredential(store, id, credentialId);
|
|
3031
4265
|
if (!guard.ok)
|
|
3032
4266
|
return reply.status(guard.status).send(guard.body);
|
|
3033
4267
|
try {
|
|
3034
|
-
const credential = await store.
|
|
4268
|
+
const credential = await store.setWeight(credentialId, weight);
|
|
3035
4269
|
store.invalidate(); // Decision 3: console action invalidates the store view
|
|
4270
|
+
// The weight rides the runtime chain — swap it in so the next
|
|
4271
|
+
// new-session placement sees the new proportions immediately.
|
|
4272
|
+
await refreshProviderCredentialChain(registry, store, id);
|
|
3036
4273
|
return { status: 'ok', success: true, credential, credentials: withCredentialHealth(id, store.listCredentials(id)) };
|
|
3037
4274
|
}
|
|
3038
4275
|
catch (err) {
|
|
@@ -3112,7 +4349,11 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3112
4349
|
try {
|
|
3113
4350
|
await store.disconnect(credentialId);
|
|
3114
4351
|
store.invalidate();
|
|
4352
|
+
await refreshProviderCredentialChain(registry, store, id); // removed key must leave the live chain
|
|
3115
4353
|
clearSuspectForCredential(registry.getCircuitBreakerManager(), id, prefix);
|
|
4354
|
+
// The last credential of a def-less provider removes the row entirely;
|
|
4355
|
+
// a takedown must not outlive the thing it targeted.
|
|
4356
|
+
dropTakedownWhenProviderGone(id, store);
|
|
3116
4357
|
// DELETE is a REVOCATION, so it must be as durable as a takedown: anchor
|
|
3117
4358
|
// the key MATERIAL as disabled. Otherwise the read sync would re-import
|
|
3118
4359
|
// the key from the client as a clean, routable credential — the delete
|
|
@@ -3233,6 +4474,71 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3233
4474
|
return reply.status(failure.status).send(failure.body);
|
|
3234
4475
|
}
|
|
3235
4476
|
},
|
|
4477
|
+
/**
|
|
4478
|
+
* Operator DISABLE / ENABLE one WHOLE provider — the coarse counterpart of
|
|
4479
|
+
* the credential takedown below. The provider keeps its defs node, models,
|
|
4480
|
+
* credentials and console card; only the routing pool drops it
|
|
4481
|
+
* (`buildDirectPool` → `operator_disabled`), so `/v1/models` omits it and
|
|
4482
|
+
* direct ids 404. State lives in the GLOBAL takedown ledger, never in
|
|
4483
|
+
* providers.json (that file is connection truth + the sync materializer's
|
|
4484
|
+
* source, ADR-0010). Manual-only lifecycle: nothing auto-clears it.
|
|
4485
|
+
*/
|
|
4486
|
+
providerSetDisabled: async (req, reply, disabled) => {
|
|
4487
|
+
const { id } = req.params;
|
|
4488
|
+
const body = req.body ?? {};
|
|
4489
|
+
if (!isValidProviderId(id)) {
|
|
4490
|
+
return reply.status(400).send({
|
|
4491
|
+
status: 'error',
|
|
4492
|
+
success: false,
|
|
4493
|
+
reasonCode: 'invalid_provider_id',
|
|
4494
|
+
error: `Invalid provider id '${id}' - ${PROVIDER_ID_RULE}`,
|
|
4495
|
+
});
|
|
4496
|
+
}
|
|
4497
|
+
const { getCredentialStore } = await import('../opencode/credentials/index.js');
|
|
4498
|
+
const store = await getCredentialStore();
|
|
4499
|
+
let hasCredential = false;
|
|
4500
|
+
try {
|
|
4501
|
+
hasCredential = store.listCredentials(id).length > 0;
|
|
4502
|
+
}
|
|
4503
|
+
catch {
|
|
4504
|
+
// unreadable per-provider detail: a defs node still proves the provider exists
|
|
4505
|
+
}
|
|
4506
|
+
if (!getProviderNodeById(id) && !hasCredential) {
|
|
4507
|
+
return reply.status(404).send({
|
|
4508
|
+
status: 'error',
|
|
4509
|
+
success: false,
|
|
4510
|
+
reasonCode: 'provider_not_found',
|
|
4511
|
+
error: `Provider '${id}' is neither defined in providers.json nor connected with a credential`,
|
|
4512
|
+
});
|
|
4513
|
+
}
|
|
4514
|
+
const takedowns = getProviderTakedownStore();
|
|
4515
|
+
if (disabled) {
|
|
4516
|
+
const raw = typeof body.reason === 'string' ? body.reason.trim() : '';
|
|
4517
|
+
if (raw.length > 200) {
|
|
4518
|
+
return reply
|
|
4519
|
+
.status(400)
|
|
4520
|
+
.send({ status: 'error', success: false, reasonCode: 'invalid_reason', error: 'reason too long (max 200 characters)' });
|
|
4521
|
+
}
|
|
4522
|
+
takedowns.disable(id, raw);
|
|
4523
|
+
return {
|
|
4524
|
+
status: 'ok',
|
|
4525
|
+
success: true,
|
|
4526
|
+
disabled: true,
|
|
4527
|
+
provider: id,
|
|
4528
|
+
message: `Provider '${id}' taken down (no model routes through it)`,
|
|
4529
|
+
};
|
|
4530
|
+
}
|
|
4531
|
+
takedowns.enable(id);
|
|
4532
|
+
return {
|
|
4533
|
+
status: 'ok',
|
|
4534
|
+
success: true,
|
|
4535
|
+
disabled: false,
|
|
4536
|
+
provider: id,
|
|
4537
|
+
message: `Provider '${id}' restored to routing`,
|
|
4538
|
+
};
|
|
4539
|
+
},
|
|
4540
|
+
providerDisable: (req, reply) => ocHandlers.providerSetDisabled(req, reply, true),
|
|
4541
|
+
providerEnable: (req, reply) => ocHandlers.providerSetDisabled(req, reply, false),
|
|
3236
4542
|
/**
|
|
3237
4543
|
* Operator DISABLE / ENABLE one credential — a durable takedown that never
|
|
3238
4544
|
* auto-returns (cooldown expiry, reconnect, Push and breaker resets all leave
|
|
@@ -3301,34 +4607,276 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3301
4607
|
app.get(`${prefix}/credential-store`, ocHandlers.credentialStore);
|
|
3302
4608
|
app.get(`${prefix}/credential-sync`, ocHandlers.credentialSyncStatus);
|
|
3303
4609
|
app.post(`${prefix}/credential-sync/toggle`, ocHandlers.credentialSyncToggle);
|
|
3304
|
-
app.post(`${prefix}/credential-sync/run`, ocHandlers.credentialSyncRun);
|
|
3305
|
-
app.get(`${prefix}/opencode/
|
|
4610
|
+
app.post(`${prefix}/credential-sync/run`, withPoolSync(registry, ocHandlers.credentialSyncRun));
|
|
4611
|
+
app.get(`${prefix}/opencode/protocol-vocabulary`, ocHandlers.protocolVocabulary);
|
|
3306
4612
|
app.get(`${prefix}/opencode/providers`, ocHandlers.list);
|
|
3307
4613
|
app.get(`${prefix}/opencode/catalog`, ocHandlers.catalog);
|
|
3308
4614
|
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
|
-
|
|
4615
|
+
app.post(`${prefix}/opencode/providers`, withPoolSync(registry, ocHandlers.create));
|
|
4616
|
+
app.patch(`${prefix}/opencode/providers/:id`, withPoolSync(registry, ocHandlers.update));
|
|
4617
|
+
app.post(`${prefix}/opencode/providers/:id/connect`, withPoolSync(registry, ocHandlers.connect));
|
|
4618
|
+
// Generic plugin web-authorization seam (device flow): start opens the
|
|
4619
|
+
// vendor login page; poll returns done+token and wires the fresh token
|
|
4620
|
+
// into the credential store. The plugin owns the whole protocol.
|
|
4621
|
+
app.post(`${prefix}/opencode/providers/:id/web-login/start`, ocHandlers.webLoginStart);
|
|
4622
|
+
// Both terminal paths write the fresh credential into the store, so both
|
|
4623
|
+
// must trigger a credential re-sync (same contract as the key route).
|
|
4624
|
+
app.get(`${prefix}/opencode/providers/:id/web-login/poll`, withPoolSync(registry, ocHandlers.webLoginPoll));
|
|
4625
|
+
app.post(`${prefix}/opencode/providers/:id/web-login/submit`, withPoolSync(registry, ocHandlers.webLoginSubmit));
|
|
4626
|
+
app.post(`${prefix}/opencode/providers/:id/key`, withPoolSync(registry, ocHandlers.setKey));
|
|
3313
4627
|
app.post(`${prefix}/opencode/providers/:id/test`, ocHandlers.test);
|
|
3314
|
-
app.delete(`${prefix}/opencode/providers/:id`, ocHandlers.remove);
|
|
4628
|
+
app.delete(`${prefix}/opencode/providers/:id`, withPoolSync(registry, ocHandlers.remove));
|
|
4629
|
+
// Provider-level operator takedown: routing state, not a defs write — the
|
|
4630
|
+
// pool resync drops (or restores) every model of the provider (ADR-0010).
|
|
4631
|
+
app.post(`${prefix}/opencode/providers/:id/disable`, withPoolSync(registry, ocHandlers.providerDisable));
|
|
4632
|
+
app.post(`${prefix}/opencode/providers/:id/enable`, withPoolSync(registry, ocHandlers.providerEnable));
|
|
3315
4633
|
// Per-provider model maintenance (config-defined providers only)
|
|
3316
4634
|
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
|
-
//
|
|
4635
|
+
app.post(`${prefix}/opencode/providers/:id/models`, withPoolSync(registry, ocHandlers.modelAdd));
|
|
4636
|
+
app.patch(`${prefix}/opencode/providers/:id/models/:modelId`, withPoolSync(registry, ocHandlers.modelUpdate));
|
|
4637
|
+
app.delete(`${prefix}/opencode/providers/:id/models/:modelId`, withPoolSync(registry, ocHandlers.modelRemove));
|
|
4638
|
+
app.post(`${prefix}/opencode/providers/:id/models/pull`, withPoolSync(registry, ocHandlers.modelsPull));
|
|
4639
|
+
app.post(`${prefix}/opencode/providers/:id/models/reorder`, withPoolSync(registry, ocHandlers.modelReorder));
|
|
4640
|
+
app.post(`${prefix}/opencode/providers/:id/models/clear`, withPoolSync(registry, ocHandlers.modelsClear));
|
|
4641
|
+
// Plugin host: read-only views + hot reload of the plugin dir.
|
|
4642
|
+
app.get(`${prefix}/plugins`, async () => {
|
|
4643
|
+
// views only — a read route must not clear+rebuild the live registry
|
|
4644
|
+
// (in-flight dispatch/probe would see an empty plugin set mid-rebuild)
|
|
4645
|
+
const { listInstalledPlugins } = await import('../plugins/host.js');
|
|
4646
|
+
return { status: 'ok', plugins: listInstalledPlugins() };
|
|
4647
|
+
});
|
|
4648
|
+
app.post(`${prefix}/plugins/reload`, async () => {
|
|
4649
|
+
const { loadInstalledPlugins, syncPluginPresets, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4650
|
+
await loadInstalledPlugins();
|
|
4651
|
+
const plugins = listInstalledPlugins();
|
|
4652
|
+
const registered = await syncPluginPresets();
|
|
4653
|
+
await refreshDirectPool(registry);
|
|
4654
|
+
return { status: 'ok', plugins, registered };
|
|
4655
|
+
});
|
|
4656
|
+
// Upload-install: raw zip bytes (application/octet-stream), id in the query.
|
|
4657
|
+
app.get(`${prefix}/plugins/:id/logo`, async (req, reply) => {
|
|
4658
|
+
const { id } = req.params;
|
|
4659
|
+
const { pluginLogoFile } = await import('../plugins/host.js');
|
|
4660
|
+
const file = pluginLogoFile(id);
|
|
4661
|
+
if (!file)
|
|
4662
|
+
return reply.code(404).send({ status: 'error', error: 'no logo' });
|
|
4663
|
+
const ext = file.split('.').pop()?.toLowerCase();
|
|
4664
|
+
const mime = ext === 'png' ? 'image/png'
|
|
4665
|
+
: ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg'
|
|
4666
|
+
: ext === 'webp' ? 'image/webp'
|
|
4667
|
+
: ext === 'svg' ? 'image/svg+xml'
|
|
4668
|
+
: undefined;
|
|
4669
|
+
if (!mime)
|
|
4670
|
+
return reply.code(415).send({ status: 'error', error: 'unsupported logo format' });
|
|
4671
|
+
// Logos ship inside operator-installed packages: treat them as untrusted
|
|
4672
|
+
// content. SVG can carry scripts on direct navigation — lock it down;
|
|
4673
|
+
// buffered send also avoids the uninstall race between check and stream.
|
|
4674
|
+
reply.header('X-Content-Type-Options', 'nosniff');
|
|
4675
|
+
reply.header('Content-Security-Policy', "default-src 'none'");
|
|
4676
|
+
return reply.type(mime).send(await fs.promises.readFile(file));
|
|
4677
|
+
});
|
|
4678
|
+
// Package export: a packaged plugin returns its installed zip verbatim; a
|
|
4679
|
+
// dev-tree plugin is bundled and zipped on the fly with the same
|
|
4680
|
+
// deterministic packer `plugins:build` uses, so a download round-trips
|
|
4681
|
+
// through Install. A bundle failure is the operator's signal that the
|
|
4682
|
+
// plugin cannot be packaged self-contained — surface the reason.
|
|
4683
|
+
app.get(`${prefix}/plugins/:id/package`, async (req, reply) => {
|
|
4684
|
+
const { id } = req.params;
|
|
4685
|
+
let zip;
|
|
4686
|
+
try {
|
|
4687
|
+
zip = await pluginPackageZip(id);
|
|
4688
|
+
}
|
|
4689
|
+
catch (err) {
|
|
4690
|
+
return reply.code(500).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4691
|
+
}
|
|
4692
|
+
if (!zip)
|
|
4693
|
+
return reply.code(404).send({ status: 'error', error: 'unknown plugin or package not found' });
|
|
4694
|
+
if (zip.length > PLUGIN_PACKAGE_MAX_BYTES) {
|
|
4695
|
+
return reply.code(413).send({ status: 'error', error: 'package exceeds 64 MiB' });
|
|
4696
|
+
}
|
|
4697
|
+
// Operator-installed bytes: lock the response down (same rule as logo).
|
|
4698
|
+
reply.header('X-Content-Type-Options', 'nosniff');
|
|
4699
|
+
reply.header('Content-Disposition', `attachment; filename="${id}.zip"`);
|
|
4700
|
+
return reply.type('application/zip').send(Buffer.from(zip));
|
|
4701
|
+
});
|
|
4702
|
+
/**
|
|
4703
|
+
* Re-materialize every client model surface a gateway plugin owns.
|
|
4704
|
+
*
|
|
4705
|
+
* A gateway's catalog config (list mode, followed key ids) is persisted in
|
|
4706
|
+
* its own artifact, but the clients it feeds MATERIALIZE that list into
|
|
4707
|
+
* their own files — those must be rewritten on save, or the picker keeps
|
|
4708
|
+
* whatever it held at hook time. A failed refresh never fails the save (the
|
|
4709
|
+
* config is already persisted); it is reported next to the values instead.
|
|
4710
|
+
*/
|
|
4711
|
+
const refreshOwnedModelSurfaces = async (pluginId) => {
|
|
4712
|
+
const { getAllClientAdapters } = await import('../cli/clients/index.js');
|
|
4713
|
+
const rows = [];
|
|
4714
|
+
for (const adapter of getAllClientAdapters()) {
|
|
4715
|
+
if (adapter.catalogPlugin !== pluginId || !adapter.refreshModelSurface)
|
|
4716
|
+
continue;
|
|
4717
|
+
try {
|
|
4718
|
+
const result = await adapter.refreshModelSurface();
|
|
4719
|
+
rows.push({ client: adapter.name, ok: result.success, message: result.message });
|
|
4720
|
+
}
|
|
4721
|
+
catch (err) {
|
|
4722
|
+
rows.push({ client: adapter.name, ok: false, message: err instanceof Error ? err.message : String(err) });
|
|
4723
|
+
}
|
|
4724
|
+
}
|
|
4725
|
+
return rows;
|
|
4726
|
+
};
|
|
4727
|
+
// Plugin-level configuration (ADR-0017): schema declared in plugin.json,
|
|
4728
|
+
// values stored as a plugin artifact — never in config.yaml.
|
|
4729
|
+
app.get(`${prefix}/plugins/:id/config`, async (req, reply) => {
|
|
4730
|
+
const { id } = req.params;
|
|
4731
|
+
const { getPluginConfig } = await import('../plugins/host.js');
|
|
4732
|
+
const cfg = getPluginConfig(id);
|
|
4733
|
+
if (!cfg)
|
|
4734
|
+
return reply.code(404).send({ status: 'error', error: 'unknown or unloaded plugin' });
|
|
4735
|
+
return { status: 'ok', schema: cfg.schema, sections: cfg.sections, values: cfg.values };
|
|
4736
|
+
});
|
|
4737
|
+
app.put(`${prefix}/plugins/:id/config`, async (req, reply) => {
|
|
4738
|
+
const { id } = req.params;
|
|
4739
|
+
const body = (req.body ?? {});
|
|
4740
|
+
if (!body.values || typeof body.values !== 'object' || Array.isArray(body.values)) {
|
|
4741
|
+
return reply.code(400).send({ status: 'error', error: 'body.values must be an object' });
|
|
4742
|
+
}
|
|
4743
|
+
try {
|
|
4744
|
+
const { applyPluginConfig } = await import('../plugins/host.js');
|
|
4745
|
+
const result = await applyPluginConfig(id, body.values);
|
|
4746
|
+
const surfaces = await refreshOwnedModelSurfaces(id);
|
|
4747
|
+
return { status: 'ok', values: result.values, warnings: result.warnings, surfaces };
|
|
4748
|
+
}
|
|
4749
|
+
catch (err) {
|
|
4750
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
4751
|
+
// Unknown/unloaded plugin = 404 (same as GET); schema/value problems = 400.
|
|
4752
|
+
if (message === 'unknown or unloaded plugin')
|
|
4753
|
+
return reply.code(404).send({ status: 'error', error: message });
|
|
4754
|
+
return reply.code(400).send({ status: 'error', error: message });
|
|
4755
|
+
}
|
|
4756
|
+
});
|
|
4757
|
+
app.delete(`${prefix}/plugins/:id/uninstall`, async (req, reply) => {
|
|
4758
|
+
const { id } = req.params;
|
|
4759
|
+
try {
|
|
4760
|
+
const { uninstallPlugin, loadInstalledPlugins, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4761
|
+
const result = await uninstallPlugin(id);
|
|
4762
|
+
await loadInstalledPlugins();
|
|
4763
|
+
const plugins = listInstalledPlugins();
|
|
4764
|
+
await refreshDirectPool(registry);
|
|
4765
|
+
return { status: 'ok', removed: result.removed, providersRemoved: result.providersRemoved, plugins };
|
|
4766
|
+
}
|
|
4767
|
+
catch (err) {
|
|
4768
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4769
|
+
}
|
|
4770
|
+
});
|
|
4771
|
+
// Toggle a plugin without deleting anything (works for dev-tree plugins
|
|
4772
|
+
// too): disabled.json skips it at discovery; enable + reload restores it.
|
|
4773
|
+
app.post(`${prefix}/plugins/:id/disable`, async (req, reply) => {
|
|
4774
|
+
const { id } = req.params;
|
|
4775
|
+
try {
|
|
4776
|
+
const { setPluginDisabled, loadInstalledPlugins, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4777
|
+
const result = await setPluginDisabled(id, true);
|
|
4778
|
+
await loadInstalledPlugins();
|
|
4779
|
+
const plugins = listInstalledPlugins();
|
|
4780
|
+
await refreshDirectPool(registry);
|
|
4781
|
+
return { status: 'ok', providersRemoved: result.providersRemoved, plugins };
|
|
4782
|
+
}
|
|
4783
|
+
catch (err) {
|
|
4784
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4785
|
+
}
|
|
4786
|
+
});
|
|
4787
|
+
app.post(`${prefix}/plugins/:id/enable`, async (req, reply) => {
|
|
4788
|
+
const { id } = req.params;
|
|
4789
|
+
try {
|
|
4790
|
+
const { setPluginDisabled, loadInstalledPlugins, listInstalledPlugins, syncPluginPresets } = await import('../plugins/host.js');
|
|
4791
|
+
await setPluginDisabled(id, false);
|
|
4792
|
+
await loadInstalledPlugins();
|
|
4793
|
+
const plugins = listInstalledPlugins();
|
|
4794
|
+
const registered = await syncPluginPresets();
|
|
4795
|
+
await refreshDirectPool(registry);
|
|
4796
|
+
return { status: 'ok', registered, plugins };
|
|
4797
|
+
}
|
|
4798
|
+
catch (err) {
|
|
4799
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4800
|
+
}
|
|
4801
|
+
});
|
|
4802
|
+
app.post(`${prefix}/plugins/install`, { bodyLimit: PLUGIN_PACKAGE_MAX_BYTES }, async (req, reply) => {
|
|
4803
|
+
const body = req.body;
|
|
4804
|
+
const bytes = typeof body === 'string' ? Buffer.from(body, 'binary') : body;
|
|
4805
|
+
if (!bytes || bytes.length === 0) {
|
|
4806
|
+
return reply.code(400).send({ status: 'error', error: 'empty body — send the plugin zip as application/octet-stream' });
|
|
4807
|
+
}
|
|
4808
|
+
if (bytes.length > PLUGIN_PACKAGE_MAX_BYTES) {
|
|
4809
|
+
return reply.code(413).send({ status: 'error', error: 'package exceeds 64 MiB' });
|
|
4810
|
+
}
|
|
4811
|
+
try {
|
|
4812
|
+
const { installPluginPackage, packageIdOf, pluginPackageZip, listInstalledPlugins: listing } = await import('../plugins/host.js');
|
|
4813
|
+
// Snapshot the version this upload is about to REPLACE (a packaged one
|
|
4814
|
+
// — a dev-tree plugin is not ours to materialize here). A failed upgrade
|
|
4815
|
+
// must not delete a working install.
|
|
4816
|
+
let previous;
|
|
4817
|
+
try {
|
|
4818
|
+
const target = packageIdOf(new Uint8Array(bytes));
|
|
4819
|
+
const existing = listing().find((p) => p.id === target);
|
|
4820
|
+
if (existing?.source === 'packaged' && !existing.disabled)
|
|
4821
|
+
previous = await pluginPackageZip(target);
|
|
4822
|
+
}
|
|
4823
|
+
catch {
|
|
4824
|
+
// unreadable upload: installPluginPackage below reports it properly
|
|
4825
|
+
}
|
|
4826
|
+
const { id: installed, version: installedVersion, replacedVersion } = installPluginPackage(new Uint8Array(bytes));
|
|
4827
|
+
const { loadInstalledPlugins, syncPluginPresets, listInstalledPlugins } = await import('../plugins/host.js');
|
|
4828
|
+
await loadInstalledPlugins();
|
|
4829
|
+
const plugins = listInstalledPlugins();
|
|
4830
|
+
const view = plugins.find((p) => p.id === installed && !p.disabled);
|
|
4831
|
+
if (!view?.loaded) {
|
|
4832
|
+
// a package that cannot load would re-fail every boot — discard it;
|
|
4833
|
+
// discard BEFORE preset sync / pool refresh so a broken package
|
|
4834
|
+
// registers nothing
|
|
4835
|
+
const { discardPluginPackage } = await import('../plugins/host.js');
|
|
4836
|
+
discardPluginPackage(installed);
|
|
4837
|
+
// Roll BACK to the version that was working until this upload, so a
|
|
4838
|
+
// bad upgrade is a no-op instead of a lost plugin.
|
|
4839
|
+
if (previous) {
|
|
4840
|
+
// A ROLLBACK is the one legitimate downgrade: the caller did not
|
|
4841
|
+
// ask for it, the loader did — the version guard exists for
|
|
4842
|
+
// uploads, and it must not block the recovery path.
|
|
4843
|
+
installPluginPackage(previous, { allowDowngrade: true });
|
|
4844
|
+
await loadInstalledPlugins();
|
|
4845
|
+
return reply.code(422).send({
|
|
4846
|
+
status: 'error',
|
|
4847
|
+
error: `package rejected and discarded (${view?.error ?? 'unknown error'}); rolled back to the previously installed version`,
|
|
4848
|
+
plugins: listInstalledPlugins(),
|
|
4849
|
+
});
|
|
4850
|
+
}
|
|
4851
|
+
// Reload AFTER the discard: otherwise the response would hand the
|
|
4852
|
+
// console a row for a package that is no longer on disk (the list is
|
|
4853
|
+
// the disk's truth, not the last failed import's).
|
|
4854
|
+
await loadInstalledPlugins();
|
|
4855
|
+
return reply
|
|
4856
|
+
.code(422)
|
|
4857
|
+
.send({ status: 'error', error: `package installed but failed to load (discarded): ${view?.error ?? 'unknown error'}`, plugins: listInstalledPlugins() });
|
|
4858
|
+
}
|
|
4859
|
+
// presets register at install time (same contract as boot/reload) —
|
|
4860
|
+
// after a verified successful load, BEFORE the pool refresh so the
|
|
4861
|
+
// fresh defs are routable immediately
|
|
4862
|
+
const registered = await syncPluginPresets();
|
|
4863
|
+
await refreshDirectPool(registry);
|
|
4864
|
+
return { status: 'ok', id: installed, version: installedVersion, replacedVersion, plugins, registered };
|
|
4865
|
+
}
|
|
4866
|
+
catch (err) {
|
|
4867
|
+
return reply.code(400).send({ status: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
4868
|
+
}
|
|
4869
|
+
});
|
|
4870
|
+
// Per-credential credential writes (reorder / rename / disconnect).
|
|
3324
4871
|
// Decision 8 double-confirm lives in the console UI; these honor the call.
|
|
3325
|
-
app.post(`${prefix}/opencode/providers/:id/credentials
|
|
4872
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/reorder`, withPoolSync(registry, ocHandlers.credentialReorder));
|
|
4873
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/weight`, withPoolSync(registry, ocHandlers.credentialSetWeight));
|
|
3326
4874
|
// Operator takedown (OCR credential state, NOT the credential store — survives
|
|
3327
4875
|
// 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);
|
|
4876
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/disable`, withPoolSync(registry, ocHandlers.credentialDisable));
|
|
4877
|
+
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/enable`, withPoolSync(registry, ocHandlers.credentialEnable));
|
|
4878
|
+
app.patch(`${prefix}/opencode/providers/:id/credentials/:credentialId`, withPoolSync(registry, ocHandlers.credentialRename));
|
|
4879
|
+
app.delete(`${prefix}/opencode/providers/:id/credentials/:credentialId`, withPoolSync(registry, ocHandlers.credentialDisconnect));
|
|
3332
4880
|
// password-gated raw-key export (controlled exception).
|
|
3333
4881
|
app.post(`${prefix}/opencode/providers/:id/credentials/:credentialId/reveal`, ocHandlers.credentialReveal);
|
|
3334
4882
|
}
|
|
@@ -3345,10 +4893,21 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3345
4893
|
};
|
|
3346
4894
|
app.get('/api/admin/catalog/logo', handleCatalogLogo);
|
|
3347
4895
|
// 9. Client API Keys Management (for external client access)
|
|
4896
|
+
// List is always masked — plaintext leaves only via the reveal endpoint
|
|
4897
|
+
// (Playground / copy flows). Defense in depth on top of the CORS tighten.
|
|
3348
4898
|
const handleListApiKeys = async () => {
|
|
3349
|
-
return { status: 'ok', keys: listApiKeys(
|
|
4899
|
+
return { status: 'ok', keys: listApiKeys(true) };
|
|
3350
4900
|
};
|
|
3351
4901
|
app.get('/api/admin/api-keys', handleListApiKeys);
|
|
4902
|
+
const handleRevealApiKey = async (req, reply) => {
|
|
4903
|
+
const { id } = req.params;
|
|
4904
|
+
const key = listApiKeys(false).find((k) => k.id === id);
|
|
4905
|
+
if (!key)
|
|
4906
|
+
return reply.status(404).send({ success: false, error: `API key '${id}' not found` });
|
|
4907
|
+
reply.header('Cache-Control', 'no-store');
|
|
4908
|
+
return { status: 'ok', id: key.id, key: key.key };
|
|
4909
|
+
};
|
|
4910
|
+
app.post('/api/admin/api-keys/:id/reveal', handleRevealApiKey);
|
|
3352
4911
|
const handleCreateApiKey = async (req, reply) => {
|
|
3353
4912
|
const body = req.body;
|
|
3354
4913
|
if (!body?.name) {
|
|
@@ -3588,6 +5147,12 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3588
5147
|
kind: 'model',
|
|
3589
5148
|
owned_by: m.provider,
|
|
3590
5149
|
tiers: registry.tiersOf(m),
|
|
5150
|
+
// Declared thinking levels (ADR-0003 vocabulary). Console pickers that
|
|
5151
|
+
// write a level into a config field (tier effort maps, variant pins)
|
|
5152
|
+
// offer ONLY these — anything else would be clamped right back by
|
|
5153
|
+
// downgradeReasoning. `[]` is a REAL answer ("no explicit level
|
|
5154
|
+
// control", e.g. a toggle-only model), never "unknown".
|
|
5155
|
+
efforts: modelSupportsEfforts(m.supportedReasoningEfforts, m.supportsReasoningEffort) ?? [],
|
|
3591
5156
|
// Resolved upstream wire (model-level npm beats provider npm, see
|
|
3592
5157
|
// providers/wire.ts). Console pickers MUST read it from here instead of
|
|
3593
5158
|
// re-deriving it from the provider's npm string — `systemone` marks a
|
|
@@ -3606,26 +5171,45 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3606
5171
|
return { status: 'ok', models };
|
|
3607
5172
|
};
|
|
3608
5173
|
app.get('/api/admin/gateway-models', handleGatewayModels);
|
|
3609
|
-
// 10. Remote restart trigger from UI — spawn a detached
|
|
3610
|
-
// first
|
|
3611
|
-
//
|
|
3612
|
-
//
|
|
5174
|
+
// 10. Remote restart trigger from UI — spawn a detached restart SUPERVISOR
|
|
5175
|
+
// first, then exit. The supervisor waits for this process to die (and
|
|
5176
|
+
// force-kills it if stuck), spawns the replacement gateway, verifies
|
|
5177
|
+
// `/health` (retrying a crashed child), and records the verdict in
|
|
5178
|
+
// ocr.restart.json. Without the spawn we would just stop and nothing
|
|
5179
|
+
// would bring the gateway back (there is no resident supervisor).
|
|
5180
|
+
// One handover at a time: this process exits 500 ms after acknowledging, so
|
|
5181
|
+
// a second POST inside that window would spawn a SECOND supervisor and two
|
|
5182
|
+
// replacements would race for the listen port. Idempotent answer instead.
|
|
5183
|
+
let restartInFlight = false;
|
|
3613
5184
|
const handleRestart = async () => {
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
|
|
5185
|
+
if (restartInFlight) {
|
|
5186
|
+
return { status: 'restarting', message: 'Gateway restart is already in progress' };
|
|
5187
|
+
}
|
|
5188
|
+
restartInFlight = true;
|
|
5189
|
+
try {
|
|
5190
|
+
const { spawnDetachedRestartChild } = await import('../cli/daemon.js');
|
|
5191
|
+
const cfg = loadConfig();
|
|
5192
|
+
const addr = app.server.address();
|
|
5193
|
+
const port = typeof addr === 'object' && addr ? addr.port : cfg.port;
|
|
5194
|
+
const spawned = spawnDetachedRestartChild({ port, host: cfg.host });
|
|
5195
|
+
if (!spawned) {
|
|
5196
|
+
restartInFlight = false;
|
|
5197
|
+
// Fault-tolerance: NEVER stop the gateway without a replacement — keep
|
|
5198
|
+
// serving and surface the failure to the UI instead of exiting.
|
|
5199
|
+
return {
|
|
5200
|
+
status: 'failed',
|
|
5201
|
+
message: 'Could not spawn a replacement process — gateway keeps running. Restart it manually when convenient.',
|
|
5202
|
+
};
|
|
5203
|
+
}
|
|
5204
|
+
setTimeout(() => process.exit(0), 500);
|
|
5205
|
+
return { status: 'restarting', message: 'Gateway restart signal acknowledged — the detached supervisor is booting the replacement' };
|
|
5206
|
+
}
|
|
5207
|
+
catch (err) {
|
|
5208
|
+
// Un-stick the guard: a thrown spawn/config error must not make every
|
|
5209
|
+
// later restart answer "already in progress" forever.
|
|
5210
|
+
restartInFlight = false;
|
|
5211
|
+
return { status: 'failed', message: `Restart failed: ${err.message}` };
|
|
3626
5212
|
}
|
|
3627
|
-
setTimeout(() => process.exit(0), 500);
|
|
3628
|
-
return { status: 'restarting', message: 'Gateway restart signal acknowledged — replacement process is booting' };
|
|
3629
5213
|
};
|
|
3630
5214
|
app.post('/api/admin/restart', handleRestart);
|
|
3631
5215
|
// 11. Process-log tail viewer — reads ~/.omnicell-router/ocr.log (only
|
|
@@ -3746,6 +5330,7 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3746
5330
|
const r = await stopHeadroomSidecar({ url: headroomSidecarCfg()?.url });
|
|
3747
5331
|
return { status: r.ok ? 'ok' : 'error', ...r };
|
|
3748
5332
|
});
|
|
5333
|
+
registerMihomoRoutes(app);
|
|
3749
5334
|
/* ---------------------------------------------------------------------- *
|
|
3750
5335
|
* 12b. Request-capture archive browser (CaptureRecorder; opt-in audit log)
|
|
3751
5336
|
* Bodies may contain sensitive data — these endpoints sit under /api/admin/*
|
|
@@ -3829,40 +5414,65 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3829
5414
|
return { status: 'ok', date, file, ...result };
|
|
3830
5415
|
});
|
|
3831
5416
|
/**
|
|
3832
|
-
* Read the HTTP exchange events written by the capture pipeline
|
|
3833
|
-
*
|
|
3834
|
-
*
|
|
3835
|
-
*
|
|
5417
|
+
* Read the HTTP exchange events written by the capture pipeline and
|
|
5418
|
+
* project them into REQUESTS. Every event carries its `requestId`,
|
|
5419
|
+
* `exchangeId` and write-time turn identity; the recorder groups all
|
|
5420
|
+
* exchanges of one request into `requests[].exchanges[]`.
|
|
3836
5421
|
*/
|
|
3837
5422
|
app.get('/api/admin/capture/:date/:file/events', async (req, reply) => {
|
|
3838
5423
|
const { date, file } = req.params;
|
|
3839
5424
|
if (!CAPTURE_DATE_RE.test(date)) {
|
|
3840
5425
|
return reply.status(400).send({ status: 'error', message: 'date must be YYYY-MM-DD' });
|
|
3841
5426
|
}
|
|
3842
|
-
|
|
5427
|
+
// `limit` is REQUESTS per page (every exchange of a request always
|
|
5428
|
+
// travels with it), so the pager counts the same unit as the header.
|
|
5429
|
+
// 50 requests is the console default.
|
|
5430
|
+
const limit = Math.min(Math.max(parseInt(req.query?.limit || '50', 10) || 50, 1), 500);
|
|
3843
5431
|
// 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
|
-
|
|
5432
|
+
// payload, instant paint); full bodies come back per request via
|
|
5433
|
+
// /request or a bodies=full re-read. bodies=chat keeps prompt-start
|
|
5434
|
+
// request bodies + response bodies only — the replay's bounded footprint.
|
|
5435
|
+
const bodiesParam = req.query?.bodies;
|
|
5436
|
+
const bodies = bodiesParam === 'none' ? 'none' : bodiesParam === 'chat' ? 'chat' : 'full';
|
|
3847
5437
|
// stitched=1: merge the session's fragments from every date dir (a
|
|
3848
5438
|
// conversation that crossed midnight — or whose session id churned) into
|
|
3849
5439
|
// one chronological timeline. Response carries the per-fragment breakdown.
|
|
3850
5440
|
const stitched = req.query?.stitched === '1';
|
|
5441
|
+
// page=1 is the NEWEST window page; older pages count up from there.
|
|
5442
|
+
// Pages are REQUEST pages (a page never splits a request's events),
|
|
5443
|
+
// bounded by the read window — older history is export-only.
|
|
5444
|
+
const page = Math.min(Math.max(parseInt(req.query?.page || '1', 10) || 1, 1), 100000);
|
|
3851
5445
|
const result = stitched
|
|
3852
|
-
? await captureRecorder.readEventsStitched(date, file, limit, bodies)
|
|
3853
|
-
: await captureRecorder.readEvents(date, file, limit, bodies);
|
|
5446
|
+
? await captureRecorder.readEventsStitched(date, file, limit, bodies, page)
|
|
5447
|
+
: await captureRecorder.readEvents(date, file, limit, bodies, page);
|
|
3854
5448
|
if (result.totalLines === 0 && !captureRecorder.listSessions(date).some(s => s.file === file)) {
|
|
3855
5449
|
return reply.status(404).send({ status: 'error', message: 'Capture archive not found' });
|
|
3856
5450
|
}
|
|
3857
5451
|
return { status: 'ok', date, file, ...result };
|
|
3858
5452
|
});
|
|
3859
5453
|
/**
|
|
3860
|
-
*
|
|
3861
|
-
*
|
|
3862
|
-
*
|
|
3863
|
-
*
|
|
5454
|
+
* EXACT whole-archive summary: the request count and the WRITE-TIME TURN
|
|
5455
|
+
* INDEX (one entry per `turnIndex`, with its request range) for the turn
|
|
5456
|
+
* selector. The events window only knows the tail; this metadata scan is
|
|
5457
|
+
* streamed and never parses request bodies.
|
|
5458
|
+
* Display-only: pagination still follows a bounded read window.
|
|
3864
5459
|
*/
|
|
3865
|
-
app.get('/api/admin/capture/:date/:file/
|
|
5460
|
+
app.get('/api/admin/capture/:date/:file/summary', async (req) => {
|
|
5461
|
+
const { date, file } = req.params;
|
|
5462
|
+
const stitched = req.query?.stitched === '1';
|
|
5463
|
+
const summary = stitched
|
|
5464
|
+
? await captureRecorder.captureSummaryStitched(date, file)
|
|
5465
|
+
: await captureRecorder.captureSummary(date, file);
|
|
5466
|
+
return { status: 'ok', date, file, ...summary };
|
|
5467
|
+
});
|
|
5468
|
+
/**
|
|
5469
|
+
* Full wire bodies for ONE REQUEST (keyed by its `requestId`; an event id
|
|
5470
|
+
* is accepted too for deep links). The metadata-first events read strips
|
|
5471
|
+
* bodies; the drawer fetches them here when a request is opened. Bounded
|
|
5472
|
+
* by the same read window as /events — a request archived beyond the
|
|
5473
|
+
* window answers 404.
|
|
5474
|
+
*/
|
|
5475
|
+
app.get('/api/admin/capture/:date/:file/request', async (req, reply) => {
|
|
3866
5476
|
const { date, file } = req.params;
|
|
3867
5477
|
if (!CAPTURE_DATE_RE.test(date)) {
|
|
3868
5478
|
return reply.status(400).send({ status: 'error', message: 'date must be YYYY-MM-DD' });
|
|
@@ -3872,13 +5482,13 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3872
5482
|
return reply.status(400).send({ status: 'error', message: 'id query param required' });
|
|
3873
5483
|
}
|
|
3874
5484
|
// stitched=1: also search the session's other date-dir fragments — a
|
|
3875
|
-
// cross-midnight
|
|
5485
|
+
// cross-midnight request's bodies live in the shard its events landed in.
|
|
3876
5486
|
const stitched = req.query?.stitched === '1';
|
|
3877
5487
|
const result = stitched
|
|
3878
|
-
? await captureRecorder.
|
|
3879
|
-
: await captureRecorder.
|
|
5488
|
+
? await captureRecorder.readRequestStitched(date, file, id)
|
|
5489
|
+
: await captureRecorder.readRequest(date, file, id);
|
|
3880
5490
|
if (!result) {
|
|
3881
|
-
return reply.status(404).send({ status: 'error', message: '
|
|
5491
|
+
return reply.status(404).send({ status: 'error', message: 'Request not found in read window' });
|
|
3882
5492
|
}
|
|
3883
5493
|
return { status: 'ok', date, file, ...result };
|
|
3884
5494
|
});
|
|
@@ -3927,10 +5537,95 @@ export function registerConsoleRoutes(app, registry, orchestrator) {
|
|
|
3927
5537
|
}
|
|
3928
5538
|
return { status: 'ok', message: `Capture archive ${date} deleted` };
|
|
3929
5539
|
});
|
|
5540
|
+
/* ---------------------------------------------------------------------- *
|
|
5541
|
+
* One-shot upstream-request replay (capture drawer debug button).
|
|
5542
|
+
* Re-sends a captured upstream request verbatim — NO pipeline, NO session
|
|
5543
|
+
* machinery, NO capture recording: the fetch here is a bare console-side
|
|
5544
|
+
* HTTP call, invisible to the observation ledgers. Debugging aid only.
|
|
5545
|
+
* ---------------------------------------------------------------------- */
|
|
5546
|
+
app.post('/api/admin/capture/replay', async (req, reply) => {
|
|
5547
|
+
const { url, method, headers, body, provider, model } = (req.body || {});
|
|
5548
|
+
if (!url || !/^https?:\/\//i.test(url)) {
|
|
5549
|
+
return reply.status(400).send({ status: 'error', message: 'an absolute http(s) "url" is required' });
|
|
5550
|
+
}
|
|
5551
|
+
if (!method || !/^[A-Z]+$/.test(method)) {
|
|
5552
|
+
return reply.status(400).send({ status: 'error', message: '"method" must be an upper-case HTTP verb' });
|
|
5553
|
+
}
|
|
5554
|
+
if (body !== undefined && typeof body !== 'string') {
|
|
5555
|
+
return reply.status(400).send({ status: 'error', message: '"body" must be a UTF-8 string (hex/binary bodies are not replayable)' });
|
|
5556
|
+
}
|
|
5557
|
+
// Hop-by-hop / recomputed-by-fetch headers: replaying them verbatim
|
|
5558
|
+
// corrupts the request (stale length, wrong authority).
|
|
5559
|
+
const SKIP_HEADERS = {
|
|
5560
|
+
host: true,
|
|
5561
|
+
'content-length': true,
|
|
5562
|
+
connection: true,
|
|
5563
|
+
'transfer-encoding': true,
|
|
5564
|
+
};
|
|
5565
|
+
const outHeaders = {};
|
|
5566
|
+
for (const [name, value] of Object.entries(headers || {})) {
|
|
5567
|
+
if (!SKIP_HEADERS[name.toLowerCase()] && typeof value === 'string')
|
|
5568
|
+
outHeaders[name] = value;
|
|
5569
|
+
}
|
|
5570
|
+
// Stream the result as NDJSON so the console can render the body
|
|
5571
|
+
// incrementally (SSE replays become live): one JSON event per line —
|
|
5572
|
+
// status (status line + headers), chunk (body piece), end (terminal cap
|
|
5573
|
+
// flag), error (transport failure). The call is console-side only —
|
|
5574
|
+
// nothing is recorded anywhere.
|
|
5575
|
+
reply.hijack();
|
|
5576
|
+
const raw = reply.raw;
|
|
5577
|
+
raw.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-store' });
|
|
5578
|
+
const send = (evt) => raw.write(`${JSON.stringify(evt)}\n`);
|
|
5579
|
+
try {
|
|
5580
|
+
// Honor the outbound proxy policy for fidelity with the original call;
|
|
5581
|
+
// provider/model are the policy's glob keys (absent → direct).
|
|
5582
|
+
const res = await proxiedFetch(url, {
|
|
5583
|
+
method,
|
|
5584
|
+
headers: outHeaders,
|
|
5585
|
+
body: body || undefined,
|
|
5586
|
+
signal: AbortSignal.timeout(DEFAULT_REPLAY_TIMEOUT_MS),
|
|
5587
|
+
}, { provider, model });
|
|
5588
|
+
const resHeaders = {};
|
|
5589
|
+
res.headers.forEach((value, key) => {
|
|
5590
|
+
resHeaders[key] = value;
|
|
5591
|
+
});
|
|
5592
|
+
send({ type: 'status', statusLine: `HTTP/1.1 ${res.status} ${res.statusText}`.trimEnd(), headers: resHeaders });
|
|
5593
|
+
// Cap the streamed echo — the replay result is console UI text, not an
|
|
5594
|
+
// archive record; huge streams surface their head then get cancelled.
|
|
5595
|
+
const REPLAY_BODY_CAP = 512 * 1024;
|
|
5596
|
+
const reader = res.body?.getReader();
|
|
5597
|
+
let total = 0;
|
|
5598
|
+
let truncated = false;
|
|
5599
|
+
if (reader) {
|
|
5600
|
+
const dec = new TextDecoder();
|
|
5601
|
+
for (;;) {
|
|
5602
|
+
const { done, value } = await reader.read();
|
|
5603
|
+
if (done)
|
|
5604
|
+
break;
|
|
5605
|
+
total += value.byteLength;
|
|
5606
|
+
if (total >= REPLAY_BODY_CAP) {
|
|
5607
|
+
truncated = true;
|
|
5608
|
+
send({ type: 'chunk', text: dec.decode(value.subarray(0, value.byteLength - (total - REPLAY_BODY_CAP))) });
|
|
5609
|
+
break;
|
|
5610
|
+
}
|
|
5611
|
+
send({ type: 'chunk', text: dec.decode(value, { stream: true }) });
|
|
5612
|
+
}
|
|
5613
|
+
await reader.cancel().catch(() => undefined);
|
|
5614
|
+
}
|
|
5615
|
+
send({ type: 'end', truncated });
|
|
5616
|
+
raw.end();
|
|
5617
|
+
}
|
|
5618
|
+
catch (err) {
|
|
5619
|
+
// Hijacked reply: transport errors must flow through the stream too.
|
|
5620
|
+
const cause = err?.cause?.code || err?.code;
|
|
5621
|
+
raw.write(`${JSON.stringify({ type: 'error', message: cause ? `${err.message} (${cause})` : String(err?.message || err) })}\n`);
|
|
5622
|
+
raw.end();
|
|
5623
|
+
}
|
|
5624
|
+
});
|
|
3930
5625
|
/* ---------------------------------------------------------------------- *
|
|
3931
5626
|
* Session observation maintenance (console /sessions page cleanup).
|
|
3932
5627
|
* Console pages cannot present API keys, so destructive session ops live
|
|
3933
|
-
* under /api/admin — same trust surface as the capture
|
|
5628
|
+
* under /api/admin — same trust surface as the capture archive deletes
|
|
3934
5629
|
* above. (DELETE /api/admin/sessions/:id is registered in server.ts together
|
|
3935
5630
|
* with the rest of the sessions* surface.)
|
|
3936
5631
|
* ---------------------------------------------------------------------- */
|