@bitkyc08/opencodex 2.97.0 → 2.98.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/bin/ocx.mjs +1 -1
- package/gui/dist/assets/App-6TFtZsUF.css +1 -0
- package/gui/dist/assets/App-FQ0OtiMJ.js +59 -0
- package/gui/dist/assets/Tray-D2d5wqLq.js +1 -0
- package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
- package/gui/dist/assets/brand-mark-A03mw_9y.js +1 -0
- package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/gui/dist/assets/index-5REODpG3.css +2 -0
- package/gui/dist/assets/index-BjTIN4to.js +94 -0
- package/gui/dist/assets/segment-thumb-features-Bf6vpwf8.js +1 -0
- package/gui/dist/classic/assets/App-C9Eg3nUo.js +58 -0
- package/gui/dist/{assets/Tray-CEw0y0jR.js → classic/assets/Tray-B8P8cokE.js} +1 -1
- package/gui/dist/classic/assets/index-DFAFnven.js +94 -0
- package/gui/dist/classic/assets/quota-summary-C-4HP4_5.js +1 -0
- package/gui/dist/classic/index.html +47 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/favicon.svg +14 -0
- package/gui/dist/index.html +15 -2
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +17 -8
- package/src/adapters/google.ts +7 -7
- package/src/adapters/kiro/adapter.ts +18 -3
- package/src/adapters/kiro/conversation.ts +8 -8
- package/src/adapters/kiro/payload.ts +45 -12
- package/src/adapters/kiro/stream.ts +169 -12
- package/src/adapters/kiro/structured-output-json.ts +191 -0
- package/src/adapters/kiro/structured-output-schema.ts +542 -0
- package/src/adapters/kiro/structured-output.ts +367 -0
- package/src/adapters/kiro-constants.ts +9 -0
- package/src/adapters/kiro-tools.ts +14 -9
- package/src/adapters/kiro-wire.ts +9 -5
- package/src/adapters/openai-chat/messages.ts +58 -5
- package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
- package/src/adapters/openai-chat/passthrough.ts +5 -3
- package/src/adapters/openai-chat/tool-schema.ts +83 -13
- package/src/adapters/openai-responses/opengateway-input.ts +18 -6
- package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
- package/src/adapters/qoder/live-models.ts +115 -1
- package/src/claude/failure-verdict.ts +21 -0
- package/src/claude/inbound-content-options.ts +15 -2
- package/src/claude/inbound-model-options.ts +2 -1
- package/src/claude/inbound-records.ts +2 -0
- package/src/claude/inbound.ts +17 -11
- package/src/claude/outbound.ts +52 -23
- package/src/cli/capabilities-access-remote.ts +13 -0
- package/src/cli/capabilities-base.ts +1 -0
- package/src/cli/capabilities-provider-models.ts +3 -3
- package/src/cli/codex-shim-autorestore.ts +7 -0
- package/src/cli/config-command.ts +11 -2
- package/src/cli/connect.ts +17 -2
- package/src/cli/dispatch.ts +3 -1
- package/src/cli/doctor.ts +95 -7
- package/src/cli/index.ts +12 -7
- package/src/cli/link-apply-restart.ts +9 -2
- package/src/cli/models.ts +124 -38
- package/src/cli/registry.ts +1 -1
- package/src/cli/restart-failure.ts +17 -0
- package/src/cli/stop-approval.ts +2 -2
- package/src/cli/sync-command.ts +1 -1
- package/src/cli/sync-fanout.ts +15 -4
- package/src/cli/system-restart-client.ts +5 -0
- package/src/cli/uninstall-client-state.ts +12 -1
- package/src/cli/update-restart-child.ts +13 -3
- package/src/cli/update-restart-home.ts +6 -3
- package/src/cli/update-restart.ts +36 -19
- package/src/client/connect.ts +4 -1
- package/src/client/hub-client.ts +5 -0
- package/src/client/link-management-relay.ts +39 -2
- package/src/client/link-readiness.ts +3 -1
- package/src/client/machine-api.ts +2 -1
- package/src/client/machine-listener.ts +7 -0
- package/src/client/orphan-token-recovery.ts +322 -0
- package/src/codex/catalog/provider-models.ts +12 -4
- package/src/codex/native-profile-api.ts +27 -1
- package/src/codex/shim-diagnostics.ts +7 -0
- package/src/codex/shim-legacy-record.ts +290 -0
- package/src/codex/shim-windows-refresh.ts +9 -2
- package/src/codex/shim-wrapper-write.ts +7 -0
- package/src/codex/shim.ts +80 -21
- package/src/config/diagnostics.ts +9 -9
- package/src/config/load-degrade.ts +27 -27
- package/src/config/provider-validation.ts +9 -2
- package/src/config/removed-opencode-free-backup.ts +6 -3
- package/src/config/tracked-runtime-inspection.ts +3 -3
- package/src/generated/compatibility-version.json +219 -147
- package/src/images/loop.ts +2 -2
- package/src/lib/client-error-body.ts +37 -6
- package/src/lib/config-ownership-removal.ts +422 -0
- package/src/lib/config-ownership.ts +646 -81
- package/src/lib/context-overflow-verdict.ts +3 -3
- package/src/lib/crash-guard.ts +4 -2
- package/src/lib/desktop-cli-handoff.d.mts +3 -4
- package/src/lib/desktop-cli-handoff.mjs +7 -16
- package/src/lib/errors.ts +1 -0
- package/src/lib/local-management-capability.ts +3 -1
- package/src/lib/messages-error-body.ts +162 -0
- package/src/lib/messages-sse-error-presentation.ts +93 -0
- package/src/lib/passive-read.ts +9 -4
- package/src/lib/socks5-fetch.ts +21 -9
- package/src/lib/upstream-retry.ts +81 -1
- package/src/lib/windows-owner-acl.ts +9 -3
- package/src/lib/winsw.ts +5 -5
- package/src/lib/workflow-budget.ts +3 -1
- package/src/oauth/index.ts +7 -0
- package/src/oauth/store.ts +20 -10
- package/src/protocols/codecs/messages-ir.ts +15 -9
- package/src/protocols/encoders/adapter-events.ts +26 -7
- package/src/protocols/encoders/messages.ts +72 -28
- package/src/providers/antigravity-models.ts +45 -12
- package/src/providers/free-directory.ts +2 -2
- package/src/providers/reasoning-metadata.ts +2 -1
- package/src/providers/registry/entries-extended.ts +9 -0
- package/src/reasoning-effort.ts +7 -2
- package/src/remote/hub-usage.ts +3 -0
- package/src/server/admission-model-scope.ts +1 -1
- package/src/server/admitted-http-turn.ts +2 -1
- package/src/server/anthropic-rate-limit-headers.ts +75 -3
- package/src/server/claude-messages.ts +130 -67
- package/src/server/gui-static.ts +4 -1
- package/src/server/hub-usage.ts +7 -2
- package/src/server/index/link-management.ts +8 -0
- package/src/server/index/ollama-routes.ts +2 -0
- package/src/server/index/serve-options.ts +23 -20
- package/src/server/index/startup-warnings.ts +5 -12
- package/src/server/index/websocket-handler.ts +1 -0
- package/src/server/inference/client-encoder-delivery.ts +5 -1
- package/src/server/management/logs-usage-routes.ts +89 -4
- package/src/server/management/provider-routes.ts +2 -22
- package/src/server/management/qoder-provider-probe.ts +105 -0
- package/src/server/management/route-registry.ts +3 -0
- package/src/server/management/usage-aggregate-cache.ts +15 -5
- package/src/server/management/usage-source-facets.ts +38 -0
- package/src/server/messages-native-tool-guard.ts +11 -3
- package/src/server/messages-native.ts +111 -40
- package/src/server/messages-response-headers.ts +25 -11
- package/src/server/messages-shared.ts +94 -64
- package/src/server/messages-sse-error-filter.ts +199 -0
- package/src/server/request-log.ts +12 -0
- package/src/server/responses/adapter-continuation.ts +11 -5
- package/src/server/responses/adapter-delivery.ts +14 -8
- package/src/server/responses/adapter-dispatch.ts +8 -8
- package/src/server/responses/anthropic-thinking-recovery.ts +2 -2
- package/src/server/responses/codex-auth-error.ts +8 -4
- package/src/server/responses/codex-ws-wire.ts +19 -3
- package/src/server/responses/compact.ts +4 -1
- package/src/server/responses/core-auth.ts +1 -1
- package/src/server/responses/core-combo-failure.ts +2 -0
- package/src/server/responses/core-combo.ts +2 -0
- package/src/server/responses/core-errors.ts +5 -4
- package/src/server/responses/core-options.ts +2 -0
- package/src/server/responses/empty-completion-guard.ts +4 -1
- package/src/server/responses/pacing-overload.ts +1 -1
- package/src/server/responses/passthrough-dispatch.ts +5 -5
- package/src/server/responses/request-prepare.ts +3 -1
- package/src/server/responses/request-transport.ts +9 -8
- package/src/server/responses/response-effects.ts +3 -2
- package/src/server/responses/terminal-guard.ts +30 -0
- package/src/server/restart-replacement.ts +3 -1
- package/src/server/sse-payload-rewrite.ts +23 -11
- package/src/server/workflow-refusal.ts +1 -1
- package/src/server/ws-bridge.ts +4 -0
- package/src/service/definition.ts +36 -4
- package/src/service/launchd.ts +89 -32
- package/src/service/logging.ts +34 -7
- package/src/service/plist-xml.ts +59 -0
- package/src/service/state.ts +8 -0
- package/src/service/systemd-env.ts +2 -0
- package/src/service/systemd.ts +31 -7
- package/src/service/windows-taskxml.ts +16 -7
- package/src/service-manager-probe.ts +4 -10
- package/src/types/provider.ts +2 -0
- package/src/types/request.ts +13 -1
- package/src/update/config-preflight.ts +48 -0
- package/src/update/index.ts +15 -1
- package/src/usage/client.ts +43 -0
- package/src/usage/error-detail.ts +1 -1
- package/src/usage/log.ts +4 -0
- package/src/usage/source-facets.ts +51 -0
- package/src/usage/source-filter.ts +65 -0
- package/src/usage/summary.ts +50 -8
- package/src/web-search/anthropic-executor.ts +105 -24
- package/src/web-search/executor.ts +5 -3
- package/src/web-search/loop.ts +2 -1
- package/src/web-search/progress-stream.ts +64 -5
- package/gui/dist/assets/App-DuNhggE1.js +0 -58
- package/gui/dist/assets/index-CynE_Rue.js +0 -94
- package/gui/dist/assets/quota-summary-VHFSlUuM.js +0 -1
- /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
- /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
|
@@ -136,6 +136,7 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [
|
|
|
136
136
|
{ method: "PUT", path: "/api/codex-auth/pool-strategy", module: "codex/auth-api/routes", mutates: true, exempt: { reason: "compatibility-alias", why: "Superseded by PUT /api/pool/settings, which the CLI now drives. Kept working for existing clients and pinned by exact-body goldens in tests/server/account-pool-management-api.test.ts; no CLI verb targets it any more." } },
|
|
137
137
|
// codex/native-profile-api
|
|
138
138
|
{ method: "GET", path: "/api/native-main-profiles", module: "codex/native-profile-api", mutates: false },
|
|
139
|
+
{ method: "GET", path: "/api/native-main-profiles/admission", module: "codex/native-profile-api", mutates: false, exempt: { reason: "deferred-verb", why: "Read by `ocx doctor` over its single-use local read capability; ocx doctor is not a registry verb, and no operator verb reports admission on its own yet.", owner: "native-main admission", ownerDoc: "structure/codex-home.md" } },
|
|
139
140
|
{ method: "GET", path: "/api/native-main-profiles/doctor", module: "codex/native-profile-api", mutates: false },
|
|
140
141
|
{ method: "POST", path: "/api/native-main-profiles/recover", module: "codex/native-profile-api", mutates: true },
|
|
141
142
|
{ method: "POST", path: "/api/native-main-profiles/register", module: "codex/native-profile-api", mutates: true },
|
|
@@ -288,6 +289,8 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [
|
|
|
288
289
|
{ method: "GET", path: "/api/storage/trash", module: "server/management/logs-usage-routes", mutates: false },
|
|
289
290
|
{ method: "GET", path: "/api/storage/trash/restore/test-stream", module: "server/management/logs-usage-routes", mutates: false, exempt: { reason: "test-seam", why: "Opt-in streaming seam declared at src/storage/restore-job.ts:34." } },
|
|
290
291
|
{ method: "GET", path: "/api/usage", module: "server/management/logs-usage-routes", mutates: false },
|
|
292
|
+
{ method: "GET", path: "/api/usage/devices", module: "server/management/logs-usage-routes", mutates: false, exempt: { reason: "session-only", why: "Device inventory requires a current dashboard session and refuses raw admin and data keys." } },
|
|
293
|
+
{ method: "GET", path: "/api/usage/source-facets", module: "server/management/logs-usage-routes", mutates: false, exempt: { reason: "session-only", why: "Usage source facets require a current dashboard session and refuse raw admin and data keys." } },
|
|
291
294
|
// server/management/usage-timeline-routes
|
|
292
295
|
{ method: "GET", path: "/api/usage/timeline", module: "server/management/usage-timeline-routes", mutates: false },
|
|
293
296
|
// server/management/advisor-routes
|
|
@@ -12,9 +12,11 @@ import {
|
|
|
12
12
|
import {
|
|
13
13
|
createUsageSummaryAccumulator,
|
|
14
14
|
type UsageSummaryAccumulator,
|
|
15
|
+
type UsageSummaryFilterInput,
|
|
15
16
|
} from "../../usage/summary";
|
|
16
17
|
import { userCostOverlayVersion } from "../../usage/user-cost-overlays";
|
|
17
18
|
import type { UsageTimeWindow } from "../../usage/time-range";
|
|
19
|
+
import { snapshotConfiguredKeyIds } from "../../usage/source-filter";
|
|
18
20
|
import {
|
|
19
21
|
createJevStatsAccumulator,
|
|
20
22
|
type JevStatsAccumulator,
|
|
@@ -28,6 +30,7 @@ import {
|
|
|
28
30
|
interface RetainedUsageAggregate {
|
|
29
31
|
accumulator: UsageSummaryAccumulator;
|
|
30
32
|
usageIncomplete: boolean;
|
|
33
|
+
usageInvalidRows: boolean;
|
|
31
34
|
revision: UsageLogRevision | null;
|
|
32
35
|
identityKey: string;
|
|
33
36
|
revisionKey: string;
|
|
@@ -54,6 +57,7 @@ type RetainedAggregateState = RetainedUsageAggregate | RetainedJevStatsAggregate
|
|
|
54
57
|
export interface UsageAggregateResult {
|
|
55
58
|
accumulator: UsageSummaryAccumulator;
|
|
56
59
|
usageIncomplete: boolean;
|
|
60
|
+
usageInvalidRows: boolean;
|
|
57
61
|
revision: UsageLogRevision | null;
|
|
58
62
|
processedThroughBytes: number;
|
|
59
63
|
overlayVersion: number;
|
|
@@ -108,6 +112,7 @@ function resultFrom(
|
|
|
108
112
|
return {
|
|
109
113
|
accumulator: state.accumulator,
|
|
110
114
|
usageIncomplete: state.usageIncomplete,
|
|
115
|
+
usageInvalidRows: state.usageInvalidRows,
|
|
111
116
|
revision: state.revision,
|
|
112
117
|
processedThroughBytes: state.processedThroughBytes,
|
|
113
118
|
overlayVersion: state.overlayVersion,
|
|
@@ -133,6 +138,7 @@ function makeRetainedAggregate(
|
|
|
133
138
|
return {
|
|
134
139
|
accumulator,
|
|
135
140
|
usageIncomplete: scan.oversizedRows > 0,
|
|
141
|
+
usageInvalidRows: scan.invalidRows > 0,
|
|
136
142
|
revision: scan.revision,
|
|
137
143
|
identityKey: usageLogIdentityKey(scan.revision),
|
|
138
144
|
revisionKey: usageLogRevisionKey(scan.revision),
|
|
@@ -233,6 +239,7 @@ async function appendAggregate(
|
|
|
233
239
|
// A partial unterminated row can be scanned again on the next append.
|
|
234
240
|
// Preserve a boolean diagnostic rather than double-counting omissions.
|
|
235
241
|
usageIncomplete: state.usageIncomplete || scan.oversizedRows > 0,
|
|
242
|
+
usageInvalidRows: state.usageInvalidRows || scan.invalidRows > 0,
|
|
236
243
|
revision: scan.revision,
|
|
237
244
|
identityKey: usageLogIdentityKey(scan.revision),
|
|
238
245
|
revisionKey: usageLogRevisionKey(scan.revision),
|
|
@@ -293,21 +300,21 @@ function normalizeExactFilterValue(value: string | null | undefined): string | n
|
|
|
293
300
|
return normalized || null;
|
|
294
301
|
}
|
|
295
302
|
|
|
296
|
-
export async function getFilteredUsageAggregate(filter: {
|
|
297
|
-
provider?: string | null;
|
|
298
|
-
model?: string | null;
|
|
299
|
-
apiKeyId?: string | null;
|
|
300
|
-
}, window?: UsageTimeWindow): Promise<UsageAggregateResult> {
|
|
303
|
+
export async function getFilteredUsageAggregate(filter: UsageSummaryFilterInput, window?: UsageTimeWindow): Promise<UsageAggregateResult> {
|
|
301
304
|
const fixedWindow = window ? Object.freeze({ ...window }) : undefined;
|
|
302
305
|
const normalizedFilter = {
|
|
303
306
|
provider: normalizeFilterValue(filter.provider),
|
|
304
307
|
model: normalizeFilterValue(filter.model),
|
|
305
308
|
apiKeyId: normalizeExactFilterValue(filter.apiKeyId),
|
|
309
|
+
...(filter.sourceFilter ? { sourceFilter: { client: filter.sourceFilter.client, device: { ...filter.sourceFilter.device } } } : {}),
|
|
310
|
+
...(filter.configuredApiKeyIds ? { configuredApiKeyIds: snapshotConfiguredKeyIds(filter.configuredApiKeyIds) } : {}),
|
|
306
311
|
};
|
|
307
312
|
const key = JSON.stringify([
|
|
308
313
|
normalizedFilter.provider,
|
|
309
314
|
normalizedFilter.model,
|
|
310
315
|
normalizedFilter.apiKeyId,
|
|
316
|
+
normalizedFilter.sourceFilter ?? null,
|
|
317
|
+
normalizedFilter.configuredApiKeyIds ?? null,
|
|
311
318
|
fixedWindow?.since ?? null,
|
|
312
319
|
fixedWindow?.until ?? null,
|
|
313
320
|
]);
|
|
@@ -330,6 +337,8 @@ type NormalizedUsageFilter = {
|
|
|
330
337
|
provider: string | null;
|
|
331
338
|
model: string | null;
|
|
332
339
|
apiKeyId: string | null;
|
|
340
|
+
sourceFilter?: UsageSummaryFilterInput["sourceFilter"];
|
|
341
|
+
configuredApiKeyIds?: readonly string[];
|
|
333
342
|
};
|
|
334
343
|
|
|
335
344
|
function trimRetainedFilteredAggregates(): void {
|
|
@@ -405,6 +414,7 @@ async function appendFilteredAggregate(
|
|
|
405
414
|
...state,
|
|
406
415
|
accumulator: candidate,
|
|
407
416
|
usageIncomplete: state.usageIncomplete || scan.oversizedRows > 0,
|
|
417
|
+
usageInvalidRows: state.usageInvalidRows || scan.invalidRows > 0,
|
|
408
418
|
revision: scan.revision,
|
|
409
419
|
identityKey: usageLogIdentityKey(scan.revision),
|
|
410
420
|
revisionKey: usageLogRevisionKey(scan.revision),
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { scanUsageLedgerCooperatively } from "../../usage/ledger-scanner";
|
|
2
|
+
import { currentUsageLogRevision, usageLogIdentityKey, usageLogRevisionKey } from "../../usage/log";
|
|
3
|
+
import { createSourceFacetAccumulator } from "../../usage/source-facets";
|
|
4
|
+
import { snapshotConfiguredKeyIds, type UsageSourceFilter } from "../../usage/source-filter";
|
|
5
|
+
import { rangeWindow } from "../../usage/summary";
|
|
6
|
+
|
|
7
|
+
const MAX_FLIGHTS = 4;
|
|
8
|
+
const flights = new Map<string, Promise<SourceFacets>>();
|
|
9
|
+
|
|
10
|
+
export class SourceFacetsBusyError extends Error {}
|
|
11
|
+
type SourceFacets = ReturnType<ReturnType<typeof createSourceFacetAccumulator>["snapshot"]> & {
|
|
12
|
+
sourceFilter: UsageSourceFilter;
|
|
13
|
+
window: { since: number; until: number; timeZone: string };
|
|
14
|
+
usageIncomplete: boolean;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** Single-flight identical requests; never retain arbitrary historical key IDs. */
|
|
18
|
+
export async function getUsageSourceFacets(filter: UsageSourceFilter, configuredIds: readonly string[]): Promise<SourceFacets> {
|
|
19
|
+
const ids = snapshotConfiguredKeyIds(configuredIds);
|
|
20
|
+
const captured: UsageSourceFilter = { client: filter.client, device: { ...filter.device } };
|
|
21
|
+
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
22
|
+
const revision = currentUsageLogRevision();
|
|
23
|
+
const key = JSON.stringify([captured, ids, timeZone, usageLogIdentityKey(revision), usageLogRevisionKey(revision)]);
|
|
24
|
+
const existing = flights.get(key);
|
|
25
|
+
if (existing) return existing;
|
|
26
|
+
if (flights.size >= MAX_FLIGHTS) throw new SourceFacetsBusyError("usage facets busy");
|
|
27
|
+
const flight = (async () => {
|
|
28
|
+
const until = Date.now();
|
|
29
|
+
const since = rangeWindow("30d", until).since!;
|
|
30
|
+
const accumulator = createSourceFacetAccumulator(captured, ids, { since, until });
|
|
31
|
+
const scan = await scanUsageLedgerCooperatively({ onEntry: row => accumulator.add(row) });
|
|
32
|
+
if (Intl.DateTimeFormat().resolvedOptions().timeZone !== timeZone) throw new Error("time zone changed");
|
|
33
|
+
return { ...accumulator.snapshot(), sourceFilter: captured, window: { since, until, timeZone },
|
|
34
|
+
usageIncomplete: scan.oversizedRows > 0 || scan.invalidRows > 0 };
|
|
35
|
+
})();
|
|
36
|
+
flights.set(key, flight);
|
|
37
|
+
try { return await flight; } finally { if (flights.get(key) === flight) flights.delete(key); }
|
|
38
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { MessagesSseFrameContext, messagesSseFrameHooks, messagesSseLocalFrame } from "../lib/messages-sse-error-presentation";
|
|
1
2
|
import { anthropicErrorBody } from "../claude/outbound";
|
|
2
3
|
import { redactSecretString } from "../lib/redact";
|
|
3
4
|
import { sseFieldValue } from "../lib/sse-decoder";
|
|
@@ -49,8 +50,10 @@ export function guardNativeMessagesEmptyToolCatalog(
|
|
|
49
50
|
budget: TranslatorBudget,
|
|
50
51
|
onRefusal: (message: string) => void,
|
|
51
52
|
declared: ReadonlySet<string> = NO_DECLARED_TOOLS,
|
|
53
|
+
frames?: MessagesSseFrameContext,
|
|
52
54
|
): ReadableStream<Uint8Array> {
|
|
53
55
|
const reader = source.getReader();
|
|
56
|
+
const hooks = frames ? messagesSseFrameHooks(frames) : undefined;
|
|
54
57
|
const decoder = new TextDecoder();
|
|
55
58
|
const encoder = new TextEncoder();
|
|
56
59
|
const scope = { kind: "live_transient" as const };
|
|
@@ -66,15 +69,19 @@ export function guardNativeMessagesEmptyToolCatalog(
|
|
|
66
69
|
queuedBytes = 0;
|
|
67
70
|
};
|
|
68
71
|
const clear = () => {
|
|
72
|
+
hooks?.dispose();
|
|
69
73
|
buffer.clear();
|
|
70
74
|
budget.releaseRetained(permittedInputBlocks.size * 32, scope);
|
|
71
75
|
permittedInputBlocks.clear();
|
|
72
76
|
};
|
|
73
|
-
const enqueue = (controller: ReadableStreamDefaultController<Uint8Array>, text: string) => {
|
|
77
|
+
const enqueue = (controller: ReadableStreamDefaultController<Uint8Array>, text: string, original = text, refusal = false) => {
|
|
74
78
|
const bytes = Buffer.byteLength(text);
|
|
75
79
|
const reservation = budget.reserveTransient(bytes, scope);
|
|
76
80
|
try {
|
|
77
|
-
|
|
81
|
+
const encoded = encoder.encode(text);
|
|
82
|
+
if (refusal) frames?.register(encoded, { client: messagesSseLocalFrame("guard", "") });
|
|
83
|
+
else hooks?.output(original, encoded);
|
|
84
|
+
controller.enqueue(encoded);
|
|
78
85
|
reservation.commitRetained();
|
|
79
86
|
queuedBytes += bytes;
|
|
80
87
|
} catch (error) {
|
|
@@ -112,7 +119,7 @@ export function guardNativeMessagesEmptyToolCatalog(
|
|
|
112
119
|
clear();
|
|
113
120
|
const message = redactSecretString(undeclaredToolCallMessage());
|
|
114
121
|
onRefusal(message);
|
|
115
|
-
enqueue(controller, `event: error\ndata: ${JSON.stringify(anthropicErrorBody(502, message, "api_error", UNDECLARED_TOOL_CALL_ERROR_CODE))}\n\n
|
|
122
|
+
enqueue(controller, `event: error\ndata: ${JSON.stringify(anthropicErrorBody(502, message, "api_error", UNDECLARED_TOOL_CALL_ERROR_CODE))}\n\n`, undefined, true);
|
|
116
123
|
settled = true;
|
|
117
124
|
cancelReader(new Error(message));
|
|
118
125
|
controller.close();
|
|
@@ -152,6 +159,7 @@ export function guardNativeMessagesEmptyToolCatalog(
|
|
|
152
159
|
const { done, value } = await reader.read();
|
|
153
160
|
if (settled) return;
|
|
154
161
|
if (!done) {
|
|
162
|
+
hooks?.input(value, buffer.isEmpty());
|
|
155
163
|
buffer.append(decoder.decode(value, { stream: true }));
|
|
156
164
|
continue;
|
|
157
165
|
}
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import { MessagesSseFrameContext, messagesSseEchoRenamedError, messagesSseFrameHooks } from "../lib/messages-sse-error-presentation";
|
|
2
|
+
import { createMessagesSseErrorFilter } from "./messages-sse-error-filter";
|
|
3
|
+
import type { MessagesFailureVerdictSink } from "../claude/failure-verdict";
|
|
4
|
+
import { upstreamErrorIsLocal } from "./request-log-failure-detail";
|
|
5
|
+
import { boundedMessagesDisplayCount, ownedAnthropicErrorPayload, ownedAnthropicErrorResponse, messagesOverflowPresentation, messagesRelayedOverflowPresentation } from "../lib/messages-error-body";
|
|
6
|
+
import { attachComboFailureEvidence, isProxyError, markProxyError } from "../lib/client-error-body";
|
|
1
7
|
import { captureAccountAutoPauseAttempt, wasAccountAutoPaused } from "../oauth/account-auto-pause";
|
|
2
8
|
import { createPhysicalSendReporter } from "../lib/request-execution-budget";
|
|
3
9
|
import { createInferenceSendBudget } from "./inference/context";
|
|
@@ -38,7 +44,7 @@ import {
|
|
|
38
44
|
type AnthropicMessagesPassthroughRequest,
|
|
39
45
|
} from "../adapters/anthropic/passthrough";
|
|
40
46
|
import { effortFromOutputConfig, resolveInboundModel } from "../claude/inbound";
|
|
41
|
-
import { anthropicErrorBody,
|
|
47
|
+
import { anthropicErrorBody, claudeOverflowSsePayload, claudePromptTooLongMessage, collectAnthropicMessage, isContextOverflowText, isThroughputLimitText } from "../claude/outbound";
|
|
42
48
|
import type { AdmissionLease } from "../lib/admission";
|
|
43
49
|
import { readBoundedResponseBody } from "../lib/bounded-body";
|
|
44
50
|
import { classifyError } from "../lib/errors";
|
|
@@ -76,7 +82,7 @@ import {
|
|
|
76
82
|
transientRetryPolicyFor,
|
|
77
83
|
} from "../providers/key-failover";
|
|
78
84
|
import { stampApiKeyAccountLabel } from "../providers/label";
|
|
79
|
-
import { OAuthAccountPausedError, OAuthLoginRequiredError, publicOAuthAuthenticationErrorMessage } from "../oauth";
|
|
85
|
+
import { publicOAuthErrorPresentation, OAuthAccountPausedError, OAuthLoginRequiredError, publicOAuthAuthenticationErrorMessage } from "../oauth";
|
|
80
86
|
import { AnthropicAccountCooldownError, formatAnthropicProviderForLog, anthropicRoutingFor } from "../oauth/anthropic-routing";
|
|
81
87
|
import { configuredAnthropicInstance } from "../providers/anthropic-instance";
|
|
82
88
|
import { resolveProtocolSettings } from "../protocols/settings";
|
|
@@ -233,7 +239,7 @@ function messageStartWithModel(frame: string, model: string): string | undefined
|
|
|
233
239
|
* (`responsesSseToAnthropicSse` is given the requested model). Works on bytes: frames before and
|
|
234
240
|
* including `message_start` are split on the blank line, and everything after is relayed as is.
|
|
235
241
|
*/
|
|
236
|
-
function echoRequestedModel(body: ReadableStream<Uint8Array>, model: string): ReadableStream<Uint8Array> {
|
|
242
|
+
function echoRequestedModel(body: ReadableStream<Uint8Array>, model: string, frames: MessagesSseFrameContext): ReadableStream<Uint8Array> {
|
|
237
243
|
const reader = body.getReader();
|
|
238
244
|
const encoder = new TextEncoder();
|
|
239
245
|
const decoder = new TextDecoder();
|
|
@@ -268,7 +274,9 @@ function echoRequestedModel(body: ReadableStream<Uint8Array>, model: string): Re
|
|
|
268
274
|
pending = pending.subarray(end);
|
|
269
275
|
const rewritten = messageStartWithModel(decoder.decode(frame), model);
|
|
270
276
|
if (rewritten !== undefined) {
|
|
271
|
-
|
|
277
|
+
const bytes = encoder.encode(rewritten);
|
|
278
|
+
if (messagesSseEchoRenamedError(decoder.decode(frame))) frames.register(bytes, { echoRenamedError: true });
|
|
279
|
+
controller.enqueue(bytes);
|
|
272
280
|
scanning = false;
|
|
273
281
|
} else {
|
|
274
282
|
controller.enqueue(frame);
|
|
@@ -372,20 +380,40 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
372
380
|
attempt.usage = usage;
|
|
373
381
|
}
|
|
374
382
|
};
|
|
375
|
-
const fail = (status: number, message: string, type?: string, code?: string): Response => {
|
|
383
|
+
const fail = (status: number, message: string, type?: string, code?: string, originalMessage = message): Response => {
|
|
376
384
|
const safeMessage = redactSecretString(message);
|
|
377
385
|
finishLog(status, safeMessage);
|
|
378
|
-
|
|
386
|
+
const legacy = anthropicErrorBody(status, redactSecretString(originalMessage), type, code);
|
|
387
|
+
return ownedAnthropicErrorResponse({ status, type, code, evidence: { status, message: originalMessage },
|
|
388
|
+
localError: markProxyError({ message: safeMessage }), overflow: messagesRelayedOverflowPresentation("", legacy) }, legacy);
|
|
389
|
+
};
|
|
390
|
+
const failEvidence = (status: number, message: string, type: string, contract?: "transport_failed", overflow?: boolean, rawError?: Rec, legacyBody?: Rec): Response => {
|
|
391
|
+
finishLog(status, message);
|
|
392
|
+
const legacy = legacyBody ?? anthropicErrorBody(status, redactSecretString(message), type);
|
|
393
|
+
return ownedAnthropicErrorResponse({ status, type, evidence: { status, message, type: typeof rawError?.type === "string" ? rawError.type : undefined, code: typeof rawError?.code === "string" ? rawError.code : undefined }, contract,
|
|
394
|
+
overflow: overflow ?? messagesRelayedOverflowPresentation("", legacy) }, legacy);
|
|
395
|
+
};
|
|
396
|
+
const preparationFailure = (error: unknown): Response => {
|
|
397
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
398
|
+
finishLog(400, message);
|
|
399
|
+
return fail(400, error instanceof Error && isProxyError(error) ? error.message : "The proxy could not translate the Messages request.", "invalid_request_error", undefined, message);
|
|
379
400
|
};
|
|
380
401
|
const localOAuthFailure = (error: unknown): Response | null => {
|
|
381
402
|
if (error instanceof AnthropicAccountCooldownError) {
|
|
382
|
-
const
|
|
403
|
+
const scope = error.routePosition === undefined ? "All Anthropic OAuth accounts" : "Anthropic OAuth accounts for this model route";
|
|
404
|
+
const reset = error.usageLimit?.resetsAt;
|
|
405
|
+
const date = typeof reset === "number" && Number.isFinite(reset) && reset >= 0 && reset <= 253402300799999
|
|
406
|
+
? new Date(Math.floor(reset / 1000) * 1000).toISOString().replace(".000Z", "Z") : undefined;
|
|
407
|
+
const message = error.usageLimit === null ? `${scope} are temporarily rate-limited`
|
|
408
|
+
: `${scope} have reached their usage limit${date ? `; the first one resets at ${date}` : ""}`;
|
|
409
|
+
finishLog(429, error.message);
|
|
410
|
+
const response = markProxyError(fail(429, message, "rate_limit_error"), date === undefined ? undefined : "usage");
|
|
383
411
|
const advice = error.retryAfterSeconds !== null ? formatClientRetryAfter(error.retryAfterSeconds) : undefined;
|
|
384
412
|
if (advice !== undefined) response.headers.set("retry-after", advice);
|
|
385
413
|
return response;
|
|
386
414
|
}
|
|
387
|
-
if (error instanceof OAuthAccountPausedError) return fail(403, publicOAuthAuthenticationErrorMessage(error), "permission_error");
|
|
388
|
-
if (error instanceof OAuthLoginRequiredError) return fail(401, publicOAuthAuthenticationErrorMessage(error), "authentication_error");
|
|
415
|
+
if (error instanceof OAuthAccountPausedError) return markProxyError(fail(403, publicOAuthAuthenticationErrorMessage(error), "permission_error"), publicOAuthErrorPresentation(error));
|
|
416
|
+
if (error instanceof OAuthLoginRequiredError) return markProxyError(fail(401, publicOAuthAuthenticationErrorMessage(error), "authentication_error"), publicOAuthErrorPresentation(error));
|
|
389
417
|
return null;
|
|
390
418
|
};
|
|
391
419
|
|
|
@@ -411,7 +439,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
411
439
|
return fail(413, "request translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
|
|
412
440
|
}
|
|
413
441
|
// An AnthropicRequestError (empty tool id) or an image the guard cannot carry.
|
|
414
|
-
return
|
|
442
|
+
return preparationFailure(error);
|
|
415
443
|
}
|
|
416
444
|
|
|
417
445
|
const upstream = new AbortController();
|
|
@@ -444,8 +472,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
444
472
|
const localRefusal = localOAuthFailure(error);
|
|
445
473
|
if (localRefusal) return localRefusal;
|
|
446
474
|
if (error instanceof NativeOAuthSelectionChangedError) return fail(409, error.message, "api_error");
|
|
447
|
-
if (error instanceof NativeOAuthModelRouteError) return fail(400,
|
|
448
|
-
return fail(401, publicOAuthAuthenticationErrorMessage(error), "authentication_error");
|
|
475
|
+
if (error instanceof NativeOAuthModelRouteError) return fail(400, "Invalid Anthropic model routes", "invalid_request_error", undefined, error.message);
|
|
476
|
+
return markProxyError(fail(401, publicOAuthAuthenticationErrorMessage(error), "authentication_error"), publicOAuthErrorPresentation(error));
|
|
449
477
|
}
|
|
450
478
|
} else {
|
|
451
479
|
// Same pre-dispatch key preference every direct send path applies (see chat-native.ts).
|
|
@@ -455,7 +483,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
455
483
|
} catch (error) {
|
|
456
484
|
cleanupAbort(); upstream.abort();
|
|
457
485
|
if (!(error instanceof RequestPacingQueueOverloadError)) throw error;
|
|
458
|
-
const refusal = fail(429, error.message, "rate_limit_error");
|
|
486
|
+
const refusal = markProxyError(fail(429, error.message, "rate_limit_error"), error.reason === "keys_exhausted" ? undefined : "pacing");
|
|
459
487
|
const advice = formatClientRetryAfter(error.retryAfterSeconds);
|
|
460
488
|
if (advice !== undefined) refusal.headers.set("Retry-After", advice);
|
|
461
489
|
return refusal;
|
|
@@ -523,7 +551,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
523
551
|
logCtx.errorCode = "unsupported_feature";
|
|
524
552
|
return fail(400, error.message, "invalid_request_error", "unsupported_feature");
|
|
525
553
|
}
|
|
526
|
-
return
|
|
554
|
+
return preparationFailure(error);
|
|
527
555
|
}
|
|
528
556
|
|
|
529
557
|
// One inbound request owns one transient send allowance, captured before any key rotation.
|
|
@@ -557,7 +585,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
557
585
|
const send = async (recovery?: "rate-limit-429" | "oauth-401" | "oauth-account-403" | "key-429" | "key-401"): Promise<Response> => {
|
|
558
586
|
const remaining = remainingTransientSends();
|
|
559
587
|
if (requestTransientPolicy && remaining <= 0) {
|
|
560
|
-
throw new Error("native Messages transient send budget exhausted before recovery dispatch");
|
|
588
|
+
throw markProxyError(new Error("native Messages transient send budget exhausted before recovery dispatch"));
|
|
561
589
|
}
|
|
562
590
|
const fetchWithPolicy = requestTransientPolicy ? fetchWithTransientRetry : fetchWithResetRetry;
|
|
563
591
|
const request = activeRequest;
|
|
@@ -590,7 +618,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
590
618
|
}
|
|
591
619
|
} else {
|
|
592
620
|
for (let attempt = 0; !providerApiKeySelectionIsCurrent(config, route.providerName, activeProvider); attempt++) {
|
|
593
|
-
if (attempt >= 3) throw new Error("Provider key selection changed repeatedly before native Messages dispatch");
|
|
621
|
+
if (attempt >= 3) throw markProxyError(new Error("Provider key selection changed repeatedly before native Messages dispatch"));
|
|
594
622
|
let current = resolveCurrentProviderApiKeyTransport(config, route.providerName, activeProvider);
|
|
595
623
|
if (!current && activeProvider.requestPacing?.enabled
|
|
596
624
|
&& (activeProvider.requestPacing.keys || activeProvider.requestPacing.keySelection === "round-robin")) {
|
|
@@ -598,12 +626,12 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
598
626
|
if (fresh) current = selectProactiveApiKeyTransport(config, route.providerName, fresh) ?? fresh;
|
|
599
627
|
}
|
|
600
628
|
if (!current || nativeMessagesDeclineReason({ ...route, provider: current }, body, config, selector) !== undefined) {
|
|
601
|
-
throw new Error("Provider key selection is no longer available for native Messages");
|
|
629
|
+
throw markProxyError(new Error("Provider key selection is no longer available for native Messages"));
|
|
602
630
|
}
|
|
603
631
|
rebuildFor(current);
|
|
604
632
|
if (current.requestPacing?.enabled
|
|
605
633
|
&& (current.requestPacing.keys || current.requestPacing.keySelection === "round-robin")) {
|
|
606
|
-
if (!reacquirePacing) throw new Error("Refreshed native Messages dispatch requires pacing readmission");
|
|
634
|
+
if (!reacquirePacing) throw markProxyError(new Error("Refreshed native Messages dispatch requires pacing readmission"));
|
|
607
635
|
await reacquirePacing(current, route.modelId);
|
|
608
636
|
}
|
|
609
637
|
}
|
|
@@ -837,21 +865,21 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
837
865
|
settleDistributedFailure();
|
|
838
866
|
const sendError = error instanceof UpstreamRetryEvidenceError ? error.cause : error;
|
|
839
867
|
if (sendError instanceof RequestPacingQueueOverloadError) {
|
|
840
|
-
const refusal = fail(429, sendError.message, "rate_limit_error");
|
|
868
|
+
const refusal = markProxyError(fail(429, sendError.message, "rate_limit_error"), sendError.reason === "keys_exhausted" ? undefined : "pacing");
|
|
841
869
|
const advice = formatClientRetryAfter(sendError.retryAfterSeconds);
|
|
842
870
|
if (advice !== undefined) refusal.headers.set("Retry-After", advice);
|
|
843
871
|
return refusal;
|
|
844
872
|
}
|
|
845
873
|
if (sendError instanceof SendBudgetExhaustedError) return fail(429, sendError.message, "send_budget_exhausted", "send_budget_exhausted");
|
|
846
874
|
if (sendError instanceof NativeMessagesSpendRefusal) {
|
|
847
|
-
const refusal = workflowRefusalResponse("workflow-spend-exhausted", logCtx);
|
|
875
|
+
const refusal = workflowRefusalResponse("workflow-spend-exhausted", logCtx, undefined, undefined, logCtx.spendRefusalDetail);
|
|
848
876
|
finishLog(429);
|
|
849
877
|
return refusal;
|
|
850
878
|
}
|
|
851
879
|
const localRefusal = localOAuthFailure(sendError);
|
|
852
880
|
if (localRefusal) return localRefusal;
|
|
853
881
|
if (sendError instanceof NativeOAuthSelectionChangedError) return fail(409, sendError.message, "api_error");
|
|
854
|
-
if (sendError instanceof NativeOAuthModelRouteError) return fail(400,
|
|
882
|
+
if (sendError instanceof NativeOAuthModelRouteError) return fail(400, "Invalid Anthropic model routes", "invalid_request_error", undefined, sendError.message);
|
|
855
883
|
if (sendError instanceof NativeOpaqueStateRefusal) {
|
|
856
884
|
logCtx.errorCode = "unsupported_feature";
|
|
857
885
|
return fail(400, sendError.message, "invalid_request_error", "unsupported_feature");
|
|
@@ -859,7 +887,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
859
887
|
if (isTranslatorBudgetExceededError(error)) {
|
|
860
888
|
return fail(413, "request translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
|
|
861
889
|
}
|
|
862
|
-
|
|
890
|
+
if (sendError instanceof Error && isProxyError(sendError)) return fail(502, sendError.message, "api_error");
|
|
891
|
+
return failEvidence(502, error instanceof Error ? error.message : String(error), "api_error", "transport_failed");
|
|
863
892
|
}
|
|
864
893
|
releaseRetainedRequest();
|
|
865
894
|
|
|
@@ -900,16 +929,18 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
900
929
|
const renamed = activeRequest.oauthToolNames
|
|
901
930
|
? restoreOAuthToolNamesInSse(observed, activeRequest.oauthToolNames, translatorBudget)
|
|
902
931
|
: observed;
|
|
903
|
-
const
|
|
932
|
+
const frames = new MessagesSseFrameContext();
|
|
933
|
+
const echoed = echoRequestedModel(renamed, requestedModel, frames);
|
|
904
934
|
let toolRefusal: string | undefined;
|
|
905
935
|
const source = clientDeclaredEmptyToolCatalog
|
|
906
936
|
? guardNativeMessagesEmptyToolCatalog(echoed, translatorBudget, message => {
|
|
907
937
|
toolRefusal = message;
|
|
908
938
|
logCtx.errorCode = UNDECLARED_TOOL_CALL_ERROR_CODE;
|
|
909
|
-
}, declaredInlineTools)
|
|
939
|
+
}, declaredInlineTools, frames)
|
|
910
940
|
: echoed;
|
|
911
941
|
if (requestedStream) {
|
|
912
942
|
transferTurnToStream();
|
|
943
|
+
const clientFilter = createMessagesSseErrorFilter(frames);
|
|
913
944
|
const relayed = tapAnthropicSseForLog(source, logCtx, (status, meta) => {
|
|
914
945
|
try {
|
|
915
946
|
cleanupAbort();
|
|
@@ -919,12 +950,12 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
919
950
|
} finally {
|
|
920
951
|
releaseStreamTurn();
|
|
921
952
|
}
|
|
922
|
-
}, bodyGuard);
|
|
953
|
+
}, bodyGuard, frames, nativeInstance ? clientFilter : undefined);
|
|
923
954
|
// A configured Messages provider words an oversized-input refusal its own way; Claude Code
|
|
924
955
|
// compacts only on Anthropic's wording (devlog/_plan/261009_claude_1m_default/010). The
|
|
925
956
|
// rewrite buffers whole frames, so it sits after the tap: stall detection keeps timing raw
|
|
926
957
|
// upstream bytes. Real Anthropic pools refuse pre-stream in that wording and keep one relay.
|
|
927
|
-
const clientStream = nativeInstance ? relayed : relaySseWithPayloadRewrite(relayed, claudeOverflowSsePayload, translatorBudget);
|
|
958
|
+
const clientStream = nativeInstance ? relayed : relaySseWithPayloadRewrite(relayed, claudeOverflowSsePayload, translatorBudget, messagesSseFrameHooks(frames), clientFilter);
|
|
928
959
|
return retainUpstreamMessagesRequestId(new Response(clientStream, {
|
|
929
960
|
status: 200,
|
|
930
961
|
headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache", Connection: "keep-alive" },
|
|
@@ -936,8 +967,9 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
936
967
|
tapState.closeReason = meta.closeReason;
|
|
937
968
|
tapState.meta = meta;
|
|
938
969
|
}, bodyGuard);
|
|
970
|
+
const collectorVerdictSink: MessagesFailureVerdictSink = {};
|
|
939
971
|
try {
|
|
940
|
-
const message = await collectAnthropicMessage(tapped, requestedModel, translatorBudget);
|
|
972
|
+
const message = await collectAnthropicMessage(tapped, requestedModel, translatorBudget, collectorVerdictSink);
|
|
941
973
|
cleanupAbort();
|
|
942
974
|
if (tapState.closeReason === "client_cancel" || req.signal.aborted) {
|
|
943
975
|
return fail(499, "Client cancelled request", "api_error");
|
|
@@ -951,15 +983,41 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
951
983
|
finishLog(502, toolRefusal, { closeReason: "terminal", terminalStatus: "failed" });
|
|
952
984
|
return fail(502, toolRefusal, "api_error", UNDECLARED_TOOL_CALL_ERROR_CODE);
|
|
953
985
|
}
|
|
986
|
+
const baselineOverflow = isNativeOverflowError(error, text);
|
|
954
987
|
// The tap's own verdict (a reset, a stall, the byte cap) closes this row with the same meta
|
|
955
988
|
// as the streaming lane's row; a plain upstream error event keeps the non_stream row.
|
|
956
989
|
const tapMeta = tapState.meta;
|
|
957
990
|
if (tapMeta && (tapMeta.terminalStatus || tapMeta.closeReason !== "terminal")) finishLog(502, text, tapMeta);
|
|
958
|
-
if (
|
|
959
|
-
|
|
991
|
+
if (upstreamErrorIsLocal(logCtx) && (logCtx.terminalSource === "synthetic" || tapMeta?.closeReason === "body_stall" || tapMeta?.closeReason === "body_overflow")) {
|
|
992
|
+
const count = boundedMessagesDisplayCount(bodyGuard.maxBytes);
|
|
993
|
+
const seconds = boundedMessagesDisplayCount(Math.round(bodyGuard.stallMs / 1000));
|
|
994
|
+
const localMessage = new Map<string, string>([
|
|
995
|
+
["body_overflow", count === undefined ? "anthropic passthrough body exceeded the safe limit" : `anthropic passthrough body exceeded ${count} bytes`],
|
|
996
|
+
["body_stall", seconds === undefined ? "anthropic passthrough body stalled" : `anthropic passthrough body stalled: no upstream bytes for ${seconds}s`],
|
|
997
|
+
["stream_error_stop", 'upstream ended the turn with stop_reason "error"'],
|
|
998
|
+
["stream_ended_early", "anthropic passthrough upstream stream ended before message_stop"],
|
|
999
|
+
["stream_failed", "The proxy could not reach or read the provider."],
|
|
1000
|
+
]).get(logCtx.failureDetail?.code ?? "");
|
|
1001
|
+
if (localMessage !== undefined) return markProxyError(fail(502, localMessage, "api_error", undefined, text), logCtx.failureDetail?.code === "body_overflow" ? "body_overflow" : logCtx.failureDetail?.code === "body_stall" ? "body_stall" : undefined);
|
|
1002
|
+
}
|
|
1003
|
+
const legacy = anthropicErrorBody(baselineOverflow ? 400 : 502,
|
|
1004
|
+
redactSecretString(baselineOverflow ? claudePromptTooLongMessage(text) : text),
|
|
1005
|
+
baselineOverflow ? "invalid_request_error" : "api_error");
|
|
1006
|
+
const overflow = messagesOverflowPresentation((legacy.error as Rec).message);
|
|
1007
|
+
if (baselineOverflow) return failEvidence(400, text, "invalid_request_error", undefined, overflow, error, legacy);
|
|
1008
|
+
return failEvidence(502, text, "api_error", undefined, overflow, error, legacy);
|
|
960
1009
|
}
|
|
961
|
-
|
|
962
|
-
|
|
1010
|
+
const finalStatus = collectorVerdictSink.collectedErrorEvent ? 502 : 200;
|
|
1011
|
+
finishLog(finalStatus);
|
|
1012
|
+
const collected = collectorVerdictSink.collected ?? message;
|
|
1013
|
+
const originalError = isRec(collected.error) ? collected.error : {};
|
|
1014
|
+
const clientMessage = collectorVerdictSink.collectedErrorEvent ? ownedAnthropicErrorPayload({ status: 200,
|
|
1015
|
+
type: typeof originalError.type === "string" ? originalError.type : undefined,
|
|
1016
|
+
code: typeof originalError.code === "string" ? originalError.code : undefined,
|
|
1017
|
+
overflow: messagesRelayedOverflowPresentation(JSON.stringify(collected), collected),
|
|
1018
|
+
evidence: { status: 200, message: typeof originalError.message === "string" ? originalError.message : undefined },
|
|
1019
|
+
}) : message;
|
|
1020
|
+
return retainUpstreamMessagesRequestId(Response.json(clientMessage, { status: finalStatus }), response.headers);
|
|
963
1021
|
} catch (error) {
|
|
964
1022
|
cleanupAbort();
|
|
965
1023
|
upstream.abort();
|
|
@@ -967,7 +1025,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
967
1025
|
if (isTranslatorBudgetExceededError(error)) {
|
|
968
1026
|
return fail(413, "upstream translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit");
|
|
969
1027
|
}
|
|
970
|
-
return
|
|
1028
|
+
return failEvidence(502, error instanceof Error ? error.message : String(error), "api_error", "transport_failed");
|
|
971
1029
|
}
|
|
972
1030
|
}
|
|
973
1031
|
|
|
@@ -984,7 +1042,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
984
1042
|
cleanupAbort();
|
|
985
1043
|
upstream.abort();
|
|
986
1044
|
if (req.signal.aborted) return fail(499, "Client cancelled request", "api_error");
|
|
987
|
-
return
|
|
1045
|
+
return failEvidence(502, error instanceof Error ? error.message : String(error), "api_error", "transport_failed");
|
|
988
1046
|
}
|
|
989
1047
|
cleanupAbort();
|
|
990
1048
|
if (read.oversized) {
|
|
@@ -1059,7 +1117,7 @@ function nativeMessagesErrorResponse(response: Response, bodyText: string, finis
|
|
|
1059
1117
|
const detail = formatAnthropicErrorBody(response.status, response.headers, bodyText);
|
|
1060
1118
|
const rawMessage = upstreamMessage
|
|
1061
1119
|
?? (detail ? `Provider error ${response.status}: ${detail}` : `Provider error ${response.status}`);
|
|
1062
|
-
const
|
|
1120
|
+
const zenOptions = {
|
|
1063
1121
|
status: response.status,
|
|
1064
1122
|
providerName,
|
|
1065
1123
|
baseUrl: provider.baseUrl,
|
|
@@ -1070,7 +1128,12 @@ function nativeMessagesErrorResponse(response: Response, bodyText: string, finis
|
|
|
1070
1128
|
upstreamErrorType: upstreamType,
|
|
1071
1129
|
upstreamErrorCode: upstreamCode,
|
|
1072
1130
|
supportsHttpSameKeyRetry: true,
|
|
1073
|
-
}
|
|
1131
|
+
};
|
|
1132
|
+
const message = enrichOpenCodeZenUpstreamMessage(rawMessage, zenOptions);
|
|
1133
|
+
const clientZenMessage = message === rawMessage ? undefined : enrichOpenCodeZenUpstreamMessage(
|
|
1134
|
+
"The provider rate limit was reached; retry later.",
|
|
1135
|
+
{ ...zenOptions, upstreamRetryAfter: /try again in \d/i.test(rawMessage) ? "0" : zenOptions.upstreamRetryAfter },
|
|
1136
|
+
);
|
|
1074
1137
|
const classified = classifyError(
|
|
1075
1138
|
response.status,
|
|
1076
1139
|
upstreamType ?? (response.status === 401 ? "authentication_error"
|
|
@@ -1097,16 +1160,24 @@ function nativeMessagesErrorResponse(response: Response, bodyText: string, finis
|
|
|
1097
1160
|
// Claude Code recognizes it and compacts (010).
|
|
1098
1161
|
// Only a 400/413 refusal: the shared classifier also files a 429 "too many tokens per minute"
|
|
1099
1162
|
// under context_length_exceeded, and that one must stay a rate limit.
|
|
1100
|
-
const
|
|
1163
|
+
const legacyOverflow = !replayRefusal && (response.status === 400 || response.status === 413)
|
|
1101
1164
|
&& !isThroughputLimitText(safeMessage)
|
|
1102
1165
|
&& (classified.code === "context_length_exceeded" || upstreamCode === "context_length_exceeded"
|
|
1103
1166
|
|| isContextOverflowText(safeMessage));
|
|
1104
|
-
const
|
|
1105
|
-
|
|
1106
|
-
overflow ? claudePromptTooLongMessage(safeMessage) : safeMessage,
|
|
1167
|
+
const legacy = anthropicErrorBody(status,
|
|
1168
|
+
legacyOverflow ? claudePromptTooLongMessage(safeMessage) : safeMessage,
|
|
1107
1169
|
transient ? "overloaded_error" : upstreamType,
|
|
1108
1170
|
replayRefusal ? UPSTREAM_RESET_REPLAY_REFUSED_CODE : undefined,
|
|
1109
|
-
)
|
|
1171
|
+
);
|
|
1172
|
+
const overflow = messagesOverflowPresentation((legacy.error as Rec).message);
|
|
1173
|
+
const out = new Response(JSON.stringify(ownedAnthropicErrorPayload({
|
|
1174
|
+
status, type: transient ? "overloaded_error" : upstreamType,
|
|
1175
|
+
code: replayRefusal ? UPSTREAM_RESET_REPLAY_REFUSED_CODE : undefined,
|
|
1176
|
+
evidence: { status: response.status, type: upstreamType, code: upstreamCode, message: safeMessage }, overflow,
|
|
1177
|
+
...(replayRefusal ? { contract: "replay_refused" as const } : {}),
|
|
1178
|
+
...(clientZenMessage === undefined ? {} : { localError: markProxyError({ message: clientZenMessage }) }),
|
|
1179
|
+
})), { status, headers });
|
|
1180
|
+
attachComboFailureEvidence(out, JSON.stringify(legacy));
|
|
1110
1181
|
return replayRefusal ? retainReplayRefusal(out) : out;
|
|
1111
1182
|
}
|
|
1112
1183
|
|
|
@@ -1,14 +1,28 @@
|
|
|
1
|
-
/**
|
|
2
|
-
export function upstreamMessagesRequestIdHeaders(
|
|
3
|
-
const requestId = upstream.get("request-id");
|
|
4
|
-
return requestId && /^req_[A-Za-z0-9_-]{1,128}$/.test(requestId)
|
|
5
|
-
? { "request-id": requestId }
|
|
6
|
-
: {};
|
|
7
|
-
}
|
|
1
|
+
/** Messages metadata contains only IDs generated by the proxy ledger wrapper. */
|
|
2
|
+
export function upstreamMessagesRequestIdHeaders(_upstream: Headers): Record<string, string> { return {}; }
|
|
8
3
|
|
|
9
|
-
/**
|
|
10
|
-
export function retainUpstreamMessagesRequestId(response: Response,
|
|
11
|
-
|
|
12
|
-
if (requestId) response.headers.set("request-id", requestId);
|
|
4
|
+
/** Preserve the newly constructed response and its lifecycle markers. */
|
|
5
|
+
export function retainUpstreamMessagesRequestId(response: Response, _upstream: Headers): Response {
|
|
6
|
+
response.headers.delete("request-id");
|
|
13
7
|
return response;
|
|
14
8
|
}
|
|
9
|
+
|
|
10
|
+
const SUCCESS_MEDIA_TYPES = new Map([
|
|
11
|
+
["application/json", "application/json"], ["text/plain", "text/plain"], ["text/event-stream", "text/event-stream"],
|
|
12
|
+
]);
|
|
13
|
+
const SUCCESS_CHARSETS = new Map([["utf-8", "utf-8"], ["us-ascii", "us-ascii"]]);
|
|
14
|
+
|
|
15
|
+
/** Re-render only supported media types and charset parameters for successful bodies. */
|
|
16
|
+
export function messagesSuccessContentType(headers: Headers): string {
|
|
17
|
+
const raw = headers.get("content-type") ?? "";
|
|
18
|
+
if (raw.length > 128) return "application/octet-stream";
|
|
19
|
+
const [media, ...parameters] = raw.toLowerCase().split(";");
|
|
20
|
+
const type = SUCCESS_MEDIA_TYPES.get(media!.trim());
|
|
21
|
+
if (!type) return "application/octet-stream";
|
|
22
|
+
for (const parameter of parameters) {
|
|
23
|
+
const match = /^\s*charset\s*=\s*(?:"([^"\s]+)"|([^"\s]+))\s*$/.exec(parameter);
|
|
24
|
+
const charset = match && SUCCESS_CHARSETS.get(match[1] ?? match[2]!);
|
|
25
|
+
if (charset) return `${type}; charset=${charset}`;
|
|
26
|
+
}
|
|
27
|
+
return type;
|
|
28
|
+
}
|