@bitkyc08/opencodex 2.93.0-preview.20261027 → 2.94.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -8
- package/bin/ocx.mjs +215 -63
- package/gui/dist/assets/App-DmvwlhQq.js +58 -0
- package/gui/dist/assets/Tray-CZatQdoF.js +1 -0
- package/gui/dist/assets/index-3EPO_KbX.js +94 -0
- package/gui/dist/assets/index-CHWwDo9L.css +1 -0
- package/gui/dist/assets/{quota-summary-DxToX1rV.js → quota-summary-BHvWg9mi.js} +1 -1
- package/gui/dist/index.html +2 -2
- package/gui/dist/provider-icons/t3code.svg +4 -0
- package/package.json +7 -4
- package/src/adapters/anthropic/account-metadata.ts +34 -3
- package/src/adapters/anthropic/beta-allowlist.ts +5 -5
- package/src/adapters/anthropic/passthrough.ts +5 -2
- package/src/adapters/anthropic.ts +17 -4
- package/src/adapters/antigravity-refusal.ts +29 -0
- package/src/adapters/base.ts +11 -1
- package/src/adapters/client-fingerprint.ts +43 -9
- package/src/adapters/coding-agent/protocol.ts +19 -9
- package/src/adapters/command-code.ts +4 -5
- package/src/adapters/cursor/catalog.ts +5 -3
- package/src/adapters/cursor/claude-id.ts +30 -19
- package/src/adapters/cursor/cursor-errors.ts +5 -2
- package/src/adapters/cursor/h2-pool.ts +9 -7
- package/src/adapters/cursor/http1-bidi.ts +1 -0
- package/src/adapters/cursor/live-models.ts +4 -2
- package/src/adapters/cursor.ts +4 -1
- package/src/adapters/devin/cloud-direct/chat.ts +18 -2
- package/src/adapters/google-antigravity-replay.ts +13 -2
- package/src/adapters/google-antigravity-wire.ts +8 -3
- package/src/adapters/google-errors.ts +33 -0
- package/src/adapters/google-http.ts +41 -16
- package/src/adapters/google-wire-compiler.ts +4 -0
- package/src/adapters/google.ts +21 -10
- package/src/adapters/kiro/adapter.ts +3 -0
- package/src/adapters/kiro/stream.ts +18 -13
- package/src/adapters/openai-chat/completed-tool-blocks.ts +65 -0
- package/src/adapters/openai-chat/messages.ts +22 -10
- package/src/adapters/openai-chat/required-tool-result.ts +3 -3
- package/src/adapters/openai-chat/serialized-tool-call-content.ts +5 -0
- package/src/adapters/openai-chat/wire.ts +9 -0
- package/src/adapters/openai-chat.ts +18 -17
- package/src/adapters/openai-responses/image-gen.ts +15 -1
- package/src/adapters/openai-responses/passthrough.ts +11 -34
- package/src/adapters/openai-responses/transport.ts +20 -2
- package/src/adapters/openai-responses/usage.ts +34 -0
- package/src/adapters/qoder/adapter.ts +9 -15
- package/src/adapters/qoder/image-input.ts +52 -0
- package/src/adapters/unique-tool-call-ids.ts +2 -2
- package/src/adapters/zed-additional-tools.ts +51 -0
- package/src/adapters/zed-diagnostic-usage.ts +22 -0
- package/src/adapters/zed-json-tokens.ts +166 -0
- package/src/adapters/zed-openai-stream.ts +723 -0
- package/src/adapters/zed-tool-arguments.ts +79 -0
- package/src/adapters/zed.ts +53 -3
- package/src/advisor/consult.ts +22 -0
- package/src/advisor/runtime.ts +3 -0
- package/src/bridge/errors.ts +22 -1
- package/src/bridge/response-json.ts +4 -1
- package/src/bridge/sse.ts +21 -12
- package/src/chat/inbound.ts +13 -2
- package/src/chatgpt/app-server-shim/bundle-trust-async.ts +111 -0
- package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +83 -0
- package/src/chatgpt/app-server-shim/bundle-trust.ts +15 -72
- package/src/claude/desktop-first-party.ts +16 -5
- package/src/claude/desktop-gateway-state.ts +4 -0
- package/src/claude/inbound-tool-loading.ts +93 -0
- package/src/claude/intercept/picker-listener.ts +33 -1
- package/src/claude/model-info.ts +29 -4
- package/src/claude/outbound.ts +33 -13
- package/src/cli/account-main.ts +43 -5
- package/src/cli/capabilities-base.ts +22 -5
- package/src/cli/capabilities-integrations.ts +4 -4
- package/src/cli/claude-desktop.ts +139 -98
- package/src/cli/codex-cli-update.ts +102 -48
- package/src/cli/codex-launch-auth.ts +93 -0
- package/src/cli/codex-launch-command.ts +32 -0
- package/src/cli/codex-launch-diagnostics.ts +37 -0
- package/src/cli/codex-launch-ownership.ts +307 -0
- package/src/cli/codex-launch-policy.ts +84 -0
- package/src/cli/codex-launcher.ts +310 -0
- package/src/cli/codex-shim-autorestore.ts +2 -0
- package/src/cli/config-command.ts +9 -4
- package/src/cli/config-mutation.ts +13 -0
- package/src/cli/dispatch.ts +13 -7
- package/src/cli/effort.ts +19 -14
- package/src/cli/ensure-desired-integrations.ts +21 -14
- package/src/cli/ensure-desktop-cold-start.ts +41 -10
- package/src/cli/export-command.ts +8 -4
- package/src/cli/help.ts +3 -1
- package/src/cli/index.ts +58 -64
- package/src/cli/integration-input.ts +12 -0
- package/src/cli/integration-plan-dto.ts +2 -0
- package/src/cli/integration-preview.ts +6 -3
- package/src/cli/integrations.ts +2 -1
- package/src/cli/link-cleanup.ts +8 -23
- package/src/cli/link-enrollment.ts +1 -4
- package/src/cli/link.ts +1 -1
- package/src/cli/loopback-family.ts +2 -31
- package/src/cli/models.ts +62 -49
- package/src/cli/provider.ts +146 -139
- package/src/cli/registry.ts +34 -3
- package/src/cli/root.ts +2 -0
- package/src/cli/start-owner-fence.ts +22 -3
- package/src/cli/status-link.ts +28 -0
- package/src/cli/status.ts +15 -0
- package/src/cli/stop-restore-guard.ts +48 -0
- package/src/cli/stop-restore.ts +117 -36
- package/src/cli/system-command.ts +2 -0
- package/src/cli/v2.ts +17 -4
- package/src/client/lifecycle-lock.ts +1 -1
- package/src/client/link-connection.ts +19 -0
- package/src/client/link-relay-transport.ts +25 -3
- package/src/client/link-tunnel.ts +10 -0
- package/src/client/machine-listener.ts +7 -1
- package/src/client/restore-ownership.ts +45 -0
- package/src/client/runtime.ts +13 -1
- package/src/client/state.ts +1 -1
- package/src/clients/client-ids.ts +7 -0
- package/src/clients/client-path.ts +13 -5
- package/src/clients/config-export/agent-clients.ts +3 -6
- package/src/clients/config-export/alias-selectors.ts +85 -0
- package/src/clients/config-export/contracts.ts +6 -25
- package/src/clients/config-export/dsh.ts +8 -1
- package/src/clients/config-export/model-metadata.ts +19 -0
- package/src/clients/config-export/model-names.ts +31 -0
- package/src/clients/config-export/qoder.ts +3 -11
- package/src/clients/config-export/t3code.ts +141 -0
- package/src/clients/config-export.ts +51 -15
- package/src/clients/gentle-shell-path.ts +3 -3
- package/src/codex/account-lifecycle.ts +27 -13
- package/src/codex/account-store.ts +32 -6
- package/src/codex/app-server-processes.ts +84 -1
- package/src/codex/auth-api/main-account-probe.ts +50 -11
- package/src/codex/auth-api/pool-mode-gate.ts +16 -8
- package/src/codex/auth-context.ts +45 -4
- package/src/codex/catalog/antigravity-discovery.ts +59 -0
- package/src/codex/catalog/build-entries.ts +12 -13
- package/src/codex/catalog/bundled.ts +59 -9
- package/src/codex/catalog/derive-entry.ts +2 -0
- package/src/codex/catalog/gather-capture.ts +3 -0
- package/src/codex/catalog/metadata.ts +6 -5
- package/src/codex/catalog/model-hints.ts +36 -4
- package/src/codex/catalog/native-priority.ts +63 -0
- package/src/codex/catalog/provider-models.ts +20 -4
- package/src/codex/catalog/retained-sync.ts +1 -1
- package/src/codex/chatgpt-refresh-failure.ts +2 -2
- package/src/codex/cli-install-provenance.ts +57 -29
- package/src/codex/cli-installation-identity.ts +1 -1
- package/src/codex/cli-installation-limits.ts +7 -0
- package/src/codex/cli-update-apply.ts +391 -0
- package/src/codex/cli-update-artifacts.ts +257 -0
- package/src/codex/cli-update-files.ts +100 -0
- package/src/codex/cli-update-inspection-context.ts +49 -0
- package/src/codex/cli-update-job-execution.ts +77 -0
- package/src/codex/cli-update-job-store-windows.ts +1010 -0
- package/src/codex/cli-update-job-worker.ts +393 -0
- package/src/codex/cli-update-job.ts +369 -0
- package/src/codex/cli-update-lease.ts +71 -0
- package/src/codex/cli-update-paths.ts +76 -0
- package/src/codex/cli-update-plan.ts +180 -47
- package/src/codex/cli-update-recovery.ts +236 -0
- package/src/codex/cli-update-selection-gate.ts +235 -0
- package/src/codex/cli-update-windows-apply.ts +308 -0
- package/src/codex/cli-update-windows-layout.ts +110 -0
- package/src/codex/cli-update-windows-observation.ts +91 -0
- package/src/codex/cli-update-windows-paths.ts +26 -0
- package/src/codex/cli-update-worker-recovery.ts +32 -0
- package/src/codex/cli-update-worker.ts +185 -0
- package/src/codex/cli-windows-plan-provenance.ts +250 -0
- package/src/codex/desktop-app-restart.ts +22 -3
- package/src/codex/exec-boundary.ts +208 -0
- package/src/codex/forward-transport-headers.ts +80 -0
- package/src/codex/history-job.ts +7 -0
- package/src/codex/history-provider.ts +5 -2
- package/src/codex/history-worker.ts +20 -1
- package/src/codex/inject/restore.ts +57 -25
- package/src/codex/internal/history-writer.ts +2 -1
- package/src/codex/mac-app-bundle.ts +52 -0
- package/src/codex/main-account.ts +161 -23
- package/src/codex/native-main-auth-temp.ts +3 -2
- package/src/codex/native-main-refresh-mode.ts +18 -3
- package/src/codex/native-profile-manager.ts +8 -6
- package/src/codex/native-profile-store.ts +9 -0
- package/src/codex/ocx-compaction-history.ts +3 -2
- package/src/codex/prompt-text-probe.ts +211 -69
- package/src/codex/quota.ts +9 -0
- package/src/codex/role-model-history.ts +253 -0
- package/src/codex/runtime.ts +120 -71
- package/src/codex/shim-overlay.ts +22 -3
- package/src/codex/shim-templates.ts +5 -2
- package/src/codex/shim-wrapper-write.ts +136 -0
- package/src/codex/shim.ts +24 -125
- package/src/codex/windows-cli-child-native.ts +119 -0
- package/src/codex/windows-cli-child-pipe.ts +87 -0
- package/src/codex/windows-cli-child.ts +260 -0
- package/src/codex/windows-cli-recovery-guardian.ts +89 -0
- package/src/codex/windows-cli-recovery.ts +39 -0
- package/src/codex/windows-installation-files.ts +52 -6
- package/src/codex/windows-npm-execution.ts +25 -0
- package/src/combos/failover.ts +84 -5
- package/src/combos/index.ts +1 -0
- package/src/combos/resolve.ts +60 -22
- package/src/config/atomic-write.ts +75 -22
- package/src/config/diagnostics.ts +18 -10
- package/src/config/live-reconcile.ts +11 -3
- package/src/config/owner-registry.ts +5 -4
- package/src/config/persist-unlocked.ts +34 -8
- package/src/config/persisted-mutation.ts +7 -0
- package/src/config/process-state.ts +9 -5
- package/src/config/removed-opencode-free-backup.ts +99 -0
- package/src/config/removed-opencode-free.ts +4 -8
- package/src/config/salvage.ts +1 -0
- package/src/config/schema/config-schema.ts +16 -1
- package/src/config/schema/leaf-validators.ts +15 -0
- package/src/config.ts +4 -4
- package/src/generated/compatibility-version.json +743 -315
- package/src/grok/inject.ts +2 -1
- package/src/grok/sync.ts +5 -2
- package/src/images/loop.ts +14 -5
- package/src/integrations/catalog-refresh.ts +1 -1
- package/src/integrations/hermes-refresh.ts +28 -0
- package/src/integrations/model-name-guard.ts +31 -0
- package/src/integrations/mutation-plan.ts +17 -4
- package/src/integrations/ownership.ts +3 -0
- package/src/integrations/registry.ts +10 -1
- package/src/integrations/state.ts +6 -0
- package/src/integrations/writer.ts +64 -59
- package/src/lib/abort.ts +8 -4
- package/src/lib/bounded-body.ts +7 -1
- package/src/lib/config-ownership.ts +4 -0
- package/src/lib/errors.ts +2 -0
- package/src/lib/eventstream-decoder.ts +3 -2
- package/src/lib/http-response-semantics.ts +9 -6
- package/src/lib/inbound-body-policy.ts +11 -0
- package/src/lib/jsonc.ts +7 -2
- package/src/lib/local-management-capability.ts +3 -1
- package/src/lib/local-upstream.ts +22 -26
- package/src/lib/loopback-family.ts +31 -0
- package/src/lib/plain-data.ts +7 -5
- package/src/lib/process-control.ts +30 -5
- package/src/lib/shadow-call.ts +55 -1
- package/src/lib/tool-argument-integers.ts +99 -7
- package/src/lib/upstream-retry.ts +6 -1
- package/src/lib/windows-elevation.ts +34 -11
- package/src/lib/windows-owner-acl.ts +272 -32
- package/src/lib/windows-secret-acl.ts +310 -44
- package/src/lib/windows-service-wrappers.ts +10 -7
- package/src/lib/winsw.ts +8 -4
- package/src/link/relay-auth.ts +38 -1
- package/src/link/remote-platform.ts +11 -23
- package/src/link/remote-probe.ts +3 -1
- package/src/link/remote-windows.ts +150 -0
- package/src/link/ssh-argv.ts +13 -5
- package/src/link/store.ts +4 -1
- package/src/link/supervisor.ts +9 -0
- package/src/local-credentials/generation.ts +238 -0
- package/src/local-credentials/inventory.ts +281 -0
- package/src/local-credentials/observation-lease.ts +83 -0
- package/src/local-credentials/publication-fence.ts +81 -0
- package/src/local-credentials/references.ts +36 -0
- package/src/local-credentials/runtime-observation.ts +28 -0
- package/src/oauth/account-auto-pause-policy.ts +11 -0
- package/src/oauth/anthropic-account-refusal.ts +1 -0
- package/src/oauth/anthropic-rate-limit-policy.ts +26 -2
- package/src/oauth/anthropic-routing.ts +34 -44
- package/src/oauth/anthropic-session-affinity-store.ts +177 -0
- package/src/oauth/chatgpt.ts +11 -9
- package/src/oauth/cursor.ts +8 -2
- package/src/oauth/generic-account-failover.ts +33 -2
- package/src/oauth/generic-session-affinity.ts +7 -0
- package/src/oauth/google-antigravity.ts +29 -5
- package/src/oauth/index.ts +1 -0
- package/src/oauth/store.ts +32 -4
- package/src/protocols/encoders/adapter-events.ts +7 -4
- package/src/protocols/encoders/messages.ts +1 -1
- package/src/providers/antigravity-account-roster.ts +73 -7
- package/src/providers/antigravity-models.ts +8 -4
- package/src/providers/api-key-resolve.ts +16 -3
- package/src/providers/claude-cli-identity.ts +2 -0
- package/src/providers/codex-capacity.ts +3 -2
- package/src/providers/free-directory.ts +10 -2
- package/src/providers/key-store.ts +7 -2
- package/src/providers/provider-id-rewrite.ts +3 -0
- package/src/providers/quota/antigravity.ts +6 -4
- package/src/providers/quota/vendor-probes-oauth.ts +0 -1
- package/src/providers/stale-model-roster-migration.ts +3 -0
- package/src/quota-pool/assemble.ts +51 -21
- package/src/quota-pool/pooled.ts +162 -0
- package/src/remote-control/workspace-codex-runtime.ts +63 -20
- package/src/responses/apply-patch-envelope.ts +35 -0
- package/src/responses/compaction-history-framing.ts +15 -4
- package/src/responses/turn-membership.ts +111 -0
- package/src/server/advisor-admission-scope.ts +43 -0
- package/src/server/audio-upstream.ts +10 -2
- package/src/server/auth-cors.ts +23 -0
- package/src/server/bind-host.ts +5 -0
- package/src/server/chat-completions.ts +17 -2
- package/src/server/chat-native.ts +16 -11
- package/src/server/claude-messages.ts +9 -1
- package/src/server/codex-model-list.ts +46 -0
- package/src/server/gui-session.ts +5 -2
- package/src/server/inbound-body-admission.ts +21 -13
- package/src/server/inbound-body-budget.ts +128 -0
- package/src/server/index/link-listener.ts +3 -1
- package/src/server/index/link-relay-sessions.ts +9 -2
- package/src/server/index/optional-listeners.ts +1 -0
- package/src/server/index/serve-options.ts +9 -43
- package/src/server/index/websocket-handler.ts +7 -0
- package/src/server/index.ts +6 -5
- package/src/server/inference/client-encoder-delivery.ts +3 -1
- package/src/server/lifecycle.ts +8 -1
- package/src/server/management/advisor-routes.ts +26 -9
- package/src/server/management/agent-settings-routes.ts +424 -543
- package/src/server/management/anthropic-reset-grant-routes.ts +2 -1
- package/src/server/management/claude-code-settings-patch.ts +211 -0
- package/src/server/management/claude-desktop-config-writers.ts +78 -0
- package/src/server/management/codex-agent-role-routes.ts +79 -2
- package/src/server/management/codex-cli-update-routes.ts +55 -0
- package/src/server/management/codex-prompt-routes.ts +2 -1
- package/src/server/management/config-routes.ts +444 -380
- package/src/server/management/consent-session.ts +6 -0
- package/src/server/management/desktop-compatibility-authorization.ts +12 -0
- package/src/server/management/desktop-compatibility-routes.ts +3 -2
- package/src/server/management/desktop-compatibility-runtime-routes.ts +2 -1
- package/src/server/management/desktop-compatibility-settings-routes.ts +2 -1
- package/src/server/management/integration-routes.ts +45 -5
- package/src/server/management/link-enrollment.ts +21 -32
- package/src/server/management/link-route-state.ts +1 -0
- package/src/server/management/link-routes.ts +4 -1
- package/src/server/management/model-routes.ts +22 -6
- package/src/server/management/model-rows.ts +3 -1
- package/src/server/management/native-integration-routes.ts +90 -38
- package/src/server/management/oauth-account-routes.ts +8 -7
- package/src/server/management/route-registry.ts +8 -3
- package/src/server/management/session-routes.ts +20 -2
- package/src/server/management/shadow-call-validation.ts +43 -2
- package/src/server/management/sidebar-routes.ts +2 -1
- package/src/server/management/system-restart.ts +47 -7
- package/src/server/management-api.ts +61 -51
- package/src/server/management-auth.ts +11 -3
- package/src/server/messages-native.ts +21 -7
- package/src/server/messages-shared.ts +110 -18
- package/src/server/persistent-gui-session.ts +155 -0
- package/src/server/port-reclaim.ts +29 -5
- package/src/server/proxy-liveness.ts +110 -33
- package/src/server/request-decompress.ts +5 -1
- package/src/server/responses/account-change-state.ts +14 -2
- package/src/server/responses/adapter-continuation.ts +5 -4
- package/src/server/responses/adapter-delivery.ts +20 -5
- package/src/server/responses/adapter-dispatch.ts +39 -45
- package/src/server/responses/advisor-plan-slot.ts +3 -0
- package/src/server/responses/advisor-slot.ts +4 -2
- package/src/server/responses/antigravity-model-denial-recovery.ts +70 -0
- package/src/server/responses/antigravity-validation-refusal.ts +6 -0
- package/src/server/responses/combo-required-tool-contract.ts +2 -1
- package/src/server/responses/combo-required-tool-fulfillments.ts +58 -0
- package/src/server/responses/combo-required-tool-stream.ts +119 -0
- package/src/server/responses/combo-stream-preflight.ts +47 -7
- package/src/server/responses/compact.ts +14 -7
- package/src/server/responses/compaction-recovery.ts +2 -1
- package/src/server/responses/core-auth.ts +2 -1
- package/src/server/responses/core-codex-account.ts +1 -0
- package/src/server/responses/core-combo-failure.ts +11 -6
- package/src/server/responses/core-combo-native.ts +6 -5
- package/src/server/responses/core-combo.ts +93 -20
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/fetch-helpers.ts +5 -1
- package/src/server/responses/jev-model-invoke.ts +8 -3
- package/src/server/responses/memory-models.ts +3 -2
- package/src/server/responses/passthrough-delivery.ts +36 -8
- package/src/server/responses/passthrough-dispatch.ts +12 -12
- package/src/server/responses/request-prepare.ts +10 -1
- package/src/server/responses/request-transport.ts +41 -6
- package/src/server/responses/run-turn-execution.ts +11 -3
- package/src/server/responses/sidecar-execution.ts +5 -0
- package/src/server/responses/turn-membership.ts +30 -0
- package/src/server/responses-custom-tool-repair.ts +86 -11
- package/src/server/responses-image-gen-repair.ts +1 -1
- package/src/server/restart-parent-ownership.ts +49 -0
- package/src/server/stop-teardown.ts +46 -9
- package/src/server/windows-tcp-drop.ts +4 -2
- package/src/service/desktop-recovery-process.ts +341 -0
- package/src/service/desktop-recovery.ts +172 -0
- package/src/service/windows-ops.ts +6 -3
- package/src/service/windows-scheduler.ts +29 -6
- package/src/stall-timeout.ts +47 -0
- package/src/tray/windows.ts +6 -4
- package/src/types/config.ts +61 -10
- package/src/types/request.ts +1 -1
- package/src/types.ts +1 -0
- package/src/update/async-check.ts +4 -3
- package/src/update/bind-probe.ts +2 -2
- package/src/update/codex-cli-update-launch-policy.mjs +9 -0
- package/src/update/guarded-port-reclaim.ts +14 -0
- package/src/update/guarded-runtime-ops.ts +58 -0
- package/src/update/guarded-tray-ops.ts +9 -0
- package/src/update/index.ts +196 -58
- package/src/update/job-pinned-start.ts +53 -0
- package/src/update/job-supervised-restart.ts +23 -6
- package/src/update/job-update-home.ts +62 -0
- package/src/update/job-update-tray.ts +29 -0
- package/src/update/job-windows-restart.ts +39 -0
- package/src/update/job.ts +179 -193
- package/src/update/mutation-guard.d.mts +30 -0
- package/src/update/mutation-guard.mjs +103 -0
- package/src/update/notify.ts +2 -2
- package/src/update/npm-cache-preflight.mjs +4 -4
- package/src/update/npm-install.mjs +5 -3
- package/src/update/pnpm-read-policy.mjs +3 -2
- package/src/update/proxy-liveness-probe.mjs +2 -2
- package/src/update/service-home-authority.ts +35 -0
- package/src/update/service-home-package-only-protocol.json +1 -0
- package/src/update/service-home-policy.d.mts +25 -0
- package/src/update/service-home-policy.mjs +112 -0
- package/src/update/service-home-probe-entry.ts +9 -0
- package/src/update/service-home-probe.d.mts +15 -0
- package/src/update/service-home-probe.mjs +79 -0
- package/src/update/service-home-protocol.json +1 -0
- package/src/update/supervised-recovery.d.mts +2 -2
- package/src/update/supervised-recovery.mjs +14 -7
- package/src/update/transactional-install.d.mts +3 -1
- package/src/update/transactional-install.mjs +29 -19
- package/src/update/update-failure-guidance.mjs +1 -1
- package/src/update/worker-launch.ts +3 -3
- package/src/vision/anthropic-describe.ts +2 -1
- package/src/web-search/anthropic-executor.ts +2 -1
- package/src/web-search/anthropic-history.ts +1 -0
- package/src/web-search/format-result.ts +3 -2
- package/src/web-search/header-deadline.ts +3 -2
- package/src/web-search/loop.ts +10 -4
- package/src/web-search/parse.ts +191 -38
- package/gui/dist/assets/App-CJZoq-uF.js +0 -58
- package/gui/dist/assets/Tray-BWQPcgZn.js +0 -1
- package/gui/dist/assets/index-DRe8Hhfz.css +0 -1
- package/gui/dist/assets/index-Xfct8owH.js +0 -94
|
@@ -50,7 +50,7 @@ import {
|
|
|
50
50
|
import type { OcxClaudeCodeConfig, OcxClaudeDesktopProfile, OcxConfig, OcxCustomModel, OcxProviderConfig } from "../types";
|
|
51
51
|
import type { DesktopProfileModel } from "../claude/desktop-profile";
|
|
52
52
|
import { drainAndShutdown } from "./lifecycle";
|
|
53
|
-
import { noteExplicitShutdownRequested } from "./management/system-restart";
|
|
53
|
+
import { acquireExplicitShutdownIntent, noteExplicitShutdownRequested } from "./management/system-restart";
|
|
54
54
|
import { filterRequestLogs, getRequestLogEntries, type RequestLogEntry } from "./request-log";
|
|
55
55
|
import { estimateComboCost, estimateRequestCost, normalizeCostTokens, tokensPerSecond } from "../usage/cost";
|
|
56
56
|
import type { PersistedUsageAttempt } from "../usage/log";
|
|
@@ -83,6 +83,7 @@ import { handleClaudeDesktopPickerRoutes } from "./management/claude-desktop-pic
|
|
|
83
83
|
import { handleDesktopCompatibilityRoutes } from "./management/desktop-compatibility-routes";
|
|
84
84
|
import { handleDesktopCompatibilityRuntimeRoutes } from "./management/desktop-compatibility-runtime-routes";
|
|
85
85
|
import { handleDesktopCompatibilitySettingsRoutes } from "./management/desktop-compatibility-settings-routes";
|
|
86
|
+
import { handleCodexCliUpdateRoutes } from "./management/codex-cli-update-routes";
|
|
86
87
|
import { handleCursorIntegrationRoutes } from "./management/cursor-integration-routes";
|
|
87
88
|
import type { ManagementContext } from "./management/context";
|
|
88
89
|
import type { ManagementPrincipal, ManagementSessionControl } from "./management-auth";
|
|
@@ -384,6 +385,7 @@ export async function handleManagementAPI(
|
|
|
384
385
|
?? (await handleDesktopCompatibilityRoutes(ctx))
|
|
385
386
|
?? (await handleDesktopCompatibilityRuntimeRoutes(ctx))
|
|
386
387
|
?? (await handleDesktopCompatibilitySettingsRoutes(ctx))
|
|
388
|
+
?? (await handleCodexCliUpdateRoutes(ctx))
|
|
387
389
|
?? (await handleAgentSettingsRoutes(ctx))
|
|
388
390
|
?? (await handleCodexPromptRoutes(ctx))
|
|
389
391
|
?? (await handleOauthAccountRoutes(ctx))
|
|
@@ -434,7 +436,7 @@ export async function handleManagementAPI(
|
|
|
434
436
|
// outcome. This process cannot verify its own post-exit respawn window; only the
|
|
435
437
|
// receipt-backed parent `ocx stop` can, which is what the deferral exists for.
|
|
436
438
|
const { deferralMatchesReceipt } = await import("../config/pending-teardown");
|
|
437
|
-
const { deferralHonored, desktopSupervisedStopRefusal, performStopTeardown } = await import("./stop-teardown");
|
|
439
|
+
const { deferralHonored, desktopSupervisedStopRefusal, performStopTeardown, preflightStopTeardownOwnership } = await import("./stop-teardown");
|
|
438
440
|
// The desktop app would start this proxy again within seconds; refuse before anything is
|
|
439
441
|
// touched and point at its tray, whose Stop it honours (#3008 refuses an undone stop the same way).
|
|
440
442
|
const desktopRefusal = desktopSupervisedStopRefusal(principal);
|
|
@@ -475,58 +477,65 @@ export async function handleManagementAPI(
|
|
|
475
477
|
message: "The Windows Task Scheduler state could not be read, so this proxy cannot tell whether a wrapper would respawn it. Nothing was changed. Run `ocx service status` to see the query error, repair Task Scheduler access, then retry.",
|
|
476
478
|
}, 409, req, config);
|
|
477
479
|
}
|
|
478
|
-
|
|
480
|
+
// Block automatic handoff while deciding, without committing a refused stop.
|
|
481
|
+
const releaseStopIntent = acquireExplicitShutdownIntent();
|
|
479
482
|
try {
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
// The installed service belongs to another CODEX_HOME/OPENCODEX_HOME: it would respawn
|
|
484
|
-
// this proxy immediately, and its shared config is not ours to tear down. Refuse the
|
|
485
|
-
// stop instead of half-performing it. 409, not 500 — the request is well-formed.
|
|
486
|
-
return jsonResponse({ success: false, message: err.message }, 409, req, config);
|
|
483
|
+
if (!holdsReceipt && !sibling) {
|
|
484
|
+
const refusal = preflightStopTeardownOwnership();
|
|
485
|
+
if (refusal) return jsonResponse(refusal, 409, req, config);
|
|
487
486
|
}
|
|
488
|
-
|
|
489
|
-
}
|
|
490
|
-
// The boolean helper collapses "failed" into the same false as "no service installed",
|
|
491
|
-
// so this route used to tear down shared config and exit while a manager that refused
|
|
492
|
-
// to stop was still there to respawn the proxy (#3008).
|
|
493
|
-
if (serviceStop === "failed") {
|
|
494
|
-
return jsonResponse({
|
|
495
|
-
success: false,
|
|
496
|
-
message: "The installed service manager did not stop; it may respawn the proxy. Shared client config was left alone. Run `ocx stop` from the home that owns the service.",
|
|
497
|
-
}, 409, req, config);
|
|
498
|
-
}
|
|
499
|
-
if (serviceStop === "state-unknown") {
|
|
500
|
-
// Same case, same remedy as the pre-check: the query is what needs fixing.
|
|
501
|
-
return jsonResponse({
|
|
502
|
-
success: false,
|
|
503
|
-
code: "service_state_unknown",
|
|
504
|
-
message: "The Windows Task Scheduler state could not be read, so this proxy cannot tell whether a wrapper would respawn it. Shared client config was left alone. Run `ocx service status` to see the query error, repair Task Scheduler access, then retry.",
|
|
505
|
-
}, 409, req, config);
|
|
506
|
-
}
|
|
507
|
-
// The pre-check above already refused the respawnable case without a receipt, so
|
|
508
|
-
// reaching here with one means the parent owns the verification.
|
|
509
|
-
// Both managed configs come down together on an explicit teardown. The daemon's own
|
|
510
|
-
// syncCleanup skips this when OCX_SERVICE is set (so a crash/respawn keeps the fence),
|
|
511
|
-
// which is exactly why an intentional stop has to do it here — unless the caller is
|
|
512
|
-
// `ocx stop`, which does it itself once the proxy is proven down.
|
|
513
|
-
// Mark the stop before the first await after acceptance, so an automatic restart draining
|
|
514
|
-
// concurrently cannot reach its handoff while teardown is still pending.
|
|
515
|
-
noteExplicitShutdownRequested();
|
|
516
|
-
const teardown = await performStopTeardown(url, { ownsReceipt: deferralMatchesReceipt });
|
|
517
|
-
setTimeout(async () => {
|
|
518
|
-
let shutdownSucceeded = false;
|
|
487
|
+
let serviceStop: import("../service").ServiceStopOutcome;
|
|
519
488
|
try {
|
|
520
|
-
|
|
521
|
-
} catch {
|
|
522
|
-
|
|
489
|
+
serviceStop = sibling ? "absent" : stopServiceIfInstalledDetailed();
|
|
490
|
+
} catch (err) {
|
|
491
|
+
if (isServiceOwnershipError(err)) {
|
|
492
|
+
// The installed service belongs to another CODEX_HOME/OPENCODEX_HOME: it would respawn
|
|
493
|
+
// this proxy immediately, and its shared config is not ours to tear down. Refuse the
|
|
494
|
+
// stop instead of half-performing it. 409, not 500 — the request is well-formed.
|
|
495
|
+
return jsonResponse({ success: false, message: err.message }, 409, req, config);
|
|
496
|
+
}
|
|
497
|
+
throw err;
|
|
523
498
|
}
|
|
524
|
-
//
|
|
525
|
-
//
|
|
526
|
-
// still
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
499
|
+
// The boolean helper collapses "failed" into the same false as "no service installed",
|
|
500
|
+
// so this route used to tear down shared config and exit while a manager that refused
|
|
501
|
+
// to stop was still there to respawn the proxy (#3008).
|
|
502
|
+
if (serviceStop === "failed") {
|
|
503
|
+
return jsonResponse({
|
|
504
|
+
success: false,
|
|
505
|
+
message: "The installed service manager did not stop; it may respawn the proxy. Shared client config was left alone. Run `ocx stop` from the home that owns the service.",
|
|
506
|
+
}, 409, req, config);
|
|
507
|
+
}
|
|
508
|
+
if (serviceStop === "state-unknown") {
|
|
509
|
+
// Same case, same remedy as the pre-check: the query is what needs fixing.
|
|
510
|
+
return jsonResponse({
|
|
511
|
+
success: false,
|
|
512
|
+
code: "service_state_unknown",
|
|
513
|
+
message: "The Windows Task Scheduler state could not be read, so this proxy cannot tell whether a wrapper would respawn it. Shared client config was left alone. Run `ocx service status` to see the query error, repair Task Scheduler access, then retry.",
|
|
514
|
+
}, 409, req, config);
|
|
515
|
+
}
|
|
516
|
+
// The pre-check above already refused the respawnable case without a receipt, so
|
|
517
|
+
// reaching here with one means the parent owns the verification.
|
|
518
|
+
// Both managed configs come down together on an explicit teardown. The daemon's own
|
|
519
|
+
// syncCleanup skips this when OCX_SERVICE is set (so a crash/respawn keeps the fence),
|
|
520
|
+
// which is exactly why an intentional stop has to do it here — unless the caller is
|
|
521
|
+
// `ocx stop`, which does it itself once the proxy is proven down.
|
|
522
|
+
const teardown = await performStopTeardown(url, { ownsReceipt: deferralMatchesReceipt });
|
|
523
|
+
if (teardown.sharedTeardown === "refused") return jsonResponse(teardown, 409, req, config);
|
|
524
|
+
noteExplicitShutdownRequested(); // Accepted stops and signals remain irreversible.
|
|
525
|
+
setTimeout(async () => {
|
|
526
|
+
let shutdownSucceeded = false;
|
|
527
|
+
try {
|
|
528
|
+
shutdownSucceeded = await drainAndShutdown(undefined, config.shutdownTimeoutMs ?? 5000);
|
|
529
|
+
} catch {
|
|
530
|
+
console.warn("[opencodex] shutdown drain failed");
|
|
531
|
+
}
|
|
532
|
+
// A drained proxy whose shared teardown failed did not finish the job. Exiting 0
|
|
533
|
+
// told a supervisor the stop was clean while native Codex or the Grok fence was
|
|
534
|
+
// still pointed at this process (#3008).
|
|
535
|
+
process.exit(shutdownSucceeded && teardown.success ? 0 : 1);
|
|
536
|
+
}, 200);
|
|
537
|
+
return jsonResponse(teardown);
|
|
538
|
+
} finally { releaseStopIntent(); }
|
|
530
539
|
}
|
|
531
540
|
|
|
532
541
|
if (url.pathname.startsWith("/api/native-main-profiles")) {
|
|
@@ -546,7 +555,8 @@ export async function handleManagementAPI(
|
|
|
546
555
|
const { ConfigMutationLockError } = await import("../config");
|
|
547
556
|
const { CodexCredentialRefreshLockTimeoutError } = await import("../codex/account-store");
|
|
548
557
|
try {
|
|
549
|
-
|
|
558
|
+
// Remembered sessions retain admin-token consent authority for account refresh.
|
|
559
|
+
return await handleCodexAuthAPI(req, url, config, convergeCodexCatalog, ctx.guiSessionIssuance === "remembered-admin" ? "admin-token" : principal);
|
|
550
560
|
} catch (error) {
|
|
551
561
|
// Credential writers remap ConfigMutationLockError to CodexCredentialRefreshLockTimeoutError;
|
|
552
562
|
// treat both as the same retryable busy response.
|
|
@@ -72,6 +72,7 @@ import {
|
|
|
72
72
|
type GuiSessionRequestContext,
|
|
73
73
|
} from "./gui-session";
|
|
74
74
|
import { hasLocalDesktopSnapshotCapability } from "./local-desktop-snapshot-auth";
|
|
75
|
+
import { forgetGuiDevice, rememberGuiDevice, rememberedGuiSessionIsCurrent, resumeGuiDevice } from "./persistent-gui-session";
|
|
75
76
|
import { hasLocalAccountSwitchCapability } from "./local-account-switch-auth";
|
|
76
77
|
import { authorizationCredential } from "../lib/authorization-scheme";
|
|
77
78
|
export type { GuiSessionBootstrap, GuiSessionRequestContext } from "./gui-session";
|
|
@@ -260,7 +261,7 @@ export function issueGuiSession(
|
|
|
260
261
|
context?: GuiSessionRequestContext,
|
|
261
262
|
): GuiSessionBootstrap | null {
|
|
262
263
|
if (!state.available) return null;
|
|
263
|
-
return issueGuiSessionFromState(req, config, state, context);
|
|
264
|
+
return resumeGuiDevice(req, config, state, context?.now) ?? issueGuiSessionFromState(req, config, state, context);
|
|
264
265
|
}
|
|
265
266
|
|
|
266
267
|
/** Returns the recorded issuance for the session that authorized this request. */
|
|
@@ -275,6 +276,8 @@ export function managementSessionIssuance(
|
|
|
275
276
|
}
|
|
276
277
|
|
|
277
278
|
export interface ManagementSessionControl {
|
|
279
|
+
rememberDevice?(req: Request, config: OcxConfig): ReturnType<typeof rememberGuiDevice>;
|
|
280
|
+
forgetDevice?(req: Request, config: OcxConfig): string | null;
|
|
278
281
|
revokeCurrent(req: Request): boolean;
|
|
279
282
|
/** Revalidate a long-lived request against current authority, without cached admission or renewal. */
|
|
280
283
|
isCurrent(req: Request, config: OcxConfig): boolean;
|
|
@@ -291,7 +294,7 @@ export function createManagementSessionControl(state: ManagementAuthState): Mana
|
|
|
291
294
|
const credential = requestManagementCredential(req);
|
|
292
295
|
if (!credential || equalSecret(credential, adminToken)) return null;
|
|
293
296
|
const session = state.sessions.get(credential);
|
|
294
|
-
if (!session) return null;
|
|
297
|
+
if (!session || !rememberedGuiSessionIsCurrent(req, config, state, session)) return null;
|
|
295
298
|
// Reuse the full origin/expiry/CSRF predicate against the current record, but
|
|
296
299
|
// isolate its sliding-expiry mutation: authority checks are not browser activity.
|
|
297
300
|
return authorizeGuiSessionRequest(req, config, {
|
|
@@ -300,6 +303,8 @@ export function createManagementSessionControl(state: ManagementAuthState): Mana
|
|
|
300
303
|
}).ok ? session : null;
|
|
301
304
|
}
|
|
302
305
|
return {
|
|
306
|
+
rememberDevice(req, config) { return state.available ? rememberGuiDevice(req, config, state) : null; },
|
|
307
|
+
forgetDevice(req, config) { return state.available ? forgetGuiDevice(req, config, state) : null; },
|
|
303
308
|
isCurrent(req: Request, config: OcxConfig): boolean {
|
|
304
309
|
if (!state.available) return false;
|
|
305
310
|
const credential = requestManagementCredential(req);
|
|
@@ -582,7 +587,10 @@ function resolveManagementAdmission(
|
|
|
582
587
|
else if (actual && isOpencodeCatalogRequest(req) && equalSecret(actual, opencodeCatalogToken(state.token))) {
|
|
583
588
|
principal = "opencode-catalog-token";
|
|
584
589
|
}
|
|
585
|
-
else if (config
|
|
590
|
+
else if (config) {
|
|
591
|
+
const admission = authorizeGuiSessionRequest(req, config, state);
|
|
592
|
+
if (admission.ok && rememberedGuiSessionIsCurrent(req, config, state, admission.session, "logout")) principal = "gui-session";
|
|
593
|
+
}
|
|
586
594
|
}
|
|
587
595
|
if (principal) admittedManagementRequests.set(req, principal);
|
|
588
596
|
return principal;
|
|
@@ -122,6 +122,8 @@ import {
|
|
|
122
122
|
type RequestLogContext,
|
|
123
123
|
} from "./request-log";
|
|
124
124
|
import { fetchWithHeaderTimeout, physicalSendObserverInit, providerFetch, safeHostLabel, sendWithConnectionPolicy } from "./responses/fetch-helpers";
|
|
125
|
+
import { isLocalUpstream } from "../lib/local-upstream";
|
|
126
|
+
import { resolveConnectTimeoutMs, resolveJsonBodyReadTimeoutMs } from "../stall-timeout";
|
|
125
127
|
import { anthropicBillingPhysicalFetch } from "../providers/anthropic-billing-ownership";
|
|
126
128
|
import { rotateAnthropicBillingKeyOnResponse } from "../providers/anthropic-billing-recovery";
|
|
127
129
|
import { linkAbortSignal } from "./responses/core-lifetime";
|
|
@@ -424,7 +426,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
424
426
|
streamTurnRegistered = false;
|
|
425
427
|
unregisterTurn(upstream);
|
|
426
428
|
};
|
|
427
|
-
|
|
429
|
+
// Set only at the final send boundary; queued refresh can replace the destination.
|
|
430
|
+
let localUpstream = false;
|
|
428
431
|
// An OAuth route is served by the account the existing OAuth selection commits now, at
|
|
429
432
|
// dispatch; the token lives on this lane's provider copy only, never on the shared route.
|
|
430
433
|
let oauthBinding: NativeOAuthBinding | undefined;
|
|
@@ -484,6 +487,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
484
487
|
callerAnthropicBeta: options.callerAnthropicBeta,
|
|
485
488
|
providerAccountUuid: oauthBinding?.providerAccountUuid,
|
|
486
489
|
clientIdentity: options.clientIdentity,
|
|
490
|
+
sessionKey: oauthBinding?.sessionKey ?? options.sessionKey,
|
|
487
491
|
});
|
|
488
492
|
if (built.strippedOpaqueState && rejectUnrepresentable) throw new NativeOpaqueStateRefusal();
|
|
489
493
|
if (built.droppedBetas) {
|
|
@@ -559,7 +563,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
559
563
|
request.url,
|
|
560
564
|
applyUpstreamRecoveryInit({ method: "POST", headers: request.headers, body: request.body }, transportRecovery),
|
|
561
565
|
upstream.signal,
|
|
562
|
-
|
|
566
|
+
0, // Final physical send owns the header clock after queued credential/destination refresh.
|
|
563
567
|
requestedStream,
|
|
564
568
|
providerFetch(activeProvider, undefined, {
|
|
565
569
|
providerName: route.providerName,
|
|
@@ -639,13 +643,19 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
639
643
|
sendOwner = snapshot ? captureAnthropicPhysicalSendOwnership(snapshot) : null;
|
|
640
644
|
if (snapshot && !sendOwner) throw new NativeOAuthSelectionChangedError();
|
|
641
645
|
physicalSendsUsed++;
|
|
642
|
-
|
|
646
|
+
const physicalFetch = ((input, physicalInit) => sendWithConnectionPolicy(
|
|
643
647
|
distributedKeyPhysicalFetch(
|
|
644
648
|
anthropicBillingPhysicalFetch((activeProvider as OcxProviderTransport).fetch ?? execute, route.providerName, activeProvider),
|
|
645
649
|
route.providerName, activeProvider, wire.url, activeProvider.apiKeyTransport === "bearer" ? "authorization" : "x-api-key"),
|
|
650
|
+
String(input), physicalInit, { providerName: route.providerName, provider: activeProvider },
|
|
651
|
+
)) as typeof fetch;
|
|
652
|
+
localUpstream = isLocalUpstream(wire.url);
|
|
653
|
+
dispatched = await fetchWithHeaderTimeout(
|
|
646
654
|
wire.url,
|
|
647
655
|
applyUpstreamRecoveryInit({ ...init, method: "POST", headers, body: wire.body, ...physicalSendObserverInit(observeAutoPause, wire.url) }, transportRecovery),
|
|
648
|
-
|
|
656
|
+
init.signal ?? upstream.signal,
|
|
657
|
+
resolveConnectTimeoutMs(config.connectTimeoutMs, { localUpstream }),
|
|
658
|
+
requestedStream, physicalFetch,
|
|
649
659
|
);
|
|
650
660
|
} finally {
|
|
651
661
|
try { if (physicalBudget.spendEnforced) spendReport(1); }
|
|
@@ -878,7 +888,10 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
878
888
|
if (contentType.includes("text/event-stream") && response.body) {
|
|
879
889
|
// `upstream` follows req.signal and is also what shutdown and turn release abort, so both
|
|
880
890
|
// the client leaving and this lane's own abort read as a cancel, not as a failed stream.
|
|
881
|
-
const bodyGuard =
|
|
891
|
+
const bodyGuard = {
|
|
892
|
+
...resolvePassthroughBodyGuard(config, upstream.signal),
|
|
893
|
+
...(activeProvider.anthropicEofTolerance === true ? { eofTolerant: true } : {}),
|
|
894
|
+
};
|
|
882
895
|
const observed = logIds ? observeFirstChunk(response.body, () => recordFirstOutput(logCtx, logIds.start)) : response.body;
|
|
883
896
|
const renamed = activeRequest.oauthToolNames
|
|
884
897
|
? restoreOAuthToolNamesInSse(observed, activeRequest.oauthToolNames, translatorBudget)
|
|
@@ -956,11 +969,12 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
|
|
|
956
969
|
|
|
957
970
|
let read;
|
|
958
971
|
try {
|
|
972
|
+
const jsonBodyReadMs = resolveJsonBodyReadTimeoutMs(config.stallTimeoutSec, { localUpstream }, config.connectTimeoutMs);
|
|
959
973
|
read = await readBoundedResponseBody(response, {
|
|
960
974
|
signal: upstream.signal,
|
|
961
975
|
maxBytes: MAX_NATIVE_MESSAGES_JSON_BYTES,
|
|
962
|
-
totalTimeoutMs:
|
|
963
|
-
inactivityTimeoutMs:
|
|
976
|
+
totalTimeoutMs: localUpstream ? 0 : jsonBodyReadMs,
|
|
977
|
+
inactivityTimeoutMs: jsonBodyReadMs,
|
|
964
978
|
});
|
|
965
979
|
} catch (error) {
|
|
966
980
|
cleanupAbort();
|
|
@@ -52,6 +52,31 @@ export function anthropicUsageToOcx(usage: Rec | undefined): { inputTokens: numb
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
/** Body-occupancy guard for the native passthrough (devlog 260716_passthrough_followups/010). */
|
|
55
|
+
/**
|
|
56
|
+
* True when an undelimited SSE tail (LF-normalized) holds nothing a client would act on: only
|
|
57
|
+
* whitespace, comments, or a ping. Anything else is a message event cut off at EOF.
|
|
58
|
+
*/
|
|
59
|
+
export function isHarmlessSseTail(tail: string): boolean {
|
|
60
|
+
const lines = tail.split("\n").filter(line => line.trim() !== "");
|
|
61
|
+
let event: string | null = null;
|
|
62
|
+
const data: string[] = [];
|
|
63
|
+
for (const line of lines) {
|
|
64
|
+
if (line.startsWith(":")) continue;
|
|
65
|
+
const eventValue = sseFieldValue(line, "event");
|
|
66
|
+
if (eventValue !== null) { event = eventValue; continue; }
|
|
67
|
+
const dataValue = sseFieldValue(line, "data");
|
|
68
|
+
if (dataValue !== null) { data.push(dataValue); continue; }
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
if (data.length === 0) return event === null || event === "ping";
|
|
72
|
+
try {
|
|
73
|
+
const payload: unknown = JSON.parse(data.join("\n"));
|
|
74
|
+
return isRec(payload) && payload.type === "ping" && (event === null || event === "ping");
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
55
80
|
export interface PassthroughBodyGuard {
|
|
56
81
|
/** Idle window in ms — raw upstream-byte inactivity while a read is pending. 0 disables. */
|
|
57
82
|
stallMs: number;
|
|
@@ -59,6 +84,11 @@ export interface PassthroughBodyGuard {
|
|
|
59
84
|
maxBytes: number;
|
|
60
85
|
/** Client request signal for deterministic cancel classification. */
|
|
61
86
|
reqSignal?: AbortSignal;
|
|
87
|
+
/**
|
|
88
|
+
* The routed provider opted into anthropicEofTolerance: a content-only clean EOF (no
|
|
89
|
+
* message_stop, no stop_reason, nothing cut) stays a completed turn, as it always was.
|
|
90
|
+
*/
|
|
91
|
+
eofTolerant?: boolean;
|
|
62
92
|
}
|
|
63
93
|
|
|
64
94
|
export type PassthroughCloseReason = "terminal" | "client_cancel" | "body_stall" | "body_overflow";
|
|
@@ -86,23 +116,43 @@ export function tapAnthropicSseForLog(
|
|
|
86
116
|
let usageAcc: Rec = {};
|
|
87
117
|
// message_stop or an upstream error event: the turn's own terminal already went through.
|
|
88
118
|
let terminalSeen = false;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
119
|
+
// stop_reason of the latest message event the client received as a complete SSE event. Any
|
|
120
|
+
// later message event (resumed content) clears it; pings and comments do not.
|
|
121
|
+
let lastDeliveredStop: string | null = null;
|
|
122
|
+
// A frame is evidence of an event only when its payload type and its event name agree (or the
|
|
123
|
+
// event line is absent): clients and the non-stream fold dispatch on the event name.
|
|
124
|
+
const named = (event: string | null, data: Rec, type: string) => data.type === type && (event === null || event === type);
|
|
125
|
+
const inspectFrame = (frame: string, delivered = true) => {
|
|
126
|
+
const lines = frame.split("\n");
|
|
127
|
+
// SSE dispatches on the last event field of a frame.
|
|
128
|
+
const eventLine = lines.map(l => sseFieldValue(l, "event")).findLast((v): v is string => v !== null);
|
|
129
|
+
// The value is used as SSE delivers it (one leading space stripped, nothing trimmed).
|
|
130
|
+
const event = eventLine === undefined ? null : eventLine;
|
|
131
|
+
const dataLine = lines
|
|
92
132
|
.map(l => sseFieldValue(l, "data"))
|
|
93
133
|
.filter((v): v is string => v !== null)
|
|
94
|
-
.join("");
|
|
134
|
+
.join("\n");
|
|
95
135
|
if (!dataLine) return;
|
|
96
136
|
let data: unknown;
|
|
97
|
-
try { data = JSON.parse(dataLine); } catch {
|
|
98
|
-
if (!isRec(data))
|
|
137
|
+
try { data = JSON.parse(dataLine); } catch { data = null; }
|
|
138
|
+
if (!isRec(data)) {
|
|
139
|
+
// A malformed event after a stop reason means the turn kept going and was cut.
|
|
140
|
+
if (delivered) lastDeliveredStop = null;
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
99
143
|
recordGenerationEvent(logCtx, data.type);
|
|
100
144
|
if (data.type === "message_start" && isRec(data.message) && isRec(data.message.usage)) {
|
|
101
145
|
usageAcc = { ...usageAcc, ...data.message.usage };
|
|
102
146
|
} else if (data.type === "message_delta" && isRec(data.usage)) {
|
|
103
147
|
usageAcc = { ...usageAcc, ...data.usage };
|
|
104
|
-
}
|
|
148
|
+
}
|
|
149
|
+
if (named(event, data, "message_stop") || named(event, data, "error")) {
|
|
105
150
|
terminalSeen = true;
|
|
151
|
+
} else if (delivered && !named(event, data, "ping")) {
|
|
152
|
+
const delta = isRec(data.delta) ? data.delta : undefined;
|
|
153
|
+
lastDeliveredStop = named(event, data, "message_delta") && typeof delta?.stop_reason === "string"
|
|
154
|
+
? delta.stop_reason
|
|
155
|
+
: null;
|
|
106
156
|
}
|
|
107
157
|
};
|
|
108
158
|
const inspect = (chunk: Uint8Array) => {
|
|
@@ -121,14 +171,24 @@ export function tapAnthropicSseForLog(
|
|
|
121
171
|
};
|
|
122
172
|
// The last block can sit in the buffer without its blank line: an upstream that stopped after
|
|
123
173
|
// it, or a held trailing CR. Count it before deciding how the turn ended (the Responses relay
|
|
124
|
-
// flushes the same candidate).
|
|
125
|
-
// client has not seen a blank line after, so the caller restores one.
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
174
|
+
// flushes the same candidate). terminalInTail: this flush found the terminal in a block the
|
|
175
|
+
// client has not seen a blank line after, so the caller restores one. tailClean: nothing but
|
|
176
|
+
// comments or a ping is left undelimited, so no message event was cut off.
|
|
177
|
+
const flushTail = (): { terminalInTail: boolean; tailClean: boolean } => {
|
|
178
|
+
// At EOF a held CR is a line ending, so it can complete a frame the client already has.
|
|
179
|
+
let tail = (buffer + decoder.decode()).replace(/\r\n?/g, "\n");
|
|
129
180
|
buffer = "";
|
|
130
|
-
|
|
131
|
-
|
|
181
|
+
let sep: number;
|
|
182
|
+
while ((sep = tail.indexOf("\n\n")) !== -1) {
|
|
183
|
+
inspectFrame(tail.slice(0, sep));
|
|
184
|
+
tail = tail.slice(sep + 2);
|
|
185
|
+
}
|
|
186
|
+
const terminalBefore = terminalSeen;
|
|
187
|
+
if (tail) inspectFrame(tail, false);
|
|
188
|
+
return {
|
|
189
|
+
terminalInTail: terminalSeen && !terminalBefore,
|
|
190
|
+
tailClean: isHarmlessSseTail(tail),
|
|
191
|
+
};
|
|
132
192
|
};
|
|
133
193
|
const reader = upstream.getReader();
|
|
134
194
|
let settled = false;
|
|
@@ -152,7 +212,7 @@ export function tapAnthropicSseForLog(
|
|
|
152
212
|
settled = true;
|
|
153
213
|
idle.cancel();
|
|
154
214
|
detachAbort();
|
|
155
|
-
const terminalInTail = flushTail();
|
|
215
|
+
const { terminalInTail } = flushTail();
|
|
156
216
|
recordUsage();
|
|
157
217
|
if (terminalSeen) {
|
|
158
218
|
// The turn already ended (message_stop or an upstream error event): an upstream that then
|
|
@@ -216,12 +276,44 @@ export function tapAnthropicSseForLog(
|
|
|
216
276
|
idle.pause();
|
|
217
277
|
if (settled) return; // stall/overflow/abort won the race while we awaited
|
|
218
278
|
if (done) {
|
|
279
|
+
// Bun can resolve a cancelled read as done before the abort listener runs: a client
|
|
280
|
+
// that left is a cancel, not a cut upstream.
|
|
281
|
+
if (guard?.reqSignal?.aborted) {
|
|
282
|
+
onClientAbort();
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
219
285
|
settled = true;
|
|
220
286
|
idle.cancel();
|
|
221
287
|
detachAbort();
|
|
288
|
+
const { terminalInTail, tailClean } = flushTail();
|
|
222
289
|
recordUsage();
|
|
223
|
-
|
|
224
|
-
|
|
290
|
+
// A clean EOF ends the turn only when the client already has its terminal, or a
|
|
291
|
+
// complete non-error stop_reason with nothing cut after it (compatible providers may
|
|
292
|
+
// omit message_stop; the translated adapter accepts the same shape). The opt-in
|
|
293
|
+
// anthropicEofTolerance profile keeps a content-only EOF as it always was.
|
|
294
|
+
const failure = terminalSeen
|
|
295
|
+
? null
|
|
296
|
+
: lastDeliveredStop === "error"
|
|
297
|
+
? 'upstream ended the turn with stop_reason "error"'
|
|
298
|
+
: !tailClean
|
|
299
|
+
? "anthropic passthrough upstream stream ended before message_stop"
|
|
300
|
+
: lastDeliveredStop !== null || guard?.eofTolerant === true
|
|
301
|
+
? null
|
|
302
|
+
: "anthropic passthrough upstream stream ended before message_stop";
|
|
303
|
+
if (failure === null) {
|
|
304
|
+
finalize(200, { closeReason: "terminal" });
|
|
305
|
+
if (terminalInTail) controller.enqueue(encoder.encode("\n\n"));
|
|
306
|
+
controller.close();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
// A body that stopped short is a failed turn, logged and surfaced like a mid-stream
|
|
310
|
+
// reset (below), so the client never reads a partial answer as a finished message.
|
|
311
|
+
logCtx.transportPhase = "mid_stream";
|
|
312
|
+
logCtx.terminalSource = "synthetic";
|
|
313
|
+
logCtx.upstreamError = failure;
|
|
314
|
+
if (logCtx.activeAttempt) logCtx.activeAttempt.streamAborted = true;
|
|
315
|
+
finalize(502, { terminalStatus: "failed", closeReason: "terminal" });
|
|
316
|
+
closeWithErrorFrame("api_error", failure);
|
|
225
317
|
return;
|
|
226
318
|
}
|
|
227
319
|
if (value.byteLength > 0) {
|
|
@@ -249,7 +341,7 @@ export function tapAnthropicSseForLog(
|
|
|
249
341
|
settled = true;
|
|
250
342
|
idle.cancel();
|
|
251
343
|
detachAbort();
|
|
252
|
-
const terminalInTail = flushTail();
|
|
344
|
+
const { terminalInTail } = flushTail();
|
|
253
345
|
recordUsage();
|
|
254
346
|
if (isTranslatorBudgetExceededError(err)) {
|
|
255
347
|
// A local cap, not an upstream failure: the non-streaming native Messages fold
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { getConfigDir } from "../config/paths";
|
|
5
|
+
import { withConfigMutationLockSync } from "../config/mutation-lock";
|
|
6
|
+
import { atomicWriteFileNoFollowStreamed } from "../config/atomic-write";
|
|
7
|
+
import type { OcxConfig } from "../types";
|
|
8
|
+
import { isLoopbackHostname, isTrustedHubManagementRequest, managementRequestOrigin } from "./auth-cors";
|
|
9
|
+
import { mintSession, type GuiSessionRecord, type GuiSessionState } from "./gui-session";
|
|
10
|
+
|
|
11
|
+
export const REMEMBERED_GUI_TTL_MS = 30 * 86400_000;
|
|
12
|
+
const RECORD_LIMIT = 128;
|
|
13
|
+
const STORE_LIMIT = 128 * 1024;
|
|
14
|
+
type State = GuiSessionState & { token: string };
|
|
15
|
+
interface DeviceRecord {
|
|
16
|
+
digest: string;
|
|
17
|
+
credential: string;
|
|
18
|
+
proof: string;
|
|
19
|
+
serverOrigin: string;
|
|
20
|
+
userAgent: string;
|
|
21
|
+
expiresAt: number;
|
|
22
|
+
}
|
|
23
|
+
const hash = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
24
|
+
const storePath = () => join(getConfigDir(), "dashboard-sessions.json");
|
|
25
|
+
|
|
26
|
+
function directOrigin(req: Request, config: OcxConfig): string | null {
|
|
27
|
+
const origin = managementRequestOrigin(req, config);
|
|
28
|
+
if (!origin) return null;
|
|
29
|
+
const url = new URL(origin);
|
|
30
|
+
// The process-marked hub management listener sits behind a local TLS terminator, so its
|
|
31
|
+
// request URL is http: while the canonical public origin is https:. Nothing forwarded is trusted.
|
|
32
|
+
if (new URL(req.url).origin !== origin && !isTrustedHubManagementRequest(req)) return null;
|
|
33
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHostname(url.hostname))) return null;
|
|
34
|
+
const browser = req.headers.get("Origin");
|
|
35
|
+
if (browser !== null && browser !== origin) return null;
|
|
36
|
+
const site = req.headers.get("Sec-Fetch-Site");
|
|
37
|
+
return site && site !== "same-origin" && site !== "none" ? null : origin;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function cookieName(origin: string): string {
|
|
41
|
+
return (origin.startsWith("https:") ? "__Host-" : "") + "ocx_dashboard_" + hash(origin).slice(0, 16);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function deviceDigest(req: Request, origin: string): string | null {
|
|
45
|
+
const name = cookieName(origin);
|
|
46
|
+
const matches = (req.headers.get("Cookie") ?? "").split(";").map(part => part.trim()).filter(part => part.startsWith(name + "="));
|
|
47
|
+
if (matches.length !== 1) return null;
|
|
48
|
+
const token = matches[0]!.slice(name.length + 1);
|
|
49
|
+
return /^ocx_device_[A-Za-z0-9_-]{43}$/.test(token) ? hash(token) : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function cookie(origin: string, token: string, maxAge: number): string {
|
|
53
|
+
return cookieName(origin) + "=" + token + "; Path=/; HttpOnly; SameSite=Strict; Max-Age=" + maxAge
|
|
54
|
+
+ (origin.startsWith("https:") ? "; Secure" : "");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function readRecords(): DeviceRecord[] {
|
|
58
|
+
const path = storePath();
|
|
59
|
+
let fd: number;
|
|
60
|
+
try { fd = openSync(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK)); }
|
|
61
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
|
|
62
|
+
try {
|
|
63
|
+
const stat = fstatSync(fd);
|
|
64
|
+
const entry = lstatSync(path);
|
|
65
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > STORE_LIMIT || entry.isSymbolicLink()
|
|
66
|
+
|| stat.dev !== entry.dev || stat.ino !== entry.ino) throw new Error("unsafe dashboard session store");
|
|
67
|
+
// Size the read from the stat we validated: a store that grows mid-read overflows
|
|
68
|
+
// the +1 sentinel byte and is rejected instead of silently truncated at a fixed limit.
|
|
69
|
+
const bytes = Buffer.alloc(stat.size + 1);
|
|
70
|
+
let length = 0;
|
|
71
|
+
while (length < bytes.length) { const count = readSync(fd, bytes, length, bytes.length - length, null); if (!count) break; length += count; }
|
|
72
|
+
if (length > stat.size) throw new Error("dashboard session store changed during read");
|
|
73
|
+
const value: unknown = JSON.parse(bytes.subarray(0, length).toString("utf8"));
|
|
74
|
+
if (!Array.isArray(value) || value.length > RECORD_LIMIT) throw new Error("invalid dashboard session store");
|
|
75
|
+
for (const row of value) {
|
|
76
|
+
if (!row || typeof row !== "object" || Object.keys(row).length !== 6
|
|
77
|
+
|| ![row.digest, row.credential, row.proof, row.userAgent].every(v => typeof v === "string" && /^[a-f0-9]{64}$/.test(v))
|
|
78
|
+
|| typeof row.serverOrigin !== "string" || row.serverOrigin.length > 2048
|
|
79
|
+
|| !Number.isSafeInteger(row.expiresAt) || row.expiresAt <= 0) throw new Error("invalid dashboard session record");
|
|
80
|
+
const url = new URL(row.serverOrigin);
|
|
81
|
+
if (url.origin !== row.serverOrigin || !["http:", "https:"].includes(url.protocol)) throw new Error("invalid dashboard session origin");
|
|
82
|
+
}
|
|
83
|
+
return value as DeviceRecord[];
|
|
84
|
+
} finally { closeSync(fd); }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function matches(row: DeviceRecord, req: Request, origin: string, state: State, now: number, ignoreUserAgent = false): boolean {
|
|
88
|
+
return row.serverOrigin === origin && row.credential === hash(state.token)
|
|
89
|
+
&& (ignoreUserAgent || row.userAgent === hash(req.headers.get("User-Agent") ?? "")) && row.expiresAt > now;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function mintDeviceSession(row: DeviceRecord, state: State, now: number) {
|
|
93
|
+
const session = mintSession(row.serverOrigin, row.serverOrigin, "remembered-admin", state, now);
|
|
94
|
+
const record = state.sessions.get(session.token)!;
|
|
95
|
+
record.persistentDigest = row.digest;
|
|
96
|
+
record.persistentExpiresAt = row.expiresAt;
|
|
97
|
+
session.expiresAt = Math.min(session.expiresAt, row.expiresAt);
|
|
98
|
+
return session;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function rememberGuiDevice(req: Request, config: OcxConfig, state: State, now = Date.now()) {
|
|
102
|
+
const origin = directOrigin(req, config);
|
|
103
|
+
if (req.method !== "POST" || !origin || req.headers.get("Origin") !== origin || req.body !== null) return null;
|
|
104
|
+
return withConfigMutationLockSync(() => {
|
|
105
|
+
const previous = deviceDigest(req, origin);
|
|
106
|
+
const rows = readRecords().filter(row => row.expiresAt > now && row.credential === hash(state.token));
|
|
107
|
+
// Re-sign-in replaces only this device, never another server or browser's record.
|
|
108
|
+
const retained = rows.filter(row => !(row.digest === previous && matches(row, req, origin, state, now)));
|
|
109
|
+
if (retained.length >= RECORD_LIMIT) throw new Error("dashboard device limit reached");
|
|
110
|
+
const token = "ocx_device_" + randomBytes(32).toString("base64url");
|
|
111
|
+
const proof = "ocx_proof_" + randomBytes(32).toString("base64url");
|
|
112
|
+
const row: DeviceRecord = { digest: hash(token), credential: hash(state.token), proof: hash(proof), serverOrigin: origin,
|
|
113
|
+
userAgent: hash(req.headers.get("User-Agent") ?? ""), expiresAt: now + REMEMBERED_GUI_TTL_MS };
|
|
114
|
+
atomicWriteFileNoFollowStreamed(storePath(), fd => writeFileSync(fd, JSON.stringify([...retained, row])));
|
|
115
|
+
return { session: mintDeviceSession(row, state, now), device: { proof }, cookie: cookie(origin, token, REMEMBERED_GUI_TTL_MS / 1000) };
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function resumeGuiDevice(req: Request, config: OcxConfig, state: State, now = Date.now()) {
|
|
120
|
+
const origin = directOrigin(req, config);
|
|
121
|
+
if (req.method !== "GET" || !origin) return null;
|
|
122
|
+
const digest = deviceDigest(req, origin);
|
|
123
|
+
const proof = req.headers.get("X-OpenCodex-Device-Proof");
|
|
124
|
+
if (!digest || !proof || !/^ocx_proof_[A-Za-z0-9_-]{43}$/.test(proof)) return null;
|
|
125
|
+
try {
|
|
126
|
+
const row = readRecords().find(row => row.digest === digest && row.proof === hash(proof) && matches(row, req, origin, state, now));
|
|
127
|
+
return row ? mintDeviceSession(row, state, now) : null;
|
|
128
|
+
} catch { return null; }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function rememberedGuiSessionIsCurrent(req: Request, config: OcxConfig, state: State, session: GuiSessionRecord, purpose: "access" | "logout" = "access"): boolean {
|
|
132
|
+
if (!session.persistentDigest) return true;
|
|
133
|
+
const origin = directOrigin(req, config);
|
|
134
|
+
if (!origin || deviceDigest(req, origin) !== session.persistentDigest) return false;
|
|
135
|
+
// Admission alone may tolerate browser updates for revocation; currentness and resume stay bound.
|
|
136
|
+
const revoking = purpose === "logout" && req.method === "POST" && new URL(req.url).pathname === "/api/session/logout";
|
|
137
|
+
try { return readRecords().some(row => row.digest === session.persistentDigest && matches(row, req, origin, state, Date.now(), revoking)); }
|
|
138
|
+
catch { return false; }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function forgetGuiDevice(req: Request, config: OcxConfig, state: State): string | null {
|
|
142
|
+
const origin = directOrigin(req, config);
|
|
143
|
+
if (!origin || req.method !== "POST") return null;
|
|
144
|
+
const digest = deviceDigest(req, origin);
|
|
145
|
+
if (digest) withConfigMutationLockSync(() => {
|
|
146
|
+
const rows = readRecords();
|
|
147
|
+
// User-Agent and expiry protect resumption, not deletion: a browser update between
|
|
148
|
+
// Remember and Forget must still remove the record Forget was reached through.
|
|
149
|
+
const found = rows.find(row => row.digest === digest && row.serverOrigin === origin
|
|
150
|
+
&& row.credential === hash(state.token));
|
|
151
|
+
if (found) atomicWriteFileNoFollowStreamed(storePath(), fd => writeFileSync(fd, JSON.stringify(rows.filter(row => row !== found))));
|
|
152
|
+
for (const [token, session] of state.sessions) if (session.persistentDigest === digest) state.sessions.delete(token);
|
|
153
|
+
});
|
|
154
|
+
return cookie(origin, "", 0);
|
|
155
|
+
}
|