@bitkyc08/opencodex 2.100.5 → 2.100.6-preview.20261119.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/ocx.mjs +2 -0
- package/gui/dist/assets/App-BI8LQ7Qk.css +1 -0
- package/gui/dist/assets/App-D5qUBOoF.js +60 -0
- package/gui/dist/assets/Tray-DMwQSAli.js +1 -0
- package/gui/dist/assets/brand-mark-ycThul7d.js +1 -0
- package/gui/dist/assets/index-Bp_GaFFu.js +138 -0
- package/gui/dist/assets/index-BtwVlpeQ.css +2 -0
- package/gui/dist/assets/{segment-thumb-features-Bquysdn5.js → segment-thumb-features-BLUW2Fb1.js} +1 -1
- package/gui/dist/classic/assets/App-CoiVLRW3.css +1 -0
- package/gui/dist/classic/assets/App-D39mkP2w.js +59 -0
- package/gui/dist/classic/assets/Tray-nUmdL7K9.js +1 -0
- package/gui/dist/classic/assets/index-BJ4uxZk0.js +138 -0
- package/gui/dist/classic/assets/usage-companion-chart-DFoYm2RY.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/native/ocx-child/Cargo.lock +62 -0
- package/native/ocx-child/Cargo.toml +1 -0
- package/native/ocx-child/src/journal.rs +32 -10
- package/native/ocx-child/src/state.rs +2 -1
- package/native/ocx-child/src/toml_surgeon.rs +183 -72
- package/package.json +2 -2
- package/src/adapters/agy-acp/acp.ts +202 -0
- package/src/adapters/agy-acp/adapter.ts +554 -0
- package/src/adapters/agy-acp/binary.ts +79 -0
- package/src/adapters/agy-acp/options.ts +163 -0
- package/src/adapters/agy-acp/output-redaction.ts +270 -0
- package/src/adapters/agy-acp/policy.ts +105 -0
- package/src/adapters/agy-acp/process.ts +218 -0
- package/src/adapters/anthropic/account-metadata.ts +4 -1
- package/src/adapters/anthropic/advisor-tool.ts +43 -9
- package/src/adapters/anthropic/client-identity.ts +2 -0
- package/src/adapters/anthropic.ts +102 -14
- package/src/adapters/antigravity-refusal.ts +5 -1
- package/src/adapters/base.ts +25 -2
- package/src/adapters/claude-cli/adapter.ts +1 -0
- package/src/adapters/claude-cli/usage-admission.ts +12 -9
- package/src/adapters/codebuddy/adapter.ts +1 -0
- package/src/adapters/command-code.ts +2 -2
- package/src/adapters/cursor/http1-bidi.ts +7 -2
- package/src/adapters/cursor/live-transport.ts +2 -0
- package/src/adapters/cursor/request-builder.ts +4 -4
- package/src/adapters/cursor/tool-naming.ts +5 -5
- package/src/adapters/cursor/transport-retry.ts +14 -8
- package/src/adapters/cursor/transport.ts +2 -0
- package/src/adapters/cursor.ts +8 -2
- package/src/adapters/google-error-details.ts +105 -0
- package/src/adapters/google-errors.ts +183 -31
- package/src/adapters/google-http.ts +66 -22
- package/src/adapters/google-truncation.ts +48 -3
- package/src/adapters/google-vertex-endpoint.ts +12 -1
- package/src/adapters/google.ts +54 -26
- package/src/adapters/kiro/adapter.ts +39 -38
- package/src/adapters/kiro/stream.ts +59 -9
- package/src/adapters/kiro-retry.ts +5 -3
- package/src/adapters/m365-copilot/LICENSE +21 -0
- package/src/adapters/m365-copilot/fenced.ts +745 -0
- package/src/adapters/m365-copilot/images.ts +89 -0
- package/src/adapters/m365-copilot/tools.ts +284 -0
- package/src/adapters/m365-copilot/transport.ts +232 -0
- package/src/adapters/m365-copilot.ts +143 -0
- package/src/adapters/openai-chat/tool-schema.ts +2 -2
- package/src/adapters/openai-responses/passthrough.ts +1 -0
- package/src/adapters/openai-responses/reasoning.ts +23 -3
- package/src/adapters/physical-send.ts +11 -4
- package/src/adapters/qoder/adapter.ts +17 -3
- package/src/adapters/registry.ts +15 -1
- package/src/adapters/zed.ts +2 -1
- package/src/advisor/consult.ts +1 -0
- package/src/bridge/response-json.ts +6 -2
- package/src/bridge/sse.ts +21 -9
- package/src/chat/inbound.ts +11 -8
- package/src/chat/outbound.ts +28 -7
- package/src/claude/context-windows.ts +32 -8
- package/src/claude/desktop-3p.ts +18 -14
- package/src/claude/desktop-picker-platform.ts +1 -1
- package/src/claude/desktop-picker.ts +3 -3
- package/src/claude/inbound-content-options.ts +11 -1
- package/src/claude/intercept/picker-ca-cleanup.ts +17 -5
- package/src/claude/intercept/picker-ca.ts +162 -27
- package/src/claude/intercept/picker-trust-linux.ts +411 -0
- package/src/claude/intercept/picker-trust.ts +35 -3
- package/src/claude/intercept/runtime.ts +2 -2
- package/src/claude/subagent-force-status.ts +24 -5
- package/src/claude/subscription-reserve.ts +87 -0
- package/src/cli/account-api.ts +3 -0
- package/src/cli/account-auth.ts +65 -11
- package/src/cli/account-extended.ts +1 -1
- package/src/cli/account-next-actions.ts +4 -1
- package/src/cli/account-policy-dto.ts +1 -1
- package/src/cli/account-policy.ts +6 -3
- package/src/cli/account-probe.ts +66 -0
- package/src/cli/account.ts +8 -2
- package/src/cli/capabilities-accounts.ts +8 -1
- package/src/cli/capabilities-agents-routing.ts +2 -2
- package/src/cli/capabilities-base.ts +4 -4
- package/src/cli/capabilities-integrations.ts +44 -4
- package/src/cli/capabilities-provider-models.ts +6 -0
- package/src/cli/claude-context-settings.ts +60 -0
- package/src/cli/claude-desktop.ts +2 -2
- package/src/cli/claude.ts +15 -7
- package/src/cli/client-start-fence.ts +64 -1
- package/src/cli/combo-result.ts +1 -0
- package/src/cli/combo-stats.ts +1 -1
- package/src/cli/combo.ts +19 -2
- package/src/cli/config-command.ts +21 -8
- package/src/cli/connect.ts +16 -0
- package/src/cli/cross-home-owner.ts +65 -18
- package/src/cli/dispatch.ts +4 -0
- package/src/cli/gateway-client-command.ts +128 -0
- package/src/cli/index.ts +98 -97
- package/src/cli/init.ts +20 -4
- package/src/cli/integrations.ts +23 -3
- package/src/cli/launcher-context.ts +12 -1
- package/src/cli/link.ts +24 -5
- package/src/cli/models-runtime-subcommands.ts +1 -0
- package/src/cli/models-runtime.ts +32 -0
- package/src/cli/start-owner-fence.ts +5 -2
- package/src/cli/status.ts +3 -3
- package/src/cli/stop-client-process.ts +51 -0
- package/src/cli/stop-restore.ts +383 -36
- package/src/cli/sync-command.ts +2 -2
- package/src/cli/uninstall-client-state.ts +7 -0
- package/src/client/connect.ts +72 -13
- package/src/client/hub-client.ts +38 -0
- package/src/client/hub-relay.ts +61 -36
- package/src/client/hub-session.ts +106 -0
- package/src/client/lifecycle-lock.ts +6 -1
- package/src/client/link-relay.ts +2 -1
- package/src/client/machine-listener.ts +60 -1
- package/src/client/runtime-restart.ts +1 -0
- package/src/client/runtime.ts +104 -34
- package/src/client/state.ts +11 -0
- package/src/client/stop-darwin-process.ts +73 -0
- package/src/client/stop-file-routing.ts +49 -0
- package/src/client/stop-native-handoff.ts +108 -0
- package/src/client/stop-routing.ts +41 -7
- package/src/client/stop-teardown-owner.ts +173 -0
- package/src/client/sync-runtime.ts +23 -4
- package/src/clients/config-export/opencode-wire.ts +24 -0
- package/src/clients/config-export.ts +28 -19
- package/src/codex/auth-api/login-flow.ts +68 -33
- package/src/codex/auth-api/main-account-probe.ts +3 -3
- package/src/codex/auth-api/pool-quota-probe.ts +8 -7
- package/src/codex/auth-api/routes.ts +1 -1
- package/src/codex/catalog/aggregation.ts +22 -10
- package/src/codex/catalog/gather-capture.ts +11 -2
- package/src/codex/catalog/m365-copilot-models.ts +52 -0
- package/src/codex/catalog/provider-models.ts +126 -53
- package/src/codex/catalog/routed-gather.ts +26 -12
- package/src/codex/catalog-admission.ts +4 -6
- package/src/codex/catalog-auto-refresh.ts +4 -2
- package/src/codex/catalog-self-heal.ts +4 -2
- package/src/codex/control-plane-models.ts +6 -0
- package/src/codex/convergence.ts +10 -0
- package/src/codex/desktop-app/picker-freshness.ts +3 -14
- package/src/codex/desktop-app/types.ts +6 -0
- package/src/codex/desktop-app/windows-command-payload.ts +9 -0
- package/src/codex/desktop-app/windows.ts +20 -12
- package/src/codex/desktop-compatibility/installed-build.ts +61 -58
- package/src/codex/desktop-compatibility/runtime-ownership.ts +11 -5
- package/src/codex/desktop-compatibility/runtime.ts +51 -14
- package/src/codex/desktop-compatibility/windows-activation-source.ts +28 -13
- package/src/codex/desktop-compatibility/windows-package-command.ts +73 -33
- package/src/codex/desktop-compatibility/windows-package-launch.ts +41 -9
- package/src/codex/desktop-compatibility/windows-package-proof.ts +104 -0
- package/src/codex/inject/config-toml.ts +67 -73
- package/src/codex/inject/plan.ts +11 -10
- package/src/codex/inject/remove.ts +4 -1
- package/src/codex/inject.ts +1 -0
- package/src/codex/journal-config-restore.ts +31 -4
- package/src/codex/journal.ts +16 -4
- package/src/codex/model-cache.ts +98 -27
- package/src/codex/native-residue.ts +14 -13
- package/src/codex/paths.ts +65 -28
- package/src/codex/quota-observation-freshness.ts +4 -0
- package/src/codex/quota.ts +71 -8
- package/src/codex/routing/selection.ts +32 -8
- package/src/combos/capability-policy.ts +31 -0
- package/src/combos/failover.ts +82 -74
- package/src/combos/identifiers.ts +2 -2
- package/src/combos/index.ts +3 -0
- package/src/combos/jev-model-backend.ts +12 -4
- package/src/combos/jev-session-pin-config.ts +22 -9
- package/src/combos/jev.ts +15 -4
- package/src/combos/request-capability.ts +214 -0
- package/src/combos/request.ts +22 -15
- package/src/combos/resolve.ts +5 -2
- package/src/combos/suggestion-channel.ts +89 -0
- package/src/combos/types.ts +14 -1
- package/src/config/account-auto-pause-revisions.ts +33 -10
- package/src/config/atomic-write.ts +1 -1
- package/src/config/codex-ws-incremental-setting.ts +34 -0
- package/src/config/diagnostics.ts +47 -8
- package/src/config/live-topology.ts +4 -2
- package/src/config/load-degrade.ts +96 -2
- package/src/config/mutation-lock.ts +7 -3
- package/src/config/paths.ts +3 -0
- package/src/config/pending-teardown.ts +19 -3
- package/src/config/process-state.ts +30 -12
- package/src/config/provider-validation.ts +10 -0
- package/src/config/salvage.ts +2 -2
- package/src/config/schema/account-auto-pause.ts +15 -1
- package/src/config/schema/agy-acp-references.ts +257 -0
- package/src/config/schema/config-schema.ts +32 -0
- package/src/config/schema/leaf-validators.ts +42 -0
- package/src/config/schema/subscription-reserve.ts +33 -0
- package/src/config/windows-process-command-line.ts +27 -9
- package/src/config.ts +6 -0
- package/src/generated/compatibility-version.json +806 -402
- package/src/images/loop.ts +79 -39
- package/src/integrations/catalog-refresh.ts +19 -1
- package/src/integrations/gateway-clients/agy.ts +340 -0
- package/src/integrations/gateway-clients/antigravity.ts +224 -0
- package/src/integrations/gateway-clients/index.ts +89 -0
- package/src/integrations/gateway-clients/io.ts +278 -0
- package/src/integrations/gateway-clients/types.ts +80 -0
- package/src/integrations/route-intent-disconnect.ts +37 -21
- package/src/lib/app-owned-memory-stores.ts +9 -0
- package/src/lib/cloud-code-appeal-link.ts +30 -0
- package/src/lib/errors.ts +32 -0
- package/src/lib/executor-physical-send-receipt.ts +42 -0
- package/src/lib/failure-detail.ts +1 -0
- package/src/lib/gcp-adc.ts +5 -0
- package/src/lib/http-date.ts +91 -0
- package/src/lib/lab-passive-linker-registration.ts +2 -1
- package/src/lib/local-chat-completion.ts +13 -3
- package/src/lib/local-internal-call-capability.ts +1 -3
- package/src/lib/messages-error-body.ts +2 -1
- package/src/lib/outbound-credential-registry.ts +40 -4
- package/src/lib/pinned-http.ts +7 -2
- package/src/lib/process-control.ts +1 -0
- package/src/lib/provider-egress.ts +16 -0
- package/src/lib/provider-outbound.ts +3 -0
- package/src/lib/redact-folding.ts +12 -3
- package/src/lib/redact.ts +37 -19
- package/src/lib/request-execution-budget.ts +241 -32
- package/src/lib/request-peer-scope.ts +64 -0
- package/src/lib/response-send-readings.ts +41 -0
- package/src/lib/state-store-registrations.ts +5 -0
- package/src/lib/tool-envelope-echo-filter.ts +33 -5
- package/src/lib/upstream-condition.ts +10 -3
- package/src/lib/upstream-retry.ts +95 -20
- package/src/lib/windows-secret-acl.ts +24 -7
- package/src/link/child-activity.ts +60 -4
- package/src/link/codex-settings.ts +2 -1
- package/src/link/relay-auth.ts +1 -0
- package/src/link/route-rounds.ts +32 -9
- package/src/link/status-projection.ts +42 -5
- package/src/link/supervisor.ts +96 -11
- package/src/link/tunnel-history.ts +5 -0
- package/src/oauth/account-auto-pause-policy.ts +72 -19
- package/src/oauth/account-auto-pause.ts +40 -16
- package/src/oauth/anthropic-account-refusal.ts +7 -0
- package/src/oauth/anthropic-continuity.ts +70 -9
- package/src/oauth/anthropic-identity.ts +75 -11
- package/src/oauth/anthropic-login-slot.ts +258 -0
- package/src/oauth/anthropic-routing.ts +24 -9
- package/src/oauth/anthropic-send-ownership.ts +4 -3
- package/src/oauth/anthropic.ts +30 -11
- package/src/oauth/health.ts +7 -2
- package/src/oauth/index.ts +50 -48
- package/src/oauth/key-providers.ts +2 -0
- package/src/oauth/login-cli.ts +11 -0
- package/src/oauth/login-flow-state.ts +10 -4
- package/src/oauth/m365-copilot-browser.ts +222 -0
- package/src/oauth/m365-copilot-web-session.ts +25 -0
- package/src/oauth/m365-copilot.ts +57 -0
- package/src/oauth/model-discovery-auth.ts +5 -0
- package/src/oauth/plan.ts +44 -0
- package/src/oauth/pool-kernel.ts +22 -8
- package/src/oauth/pool-settings-capability.ts +14 -3
- package/src/oauth/reauth-precheck.ts +27 -0
- package/src/oauth/store-anthropic-instance.ts +3 -1
- package/src/oauth/store.ts +121 -23
- package/src/oauth/types.ts +27 -2
- package/src/protocols/codecs/chat-ir.ts +7 -4
- package/src/protocols/codecs/gemini-interactions.ts +770 -0
- package/src/protocols/codecs/gemini.ts +470 -0
- package/src/protocols/contract.ts +2 -0
- package/src/protocols/encoders/adapter-events.ts +5 -3
- package/src/protocols/encoders/chat.ts +23 -7
- package/src/protocols/settings.ts +3 -0
- package/src/providers/account-quota-disk.ts +26 -8
- package/src/providers/api-key-pause.ts +2 -2
- package/src/providers/api-key-response-ownership.ts +14 -4
- package/src/providers/claude-cli-usage-state.ts +1 -0
- package/src/providers/claude-cli-usage.ts +24 -7
- package/src/providers/default-aliases.ts +11 -5
- package/src/providers/derive.ts +5 -1
- package/src/providers/fastwire.ts +6 -5
- package/src/providers/free-directory.ts +2 -2
- package/src/providers/google-vertex-location.ts +2 -1
- package/src/providers/google-vertex-model-discovery.ts +22 -0
- package/src/providers/key-failover.ts +18 -23
- package/src/providers/m365-copilot-discovery-fetch.ts +17 -0
- package/src/providers/m365-copilot-discovery.ts +68 -0
- package/src/providers/m365-copilot-models.ts +32 -0
- package/src/providers/model-rename-fields.ts +6 -0
- package/src/providers/new-model-policy-runtime.ts +27 -6
- package/src/providers/openai-forward-destination.ts +19 -0
- package/src/providers/openai-tiers-destination.ts +3 -19
- package/src/providers/quota/account-cache.ts +183 -27
- package/src/providers/quota/anthropic-account-quota.ts +21 -17
- package/src/providers/quota/anthropic-cooldown-recovery.ts +57 -27
- package/src/providers/quota/anthropic-decision-windows.ts +7 -3
- package/src/providers/quota/anthropic-usage-windows.ts +34 -4
- package/src/providers/quota/antigravity-account-probe.ts +165 -0
- package/src/providers/quota/antigravity.ts +71 -3
- package/src/providers/quota/vendor-probes-oauth.ts +52 -28
- package/src/providers/quota-decision-publication.ts +1 -1
- package/src/providers/quota-decision-snapshot.ts +4 -1
- package/src/providers/quota-types.ts +2 -0
- package/src/providers/quota.ts +8 -7
- package/src/providers/registry/agy-acp-models.ts +3 -0
- package/src/providers/registry/entries-core.ts +9 -0
- package/src/providers/registry/entries-extended.ts +60 -0
- package/src/providers/registry/model-seeds.ts +51 -0
- package/src/providers/request-pacing.ts +37 -7
- package/src/providers/service-tier.ts +2 -0
- package/src/providers/xai-privacy-mode.ts +52 -0
- package/src/remote/hub-management-relay.ts +74 -0
- package/src/responses/id-limits.ts +2 -0
- package/src/responses/input-media.ts +15 -3
- package/src/responses/parser-tools.ts +74 -11
- package/src/responses/parser.ts +16 -14
- package/src/responses/provider-opaque-metadata.ts +10 -0
- package/src/responses/reasoning-envelope.ts +3 -0
- package/src/responses/schema.ts +2 -3
- package/src/responses/spill-store.ts +5 -3
- package/src/responses/state/connection-scope.ts +232 -0
- package/src/responses/state/entry-types.ts +47 -0
- package/src/responses/state/snapshot-codec.ts +75 -14
- package/src/responses/state/snapshot-select.ts +2 -0
- package/src/responses/state/spill-codec.ts +59 -0
- package/src/responses/state/spill-queue.ts +11 -2
- package/src/responses/state.ts +178 -159
- package/src/router.ts +2 -6
- package/src/routing/compatibility/behavior.ts +6 -2
- package/src/routing/compatibility/subject.ts +17 -12
- package/src/routing/machine-weighted-routing.ts +58 -0
- package/src/server/advisor-admission-scope.ts +15 -7
- package/src/server/auth-cors.ts +27 -0
- package/src/server/chat-completions.ts +37 -17
- package/src/server/chat-native-eligibility.ts +21 -0
- package/src/server/chat-native.ts +15 -6
- package/src/server/claude-messages.ts +54 -6
- package/src/server/credential-recovery-attempt.ts +32 -0
- package/src/server/effort-policy.ts +6 -3
- package/src/server/gemini-inbound.ts +267 -0
- package/src/server/gemini-interactions-inbound.ts +229 -0
- package/src/server/gemini-interactions-store.ts +129 -0
- package/src/server/gemini-native-catalog.ts +64 -0
- package/src/server/gemini-native-log.ts +33 -0
- package/src/server/gemini-native-paths.ts +88 -0
- package/src/server/gemini-native-wire.ts +201 -0
- package/src/server/gemini-native.ts +218 -0
- package/src/server/grok-upstream-envelope-echo.ts +8 -2
- package/src/server/hub-relay-auth.ts +87 -0
- package/src/server/hub-usage-windows.ts +135 -0
- package/src/server/hub-usage.ts +16 -3
- package/src/server/inbound-body-admission.ts +2 -1
- package/src/server/index/anthropic-model-listing.ts +75 -0
- package/src/server/index/gemini-routes.ts +147 -0
- package/src/server/index/link-management.ts +3 -22
- package/src/server/index/link-relay-sessions.ts +71 -13
- package/src/server/index/link-websocket.ts +2 -0
- package/src/server/index/passive-management-read.ts +55 -0
- package/src/server/index/serve-options.ts +93 -107
- package/src/server/index/websocket-handler.ts +15 -2
- package/src/server/index.ts +10 -0
- package/src/server/inference/client-encoder-delivery.ts +2 -1
- package/src/server/inference/context.ts +33 -6
- package/src/server/management/agent-settings-routes.ts +33 -16
- package/src/server/management/claude-code-settings-patch.ts +6 -0
- package/src/server/management/combo-routes.ts +21 -1
- package/src/server/management/combo-suggestion-routes.ts +212 -0
- package/src/server/management/config-routes.ts +12 -4
- package/src/server/management/context.ts +2 -0
- package/src/server/management/gateway-client-routes.ts +62 -0
- package/src/server/management/integration-routes.ts +5 -0
- package/src/server/management/link-routes.ts +5 -1
- package/src/server/management/m365-copilot-provider-probe.ts +23 -0
- package/src/server/management/model-routes.ts +32 -2
- package/src/server/management/model-rows.ts +36 -3
- package/src/server/management/oauth-account-routes.ts +68 -15
- package/src/server/management/protocol-settings-patch.ts +1 -0
- package/src/server/management/provider-omitted-fields.ts +25 -0
- package/src/server/management/provider-overwrite-carry.ts +33 -8
- package/src/server/management/provider-routes.ts +10 -16
- package/src/server/management/request-history-routes.ts +2 -2
- package/src/server/management/route-registry.ts +10 -0
- package/src/server/management/shared.ts +118 -30
- package/src/server/management/sibling-guard.ts +2 -1
- package/src/server/management/system-routes.ts +6 -0
- package/src/server/management-auth.ts +8 -1
- package/src/server/messages-native-scope.ts +19 -0
- package/src/server/messages-native.ts +156 -59
- package/src/server/messages-shared.ts +6 -0
- package/src/server/models-capabilities.ts +24 -0
- package/src/server/native-chat-bridge.ts +259 -0
- package/src/server/ollama-inbound.ts +36 -184
- package/src/server/passive-route-linker.ts +3 -1
- package/src/server/port-reclaim.ts +48 -4
- package/src/server/proxy-liveness.ts +79 -22
- package/src/server/relay.ts +16 -9
- package/src/server/request-log-account-rotation.ts +2 -1
- package/src/server/request-log-attempt-recovery.ts +24 -2
- package/src/server/request-log-attempt-usage.ts +5 -4
- package/src/server/request-log-committed-terminal.ts +87 -0
- package/src/server/request-log-failure-attribution.ts +3 -3
- package/src/server/request-log-failure-detail.ts +34 -0
- package/src/server/request-log-key-failure.ts +27 -0
- package/src/server/request-log-terminal-status.ts +25 -12
- package/src/server/request-log.ts +59 -63
- package/src/server/responses/adapter-continuation.ts +77 -44
- package/src/server/responses/adapter-delivery.ts +47 -22
- package/src/server/responses/adapter-dispatch.ts +150 -149
- package/src/server/responses/advisor-retention.ts +12 -4
- package/src/server/responses/advisor-slot.ts +97 -2
- package/src/server/responses/agent-task-recovery.ts +44 -11
- package/src/server/responses/agy-acp-preflight.ts +41 -0
- package/src/server/responses/anthropic-image-context.ts +44 -0
- package/src/server/responses/antigravity-validation-refusal.ts +25 -1
- package/src/server/responses/buffered-sse-json.ts +18 -1
- package/src/server/responses/codex-ws-correlation.ts +5 -2
- package/src/server/responses/codex-ws-exchange.ts +91 -8
- package/src/server/responses/codex-ws-incremental.ts +136 -0
- package/src/server/responses/codex-ws-pool.ts +22 -8
- package/src/server/responses/codex-ws-request.ts +5 -0
- package/src/server/responses/codex-ws-send-accounting.ts +8 -0
- package/src/server/responses/codex-ws-session.ts +14 -0
- package/src/server/responses/codex-ws-wire.ts +44 -22
- package/src/server/responses/combo-admission-snapshot.ts +93 -0
- package/src/server/responses/combo-required-tool-stream.ts +16 -4
- package/src/server/responses/combo-selection-keepalive.ts +5 -0
- package/src/server/responses/combo-stream-preflight.ts +182 -73
- package/src/server/responses/compact-response-body.ts +27 -0
- package/src/server/responses/compact.ts +174 -121
- package/src/server/responses/compaction-recovery.ts +7 -0
- package/src/server/responses/core-codex-account.ts +88 -62
- package/src/server/responses/core-combo-failure.ts +15 -0
- package/src/server/responses/core-combo-native.ts +12 -1
- package/src/server/responses/core-combo.ts +340 -94
- package/src/server/responses/core-normalize.ts +19 -12
- package/src/server/responses/core-opaque-recovery.ts +15 -4
- package/src/server/responses/core-options.ts +50 -5
- package/src/server/responses/core-pipeline.ts +11 -0
- package/src/server/responses/core.ts +7 -1
- package/src/server/responses/empty-completion-guard.ts +21 -7
- package/src/server/responses/estimated-usage.ts +2 -1
- package/src/server/responses/fetch-helpers.ts +95 -19
- package/src/server/responses/history-slim.ts +204 -0
- package/src/server/responses/hosted-advisor-spend.ts +49 -0
- package/src/server/responses/image-context-recovery.ts +199 -0
- package/src/server/responses/input-admission.ts +36 -11
- package/src/server/responses/jev-model-invoke.ts +23 -16
- package/src/server/responses/non-replayable-error.ts +12 -2
- package/src/server/responses/passthrough-build-error.ts +5 -3
- package/src/server/responses/passthrough-delivery.ts +74 -33
- package/src/server/responses/passthrough-dispatch.ts +170 -197
- package/src/server/responses/policy-fallback.ts +7 -2
- package/src/server/responses/policy-request-scope.ts +36 -2
- package/src/server/responses/replay-owner.ts +20 -0
- package/src/server/responses/request-prepare.ts +97 -16
- package/src/server/responses/request-send-budget.ts +97 -25
- package/src/server/responses/request-sidecar-auth.ts +138 -65
- package/src/server/responses/request-spend-target.ts +13 -1
- package/src/server/responses/request-spend.ts +228 -47
- package/src/server/responses/request-transport.ts +395 -70
- package/src/server/responses/run-turn-execution.ts +40 -9
- package/src/server/responses/sidecar-execution.ts +214 -67
- package/src/server/responses/sidecar-send-budget.ts +9 -9
- package/src/server/responses/terminal-guard.ts +35 -9
- package/src/server/responses/ws-upstream.ts +27 -6
- package/src/server/responses-phase-inference.ts +32 -9
- package/src/server/responses-terminal-repair.ts +14 -35
- package/src/server/system-env.ts +8 -5
- package/src/server/ws-bridge.ts +23 -17
- package/src/service/health-sentinel-linux.ts +16 -7
- package/src/service/systemd.ts +11 -2
- package/src/service/windows-checked-stop-live.ts +60 -55
- package/src/service/windows-checked-stop.ts +29 -11
- package/src/service/windows-guarded-manager.ts +14 -26
- package/src/service/windows-process-evidence.ts +82 -74
- package/src/service/windows-process-native.ts +69 -20
- package/src/service/windows-service-stop.ts +14 -12
- package/src/service/windows-stop-binding.ts +14 -5
- package/src/service/windows-stop-confirm.ts +1 -1
- package/src/service/windows-task-instance-stop.ts +98 -0
- package/src/service/windows-taskxml.ts +30 -7
- package/src/sidecar/anthropic-binding.ts +1 -1
- package/src/stall-timeout.ts +30 -0
- package/src/telemetry/aggregate.ts +6 -3
- package/src/types/account-auto-pause.ts +19 -1
- package/src/types/accounts.ts +21 -0
- package/src/types/anthropic-account-pool.ts +1 -1
- package/src/types/combo-capability-policy.ts +19 -0
- package/src/types/config.ts +22 -2
- package/src/types/provider.ts +42 -8
- package/src/types/request.ts +15 -0
- package/src/types/tools.ts +22 -5
- package/src/types/wire.ts +1 -0
- package/src/types.ts +4 -0
- package/src/update/check-types.ts +2 -0
- package/src/update/job.ts +8 -3
- package/src/update/managed-release.ts +6 -0
- package/src/update/orchestrated-entry.ts +13 -4
- package/src/update/refresh-scheduler.ts +17 -7
- package/src/usage/attempt-delivery.ts +6 -0
- package/src/usage/cache-provenance.ts +71 -0
- package/src/usage/cost.ts +216 -27
- package/src/usage/credit-billing.ts +88 -0
- package/src/usage/jev-stats.ts +13 -9
- package/src/usage/log.ts +5 -33
- package/src/usage/summary.ts +8 -43
- package/src/usage/user-cost-overlays.ts +13 -1
- package/src/vision/index.ts +8 -3
- package/src/vision/plan.ts +28 -14
- package/src/vision/routed-describe.ts +24 -36
- package/src/web-search/header-deadline.ts +14 -3
- package/src/web-search/index.ts +6 -4
- package/src/web-search/loop.ts +240 -78
- package/src/web-search/progress-stream.ts +29 -2
- package/src/web-search/run-turn-loop.ts +5 -1
- package/gui/dist/assets/App-BGP8I0V4.css +0 -1
- package/gui/dist/assets/App-BRExzhwL.js +0 -60
- package/gui/dist/assets/Tray-DHCWAn8V.js +0 -1
- package/gui/dist/assets/brand-mark-C70PuQ3j.js +0 -1
- package/gui/dist/assets/index-DJxM-imn.css +0 -2
- package/gui/dist/assets/index-Dy1jIGty.js +0 -138
- package/gui/dist/classic/assets/App-B4j-Txmb.css +0 -1
- package/gui/dist/classic/assets/App-CaC-E6Vl.js +0 -59
- package/gui/dist/classic/assets/Tray-BG253fiL.js +0 -1
- package/gui/dist/classic/assets/index-CR_AThOp.js +0 -138
- package/gui/dist/classic/assets/quota-summary-B7KQPpEC.js +0 -1
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
AdmissionModelDeniedError,
|
|
23
23
|
assertRouteAllowedByScope,
|
|
24
24
|
resolveAdmissionModelScope,
|
|
25
|
+
routeAllowedByScope,
|
|
25
26
|
} from "./admission-model-scope";
|
|
26
27
|
import { jsonUtf8Bytes } from "../lib/json-byte-size";
|
|
27
28
|
import { redactSecretString } from "../lib/redact";
|
|
@@ -40,12 +41,13 @@ import { AnthropicRequestError, callerCacheRetention, DesktopModelMappingUnavail
|
|
|
40
41
|
import { nativeReasoningTag, type NativeReasoningOwner } from "../responses/reasoning-replay-cache";
|
|
41
42
|
import { isKnownDesktop3pModelId, resolveDesktop3pAlias } from "../claude/desktop-3p";
|
|
42
43
|
import { resolveAlias, claudeCodeNativeAlias, legacyAliasForNative } from "../claude/alias";
|
|
44
|
+
import { decideReserve, isSubscriptionBackground, nativeSubscriptionObservationKey, observeWeeklyHeaders, SUBSCRIPTION_PRIORITY_HEADER } from "../claude/subscription-reserve";
|
|
43
45
|
import { recordDesktopRequest } from "../claude/desktop-health";
|
|
44
46
|
import { stripOneMillionMarker } from "../claude/context-windows";
|
|
45
47
|
import { captureAdmissionPolicy } from "./capture-admission-policy";
|
|
46
48
|
import type { CapturedAdmissionPolicy } from "../types/admission-policy";
|
|
47
49
|
import { captureClaudeInbound } from "../claude/inbound-debug";
|
|
48
|
-
import { declaredAnthropicServerTools, replayedAnthropicServerBlocks, systemCachePrefix } from "../claude/inbound-content-options";
|
|
50
|
+
import { declaredAnthropicServerTools, hostedAdvisorSelection, replayedAnthropicServerBlocks, systemCachePrefix, type HostedAdvisorSelection } from "../claude/inbound-content-options";
|
|
49
51
|
import { linkAdvisorPlanConfig } from "./responses/advisor-plan-slot";
|
|
50
52
|
import { claudeCodeForIngress } from "../claude/intercept/model-bindings";
|
|
51
53
|
import { classifyInterceptClient } from "../claude/intercept/client-class";
|
|
@@ -239,7 +241,7 @@ async function readAnthropicBody(req: Request, budget: TranslatorBudget, maxByte
|
|
|
239
241
|
const PASSTHROUGH_STRIP_HEADERS = new Set([
|
|
240
242
|
"connection", "keep-alive", "transfer-encoding", "upgrade", "te", "trailer",
|
|
241
243
|
"proxy-authenticate", "proxy-authorization", "host", "content-length",
|
|
242
|
-
"accept-encoding", "x-opencodex-api-key", "origin",
|
|
244
|
+
"accept-encoding", "x-opencodex-api-key", "origin", SUBSCRIPTION_PRIORITY_HEADER,
|
|
243
245
|
]);
|
|
244
246
|
|
|
245
247
|
function singleCredentialToken(name: "authorization" | "x-api-key", value: string | null): string | null {
|
|
@@ -293,6 +295,20 @@ function shouldForwardNativeHeader(name: string, value: string, config: OcxConfi
|
|
|
293
295
|
return !!token && !isProxyAdmissionSecret(token, config);
|
|
294
296
|
}
|
|
295
297
|
|
|
298
|
+
function nativeAnthropicBaseUrl(config: OcxConfig): string {
|
|
299
|
+
return (config.claudeCode?.anthropicBaseUrl ?? "https://api.anthropic.com").replace(/\/$/, "");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function callerSubscriptionObservationKey(config: OcxConfig, headers: Headers): string | undefined {
|
|
303
|
+
if (config.subscriptionReserve?.enabled !== true) return undefined;
|
|
304
|
+
const authorization = headers.get("authorization");
|
|
305
|
+
const apiKey = headers.get("x-api-key");
|
|
306
|
+
if (!authorization || !shouldForwardNativeHeader("authorization", authorization, config)
|
|
307
|
+
|| (apiKey && shouldForwardNativeHeader("x-api-key", apiKey, config))) return undefined;
|
|
308
|
+
const bearer = singleCredentialToken("authorization", authorization);
|
|
309
|
+
return bearer ? nativeSubscriptionObservationKey(nativeAnthropicBaseUrl(config), bearer) : undefined;
|
|
310
|
+
}
|
|
311
|
+
|
|
296
312
|
/** Format a 32-hex cache key as a uuid-shaped session id (version/variant nibbles forced). */
|
|
297
313
|
function uuidFromHex(hex32: string): string {
|
|
298
314
|
const h = (hex32 + "0".repeat(32)).slice(0, 32);
|
|
@@ -358,7 +374,7 @@ async function anthropicNativePassthrough(
|
|
|
358
374
|
overflow: messagesRelayedOverflowPresentation("", legacy) }, legacy), closeReason === "body_stall" ? "body_stall" : closeReason === "body_overflow" ? "body_overflow" : undefined);
|
|
359
375
|
};
|
|
360
376
|
|
|
361
|
-
const base = (config
|
|
377
|
+
const base = nativeAnthropicBaseUrl(config);
|
|
362
378
|
const search = new URL(req.url).search;
|
|
363
379
|
// Native passthrough bypasses the anthropic adapter, so the generous image pipeline
|
|
364
380
|
// (devlog/260714_image_normalization_pipeline/040) must run here: tier-normalize then
|
|
@@ -376,6 +392,7 @@ async function anthropicNativePassthrough(
|
|
|
376
392
|
});
|
|
377
393
|
headers.set("content-type", "application/json");
|
|
378
394
|
|
|
395
|
+
const reserveKey = callerSubscriptionObservationKey(config, headers);
|
|
379
396
|
const result = await fetchWithHeaderDeadline(
|
|
380
397
|
`${base}${pathname}${search}`,
|
|
381
398
|
{ method: "POST", headers, body: JSON.stringify(body) },
|
|
@@ -394,6 +411,7 @@ async function anthropicNativePassthrough(
|
|
|
394
411
|
const upstream = result.upstream;
|
|
395
412
|
|
|
396
413
|
const contentType = upstream.headers.get("content-type") ?? "application/json";
|
|
414
|
+
if (reserveKey) observeWeeklyHeaders(config, reserveKey, upstream.headers);
|
|
397
415
|
const rateLimitHeaders = {
|
|
398
416
|
...anthropicRateLimitHeaders(upstream.headers),
|
|
399
417
|
...(pathname === "/v1/messages" ? upstreamMessagesRequestIdHeaders(upstream.headers) : {}),
|
|
@@ -655,6 +673,7 @@ async function handleClaudeMessagesWithBudget(
|
|
|
655
673
|
let nativeComboSource = false;
|
|
656
674
|
|
|
657
675
|
let anthropicBody: unknown;
|
|
676
|
+
let anthropicHostedAdvisorSelection: HostedAdvisorSelection | undefined;
|
|
658
677
|
let internalBody: Rec;
|
|
659
678
|
let cacheKeySource: ClaudeCacheKeySource = null;
|
|
660
679
|
let nativeReasoningReplay: ReadonlyMap<string, string> | undefined;
|
|
@@ -715,6 +734,32 @@ async function handleClaudeMessagesWithBudget(
|
|
|
715
734
|
}
|
|
716
735
|
if (fastRow) anthropicBody.model = fastRow.baseId;
|
|
717
736
|
}
|
|
737
|
+
// Only caller-forward subscription requests may act on caller-forward observations.
|
|
738
|
+
// A selected target deliberately bypasses passthrough, even if its provider starts with "anthropic".
|
|
739
|
+
let reserveDowngraded = false;
|
|
740
|
+
if (config.subscriptionReserve?.enabled === true && !effortRow && !fastRow && isRec(anthropicBody)
|
|
741
|
+
&& typeof anthropicBody.model === "string" && !anthropicBody.model.includes("/")
|
|
742
|
+
&& !carriesMessageThread(anthropicBody)
|
|
743
|
+
&& isSubscriptionBackground(req.headers) && wantsNativePassthrough(req, config, requestPolicy, anthropicBody.model, cc)) {
|
|
744
|
+
const key = callerSubscriptionObservationKey(config, req.headers);
|
|
745
|
+
const scope = resolveAdmissionModelScope(config, logIds?.admission);
|
|
746
|
+
const reserve = key && decideReserve(config, key, (target, route) => {
|
|
747
|
+
if (resolveInboundModel(target, cc) !== target) return false;
|
|
748
|
+
if (!scope) return true;
|
|
749
|
+
route.staticPolicy = captureRouteStaticPolicy(
|
|
750
|
+
route.providerName, route.modelId, route.provider, route.staticPolicy.effectiveAlias, "anthropic",
|
|
751
|
+
);
|
|
752
|
+
// Reserve candidates have no Fast-row service-tier override.
|
|
753
|
+
const modelId = previewXaiOauthWireModel({ options: {} }, route, config, "anthropic");
|
|
754
|
+
return routeAllowedByScope(scope, { providerName: route.providerName, modelId });
|
|
755
|
+
});
|
|
756
|
+
if (reserve) {
|
|
757
|
+
const requested = redactSecretString(clientFacingModelText(clientModelLabel));
|
|
758
|
+
console.warn(`[route] requested=${requested} served=${redactSecretString(reserve.target)} fallback=yes reason="${reserve.reason}"`);
|
|
759
|
+
anthropicBody.model = reserve.target;
|
|
760
|
+
reserveDowngraded = true;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
718
763
|
// Debug capture (opt-in allowlist scalars) BEFORE the passthrough branch so
|
|
719
764
|
// native, routed, and disabled-alias paths are all observable (devlog 130 B1).
|
|
720
765
|
captureClaudeInbound(
|
|
@@ -761,7 +806,7 @@ async function handleClaudeMessagesWithBudget(
|
|
|
761
806
|
messagesFeatures = sourceEnvelope
|
|
762
807
|
? () => sourceEnvelope.features()
|
|
763
808
|
: () => (scannedFeatures ??= featuresFromMessagesBody(messagesBody));
|
|
764
|
-
if (!effortRow && !fastRow && isRec(anthropicBody) && wantsNativePassthrough(req, config, requestPolicy, anthropicBody.model, cc)) {
|
|
809
|
+
if (!reserveDowngraded && !effortRow && !fastRow && isRec(anthropicBody) && wantsNativePassthrough(req, config, requestPolicy, anthropicBody.model, cc)) {
|
|
765
810
|
markProtocolEntry(logCtx, { inbound: "messages", lane: "native", features: messagesFeatures });
|
|
766
811
|
recordProtocolShadowPlan(logCtx, config, { inbound: "messages", model: requestedModel });
|
|
767
812
|
let projectedBody: Rec;
|
|
@@ -827,6 +872,7 @@ async function handleClaudeMessagesWithBudget(
|
|
|
827
872
|
};
|
|
828
873
|
delete anthropicBody.thinking;
|
|
829
874
|
}
|
|
875
|
+
anthropicHostedAdvisorSelection = hostedAdvisorSelection(anthropicBody);
|
|
830
876
|
// On the direct lane the core receives only the request settings; the conversation is
|
|
831
877
|
// already decoded into the IR. Without a plan the translation below runs as before.
|
|
832
878
|
directPlan = planMessagesAntigravityDirect(anthropicBody, cc, config, translatorBudget);
|
|
@@ -1312,6 +1358,7 @@ async function handleClaudeMessagesWithBudget(
|
|
|
1312
1358
|
nativeReasoningMint,
|
|
1313
1359
|
// Out of body like the replay above: the core hands these to an Anthropic destination only.
|
|
1314
1360
|
anthropicServerTools: declaredAnthropicServerTools(anthropicBody),
|
|
1361
|
+
anthropicHostedAdvisorSelection,
|
|
1315
1362
|
anthropicServerReplay: replayedAnthropicServerBlocks(anthropicBody),
|
|
1316
1363
|
anthropicSystemCachePrefix: isRec(anthropicBody) ? systemCachePrefix(anthropicBody.system) : undefined,
|
|
1317
1364
|
// Preserve the original catalog through late fallback; only the physical adapter projects it.
|
|
@@ -1400,7 +1447,8 @@ async function handleClaudeMessagesWithBudget(
|
|
|
1400
1447
|
&& message === CODEX_MAIN_PROFILE_MAINTENANCE_MESSAGE;
|
|
1401
1448
|
// The undeclared-tool guard's refusal is deterministic: the same request produces the
|
|
1402
1449
|
// same verdict, so it must not arrive as a retryable overload like a transient 5xx.
|
|
1403
|
-
const
|
|
1450
|
+
const localComboUnavailable = response.status === 503 && originalCode === "combo_unavailable" && isProxyError(response);
|
|
1451
|
+
const transient = !localComboUnavailable && !replayRefusal && !nativeMainFence && !contextError && !catalogRefusal
|
|
1404
1452
|
&& isTransientUpstreamStatus(response.status);
|
|
1405
1453
|
const outStatus = replayRefusal
|
|
1406
1454
|
? REPLAY_REFUSED_STATUS
|
|
@@ -1410,7 +1458,7 @@ async function handleClaudeMessagesWithBudget(
|
|
|
1410
1458
|
if (clientRetryAfter) outHeaders.set("Retry-After", clientRetryAfter);
|
|
1411
1459
|
else if (transient) outHeaders.set("Retry-After", "2");
|
|
1412
1460
|
if (replayRefusal) applyReplayRefusalClientHeaders(outHeaders);
|
|
1413
|
-
const decidedCode = replayRefusal ? UPSTREAM_RESET_REPLAY_REFUSED_CODE : contextError ? "context_length_exceeded" : catalogRefusal ? UNDECLARED_TOOL_CALL_ERROR_CODE : undefined;
|
|
1461
|
+
const decidedCode = replayRefusal ? UPSTREAM_RESET_REPLAY_REFUSED_CODE : contextError ? "context_length_exceeded" : catalogRefusal ? UNDECLARED_TOOL_CALL_ERROR_CODE : localComboUnavailable ? originalCode : undefined;
|
|
1414
1462
|
const legacy = anthropicErrorBody(outStatus, message, undefined, decidedCode);
|
|
1415
1463
|
const legacyBody = JSON.stringify(legacy);
|
|
1416
1464
|
const out = new Response(JSON.stringify(ownedAnthropicErrorPayload({
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { beginRequestAttempt, finishRequestAttempt, noteProviderAttemptSend, type RequestLogContext } from "./request-log";
|
|
2
|
+
import { sealedCredentialRefusals } from "./request-log-attempt-recovery";
|
|
3
|
+
import { attributeSealedAttempt } from "./request-log-failure-attribution";
|
|
4
|
+
import type { AttemptRecoveryKind } from "../usage/log";
|
|
5
|
+
|
|
6
|
+
/** Freeze the physical refusal while a replacement is only a plan. */
|
|
7
|
+
export function sealCredentialRefusal(logCtx: RequestLogContext, status: number, recovery?: AttemptRecoveryKind): void {
|
|
8
|
+
const attempt = logCtx.activeAttempt;
|
|
9
|
+
if (!attempt?.sendCount || sealedCredentialRefusals.has(attempt)) return;
|
|
10
|
+
// An estimate cannot prove that a refused RPC consumed any tokens.
|
|
11
|
+
delete attempt.inputTokenEstimate;
|
|
12
|
+
finishRequestAttempt(attempt, status, Date.now() - (logCtx.activeAttemptStartedAt ?? Date.now()), attempt.usage ?? logCtx.usage);
|
|
13
|
+
attributeSealedAttempt(attempt, recovery);
|
|
14
|
+
if (attempt.tierOutcome) attempt.tierOutcome = { ...attempt.tierOutcome };
|
|
15
|
+
sealedCredentialRefusals.add(attempt);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type AttemptSendProvider = Parameters<typeof noteProviderAttemptSend>[2];
|
|
19
|
+
type AttemptSendRecovery = Parameters<typeof noteProviderAttemptSend>[4];
|
|
20
|
+
|
|
21
|
+
/** Open a native compact attempt at its first physical send and count each send against it. */
|
|
22
|
+
export function noteCompactAttemptSend(
|
|
23
|
+
logCtx: RequestLogContext, route: { providerName: string; modelId: string }, provider: AttemptSendProvider, recovery?: AttemptSendRecovery,
|
|
24
|
+
): void {
|
|
25
|
+
const { providerName, modelId } = route;
|
|
26
|
+
if (!logCtx.activeAttempt) {
|
|
27
|
+
logCtx.activeAttempt = beginRequestAttempt((logCtx.attempts?.length ?? 0) + 1, logCtx.provider, modelId, provider.adapter);
|
|
28
|
+
logCtx.activeAttemptStartedAt = Date.now();
|
|
29
|
+
(logCtx.attempts ??= []).push(logCtx.activeAttempt);
|
|
30
|
+
}
|
|
31
|
+
noteProviderAttemptSend(logCtx, providerName, provider, logCtx.usageLogInputTokens, recovery, { model: modelId, adapter: provider.adapter });
|
|
32
|
+
}
|
|
@@ -31,9 +31,12 @@ import { catalogModelEfforts } from "../codex/catalog/effort";
|
|
|
31
31
|
* not spawned children, and must never trip subagentEffortCap.
|
|
32
32
|
*/
|
|
33
33
|
export function isThreadSpawnRequest(headers: Headers): boolean {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
return headers.get("x-openai-subagent") === "collab_spawn"
|
|
35
|
+
|| isThreadSpawnTurnMetadata(headers.get("x-codex-turn-metadata"));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function isThreadSpawnTurnMetadata(turnMeta: unknown): boolean {
|
|
39
|
+
if (typeof turnMeta !== "string" || !turnMeta) return false;
|
|
37
40
|
try {
|
|
38
41
|
const parsed = JSON.parse(turnMeta) as { subagent_kind?: unknown };
|
|
39
42
|
return parsed.subagent_kind === "thread_spawn";
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gemini-compatible inbound API: GET /v1beta/models[/{model}] and POST
|
|
3
|
+
* /v1beta|v1/models/{model}:generateContent|streamGenerateContent (countTokens and the embed
|
|
4
|
+
* methods answer 501).
|
|
5
|
+
*
|
|
6
|
+
* Same shape as the Ollama inbound (./ollama-inbound): the model list describes configured
|
|
7
|
+
* provider routes, generation is translated into an internal Chat Completions request handled by
|
|
8
|
+
* the ordinary Chat path, and this handler owns the final request-log row. Errors use the Gemini
|
|
9
|
+
* `{ error: { code, message, status } }` body with a fixed message chosen by HTTP status.
|
|
10
|
+
*/
|
|
11
|
+
import { GeminiCodecError, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, geminiStreamTerminal, geminiToChat } from "../protocols/codecs/gemini";
|
|
12
|
+
import { createTranslatorBudget, isTranslatorBudgetExceededError } from "../lib/translator-budget";
|
|
13
|
+
import type { OcxConfig, OcxParsedRequest } from "../types";
|
|
14
|
+
import type { RouteResult } from "../router";
|
|
15
|
+
import { configuredContextWindow, configuredMaxInputTokens } from "../codex/catalog/model-hints";
|
|
16
|
+
import { modelRecordValue } from "../reasoning-effort";
|
|
17
|
+
import { getModelMetadata, resolveMetadataProvider } from "../generated/model-metadata";
|
|
18
|
+
import { chatConversationToIr } from "../protocols/codecs/chat-ir";
|
|
19
|
+
import { ChatCompletionsRequestError } from "../chat/inbound";
|
|
20
|
+
import { estimateInputTokens } from "./responses/input-admission";
|
|
21
|
+
import type { DataPlaneAdmission } from "./auth-cors";
|
|
22
|
+
import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope";
|
|
23
|
+
import type { GeminiMethod } from "./gemini-native-paths";
|
|
24
|
+
import { geminiNativeCatalogAliases, geminiNativeCatalogLookup } from "./gemini-native-catalog";
|
|
25
|
+
import {
|
|
26
|
+
applyLocalRefusalCode,
|
|
27
|
+
commitCancelled,
|
|
28
|
+
drainedInnerErrorMessage,
|
|
29
|
+
handleNativeChat,
|
|
30
|
+
nativeRefusalParts,
|
|
31
|
+
nativeRetryAfter,
|
|
32
|
+
streamNativeFromChat,
|
|
33
|
+
type NativeLogIds,
|
|
34
|
+
} from "./native-chat-bridge";
|
|
35
|
+
import { createNativeFinalLog, type NativeFinalLog } from "./native-final-log";
|
|
36
|
+
import { findOllamaRoute, listOllamaRoutes, preflightOllamaRoute } from "./ollama-route-policy";
|
|
37
|
+
import { DecompressedBodyTooLargeError, readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress";
|
|
38
|
+
import { addFinalRequestLog, type RequestLogContext } from "./request-log";
|
|
39
|
+
|
|
40
|
+
const STATUS_NAMES: Readonly<Record<number, string>> = {
|
|
41
|
+
400: "INVALID_ARGUMENT", 401: "UNAUTHENTICATED", 403: "PERMISSION_DENIED", 404: "NOT_FOUND", 413: "INVALID_ARGUMENT",
|
|
42
|
+
429: "RESOURCE_EXHAUSTED", 499: "CANCELLED", 501: "UNIMPLEMENTED", 503: "UNAVAILABLE", 504: "DEADLINE_EXCEEDED",
|
|
43
|
+
// google.rpc.Code by HTTP mapping; 402 has no canonical code, so the closest precondition.
|
|
44
|
+
402: "FAILED_PRECONDITION", 405: "UNIMPLEMENTED", 408: "DEADLINE_EXCEEDED", 409: "ABORTED", 422: "INVALID_ARGUMENT",
|
|
45
|
+
500: "INTERNAL", 502: "UNAVAILABLE",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export function geminiErrorBody(status: number, message: string): { error: { code: number; message: string; status: string } } {
|
|
49
|
+
return { error: { code: status, message, status: STATUS_NAMES[status] ?? "INTERNAL" } };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Every Gemini error response is built from scratch: content type, our own error text, and
|
|
54
|
+
* optionally a reformatted Retry-After. Callers add CORS and the request-log id.
|
|
55
|
+
*/
|
|
56
|
+
export function geminiError(status: number, message: string, retryAfter?: string | null): Response {
|
|
57
|
+
const headers = new Headers({ "content-type": "application/json" });
|
|
58
|
+
const advice = nativeRetryAfter(retryAfter);
|
|
59
|
+
if (advice !== undefined) headers.set("Retry-After", advice);
|
|
60
|
+
return new Response(JSON.stringify(geminiErrorBody(status, message)), { status, headers });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Reshape an existing proxy refusal (capacity, workflow, drain) keeping its status and retry advice. */
|
|
64
|
+
export function toGeminiRefusal(response: Response): Response {
|
|
65
|
+
const parts = nativeRefusalParts(response);
|
|
66
|
+
return applyLocalRefusalCode(geminiError(parts.status, parts.message, parts.retryAfter), parts.localRefusalCode);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function eligibleRoutes(config: OcxConfig, req: Request, admission: DataPlaneAdmission) {
|
|
70
|
+
const scope = resolveAdmissionModelScope(config, admission);
|
|
71
|
+
return listOllamaRoutes(config, req)
|
|
72
|
+
.filter(row => routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId }));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Token limits from configuration first, then generated model metadata; omitted when unknown. */
|
|
76
|
+
function tokenLimits(config: OcxConfig, route: RouteResult): { inputTokenLimit?: number; outputTokenLimit?: number } {
|
|
77
|
+
const metadataProvider = resolveMetadataProvider(route.providerName) ?? route.providerName;
|
|
78
|
+
const metadata = getModelMetadata(metadataProvider, route.modelId);
|
|
79
|
+
const custom = config.customModels?.find(row => row.provider === route.providerName && row.modelId === route.modelId);
|
|
80
|
+
const customContext = custom?.contextWindow;
|
|
81
|
+
const input = configuredMaxInputTokens(route.provider, route.modelId)
|
|
82
|
+
?? configuredContextWindow(route.provider, route.modelId)
|
|
83
|
+
?? (typeof customContext === "number" && customContext > 0 ? customContext : metadata?.contextWindow);
|
|
84
|
+
const output = modelRecordValue(route.provider.modelMaxOutputTokens, route.modelId) ?? route.provider.defaultMaxOutputTokens ?? metadata?.maxTokens;
|
|
85
|
+
return {
|
|
86
|
+
...(typeof input === "number" && input > 0 ? { inputTokenLimit: input } : {}),
|
|
87
|
+
...(typeof output === "number" && output > 0 ? { outputTokenLimit: output } : {}),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const modelResource = (config: OcxConfig, row: { selector: string; route: RouteResult }) => ({
|
|
92
|
+
name: `models/${row.selector}`,
|
|
93
|
+
displayName: row.selector,
|
|
94
|
+
...tokenLimits(config, row.route),
|
|
95
|
+
supportedGenerationMethods: ["generateContent", "streamGenerateContent", "countTokens"],
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export function handleGeminiModels(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Response {
|
|
99
|
+
const rows = eligibleRoutes(config, req, admission);
|
|
100
|
+
const aliases = geminiNativeCatalogAliases(config, req, rows, resolveAdmissionModelScope(config, admission));
|
|
101
|
+
return Response.json({ models: [...rows, ...aliases].map(row => modelResource(config, row)) });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function findGeminiCatalogRow(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string) {
|
|
105
|
+
const row = findOllamaRoute(config, model, req);
|
|
106
|
+
const scope = resolveAdmissionModelScope(config, admission);
|
|
107
|
+
if (row && routeAllowedByScope(scope, row.route)) return row;
|
|
108
|
+
return geminiNativeCatalogLookup(config, req, model, () => eligibleRoutes(config, req, admission), scope);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function handleGeminiModel(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Response {
|
|
112
|
+
const row = findGeminiCatalogRow(config, req, admission, model);
|
|
113
|
+
return row ? Response.json(modelResource(config, row)) : geminiError(404, "model not found");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* `:countTokens`: a local estimate over the same Chat projection generation uses, for the routes the
|
|
118
|
+
* key may reach. No upstream call. Body: `{contents, systemInstruction, tools}` or `{generateContentRequest}`.
|
|
119
|
+
*/
|
|
120
|
+
export async function handleGeminiCountTokens(config: OcxConfig, req: Request, admission: DataPlaneAdmission, model: string): Promise<Response> {
|
|
121
|
+
const row = findGeminiCatalogRow(config, req, admission, model);
|
|
122
|
+
if (!row) return geminiError(404, "model not found");
|
|
123
|
+
const limit = resolveInboundBodyLimitBytes(config.maxInboundBodyBytes);
|
|
124
|
+
const budget = createTranslatorBudget();
|
|
125
|
+
try {
|
|
126
|
+
const body = await readJsonRequestBody(req, budget, limit);
|
|
127
|
+
const source = body && typeof body === "object" && !Array.isArray(body) && (body as Record<string, unknown>).generateContentRequest !== undefined
|
|
128
|
+
? (body as Record<string, unknown>).generateContentRequest
|
|
129
|
+
: body;
|
|
130
|
+
const chat = geminiToChat(row.route.modelId, source, false);
|
|
131
|
+
const conversation = chatConversationToIr(chat, row.route.modelId);
|
|
132
|
+
const totalTokens = estimateInputTokens({ ...conversation, modelId: row.route.modelId } as unknown as OcxParsedRequest, row.route.modelId, row.route.provider);
|
|
133
|
+
return Response.json({ totalTokens });
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (req.signal.aborted) return geminiError(499, "request cancelled");
|
|
136
|
+
if (error instanceof DecompressedBodyTooLargeError) return geminiError(413, "request body too large");
|
|
137
|
+
if (isTranslatorBudgetExceededError(error)) return geminiError(502, "request translation buffer exceeded the safe limit");
|
|
138
|
+
if (error instanceof GeminiCodecError || error instanceof ChatCompletionsRequestError) return geminiError(400, error.message);
|
|
139
|
+
return geminiError(400, "invalid JSON body");
|
|
140
|
+
} finally {
|
|
141
|
+
budget.dispose();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function failBeforeInner(ids: NativeLogIds, logCtx: RequestLogContext, status: number, message: string): Response {
|
|
146
|
+
addFinalRequestLog(ids.requestId, ids.start, logCtx, status, { closeReason: "non_stream" });
|
|
147
|
+
return geminiError(status, message);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function cancelledNonStream(finalLog: NativeFinalLog): Response {
|
|
151
|
+
commitCancelled(finalLog);
|
|
152
|
+
return geminiError(499, "request cancelled");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** generateContent and streamGenerateContent. `req` is the admitted, session-promoted request. */
|
|
156
|
+
export async function handleGeminiGeneration(
|
|
157
|
+
method: Extract<GeminiMethod, "generateContent" | "streamGenerateContent">,
|
|
158
|
+
model: string,
|
|
159
|
+
sse: boolean,
|
|
160
|
+
req: Request,
|
|
161
|
+
config: OcxConfig,
|
|
162
|
+
logCtx: RequestLogContext,
|
|
163
|
+
ids: NativeLogIds,
|
|
164
|
+
): Promise<Response> {
|
|
165
|
+
const limit = resolveInboundBodyLimitBytes(config.maxInboundBodyBytes);
|
|
166
|
+
const stream = method === "streamGenerateContent";
|
|
167
|
+
const budget = createTranslatorBudget();
|
|
168
|
+
let originalBody: unknown;
|
|
169
|
+
let chat: Record<string, unknown>;
|
|
170
|
+
try {
|
|
171
|
+
originalBody = await readJsonRequestBody(req, budget, limit);
|
|
172
|
+
chat = geminiToChat(model, originalBody, stream);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (req.signal.aborted) return failBeforeInner(ids, logCtx, 499, "request cancelled");
|
|
175
|
+
if (error instanceof DecompressedBodyTooLargeError) return failBeforeInner(ids, logCtx, 413, "request body too large");
|
|
176
|
+
if (isTranslatorBudgetExceededError(error)) return failBeforeInner(ids, logCtx, 502, "request translation buffer exceeded the safe limit");
|
|
177
|
+
return failBeforeInner(ids, logCtx, 400, error instanceof GeminiCodecError ? error.message : "invalid JSON body");
|
|
178
|
+
} finally {
|
|
179
|
+
budget.dispose();
|
|
180
|
+
}
|
|
181
|
+
logCtx.requestedModel = model;
|
|
182
|
+
const preflight = preflightOllamaRoute(config, model, req);
|
|
183
|
+
if (!preflight.ok) {
|
|
184
|
+
logCtx.errorCode = preflight.error.code;
|
|
185
|
+
return failBeforeInner(ids, logCtx, preflight.error.status, preflight.error.message);
|
|
186
|
+
}
|
|
187
|
+
const chatJson = JSON.stringify(chat);
|
|
188
|
+
if (Buffer.byteLength(chatJson) > limit) return failBeforeInner(ids, logCtx, 413, "request body too large");
|
|
189
|
+
const finalLog = createNativeFinalLog(ids.requestId, ids.start, logCtx);
|
|
190
|
+
let inner: Response;
|
|
191
|
+
try {
|
|
192
|
+
inner = await handleNativeChat(req, originalBody, chatJson, config, logCtx, ids);
|
|
193
|
+
} catch {
|
|
194
|
+
await finalLog.waitForInner();
|
|
195
|
+
if (req.signal.aborted) return cancelledNonStream(finalLog);
|
|
196
|
+
finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" });
|
|
197
|
+
return geminiError(502, "request failed");
|
|
198
|
+
}
|
|
199
|
+
if (!inner.ok || !inner.body) {
|
|
200
|
+
const message = await drainedInnerErrorMessage(inner);
|
|
201
|
+
await finalLog.waitForInner();
|
|
202
|
+
if (req.signal.aborted) return cancelledNonStream(finalLog);
|
|
203
|
+
finalLog.commit({ status: inner.ok ? 502 : inner.status, terminalStatus: "failed", closeReason: "non_stream" });
|
|
204
|
+
return geminiError(inner.ok ? 502 : inner.status, message, inner.headers.get("retry-after"));
|
|
205
|
+
}
|
|
206
|
+
return stream
|
|
207
|
+
? streamGemini(model, sse, inner.body, finalLog, req.signal)
|
|
208
|
+
: bufferedGemini(model, inner, finalLog, req.signal);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function bufferedGemini(model: string, inner: Response, finalLog: NativeFinalLog, signal: AbortSignal): Promise<Response> {
|
|
212
|
+
let native: Record<string, unknown>;
|
|
213
|
+
try {
|
|
214
|
+
native = chatToGeminiResponse(model, JSON.parse(await inner.text()));
|
|
215
|
+
} catch {
|
|
216
|
+
await finalLog.waitForInner();
|
|
217
|
+
if (signal.aborted) return cancelledNonStream(finalLog);
|
|
218
|
+
finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" });
|
|
219
|
+
return geminiError(502, "invalid upstream response");
|
|
220
|
+
}
|
|
221
|
+
const settled = await finalLog.waitForInner();
|
|
222
|
+
if (signal.aborted) return cancelledNonStream(finalLog);
|
|
223
|
+
if (!settled) {
|
|
224
|
+
finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" });
|
|
225
|
+
return geminiError(502, "request did not complete");
|
|
226
|
+
}
|
|
227
|
+
finalLog.commit({ status: 200, terminalStatus: "completed", closeReason: "non_stream" });
|
|
228
|
+
return Response.json(native);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const encoder = new TextEncoder();
|
|
232
|
+
|
|
233
|
+
/** How records become bytes: SSE data frames, or the elements of one JSON array. */
|
|
234
|
+
interface GeminiFraming {
|
|
235
|
+
contentType: string;
|
|
236
|
+
frames(records: unknown[]): Uint8Array[];
|
|
237
|
+
end(records: unknown[]): Uint8Array[];
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const sseFraming = (): GeminiFraming => {
|
|
241
|
+
const frames = (records: unknown[]) => records.map(record => encoder.encode(`data: ${JSON.stringify(record)}\r\n\r\n`));
|
|
242
|
+
return { contentType: "text/event-stream", frames, end: frames };
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const arrayFraming = (): GeminiFraming => {
|
|
246
|
+
let opened = false;
|
|
247
|
+
const frames = (records: unknown[]) => records.map(record => {
|
|
248
|
+
const prefix = opened ? ",\n" : "[\n";
|
|
249
|
+
opened = true;
|
|
250
|
+
return encoder.encode(prefix + JSON.stringify(record));
|
|
251
|
+
});
|
|
252
|
+
return { contentType: "application/json", frames, end: records => [...frames(records), encoder.encode("\n]")] };
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
function streamGemini(model: string, sse: boolean, body: ReadableStream<Uint8Array>, finalLog: NativeFinalLog, signal: AbortSignal): Response {
|
|
256
|
+
const state = createGeminiStreamState(model);
|
|
257
|
+
const framing = sse ? sseFraming() : arrayFraming();
|
|
258
|
+
return streamNativeFromChat({
|
|
259
|
+
contentType: framing.contentType,
|
|
260
|
+
chunk: parsed => framing.frames(consumeGeminiChatChunk(state, parsed)),
|
|
261
|
+
terminal() {
|
|
262
|
+
const record = geminiStreamTerminal(state);
|
|
263
|
+
return record ? { ok: true, frames: () => framing.end([record]) } : { ok: false, error: "request did not complete" };
|
|
264
|
+
},
|
|
265
|
+
failure: message => framing.end([geminiErrorBody(502, message)]),
|
|
266
|
+
}, body, finalLog, signal);
|
|
267
|
+
}
|