@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
package/src/claude/outbound.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import type { UpstreamConditionEvidence } from "../lib/upstream-condition";
|
|
2
|
+
import { ownedAnthropicErrorPayload, messagesOverflowPresentation } from "../lib/messages-error-body";
|
|
3
|
+
import { proxyMessagePresentation, markProxyError, hasProxyErrorMessage, hasProxyIncomplete } from "../lib/client-error-body";
|
|
4
|
+
import { admitMessagesFailure, collectMessagesFailure, type MessagesFailureVerdictSink } from "./failure-verdict";
|
|
1
5
|
import { anthropicProgressEnvelope, isAnthropicProgressMirror } from "../responses/anthropic-progress";
|
|
2
6
|
/**
|
|
3
7
|
* Claude Code outbound: internal /v1/responses output -> Anthropic Messages API shapes.
|
|
@@ -133,7 +137,8 @@ export function isThroughputLimitText(message: string): boolean {
|
|
|
133
137
|
}
|
|
134
138
|
|
|
135
139
|
/** Codes that say nothing about the cause, so the message decides (#8127). */
|
|
136
|
-
|
|
140
|
+
/** Generic 5xx responses use `upstream_server_error`; 503 uses `server_is_overloaded`. */
|
|
141
|
+
const GENERIC_FAILURE_CODES: ReadonlySet<string> = new Set(["server_error", "upstream_error", "upstream_server_error", "api_error", "internal_error"]);
|
|
137
142
|
const NON_OVERFLOW_ERROR_TYPES: ReadonlySet<string> = new Set(["rate_limit_error", "authentication_error", "permission_error"]);
|
|
138
143
|
const NON_OVERFLOW_STATUSES: ReadonlySet<number> = new Set([401, 403, 429]);
|
|
139
144
|
/**
|
|
@@ -157,8 +162,10 @@ function assertsOverflow(message: string): boolean {
|
|
|
157
162
|
if (tooLong && !NEGATION_RE.test(tooLong[1] ?? "") && !CONDITIONAL_LEAD_RE.test(text.slice(0, tooLong.index))) return true;
|
|
158
163
|
const counts = STATED_COUNTS_RE.exec(text);
|
|
159
164
|
if (counts && Number(counts[2]) > Number(counts[1])) return true;
|
|
160
|
-
const exceeds
|
|
161
|
-
|
|
165
|
+
for (const exceeds of text.matchAll(new RegExp(EXCEEDS_TEXT_RE, "gi"))) {
|
|
166
|
+
if (!NEGATION_RE.test(exceeds[0]) && !CONDITIONAL_LEAD_RE.test(text.slice(0, exceeds.index))) return true;
|
|
167
|
+
}
|
|
168
|
+
return false;
|
|
162
169
|
}
|
|
163
170
|
|
|
164
171
|
/**
|
|
@@ -427,6 +434,8 @@ export function responsesSseToAnthropicSse(
|
|
|
427
434
|
model: string,
|
|
428
435
|
opts: {
|
|
429
436
|
pingIntervalMs?: number;
|
|
437
|
+
failureVerdictSink?: MessagesFailureVerdictSink;
|
|
438
|
+
proxyErrorContext?: object;
|
|
430
439
|
translatorBudget: TranslatorBudget;
|
|
431
440
|
/**
|
|
432
441
|
* This proxy's count of the prompt it forwarded, published on `message_start` only when the
|
|
@@ -479,12 +488,13 @@ export function responsesSseToAnthropicSse(
|
|
|
479
488
|
|
|
480
489
|
return new ReadableStream<Uint8Array>({
|
|
481
490
|
start(controller) {
|
|
482
|
-
const emit = (name: string, data: Rec) => {
|
|
491
|
+
const emit = (name: string, data: Rec, admissionData: Rec = data) => {
|
|
483
492
|
const frame = encoder.encode(sseFrame(name, data));
|
|
484
|
-
const
|
|
493
|
+
const admittedBytes = admissionData === data ? frame.byteLength : Buffer.byteLength(sseFrame(name, admissionData));
|
|
494
|
+
const reservation = translatorBudget.reserveTransient(admittedBytes, { kind: "live_transient" });
|
|
485
495
|
controller.enqueue(frame);
|
|
486
496
|
reservation.commitRetained();
|
|
487
|
-
queuedLiveFrameBytes.push(
|
|
497
|
+
queuedLiveFrameBytes.push(admittedBytes);
|
|
488
498
|
};
|
|
489
499
|
const ensureStarted = () => {
|
|
490
500
|
if (started) return;
|
|
@@ -588,11 +598,20 @@ export function responsesSseToAnthropicSse(
|
|
|
588
598
|
// (devlog/_plan/260716_claudecode_hardening/020). On win32 mid-stream socket
|
|
589
599
|
// resets reach the reader catch (no failed-tail relay) and stay api_error —
|
|
590
600
|
// same as today, deliberate residual.
|
|
591
|
-
const fail = (status: number, message: string, upstreamDerived = false, code?: string) => {
|
|
601
|
+
const fail = (status: number, message: string, upstreamDerived = false, code?: string, local = false, contract?: "stream_incomplete" | "transport_failed", evidence?: UpstreamConditionEvidence) => {
|
|
592
602
|
// finish/fail sets terminated before closeOpenBlock. A closure-time
|
|
593
603
|
// allocation failure must still emit one error, without retrying closure.
|
|
594
604
|
if (terminated && (code !== "translation_buffer_limit" || terminalDelivered)) return;
|
|
595
605
|
terminated = true;
|
|
606
|
+
const type = code === "translation_buffer_limit" ? "request_too_large"
|
|
607
|
+
: upstreamDerived && isTransientUpstreamStatus(status) ? "overloaded_error" : anthropicErrorType(status);
|
|
608
|
+
const legacy = anthropicErrorBody(status, message, type, code);
|
|
609
|
+
const payload = ownedAnthropicErrorPayload({ status, type, code, evidence: evidence ?? { status, message },
|
|
610
|
+
overflow: messagesOverflowPresentation((legacy.error as Rec).message),
|
|
611
|
+
condition: code === "context_length_exceeded" && isThroughputLimitText(message) ? "rate_limited" : undefined, contract,
|
|
612
|
+
...(local ? { localError: markProxyError({ message }, proxyMessagePresentation(opts.proxyErrorContext, message, { type: evidence?.type, code: evidence?.code ?? code })) } : {}),
|
|
613
|
+
});
|
|
614
|
+
const admitted = () => admitMessagesFailure(opts.failureVerdictSink, payload, legacy);
|
|
596
615
|
if (code === "translation_buffer_limit") {
|
|
597
616
|
releaseThinkingBuffer(open);
|
|
598
617
|
if (open?.callId) translatorBudget.closeCall(open.callId);
|
|
@@ -600,25 +619,22 @@ export function responsesSseToAnthropicSse(
|
|
|
600
619
|
terminalDelivered = true;
|
|
601
620
|
// No normal close frames are valid after overflow. Emit exactly one bounded
|
|
602
621
|
// typed terminal without consulting the exhausted budget.
|
|
603
|
-
controller.enqueue(encoder.encode(sseFrame("error",
|
|
604
|
-
|
|
605
|
-
message,
|
|
606
|
-
"request_too_large",
|
|
607
|
-
"translation_buffer_limit",
|
|
608
|
-
))));
|
|
622
|
+
controller.enqueue(encoder.encode(sseFrame("error", payload)));
|
|
623
|
+
admitted();
|
|
609
624
|
return;
|
|
610
625
|
}
|
|
611
|
-
const type = upstreamDerived && isTransientUpstreamStatus(status) ? "overloaded_error" : undefined;
|
|
612
626
|
if (!started) {
|
|
613
627
|
// An initial upstream failure is an Anthropic error stream, not a partial message.
|
|
614
628
|
// Do not manufacture message_start before the terminal error. Earlier transport-only
|
|
615
629
|
// pings remain valid and do not turn the failure into a partial message.
|
|
616
|
-
emit("error",
|
|
630
|
+
emit("error", payload, legacy);
|
|
631
|
+
admitted();
|
|
617
632
|
terminalDelivered = true;
|
|
618
633
|
return;
|
|
619
634
|
}
|
|
620
635
|
closeOpenBlock();
|
|
621
|
-
emit("error",
|
|
636
|
+
emit("error", payload, legacy);
|
|
637
|
+
admitted();
|
|
622
638
|
terminalDelivered = true;
|
|
623
639
|
};
|
|
624
640
|
|
|
@@ -866,7 +882,7 @@ export function responsesSseToAnthropicSse(
|
|
|
866
882
|
case "response.completed": {
|
|
867
883
|
const response = isRec(data.response) ? data.response : {};
|
|
868
884
|
if (response.end_turn === false && !sawToolUse) {
|
|
869
|
-
fail(529, "upstream turn ended without a final answer", true);
|
|
885
|
+
fail(529, "upstream turn ended without a final answer", true, undefined, true);
|
|
870
886
|
break;
|
|
871
887
|
}
|
|
872
888
|
finish(sawToolUse ? "tool_use" : "end_turn", response.usage);
|
|
@@ -877,7 +893,7 @@ export function responsesSseToAnthropicSse(
|
|
|
877
893
|
const details = isRec(response.incomplete_details) ? response.incomplete_details : {};
|
|
878
894
|
const outcome = anthropicIncompleteOutcome(details.reason, details.message);
|
|
879
895
|
if ("stopReason" in outcome) finish(outcome.stopReason, response.usage);
|
|
880
|
-
else fail(529, outcome.failMessage, true);
|
|
896
|
+
else fail(529, outcome.failMessage, true, undefined, hasProxyIncomplete(opts.proxyErrorContext ?? upstream, details.reason, details.message), "stream_incomplete");
|
|
881
897
|
break;
|
|
882
898
|
}
|
|
883
899
|
case "response.failed": {
|
|
@@ -900,6 +916,8 @@ export function responsesSseToAnthropicSse(
|
|
|
900
916
|
message,
|
|
901
917
|
!deterministic,
|
|
902
918
|
deterministic ? code : isContextOverflowError(error, message) ? "context_length_exceeded" : undefined,
|
|
919
|
+
hasProxyErrorMessage(opts.proxyErrorContext, message, { type: typeof error.type === "string" ? error.type : undefined, code }),
|
|
920
|
+
undefined, { status, message, type: typeof error.type === "string" ? error.type : undefined, code },
|
|
903
921
|
);
|
|
904
922
|
break;
|
|
905
923
|
}
|
|
@@ -910,9 +928,12 @@ export function responsesSseToAnthropicSse(
|
|
|
910
928
|
|
|
911
929
|
reader = upstream.getReader();
|
|
912
930
|
void (async () => {
|
|
931
|
+
let readingUpstream = false;
|
|
913
932
|
try {
|
|
914
933
|
for (;;) {
|
|
934
|
+
readingUpstream = true;
|
|
915
935
|
const { done, value } = await reader.read();
|
|
936
|
+
readingUpstream = false;
|
|
916
937
|
if (done) break;
|
|
917
938
|
const decodedReservation = translatorBudget.reserveTransient(value.byteLength, { kind: "live_transient" });
|
|
918
939
|
let decodedCommitted = false;
|
|
@@ -1023,12 +1044,12 @@ export function responsesSseToAnthropicSse(
|
|
|
1023
1044
|
// gateways that close such streams politely hand Claude Code an empty/partial
|
|
1024
1045
|
// turn with no retryable error — CLIProxyAPI#2189 failure pattern). Fail closed
|
|
1025
1046
|
// with a mid-stream Anthropic error event so the client can retry.
|
|
1026
|
-
if (!cancelled) fail(502, "upstream stream ended before a terminal frame (truncated response)", true);
|
|
1047
|
+
if (!cancelled) fail(502, "upstream stream ended before a terminal frame (truncated response)", true, undefined, true);
|
|
1027
1048
|
} catch (err) {
|
|
1028
1049
|
if (isTranslatorBudgetExceededError(err)) {
|
|
1029
1050
|
try { await reader.cancel(err); } catch { /* already closed */ }
|
|
1030
|
-
fail(413, "upstream translation buffer exceeded the safe limit", false, "translation_buffer_limit");
|
|
1031
|
-
} else fail(500, err instanceof Error ? err.message : String(err));
|
|
1051
|
+
fail(413, "upstream translation buffer exceeded the safe limit", false, "translation_buffer_limit", true);
|
|
1052
|
+
} else fail(500, err instanceof Error ? err.message : String(err), false, undefined, false, readingUpstream ? "transport_failed" : undefined);
|
|
1032
1053
|
} finally {
|
|
1033
1054
|
releaseThinkingBuffer(open);
|
|
1034
1055
|
translatorBudget.releaseRetained(bufferBytes, { kind: "live_transient" });
|
|
@@ -1136,10 +1157,15 @@ export function responsesJsonToAnthropicMessage(json: unknown, model: string, tr
|
|
|
1136
1157
|
const message = typeof details.message === "string" && details.message.trim()
|
|
1137
1158
|
? details.message
|
|
1138
1159
|
: `upstream response was incomplete${typeof details.reason === "string" ? ` (${details.reason})` : ""}`;
|
|
1139
|
-
|
|
1160
|
+
const legacy = anthropicErrorBody(529, message, "overloaded_error");
|
|
1161
|
+
return ownedAnthropicErrorPayload({ status: 529, type: "overloaded_error", evidence: { status: 529, message },
|
|
1162
|
+
overflow: messagesOverflowPresentation((legacy.error as Rec).message), contract: "stream_incomplete" });
|
|
1140
1163
|
}
|
|
1141
1164
|
if (body.status === "completed" && body.end_turn === false && !sawToolUse) {
|
|
1142
|
-
|
|
1165
|
+
const message = "upstream turn ended without a final answer";
|
|
1166
|
+
const legacy = anthropicErrorBody(529, message, "overloaded_error");
|
|
1167
|
+
return ownedAnthropicErrorPayload({ status: 529, type: "overloaded_error", evidence: { status: 529 },
|
|
1168
|
+
localError: markProxyError({ message }), overflow: messagesOverflowPresentation((legacy.error as Rec).message) });
|
|
1143
1169
|
}
|
|
1144
1170
|
const stopReason = body.status === "incomplete" && details.reason === "max_output_tokens"
|
|
1145
1171
|
? "max_tokens"
|
|
@@ -1169,6 +1195,7 @@ export async function collectAnthropicMessage(
|
|
|
1169
1195
|
stream: ReadableStream<Uint8Array>,
|
|
1170
1196
|
model: string,
|
|
1171
1197
|
translatorBudget: TranslatorBudget,
|
|
1198
|
+
failureVerdictSink?: MessagesFailureVerdictSink,
|
|
1172
1199
|
): Promise<Rec> {
|
|
1173
1200
|
const decoder = new TextDecoder();
|
|
1174
1201
|
const reader = stream.getReader();
|
|
@@ -1230,6 +1257,7 @@ export async function collectAnthropicMessage(
|
|
|
1230
1257
|
break;
|
|
1231
1258
|
}
|
|
1232
1259
|
case "error":
|
|
1260
|
+
collectMessagesFailure(failureVerdictSink, data);
|
|
1233
1261
|
error = data;
|
|
1234
1262
|
break;
|
|
1235
1263
|
default:
|
|
@@ -1253,6 +1281,7 @@ export async function collectAnthropicMessage(
|
|
|
1253
1281
|
if (dataValue !== null) dataLines.push(dataValue);
|
|
1254
1282
|
}
|
|
1255
1283
|
const dataLine = dataLines.join("\n");
|
|
1284
|
+
if (eventName === "error" && failureVerdictSink) failureVerdictSink.collectedErrorEvent = true;
|
|
1256
1285
|
if (!dataLine) continue;
|
|
1257
1286
|
let data: unknown;
|
|
1258
1287
|
try { data = JSON.parse(dataLine); } catch { continue; }
|
|
@@ -2,6 +2,19 @@ import type { Capability } from "./capability-types";
|
|
|
2
2
|
|
|
3
3
|
/** Verified existing handlers only; local operations never claim management routes. */
|
|
4
4
|
export const ACCESS_REMOTE_CAPABILITIES: readonly Capability[] = [
|
|
5
|
+
{
|
|
6
|
+
command: ["disconnect"], summary: "Disconnect a client or preserve orphaned token files for recovery.",
|
|
7
|
+
usage: "ocx disconnect [--keep-catalog] [--json] | ocx disconnect --orphaned-token --yes [--json]",
|
|
8
|
+
routes: [],
|
|
9
|
+
flags: [
|
|
10
|
+
{ name: "--keep-catalog", value: "boolean", summary: "Keep the connected client's catalog during ordinary disconnect." },
|
|
11
|
+
{ name: "--orphaned-token", value: "boolean", summary: "Preserve unowned service-token files in a private backup when disconnected." },
|
|
12
|
+
{ name: "--yes", value: "boolean", summary: "Explicitly confirm orphan-token recovery; requires --orphaned-token." },
|
|
13
|
+
{ name: "--json", value: "boolean", summary: "Emit the local result and backup location as JSON." },
|
|
14
|
+
],
|
|
15
|
+
mutates: true, json: "payload",
|
|
16
|
+
details: ["Orphan recovery requires a disconnected durable state, no pending connect or disconnect, no Hub or admission-secret use, no installed or unverified service, and verified absence of a client runtime. It preserves rather than deletes token files and does not establish their ownership.", "If refused, inspect the bind, API keys, token environment and service status; manage a Hub secret through its service. Stop OpenCodex and move saved files back only when their original names are absent. Never print their contents."],
|
|
17
|
+
},
|
|
5
18
|
{
|
|
6
19
|
command: ["hub", "disable"], summary: "Return a hub to standalone in one validated config write.",
|
|
7
20
|
usage: "ocx hub disable [--revoke-clients --client-key <id> ...] [--json]",
|
|
@@ -784,6 +784,7 @@ export const CAPABILITIES: readonly Capability[] = [
|
|
|
784
784
|
"The Aside refresh uses the live server; other catalog synchronization also performs local work.",
|
|
785
785
|
"An update in flight or an unavailable update/sync mutex refuses without changes: update-in-flight, exit 7. Another sync reports sync-in-progress, exit 1.",
|
|
786
786
|
"A current Home catalog fans out to linked Children. Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex there. Applying changed Home settings may restart the Child's own OpenCodex client runtime.",
|
|
787
|
+
"After a successful Home sync, a connected Child skipped during fan-out, a failed or timed-out Child, or an unreadable link store yields partial exit 6. Skipped connected Children include an actionable hint; update an outdated ocx through its owning installer, with the Desktop tray as an option for Desktop installs. Intentional skips, including client-initiated links and --local-only, keep their existing exit behavior.",
|
|
787
788
|
"--expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {\"phase\":\"child_link_mismatch\"|\"hub_client_mismatch\",\"reason\":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2.",
|
|
788
789
|
],
|
|
789
790
|
usage: "ocx sync [--expect-link <linkId> | --expect-hub-key <apiKeyId>] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]",
|
|
@@ -87,10 +87,10 @@ export const PROVIDER_MODEL_CAPABILITIES: readonly Capability[] = [
|
|
|
87
87
|
details: ["Projects values only from an explicit allowlist of non-secret metadata fields (provider IDs, app types, base URLs, wire dialects, and default models); source and embedded-config bytes are read transiently while secret fields, free-text names, and TOML comments are skipped at the byte level and never decoded into strings, written, or logged, and transient byte buffers are zeroed in finally.", "Only import from a trusted local CC-Switch source: apply prints every imported ID, model, and destination URL before writing, refuses SQLite hard links (nlink > 1) and non-empty -wal/-journal sidecars until CC-Switch is closed, and opens sources read-only with O_NOFOLLOW|O_NONBLOCK descriptor checks; restore inspects auth.json read-only at the byte level and retains any provider that was edited, selected as defaultProvider, or referenced by routing, combos, fallback policy, OAuth accounts, or API keys."],
|
|
88
88
|
},
|
|
89
89
|
{
|
|
90
|
-
command: ["models", "list"], summary: "List
|
|
90
|
+
command: ["models", "list"], summary: "List local configured and router-known models.",
|
|
91
91
|
usage: "ocx models list [--provider <name>] [--json]", routes: [], mutates: false, json: "envelope",
|
|
92
|
-
flags: [{ name: "--provider", value: "string", summary: "Limit to a configured provider." }, { name: "--json", value: "boolean", summary: "Emit models and the
|
|
93
|
-
details: ["A bare models invocation is equivalent.
|
|
92
|
+
flags: [{ name: "--provider", value: "string", summary: "Limit to a configured provider." }, { name: "--json", value: "boolean", summary: "Emit models and the local-catalog note." }],
|
|
93
|
+
details: ["A bare models invocation is equivalent. Includes saved IDs, registry seeds, custom models and this process's discovery cache; use models live for the running catalog."],
|
|
94
94
|
},
|
|
95
95
|
{
|
|
96
96
|
command: ["models","add"],
|
|
@@ -24,6 +24,8 @@ export function skipsCodexShimAutoRestore(command: string | undefined, args: str
|
|
|
24
24
|
if (command === "update" && isOrchestratedUpdateArgv(args)) return true;
|
|
25
25
|
if (command === "sync") return true;
|
|
26
26
|
if (command === "status" || command === "doctor") return true;
|
|
27
|
+
// Explicit orphan-token recovery must not mutate Codex before its guards run.
|
|
28
|
+
if (command === "disconnect" && args.includes("--orphaned-token")) return true;
|
|
27
29
|
// The launcher owns shim handoff after classifying routing, including native fast paths.
|
|
28
30
|
if (command === "codex") return true;
|
|
29
31
|
// Exec admission only observes the selected target; it must never repair a shim first.
|
|
@@ -35,6 +37,11 @@ export function skipsCodexShimAutoRestore(command: string | undefined, args: str
|
|
|
35
37
|
// `resolve` is read-only inspection for embedding shells: a lookup made to populate
|
|
36
38
|
// a consent surface must not trigger a shim repair side effect first.
|
|
37
39
|
if (command === "resolve") return true;
|
|
40
|
+
// Local model inventory is read-only; mutations and live commands keep preflight.
|
|
41
|
+
if (command === "models" || command === "model") {
|
|
42
|
+
const subcommand = args[1];
|
|
43
|
+
if (!subcommand || subcommand.startsWith("-") || subcommand === "list" || subcommand === "list-custom") return true;
|
|
44
|
+
}
|
|
38
45
|
// `service status --json` is a passive inventory read for peers such as GOAT: a shim repair
|
|
39
46
|
// before dispatch would change the installation it was asked only to describe.
|
|
40
47
|
// Flags may precede the verb (`ocx service --json status`), exactly as parseServiceArgs reads it.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { clearCodexAccountPin } from "../codex/account-priority";
|
|
3
|
-
import { getConfigPath, mutatePersistedConfig, readConfigDiagnostics, sanitizeModelCostsForDisplay, saveConfig, validateConfigCandidate } from "../config";
|
|
3
|
+
import { getConfigPath, mutatePersistedConfig, readConfigDiagnostics, sanitizeModelCostsForDisplay, saveConfig, validateConfigCandidate, withConfigMutationLockSync } from "../config";
|
|
4
|
+
import { readClientConnectionState } from "../client/state";
|
|
4
5
|
import { getConfigDir, withConfigDirHardeningSettled } from "../config/paths";
|
|
5
6
|
import { readCliConfigForMutation } from "./config-mutation";
|
|
6
7
|
import { VISION_REASONING_EFFORTS, isVisionReasoningEffort } from "../reasoning-effort";
|
|
@@ -331,7 +332,15 @@ export async function handleConfigCommand(argv: string[]): Promise<number> {
|
|
|
331
332
|
rejectArgs(args, USAGE);
|
|
332
333
|
await withConfigDirHardeningSettled(getConfigDir(), () => {
|
|
333
334
|
readCliConfigForMutation();
|
|
334
|
-
|
|
335
|
+
const imported = validate(loadInput(path));
|
|
336
|
+
withConfigMutationLockSync(() => {
|
|
337
|
+
const client = readClientConnectionState();
|
|
338
|
+
if (client.kind === "connected" && (imported.runtimeRole !== "client"
|
|
339
|
+
|| JSON.stringify(imported.client) !== JSON.stringify(client.value))) {
|
|
340
|
+
throw new Error("config import refused: disconnect the active client before replacing its connection");
|
|
341
|
+
}
|
|
342
|
+
saveConfig(imported);
|
|
343
|
+
});
|
|
335
344
|
});
|
|
336
345
|
printData({ ok: true, source: path }, wantsJson, [`Imported config from ${path}. Restart or run ocx sync if needed.`]);
|
|
337
346
|
return;
|
package/src/cli/connect.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { teardownClientLink } from "../client/link-teardown";
|
|
|
20
20
|
import { reapOrphanTunnel } from "../client/link-tunnel";
|
|
21
21
|
import { readServiceApiTokenState } from "../lib/service-secrets";
|
|
22
22
|
import type { ClientLifecycleLockDeps } from "../client/lifecycle-lock";
|
|
23
|
+
import { recoverOrphanedTokens, type OrphanTokenRecoveryDeps } from "../client/orphan-token-recovery";
|
|
23
24
|
import { linkKnownHostsPath } from "../link/paths";
|
|
24
25
|
import { createSshRunner, type SshRunner } from "../link/ssh-runner";
|
|
25
26
|
import type { OrphanTunnelResult } from "../client/link-tunnel";
|
|
@@ -83,7 +84,8 @@ export const CONNECT_USAGE = `Usage:
|
|
|
83
84
|
ocx connect revoke --admin-token-stdin [--json]`;
|
|
84
85
|
|
|
85
86
|
export const DISCONNECT_USAGE = `Usage:
|
|
86
|
-
ocx disconnect [--keep-catalog] [--json]
|
|
87
|
+
ocx disconnect [--keep-catalog] [--json]
|
|
88
|
+
ocx disconnect --orphaned-token --yes [--json]`;
|
|
87
89
|
|
|
88
90
|
export type ClientConnectionStatus = {
|
|
89
91
|
state: "disconnected" | "connected" | "invalid" | "mismatched";
|
|
@@ -529,13 +531,26 @@ export async function handleConnectCommand(argv: string[], deps: ClientCommandDe
|
|
|
529
531
|
|
|
530
532
|
export async function handleDisconnectCommand(
|
|
531
533
|
argv: string[],
|
|
532
|
-
deps: Pick<ClientCommandDeps, "lifecycleLockDeps" | "linkTeardownDeps"> = {},
|
|
534
|
+
deps: Pick<ClientCommandDeps, "lifecycleLockDeps" | "linkTeardownDeps"> & { orphanRecoveryDeps?: OrphanTokenRecoveryDeps } = {},
|
|
533
535
|
): Promise<number> {
|
|
534
536
|
return runCliAction(async () => {
|
|
535
537
|
const args = [...argv];
|
|
536
538
|
const keepCatalog = takeFlag(args, "--keep-catalog");
|
|
537
539
|
const wantsJson = takeFlag(args, "--json");
|
|
540
|
+
const orphanedToken = takeFlag(args, "--orphaned-token");
|
|
541
|
+
const yes = takeFlag(args, "--yes");
|
|
538
542
|
rejectArgs(args, DISCONNECT_USAGE, { redactValues: true });
|
|
543
|
+
if (orphanedToken) {
|
|
544
|
+
if (!yes || keepCatalog) throw new CliUsageError("--orphaned-token requires --yes and cannot be combined with --keep-catalog", DISCONNECT_USAGE);
|
|
545
|
+
const backup = await recoverOrphanedTokens({ ...deps.orphanRecoveryDeps, lifecycleLockDeps: deps.lifecycleLockDeps });
|
|
546
|
+
const restore = "Stop OpenCodex and move the saved files back into its config directory only if the destination names are absent.";
|
|
547
|
+
printData({ ...backup, restore }, wantsJson, [
|
|
548
|
+
`Preserved token files in ${backup.backupDir}.`,
|
|
549
|
+
`To restore: ${restore}`,
|
|
550
|
+
]);
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
if (yes) throw new CliUsageError("--yes requires --orphaned-token", DISCONNECT_USAGE);
|
|
539
554
|
const teardown = await teardownClientLink({
|
|
540
555
|
readSidecar: readClientLinkState,
|
|
541
556
|
connectedLinkId: () => {
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ProxyRestartStartOutcome } from "./tray-proxy";
|
|
2
|
+
import type { RestartSupervisor } from "./restart-failure";
|
|
2
3
|
/**
|
|
3
4
|
* Registry-driven command dispatch (Phase 3 of the CLI deepening).
|
|
4
5
|
*
|
|
@@ -59,7 +60,7 @@ export interface CliDispatchDeps {
|
|
|
59
60
|
handleTrayProxyStart: (existingIsSuccess?: boolean) => Promise<boolean>;
|
|
60
61
|
handleTrayProxyRestart: () => Promise<void>;
|
|
61
62
|
handleRestartStartWhenStopped: (recoveringLiveRestart?: boolean) => Promise<ProxyRestartStartOutcome>;
|
|
62
|
-
handleProxyRestart: (startWhenStopped: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome
|
|
63
|
+
handleProxyRestart: (startWhenStopped: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome>, onSupervised?: (supervisor: RestartSupervisor) => void) => Promise<boolean>;
|
|
63
64
|
handleUninstall: () => Promise<void>;
|
|
64
65
|
handleStatus: () => Promise<void>;
|
|
65
66
|
handleRecoverHistory: () => Promise<void>;
|
|
@@ -601,6 +602,7 @@ const commandRunners: Record<string, CommandRunner> = {
|
|
|
601
602
|
case "remove": {
|
|
602
603
|
const r = await uninstallCodexShimAsync();
|
|
603
604
|
console.log(r.removed ? `✅ ${r.message}` : `⚠️ ${r.message}`);
|
|
605
|
+
if (r.refused) return 1;
|
|
604
606
|
break;
|
|
605
607
|
}
|
|
606
608
|
default:
|
package/src/cli/doctor.ts
CHANGED
|
@@ -80,6 +80,84 @@ import {
|
|
|
80
80
|
fetchBoundLocalManagementRead,
|
|
81
81
|
type LocalManagementReadDeps,
|
|
82
82
|
} from "../server/local-management-read-client";
|
|
83
|
+
|
|
84
|
+
/** The live proxy’s native-main admission report, or why it could not be read. */
|
|
85
|
+
export type NativeMainAdmissionBlockReason =
|
|
86
|
+
| "foreign-ownership"
|
|
87
|
+
| "ownership-unknown"
|
|
88
|
+
| "recovery-pending"
|
|
89
|
+
| "manual-recovery"
|
|
90
|
+
| "owner-conflict"
|
|
91
|
+
| "owner-unavailable"
|
|
92
|
+
| "stage-cleanup-required";
|
|
93
|
+
|
|
94
|
+
export type NativeMainAdmissionReport =
|
|
95
|
+
| { status: "ready" }
|
|
96
|
+
| { status: "blocked"; reason: NativeMainAdmissionBlockReason }
|
|
97
|
+
| { status: "unavailable"; reason: string };
|
|
98
|
+
|
|
99
|
+
const NATIVE_MAIN_ADMISSION_BLOCK_REASONS: ReadonlySet<string> = new Set([
|
|
100
|
+
"foreign-ownership", "ownership-unknown", "recovery-pending", "manual-recovery",
|
|
101
|
+
"owner-conflict", "owner-unavailable", "stage-cleanup-required",
|
|
102
|
+
]);
|
|
103
|
+
|
|
104
|
+
function isNativeMainAdmissionBlockReason(value: unknown): value is NativeMainAdmissionBlockReason {
|
|
105
|
+
return typeof value === "string" && NATIVE_MAIN_ADMISSION_BLOCK_REASONS.has(value);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Read native-main admission from the running proxy, never this doctor process.
|
|
110
|
+
*
|
|
111
|
+
* A separate `ocx doctor` run has its own process-global gate, usually `ready`, while the
|
|
112
|
+
* proxy answering native traffic can be fenced. The proxy's side-effect-free admission
|
|
113
|
+
* endpoint carries its own admissionStatus; the bound read stays on the existing short-lived,
|
|
114
|
+
* path-signed capability rather than exposing the admin token to doctor. An older proxy
|
|
115
|
+
* without that route answers 404, which is reported as unavailable.
|
|
116
|
+
*/
|
|
117
|
+
export async function fetchNativeMainAdmission(
|
|
118
|
+
target: LiveProxy,
|
|
119
|
+
deps: LocalManagementReadDeps = {},
|
|
120
|
+
): Promise<NativeMainAdmissionReport> {
|
|
121
|
+
const read = await fetchBoundLocalManagementRead(
|
|
122
|
+
target,
|
|
123
|
+
LOCAL_MANAGEMENT_READ_PATHS.nativeMainAdmission,
|
|
124
|
+
{ timeoutMs: 4_000, ...deps, requireResponseProof: true },
|
|
125
|
+
);
|
|
126
|
+
if (read.kind !== "response") return { status: "unavailable", reason: read.reason };
|
|
127
|
+
if (read.response.status === 401 || read.response.status === 403) return { status: "unavailable", reason: "unauthorized" };
|
|
128
|
+
if (!read.response.ok) return { status: "unavailable", reason: `http ${read.response.status}` };
|
|
129
|
+
let payload: unknown;
|
|
130
|
+
try { payload = await read.response.json(); } catch { return { status: "unavailable", reason: "malformed" }; }
|
|
131
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { status: "unavailable", reason: "malformed" };
|
|
132
|
+
const row = payload as Record<string, unknown>;
|
|
133
|
+
if (row.admissionStatus !== "ready" && row.admissionStatus !== "blocked") return { status: "unavailable", reason: "malformed" };
|
|
134
|
+
if (row.admissionStatus === "ready") return { status: "ready" };
|
|
135
|
+
if (!isNativeMainAdmissionBlockReason(row.admissionBlockReason)) return { status: "unavailable", reason: "malformed" };
|
|
136
|
+
return { status: "blocked", reason: row.admissionBlockReason };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function formatNativeMainAdmissionLines(report: NativeMainAdmissionReport): string[] {
|
|
140
|
+
if (report.status === "blocked") {
|
|
141
|
+
const homeGuidance = report.reason === "foreign-ownership"
|
|
142
|
+
? "Repair the service definition and restart the proxy so it uses the recorded CODEX_HOME."
|
|
143
|
+
: report.reason === "ownership-unknown"
|
|
144
|
+
? "Resolve native Codex ownership evidence, then restart the proxy."
|
|
145
|
+
: report.reason === "owner-conflict" || report.reason === "owner-unavailable"
|
|
146
|
+
? "Ensure exactly one OpenCodex proxy owns CODEX_HOME, then restart the proxy."
|
|
147
|
+
: report.reason === "recovery-pending" || report.reason === "manual-recovery"
|
|
148
|
+
? "Run `ocx account main recover` and inspect native-profile doctor before retrying."
|
|
149
|
+
: "Inspect native-profile doctor and clean up the pending staging state before retrying.";
|
|
150
|
+
return [
|
|
151
|
+
` !! native-main admission is fenced (reason: ${report.reason})`,
|
|
152
|
+
` Native model requests return 503 until this clears. ${homeGuidance}`,
|
|
153
|
+
];
|
|
154
|
+
}
|
|
155
|
+
if (report.status === "unavailable") {
|
|
156
|
+
return [" -- native-main admission unavailable from the running proxy"];
|
|
157
|
+
}
|
|
158
|
+
return [];
|
|
159
|
+
}
|
|
160
|
+
|
|
83
161
|
export { resolveCodexHomeDir } from "../codex/home";
|
|
84
162
|
|
|
85
163
|
/**
|
|
@@ -1142,7 +1220,7 @@ export interface DefaultModelExposureDeps {
|
|
|
1142
1220
|
* data-plane admission on a non-loopback bind (`isApiAuthRequired`), and doctor deliberately
|
|
1143
1221
|
* holds no data-plane key, so a remote-bound proxy always falls through to the catalog.
|
|
1144
1222
|
*/
|
|
1145
|
-
async function fetchExposedModelIds(live: LiveProxy, fetchFn: ExposedModelsFetch): Promise<Set<string> | null> {
|
|
1223
|
+
async function fetchExposedModelIds(live: LiveProxy, fetchFn: ExposedModelsFetch): Promise<Set<string> | null | "timeout"> {
|
|
1146
1224
|
try {
|
|
1147
1225
|
// directLocalHttpFetch never follows redirects and aborts past its byte cap, so the
|
|
1148
1226
|
// unbounded-body and redirect cases are covered below the JSON parse, not by options here.
|
|
@@ -1167,8 +1245,10 @@ async function fetchExposedModelIds(live: LiveProxy, fetchFn: ExposedModelsFetch
|
|
|
1167
1245
|
}
|
|
1168
1246
|
}
|
|
1169
1247
|
return ids;
|
|
1170
|
-
} catch {
|
|
1171
|
-
|
|
1248
|
+
} catch (error) {
|
|
1249
|
+
// Past the deadline the proxy is usually still gathering, for example a provider CLI that is
|
|
1250
|
+
// still listing models (#8115); the caller says so instead of implying a failed check.
|
|
1251
|
+
return error instanceof Error && error.name === "TimeoutError" ? "timeout" : null;
|
|
1172
1252
|
}
|
|
1173
1253
|
}
|
|
1174
1254
|
|
|
@@ -1220,14 +1300,18 @@ export async function collectDefaultModelExposure(
|
|
|
1220
1300
|
}
|
|
1221
1301
|
|
|
1222
1302
|
const live = deps.live ?? null;
|
|
1223
|
-
const
|
|
1303
|
+
const proxyRead = live ? await fetchExposedModelIds(live, deps.fetchFn ?? directLocalHttpFetch) : null;
|
|
1304
|
+
const proxyIds = proxyRead === "timeout" ? null : proxyRead;
|
|
1305
|
+
const stillGathering = proxyRead === "timeout"
|
|
1306
|
+
? ` (the running proxy was still gathering its model list after ${EXPOSED_MODELS_TIMEOUT_MS / 1000} s; a provider may still be discovering models)`
|
|
1307
|
+
: "";
|
|
1224
1308
|
const catalogIds = catalogExposedModelIds((deps.readCatalogModelsFn ?? defaultCatalogModels)());
|
|
1225
1309
|
if (proxyIds === null && catalogIds === null) {
|
|
1226
1310
|
return {
|
|
1227
1311
|
status: "undeterminable",
|
|
1228
1312
|
model,
|
|
1229
1313
|
source: null,
|
|
1230
|
-
detail: `could not read the exposed model set, so Codex \`model = "${model}"\` was not checked`,
|
|
1314
|
+
detail: `could not read the exposed model set, so Codex \`model = "${model}"\` was not checked${stillGathering}`,
|
|
1231
1315
|
action: "Start the proxy with 'ocx start', or run 'ocx sync' to write the Codex catalog, then re-run 'ocx doctor'",
|
|
1232
1316
|
};
|
|
1233
1317
|
}
|
|
@@ -1243,7 +1327,7 @@ export async function collectDefaultModelExposure(
|
|
|
1243
1327
|
status: "exposed",
|
|
1244
1328
|
model,
|
|
1245
1329
|
source: matched,
|
|
1246
|
-
detail: `Codex \`model = "${model}"\` is exposed by this install`,
|
|
1330
|
+
detail: `Codex \`model = "${model}"\` is exposed by this install${matched === "catalog" ? stillGathering : ""}`,
|
|
1247
1331
|
};
|
|
1248
1332
|
}
|
|
1249
1333
|
// Name only the surfaces that actually answered: claiming a check that did not happen is the
|
|
@@ -1256,7 +1340,7 @@ export async function collectDefaultModelExposure(
|
|
|
1256
1340
|
status: "not_exposed",
|
|
1257
1341
|
model,
|
|
1258
1342
|
source,
|
|
1259
|
-
detail: `Codex \`model = "${model}"\` is NOT exposed by this install (checked ${checked}), so every new Codex session starts on a model this proxy does not serve`,
|
|
1343
|
+
detail: `Codex \`model = "${model}"\` is NOT exposed by this install (checked ${checked})${stillGathering}, so every new Codex session starts on a model this proxy does not serve`,
|
|
1260
1344
|
action: "Expose that model (enable it in the dashboard or drop it from 'disabledModels') and run 'ocx sync', or pin an exposed id as 'model' in CODEX_HOME/config.toml",
|
|
1261
1345
|
};
|
|
1262
1346
|
}
|
|
@@ -1441,6 +1525,10 @@ export async function runDoctor(args: string[] = []): Promise<void> {
|
|
|
1441
1525
|
const resolution = await resolveNativeMainRefreshMode(loadConfig());
|
|
1442
1526
|
for (const line of formatNativeMainRefreshDoctorLines(resolution)) console.log(line);
|
|
1443
1527
|
}
|
|
1528
|
+
const admission = live
|
|
1529
|
+
? await fetchNativeMainAdmission(live)
|
|
1530
|
+
: { status: "unavailable" as const, reason: "proxy-not-found" };
|
|
1531
|
+
for (const line of formatNativeMainAdmissionLines(admission)) console.log(line);
|
|
1444
1532
|
|
|
1445
1533
|
// Mirrors `ocx status` through the same comparison rather than a second implementation:
|
|
1446
1534
|
// two diagnostics disagreeing about whether an install is stale is worse than one (#2701).
|
package/src/cli/index.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { getCodexHome } from "../codex/paths";
|
|
|
13
13
|
import { admitUpdateRestartChild } from "./update-restart-child";
|
|
14
14
|
import { HEALTH_SENTINEL_STANDALONE_ARG, startServiceHealthSentinel } from "../service/health-sentinel-launch";
|
|
15
15
|
import { UpdateRestartRequired } from "./update-restart-candidate";
|
|
16
|
-
import {
|
|
16
|
+
import { reportUpdateRestartFailure, restartFromCurrentInstallation } from "./update-restart";
|
|
17
17
|
import { findGuiDist } from "../server/gui-static";
|
|
18
18
|
import { inspectGuiBundleFreshness, staleGuiBundleLines } from "../server/gui-freshness";
|
|
19
19
|
// Best-effort recovery for runtime execution and spawned children if launched
|
|
@@ -93,7 +93,7 @@ import {
|
|
|
93
93
|
type ProxyRestartStartOutcome,
|
|
94
94
|
} from "./tray-proxy";
|
|
95
95
|
import { duplicateRuntimeMessage, runDesktopAwareProxyRestart } from "./desktop-runtime-guidance";
|
|
96
|
-
import { reportRestartFailure } from "./restart-failure";
|
|
96
|
+
import { deferSupervisedRestart, reportRestartFailure, type RestartSupervisor } from "./restart-failure";
|
|
97
97
|
import { requestBoundSystemRestart } from "./system-restart-client";
|
|
98
98
|
import { installCrashGuards } from "../lib/crash-guard";
|
|
99
99
|
import { SpendLedgerOwnerError } from "../lib/spend-ledger-owner";
|
|
@@ -160,6 +160,7 @@ import { productionDesktopColdStartDeps, runDesktopColdStart } from "./ensure-de
|
|
|
160
160
|
import { refreshOwnedCatalogIntegrations } from "../integrations/catalog-refresh";
|
|
161
161
|
import { loadExportModels } from "../server/management/model-rows";
|
|
162
162
|
import { removeOwnedConfigAfterDesktopCleanup } from "./uninstall-client-state";
|
|
163
|
+
import { uninstallPrivilegeRefusal } from "../lib/config-ownership";
|
|
163
164
|
import { withProcessRuntimeProvenance } from "../lib/bun-runtime";
|
|
164
165
|
import { startArgv } from "../lib/self-launch-argv";
|
|
165
166
|
import { initializeNodeLauncherContext } from "./launcher-context";
|
|
@@ -605,7 +606,7 @@ async function handleStart(options: { block?: boolean } = {}) {
|
|
|
605
606
|
writeRuntime: bound => { updateRestartChild?.check(bound.port, bound.config.hostname ?? ""); writeRuntimePort({
|
|
606
607
|
pid: process.pid,
|
|
607
608
|
port: bound.port,
|
|
608
|
-
hostname: bound.
|
|
609
|
+
hostname: bound.server.hostname,
|
|
609
610
|
attestationSecret: bound.localAttestationSecret,
|
|
610
611
|
command: currentServingCommand(),
|
|
611
612
|
...siblingRuntimeField(),
|
|
@@ -954,10 +955,9 @@ async function handleTrayProxyStart(existingIsSuccess = true): Promise<boolean>
|
|
|
954
955
|
}
|
|
955
956
|
|
|
956
957
|
const PROXY_RESTART_OBSERVE_MS = MEMORY_DRAIN_RESTART_MS + REPLACEMENT_READY_TIMEOUT_MS + 15_000;
|
|
957
|
-
|
|
958
958
|
/** Reserve confirmation time within the shared restart deadline. */
|
|
959
959
|
async function handleProxyRestart(
|
|
960
|
-
startWhenStopped: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome>,
|
|
960
|
+
startWhenStopped: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome>, onSupervised?: (supervisor: RestartSupervisor) => void,
|
|
961
961
|
): Promise<boolean> {
|
|
962
962
|
const deadlineAt = Date.now() + PROXY_RESTART_OBSERVE_MS;
|
|
963
963
|
const result = await runDesktopAwareProxyRestart({
|
|
@@ -983,10 +983,11 @@ async function handleProxyRestart(
|
|
|
983
983
|
console.log(`🔄 Running proxy ${candidate.target.version} is older than this CLI (${candidate.cliVersion}); restarting it from the current installation...`);
|
|
984
984
|
const update = await restartFromCurrentInstallation(candidate, deadlineAt, detachedStartEnvironment());
|
|
985
985
|
if (update.ok) console.log(`✅ Proxy updated to ${update.live.version} (PID ${update.live.pid}).`);
|
|
986
|
-
else
|
|
986
|
+
else reportUpdateRestartFailure(update);
|
|
987
987
|
process.exitCode = update.ok ? 0 : 1;
|
|
988
988
|
return update.ok;
|
|
989
989
|
}
|
|
990
|
+
if (onSupervised && deferSupervisedRestart(result, onSupervised)) return false;
|
|
990
991
|
if (!result.ok) reportRestartFailure(result);
|
|
991
992
|
process.exitCode = result.ok ? 0 : 1;
|
|
992
993
|
return result.ok;
|
|
@@ -1529,6 +1530,9 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
|
|
|
1529
1530
|
}
|
|
1530
1531
|
|
|
1531
1532
|
async function handleUninstall() {
|
|
1533
|
+
// Before every teardown step: an elevated run must not act on a home another account can change.
|
|
1534
|
+
const privilegeRefusal = uninstallPrivilegeRefusal(getConfigDir());
|
|
1535
|
+
if (privilegeRefusal) { console.error(`❌ ${privilegeRefusal}`); process.exit(1); }
|
|
1532
1536
|
/** Definitive "nothing is answering" on the endpoint this home would serve. */
|
|
1533
1537
|
const proxyEndpointProvenDown = async (): Promise<boolean> => {
|
|
1534
1538
|
try {
|
|
@@ -1683,7 +1687,8 @@ async function handleUninstall() {
|
|
|
1683
1687
|
try {
|
|
1684
1688
|
const { uninstallCodexShimAsync } = await import("../codex/shim");
|
|
1685
1689
|
const r = await uninstallCodexShimAsync();
|
|
1686
|
-
|
|
1690
|
+
if (r.refused) { failures.push("Codex autostart shim removed"); console.error(`⚠️ Codex autostart shim removed failed: ${r.message}`); }
|
|
1691
|
+
else console.log(r.removed ? "✅ Codex autostart shim removed" : "- Codex autostart shim removed: not installed");
|
|
1687
1692
|
} catch (err) {
|
|
1688
1693
|
failures.push("Codex autostart shim removed");
|
|
1689
1694
|
console.error(`⚠️ Codex autostart shim removed failed: ${err instanceof Error ? err.message : String(err)}`);
|