@bitkyc08/opencodex 2.97.0 → 2.98.0-preview.20261107
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-B8_sOxoz.js +59 -0
- package/gui/dist/assets/Tray-DpWEp6ee.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-VPhzz-WE.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-BWKBeK77.js +94 -0
- package/gui/dist/assets/segment-thumb-features-BQYzrze9.js +1 -0
- package/gui/dist/classic/assets/App-Bz65x1J6.js +58 -0
- package/gui/dist/{assets/Tray-CEw0y0jR.js → classic/assets/Tray-kk7mdO6I.js} +1 -1
- package/gui/dist/classic/assets/index-Dp2j8bSc.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CvamtHjB.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
|
@@ -63,7 +63,6 @@ function isParameterValidationRecord(record: Record<string, unknown>): boolean {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
function isDefiniteContextOverflowMessage(text: string): boolean {
|
|
66
|
-
if (PARAMETER_VALIDATION_MARKERS.some(marker => marker.test(text))) return false;
|
|
67
66
|
const normalized = text.toLowerCase();
|
|
68
67
|
return normalized === "context_length_exceeded"
|
|
69
68
|
|| DEFINITE_CONTEXT_OVERFLOW_PHRASES.some(phrase => normalized.includes(phrase))
|
|
@@ -83,9 +82,10 @@ function isDefiniteContextOverflowMessage(text: string): boolean {
|
|
|
83
82
|
* arbitrary field that happens to sit in the first 500 bytes authorize a hop, so it fails closed.
|
|
84
83
|
*
|
|
85
84
|
* Only the exact proxy wrapper is unwrapped, within a fixed envelope budget and 16,384 characters.
|
|
85
|
+
* An optional caller matcher specializes the verdict on the unwrapped, validated leaf.
|
|
86
86
|
* Exported for the sidecar loops, which classify their own provider failures with the same rule.
|
|
87
87
|
*/
|
|
88
|
-
export function isDefiniteContextOverflow(status: number, message: string): boolean {
|
|
88
|
+
export function isDefiniteContextOverflow(status: number, message: string, matchMessage = isDefiniteContextOverflowMessage): boolean {
|
|
89
89
|
if (!CONTEXT_VERDICT_STATUSES.has(status) && status < 500) return false;
|
|
90
90
|
if (message.length > 16_384) return false;
|
|
91
91
|
let text = message.trim();
|
|
@@ -93,7 +93,7 @@ export function isDefiniteContextOverflow(status: number, message: string): bool
|
|
|
93
93
|
for (let unwrapped = 0; unwrapped <= MAX_CONTEXT_OVERFLOW_ENVELOPES; unwrapped += 1) {
|
|
94
94
|
const providerPrefix = /^Provider error \d{3}:\s*/.exec(text);
|
|
95
95
|
if (providerPrefix) text = text.slice(providerPrefix[0].length).trim();
|
|
96
|
-
if (!text.startsWith("{")) return
|
|
96
|
+
if (!text.startsWith("{")) return !PARAMETER_VALIDATION_MARKERS.some(marker => marker.test(text)) && matchMessage(text);
|
|
97
97
|
if (unwrapped === MAX_CONTEXT_OVERFLOW_ENVELOPES) return false;
|
|
98
98
|
let payload: unknown;
|
|
99
99
|
try { payload = JSON.parse(text); } catch { return false; }
|
package/src/lib/crash-guard.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { appendFileSync, mkdirSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { getConfigDir } from "../config";
|
|
4
|
-
import { recordOwnedConfigPath } from "./config-ownership";
|
|
4
|
+
import { ConfigUninstallInProgressError, recordOwnedConfigPath } from "./config-ownership";
|
|
5
5
|
import { redactSecretString, redactUrlForLog } from "./redact";
|
|
6
6
|
import { sidecarBreadcrumb, activityBreadcrumb } from "./sidecar-tracker";
|
|
7
7
|
import { retainedUtf8Bytes, truncateRetainedUtf8 } from "./admission";
|
|
@@ -32,7 +32,9 @@ function crashLogPath(): string {
|
|
|
32
32
|
try {
|
|
33
33
|
recordOwnedConfigPath(dir, join(dir, "crash.log"));
|
|
34
34
|
mkdirSync(dir, { recursive: true });
|
|
35
|
-
} catch {
|
|
35
|
+
} catch (error) {
|
|
36
|
+
// During uninstall the log is skipped (both callers swallow this) rather than recreated.
|
|
37
|
+
if (error instanceof ConfigUninstallInProgressError) throw error;
|
|
36
38
|
/* best-effort: directory usually already exists */
|
|
37
39
|
}
|
|
38
40
|
return join(dir, "crash.log");
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import type { spawn } from "node:child_process";
|
|
2
|
-
import type { accessSync,
|
|
2
|
+
import type { accessSync, statSync } from "node:fs";
|
|
3
3
|
import type { DesktopCliRecordRead, DesktopCliRecordIssue } from "./desktop-cli-record.mjs";
|
|
4
4
|
export type DesktopHandoffIssue = DesktopCliRecordIssue | "target-invalid" | "target-self" | "target-unusable" | "spawn-failed";
|
|
5
5
|
export type DesktopCliHandoffPlan =
|
|
6
|
-
| { kind: "continue"; reason: "excluded" | "missing" | "disabled" | "
|
|
6
|
+
| { kind: "continue"; reason: "excluded" | "missing" | "disabled" | "windows-path-only" }
|
|
7
7
|
| { kind: "error"; issue: DesktopHandoffIssue }
|
|
8
8
|
| { kind: "handoff"; target: string };
|
|
9
9
|
export type DesktopCliHandoffExit =
|
|
10
|
-
| { kind: "continue" }
|
|
11
10
|
| { kind: "error"; issue: "spawn-failed" }
|
|
12
11
|
| { kind: "exit"; code: number; signal: NodeJS.Signals | null };
|
|
13
12
|
export function desktopHandoffExcluded(argv: string[], env?: NodeJS.ProcessEnv): boolean;
|
|
@@ -17,4 +16,4 @@ export function planDesktopCliHandoff(input?: {
|
|
|
17
16
|
}, deps?: { stat?: typeof statSync; access?: typeof accessSync; realpath?: (path: string) => string }): DesktopCliHandoffPlan;
|
|
18
17
|
export function runDesktopCliHandoff(plan: Extract<DesktopCliHandoffPlan, { kind: "handoff" }>, launch: {
|
|
19
18
|
argv: string[]; env: NodeJS.ProcessEnv; proof: string; context: string; onSpawn?: (pid: number) => void;
|
|
20
|
-
}, deps?: { spawn?: typeof spawn;
|
|
19
|
+
}, deps?: { spawn?: typeof spawn; parent?: Pick<NodeJS.Process, "on" | "removeListener">; platform?: NodeJS.Platform }): Promise<DesktopCliHandoffExit>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { accessSync, constants,
|
|
2
|
+
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
|
3
3
|
import { posix, win32 } from "node:path";
|
|
4
4
|
import { readDesktopCliRecord } from "./desktop-cli-record.mjs";
|
|
5
5
|
import { isCodexCliUpdateInspectionArgv } from "../update/codex-cli-update-launch-policy.mjs";
|
|
@@ -45,10 +45,8 @@ export function planDesktopCliHandoff(input = {}, deps = {}) {
|
|
|
45
45
|
if (key(own) === key(physical)) return { kind: "error", issue: "target-self" };
|
|
46
46
|
}
|
|
47
47
|
return { kind: "handoff", target: physical };
|
|
48
|
-
} catch
|
|
49
|
-
return error
|
|
50
|
-
? { kind: "continue", reason: "target-missing" }
|
|
51
|
-
: { kind: "error", issue: "target-unusable" };
|
|
48
|
+
} catch {
|
|
49
|
+
return { kind: "error", issue: "target-unusable" };
|
|
52
50
|
}
|
|
53
51
|
}
|
|
54
52
|
|
|
@@ -56,14 +54,7 @@ export function runDesktopCliHandoff(plan, launch, deps = {}) {
|
|
|
56
54
|
const spawnChild = deps.spawn ?? spawn;
|
|
57
55
|
const parent = deps.parent ?? process;
|
|
58
56
|
const platform = deps.platform ?? process.platform;
|
|
59
|
-
const
|
|
60
|
-
const spawnFailure = error => {
|
|
61
|
-
if (error?.code === "ENOENT") {
|
|
62
|
-
try { lstat(plan.target); }
|
|
63
|
-
catch (checkError) { if (checkError?.code === "ENOENT") return { kind: "continue" }; }
|
|
64
|
-
}
|
|
65
|
-
return { kind: "error", issue: "spawn-failed" };
|
|
66
|
-
};
|
|
57
|
+
const spawnFailure = () => ({ kind: "error", issue: "spawn-failed" });
|
|
67
58
|
const argv = launch.argv.filter(arg => !arg.startsWith(PROOF_PREFIX));
|
|
68
59
|
const env = { ...launch.env, OCX_NO_DESKTOP_HANDOFF: "1", OCX_NODE_LAUNCH_CONTEXT: launch.context };
|
|
69
60
|
delete env.OCX_BUN_RUNTIME_SOURCE;
|
|
@@ -74,8 +65,8 @@ export function runDesktopCliHandoff(plan, launch, deps = {}) {
|
|
|
74
65
|
child = spawnChild(plan.target, [`${PROOF_PREFIX}${launch.proof}`, ...argv], {
|
|
75
66
|
stdio: "inherit", shell: false, windowsHide: true, env,
|
|
76
67
|
});
|
|
77
|
-
} catch
|
|
78
|
-
resolveExit(spawnFailure(
|
|
68
|
+
} catch {
|
|
69
|
+
resolveExit(spawnFailure());
|
|
79
70
|
return;
|
|
80
71
|
}
|
|
81
72
|
const forwarded = platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
@@ -87,7 +78,7 @@ export function runDesktopCliHandoff(plan, launch, deps = {}) {
|
|
|
87
78
|
const clear = () => { for (const [signal, handler] of handlers) parent.removeListener(signal, handler); };
|
|
88
79
|
let done = false;
|
|
89
80
|
const finish = result => { if (done) return; done = true; clear(); resolveExit(result); };
|
|
90
|
-
child.once("error",
|
|
81
|
+
child.once("error", () => finish(spawnFailure()));
|
|
91
82
|
let delegateError = false;
|
|
92
83
|
child.once("exit", (code, signal) => finish(delegateError ? { kind: "error", issue: "spawn-failed" } : { kind: "exit", code: code ?? 1, signal }));
|
|
93
84
|
if (child.pid && launch.onSpawn) {
|
package/src/lib/errors.ts
CHANGED
|
@@ -777,6 +777,7 @@ export function httpStatusFromTerminalError(error: {
|
|
|
777
777
|
if (message && isClientClosedMessage(message)) return 499;
|
|
778
778
|
if (error.type === "invalid_request_error") return 400;
|
|
779
779
|
if (error.type === "proxy_error") return 500;
|
|
780
|
+
if (error.code === "upstream_stall_timeout") return 504;
|
|
780
781
|
// A structured server class must not be downgraded to a CLIENT error by message wording.
|
|
781
782
|
// classifyError assigns `server_error` + `upstream_server_error` to every 5xx it sees, so
|
|
782
783
|
// the class is authoritative about blame: the upstream failed, the caller did not send a
|
|
@@ -20,6 +20,7 @@ export const LOCAL_MANAGEMENT_READ_PATHS = {
|
|
|
20
20
|
providerQuotas: "/api/provider-quotas",
|
|
21
21
|
usageTimeline: "/api/usage/timeline",
|
|
22
22
|
stop: "/api/stop",
|
|
23
|
+
nativeMainAdmission: "/api/native-main-profiles/admission",
|
|
23
24
|
} as const;
|
|
24
25
|
|
|
25
26
|
export type LocalManagementReadPath =
|
|
@@ -52,7 +53,8 @@ function isLocalManagementReadPath(path: string): path is LocalManagementReadPat
|
|
|
52
53
|
|| path === LOCAL_MANAGEMENT_READ_PATHS.startupHealth
|
|
53
54
|
|| path === LOCAL_MANAGEMENT_READ_PATHS.providerQuotas
|
|
54
55
|
|| path === LOCAL_MANAGEMENT_READ_PATHS.usageTimeline
|
|
55
|
-
|| path === LOCAL_MANAGEMENT_READ_PATHS.stop
|
|
56
|
+
|| path === LOCAL_MANAGEMENT_READ_PATHS.stop
|
|
57
|
+
|| path === LOCAL_MANAGEMENT_READ_PATHS.nativeMainAdmission;
|
|
56
58
|
}
|
|
57
59
|
|
|
58
60
|
function localReadCapabilityPayload(
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { carryReplayRefusal, isNonReplayableResponse, markResponseNonReplayable } from "./upstream-retry";
|
|
2
|
+
import {
|
|
3
|
+
ANTHROPIC_ERROR_CODES, ANTHROPIC_ERROR_TYPES, CLAUDE_CONTEXT_OVERFLOW_MESSAGE,
|
|
4
|
+
CLIENT_ERROR_CONTRACTS, clientErrorCodeMessage, actionableRefusalMessage, isProxyError, attachComboFailureEvidence, carryProxyError, proxyErrorPresentation, comboFailureEvidence, markProxyError, type ProxyErrorPresentation, type ClientErrorContract,
|
|
5
|
+
} from "./client-error-body";
|
|
6
|
+
import { classifyUpstreamCondition, upstreamConditionMessage, type UpstreamCondition, type UpstreamConditionEvidence } from "./upstream-condition";
|
|
7
|
+
|
|
8
|
+
type Rec = Record<string, unknown>;
|
|
9
|
+
const STATUS_TYPES: ReadonlyMap<number, string> = new Map([
|
|
10
|
+
[401, "authentication_error"], [402, "billing_error"], [403, "permission_error"],
|
|
11
|
+
[404, "not_found_error"], [409, "conflict_error"], [413, "request_too_large"],
|
|
12
|
+
[429, "rate_limit_error"], [504, "timeout_error"], [529, "overloaded_error"],
|
|
13
|
+
]);
|
|
14
|
+
/** Select the owned sentence from the message this path previously delivered. */
|
|
15
|
+
export function messagesOverflowPresentation(baselineMessage: unknown): boolean {
|
|
16
|
+
if (typeof baselineMessage !== "string") return false;
|
|
17
|
+
const message = baselineMessage.toLowerCase();
|
|
18
|
+
return message.includes("prompt is too long") || message.includes("input is too long for requested model");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Preserve the former JSON role display decision without rendering caller values. */
|
|
22
|
+
export function messagesRolePresentation(role: unknown): { overflow: boolean; coercionFailed: boolean } {
|
|
23
|
+
let overflow = false;
|
|
24
|
+
const active = new WeakSet<unknown[]>();
|
|
25
|
+
const stack: { array: unknown[]; index: number }[] = [];
|
|
26
|
+
let value = role;
|
|
27
|
+
for (;;) {
|
|
28
|
+
if (typeof value === "string") overflow ||= messagesOverflowPresentation(value);
|
|
29
|
+
else if (Array.isArray(value)) {
|
|
30
|
+
if (!active.has(value)) { active.add(value); stack.push({ array: value, index: 0 }); }
|
|
31
|
+
} else if (value !== null && typeof value === "object" && Object.hasOwn(value, "toString")) {
|
|
32
|
+
return { overflow: false, coercionFailed: true };
|
|
33
|
+
}
|
|
34
|
+
let next = false;
|
|
35
|
+
while (stack.length > 0) {
|
|
36
|
+
const frame = stack[stack.length - 1]!;
|
|
37
|
+
if (frame.index < frame.array.length) { value = frame.array[frame.index++]; next = true; break; }
|
|
38
|
+
active.delete(frame.array); stack.pop();
|
|
39
|
+
}
|
|
40
|
+
if (!next) return { overflow, coercionFailed: false };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isMessagesErrorEnvelope(value: unknown): value is Rec {
|
|
45
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
46
|
+
const body = value as Rec;
|
|
47
|
+
const error = body.error;
|
|
48
|
+
return body.type === "error" || (error !== null && typeof error === "object" && !Array.isArray(error)
|
|
49
|
+
&& (typeof (error as Rec).type === "string" || typeof (error as Rec).message === "string"));
|
|
50
|
+
}
|
|
51
|
+
/** Match the SDK's diagnostic selection on the parsed body or non-JSON response text. */
|
|
52
|
+
function messagesErrorDiagnostic(value: unknown, fallback: string | undefined): string | undefined {
|
|
53
|
+
const message = value !== null && typeof value === "object" && Object.hasOwn(value, "message")
|
|
54
|
+
? (value as Rec).message : undefined;
|
|
55
|
+
return message ? typeof message === "string" ? message : JSON.stringify(message)
|
|
56
|
+
: value ? JSON.stringify(value) : fallback;
|
|
57
|
+
}
|
|
58
|
+
export function messagesRelayedOverflowPresentation(text: string, parsed: unknown): boolean {
|
|
59
|
+
return messagesOverflowPresentation(messagesErrorDiagnostic(parsed, text));
|
|
60
|
+
}
|
|
61
|
+
/** The pinned SSE APIError uses the parsed-or-raw whole body and no HTTP fallback. */
|
|
62
|
+
export function messagesSseErrorOverflowPresentation(data: string, parsed: unknown): boolean {
|
|
63
|
+
return messagesOverflowPresentation(messagesErrorDiagnostic(parsed ?? data, undefined) || "(no status code or body)");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface OwnedAnthropicErrorOptions {
|
|
67
|
+
status: number;
|
|
68
|
+
type?: string;
|
|
69
|
+
code?: string;
|
|
70
|
+
evidence: UpstreamConditionEvidence;
|
|
71
|
+
overflow?: boolean;
|
|
72
|
+
contract?: ClientErrorContract;
|
|
73
|
+
condition?: UpstreamCondition;
|
|
74
|
+
/** An object marked by the local producer; serialized fields cannot grant ownership. */
|
|
75
|
+
localError?: { message: string };
|
|
76
|
+
}
|
|
77
|
+
export function ownedAnthropicErrorPayload(options: OwnedAnthropicErrorOptions): Rec {
|
|
78
|
+
const type = ANTHROPIC_ERROR_TYPES.get(options.type ?? "")
|
|
79
|
+
?? STATUS_TYPES.get(options.status) ?? (options.status >= 500 ? "api_error" : "invalid_request_error");
|
|
80
|
+
const code = options.code === "thread_unsupported_request" ? undefined : ANTHROPIC_ERROR_CODES.get(options.code ?? "");
|
|
81
|
+
const message = options.overflow ? CLAUDE_CONTEXT_OVERFLOW_MESSAGE
|
|
82
|
+
: options.localError && isProxyError(options.localError) ? fixedLocalMessage(options.localError, options.evidence.code ?? code, options.evidence.type) ?? options.localError.message
|
|
83
|
+
: actionableRefusalMessage(options.evidence, code ?? null, options.contract)
|
|
84
|
+
?? (options.contract ? CLIENT_ERROR_CONTRACTS[options.contract] : undefined)
|
|
85
|
+
?? (options.condition ? upstreamConditionMessage(options.condition) : undefined)
|
|
86
|
+
?? clientErrorCodeMessage(code)
|
|
87
|
+
?? upstreamConditionMessage(classifyUpstreamCondition(options.evidence) ?? "upstream_failed");
|
|
88
|
+
return { type: "error", error: { type, message, ...(code ? { code } : {}) } };
|
|
89
|
+
}
|
|
90
|
+
export function ownedAnthropicErrorResponse(options: OwnedAnthropicErrorOptions, legacy?: Rec): Response {
|
|
91
|
+
const response = Response.json(ownedAnthropicErrorPayload(options), { status: options.status, headers: { "Content-Type": "application/json" } });
|
|
92
|
+
return legacy === undefined ? response : attachComboFailureEvidence(response, JSON.stringify(legacy));
|
|
93
|
+
}
|
|
94
|
+
/** Admission and presentation use separate numbers; this bounds display only. */
|
|
95
|
+
export function boundedMessagesDisplayCount(value: number): string | undefined {
|
|
96
|
+
return Number.isSafeInteger(value) && value >= 0 && value <= 1e12 ? String(value) : undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const METHOD: ReadonlyMap<string, string> = new Map(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT", "TRACE"].map(method => [method, method]));
|
|
100
|
+
const MESSAGES_PATH: ReadonlyMap<string, string> = new Map([["/v1/messages", "/v1/messages"], ["/v1/messages/count_tokens", "/v1/messages/count_tokens"]]);
|
|
101
|
+
/** Other listeners retain their own endpoint diagnostics. */
|
|
102
|
+
export function messagesUnknownEndpointMessage(req: Request): string {
|
|
103
|
+
const path = new URL(req.url).pathname;
|
|
104
|
+
const localPath = MESSAGES_PATH.get(path);
|
|
105
|
+
return localPath ? `Unknown endpoint: ${METHOD.get(req.method) ?? "unsupported"} ${localPath}`
|
|
106
|
+
: `Unknown endpoint: ${req.method} ${path}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Surface projection uses construction metadata; shared producer bodies retain their own wire. */
|
|
110
|
+
const FIXED_MESSAGES: ReadonlyMap<ProxyErrorPresentation, string> = new Map([
|
|
111
|
+
["roster", "The selected Google Antigravity account does not list the requested model. Choose a model your accounts list, select an account with access, or review account failover settings before retrying."],
|
|
112
|
+
["pacing", "The provider request queue is full or has expired. Wait for queued requests to finish, then retry."],
|
|
113
|
+
["input", "The input exceeds the configured admission limit. Start a new session or choose a model with a larger input limit."],
|
|
114
|
+
["outbound", "The provider request body exceeds the configured limit. Reduce the request size before retrying."],
|
|
115
|
+
["inbound", "The request body exceeds the configured limit. Reduce the request size before retrying."],
|
|
116
|
+
["send", "request send budget exhausted before dispatch"],
|
|
117
|
+
["cooldown", "The selected Codex account is cooling down. Run 'ocx account list openai' to find the id, then 'ocx account clear-cooldown openai <id>' to lift it, or switch accounts with 'ocx account use openai <id>'."],
|
|
118
|
+
["cooldown_pinned", "The selected Codex account is cooling down. This request is pinned to that selector and will not switch accounts; choose another account-qualified model or retry later."],
|
|
119
|
+
["hard_lock", "Codex main account is blocked by the main-account quota policy. Choose another account, wait for quota to reset, or disable codexMainAccountHardLock in Settings."],
|
|
120
|
+
["recovery", "The selected Codex account is held after repeated upstream failures and the pool's recovery budget for this window is spent, so nothing was sent upstream. Retry later. This clears on its own as the account recovers; no cooldown to lift and no account to switch."],
|
|
121
|
+
["usage", "The configured account usage limit was reached. Wait for its reset or adjust the usage limits before retrying."],
|
|
122
|
+
["model_availability", "The requested model is unavailable for the selected account. Choose a supported model or retry when it becomes available."],
|
|
123
|
+
["oauth_login", "The configured provider needs sign-in. Run ocx login for that provider, then retry."],
|
|
124
|
+
["discovery", "Antigravity login could not discover a Cloud Code Assist project for this account. Ensure the account has Antigravity/Cloud Code Assist access and try again."],
|
|
125
|
+
["muse_http", "The Muse Code credential was rejected by the Meta Model API. Renew it with `muse login` or copy it again from https://dev.meta.ai, then retry."],
|
|
126
|
+
["config", "The configured OAuth provider is unsupported. Remove or reconfigure the provider in the OpenCodex configuration."],
|
|
127
|
+
["workflow", "The configured token ceiling is spent, so this send was refused before contacting a provider. Review the task, account and pool spending limits to grant more."],
|
|
128
|
+
["workflow_unbound", "The configured token ceiling is spent, including unassigned provider-pool history. Resolve verified pool mappings or adjust the spending limits before retrying."],
|
|
129
|
+
["scope", "The requested model is not allowed for this API key."],
|
|
130
|
+
["body_stall", "anthropic passthrough body stalled: no upstream bytes arrived before the configured timeout"],
|
|
131
|
+
["body_overflow", "anthropic passthrough body exceeded the safe limit"],
|
|
132
|
+
["combo", "No available targets for combo; review target availability, quota and cooldowns before retrying."],
|
|
133
|
+
["pool_refresh", "Codex credential refresh did not complete for the selected Codex pool account; retry this request. If it keeps failing, sign in to that account again."],
|
|
134
|
+
["copilot", "GitHub Copilot Auto negotiation failed; retry or check your Copilot account permissions."],
|
|
135
|
+
]);
|
|
136
|
+
const LOCAL_CODES: ReadonlyMap<string, ProxyErrorPresentation> = new Map([
|
|
137
|
+
["request_send_budget_exhausted", "send"], ["send_budget_exhausted", "send"], ["model_not_allowed_for_key", "scope"],
|
|
138
|
+
]);
|
|
139
|
+
function fixedLocalMessage(local: object, code?: string, type?: string): string | undefined {
|
|
140
|
+
const kind = proxyErrorPresentation(local) ?? LOCAL_CODES.get(code ?? "") ?? LOCAL_CODES.get(type ?? "");
|
|
141
|
+
return kind === undefined ? undefined : FIXED_MESSAGES.get(kind);
|
|
142
|
+
}
|
|
143
|
+
function isMessagesRequest(req: Request): boolean {
|
|
144
|
+
const path = new URL(req.url).pathname;
|
|
145
|
+
return path === "/v1/messages" || path === "/v1/messages/count_tokens";
|
|
146
|
+
}
|
|
147
|
+
export async function normalizeMessagesProxyRefusal(req: Request, response: Response): Promise<Response> {
|
|
148
|
+
if (!isMessagesRequest(req) || response.ok || !isProxyError(response)) return response;
|
|
149
|
+
const kind = proxyErrorPresentation(response);
|
|
150
|
+
if (kind === undefined) return response;
|
|
151
|
+
const message = FIXED_MESSAGES.get(kind);
|
|
152
|
+
if (message === undefined) throw new Error("Unknown local Messages presentation");
|
|
153
|
+
const original = await response.clone().json() as Rec;
|
|
154
|
+
const error = original.error as Rec;
|
|
155
|
+
const next = { ...error, message: messagesOverflowPresentation(error.message) ? CLAUDE_CONTEXT_OVERFLOW_MESSAGE : message };
|
|
156
|
+
if (kind === "scope") delete (next as Rec).model;
|
|
157
|
+
const headers = new Headers(response.headers); headers.delete("content-length");
|
|
158
|
+
const out = carryProxyError(response, carryReplayRefusal(response, new Response(JSON.stringify({ ...original, error: next }), { status: response.status, headers })));
|
|
159
|
+
if (isNonReplayableResponse(response)) markResponseNonReplayable(out);
|
|
160
|
+
const evidence = comboFailureEvidence(response);
|
|
161
|
+
return evidence === undefined ? out : attachComboFailureEvidence(out, evidence);
|
|
162
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { markProxyError, UNDECLARED_TOOL_CALL_MESSAGE } from "./client-error-body";
|
|
2
|
+
import { messagesOverflowPresentation, messagesSseErrorOverflowPresentation, ownedAnthropicErrorPayload } from "./messages-error-body";
|
|
3
|
+
import { sseFieldValue } from "./sse-decoder";
|
|
4
|
+
|
|
5
|
+
export const MESSAGES_SSE_ERROR_HOLD_BYTES = 1024 * 1024;
|
|
6
|
+
export type MessagesSseLocalOrigin = "guard" | "eof" | "stop-error" | "stall" | "cap" | "read";
|
|
7
|
+
type Rec = Record<string, unknown>;
|
|
8
|
+
const record = (value: unknown): Rec => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Rec : {};
|
|
9
|
+
const encoder = new TextEncoder();
|
|
10
|
+
const overLimit = markProxyError({ message: "The provider stream reported an error." });
|
|
11
|
+
export function messagesSseErrorPayload(data: string): string {
|
|
12
|
+
let parsed: unknown;
|
|
13
|
+
try { parsed = JSON.parse(data); } catch { parsed = undefined; }
|
|
14
|
+
const body = record(parsed), nested = body.error;
|
|
15
|
+
// A null, scalar or array error member carries no fields; read the top-level ones, as the buffered paths do.
|
|
16
|
+
const error = nested !== null && typeof nested === "object" && !Array.isArray(nested) ? nested as Rec : body;
|
|
17
|
+
return JSON.stringify(ownedAnthropicErrorPayload({ status: 502,
|
|
18
|
+
type: typeof error.type === "string" ? error.type : "api_error",
|
|
19
|
+
code: typeof error.code === "string" ? error.code : undefined,
|
|
20
|
+
evidence: { status: 502, type: typeof error.type === "string" ? error.type : undefined,
|
|
21
|
+
code: typeof error.code === "string" ? error.code : undefined,
|
|
22
|
+
message: typeof error.message === "string" ? error.message : undefined },
|
|
23
|
+
overflow: messagesSseErrorOverflowPresentation(data, parsed),
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
export function messagesSseOversizePayload(): string {
|
|
27
|
+
return JSON.stringify(ownedAnthropicErrorPayload({ status: 502, type: "api_error", evidence: { status: 502 }, localError: overLimit }));
|
|
28
|
+
}
|
|
29
|
+
const localMessages: Readonly<Record<MessagesSseLocalOrigin, string>> = {
|
|
30
|
+
guard: UNDECLARED_TOOL_CALL_MESSAGE,
|
|
31
|
+
eof: "anthropic passthrough upstream stream ended before message_stop",
|
|
32
|
+
"stop-error": 'upstream ended the turn with stop_reason "error"',
|
|
33
|
+
stall: "anthropic passthrough body stalled: no upstream bytes arrived before the configured timeout",
|
|
34
|
+
cap: "anthropic passthrough body exceeded the safe limit",
|
|
35
|
+
read: "anthropic passthrough upstream stream failed",
|
|
36
|
+
};
|
|
37
|
+
export function messagesSseLocalFrame(origin: MessagesSseLocalOrigin, originalMessage: string): Uint8Array {
|
|
38
|
+
const local = markProxyError({ message: localMessages[origin] }, origin === "stall" ? "body_stall" : origin === "cap" ? "body_overflow" : undefined);
|
|
39
|
+
const payload = ownedAnthropicErrorPayload({ status: 502, type: origin === "stall" ? "timeout_error" : "api_error",
|
|
40
|
+
code: origin === "guard" ? "undeclared_tool_call" : undefined, evidence: { status: 502 },
|
|
41
|
+
overflow: messagesOverflowPresentation(originalMessage), localError: local });
|
|
42
|
+
return encoder.encode(`${origin === "guard" ? "" : "\n\n"}event: error\ndata: ${JSON.stringify(payload)}\n\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The echo flag comes from the original field order, never the parsed payload. */
|
|
46
|
+
export function messagesSseEchoRenamedError(frame: string): boolean {
|
|
47
|
+
const lines = frame.split(/\r\n|\r|\n/).filter(line => line !== "" && !line.startsWith(":"));
|
|
48
|
+
return sseFieldValue(lines[0] ?? "", "event") === "error"
|
|
49
|
+
&& lines.map(line => sseFieldValue(line, "event")).filter(value => value !== null).at(-1) === "error";
|
|
50
|
+
}
|
|
51
|
+
export type MessagesSseFrameOrigin = { echoRenamedError: true } | { client: Uint8Array };
|
|
52
|
+
/** One request's complete-frame handoffs. Input bytes alone can never create an origin. */
|
|
53
|
+
export class MessagesSseFrameContext {
|
|
54
|
+
private readonly frames = new WeakMap<Uint8Array, MessagesSseFrameOrigin>();
|
|
55
|
+
register(bytes: Uint8Array, origin: MessagesSseFrameOrigin): Uint8Array { this.frames.set(bytes, origin); return bytes; }
|
|
56
|
+
take(bytes: Uint8Array): MessagesSseFrameOrigin | undefined {
|
|
57
|
+
const origin = this.frames.get(bytes); this.frames.delete(bytes); return origin;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export interface MessagesSseFrameHooks {
|
|
61
|
+
input(bytes: Uint8Array, empty: boolean, tailLineFeed?: boolean, continuation?: boolean): void;
|
|
62
|
+
output(original: string, bytes: Uint8Array): void;
|
|
63
|
+
dispose(): void;
|
|
64
|
+
}
|
|
65
|
+
/** Only a dedicated, complete producer frame may traverse a buffering stage. */
|
|
66
|
+
export function messagesSseFrameHooks(context: MessagesSseFrameContext): MessagesSseFrameHooks {
|
|
67
|
+
let pending: { digest: string; origin: MessagesSseFrameOrigin; repair?: boolean } | undefined;
|
|
68
|
+
const digest = (value: string | Uint8Array, prefix = "") => new Bun.CryptoHasher("sha256").update(prefix).update(value).digest("hex");
|
|
69
|
+
const broken = () => new Error("The proxy could not reach or read the provider.");
|
|
70
|
+
return {
|
|
71
|
+
input(bytes, empty, tailLineFeed = false, continuation = false) {
|
|
72
|
+
const origin = context.take(bytes);
|
|
73
|
+
if (!origin) return;
|
|
74
|
+
if (pending) throw broken();
|
|
75
|
+
if ("client" in origin && bytes[0] === 10 && bytes[1] === 10) {
|
|
76
|
+
const prefix = tailLineFeed || empty && continuation ? "\n" : "";
|
|
77
|
+
pending = { digest: digest(bytes.subarray(2), prefix),
|
|
78
|
+
origin: { client: encoder.encode(prefix + new TextDecoder().decode(origin.client.subarray(2))) },
|
|
79
|
+
repair: !(empty && continuation) };
|
|
80
|
+
} else {
|
|
81
|
+
if (!empty) throw broken();
|
|
82
|
+
pending = { digest: digest(bytes), origin };
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
output(original, bytes) {
|
|
86
|
+
if (!pending) return;
|
|
87
|
+
if (pending.repair) { pending.repair = false; return; }
|
|
88
|
+
if (digest(original) !== pending.digest) { pending = undefined; throw broken(); }
|
|
89
|
+
context.register(bytes, pending.origin); pending = undefined;
|
|
90
|
+
},
|
|
91
|
+
dispose() { pending = undefined; },
|
|
92
|
+
};
|
|
93
|
+
}
|
package/src/lib/passive-read.ts
CHANGED
|
@@ -23,13 +23,18 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
25
25
|
|
|
26
|
-
const passive = new AsyncLocalStorage<
|
|
26
|
+
const passive = new AsyncLocalStorage<{ onDiagnostic?: (message: string) => void }>();
|
|
27
27
|
|
|
28
28
|
/** Run a management read passively, including everything it awaits or schedules. */
|
|
29
|
-
export function runPassiveRead<T>(run: () => Promise<T
|
|
30
|
-
return passive.run(
|
|
29
|
+
export function runPassiveRead<T>(run: () => Promise<T>, options: { onDiagnostic?: (message: string) => void } = {}): Promise<T> {
|
|
30
|
+
return passive.run(options, run);
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
export function isPassiveRead(): boolean {
|
|
34
|
-
return passive.getStore()
|
|
34
|
+
return passive.getStore() !== undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Deliver an optional read-only diagnostic without affecting other passive callers. */
|
|
38
|
+
export function passiveReadDiagnostic(message: string): void {
|
|
39
|
+
passive.getStore()?.onDiagnostic?.(message);
|
|
35
40
|
}
|
package/src/lib/socks5-fetch.ts
CHANGED
|
@@ -256,9 +256,13 @@ class SocketReader {
|
|
|
256
256
|
if (preserveBuffered && !this.ended && !this.socket.destroyed && this.buffer.byteLength > 0) {
|
|
257
257
|
this.socket.unshift(this.buffer);
|
|
258
258
|
}
|
|
259
|
+
// A read continuation may resume after cleanup; it must not enqueue a new waiter
|
|
260
|
+
// after the socket listeners that could settle it have been removed.
|
|
261
|
+
this.ended = true;
|
|
262
|
+
this.failure ??= new Socks5FetchError("SOCKS5 reader disposed");
|
|
259
263
|
this.buffer = Buffer.alloc(0);
|
|
260
|
-
this.rejectExact(
|
|
261
|
-
this.rejectAny(
|
|
264
|
+
this.rejectExact(this.failure);
|
|
265
|
+
this.rejectAny(this.failure);
|
|
262
266
|
}
|
|
263
267
|
}
|
|
264
268
|
|
|
@@ -267,19 +271,21 @@ async function socks5Connect(proxy: string, target: URL, signal?: AbortSignal):
|
|
|
267
271
|
const credentials = socks5Credentials(parsedProxy);
|
|
268
272
|
const proxyHost = parsedProxy.hostname.replace(/^\[|\]$/g, "");
|
|
269
273
|
const socket = await connectSocket(proxyHost, Number(parsedProxy.port) || DEFAULT_SOCKS5_PORT, signal);
|
|
270
|
-
|
|
274
|
+
const onHandshakeTimeout = () => {
|
|
271
275
|
socket.destroy(new Socks5FetchError("SOCKS5 handshake timed out"));
|
|
272
|
-
}
|
|
276
|
+
};
|
|
277
|
+
socket.setTimeout(SOCKS5_CONNECT_TIMEOUT_MS, onHandshakeTimeout);
|
|
273
278
|
const reader = new SocketReader(socket);
|
|
274
279
|
try {
|
|
275
280
|
await socks5Handshake(reader, { host: target.hostname, port: targetPort(target) }, credentials, signal);
|
|
276
|
-
socket.setTimeout(0);
|
|
277
281
|
return socket;
|
|
278
282
|
} catch (error) {
|
|
279
283
|
socket.destroy();
|
|
280
284
|
if (error instanceof Socks5HandshakeError) throw new Socks5FetchError(error.message);
|
|
281
285
|
throw error;
|
|
282
286
|
} finally {
|
|
287
|
+
socket.setTimeout(0);
|
|
288
|
+
socket.removeListener("timeout", onHandshakeTimeout);
|
|
283
289
|
reader.dispose(true);
|
|
284
290
|
}
|
|
285
291
|
}
|
|
@@ -420,10 +426,12 @@ function responseBody(
|
|
|
420
426
|
headers: Headers,
|
|
421
427
|
status: number,
|
|
422
428
|
method: string,
|
|
429
|
+
onResponseTimeout: () => void,
|
|
423
430
|
): ReadableStream<Uint8Array> | null {
|
|
424
431
|
if (bodylessResponse(method, status)) {
|
|
425
432
|
reader.dispose();
|
|
426
433
|
socket.setTimeout(0);
|
|
434
|
+
socket.removeListener("timeout", onResponseTimeout);
|
|
427
435
|
socket.destroy();
|
|
428
436
|
return null;
|
|
429
437
|
}
|
|
@@ -443,6 +451,7 @@ function responseBody(
|
|
|
443
451
|
signal.removeEventListener("abort", onAbort);
|
|
444
452
|
reader.dispose();
|
|
445
453
|
socket.setTimeout(0);
|
|
454
|
+
socket.removeListener("timeout", onResponseTimeout);
|
|
446
455
|
socket.destroy();
|
|
447
456
|
};
|
|
448
457
|
const onAbort = () => socket.destroy();
|
|
@@ -677,12 +686,13 @@ export async function socks5Fetch(
|
|
|
677
686
|
// Pending reads carry the abort reason; destruction must not enqueue an
|
|
678
687
|
// unhandled socket error after their listeners have been removed.
|
|
679
688
|
const onAbort = () => socket.destroy();
|
|
689
|
+
const onResponseTimeout = () => {
|
|
690
|
+
socket.destroy(new Socks5FetchError("SOCKS5 upstream request timed out"));
|
|
691
|
+
};
|
|
680
692
|
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
681
693
|
try {
|
|
682
694
|
if (target.protocol === "https:") socket = await secureSocket(tunnel, target, request.signal);
|
|
683
|
-
socket.setTimeout(SOCKS5_RESPONSE_TIMEOUT_MS,
|
|
684
|
-
socket.destroy(new Socks5FetchError("SOCKS5 upstream request timed out"));
|
|
685
|
-
});
|
|
695
|
+
socket.setTimeout(SOCKS5_RESPONSE_TIMEOUT_MS, onResponseTimeout);
|
|
686
696
|
// Observe socket errors and early responses while uploading, not only after it.
|
|
687
697
|
reader = new SocketReader(socket);
|
|
688
698
|
const headers = requestHeaders(request, target);
|
|
@@ -706,7 +716,7 @@ export async function socks5Fetch(
|
|
|
706
716
|
const codingFormat = bodylessResponse(request.method, responseHead.status)
|
|
707
717
|
? undefined
|
|
708
718
|
: contentCodingFormat(responseHead.headers);
|
|
709
|
-
const body = responseBody(reader, socket, request.signal, responseHead.headers, responseHead.status, request.method);
|
|
719
|
+
const body = responseBody(reader, socket, request.signal, responseHead.headers, responseHead.status, request.method, onResponseTimeout);
|
|
710
720
|
const responseHeaders = new Headers(responseHead.headers);
|
|
711
721
|
if (codingFormat !== undefined) {
|
|
712
722
|
responseHeaders.delete("content-encoding");
|
|
@@ -729,6 +739,8 @@ export async function socks5Fetch(
|
|
|
729
739
|
} catch (error) {
|
|
730
740
|
request.signal.removeEventListener("abort", onAbort);
|
|
731
741
|
reader?.dispose();
|
|
742
|
+
socket.setTimeout(0);
|
|
743
|
+
socket.removeListener("timeout", onResponseTimeout);
|
|
732
744
|
socket.destroy();
|
|
733
745
|
// An aborted caller gets its own reason back. Several waiters inside this transport can win
|
|
734
746
|
// the race that settles an abort, and they do not agree on what to do with a reason they
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* the shared abort helpers from here).
|
|
17
17
|
*/
|
|
18
18
|
import { clearableDeadline } from "./abort";
|
|
19
|
+
import { isDefiniteContextOverflow } from "./context-overflow-verdict";
|
|
19
20
|
import { errorDestinationLabel, errorDestinationText, type ErrorDestinationLabel } from "./error-destination";
|
|
20
21
|
export { errorDestinationLabel, providerErrorDestinationLabel, errorDestinationText } from "./error-destination";
|
|
21
22
|
import { redactSecretString } from "./redact";
|
|
@@ -721,6 +722,82 @@ export async function fetchWithResetRetry(
|
|
|
721
722
|
} finally { opts.onSendsConsumed?.close?.(); }
|
|
722
723
|
}
|
|
723
724
|
|
|
725
|
+
/** Bytes of a 5xx body read to look for a context-overflow verdict; the verdict caps its input too. */
|
|
726
|
+
const CONTEXT_OVERFLOW_PEEK_BYTES = 16_384;
|
|
727
|
+
/** A body that has not arrived by then is not evidence; the peek must never stall the retry. */
|
|
728
|
+
const CONTEXT_OVERFLOW_PEEK_MS = 250;
|
|
729
|
+
// A hypothetical, negated, or configuration-failure mention does not justify suppressing a retry.
|
|
730
|
+
// Inspect the unwrapped provider message, not its JSON spelling or unrelated envelope fields.
|
|
731
|
+
const NON_VERDICT_CONTEXT = /(?:\b(?:not|never|no|neither|nor|if|unless|whether)\b|n['\u2019]t\b)[^.!?\n]{0,100}\b(?:context(?:\s+(?:window|length))?|tokens?|(?:input|prompt)\s+is\s+too\s+long)\b|\b(?:context\s+(?:window|length)|token\s+limit|(?:input|prompt)\s+is\s+too\s+long)\b[^.!?\n]{0,40}\?/i;
|
|
732
|
+
const CONTEXT_CONFIG_FAILURE = /\b(?:fail(?:ed|ure)?|unable|cannot|error)\b[^.!?\n]{0,100}\b(?:configuration|settings|documentation)\b|\b(?:configuration|settings|documentation)\b[^.!?\n]{0,100}\b(?:fail(?:ed|ure)?|unavailable|missing|error)\b/i;
|
|
733
|
+
const CONTEXT_THROUGHPUT = /\bper (?:second|minute|hour|day)\b|\brate limit|\bquota\b|\btpm\b/i;
|
|
734
|
+
|
|
735
|
+
function retryContextOverflowMessage(message: string): boolean {
|
|
736
|
+
if (CONTEXT_THROUGHPUT.test(message)) return false;
|
|
737
|
+
return message.split(/(?<=[.!?])\s+|[\r\n]+/).some(sentence => {
|
|
738
|
+
if (NON_VERDICT_CONTEXT.test(sentence) || CONTEXT_CONFIG_FAILURE.test(sentence)) return false;
|
|
739
|
+
const withoutGenericThrottle = sentence.replace(/too many tokens/gi, "");
|
|
740
|
+
return isDefiniteContextOverflow(503, withoutGenericThrottle)
|
|
741
|
+
|| /\bprompt is too long\b/i.test(sentence);
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** Up to `maxBytes` of a clone of the body, or what arrived before the deadline. */
|
|
746
|
+
async function peekBodyText(res: Response, maxBytes: number, deadlineMs: number, signal?: AbortSignal): Promise<string> {
|
|
747
|
+
const reader = res.clone().body?.getReader();
|
|
748
|
+
if (!reader) return "";
|
|
749
|
+
const decoder = new TextDecoder();
|
|
750
|
+
let text = "";
|
|
751
|
+
let bytes = 0;
|
|
752
|
+
let emptyChunks = 0;
|
|
753
|
+
const deadlineAt = performance.now() + deadlineMs;
|
|
754
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
755
|
+
let stop = () => {};
|
|
756
|
+
const timedOut = new Promise<null>(resolve => {
|
|
757
|
+
stop = () => resolve(null);
|
|
758
|
+
timer = setTimeout(stop, deadlineMs);
|
|
759
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
760
|
+
if (signal?.aborted) stop();
|
|
761
|
+
});
|
|
762
|
+
try {
|
|
763
|
+
while (bytes < maxBytes) {
|
|
764
|
+
if (signal?.aborted || performance.now() >= deadlineAt) break;
|
|
765
|
+
const chunk = await Promise.race([reader.read(), timedOut]);
|
|
766
|
+
if (!chunk || chunk.done) break;
|
|
767
|
+
if (chunk.value.byteLength === 0) {
|
|
768
|
+
if (++emptyChunks % 64 === 0) await new Promise<void>(resolve => setTimeout(resolve, 0));
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
emptyChunks = 0;
|
|
772
|
+
const bounded = chunk.value.subarray(0, maxBytes - bytes);
|
|
773
|
+
bytes += bounded.byteLength;
|
|
774
|
+
text += decoder.decode(bounded, { stream: true });
|
|
775
|
+
}
|
|
776
|
+
return text;
|
|
777
|
+
} finally {
|
|
778
|
+
clearTimeout(timer);
|
|
779
|
+
signal?.removeEventListener("abort", stop);
|
|
780
|
+
reader.cancel().catch(() => {});
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* True when a transient-status response's body is a definite context-overflow verdict. Peeks a
|
|
786
|
+
* clone within a byte and time bound, so the caller still receives the untouched body. A slow
|
|
787
|
+
* or endless body keeps the normal retry unless its observed prefix already proves overflow.
|
|
788
|
+
* "Too many tokens" alone is not enough here: a 5xx
|
|
789
|
+
* "Too many tokens, please wait" is a throttle that the retry exists for.
|
|
790
|
+
*/
|
|
791
|
+
async function isContextOverflowResponse(res: Response, signal?: AbortSignal): Promise<boolean> {
|
|
792
|
+
if ((res.headers.get("content-type") ?? "").includes("text/event-stream")) return false;
|
|
793
|
+
try {
|
|
794
|
+
const text = await peekBodyText(res, CONTEXT_OVERFLOW_PEEK_BYTES, CONTEXT_OVERFLOW_PEEK_MS, signal);
|
|
795
|
+
return text.length > 0 && isDefiniteContextOverflow(res.status, text, retryContextOverflowMessage);
|
|
796
|
+
} catch {
|
|
797
|
+
return false;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
724
801
|
/**
|
|
725
802
|
* fetchWithResetRetry plus the caller-selected transient-5xx policy, PRE-STREAM only.
|
|
726
803
|
* A received HTTP error follows that policy; an ambiguous reset's non-replayable
|
|
@@ -782,10 +859,13 @@ export async function fetchWithTransientRetry(
|
|
|
782
859
|
// thing about its own failure, so the ladder stops and hands the response back untouched.
|
|
783
860
|
if (res.ok || !isTransientUpstreamStatus(res.status) || isNonReplayableResponse(res)
|
|
784
861
|
|| res.headers.get(REPLAY_REFUSAL_NO_RETRY_HEADER) === REPLAY_REFUSAL_NO_RETRY_VALUE) return res;
|
|
862
|
+
if (opts.abortSignal?.aborted || Date.now() - attemptStart > slowAttemptMs) return res;
|
|
863
|
+
// A 5xx that says the input does not fit is deterministic: resending the same body is
|
|
864
|
+
// refused the same way, so it goes back for the caller to classify (#8127).
|
|
865
|
+
if (await isContextOverflowResponse(res, opts.abortSignal)) return res;
|
|
785
866
|
// Checked before cancelResponseBodyBestEffort so an already-aborted caller never receives
|
|
786
867
|
// a response whose body we just cancelled.
|
|
787
868
|
if (opts.abortSignal?.aborted) return res;
|
|
788
|
-
if (Date.now() - attemptStart > slowAttemptMs) return res;
|
|
789
869
|
const instructedDelay = retryAfterDelayMs(res.headers);
|
|
790
870
|
// The deadline is the CALLER'S, not this module's default. Reading the constant directly
|
|
791
871
|
// broke it in both directions: a caller with a 30s budget slept the full 45s an upstream
|