@yansigit/opencodex 2.31.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/AGENTS_INSTALL.md +109 -0
- package/LICENSE +21 -0
- package/README.md +303 -0
- package/assets/architecture.png +0 -0
- package/assets/banner.png +0 -0
- package/assets/claude-code-models.gif +0 -0
- package/assets/codex-app-picker.png +0 -0
- package/bin/ocx.mjs +587 -0
- package/bin/package-main.mjs +9 -0
- package/gui/dist/assets/index-BNJ7r4Gd.js +102 -0
- package/gui/dist/assets/index-CGoDO3uO.css +1 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/icons.svg +24 -0
- package/gui/dist/index.html +25 -0
- package/gui/dist/logo.png +0 -0
- package/gui/dist/provider-icons/alibaba-color.svg +1 -0
- package/gui/dist/provider-icons/antigravity-color.svg +1 -0
- package/gui/dist/provider-icons/claude-color.svg +1 -0
- package/gui/dist/provider-icons/cline-color.svg +16 -0
- package/gui/dist/provider-icons/cloudflare-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/commandcode-color.svg +1 -0
- package/gui/dist/provider-icons/copilot-color.svg +1 -0
- package/gui/dist/provider-icons/cursor-color.svg +2 -0
- package/gui/dist/provider-icons/deepseek-color.svg +1 -0
- package/gui/dist/provider-icons/discord.svg +1 -0
- package/gui/dist/provider-icons/firepass-color.svg +1 -0
- package/gui/dist/provider-icons/fireworks-color.svg +1 -0
- package/gui/dist/provider-icons/gemini-color.svg +1 -0
- package/gui/dist/provider-icons/github-copilot-color.svg +1 -0
- package/gui/dist/provider-icons/gitlab-duo-color.svg +1 -0
- package/gui/dist/provider-icons/grok.svg +1 -0
- package/gui/dist/provider-icons/groq-color.svg +1 -0
- package/gui/dist/provider-icons/huggingface-color.svg +1 -0
- package/gui/dist/provider-icons/kimi-color.svg +1 -0
- package/gui/dist/provider-icons/kiro-color.svg +15 -0
- package/gui/dist/provider-icons/lm-studio-color.svg +1 -0
- package/gui/dist/provider-icons/mistral-color.svg +1 -0
- package/gui/dist/provider-icons/moonshot-color.svg +1 -0
- package/gui/dist/provider-icons/nvidia-color.svg +1 -0
- package/gui/dist/provider-icons/ollama-color.svg +1 -0
- package/gui/dist/provider-icons/openai.svg +1 -0
- package/gui/dist/provider-icons/opencode.svg +2 -0
- package/gui/dist/provider-icons/openrouter-color.svg +1 -0
- package/gui/dist/provider-icons/pi.svg +21 -0
- package/gui/dist/provider-icons/qianfan-color.svg +1 -0
- package/gui/dist/provider-icons/qwen-portal-color.svg +1 -0
- package/gui/dist/provider-icons/telegram.svg +1 -0
- package/gui/dist/provider-icons/vercel-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/vllm-color.svg +1 -0
- package/gui/dist/provider-icons/xiaomi-color.svg +1 -0
- package/package.json +108 -0
- package/src/AGENTS.md +28 -0
- package/src/adapters/anthropic-image-guard.ts +251 -0
- package/src/adapters/anthropic-image-normalize.ts +518 -0
- package/src/adapters/anthropic-output-schema.ts +137 -0
- package/src/adapters/anthropic.ts +1327 -0
- package/src/adapters/azure.ts +36 -0
- package/src/adapters/base.ts +121 -0
- package/src/adapters/client-fingerprint.ts +65 -0
- package/src/adapters/cline-pass-deepseek-v4-tool-replay.ts +69 -0
- package/src/adapters/command-code.ts +601 -0
- package/src/adapters/cursor/arg-codec.ts +38 -0
- package/src/adapters/cursor/arg-normalize.ts +104 -0
- package/src/adapters/cursor/checkpoint-store.ts +303 -0
- package/src/adapters/cursor/cursor-errors.ts +288 -0
- package/src/adapters/cursor/discovery.ts +333 -0
- package/src/adapters/cursor/effort-map.ts +151 -0
- package/src/adapters/cursor/exec-policy.ts +88 -0
- package/src/adapters/cursor/framing.ts +250 -0
- package/src/adapters/cursor/gen/agent_pb.ts +15274 -0
- package/src/adapters/cursor/h2-pool.ts +123 -0
- package/src/adapters/cursor/http1-bidi.ts +361 -0
- package/src/adapters/cursor/images.ts +704 -0
- package/src/adapters/cursor/kv-store.ts +52 -0
- package/src/adapters/cursor/live-models.ts +269 -0
- package/src/adapters/cursor/live-smoke-gate.ts +41 -0
- package/src/adapters/cursor/live-transport.ts +1653 -0
- package/src/adapters/cursor/mcp-config.ts +42 -0
- package/src/adapters/cursor/mcp-manager.ts +333 -0
- package/src/adapters/cursor/message-mapper.ts +49 -0
- package/src/adapters/cursor/native-exec-common.ts +76 -0
- package/src/adapters/cursor/native-exec-desktop.ts +184 -0
- package/src/adapters/cursor/native-exec-fs.ts +332 -0
- package/src/adapters/cursor/native-exec-mcp.ts +153 -0
- package/src/adapters/cursor/native-exec-network.ts +43 -0
- package/src/adapters/cursor/native-exec-shell.ts +547 -0
- package/src/adapters/cursor/native-exec-tools.ts +118 -0
- package/src/adapters/cursor/native-exec.ts +663 -0
- package/src/adapters/cursor/protobuf-events.ts +1381 -0
- package/src/adapters/cursor/protobuf-request.ts +1032 -0
- package/src/adapters/cursor/request-builder.ts +461 -0
- package/src/adapters/cursor/thread-continuity.ts +67 -0
- package/src/adapters/cursor/tool-definitions.ts +735 -0
- package/src/adapters/cursor/tool-result-normalize.ts +92 -0
- package/src/adapters/cursor/transport-retry.ts +132 -0
- package/src/adapters/cursor/transport.ts +79 -0
- package/src/adapters/cursor/types.ts +79 -0
- package/src/adapters/cursor.ts +322 -0
- package/src/adapters/google-antigravity-hosts.ts +48 -0
- package/src/adapters/google-antigravity-replay.ts +827 -0
- package/src/adapters/google-antigravity-tools.ts +105 -0
- package/src/adapters/google-antigravity-wire.ts +141 -0
- package/src/adapters/google-errors.ts +92 -0
- package/src/adapters/google-http.ts +460 -0
- package/src/adapters/google-tool-schema.ts +238 -0
- package/src/adapters/google-truncation.ts +24 -0
- package/src/adapters/google-wire-compiler.ts +232 -0
- package/src/adapters/google.ts +1377 -0
- package/src/adapters/identity.ts +77 -0
- package/src/adapters/image.ts +23 -0
- package/src/adapters/kiro-constants.ts +16 -0
- package/src/adapters/kiro-errors.ts +208 -0
- package/src/adapters/kiro-events.ts +197 -0
- package/src/adapters/kiro-images.ts +129 -0
- package/src/adapters/kiro-retry.ts +312 -0
- package/src/adapters/kiro-thinking.ts +112 -0
- package/src/adapters/kiro-tool-fallback.ts +36 -0
- package/src/adapters/kiro-tools.ts +224 -0
- package/src/adapters/kiro-truncation.ts +33 -0
- package/src/adapters/kiro-wire.ts +129 -0
- package/src/adapters/kiro.ts +1936 -0
- package/src/adapters/mimo-free.ts +280 -0
- package/src/adapters/openai-chat-url.ts +11 -0
- package/src/adapters/openai-chat.ts +1980 -0
- package/src/adapters/openai-responses-url.ts +16 -0
- package/src/adapters/openai-responses.ts +1911 -0
- package/src/adapters/registry.ts +175 -0
- package/src/adapters/responses-tool-schema.ts +67 -0
- package/src/adapters/run-turn-queue.ts +114 -0
- package/src/adapters/tool-call-id.ts +119 -0
- package/src/adapters/tool-catalog-nudge.ts +154 -0
- package/src/adapters/upstream-http-error.ts +48 -0
- package/src/adapters/xai-web-search.ts +185 -0
- package/src/bridge.ts +1986 -0
- package/src/chat/inbound.ts +319 -0
- package/src/chat/outbound.ts +821 -0
- package/src/claude/agents-inject.ts +266 -0
- package/src/claude/alias.ts +149 -0
- package/src/claude/auth-detect.ts +229 -0
- package/src/claude/auth-mode-migration.ts +32 -0
- package/src/claude/auth-mode.ts +62 -0
- package/src/claude/context-windows.ts +205 -0
- package/src/claude/desktop-3p-guard.ts +35 -0
- package/src/claude/desktop-3p-paths.ts +84 -0
- package/src/claude/desktop-3p.ts +615 -0
- package/src/claude/desktop-health.ts +26 -0
- package/src/claude/desktop-profile.ts +263 -0
- package/src/claude/gateway-cache.ts +107 -0
- package/src/claude/inbound-debug.ts +163 -0
- package/src/claude/inbound.ts +578 -0
- package/src/claude/model-info.ts +174 -0
- package/src/claude/outbound.ts +926 -0
- package/src/cli/access.ts +108 -0
- package/src/cli/account-api.ts +302 -0
- package/src/cli/account-auth.ts +250 -0
- package/src/cli/account-catalog-refresh.ts +14 -0
- package/src/cli/account-extended.ts +737 -0
- package/src/cli/account-main.ts +317 -0
- package/src/cli/account.ts +299 -0
- package/src/cli/agent-driven.ts +70 -0
- package/src/cli/agent.ts +290 -0
- package/src/cli/catalog-prewarm.ts +27 -0
- package/src/cli/claude-agent-startup-sync.ts +73 -0
- package/src/cli/claude-desktop.ts +213 -0
- package/src/cli/claude.ts +355 -0
- package/src/cli/codex-log-guard-doctor.ts +103 -0
- package/src/cli/codex-shim-autorestore.ts +47 -0
- package/src/cli/codex-shim-readiness.ts +76 -0
- package/src/cli/combo.ts +127 -0
- package/src/cli/config-command.ts +209 -0
- package/src/cli/debug.ts +228 -0
- package/src/cli/dispatch.ts +585 -0
- package/src/cli/doctor.ts +1202 -0
- package/src/cli/ensure-desired-integrations.ts +152 -0
- package/src/cli/export-command.ts +213 -0
- package/src/cli/help.ts +101 -0
- package/src/cli/index.ts +973 -0
- package/src/cli/init.ts +211 -0
- package/src/cli/integrations.ts +260 -0
- package/src/cli/interactive-confirm.ts +133 -0
- package/src/cli/lab.ts +607 -0
- package/src/cli/launcher-context.ts +77 -0
- package/src/cli/minimax.ts +497 -0
- package/src/cli/models-runtime.ts +245 -0
- package/src/cli/models.ts +422 -0
- package/src/cli/observe.ts +206 -0
- package/src/cli/opencode.ts +588 -0
- package/src/cli/provider-replit.ts +232 -0
- package/src/cli/provider-runtime.ts +179 -0
- package/src/cli/provider.ts +492 -0
- package/src/cli/ready.ts +301 -0
- package/src/cli/registry.ts +422 -0
- package/src/cli/replit-gateway-key-input.ts +138 -0
- package/src/cli/root.ts +86 -0
- package/src/cli/route-policy.ts +92 -0
- package/src/cli/runtime-api.ts +328 -0
- package/src/cli/star-prompt.ts +211 -0
- package/src/cli/status-oauth.ts +78 -0
- package/src/cli/status.ts +328 -0
- package/src/cli/system-command.ts +112 -0
- package/src/cli/system-restart-client.ts +146 -0
- package/src/cli/tray-proxy.ts +199 -0
- package/src/cli/v2.ts +268 -0
- package/src/cli.ts +10 -0
- package/src/clients/config-export.ts +1704 -0
- package/src/codex/account-id.ts +34 -0
- package/src/codex/account-label.ts +47 -0
- package/src/codex/account-lifecycle.ts +172 -0
- package/src/codex/account-namespace-match.ts +63 -0
- package/src/codex/account-namespaces.ts +195 -0
- package/src/codex/account-pause.ts +20 -0
- package/src/codex/account-priority.ts +83 -0
- package/src/codex/account-runtime-state.ts +31 -0
- package/src/codex/account-store.ts +544 -0
- package/src/codex/account-usability.ts +43 -0
- package/src/codex/admission.ts +256 -0
- package/src/codex/affinity-debug.ts +162 -0
- package/src/codex/agent-roles-sync.ts +225 -0
- package/src/codex/agent-roles.ts +238 -0
- package/src/codex/app-server-processes.ts +1143 -0
- package/src/codex/app-server-restart-service.ts +232 -0
- package/src/codex/auth-api.ts +2147 -0
- package/src/codex/auth-collision.ts +109 -0
- package/src/codex/auth-context.ts +665 -0
- package/src/codex/autostart-health.ts +156 -0
- package/src/codex/catalog/account-models.ts +67 -0
- package/src/codex/catalog/aggregation.ts +436 -0
- package/src/codex/catalog/bundled.ts +549 -0
- package/src/codex/catalog/effort.ts +446 -0
- package/src/codex/catalog/filesystem-evidence.ts +302 -0
- package/src/codex/catalog/kinds.ts +2 -0
- package/src/codex/catalog/metadata.ts +664 -0
- package/src/codex/catalog/native-models.ts +72 -0
- package/src/codex/catalog/parsing.ts +650 -0
- package/src/codex/catalog/provider-fetch.ts +2064 -0
- package/src/codex/catalog/sync.ts +1883 -0
- package/src/codex/catalog-admission.ts +199 -0
- package/src/codex/catalog-refresh-status.ts +105 -0
- package/src/codex/catalog-write-serialization.ts +242 -0
- package/src/codex/catalog.ts +14 -0
- package/src/codex/codex-write-lock.ts +384 -0
- package/src/codex/convergence-types.ts +614 -0
- package/src/codex/convergence.ts +651 -0
- package/src/codex/coordinator-doctor.ts +332 -0
- package/src/codex/custom-model-catalog-migration.ts +176 -0
- package/src/codex/data/upstream-models.json +830 -0
- package/src/codex/desired-state.ts +230 -0
- package/src/codex/exec-invocation.ts +22 -0
- package/src/codex/features.ts +1566 -0
- package/src/codex/generation.ts +202 -0
- package/src/codex/history-job.ts +407 -0
- package/src/codex/history-lock.ts +242 -0
- package/src/codex/history-migration-guardian.ts +108 -0
- package/src/codex/history-provider.ts +979 -0
- package/src/codex/history-transition.ts +105 -0
- package/src/codex/history-worker.ts +220 -0
- package/src/codex/home.ts +206 -0
- package/src/codex/inject-coordination.ts +290 -0
- package/src/codex/inject.ts +1733 -0
- package/src/codex/injected-marker.ts +106 -0
- package/src/codex/integration-record.ts +266 -0
- package/src/codex/internal/catalog-writer.ts +203 -0
- package/src/codex/internal/history-writer.ts +80 -0
- package/src/codex/journal.ts +225 -0
- package/src/codex/log-guard/inspect.ts +506 -0
- package/src/codex/log-guard/lock.ts +150 -0
- package/src/codex/log-guard/maintenance.ts +403 -0
- package/src/codex/log-guard/path-safety.ts +88 -0
- package/src/codex/log-guard/policy.ts +44 -0
- package/src/codex/log-guard/processes.ts +205 -0
- package/src/codex/log-guard/protection.ts +489 -0
- package/src/codex/log-guard/sqlite-errors.ts +9 -0
- package/src/codex/main-account-cache.ts +56 -0
- package/src/codex/main-account.ts +68 -0
- package/src/codex/management-convergence.ts +167 -0
- package/src/codex/model-cache.ts +273 -0
- package/src/codex/model-entitlements.ts +353 -0
- package/src/codex/native-main-admission.ts +47 -0
- package/src/codex/native-main-auth-temp.ts +187 -0
- package/src/codex/native-main-claim.ts +178 -0
- package/src/codex/native-main-lock-file.ts +162 -0
- package/src/codex/native-main-owner.ts +329 -0
- package/src/codex/native-profile-api.ts +247 -0
- package/src/codex/native-profile-manager.ts +1531 -0
- package/src/codex/native-profile-processes.ts +121 -0
- package/src/codex/native-profile-recovery.ts +99 -0
- package/src/codex/native-profile-stage-store.ts +387 -0
- package/src/codex/native-profile-startup.ts +492 -0
- package/src/codex/native-profile-store.ts +855 -0
- package/src/codex/native-profile-types.ts +120 -0
- package/src/codex/native-residue.ts +682 -0
- package/src/codex/paths.ts +144 -0
- package/src/codex/plan-from-token.ts +140 -0
- package/src/codex/plan.ts +40 -0
- package/src/codex/plugins-doctor.ts +242 -0
- package/src/codex/pool-rotation.ts +295 -0
- package/src/codex/project-config-warnings.ts +425 -0
- package/src/codex/prompt-journal.ts +352 -0
- package/src/codex/prompt-layers.ts +967 -0
- package/src/codex/prompt-lock.ts +143 -0
- package/src/codex/quota-rejection.ts +298 -0
- package/src/codex/quota.ts +573 -0
- package/src/codex/refresh.ts +62 -0
- package/src/codex/reset-credit-recovery.ts +1044 -0
- package/src/codex/routing.ts +1888 -0
- package/src/codex/runtime.ts +659 -0
- package/src/codex/shim.ts +2170 -0
- package/src/codex/subagent-defaults.ts +550 -0
- package/src/codex/subagent-model-fallback.ts +784 -0
- package/src/codex/sync.ts +319 -0
- package/src/codex/transition-state.ts +612 -0
- package/src/codex/upstream-host-health.ts +368 -0
- package/src/codex/user-identity.ts +557 -0
- package/src/codex/warmup.ts +298 -0
- package/src/codex/websocket-registry.ts +100 -0
- package/src/codex/write-coordination.ts +114 -0
- package/src/combos/failover.ts +160 -0
- package/src/combos/index.ts +45 -0
- package/src/combos/request.ts +94 -0
- package/src/combos/resolve.ts +232 -0
- package/src/combos/types.ts +398 -0
- package/src/config/provider-name.ts +24 -0
- package/src/config.ts +4041 -0
- package/src/fork/register.ts +3 -0
- package/src/generated/compatibility-version.json +3116 -0
- package/src/generated/model-metadata.ts +106 -0
- package/src/github/star-state.ts +203 -0
- package/src/grok/inject.ts +530 -0
- package/src/grok/inspect.ts +45 -0
- package/src/grok/status.ts +121 -0
- package/src/grok/sync.ts +66 -0
- package/src/images/artifacts.ts +516 -0
- package/src/images/fulfill-video.ts +163 -0
- package/src/images/fulfill.ts +149 -0
- package/src/images/index.ts +4 -0
- package/src/images/loop.ts +955 -0
- package/src/images/plan.ts +143 -0
- package/src/images/synthetic-tool.ts +133 -0
- package/src/images/types.ts +41 -0
- package/src/images/xai-client.ts +141 -0
- package/src/images/xai-video-client.ts +163 -0
- package/src/index.ts +22 -0
- package/src/integrations/config-io.ts +269 -0
- package/src/integrations/journal.ts +315 -0
- package/src/integrations/merge.ts +135 -0
- package/src/integrations/mutation-flight.ts +71 -0
- package/src/integrations/native/ownership-preflight.ts +202 -0
- package/src/integrations/omp-yaml-source.ts +358 -0
- package/src/integrations/owned-refresh.ts +74 -0
- package/src/integrations/ownership.ts +111 -0
- package/src/integrations/registry.ts +159 -0
- package/src/integrations/serialize.ts +314 -0
- package/src/integrations/state.ts +361 -0
- package/src/integrations/store.ts +103 -0
- package/src/integrations/writer-lock.ts +98 -0
- package/src/integrations/writer.ts +691 -0
- package/src/lab/artifacts/sanitize.ts +586 -0
- package/src/lab/artifacts/secure-fs.ts +475 -0
- package/src/lab/artifacts/store.ts +310 -0
- package/src/lab/automation/budgets.ts +78 -0
- package/src/lab/automation/config-persistence.ts +256 -0
- package/src/lab/automation/constants.ts +39 -0
- package/src/lab/automation/cooldown.ts +103 -0
- package/src/lab/automation/dispatch.ts +211 -0
- package/src/lab/automation/index.ts +13 -0
- package/src/lab/automation/orchestrator.ts +499 -0
- package/src/lab/automation/persistence.ts +512 -0
- package/src/lab/automation/planner.ts +371 -0
- package/src/lab/automation/policy.ts +136 -0
- package/src/lab/automation/queue.ts +191 -0
- package/src/lab/automation/recovery.ts +24 -0
- package/src/lab/automation/route-context.ts +21 -0
- package/src/lab/automation/run-key.ts +44 -0
- package/src/lab/automation/runs-query.ts +34 -0
- package/src/lab/automation/types.ts +160 -0
- package/src/lab/conformance/assertion.ts +325 -0
- package/src/lab/conformance/digest.ts +22 -0
- package/src/lab/conformance/executor.ts +741 -0
- package/src/lab/conformance/fixture-provider.ts +27 -0
- package/src/lab/conformance/fixtures/live-v1-cases.json +175 -0
- package/src/lab/conformance/fixtures/protocol-v1-cases.json +461 -0
- package/src/lab/conformance/harness-budget.ts +47 -0
- package/src/lab/conformance/index.ts +5 -0
- package/src/lab/conformance/jcs.ts +64 -0
- package/src/lab/conformance/json-pointer.ts +39 -0
- package/src/lab/conformance/manifest.ts +180 -0
- package/src/lab/conformance/mcp-stub.ts +179 -0
- package/src/lab/conformance/negative-controls.ts +164 -0
- package/src/lab/conformance/observation.ts +355 -0
- package/src/lab/conformance/runner.ts +68 -0
- package/src/lab/conformance/sse-normalize.ts +59 -0
- package/src/lab/conformance/suite-manifest.ts +78 -0
- package/src/lab/conformance/types.ts +214 -0
- package/src/lab/constants.ts +126 -0
- package/src/lab/digest.ts +64 -0
- package/src/lab/events/errors.ts +9 -0
- package/src/lab/events/limits.ts +117 -0
- package/src/lab/events/types.ts +229 -0
- package/src/lab/events/validate.ts +781 -0
- package/src/lab/fabric/constants.ts +40 -0
- package/src/lab/fabric/executor.ts +492 -0
- package/src/lab/fabric/index.ts +80 -0
- package/src/lab/fabric/manifest.ts +222 -0
- package/src/lab/fabric/observe.ts +489 -0
- package/src/lab/fabric/patch.ts +79 -0
- package/src/lab/fabric/producer-child.ts +139 -0
- package/src/lab/fabric/producer-isolate.ts +276 -0
- package/src/lab/fabric/producer-protocol.ts +61 -0
- package/src/lab/fabric/scratch.ts +439 -0
- package/src/lab/fabric/subject.ts +106 -0
- package/src/lab/fabric/types.ts +134 -0
- package/src/lab/fabric/verifier.ts +98 -0
- package/src/lab/index.ts +54 -0
- package/src/lab/ledger/artifact-refs.ts +127 -0
- package/src/lab/ledger/invalidation.ts +136 -0
- package/src/lab/ledger/purge.ts +310 -0
- package/src/lab/ledger/store.ts +532 -0
- package/src/lab/live/credential-lease.ts +53 -0
- package/src/lab/live/destination.ts +155 -0
- package/src/lab/live/executor.ts +336 -0
- package/src/lab/live/inert-tools.ts +56 -0
- package/src/lab/live/manifest.ts +85 -0
- package/src/lab/live/mcp-loopback.ts +57 -0
- package/src/lab/live/runner.ts +19 -0
- package/src/lab/live/sandbox.ts +61 -0
- package/src/lab/live/suite-manifest.ts +41 -0
- package/src/lab/live/transport.ts +118 -0
- package/src/lab/live/types.ts +197 -0
- package/src/lab/observe/from-conformance.ts +301 -0
- package/src/lab/observe/from-live.ts +117 -0
- package/src/lab/paths.ts +153 -0
- package/src/lab/projection/rebuild.ts +495 -0
- package/src/lab/projection/schema.ts +135 -0
- package/src/lab/projection/verdicts.ts +474 -0
- package/src/lab/projection/verification.ts +412 -0
- package/src/lab/public/bundle.ts +217 -0
- package/src/lab/public/community-authority.ts +175 -0
- package/src/lab/public/community-files.ts +29 -0
- package/src/lab/public/community.ts +479 -0
- package/src/lab/public/file-safety.ts +155 -0
- package/src/lab/public/ids.ts +26 -0
- package/src/lab/public/index.ts +16 -0
- package/src/lab/public/mutation-lock.ts +424 -0
- package/src/lab/public/operator.ts +353 -0
- package/src/lab/public/origin-purge.ts +79 -0
- package/src/lab/public/origin.ts +203 -0
- package/src/lab/public/privacy.ts +143 -0
- package/src/lab/public/private-file.ts +261 -0
- package/src/lab/public/project.ts +124 -0
- package/src/lab/public/purge-test-fault.ts +21 -0
- package/src/lab/public/purge.ts +223 -0
- package/src/lab/public/registry.ts +44 -0
- package/src/lab/public/revocation.ts +252 -0
- package/src/lab/public/signature.ts +243 -0
- package/src/lab/public/storage.ts +105 -0
- package/src/lab/public/strict-json.ts +206 -0
- package/src/lab/public/time.ts +26 -0
- package/src/lab/public/types.ts +172 -0
- package/src/lab/public/validate.ts +391 -0
- package/src/lab/query/catalog.ts +101 -0
- package/src/lab/query/connection.ts +107 -0
- package/src/lab/query/constants.ts +4 -0
- package/src/lab/query/cursor.ts +132 -0
- package/src/lab/query/dto-map.ts +277 -0
- package/src/lab/query/errors.ts +22 -0
- package/src/lab/query/freshness.ts +53 -0
- package/src/lab/query/index.ts +45 -0
- package/src/lab/query/latest-observation.ts +59 -0
- package/src/lab/query/passive-production.ts +159 -0
- package/src/lab/query/queries.ts +444 -0
- package/src/lab/query/types.ts +266 -0
- package/src/lab/subject/behavior-fingerprint.ts +77 -0
- package/src/lab/subject/installation-salt.ts +112 -0
- package/src/lab/subject/protocol-subject.ts +80 -0
- package/src/lab/subject/route-subject.ts +74 -0
- package/src/lib/abort.ts +146 -0
- package/src/lib/admin-secrets.ts +25 -0
- package/src/lib/admission.ts +83 -0
- package/src/lib/app-owned-memory-stores.ts +195 -0
- package/src/lib/app-owned-memory.ts +265 -0
- package/src/lib/bounded-body.ts +346 -0
- package/src/lib/bun-binary-validator.d.mts +3 -0
- package/src/lib/bun-binary-validator.mjs +18 -0
- package/src/lib/bun-runtime.ts +184 -0
- package/src/lib/bun-stream-caps.ts +130 -0
- package/src/lib/codex-restart-contract.ts +120 -0
- package/src/lib/config-ownership.ts +364 -0
- package/src/lib/crash-guard.ts +344 -0
- package/src/lib/debug-log-buffer.ts +83 -0
- package/src/lib/debug-settings.ts +108 -0
- package/src/lib/debug.ts +31 -0
- package/src/lib/destination-policy.ts +380 -0
- package/src/lib/errors.ts +406 -0
- package/src/lib/eventstream-decoder.ts +253 -0
- package/src/lib/fabric-task-execution-authority.ts +7 -0
- package/src/lib/fabric-task-host.ts +29 -0
- package/src/lib/gcp-adc.ts +341 -0
- package/src/lib/injection-debug-log.ts +58 -0
- package/src/lib/lab-activation.ts +223 -0
- package/src/lib/lab-live-execution-authority.ts +13 -0
- package/src/lib/lab-live-host.ts +30 -0
- package/src/lib/lab-live-pinned-sender.ts +56 -0
- package/src/lib/lab-live-route-production.ts +130 -0
- package/src/lib/lab-passive-linker-registration.ts +26 -0
- package/src/lib/local-management-attestation.ts +51 -0
- package/src/lib/local-management-capability.ts +100 -0
- package/src/lib/local-provider-reload-contract.ts +100 -0
- package/src/lib/open-url.ts +25 -0
- package/src/lib/optional-shutdown-hooks.ts +57 -0
- package/src/lib/pinned-http.ts +270 -0
- package/src/lib/privacy.ts +20 -0
- package/src/lib/process-control.ts +168 -0
- package/src/lib/provider-outbound.ts +210 -0
- package/src/lib/provider-url.ts +14 -0
- package/src/lib/proxy-env.ts +18 -0
- package/src/lib/redact.ts +521 -0
- package/src/lib/retry-after.ts +55 -0
- package/src/lib/self-launch-argv.ts +15 -0
- package/src/lib/server-resource-ownership.ts +71 -0
- package/src/lib/service-secrets.ts +25 -0
- package/src/lib/shadow-call.ts +61 -0
- package/src/lib/sidecar-tracker.ts +52 -0
- package/src/lib/sse-decoder.ts +364 -0
- package/src/lib/state-store-registrations.ts +119 -0
- package/src/lib/state-store-sweeper.ts +184 -0
- package/src/lib/system-restart-contract.ts +73 -0
- package/src/lib/test-home-guard.ts +90 -0
- package/src/lib/token-estimate.ts +86 -0
- package/src/lib/tool-argument-integers.ts +202 -0
- package/src/lib/translator-budget.ts +400 -0
- package/src/lib/upstream-http-version.ts +57 -0
- package/src/lib/upstream-reachability.ts +95 -0
- package/src/lib/upstream-retry.ts +392 -0
- package/src/lib/win-exec.ts +115 -0
- package/src/lib/win-paths.ts +68 -0
- package/src/lib/windows-atomic-replace.ts +156 -0
- package/src/lib/windows-elevation.ts +773 -0
- package/src/lib/windows-secret-acl.ts +854 -0
- package/src/lib/windows-service-wrappers.ts +72 -0
- package/src/lib/windows-text.ts +106 -0
- package/src/lib/windows-user-principal.ts +341 -0
- package/src/lib/winsw.ts +403 -0
- package/src/oauth/account-import/google-antigravity-adapter.ts +74 -0
- package/src/oauth/account-import/index.ts +15 -0
- package/src/oauth/account-import/parser.ts +83 -0
- package/src/oauth/account-import/registry.ts +18 -0
- package/src/oauth/account-import/service.ts +75 -0
- package/src/oauth/account-import/types.ts +91 -0
- package/src/oauth/anthropic-routing.ts +594 -0
- package/src/oauth/anthropic.ts +188 -0
- package/src/oauth/antigravity-routing.ts +151 -0
- package/src/oauth/callback-server.ts +300 -0
- package/src/oauth/chatgpt.ts +161 -0
- package/src/oauth/command-code.ts +239 -0
- package/src/oauth/cursor.ts +252 -0
- package/src/oauth/github-copilot.ts +428 -0
- package/src/oauth/google-antigravity.ts +262 -0
- package/src/oauth/health.ts +407 -0
- package/src/oauth/index.ts +1504 -0
- package/src/oauth/key-providers.ts +124 -0
- package/src/oauth/kimi.ts +227 -0
- package/src/oauth/kiro-credentials.ts +726 -0
- package/src/oauth/kiro.ts +621 -0
- package/src/oauth/local-token-detect.ts +130 -0
- package/src/oauth/log.ts +50 -0
- package/src/oauth/login-cli.ts +223 -0
- package/src/oauth/nous.ts +798 -0
- package/src/oauth/pkce.ts +15 -0
- package/src/oauth/store.ts +728 -0
- package/src/oauth/token-guardian.ts +309 -0
- package/src/oauth/types.ts +62 -0
- package/src/oauth/xai.ts +241 -0
- package/src/providers/alibaba-region-backup.ts +75 -0
- package/src/providers/alibaba-region-migration.ts +156 -0
- package/src/providers/alibaba-region-startup.ts +36 -0
- package/src/providers/antigravity-models.ts +695 -0
- package/src/providers/antigravity-quota.ts +216 -0
- package/src/providers/api-keys.ts +140 -0
- package/src/providers/base-url-choices.ts +74 -0
- package/src/providers/codex-capacity.ts +292 -0
- package/src/providers/command-code-efforts.ts +144 -0
- package/src/providers/context-cap.ts +82 -0
- package/src/providers/cursor-pool.ts +72 -0
- package/src/providers/derive.ts +586 -0
- package/src/providers/fastwire.ts +501 -0
- package/src/providers/free-directory.ts +187 -0
- package/src/providers/github-copilot-transport.ts +56 -0
- package/src/providers/google-vertex-location.ts +14 -0
- package/src/providers/key-failover.ts +271 -0
- package/src/providers/kiro-models.ts +67 -0
- package/src/providers/label.ts +19 -0
- package/src/providers/model-discovery-limits.ts +16 -0
- package/src/providers/model-discovery.ts +449 -0
- package/src/providers/model-rename-migration.ts +255 -0
- package/src/providers/model-rename-startup.ts +28 -0
- package/src/providers/openai-sidecar.ts +243 -0
- package/src/providers/openai-tier-startup.ts +56 -0
- package/src/providers/openai-tiers.ts +423 -0
- package/src/providers/openai-virtual-models.ts +83 -0
- package/src/providers/opencode-zen-rate-limit.ts +102 -0
- package/src/providers/openrouter-routing.ts +102 -0
- package/src/providers/provider-id-rewrite.ts +185 -0
- package/src/providers/quota.ts +2345 -0
- package/src/providers/registry.ts +2918 -0
- package/src/providers/replit/constants.ts +27 -0
- package/src/providers/replit/derive.ts +85 -0
- package/src/providers/replit/headers.ts +28 -0
- package/src/providers/replit/origin.ts +55 -0
- package/src/providers/replit/pair-install-response.ts +72 -0
- package/src/providers/replit/probe.ts +199 -0
- package/src/providers/replit/setup.ts +350 -0
- package/src/providers/request-pacing.ts +310 -0
- package/src/providers/service-tier.ts +277 -0
- package/src/providers/slug-codec.ts +103 -0
- package/src/providers/static-model-discovery.ts +86 -0
- package/src/providers/xai-responses-opt-in.ts +15 -0
- package/src/providers/xai-transport.ts +148 -0
- package/src/reasoning-effort.ts +183 -0
- package/src/responses/compaction.ts +142 -0
- package/src/responses/custom-tool-compat.ts +266 -0
- package/src/responses/hosted-tool-policy.ts +9 -0
- package/src/responses/namespace-tool-compat.ts +355 -0
- package/src/responses/parser.ts +838 -0
- package/src/responses/provider-continuation.ts +98 -0
- package/src/responses/provider-opaque-metadata.ts +73 -0
- package/src/responses/reasoning-envelope.ts +60 -0
- package/src/responses/reasoning-replay-cache.ts +426 -0
- package/src/responses/schema.ts +165 -0
- package/src/responses/spill-store.ts +459 -0
- package/src/responses/state.ts +1433 -0
- package/src/responses/thought-signature-replay.ts +347 -0
- package/src/responses/tool-groups.ts +19 -0
- package/src/responses/tool-search-compat.ts +301 -0
- package/src/responses/truncated-stop-reason.ts +60 -0
- package/src/router.ts +761 -0
- package/src/routing/analytics.ts +378 -0
- package/src/routing/capability.ts +244 -0
- package/src/routing/compatibility/assemble.ts +73 -0
- package/src/routing/compatibility/behavior.ts +278 -0
- package/src/routing/compatibility/catalog.ts +99 -0
- package/src/routing/compatibility/endpoint.ts +52 -0
- package/src/routing/compatibility/lab-evidence-provider.ts +130 -0
- package/src/routing/compatibility/policy.ts +181 -0
- package/src/routing/compatibility/provider-slot.ts +56 -0
- package/src/routing/compatibility/reader.ts +110 -0
- package/src/routing/compatibility/subject.ts +191 -0
- package/src/routing/compatibility/types.ts +64 -0
- package/src/routing/compatibility/version.ts +104 -0
- package/src/routing/cost.ts +77 -0
- package/src/routing/evaluator.ts +495 -0
- package/src/routing/health.ts +412 -0
- package/src/routing/history/cursor.ts +43 -0
- package/src/routing/history/indexer.ts +605 -0
- package/src/routing/history/schema.ts +72 -0
- package/src/routing/profile-namespace.ts +15 -0
- package/src/routing/profile.ts +547 -0
- package/src/routing/quota.ts +145 -0
- package/src/routing/request-evidence.ts +45 -0
- package/src/routing/trace.ts +776 -0
- package/src/server/adapter-resolve.ts +53 -0
- package/src/server/auth-cors.ts +751 -0
- package/src/server/background-lifecycle.ts +182 -0
- package/src/server/chat-completions.ts +442 -0
- package/src/server/chat-native-sse.ts +331 -0
- package/src/server/chat-native.ts +426 -0
- package/src/server/claude-messages.ts +1030 -0
- package/src/server/direct-local-http.ts +347 -0
- package/src/server/effort-policy.ts +190 -0
- package/src/server/github-copilot-responses-repair.ts +338 -0
- package/src/server/gui-static.ts +152 -0
- package/src/server/image-retry.ts +42 -0
- package/src/server/images.ts +568 -0
- package/src/server/index.ts +1813 -0
- package/src/server/lifecycle.ts +498 -0
- package/src/server/live.ts +717 -0
- package/src/server/local-management-read-client.ts +90 -0
- package/src/server/local-provider-reload-client.ts +137 -0
- package/src/server/management/agent-settings-routes.ts +1433 -0
- package/src/server/management/api-access.ts +141 -0
- package/src/server/management/api-key-usage.ts +193 -0
- package/src/server/management/body.ts +41 -0
- package/src/server/management/combo-routes.ts +263 -0
- package/src/server/management/config-routes.ts +835 -0
- package/src/server/management/context.ts +113 -0
- package/src/server/management/integration-routes.ts +498 -0
- package/src/server/management/lab-automation-routes.ts +206 -0
- package/src/server/management/lab-routes.ts +563 -0
- package/src/server/management/logs-usage-routes.ts +586 -0
- package/src/server/management/model-routes.ts +560 -0
- package/src/server/management/model-rows.ts +163 -0
- package/src/server/management/native-integration-routes.ts +769 -0
- package/src/server/management/oauth-account-routes.ts +637 -0
- package/src/server/management/provider-capability-config.ts +48 -0
- package/src/server/management/provider-routes.ts +1033 -0
- package/src/server/management/replit-provider-routes.ts +86 -0
- package/src/server/management/request-history-routes.ts +191 -0
- package/src/server/management/routing-analytics-routes.ts +74 -0
- package/src/server/management/routing-profile-routes.ts +385 -0
- package/src/server/management/shared.ts +286 -0
- package/src/server/management/sidebar-routes.ts +106 -0
- package/src/server/management/storage-log-guard-routes.ts +186 -0
- package/src/server/management/sync-response.ts +69 -0
- package/src/server/management/system-restart.ts +435 -0
- package/src/server/management/system-routes.ts +194 -0
- package/src/server/management/usage-summary-cache.ts +94 -0
- package/src/server/management/vision-sidecar-options.ts +167 -0
- package/src/server/management/web-search-sidecar-options.ts +120 -0
- package/src/server/management-api.ts +314 -0
- package/src/server/management-auth.ts +482 -0
- package/src/server/memory-watchdog.ts +156 -0
- package/src/server/passive-route-linker.ts +66 -0
- package/src/server/port-reclaim.ts +307 -0
- package/src/server/ports.ts +156 -0
- package/src/server/proxy-liveness.ts +328 -0
- package/src/server/readiness.ts +99 -0
- package/src/server/relay-eager.ts +353 -0
- package/src/server/relay.ts +1209 -0
- package/src/server/request-decompress.ts +239 -0
- package/src/server/request-log-conversation.ts +168 -0
- package/src/server/request-log.ts +1259 -0
- package/src/server/responses/agent-task-recovery-cache.ts +143 -0
- package/src/server/responses/agent-task-recovery.ts +465 -0
- package/src/server/responses/collaboration.ts +551 -0
- package/src/server/responses/compact.ts +771 -0
- package/src/server/responses/core.ts +5389 -0
- package/src/server/responses/empty-completion-guard.ts +276 -0
- package/src/server/responses/encrypted-payload.ts +331 -0
- package/src/server/responses/fetch-helpers.ts +232 -0
- package/src/server/responses/input-admission.ts +185 -0
- package/src/server/responses/pacing-overload.ts +13 -0
- package/src/server/responses/passthrough-error.ts +78 -0
- package/src/server/responses/policy-fallback.ts +178 -0
- package/src/server/responses/responses-field-backfill.ts +251 -0
- package/src/server/responses/terminal-guard.ts +251 -0
- package/src/server/responses/upstream-error.ts +53 -0
- package/src/server/responses/ws-upstream.ts +308 -0
- package/src/server/responses-custom-tool-repair.ts +282 -0
- package/src/server/responses-image-gen-repair.ts +132 -0
- package/src/server/responses-item-id-repair.ts +272 -0
- package/src/server/responses-json-events.ts +90 -0
- package/src/server/responses-model-rewrite.ts +29 -0
- package/src/server/responses-reasoning-summary-rewrite.ts +178 -0
- package/src/server/responses-snapshot-repair.ts +621 -0
- package/src/server/responses-terminal-repair.ts +342 -0
- package/src/server/responses-tool-search-repair.ts +267 -0
- package/src/server/responses-undeclared-tool-guard.ts +153 -0
- package/src/server/responses.ts +25 -0
- package/src/server/search.ts +201 -0
- package/src/server/sse-frame-buffer.ts +292 -0
- package/src/server/sse-payload-rewrite.ts +263 -0
- package/src/server/startup-action-control.ts +315 -0
- package/src/server/startup-health-cache.ts +131 -0
- package/src/server/system-env.ts +484 -0
- package/src/server/windows-tcp-drop.ts +184 -0
- package/src/server/windows-tray-control.ts +41 -0
- package/src/server/ws-bridge.ts +472 -0
- package/src/service-manager-probe.ts +892 -0
- package/src/service.ts +3575 -0
- package/src/sidecar/auth.ts +92 -0
- package/src/sidecar/candidates.ts +83 -0
- package/src/stall-timeout.ts +20 -0
- package/src/storage/cleanup-job.ts +57 -0
- package/src/storage/cleanup.ts +3085 -0
- package/src/storage/policy-job.ts +457 -0
- package/src/storage/policy-scheduler.ts +40 -0
- package/src/storage/policy-worker.ts +59 -0
- package/src/storage/policy.ts +527 -0
- package/src/storage/restore-job.ts +299 -0
- package/src/storage/restore-worker.ts +58 -0
- package/src/storage/scanner.ts +238 -0
- package/src/storage/storage-mutation-coordinator.ts +139 -0
- package/src/storage/worker-lifecycle.ts +215 -0
- package/src/tray/assets/opencodex-tray-offline.ico +0 -0
- package/src/tray/assets/opencodex-tray-online.ico +0 -0
- package/src/tray/assets/opencodex-tray-warning.ico +0 -0
- package/src/tray/assets/opencodex-tray.png +0 -0
- package/src/tray/windows-tray.ps1 +364 -0
- package/src/tray/windows.ts +757 -0
- package/src/types/accounts.ts +37 -0
- package/src/types/config.ts +876 -0
- package/src/types/provider.ts +545 -0
- package/src/types/request.ts +384 -0
- package/src/types/tools.ts +131 -0
- package/src/types/wire.ts +80 -0
- package/src/types.ts +106 -0
- package/src/update/badge.ts +72 -0
- package/src/update/index.ts +415 -0
- package/src/update/job.ts +1887 -0
- package/src/update/notify.ts +263 -0
- package/src/update/npm-cache-preflight.d.mts +47 -0
- package/src/update/npm-cache-preflight.mjs +201 -0
- package/src/update/npm-invocation.d.mts +23 -0
- package/src/update/npm-invocation.mjs +94 -0
- package/src/update/transactional-install.d.mts +22 -0
- package/src/update/transactional-install.mjs +259 -0
- package/src/update/tray-update-plan.d.mts +18 -0
- package/src/update/tray-update-plan.mjs +38 -0
- package/src/usage/cost.ts +625 -0
- package/src/usage/debug.ts +97 -0
- package/src/usage/expected-prices.ts +416 -0
- package/src/usage/log.ts +1223 -0
- package/src/usage/summary.ts +753 -0
- package/src/usage/totals.ts +14 -0
- package/src/usage/user-cost-overlay-reconciler.ts +313 -0
- package/src/usage/user-cost-overlays.ts +314 -0
- package/src/vision/anthropic-describe.ts +189 -0
- package/src/vision/backends.ts +97 -0
- package/src/vision/describe.ts +131 -0
- package/src/vision/eligibility.ts +250 -0
- package/src/vision/index.ts +681 -0
- package/src/vision/reasoning.ts +55 -0
- package/src/vision/routed-describe.ts +175 -0
- package/src/vision/timeout-bounds.ts +9 -0
- package/src/web-search/anthropic-executor.ts +195 -0
- package/src/web-search/backends.ts +108 -0
- package/src/web-search/exa-executor.ts +88 -0
- package/src/web-search/executor.ts +113 -0
- package/src/web-search/format-result.ts +89 -0
- package/src/web-search/gemini-executor.ts +141 -0
- package/src/web-search/index.ts +331 -0
- package/src/web-search/loop.ts +896 -0
- package/src/web-search/parse.ts +315 -0
- package/src/web-search/progress-stream.ts +342 -0
- package/src/web-search/sources.ts +60 -0
- package/src/web-search/synthetic-tool.ts +47 -0
- package/src/web-search/xai-executor.ts +219 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,4041 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { chmodSync, constants as fsConstants, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, truncateSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { Database } from "bun:sqlite";
|
|
7
|
+
import * as z from "zod/v4";
|
|
8
|
+
import { isValidProviderName, hasOwnProvider } from "./config/provider-name";
|
|
9
|
+
import {
|
|
10
|
+
bumpConfigGenerationAtPath,
|
|
11
|
+
bumpCurrentConfigGeneration,
|
|
12
|
+
initializeConfigGeneration,
|
|
13
|
+
observeConfigGenerationAtPath,
|
|
14
|
+
readConfigGenerationAtPath,
|
|
15
|
+
readConfigGenerationInTransaction,
|
|
16
|
+
type ConfigGenerationObservation,
|
|
17
|
+
} from "./codex/generation";
|
|
18
|
+
import type {
|
|
19
|
+
BumpConfigGeneration,
|
|
20
|
+
ConfigGeneration,
|
|
21
|
+
ReadConfigGeneration,
|
|
22
|
+
WithExpectedConfigGenerationSync,
|
|
23
|
+
} from "./codex/convergence-types";
|
|
24
|
+
import {
|
|
25
|
+
CODEX_ACCOUNT_NAMESPACE_COMBO_ALIAS_COLLISION_ERROR,
|
|
26
|
+
codexAccountNamespaceForModel,
|
|
27
|
+
codexProviderNamespaceKey,
|
|
28
|
+
isValidCodexAccountNamespaceTarget,
|
|
29
|
+
MAIN_CODEX_ACCOUNT_NAMESPACE_TARGET,
|
|
30
|
+
} from "./codex/account-namespace-match";
|
|
31
|
+
import { isCodexAccountPriorityKey } from "./codex/account-priority";
|
|
32
|
+
import { UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD } from "./codex/upstream-host-health";
|
|
33
|
+
import {
|
|
34
|
+
adoptCustomModelCatalogMigration,
|
|
35
|
+
projectCustomModelCatalogMigration,
|
|
36
|
+
} from "./codex/custom-model-catalog-migration";
|
|
37
|
+
import { parseAccountPriority } from "./codex/pool-rotation";
|
|
38
|
+
import { COMBO_NAMESPACE, comboConfigIssues } from "./combos/types";
|
|
39
|
+
import { routingProfileIssues } from "./routing/profile";
|
|
40
|
+
import { POLICY_NAMESPACE } from "./routing/profile-namespace";
|
|
41
|
+
import {
|
|
42
|
+
forgetEphemeralSecretPath,
|
|
43
|
+
hardenSecretDir,
|
|
44
|
+
hardenSecretPath,
|
|
45
|
+
hardenSecretPathAsync,
|
|
46
|
+
windowsSecretAclApplies,
|
|
47
|
+
} from "./lib/windows-secret-acl";
|
|
48
|
+
import { recordOwnedConfigPath } from "./lib/config-ownership";
|
|
49
|
+
import { assertNotRealHomeUnderTest } from "./lib/test-home-guard";
|
|
50
|
+
import { isLocalAttestationSecret } from "./lib/local-management-attestation";
|
|
51
|
+
import { providerDestinationConfigError } from "./lib/destination-policy";
|
|
52
|
+
import { redactSecretString } from "./lib/redact";
|
|
53
|
+
import {
|
|
54
|
+
resolveTrustedWindowsPowerShellExe,
|
|
55
|
+
resolveTrustedWindowsSystemDirectory,
|
|
56
|
+
} from "./lib/windows-elevation";
|
|
57
|
+
import { openRouterRoutingConfigError } from "./providers/openrouter-routing";
|
|
58
|
+
import {
|
|
59
|
+
isWirePinnedModel,
|
|
60
|
+
MODEL_ADAPTER_OVERRIDE_ALLOWED,
|
|
61
|
+
OPENAI_PROVIDER_TIER_VERSION,
|
|
62
|
+
pinnedWireAdapter,
|
|
63
|
+
REASONING_SUMMARY_DELIVERY_VALUES,
|
|
64
|
+
UPSTREAM_HTTP_VERSION_VALUES,
|
|
65
|
+
type OcxClaudeCodeConfig,
|
|
66
|
+
type OcxConfig,
|
|
67
|
+
type OcxApiKeyEntry,
|
|
68
|
+
type OcxProviderConfig,
|
|
69
|
+
type FastWire,
|
|
70
|
+
type ProviderCostOverlay,
|
|
71
|
+
} from "./types";
|
|
72
|
+
import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "./providers/openai-tiers";
|
|
73
|
+
import { fastWireDeclarationError, hasFastWireCapabilityConflict } from "./providers/fastwire";
|
|
74
|
+
import {
|
|
75
|
+
getProviderRegistryEntry,
|
|
76
|
+
providerMatchesRegistryTransport,
|
|
77
|
+
providerModelWireDefault,
|
|
78
|
+
registryModelServiceTierCapabilityApplies,
|
|
79
|
+
} from "./providers/registry";
|
|
80
|
+
import { resolveOpenAiVirtualModel } from "./providers/openai-virtual-models";
|
|
81
|
+
import { parseDesktopProfile } from "./claude/desktop-profile";
|
|
82
|
+
import { isCodexReasoningEffort, modelRecordValue } from "./reasoning-effort";
|
|
83
|
+
import { parseSubagentRoles, salvageSubagentRoles } from "./codex/agent-roles";
|
|
84
|
+
import {
|
|
85
|
+
COST4_RATE_KEYS,
|
|
86
|
+
isValidCost4Rate,
|
|
87
|
+
refreshPreservedProviderOwner,
|
|
88
|
+
refreshUserCostOverlays,
|
|
89
|
+
withPreservedDiskOnlyProviders,
|
|
90
|
+
} from "./usage/user-cost-overlays";
|
|
91
|
+
import { MAX_COST4_RATE } from "./usage/expected-prices";
|
|
92
|
+
import {
|
|
93
|
+
DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES,
|
|
94
|
+
MAX_APP_OWNED_MEMORY_BUDGET_MB,
|
|
95
|
+
MIN_APP_OWNED_MEMORY_BUDGET_MB,
|
|
96
|
+
} from "./lib/app-owned-memory";
|
|
97
|
+
import { isHostedToolUnsupportedForModel } from "./responses/hosted-tool-policy";
|
|
98
|
+
|
|
99
|
+
let _atomicSeq = 0;
|
|
100
|
+
|
|
101
|
+
// The Windows-tolerant replace lives in lib/windows-atomic-replace: config-ownership
|
|
102
|
+
// is one of its callers and this module already imports config-ownership, so
|
|
103
|
+
// exporting it from here would close an import cycle. Re-exported because these
|
|
104
|
+
// names are part of this module's public surface and its callers.
|
|
105
|
+
export type { AtomicRenameIO } from "./lib/windows-atomic-replace";
|
|
106
|
+
export { renameAtomicFile } from "./lib/windows-atomic-replace";
|
|
107
|
+
import { renameAtomicFile, renameAtomicFileAsync } from "./lib/windows-atomic-replace";
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Write a file atomically (temp + rename) so concurrent writers — e.g. `ocx stop` and the
|
|
111
|
+
* proxy's own shutdown handler both restoring Codex — can never leave a half-written file.
|
|
112
|
+
*/
|
|
113
|
+
export interface AtomicWriteIO {
|
|
114
|
+
write: (path: string, content: string) => void;
|
|
115
|
+
harden: (path: string) => void;
|
|
116
|
+
rename: (source: string, destination: string) => void;
|
|
117
|
+
truncate: (path: string) => void;
|
|
118
|
+
unlink: (path: string) => void;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export class AtomicWriteResidualTempError extends Error {
|
|
122
|
+
constructor(readonly tempPath: string, readonly hardened = true, options?: ErrorOptions) {
|
|
123
|
+
super(`Atomic config write left a ${hardened ? "hardened " : ""}zero-byte temporary file`, options);
|
|
124
|
+
this.name = "AtomicWriteResidualTempError";
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export class AtomicWriteSecretResidualError extends Error {
|
|
129
|
+
constructor(readonly tempPath: string, options?: ErrorOptions) {
|
|
130
|
+
super("Atomic config write could not scrub or remove a secret-bearing temporary file", options);
|
|
131
|
+
this.name = "AtomicWriteSecretResidualError";
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isMissingPathError(error: unknown): boolean {
|
|
136
|
+
return (error as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Resolve a write target through any symlink before the temp+rename dance.
|
|
141
|
+
*
|
|
142
|
+
* rename(2) replaces a directory ENTRY. When the entry is itself a symlink
|
|
143
|
+
* (a dotfiles-managed `~/.codex/config.toml` -> `~/dotfiles/.codex/config.toml`,
|
|
144
|
+
* say), renaming a sibling temp file over it destroys the link and leaves a plain
|
|
145
|
+
* file behind — the repo silently stops receiving writes. Resolving first puts both
|
|
146
|
+
* the temp file and the rename target inside the link's real directory, so the entry
|
|
147
|
+
* being replaced is the real file and the symlink survives.
|
|
148
|
+
*
|
|
149
|
+
* Same-filesystem atomicity is preserved because the temp file stays beside its
|
|
150
|
+
* resolved target. A genuinely absent destination (not yet created) falls back to
|
|
151
|
+
* the literal path, which is the correct target for a first write.
|
|
152
|
+
*
|
|
153
|
+
* An EXISTING symlink that cannot be resolved — dangling because its target volume
|
|
154
|
+
* is unmounted, an ELOOP chain, an EACCES parent — is refused instead. Falling back
|
|
155
|
+
* to the literal path there would let the rename replace the link, recreating the
|
|
156
|
+
* exact dotfiles-divergence failure this helper exists to prevent (audit: wt4 wp2).
|
|
157
|
+
*/
|
|
158
|
+
export function resolveWriteTarget(path: string): string {
|
|
159
|
+
try {
|
|
160
|
+
return realpathSync(path);
|
|
161
|
+
} catch (cause) {
|
|
162
|
+
let entry;
|
|
163
|
+
try {
|
|
164
|
+
entry = lstatSync(path);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (isMissingPathError(error)) return path; // no entry at all — first write
|
|
167
|
+
throw error;
|
|
168
|
+
}
|
|
169
|
+
if (entry.isSymbolicLink()) {
|
|
170
|
+
throw new Error(`refusing to replace unresolvable symlinked write target: ${path}`, { cause });
|
|
171
|
+
}
|
|
172
|
+
return path;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Re-apply the real-home guard to a RESOLVED write target.
|
|
178
|
+
*
|
|
179
|
+
* Callers such as saveConfig check only their logical config dir, which passes when
|
|
180
|
+
* OPENCODEX_HOME points at a temp fixture. Following a symlink out of that fixture
|
|
181
|
+
* would land on the protected home the caller's own check just cleared, so the guard
|
|
182
|
+
* has to run again on wherever the write actually terminates. Inert in production,
|
|
183
|
+
* where the guard is disarmed.
|
|
184
|
+
*/
|
|
185
|
+
function assertResolvedTargetAllowed(path: string, target: string): void {
|
|
186
|
+
// The file itself may resolve literally while its PARENT is a symlink out
|
|
187
|
+
// of the fixture (a first write beneath a symlinked config dir). Guard the
|
|
188
|
+
// directory the write actually lands in either way.
|
|
189
|
+
if (target === path) {
|
|
190
|
+
let realParent: string;
|
|
191
|
+
try {
|
|
192
|
+
realParent = realpathSync(dirname(target));
|
|
193
|
+
} catch {
|
|
194
|
+
return; // unresolvable parent: resolveWriteTarget already owns that refusal
|
|
195
|
+
}
|
|
196
|
+
if (realParent !== dirname(target)) assertNotRealHomeUnderTest(realParent);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
assertNotRealHomeUnderTest(dirname(target));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function atomicWriteFile(path: string, content: string, io: AtomicWriteIO = {
|
|
203
|
+
write: (target, value) => writeFileSync(target, value, { encoding: "utf-8", mode: 0o600 }),
|
|
204
|
+
harden: target => {
|
|
205
|
+
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
206
|
+
// Timeout memo keyed by the stable destination (matches the async writer):
|
|
207
|
+
// a failed temp harden must not mint a new unique-temp key on every write.
|
|
208
|
+
if (process.platform === "win32") hardenSecretPath(target, { required: true, timeoutMemoKey: path });
|
|
209
|
+
},
|
|
210
|
+
rename: renameAtomicFile,
|
|
211
|
+
truncate: target => truncateSync(target, 0),
|
|
212
|
+
unlink: unlinkSync,
|
|
213
|
+
}): void {
|
|
214
|
+
recordOwnedConfigPath(resolveConfigDir(), path);
|
|
215
|
+
const target = resolveWriteTarget(path);
|
|
216
|
+
assertResolvedTargetAllowed(path, target);
|
|
217
|
+
const tmp = `${target}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
218
|
+
let hardened = false;
|
|
219
|
+
try {
|
|
220
|
+
io.write(tmp, content);
|
|
221
|
+
io.harden(tmp);
|
|
222
|
+
hardened = true;
|
|
223
|
+
io.rename(tmp, target);
|
|
224
|
+
forgetEphemeralSecretPath(tmp);
|
|
225
|
+
} catch (cause) {
|
|
226
|
+
let scrubbed = false;
|
|
227
|
+
try {
|
|
228
|
+
io.truncate(tmp);
|
|
229
|
+
scrubbed = true;
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (isMissingPathError(error)) scrubbed = true;
|
|
232
|
+
else {
|
|
233
|
+
try { io.write(tmp, ""); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
let removed = false;
|
|
237
|
+
try {
|
|
238
|
+
io.unlink(tmp);
|
|
239
|
+
removed = true;
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (isMissingPathError(error)) removed = true;
|
|
242
|
+
else {
|
|
243
|
+
try { io.unlink(tmp); removed = true; }
|
|
244
|
+
catch (retryError) { if (isMissingPathError(retryError)) removed = true; }
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (!removed && !scrubbed) throw new AtomicWriteSecretResidualError(tmp, { cause });
|
|
248
|
+
if (!removed && !hardened) {
|
|
249
|
+
try { io.harden(tmp); hardened = true; } catch { /* zero-byte residual is reported honestly */ }
|
|
250
|
+
}
|
|
251
|
+
if (removed) forgetEphemeralSecretPath(tmp);
|
|
252
|
+
if (!removed) throw new AtomicWriteResidualTempError(tmp, hardened, { cause });
|
|
253
|
+
throw cause;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Async atomic-write I/O: harden may await icacls without blocking the event loop (#612). */
|
|
258
|
+
export interface AtomicWriteAsyncIO {
|
|
259
|
+
write: (path: string, content: string) => void | Promise<void>;
|
|
260
|
+
harden: (path: string) => void | Promise<void>;
|
|
261
|
+
rename: (source: string, destination: string) => void | Promise<void>;
|
|
262
|
+
truncate: (path: string) => void | Promise<void>;
|
|
263
|
+
unlink: (path: string) => void | Promise<void>;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Test-only crash seam. Production callers leave this undefined. */
|
|
267
|
+
export interface AtomicWriteAsyncTestSeam {
|
|
268
|
+
afterTempWrite?: (tempPath: string) => void | Promise<void>;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Async atomic write (#612): same temp+harden+rename and residual-temp policy as
|
|
273
|
+
* atomicWriteFile, but Windows ACL harden yields the event loop. Timeout memo is keyed
|
|
274
|
+
* by the final destination path (not the unique temp, not the parent directory).
|
|
275
|
+
*/
|
|
276
|
+
export async function atomicWriteFileAsync(
|
|
277
|
+
path: string,
|
|
278
|
+
content: string,
|
|
279
|
+
io?: AtomicWriteAsyncIO,
|
|
280
|
+
testSeam?: AtomicWriteAsyncTestSeam,
|
|
281
|
+
): Promise<void> {
|
|
282
|
+
const effective: AtomicWriteAsyncIO = io ?? {
|
|
283
|
+
write: (target, value) => writeFileSync(target, value, { encoding: "utf-8", mode: 0o600 }),
|
|
284
|
+
harden: async target => {
|
|
285
|
+
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
286
|
+
if (process.platform === "win32") {
|
|
287
|
+
await hardenSecretPathAsync(target, { required: true, timeoutMemoKey: path });
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
rename: renameAtomicFileAsync,
|
|
291
|
+
truncate: target => truncateSync(target, 0),
|
|
292
|
+
unlink: unlinkSync,
|
|
293
|
+
};
|
|
294
|
+
const target = resolveWriteTarget(path);
|
|
295
|
+
assertResolvedTargetAllowed(path, target);
|
|
296
|
+
const tmp = `${target}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
297
|
+
let hardened = false;
|
|
298
|
+
try {
|
|
299
|
+
await effective.write(tmp, content);
|
|
300
|
+
await testSeam?.afterTempWrite?.(tmp);
|
|
301
|
+
await effective.harden(tmp);
|
|
302
|
+
hardened = true;
|
|
303
|
+
await effective.rename(tmp, target);
|
|
304
|
+
forgetEphemeralSecretPath(tmp);
|
|
305
|
+
} catch (cause) {
|
|
306
|
+
let scrubbed = false;
|
|
307
|
+
try {
|
|
308
|
+
await effective.truncate(tmp);
|
|
309
|
+
scrubbed = true;
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (isMissingPathError(error)) scrubbed = true;
|
|
312
|
+
else {
|
|
313
|
+
try { await effective.write(tmp, ""); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
let removed = false;
|
|
317
|
+
try {
|
|
318
|
+
await effective.unlink(tmp);
|
|
319
|
+
removed = true;
|
|
320
|
+
} catch (error) {
|
|
321
|
+
if (isMissingPathError(error)) removed = true;
|
|
322
|
+
else {
|
|
323
|
+
try { await effective.unlink(tmp); removed = true; }
|
|
324
|
+
catch (retryError) { if (isMissingPathError(retryError)) removed = true; }
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (!removed && !scrubbed) throw new AtomicWriteSecretResidualError(tmp, { cause });
|
|
328
|
+
if (!removed && !hardened) {
|
|
329
|
+
try { await effective.harden(tmp); hardened = true; } catch { /* zero-byte residual is reported honestly */ }
|
|
330
|
+
}
|
|
331
|
+
if (removed) forgetEphemeralSecretPath(tmp);
|
|
332
|
+
if (!removed) throw new AtomicWriteResidualTempError(tmp, hardened, { cause });
|
|
333
|
+
throw cause;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export class OpenAiTierBackupCleanupError extends Error {
|
|
338
|
+
constructor() { super("OpenAI tier backup temporary cleanup failed"); this.name = "OpenAiTierBackupCleanupError"; }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export class OpenAiTierBackupRollbackError extends Error {
|
|
342
|
+
constructor() { super("OpenAI tier backup rollback failed"); this.name = "OpenAiTierBackupRollbackError"; }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export class OpenAiTierBackupCollisionError extends Error {
|
|
346
|
+
readonly configPath?: string;
|
|
347
|
+
constructor(configPath?: string) {
|
|
348
|
+
super("Existing OpenAI tier backup differs from the current config");
|
|
349
|
+
this.name = "OpenAiTierBackupCollisionError";
|
|
350
|
+
this.configPath = configPath;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export class OpenAiTierRollbackPreserveError extends Error {
|
|
355
|
+
readonly code?: "missing" | "not-rollback" | "mismatch" | "exhausted";
|
|
356
|
+
constructor(message: string, options?: ErrorOptions & { code?: OpenAiTierRollbackPreserveError["code"] }) {
|
|
357
|
+
super(message, options);
|
|
358
|
+
this.name = "OpenAiTierRollbackPreserveError";
|
|
359
|
+
this.code = options?.code;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export class OpenAiTierBackupSecretResidualError extends Error {
|
|
364
|
+
constructor(readonly tempPath: string, options?: ErrorOptions) {
|
|
365
|
+
super("OpenAI tier backup could not scrub or remove a secret-bearing temporary file", options);
|
|
366
|
+
this.name = "OpenAiTierBackupSecretResidualError";
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export interface OpenAiTierBackupIO {
|
|
371
|
+
exists(path: string): boolean;
|
|
372
|
+
read(path: string): Uint8Array;
|
|
373
|
+
createExclusive(path: string): void;
|
|
374
|
+
write(path: string, bytes: Uint8Array): void;
|
|
375
|
+
harden(path: string): void;
|
|
376
|
+
publishNoReplace(temp: string, backup: string): void;
|
|
377
|
+
truncate(path: string): void;
|
|
378
|
+
unlink(path: string): void;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function sameBytes(left: Uint8Array, right: Uint8Array): boolean {
|
|
382
|
+
return left.byteLength === right.byteLength && left.every((value, index) => value === right[index]);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function isAlreadyExistsError(error: unknown): boolean {
|
|
386
|
+
return (error as NodeJS.ErrnoException | undefined)?.code === "EEXIST";
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Classify an existing `.pre-openai-tiers-v2.bak` snapshot.
|
|
391
|
+
*
|
|
392
|
+
* - `"stale"`: unparseable JSON (not written by us / truncated) or already a
|
|
393
|
+
* post-migration (tier v2) snapshot — safe to delete or replace.
|
|
394
|
+
* - `"rollback"`: parses as a valid pre-migration (v1) config — a
|
|
395
|
+
* user-intentional rollback point that must never be silently destroyed.
|
|
396
|
+
*
|
|
397
|
+
* Shared by the startup migration backup path and `ocx init` cleanup so both
|
|
398
|
+
* apply the same preservation policy (issue #257 / sol review 260722).
|
|
399
|
+
*/
|
|
400
|
+
export function classifyOpenAiTierBackup(backupBytes: Uint8Array): "stale" | "rollback" {
|
|
401
|
+
try {
|
|
402
|
+
// Use Buffer.from to ensure proper UTF-8 decoding from Uint8Array/Buffer.
|
|
403
|
+
const parsed = JSON.parse(Buffer.from(backupBytes).toString("utf8")) as Record<string, unknown>;
|
|
404
|
+
return parsed.openaiProviderTierVersion === 2 ? "stale" : "rollback";
|
|
405
|
+
} catch {
|
|
406
|
+
// Unparseable: not a config file we created, treat as stale.
|
|
407
|
+
return "stale";
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export function backupConfigBeforeOpenAiTierMigration(
|
|
412
|
+
configPath = getConfigPath(),
|
|
413
|
+
io: OpenAiTierBackupIO = {
|
|
414
|
+
exists: existsSync,
|
|
415
|
+
read: target => readFileSync(target),
|
|
416
|
+
createExclusive: target => { writeFileSync(target, new Uint8Array(), { flag: "wx", mode: 0o600 }); },
|
|
417
|
+
write: (target, bytes) => writeFileSync(target, bytes),
|
|
418
|
+
harden: target => {
|
|
419
|
+
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
420
|
+
// Soft-fail: a wedged/failed icacls on CI temp volumes must not abort
|
|
421
|
+
// startServer mid-suite (timeout + EBUSY cascade on shared TEST_DIR).
|
|
422
|
+
// chmod above still applies; live credential writes keep required:true.
|
|
423
|
+
if (process.platform === "win32") hardenSecretPath(target, { required: false });
|
|
424
|
+
},
|
|
425
|
+
publishNoReplace: (temp, backup) => linkSync(temp, backup),
|
|
426
|
+
truncate: target => truncateSync(target, 0),
|
|
427
|
+
unlink: unlinkSync,
|
|
428
|
+
},
|
|
429
|
+
): "absent" | "created" | "reused" {
|
|
430
|
+
const source = configPath;
|
|
431
|
+
if (!io.exists(source)) return "absent";
|
|
432
|
+
const original = io.read(source);
|
|
433
|
+
// v2 snapshot path. The historical `.pre-openai-tiers-v1.bak` is read only by restore
|
|
434
|
+
// docs/fixtures and is never reused or overwritten as the v2 snapshot.
|
|
435
|
+
const backup = `${source}.pre-openai-tiers-v2.bak`;
|
|
436
|
+
if (io.exists(backup)) {
|
|
437
|
+
if (!sameBytes(original, io.read(backup))) {
|
|
438
|
+
// The backup differs from the current config. Only treat it as stale when it is
|
|
439
|
+
// clearly not a user-intentional rollback point:
|
|
440
|
+
// - unparseable JSON: written by a different tool or truncated
|
|
441
|
+
// - already at tier version 2: the backup is from a post-migration config (e.g.
|
|
442
|
+
// ocx init wrote a fresh v2 config, making the old backup obsolete)
|
|
443
|
+
// A backup that parses as a valid pre-migration (v1) config is kept as-is and
|
|
444
|
+
// we throw a collision error, because silently replacing a user-created rollback
|
|
445
|
+
// point would be surprising and potentially destructive.
|
|
446
|
+
const backupBytes = io.read(backup);
|
|
447
|
+
if (classifyOpenAiTierBackup(backupBytes) === "rollback") {
|
|
448
|
+
throw new OpenAiTierBackupCollisionError(source);
|
|
449
|
+
}
|
|
450
|
+
console.warn("[openai-provider-migration] Replacing stale pre-migration backup (post-migration config was rewritten since last migration).");
|
|
451
|
+
io.unlink(backup);
|
|
452
|
+
} else {
|
|
453
|
+
return "reused";
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
const temp = `${backup}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
457
|
+
let published = false;
|
|
458
|
+
let cleanupAttempted = false;
|
|
459
|
+
|
|
460
|
+
const scrubUnpublishedTemp = (): void => {
|
|
461
|
+
cleanupAttempted = true;
|
|
462
|
+
let scrubbed = false;
|
|
463
|
+
try {
|
|
464
|
+
io.truncate(temp);
|
|
465
|
+
scrubbed = true;
|
|
466
|
+
} catch (error) {
|
|
467
|
+
if (isMissingPathError(error)) scrubbed = true;
|
|
468
|
+
else {
|
|
469
|
+
try { io.write(temp, new Uint8Array()); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
let removed = false;
|
|
473
|
+
try {
|
|
474
|
+
io.unlink(temp);
|
|
475
|
+
removed = true;
|
|
476
|
+
} catch (error) {
|
|
477
|
+
if (isMissingPathError(error)) {
|
|
478
|
+
removed = true;
|
|
479
|
+
}
|
|
480
|
+
else {
|
|
481
|
+
try { io.unlink(temp); removed = true; }
|
|
482
|
+
catch (retryError) {
|
|
483
|
+
if (isMissingPathError(retryError)) {
|
|
484
|
+
removed = true;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (removed) forgetEphemeralSecretPath(temp);
|
|
490
|
+
if (!removed && !scrubbed) throw new OpenAiTierBackupSecretResidualError(temp);
|
|
491
|
+
if (!removed) throw new OpenAiTierBackupCleanupError();
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
try {
|
|
495
|
+
io.createExclusive(temp);
|
|
496
|
+
io.write(temp, original);
|
|
497
|
+
io.harden(temp);
|
|
498
|
+
try {
|
|
499
|
+
io.publishNoReplace(temp, backup);
|
|
500
|
+
} catch (cause) {
|
|
501
|
+
if (!isAlreadyExistsError(cause)) throw cause;
|
|
502
|
+
const winner = io.read(backup);
|
|
503
|
+
if (!sameBytes(original, winner)) throw new OpenAiTierBackupCollisionError(source);
|
|
504
|
+
scrubUnpublishedTemp();
|
|
505
|
+
return "reused";
|
|
506
|
+
}
|
|
507
|
+
published = true;
|
|
508
|
+
try {
|
|
509
|
+
io.unlink(temp);
|
|
510
|
+
forgetEphemeralSecretPath(temp);
|
|
511
|
+
} catch (firstError) {
|
|
512
|
+
if (isMissingPathError(firstError)) {
|
|
513
|
+
forgetEphemeralSecretPath(temp);
|
|
514
|
+
} else try {
|
|
515
|
+
io.unlink(temp);
|
|
516
|
+
forgetEphemeralSecretPath(temp);
|
|
517
|
+
} catch (secondError) {
|
|
518
|
+
if (isMissingPathError(secondError)) {
|
|
519
|
+
forgetEphemeralSecretPath(temp);
|
|
520
|
+
return "created";
|
|
521
|
+
}
|
|
522
|
+
// temp and backup are hard links to the same inode. Roll back the backup
|
|
523
|
+
// link before any truncation so the downgrade snapshot is never zeroed.
|
|
524
|
+
try { io.unlink(backup); } catch { throw new OpenAiTierBackupRollbackError(); }
|
|
525
|
+
published = false;
|
|
526
|
+
scrubUnpublishedTemp();
|
|
527
|
+
throw new OpenAiTierBackupCleanupError();
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return "created";
|
|
531
|
+
} catch (cause) {
|
|
532
|
+
if (!published && !cleanupAttempted) {
|
|
533
|
+
scrubUnpublishedTemp();
|
|
534
|
+
}
|
|
535
|
+
throw cause;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
export interface OpenAiTierRollbackPreserveIO {
|
|
540
|
+
exists(path: string): boolean;
|
|
541
|
+
read(path: string): Uint8Array;
|
|
542
|
+
copyExclusive(source: string, destination: string): void;
|
|
543
|
+
unlink(path: string): void;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const DEFAULT_ROLLBACK_PRESERVE_IO: OpenAiTierRollbackPreserveIO = {
|
|
547
|
+
exists: existsSync,
|
|
548
|
+
read: target => readFileSync(target),
|
|
549
|
+
copyExclusive: (source, destination) => {
|
|
550
|
+
copyFileSync(source, destination, fsConstants.COPYFILE_EXCL);
|
|
551
|
+
},
|
|
552
|
+
unlink: unlinkSync,
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
const OPENAI_TIER_ROLLBACK_PRESERVE_ATTEMPTS = 16;
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Copy a rollback-classified `.pre-openai-tiers-v2.bak` to a unique
|
|
559
|
+
* `.pre-openai-tiers-v1-rollback.<timestamp>[suffix].bak` path, then unlink the
|
|
560
|
+
* blocking v2 name. The original bytes are copied with no-replace publication;
|
|
561
|
+
* the v2 path is removed only after the copy is verified. Shared by startup
|
|
562
|
+
* migration recovery and `ocx init` cleanup so the two paths cannot drift.
|
|
563
|
+
*/
|
|
564
|
+
export function preserveOpenAiTierRollbackSnapshot(
|
|
565
|
+
configPath = getConfigPath(),
|
|
566
|
+
io: OpenAiTierRollbackPreserveIO = DEFAULT_ROLLBACK_PRESERVE_IO,
|
|
567
|
+
): string {
|
|
568
|
+
const backup = `${configPath}.pre-openai-tiers-v2.bak`;
|
|
569
|
+
if (!io.exists(backup)) {
|
|
570
|
+
throw new OpenAiTierRollbackPreserveError("OpenAI tier rollback backup is missing", { code: "missing" });
|
|
571
|
+
}
|
|
572
|
+
const original = io.read(backup);
|
|
573
|
+
if (classifyOpenAiTierBackup(original) !== "rollback") {
|
|
574
|
+
throw new OpenAiTierRollbackPreserveError("OpenAI tier backup is not a rollback snapshot", { code: "not-rollback" });
|
|
575
|
+
}
|
|
576
|
+
for (let attempt = 0; attempt < OPENAI_TIER_ROLLBACK_PRESERVE_ATTEMPTS; attempt++) {
|
|
577
|
+
const preserved = `${configPath}.pre-openai-tiers-v1-rollback.${Date.now()}${attempt ? `-${attempt}` : ""}.bak`;
|
|
578
|
+
try {
|
|
579
|
+
io.copyExclusive(backup, preserved);
|
|
580
|
+
} catch (error) {
|
|
581
|
+
if (isAlreadyExistsError(error)) continue;
|
|
582
|
+
throw error;
|
|
583
|
+
}
|
|
584
|
+
let copied: Uint8Array;
|
|
585
|
+
try {
|
|
586
|
+
copied = io.read(preserved);
|
|
587
|
+
} catch (error) {
|
|
588
|
+
throw new OpenAiTierRollbackPreserveError("Failed to read preserved rollback snapshot", { cause: error, code: "mismatch" });
|
|
589
|
+
}
|
|
590
|
+
if (!sameBytes(original, copied)) {
|
|
591
|
+
try { io.unlink(preserved); } catch { /* keep the original backup; incomplete copy is best-effort */ }
|
|
592
|
+
throw new OpenAiTierRollbackPreserveError("Preserved rollback snapshot does not match source bytes", { code: "mismatch" });
|
|
593
|
+
}
|
|
594
|
+
io.unlink(backup);
|
|
595
|
+
return preserved;
|
|
596
|
+
}
|
|
597
|
+
throw new OpenAiTierRollbackPreserveError("Unable to find a unique rollback snapshot path", { code: "exhausted" });
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* Expand a leading `~` to the home directory in user-supplied paths
|
|
602
|
+
* (OPENCODEX_HOME/CODEX_HOME set from GUIs/service files where no shell expanded it).
|
|
603
|
+
* `~user` and `%VAR%`/`$VAR` forms pass through untouched — those belong to the shell.
|
|
604
|
+
*/
|
|
605
|
+
export function expandUserPath(raw: string): string {
|
|
606
|
+
if (raw === "~") return homedir();
|
|
607
|
+
if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(homedir(), raw.slice(2));
|
|
608
|
+
return raw;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
let resolvedConfigDirCache: { raw: string | undefined; path: string } | null = null;
|
|
612
|
+
|
|
613
|
+
function resolveConfigDir(): string {
|
|
614
|
+
const raw = process.env["OPENCODEX_HOME"]?.trim() || undefined;
|
|
615
|
+
if (resolvedConfigDirCache && resolvedConfigDirCache.raw === raw) return resolvedConfigDirCache.path;
|
|
616
|
+
const path = raw ? resolve(expandUserPath(raw)) : join(homedir(), ".opencodex");
|
|
617
|
+
resolvedConfigDirCache = { raw, path };
|
|
618
|
+
return path;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function resolveConfigPath(): string {
|
|
622
|
+
return join(resolveConfigDir(), "config.json");
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function resolvePidPath(): string {
|
|
626
|
+
return join(resolveConfigDir(), "ocx.pid");
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
function resolveRuntimePortPath(): string {
|
|
630
|
+
return join(resolveConfigDir(), "runtime-port.json");
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const warnedConfigFallbacks = new Set<string>();
|
|
634
|
+
const warnedInheritedFastWireConflicts = new Set<string>();
|
|
635
|
+
let lastWarningReconciledGeneration = 0;
|
|
636
|
+
|
|
637
|
+
export function reconcileConfigWarningMemos(generation: number): number {
|
|
638
|
+
if (generation <= lastWarningReconciledGeneration) return 0;
|
|
639
|
+
const removed = warnedConfigFallbacks.size + warnedInheritedFastWireConflicts.size;
|
|
640
|
+
warnedConfigFallbacks.clear();
|
|
641
|
+
warnedInheritedFastWireConflicts.clear();
|
|
642
|
+
lastWarningReconciledGeneration = generation;
|
|
643
|
+
return removed;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Bounds for the opt-in same-target 429 wait-and-retry policy. Single source of truth
|
|
648
|
+
* shared by the config schema, the load-time sanitizer, and the management write
|
|
649
|
+
* boundary. Strict, so an unknown key is rejected at every validation boundary instead
|
|
650
|
+
* of being silently ignored (the load-time sanitizer still degrades unknown keys with a
|
|
651
|
+
* warning before schema validation, so hand-edited configs keep loading).
|
|
652
|
+
*/
|
|
653
|
+
const retryOn429PolicySchema = z.object({
|
|
654
|
+
enabled: z.boolean().optional(),
|
|
655
|
+
attempts: z.number().int().min(1).max(20).optional(),
|
|
656
|
+
intervalMs: z.number().int().min(100).max(600_000).optional(),
|
|
657
|
+
// The effective cap for a single wait is MAX_COOLDOWN_MS (10 min) in key-failover.ts;
|
|
658
|
+
// larger configured values would be dead config.
|
|
659
|
+
maxIntervalMs: z.number().int().min(100).max(600_000).optional(),
|
|
660
|
+
respectRetryAfter: z.boolean().optional(),
|
|
661
|
+
}).strict();
|
|
662
|
+
|
|
663
|
+
const requestPacingRuleSchema = z.object({
|
|
664
|
+
// Keep the RPM-derived timer within the same one-hour bound as minIntervalMs.
|
|
665
|
+
requestsPerMinute: z.number().min(1 / 60).max(60_000).optional(),
|
|
666
|
+
minIntervalMs: z.number().int().min(1).max(3_600_000).optional(),
|
|
667
|
+
}).strict().refine(value => value.requestsPerMinute !== undefined || value.minIntervalMs !== undefined, {
|
|
668
|
+
message: "request pacing rules need requestsPerMinute or minIntervalMs",
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
const requestPacingSchema = z.object({
|
|
672
|
+
enabled: z.boolean(),
|
|
673
|
+
requestsPerMinute: z.number().min(1 / 60).max(60_000).optional(),
|
|
674
|
+
minIntervalMs: z.number().int().min(1).max(3_600_000).optional(),
|
|
675
|
+
models: z.record(z.string().trim().min(1), requestPacingRuleSchema).optional(),
|
|
676
|
+
}).strict().refine(value => value.enabled === false
|
|
677
|
+
|| value.requestsPerMinute !== undefined
|
|
678
|
+
|| value.minIntervalMs !== undefined
|
|
679
|
+
|| (value.models !== undefined && Object.keys(value.models).length > 0), {
|
|
680
|
+
message: "enabled request pacing needs a provider rule or model override",
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
export function requestPacingConfigError(value: unknown): string | null {
|
|
684
|
+
if (value === undefined) return null;
|
|
685
|
+
const parsed = requestPacingSchema.safeParse(value);
|
|
686
|
+
if (parsed.success) return null;
|
|
687
|
+
return "requestPacing must contain enabled and a valid requestsPerMinute/minIntervalMs provider rule or model overrides";
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
const fastWireSchema = z.object({
|
|
691
|
+
kind: z.string(),
|
|
692
|
+
canonicalToWire: z.record(z.string().trim(), z.string().trim()),
|
|
693
|
+
foreignCallerTiers: z.string(),
|
|
694
|
+
betas: z.array(z.string().trim()).optional(),
|
|
695
|
+
}).strict().superRefine((fastWire, ctx) => {
|
|
696
|
+
const error = fastWireDeclarationError({ fastWire });
|
|
697
|
+
if (error) ctx.addIssue({ code: "custom", message: error });
|
|
698
|
+
}).transform(fastWire => fastWire as FastWire);
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Zod schema for one provider entry: known fields are validated strictly while unknown
|
|
702
|
+
* fields pass through (preserved for runtime extensions).
|
|
703
|
+
*/
|
|
704
|
+
const providerConfigSchema = z.object({
|
|
705
|
+
adapter: z.string().min(1),
|
|
706
|
+
baseUrl: z.string().min(1),
|
|
707
|
+
requestPacing: requestPacingSchema.optional().catch(undefined),
|
|
708
|
+
mcpMaxTools: z.number().int().positive().optional(),
|
|
709
|
+
mcpMaxSchemaBytes: z.number().int().positive().optional(),
|
|
710
|
+
mcpMaxResultBytes: z.number().int().positive().optional(),
|
|
711
|
+
apiKeyTransport: z.enum(["x-api-key", "bearer"]).optional(),
|
|
712
|
+
responsesPath: z.string().min(1).optional(),
|
|
713
|
+
statelessResponses: z.boolean().optional(),
|
|
714
|
+
requiresAdjacentResponsesToolResults: z.boolean().optional(),
|
|
715
|
+
fastWire: fastWireSchema.nullable().optional(),
|
|
716
|
+
supportsServiceTier: z.boolean().optional(),
|
|
717
|
+
modelSupportsServiceTier: z.record(z.string().min(1), z.boolean()).optional(),
|
|
718
|
+
preserveResponsesReasoningContent: z.boolean().optional(),
|
|
719
|
+
decodesNativeCompactionBlobs: z.boolean().optional(),
|
|
720
|
+
allowPrivateNetwork: z.boolean().optional(),
|
|
721
|
+
// The management API accepts `null` as "clear this", so a config written before the POST
|
|
722
|
+
// canonicalization below can hold one on disk. Rejecting it here would send the operator
|
|
723
|
+
// through invalid-config recovery for a value the API told them was fine.
|
|
724
|
+
upstreamHttpVersion: z.enum(UPSTREAM_HTTP_VERSION_VALUES)
|
|
725
|
+
.nullish()
|
|
726
|
+
.transform(value => value ?? undefined),
|
|
727
|
+
directGeminiWireRenames: z.boolean().optional(),
|
|
728
|
+
noStructuredOutputModels: z.array(z.string().min(1))
|
|
729
|
+
.transform(normalizeNonBlankStringArray)
|
|
730
|
+
.optional(),
|
|
731
|
+
retryOn429: retryOn429PolicySchema.optional(),
|
|
732
|
+
codexAccountMode: z.enum(["pool", "direct"]).optional(),
|
|
733
|
+
// Validated rather than passed through: this schema ends in `.passthrough()`, so an
|
|
734
|
+
// undeclared key survives verbatim. A misspelled `codexToolMode` therefore used to be
|
|
735
|
+
// accepted, persisted, and then silently resolved to the `code_mode_only` default — the
|
|
736
|
+
// operator asked for shell mode, got code mode, and was told nothing (#2106).
|
|
737
|
+
codexToolMode: z.enum(["code_mode_only", "shell"]).optional(),
|
|
738
|
+
responsesItemIdRepair: z.object({
|
|
739
|
+
message: z.array(z.string().min(1)).optional(),
|
|
740
|
+
reasoning: z.array(z.string().min(1)).optional(),
|
|
741
|
+
repairMissingTerminalIds: z.boolean().optional(),
|
|
742
|
+
repairInvalidIds: z.boolean().optional(),
|
|
743
|
+
}).strict().optional(),
|
|
744
|
+
responsesSnapshotRepair: z.boolean().optional(),
|
|
745
|
+
}).passthrough();
|
|
746
|
+
|
|
747
|
+
const HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
748
|
+
const SENSITIVE_PROVIDER_HEADERS = new Set([
|
|
749
|
+
"authorization",
|
|
750
|
+
"cookie",
|
|
751
|
+
"set-cookie",
|
|
752
|
+
"proxy-authorization",
|
|
753
|
+
"x-api-key",
|
|
754
|
+
"x-goog-api-key",
|
|
755
|
+
"x-amz-security-token",
|
|
756
|
+
]);
|
|
757
|
+
|
|
758
|
+
export { isValidProviderName, hasOwnProvider } from "./config/provider-name";
|
|
759
|
+
|
|
760
|
+
export function providerBaseUrlConfigError(baseUrl: string): string | null {
|
|
761
|
+
try {
|
|
762
|
+
const parsed = new URL(baseUrl.trim());
|
|
763
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "baseUrl must be an http(s) URL";
|
|
764
|
+
if (parsed.username || parsed.password) return "baseUrl must not include embedded credentials";
|
|
765
|
+
if (parsed.search || parsed.hash) return "baseUrl must not include query strings or fragments";
|
|
766
|
+
} catch {
|
|
767
|
+
return "baseUrl must be a valid URL";
|
|
768
|
+
}
|
|
769
|
+
return null;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function providerResponsesPathConfigError(responsesPath: string | undefined): string | null {
|
|
773
|
+
if (responsesPath === undefined) return null;
|
|
774
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(responsesPath) || responsesPath.includes("://")) {
|
|
775
|
+
return "responsesPath must be a relative path without a URL scheme";
|
|
776
|
+
}
|
|
777
|
+
if (!responsesPath.startsWith("/")) return "responsesPath must start with /";
|
|
778
|
+
if (responsesPath.includes("?") || responsesPath.includes("#")) {
|
|
779
|
+
return "responsesPath must not include query strings or fragments";
|
|
780
|
+
}
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
export function providerHeadersConfigError(headers: unknown): string | null {
|
|
785
|
+
if (headers === undefined) return null;
|
|
786
|
+
if (!headers || typeof headers !== "object" || Array.isArray(headers)) return "headers must be an object";
|
|
787
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
788
|
+
const normalized = name.trim().toLowerCase();
|
|
789
|
+
if (!normalized || !HEADER_NAME_PATTERN.test(name)) return "headers must use valid HTTP header names";
|
|
790
|
+
if (SENSITIVE_PROVIDER_HEADERS.has(normalized)) return `headers must not include sensitive header "${name}"; use apiKey/authMode instead`;
|
|
791
|
+
if (typeof value !== "string") return `header "${name}" value must be a string`;
|
|
792
|
+
if (/[\r\n]/.test(value)) return `header "${name}" value must not include line breaks`;
|
|
793
|
+
}
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Validate `providers.<name>.modelCosts`: a plain object keyed by exact model
|
|
799
|
+
* id, each value a 4-tuple of non-negative finite USD-per-1M-token rates.
|
|
800
|
+
* Returns null when valid/absent, else a human-readable error.
|
|
801
|
+
*/
|
|
802
|
+
export function providerModelCostsConfigError(value: unknown, field = "modelCosts"): string | null {
|
|
803
|
+
if (value === undefined) return null;
|
|
804
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
805
|
+
return `${field} must be a plain object keyed by model id`;
|
|
806
|
+
}
|
|
807
|
+
for (const [modelId, entry] of Object.entries(value)) {
|
|
808
|
+
if (!modelId.trim()) return `${field} keys must be nonblank model ids`;
|
|
809
|
+
// Redact secret-shaped model ids and JSON-escape control characters so a
|
|
810
|
+
// malformed write cannot echo a pasted key/secret back through the
|
|
811
|
+
// management API response.
|
|
812
|
+
const safeModelId = JSON.stringify(redactSecretString(modelId));
|
|
813
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
814
|
+
return `${field}.${safeModelId} must be an object with input, output, cacheRead, and cacheWrite (USD per 1M tokens)`;
|
|
815
|
+
}
|
|
816
|
+
const rates = entry as Record<string, unknown>;
|
|
817
|
+
for (const key of COST4_RATE_KEYS) {
|
|
818
|
+
const rate = rates[key];
|
|
819
|
+
if (!isValidCost4Rate(rate)) {
|
|
820
|
+
return `${field}.${safeModelId}.${key} must be a non-negative finite number at most ${MAX_COST4_RATE} (USD per 1M tokens)`;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
// Reject unknown fields: a misplaced apiKey/apiKeyPool under a cost row
|
|
824
|
+
// would otherwise be persisted and echoed verbatim by display paths that
|
|
825
|
+
// mask only top-level provider secrets.
|
|
826
|
+
const extraKeys = Object.keys(rates)
|
|
827
|
+
.filter((key) => !(COST4_RATE_KEYS as readonly string[]).includes(key));
|
|
828
|
+
if (extraKeys.length > 0) {
|
|
829
|
+
return `${field}.${safeModelId} has unexpected fields ${JSON.stringify(extraKeys.map(redactSecretString).join(", "))} — only input, output, cacheRead, and cacheWrite are allowed (USD per 1M tokens)`;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
return null;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* Serialize `providers.<name>.modelCosts` for display: copy ONLY the four
|
|
837
|
+
* numeric rate fields per model and DROP secret-shaped model ids, so a pasted
|
|
838
|
+
* API key in a key position cannot be echoed back by CLI/DTO display paths.
|
|
839
|
+
* The result uses a null prototype so "__proto__" remains an own row.
|
|
840
|
+
*/
|
|
841
|
+
export function sanitizeModelCostsForDisplay(costs: unknown): Record<string, ProviderCostOverlay> | undefined {
|
|
842
|
+
if (!costs || typeof costs !== "object" || Array.isArray(costs)) return undefined;
|
|
843
|
+
const out = Object.create(null) as Record<string, ProviderCostOverlay>;
|
|
844
|
+
for (const [modelId, entry] of Object.entries(costs)) {
|
|
845
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
846
|
+
const rates = entry as Record<string, unknown>;
|
|
847
|
+
const input = rates.input;
|
|
848
|
+
const output = rates.output;
|
|
849
|
+
const cacheRead = rates.cacheRead;
|
|
850
|
+
const cacheWrite = rates.cacheWrite;
|
|
851
|
+
if (
|
|
852
|
+
isValidCost4Rate(input)
|
|
853
|
+
&& isValidCost4Rate(output)
|
|
854
|
+
&& isValidCost4Rate(cacheRead)
|
|
855
|
+
&& isValidCost4Rate(cacheWrite)
|
|
856
|
+
) {
|
|
857
|
+
// Secret-shaped ids are DROPPED rather than mapped to "[REDACTED]" so
|
|
858
|
+
// distinct rows cannot collapse into one placeholder key.
|
|
859
|
+
if (redactSecretString(modelId) !== modelId) continue;
|
|
860
|
+
out[modelId] = { input, output, cacheRead, cacheWrite };
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/** Keep the configured API-key header style scoped to Anthropic-compatible key auth. */
|
|
867
|
+
export function apiKeyTransportConfigError(
|
|
868
|
+
provider: Pick<OcxProviderConfig, "adapter" | "authMode" | "apiKeyTransport">,
|
|
869
|
+
): string | null {
|
|
870
|
+
if (provider.apiKeyTransport === undefined) return null;
|
|
871
|
+
if (provider.apiKeyTransport !== "x-api-key" && provider.apiKeyTransport !== "bearer") {
|
|
872
|
+
return 'apiKeyTransport must be "x-api-key" or "bearer"';
|
|
873
|
+
}
|
|
874
|
+
if (provider.adapter !== "anthropic") {
|
|
875
|
+
return "apiKeyTransport is supported only by the anthropic adapter";
|
|
876
|
+
}
|
|
877
|
+
if (provider.authMode === "oauth" || provider.authMode === "forward" || provider.authMode === "local") {
|
|
878
|
+
return "apiKeyTransport requires Anthropic API-key authentication";
|
|
879
|
+
}
|
|
880
|
+
return null;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* Shared runtime boundary for the per-provider upstream HTTP-version pin (#1668). Used by
|
|
885
|
+
* the management write path (providerManagementConfigError / PATCH) so it can never disagree
|
|
886
|
+
* with the strict zod load schema: a value that survives POST/PATCH is always loadable, and
|
|
887
|
+
* a value the loader rejects is rejected at write time too.
|
|
888
|
+
*/
|
|
889
|
+
export function upstreamHttpVersionConfigError(value: unknown): string | null {
|
|
890
|
+
if (value === undefined || value === null) return null;
|
|
891
|
+
if (typeof value !== "string" || !(UPSTREAM_HTTP_VERSION_VALUES as readonly string[]).includes(value)) {
|
|
892
|
+
return 'upstreamHttpVersion must be one of "auto", "http1.1", "h1", "http2", "h2", or null to clear';
|
|
893
|
+
}
|
|
894
|
+
return null;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
export function positiveIntegerRecordConfigError(value: unknown, field: string): string | null {
|
|
898
|
+
if (value === undefined) return null;
|
|
899
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
900
|
+
const prototype = Object.getPrototypeOf(value);
|
|
901
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
902
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
903
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
904
|
+
if (typeof entry !== "number" || !Number.isFinite(entry) || !Number.isInteger(entry) || entry <= 0) {
|
|
905
|
+
return `${field}.${key} must be a positive finite integer`;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
return null;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
export function positiveIntegerConfigError(value: unknown, field: string): string | null {
|
|
912
|
+
if (value === undefined) return null;
|
|
913
|
+
if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
|
|
914
|
+
return `${field} must be a positive finite integer`;
|
|
915
|
+
}
|
|
916
|
+
return null;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
export function nonBlankStringArrayConfigError(value: unknown, field: string): string | null {
|
|
920
|
+
if (value === undefined) return null;
|
|
921
|
+
if (!Array.isArray(value)) return `${field} must be an array`;
|
|
922
|
+
for (const [index, entry] of value.entries()) {
|
|
923
|
+
if (typeof entry !== "string" || !entry.trim()) {
|
|
924
|
+
return `${field}.${index} must be a nonblank model id`;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
return null;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* Keep hand-edited config and management writes on one canonical model-id list.
|
|
932
|
+
* Validation happens separately so an all-whitespace value is rejected rather than
|
|
933
|
+
* normalized into a model id that can never match at runtime.
|
|
934
|
+
*/
|
|
935
|
+
export function normalizeNonBlankStringArray(value: readonly string[]): string[] {
|
|
936
|
+
return [...new Set(value.map(entry => entry.trim()))];
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
export function booleanRecordConfigError(value: unknown, field: string): string | null {
|
|
940
|
+
if (value === undefined) return null;
|
|
941
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
942
|
+
const prototype = Object.getPrototypeOf(value);
|
|
943
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
944
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
945
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
946
|
+
if (typeof entry !== "boolean") return `${field}.${key} must be a boolean`;
|
|
947
|
+
}
|
|
948
|
+
return null;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
const REASONING_SUMMARY_DELIVERY_SET = new Set<string>(REASONING_SUMMARY_DELIVERY_VALUES);
|
|
952
|
+
|
|
953
|
+
export function reasoningSummaryDeliveryRecordConfigError(
|
|
954
|
+
value: unknown,
|
|
955
|
+
supportsReasoningSummaries: unknown,
|
|
956
|
+
field = "modelReasoningSummaryDelivery",
|
|
957
|
+
): string | null {
|
|
958
|
+
if (value === undefined) return null;
|
|
959
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
960
|
+
const prototype = Object.getPrototypeOf(value);
|
|
961
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
962
|
+
|
|
963
|
+
const supports = booleanRecordConfigError(supportsReasoningSummaries, "modelSupportsReasoningSummaries") === null
|
|
964
|
+
&& supportsReasoningSummaries && typeof supportsReasoningSummaries === "object"
|
|
965
|
+
? supportsReasoningSummaries as Record<string, boolean>
|
|
966
|
+
: undefined;
|
|
967
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
968
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
969
|
+
if (typeof entry !== "string" || !REASONING_SUMMARY_DELIVERY_SET.has(entry)) {
|
|
970
|
+
return `${field}.${key} must be one of: ${REASONING_SUMMARY_DELIVERY_VALUES.join(", ")}`;
|
|
971
|
+
}
|
|
972
|
+
if (modelRecordValue(supports, key) === false) {
|
|
973
|
+
return `${field}.${key} conflicts with modelSupportsReasoningSummaries=false`;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return null;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
const SUPPORTED_PREFERRED_HOSTED_TOOLS = new Set(["image_generation"]);
|
|
980
|
+
|
|
981
|
+
export function modelPreferHostedToolsConfigError(
|
|
982
|
+
value: unknown,
|
|
983
|
+
field: string,
|
|
984
|
+
providerName: string,
|
|
985
|
+
provider: { adapter?: unknown; authMode?: unknown; modelAdapters?: unknown; baseUrl?: unknown },
|
|
986
|
+
): string | null {
|
|
987
|
+
if (value === undefined) return null;
|
|
988
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
989
|
+
const prototype = Object.getPrototypeOf(value);
|
|
990
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
991
|
+
const entries = Object.entries(value);
|
|
992
|
+
const registry = getProviderRegistryEntry(providerName);
|
|
993
|
+
// Effective transport: a `preserveCustomDestination` registry row reused under a
|
|
994
|
+
// different endpoint keeps its own adapter AND its own auth at runtime, because
|
|
995
|
+
// `routedProviderConfig()` honors `providerMatchesRegistryTransport()`. Both the
|
|
996
|
+
// wire check below and the forward-auth check here have to start from the same
|
|
997
|
+
// decision, or validation accepts a preference the adapter never applies —
|
|
998
|
+
// `preferConfiguredHostedTools()` runs only on the non-forward branch.
|
|
999
|
+
const registryTransportMatches = typeof provider.baseUrl === "string"
|
|
1000
|
+
&& providerMatchesRegistryTransport(providerName, {
|
|
1001
|
+
baseUrl: provider.baseUrl,
|
|
1002
|
+
adapter: provider.adapter as OcxProviderConfig["adapter"],
|
|
1003
|
+
...(typeof provider.authMode === "string" ? { authMode: provider.authMode as OcxProviderConfig["authMode"] } : {}),
|
|
1004
|
+
});
|
|
1005
|
+
const effectiveForwardAuth = registryTransportMatches
|
|
1006
|
+
? registry?.authKind === "forward"
|
|
1007
|
+
: provider.authMode === "forward";
|
|
1008
|
+
if (entries.length > 0 && effectiveForwardAuth) {
|
|
1009
|
+
return `${field} is not supported on forward-auth Responses providers`;
|
|
1010
|
+
}
|
|
1011
|
+
const requestedWireFor = (modelId: string): unknown => provider.modelAdapters
|
|
1012
|
+
&& typeof provider.modelAdapters === "object"
|
|
1013
|
+
&& !Array.isArray(provider.modelAdapters)
|
|
1014
|
+
? (provider.modelAdapters as Record<string, unknown>)[modelId]
|
|
1015
|
+
: undefined;
|
|
1016
|
+
const resolveEffectiveWire = (modelId: string, currentWire: unknown): unknown => {
|
|
1017
|
+
const pinned = pinnedWireAdapter(providerName, modelId);
|
|
1018
|
+
if (pinned) return pinned;
|
|
1019
|
+
const requestedWire = requestedWireFor(modelId);
|
|
1020
|
+
if (typeof requestedWire === "string" && MODEL_ADAPTER_OVERRIDE_ALLOWED.has(requestedWire)) {
|
|
1021
|
+
return requestedWire;
|
|
1022
|
+
}
|
|
1023
|
+
// No explicit override: fall back to the registry's per-model wire default before
|
|
1024
|
+
// the provider-wide adapter, because that is the order `resolveModelAdapter()`
|
|
1025
|
+
// uses at request time (src/server/adapter-resolve.ts:38-48). Skipping it rejected
|
|
1026
|
+
// preferences the runtime would have honored — DeepSeek routes `deepseek-v4-flash`
|
|
1027
|
+
// over native Responses for a Responses inbound while the provider-wide wire stays
|
|
1028
|
+
// openai-chat. Hosted-tool preferences only apply to Responses traffic, so the
|
|
1029
|
+
// inbound to ask about is "responses".
|
|
1030
|
+
const registryDefault = typeof currentWire === "string" && typeof provider.baseUrl === "string"
|
|
1031
|
+
? providerModelWireDefault(
|
|
1032
|
+
providerName,
|
|
1033
|
+
{
|
|
1034
|
+
baseUrl: provider.baseUrl,
|
|
1035
|
+
adapter: currentWire,
|
|
1036
|
+
...(typeof provider.authMode === "string" ? { authMode: provider.authMode as OcxProviderConfig["authMode"] } : {}),
|
|
1037
|
+
},
|
|
1038
|
+
modelId,
|
|
1039
|
+
MODEL_ADAPTER_OVERRIDE_ALLOWED,
|
|
1040
|
+
"responses",
|
|
1041
|
+
)
|
|
1042
|
+
: undefined;
|
|
1043
|
+
return registryDefault ?? currentWire;
|
|
1044
|
+
};
|
|
1045
|
+
for (const [key, entry] of entries) {
|
|
1046
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
1047
|
+
if (!Array.isArray(entry)) return `${field}.${key} must be an array`;
|
|
1048
|
+
if (entry.length === 0) return `${field}.${key} must include image_generation`;
|
|
1049
|
+
for (const tool of entry) {
|
|
1050
|
+
if (typeof tool !== "string" || !SUPPORTED_PREFERRED_HOSTED_TOOLS.has(tool)) {
|
|
1051
|
+
return `${field}.${key} supports only image_generation`;
|
|
1052
|
+
}
|
|
1053
|
+
if (isHostedToolUnsupportedForModel(key, tool)) {
|
|
1054
|
+
return `${field}.${key} cannot prefer ${tool}: the model does not support it`;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
// Same `registryTransportMatches` decision the forward-auth check above uses:
|
|
1058
|
+
// start from the registry adapter only when this config still points at the
|
|
1059
|
+
// registry's documented transport.
|
|
1060
|
+
const baseWire = registryTransportMatches ? registry?.adapter ?? provider.adapter : provider.adapter;
|
|
1061
|
+
let effectiveWire = resolveEffectiveWire(key, baseWire);
|
|
1062
|
+
const virtualWireModel = resolveOpenAiVirtualModel(providerName, key)?.wireModelId;
|
|
1063
|
+
if (virtualWireModel && virtualWireModel !== key) {
|
|
1064
|
+
effectiveWire = resolveEffectiveWire(virtualWireModel, effectiveWire);
|
|
1065
|
+
}
|
|
1066
|
+
if (effectiveWire !== "openai-responses") {
|
|
1067
|
+
return `${field}.${key} requires the openai-responses wire`;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
return null;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* Validate a provider's per-model wire override map (#404).
|
|
1075
|
+
*
|
|
1076
|
+
* Rejects, rather than silently ignoring, configurations the resolver would refuse:
|
|
1077
|
+
* a value outside the allowed wires, a model the upstream pins to one wire, and any
|
|
1078
|
+
* override on a canonical forward provider (where switching wires would drop the
|
|
1079
|
+
* caller's forwarded credential). Silently dropping them would leave the user
|
|
1080
|
+
* believing an override is in effect.
|
|
1081
|
+
*/
|
|
1082
|
+
export function modelAdapterRecordConfigError(
|
|
1083
|
+
value: unknown,
|
|
1084
|
+
field: string,
|
|
1085
|
+
providerName: string,
|
|
1086
|
+
provider: { adapter?: unknown; authMode?: unknown; baseUrl?: unknown },
|
|
1087
|
+
): string | null {
|
|
1088
|
+
if (value === undefined) return null;
|
|
1089
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
1090
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1091
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
1092
|
+
const entries = Object.entries(value);
|
|
1093
|
+
if (entries.length > 0 && isCanonicalOpenAiForwardProvider(provider as OcxProviderConfig)) {
|
|
1094
|
+
return `${field} is not supported on the canonical ChatGPT forward provider`;
|
|
1095
|
+
}
|
|
1096
|
+
for (const [key, entry] of entries) {
|
|
1097
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
1098
|
+
if (typeof entry !== "string" || !MODEL_ADAPTER_OVERRIDE_ALLOWED.has(entry)) {
|
|
1099
|
+
return `${field}.${key} must be one of: ${[...MODEL_ADAPTER_OVERRIDE_ALLOWED].join(", ")}`;
|
|
1100
|
+
}
|
|
1101
|
+
if (isWirePinnedModel(providerName, key.trim())) {
|
|
1102
|
+
return `${field}.${key} cannot be overridden: the upstream only speaks one wire for this model`;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
return null;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
const CODEX_ACCOUNT_NAMESPACES_RECORD_ERROR =
|
|
1109
|
+
"codexAccountNamespaces must be a plain object mapping account selectors to Codex account ids";
|
|
1110
|
+
const CODEX_ACCOUNT_NAMESPACE_KEY_ERROR =
|
|
1111
|
+
"account selectors must use 1-64 letters, numbers, dots, underscores, or hyphens and cannot be reserved JavaScript object keys";
|
|
1112
|
+
const CODEX_ACCOUNT_NAMESPACE_TARGET_ERROR =
|
|
1113
|
+
"account selector targets must be @main or valid Codex pool-account ids";
|
|
1114
|
+
const CODEX_ACCOUNT_NAMESPACE_ACCOUNT_ID_COLLISION_ERROR =
|
|
1115
|
+
"account selectors must not collide with configured Codex pool-account ids or account selector targets";
|
|
1116
|
+
|
|
1117
|
+
function configuredCodexPoolAccountIds(value: unknown): Set<string> {
|
|
1118
|
+
const accountIds = new Set<string>();
|
|
1119
|
+
if (!Array.isArray(value)) return accountIds;
|
|
1120
|
+
for (const account of value) {
|
|
1121
|
+
if (!account || typeof account !== "object" || Array.isArray(account)) continue;
|
|
1122
|
+
const { id, isMain } = account as { id?: unknown; isMain?: unknown };
|
|
1123
|
+
if (typeof id === "string" && isMain !== true) accountIds.add(id);
|
|
1124
|
+
}
|
|
1125
|
+
return accountIds;
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
const codexAccountNamespacesSchema = z.custom<Record<string, unknown>>(
|
|
1129
|
+
(value): value is Record<string, unknown> => !!value
|
|
1130
|
+
&& typeof value === "object"
|
|
1131
|
+
&& !Array.isArray(value)
|
|
1132
|
+
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null),
|
|
1133
|
+
{ error: CODEX_ACCOUNT_NAMESPACES_RECORD_ERROR },
|
|
1134
|
+
).superRefine((accountNamespaces, ctx) => {
|
|
1135
|
+
// Inspect raw own entries before z.record parses them; Zod omits __proto__ record keys.
|
|
1136
|
+
for (const [namespace, accountId] of Object.entries(accountNamespaces)) {
|
|
1137
|
+
if (!isValidProviderName(namespace)) {
|
|
1138
|
+
ctx.addIssue({
|
|
1139
|
+
code: "custom",
|
|
1140
|
+
path: [namespace],
|
|
1141
|
+
message: CODEX_ACCOUNT_NAMESPACE_KEY_ERROR,
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
if (!isValidCodexAccountNamespaceTarget(accountId)) {
|
|
1145
|
+
ctx.addIssue({
|
|
1146
|
+
code: "custom",
|
|
1147
|
+
path: [namespace],
|
|
1148
|
+
message: CODEX_ACCOUNT_NAMESPACE_TARGET_ERROR,
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
}).pipe(z.record(z.string(), z.string()));
|
|
1153
|
+
|
|
1154
|
+
const CODEX_ACCOUNT_PRIORITIES_RECORD_ERROR =
|
|
1155
|
+
"codexAccountPriorities must be a plain object mapping Codex account ids to selection-order integers";
|
|
1156
|
+
const CODEX_ACCOUNT_PRIORITY_KEY_ERROR =
|
|
1157
|
+
"selection-order keys must be a Codex pool-account id or the main Codex account and cannot be reserved JavaScript object keys";
|
|
1158
|
+
const CODEX_ACCOUNT_PRIORITY_VALUE_ERROR =
|
|
1159
|
+
"selection order must be an integer between -100 and 100";
|
|
1160
|
+
|
|
1161
|
+
const CODEX_ACCOUNT_PIN_PATTERN = /^[a-zA-Z0-9._-]{1,64}$/;
|
|
1162
|
+
|
|
1163
|
+
const codexAccountPrioritiesSchema = z.custom<Record<string, unknown>>(
|
|
1164
|
+
(value): value is Record<string, unknown> => !!value
|
|
1165
|
+
&& typeof value === "object"
|
|
1166
|
+
&& !Array.isArray(value)
|
|
1167
|
+
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null),
|
|
1168
|
+
{ error: CODEX_ACCOUNT_PRIORITIES_RECORD_ERROR },
|
|
1169
|
+
).superRefine((priorities, ctx) => {
|
|
1170
|
+
// Inspect raw own entries before z.record parses them; Zod omits __proto__ record keys.
|
|
1171
|
+
for (const [accountId, priority] of Object.entries(priorities)) {
|
|
1172
|
+
if (!isCodexAccountPriorityKey(accountId)) {
|
|
1173
|
+
ctx.addIssue({ code: "custom", path: [accountId], message: CODEX_ACCOUNT_PRIORITY_KEY_ERROR });
|
|
1174
|
+
}
|
|
1175
|
+
if (parseAccountPriority(priority) === null) {
|
|
1176
|
+
ctx.addIssue({ code: "custom", path: [accountId], message: CODEX_ACCOUNT_PRIORITY_VALUE_ERROR });
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
}).pipe(z.record(z.string(), z.number().int()));
|
|
1180
|
+
|
|
1181
|
+
/**
|
|
1182
|
+
* Deliberately permissive. A user's config is not ours to invalidate: a strict
|
|
1183
|
+
* entry fails the whole parse, and loadConfig's fallback then backs the file up
|
|
1184
|
+
* and returns defaults — losing providers and pool accounts because one key name
|
|
1185
|
+
* was too long. Length and charset rules live at the POST/PATCH boundary, where
|
|
1186
|
+
* rejecting produces a 400 instead. `.passthrough()` keeps unknown per-key
|
|
1187
|
+
* properties across a load -> mutate -> save round trip.
|
|
1188
|
+
*
|
|
1189
|
+
* Only `key` is load-bearing: admission compares that string and nothing else
|
|
1190
|
+
* (src/server/auth-cors.ts isDataPlaneAdmissionSecret). So the secret is the one
|
|
1191
|
+
* field that must be a usable string, and every piece of metadata around it
|
|
1192
|
+
* degrades instead of taking the credential down with it. Dropping a working key
|
|
1193
|
+
* because its `name` was hand-edited to a number would be a silent revocation —
|
|
1194
|
+
* and on a remote bind, potentially a server that refuses to start.
|
|
1195
|
+
*
|
|
1196
|
+
* "Usable" matches admission exactly. The presented token is trimmed before the
|
|
1197
|
+
* comparison but the stored value is not, so a key with surrounding whitespace
|
|
1198
|
+
* can never match either form of itself. Keeping one would be worse than dropping
|
|
1199
|
+
* it: `system-env.ts` and `cli/claude.ts` hand `apiKeys[0].key` to launched
|
|
1200
|
+
* clients, so a junk first entry would mask a valid later one.
|
|
1201
|
+
*/
|
|
1202
|
+
const apiKeyEntrySchema = z.object({
|
|
1203
|
+
key: z.string().refine(isUsableApiKeySecret),
|
|
1204
|
+
// Degrades to "" here; every schema consumer then runs `normalizeApiKeyIds`,
|
|
1205
|
+
// which fills it deterministically so the id is stable across loads.
|
|
1206
|
+
id: z.string().catch(""),
|
|
1207
|
+
name: z.string().catch(""),
|
|
1208
|
+
createdAt: z.string().catch(""),
|
|
1209
|
+
}).passthrough();
|
|
1210
|
+
|
|
1211
|
+
/**
|
|
1212
|
+
* Durable per-client intent.
|
|
1213
|
+
*
|
|
1214
|
+
* `.passthrough()` is load-bearing: a binary that only knows `codex` must not
|
|
1215
|
+
* erase a key a later version wrote during a field-scoped mutation. And each key
|
|
1216
|
+
* degrades on its own — a hand edit of `{"codex": "false", "future": false}`
|
|
1217
|
+
* drops `codex` to absent (which reads as ON) and keeps `future`, rather than
|
|
1218
|
+
* invalidating the object or, worse, the whole config.
|
|
1219
|
+
*/
|
|
1220
|
+
const clientIntegrationsSchema = z.object({
|
|
1221
|
+
codex: z.boolean().optional().catch(undefined),
|
|
1222
|
+
grok: z.boolean().optional().catch(undefined),
|
|
1223
|
+
"claude-desktop": z.boolean().optional().catch(undefined),
|
|
1224
|
+
}).passthrough();
|
|
1225
|
+
|
|
1226
|
+
const agentTaskRecoverySchema = z.object({
|
|
1227
|
+
enabled: z.boolean().optional(),
|
|
1228
|
+
model: z.string().trim().min(1).optional(),
|
|
1229
|
+
timeoutMs: z.number().int().min(1_000).max(120_000).optional(),
|
|
1230
|
+
cacheEntries: z.number().int().min(1).max(512).optional(),
|
|
1231
|
+
}).strict();
|
|
1232
|
+
|
|
1233
|
+
const configSchema = z.object({
|
|
1234
|
+
port: z.number().int().min(0).max(65535).default(10100),
|
|
1235
|
+
managementUsageMaxReadBytes: z.number().int().positive().default(64 * 1024 * 1024),
|
|
1236
|
+
// Invalid hand edits disable only this opt-in circuit. Live writes remain strict.
|
|
1237
|
+
upstreamHostCircuitThreshold: z.number().int()
|
|
1238
|
+
.min(0)
|
|
1239
|
+
.max(UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD)
|
|
1240
|
+
.optional()
|
|
1241
|
+
.catch(undefined),
|
|
1242
|
+
appOwnedMemoryBudgetMb: z.number().int()
|
|
1243
|
+
.min(MIN_APP_OWNED_MEMORY_BUDGET_MB)
|
|
1244
|
+
.max(MAX_APP_OWNED_MEMORY_BUDGET_MB)
|
|
1245
|
+
.default(DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES / (1024 * 1024))
|
|
1246
|
+
.catch(DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES / (1024 * 1024)),
|
|
1247
|
+
// A blank hostname degrades to undefined rather than failing the parse. `getDefaultConfig()`
|
|
1248
|
+
// carries no `hostname` key, so the backup-and-defaults repair path below cannot merge one
|
|
1249
|
+
// away — a hand-edited `"hostname": ""` would fail twice and reset providers/apiKeys to
|
|
1250
|
+
// defaults, which is strictly worse than the bind bug this validation exists for. Degrading
|
|
1251
|
+
// is safe: startServer() already falls back to 127.0.0.1 for a missing hostname. Write-time
|
|
1252
|
+
// rejection lives in validateConfigCandidate() so bad values still surface to the caller.
|
|
1253
|
+
hostname: z.string().trim().min(1).optional().catch(undefined),
|
|
1254
|
+
// Discriminated on `enabled` so a disabled entry cannot be forced to carry a port, and an
|
|
1255
|
+
// enabled one cannot omit it (#1102). A malformed value degrades to undefined rather than
|
|
1256
|
+
// failing the whole parse: this is an opt-in convenience surface, and a hand-edit typo here
|
|
1257
|
+
// must never reset providers/apiKeys through the backup-and-defaults repair path.
|
|
1258
|
+
unauthenticatedLoopbackListener: z.union([
|
|
1259
|
+
z.object({ enabled: z.literal(false) }),
|
|
1260
|
+
z.object({ enabled: z.literal(true), port: z.number().int().min(1).max(65535) }),
|
|
1261
|
+
]).optional().catch(undefined),
|
|
1262
|
+
providers: z.record(z.string(), providerConfigSchema),
|
|
1263
|
+
defaultProvider: z.string().min(1).default("openai"),
|
|
1264
|
+
// A retry can be billable, so absence and malformed hand edits both stay off.
|
|
1265
|
+
emptyCompletionRetry: z.boolean().optional().catch(false),
|
|
1266
|
+
openaiProviderTierVersion: z.union([z.literal(1), z.literal(2)]).optional(),
|
|
1267
|
+
// Invalid hand edits must not discard an otherwise usable config.
|
|
1268
|
+
googleAntigravityStaticCatalogVersion: z.union([z.literal(1), z.literal(2)]).optional().catch(undefined),
|
|
1269
|
+
clientIntegrations: clientIntegrationsSchema.optional().catch(undefined),
|
|
1270
|
+
providerContextCaps: z.record(z.string(), z.number().int().positive()).optional(),
|
|
1271
|
+
contextCapValue: z.number().int().positive().optional(),
|
|
1272
|
+
multiAgentGuidanceEnabled: z.boolean().optional(),
|
|
1273
|
+
// Invalid optional recovery config must not discard unrelated provider/account state.
|
|
1274
|
+
agentTaskRecovery: agentTaskRecoverySchema.optional().catch(undefined),
|
|
1275
|
+
// These selections pre-date schema validation and used to pass through as
|
|
1276
|
+
// unknown fields. Invalid hand edits must disable only the optional
|
|
1277
|
+
// delegation/native-default feature, not reject the whole config and hide
|
|
1278
|
+
// otherwise valid providers, accounts, or the configured listen port.
|
|
1279
|
+
injectionModel: z.string().optional().catch(undefined),
|
|
1280
|
+
injectionEffort: z.string().optional().catch(undefined),
|
|
1281
|
+
syncCodexSubagentDefaults: z.boolean().optional().catch(undefined),
|
|
1282
|
+
syncCodexAgentRoles: z.boolean().optional().catch(undefined),
|
|
1283
|
+
// Salvage element by element. A malformed neighbour must not wipe the catalog.
|
|
1284
|
+
subagentRoles: z.unknown().optional(),
|
|
1285
|
+
// Per-primary-model fallback chains. Values must be non-empty string arrays;
|
|
1286
|
+
// malformed entries degrade to undefined rather than rejecting the whole config.
|
|
1287
|
+
subagentModelFallbackByModel: z.record(
|
|
1288
|
+
z.string(),
|
|
1289
|
+
z.array(z.string().trim().min(1)).min(1),
|
|
1290
|
+
).optional().catch(undefined),
|
|
1291
|
+
codexShimAutoRestore: z.boolean().optional(),
|
|
1292
|
+
pausedCodexAccountIds: z.array(z.string().regex(/^[a-zA-Z0-9._-]{1,64}$/)).optional(),
|
|
1293
|
+
codexAccountNamespaces: codexAccountNamespacesSchema.optional(),
|
|
1294
|
+
// Selection order is a preference, not a safety control like pause: a malformed
|
|
1295
|
+
// map degrades to "no ordering" rather than failing the parse, so a hand-edited
|
|
1296
|
+
// typo cannot trip the backup-and-defaults repair path and wipe providers or
|
|
1297
|
+
// pool accounts. Warning emitted in loadConfig.
|
|
1298
|
+
codexAccountPriorities: codexAccountPrioritiesSchema.optional().catch(undefined),
|
|
1299
|
+
activeCodexAccountPinned: z.string().regex(CODEX_ACCOUNT_PIN_PATTERN).optional().catch(undefined),
|
|
1300
|
+
// A malformed hand edit must degrade to false without discarding providers, accounts,
|
|
1301
|
+
// or the exact selector map. Live writes remain strict.
|
|
1302
|
+
codexAccountPickerEnabled: z.boolean().optional().catch(false),
|
|
1303
|
+
// Model ids excluded from the Grok Build managed block (dashboard switches).
|
|
1304
|
+
grokExcludedModels: z.array(z.string()).optional(),
|
|
1305
|
+
// Invalid values degrade to undefined ("auto") instead of failing the whole
|
|
1306
|
+
// parse: a hand-edited typo must never trip the backup-and-defaults repair
|
|
1307
|
+
// path below and wipe providers/pool accounts. Warning emitted in loadConfig.
|
|
1308
|
+
streamMode: z.enum(["auto", "legacy-tee", "eager-relay"]).optional().catch(undefined),
|
|
1309
|
+
// Same degrade-don't-reject rationale as the fields above: a hand-edited
|
|
1310
|
+
// non-string must not trip the backup-and-defaults repair path. Unset then
|
|
1311
|
+
// takes the canonical sideband path (src/server/live.ts normalizeSidebandRoot).
|
|
1312
|
+
experimentalRealtimeWsBaseUrl: z.string().optional().catch(undefined),
|
|
1313
|
+
// Salvage element by element, and never fail the parse. Two spellings were
|
|
1314
|
+
// measured on this zod version and both lose data:
|
|
1315
|
+
// `z.array(entry).catch(undefined)` -> one bad entry discards EVERY key
|
|
1316
|
+
// `z.array(z.unknown())` -> a non-array value still raises
|
|
1317
|
+
// invalid_type, reaching the
|
|
1318
|
+
// backup-and-defaults repair path
|
|
1319
|
+
// Starting from `unknown` is what makes both survivable. A key the user still
|
|
1320
|
+
// has deployed must not be collateral damage for one bad neighbour, and on a
|
|
1321
|
+
// remote bind an emptied array is worse than cosmetic: assertServerAuthConfig
|
|
1322
|
+
// refuses to start without a data credential.
|
|
1323
|
+
apiKeys: z.unknown().optional().transform(value => {
|
|
1324
|
+
if (value === undefined) return undefined;
|
|
1325
|
+
if (!Array.isArray(value)) return undefined;
|
|
1326
|
+
return value
|
|
1327
|
+
.filter(row => apiKeyEntrySchema.safeParse(row).success)
|
|
1328
|
+
.map(row => apiKeyEntrySchema.parse(row) as OcxApiKeyEntry);
|
|
1329
|
+
}),
|
|
1330
|
+
}).passthrough().superRefine((config, ctx) => {
|
|
1331
|
+
const claudeCode = (config as { claudeCode?: unknown }).claudeCode;
|
|
1332
|
+
if (claudeCode !== undefined && (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode))) {
|
|
1333
|
+
ctx.addIssue({ code: "custom", path: ["claudeCode"], message: "claudeCode must be an object" });
|
|
1334
|
+
} else if (claudeCode) {
|
|
1335
|
+
const claude = claudeCode as { desktopProfile?: unknown };
|
|
1336
|
+
if (claude.desktopProfile !== undefined) {
|
|
1337
|
+
try {
|
|
1338
|
+
parseDesktopProfile(claude.desktopProfile);
|
|
1339
|
+
} catch (error) {
|
|
1340
|
+
ctx.addIssue({
|
|
1341
|
+
code: "custom",
|
|
1342
|
+
path: ["claudeCode", "desktopProfile"],
|
|
1343
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
const accountNamespaces = config.codexAccountNamespaces;
|
|
1350
|
+
if (accountNamespaces) {
|
|
1351
|
+
const configuredAccountIds = configuredCodexPoolAccountIds(config.codexAccounts);
|
|
1352
|
+
const configuredProviderNamespaces = new Set([
|
|
1353
|
+
COMBO_NAMESPACE,
|
|
1354
|
+
OPENAI_CODEX_PROVIDER_ID,
|
|
1355
|
+
POLICY_NAMESPACE,
|
|
1356
|
+
...Object.keys(config.providers),
|
|
1357
|
+
].map(codexProviderNamespaceKey));
|
|
1358
|
+
const namespaceTargets = new Set(
|
|
1359
|
+
Object.values(accountNamespaces)
|
|
1360
|
+
.filter(accountId => accountId !== MAIN_CODEX_ACCOUNT_NAMESPACE_TARGET),
|
|
1361
|
+
);
|
|
1362
|
+
for (const namespace of Object.keys(accountNamespaces)) {
|
|
1363
|
+
if (configuredProviderNamespaces.has(codexProviderNamespaceKey(namespace))) {
|
|
1364
|
+
ctx.addIssue({
|
|
1365
|
+
code: "custom",
|
|
1366
|
+
path: ["codexAccountNamespaces", namespace],
|
|
1367
|
+
message: "account selectors must not collide with configured provider, combo, or routing policy namespaces",
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
if (configuredAccountIds.has(namespace) || namespaceTargets.has(namespace)) {
|
|
1371
|
+
ctx.addIssue({
|
|
1372
|
+
code: "custom",
|
|
1373
|
+
path: ["codexAccountNamespaces", namespace],
|
|
1374
|
+
message: CODEX_ACCOUNT_NAMESPACE_ACCOUNT_ID_COLLISION_ERROR,
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
for (const name of Object.keys(config.providers)) {
|
|
1380
|
+
if (!isValidProviderName(name)) {
|
|
1381
|
+
ctx.addIssue({
|
|
1382
|
+
code: "custom",
|
|
1383
|
+
path: ["providers", redactSecretString(name)],
|
|
1384
|
+
message: "provider names must use letters, numbers, dot, underscore, or hyphen and cannot be reserved JavaScript object keys or routing namespaces (policy)",
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
const provider = config.providers[name];
|
|
1388
|
+
if (hasFastWireCapabilityConflict(provider)) {
|
|
1389
|
+
ctx.addIssue({
|
|
1390
|
+
code: "custom",
|
|
1391
|
+
path: ["providers", redactSecretString(name), "fastWire"],
|
|
1392
|
+
message: "fastWire=null conflicts with supportsServiceTier=true",
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
const openRouterRoutingError = openRouterRoutingConfigError(provider);
|
|
1396
|
+
if (openRouterRoutingError) {
|
|
1397
|
+
ctx.addIssue({
|
|
1398
|
+
code: "custom",
|
|
1399
|
+
path: [
|
|
1400
|
+
"providers",
|
|
1401
|
+
redactSecretString(name),
|
|
1402
|
+
openRouterRoutingError.startsWith("modelOpenRouterRouting")
|
|
1403
|
+
? "modelOpenRouterRouting"
|
|
1404
|
+
: "openRouterRouting",
|
|
1405
|
+
],
|
|
1406
|
+
message: openRouterRoutingError,
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
if (Object.hasOwn(provider, "virtualModels")) {
|
|
1410
|
+
ctx.addIssue({
|
|
1411
|
+
code: "custom",
|
|
1412
|
+
path: ["providers", redactSecretString(name), "virtualModels"],
|
|
1413
|
+
message: "virtualModels is registry-only and must not be persisted",
|
|
1414
|
+
});
|
|
1415
|
+
}
|
|
1416
|
+
const baseUrlError = providerBaseUrlConfigError(provider.baseUrl);
|
|
1417
|
+
if (baseUrlError) {
|
|
1418
|
+
ctx.addIssue({
|
|
1419
|
+
code: "custom",
|
|
1420
|
+
path: ["providers", redactSecretString(name), "baseUrl"],
|
|
1421
|
+
message: baseUrlError,
|
|
1422
|
+
});
|
|
1423
|
+
} else {
|
|
1424
|
+
const destinationError = providerDestinationConfigError(name, provider);
|
|
1425
|
+
if (destinationError) {
|
|
1426
|
+
ctx.addIssue({
|
|
1427
|
+
code: "custom",
|
|
1428
|
+
path: ["providers", redactSecretString(name), "baseUrl"],
|
|
1429
|
+
message: destinationError,
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
const responsesPathError = providerResponsesPathConfigError(provider.responsesPath);
|
|
1434
|
+
if (responsesPathError) {
|
|
1435
|
+
ctx.addIssue({
|
|
1436
|
+
code: "custom",
|
|
1437
|
+
path: ["providers", redactSecretString(name), "responsesPath"],
|
|
1438
|
+
message: responsesPathError,
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
const headersError = providerHeadersConfigError((provider as { headers?: unknown }).headers);
|
|
1442
|
+
if (headersError) {
|
|
1443
|
+
ctx.addIssue({
|
|
1444
|
+
code: "custom",
|
|
1445
|
+
path: ["providers", redactSecretString(name), "headers"],
|
|
1446
|
+
message: headersError,
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
const modelCostsError = providerModelCostsConfigError((provider as { modelCosts?: unknown }).modelCosts);
|
|
1450
|
+
if (modelCostsError) {
|
|
1451
|
+
ctx.addIssue({
|
|
1452
|
+
code: "custom",
|
|
1453
|
+
// The provider key is caller-controlled and can be token-shaped; redact it
|
|
1454
|
+
// before schemaDiagnosticsError serializes the path (ocx config validate/import).
|
|
1455
|
+
path: ["providers", redactSecretString(name), "modelCosts"],
|
|
1456
|
+
message: modelCostsError,
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
const apiKeyTransportError = apiKeyTransportConfigError(provider as OcxProviderConfig);
|
|
1460
|
+
if (apiKeyTransportError) {
|
|
1461
|
+
ctx.addIssue({
|
|
1462
|
+
code: "custom",
|
|
1463
|
+
path: ["providers", redactSecretString(name), "apiKeyTransport"],
|
|
1464
|
+
message: apiKeyTransportError,
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
1467
|
+
const modelAdaptersError = modelAdapterRecordConfigError(
|
|
1468
|
+
(provider as { modelAdapters?: unknown }).modelAdapters,
|
|
1469
|
+
"modelAdapters",
|
|
1470
|
+
name,
|
|
1471
|
+
provider,
|
|
1472
|
+
);
|
|
1473
|
+
if (modelAdaptersError) {
|
|
1474
|
+
ctx.addIssue({
|
|
1475
|
+
code: "custom",
|
|
1476
|
+
path: ["providers", redactSecretString(name), "modelAdapters"],
|
|
1477
|
+
message: modelAdaptersError,
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
const preferHostedToolsError = modelPreferHostedToolsConfigError(
|
|
1481
|
+
(provider as { modelPreferHostedTools?: unknown }).modelPreferHostedTools,
|
|
1482
|
+
"modelPreferHostedTools",
|
|
1483
|
+
name,
|
|
1484
|
+
provider,
|
|
1485
|
+
);
|
|
1486
|
+
if (preferHostedToolsError) {
|
|
1487
|
+
ctx.addIssue({
|
|
1488
|
+
code: "custom",
|
|
1489
|
+
path: ["providers", redactSecretString(name), "modelPreferHostedTools"],
|
|
1490
|
+
message: preferHostedToolsError,
|
|
1491
|
+
});
|
|
1492
|
+
}
|
|
1493
|
+
const maxInputError = positiveIntegerRecordConfigError(
|
|
1494
|
+
(provider as { modelMaxInputTokens?: unknown }).modelMaxInputTokens,
|
|
1495
|
+
"modelMaxInputTokens",
|
|
1496
|
+
);
|
|
1497
|
+
if (maxInputError) {
|
|
1498
|
+
ctx.addIssue({
|
|
1499
|
+
code: "custom",
|
|
1500
|
+
path: ["providers", redactSecretString(name), "modelMaxInputTokens"],
|
|
1501
|
+
message: maxInputError,
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
const reasoningSummariesError = booleanRecordConfigError(
|
|
1505
|
+
(provider as { modelSupportsReasoningSummaries?: unknown }).modelSupportsReasoningSummaries,
|
|
1506
|
+
"modelSupportsReasoningSummaries",
|
|
1507
|
+
);
|
|
1508
|
+
if (reasoningSummariesError) {
|
|
1509
|
+
ctx.addIssue({
|
|
1510
|
+
code: "custom",
|
|
1511
|
+
path: ["providers", redactSecretString(name), "modelSupportsReasoningSummaries"],
|
|
1512
|
+
message: reasoningSummariesError,
|
|
1513
|
+
});
|
|
1514
|
+
}
|
|
1515
|
+
const serviceTierModelsError = booleanRecordConfigError(
|
|
1516
|
+
(provider as { modelSupportsServiceTier?: unknown }).modelSupportsServiceTier,
|
|
1517
|
+
"modelSupportsServiceTier",
|
|
1518
|
+
);
|
|
1519
|
+
if (serviceTierModelsError) {
|
|
1520
|
+
ctx.addIssue({
|
|
1521
|
+
code: "custom",
|
|
1522
|
+
path: ["providers", redactSecretString(name), "modelSupportsServiceTier"],
|
|
1523
|
+
message: serviceTierModelsError,
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
const reasoningSummaryDeliveryError = reasoningSummaryDeliveryRecordConfigError(
|
|
1527
|
+
(provider as { modelReasoningSummaryDelivery?: unknown }).modelReasoningSummaryDelivery,
|
|
1528
|
+
(provider as { modelSupportsReasoningSummaries?: unknown }).modelSupportsReasoningSummaries,
|
|
1529
|
+
);
|
|
1530
|
+
if (reasoningSummaryDeliveryError) {
|
|
1531
|
+
ctx.addIssue({
|
|
1532
|
+
code: "custom",
|
|
1533
|
+
path: ["providers", redactSecretString(name), "modelReasoningSummaryDelivery"],
|
|
1534
|
+
message: reasoningSummaryDeliveryError,
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
1537
|
+
const defaultMaxOutputError = positiveIntegerConfigError(
|
|
1538
|
+
(provider as { defaultMaxOutputTokens?: unknown }).defaultMaxOutputTokens,
|
|
1539
|
+
"defaultMaxOutputTokens",
|
|
1540
|
+
);
|
|
1541
|
+
if (defaultMaxOutputError) {
|
|
1542
|
+
ctx.addIssue({
|
|
1543
|
+
code: "custom",
|
|
1544
|
+
path: ["providers", redactSecretString(name), "defaultMaxOutputTokens"],
|
|
1545
|
+
message: defaultMaxOutputError,
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
const maxOutputError = positiveIntegerRecordConfigError(
|
|
1549
|
+
(provider as { modelMaxOutputTokens?: unknown }).modelMaxOutputTokens,
|
|
1550
|
+
"modelMaxOutputTokens",
|
|
1551
|
+
);
|
|
1552
|
+
if (maxOutputError) {
|
|
1553
|
+
ctx.addIssue({
|
|
1554
|
+
code: "custom",
|
|
1555
|
+
path: ["providers", redactSecretString(name), "modelMaxOutputTokens"],
|
|
1556
|
+
message: maxOutputError,
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
const structuredOutputOptOutError = nonBlankStringArrayConfigError(
|
|
1560
|
+
(provider as { noStructuredOutputModels?: unknown }).noStructuredOutputModels,
|
|
1561
|
+
"noStructuredOutputModels",
|
|
1562
|
+
);
|
|
1563
|
+
if (structuredOutputOptOutError) {
|
|
1564
|
+
ctx.addIssue({
|
|
1565
|
+
code: "custom",
|
|
1566
|
+
path: ["providers", redactSecretString(name), "noStructuredOutputModels"],
|
|
1567
|
+
message: structuredOutputOptOutError,
|
|
1568
|
+
});
|
|
1569
|
+
}
|
|
1570
|
+
if (Object.hasOwn(provider, "codexAccountMode") && provider.codexAccountMode !== undefined) {
|
|
1571
|
+
// Persisted account mode is valid ONLY on the canonical built-in `openai` forward provider.
|
|
1572
|
+
// Old openai-multi rows stay parseable (they never carry a mode) so startup can migrate them.
|
|
1573
|
+
const canonicalOpenAiShape = name === "openai"
|
|
1574
|
+
&& provider.adapter === "openai-responses"
|
|
1575
|
+
&& (provider as { authMode?: unknown }).authMode === "forward"
|
|
1576
|
+
&& typeof provider.baseUrl === "string"
|
|
1577
|
+
&& provider.baseUrl.replace(/\/+$/, "") === "https://chatgpt.com/backend-api/codex";
|
|
1578
|
+
if (!canonicalOpenAiShape) {
|
|
1579
|
+
ctx.addIssue({
|
|
1580
|
+
code: "custom",
|
|
1581
|
+
path: ["providers", redactSecretString(name), "codexAccountMode"],
|
|
1582
|
+
message: "codexAccountMode is valid only on the canonical built-in openai provider",
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
if (!hasOwnProvider(config.providers, config.defaultProvider)) {
|
|
1588
|
+
ctx.addIssue({
|
|
1589
|
+
code: "custom",
|
|
1590
|
+
path: ["defaultProvider"],
|
|
1591
|
+
message: "defaultProvider must exist in providers",
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
const combos = (config as { combos?: unknown }).combos;
|
|
1595
|
+
if (combos !== undefined) {
|
|
1596
|
+
if (!combos || typeof combos !== "object" || Array.isArray(combos)) {
|
|
1597
|
+
ctx.addIssue({ code: "custom", path: ["combos"], message: "combos must be an object" });
|
|
1598
|
+
} else {
|
|
1599
|
+
for (const [id, raw] of Object.entries(combos as Record<string, unknown>)) {
|
|
1600
|
+
const alias = raw && typeof raw === "object" && !Array.isArray(raw)
|
|
1601
|
+
? (raw as { alias?: unknown }).alias
|
|
1602
|
+
: undefined;
|
|
1603
|
+
if (typeof alias === "string" && codexAccountNamespaceForModel(accountNamespaces, alias.trim())) {
|
|
1604
|
+
ctx.addIssue({
|
|
1605
|
+
code: "custom",
|
|
1606
|
+
path: ["combos", id, "alias"],
|
|
1607
|
+
message: CODEX_ACCOUNT_NAMESPACE_COMBO_ALIAS_COLLISION_ERROR,
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
// Pass the full map so cross-combo rules (alias uniqueness) apply at load time
|
|
1611
|
+
// too, not just via the management API; each combo is excluded from its own check.
|
|
1612
|
+
for (const issue of comboConfigIssues(id, raw, config.providers, {
|
|
1613
|
+
combos: combos as Record<string, import("./types").OcxComboConfig>,
|
|
1614
|
+
excludeComboId: id,
|
|
1615
|
+
})) {
|
|
1616
|
+
ctx.addIssue({
|
|
1617
|
+
code: "custom",
|
|
1618
|
+
path: ["combos", id, ...issue.path],
|
|
1619
|
+
message: issue.message,
|
|
1620
|
+
});
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
const routingProfiles = (config as { routingProfiles?: unknown }).routingProfiles;
|
|
1626
|
+
if (routingProfiles !== undefined) {
|
|
1627
|
+
if (!routingProfiles || typeof routingProfiles !== "object" || Array.isArray(routingProfiles)) {
|
|
1628
|
+
ctx.addIssue({ code: "custom", path: ["routingProfiles"], message: "routingProfiles must be an object" });
|
|
1629
|
+
} else {
|
|
1630
|
+
for (const [id, raw] of Object.entries(routingProfiles as Record<string, unknown>)) {
|
|
1631
|
+
for (const issue of routingProfileIssues(id, raw, {
|
|
1632
|
+
providers: config.providers,
|
|
1633
|
+
combos: combos as Record<string, import("./types").OcxComboConfig> | undefined,
|
|
1634
|
+
routingProfiles: routingProfiles as Record<string, import("./types").OcxRoutingProfileConfig>,
|
|
1635
|
+
codexAccountNamespaces: accountNamespaces,
|
|
1636
|
+
}, { excludeProfileId: id })) {
|
|
1637
|
+
ctx.addIssue({
|
|
1638
|
+
code: "custom",
|
|
1639
|
+
path: ["routingProfiles", id, ...issue.path],
|
|
1640
|
+
message: issue.message,
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
});
|
|
1647
|
+
|
|
1648
|
+
/**
|
|
1649
|
+
* Default featured subagent models (native GPT) seeded on a fresh install and when `subagentModels`
|
|
1650
|
+
* is unset. Codex's spawn_agent advertises the first 5 featured catalog entries, so this seed is a
|
|
1651
|
+
* deliberate 5-list: frontier gpt-5.5 first, the gpt-5.6 preview trio, and gpt-5.4-mini as the cheap
|
|
1652
|
+
* tier. gpt-5.4 / gpt-5.3-codex-spark stay selectable in the GUI's available list. The user can
|
|
1653
|
+
* remove any in the GUI — once they set the list (even to []), it is respected, so removals persist
|
|
1654
|
+
* (start-up only seeds the UNSET case). Kept to ids ChatGPT accepts; the start-up seed prefers the
|
|
1655
|
+
* live catalog's native slugs.
|
|
1656
|
+
*/
|
|
1657
|
+
export const DEFAULT_SUBAGENT_MODELS = ["gpt-5.5", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.4-mini"];
|
|
1658
|
+
|
|
1659
|
+
export function getConfigDir(): string {
|
|
1660
|
+
return resolveConfigDir();
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
export function getConfigPath(): string {
|
|
1664
|
+
return resolveConfigPath();
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
export function getPidPath(): string {
|
|
1668
|
+
return resolvePidPath();
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
export function getRuntimePortPath(): string {
|
|
1672
|
+
return resolveRuntimePortPath();
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
export function hardenConfigDir(): void {
|
|
1676
|
+
const dir = getConfigDir();
|
|
1677
|
+
// The guard runs BEFORE any mutation: refusing the write after chmod/ACL
|
|
1678
|
+
// would already have changed the protected directory (review round 2).
|
|
1679
|
+
assertNotRealHomeUnderTest(dir);
|
|
1680
|
+
if (existsSync(dir)) {
|
|
1681
|
+
try { chmodSync(dir, 0o700); } catch { /* best-effort */ }
|
|
1682
|
+
if (process.platform === "win32") {
|
|
1683
|
+
hardenSecretDir(dir, { required: false });
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
export function hardenExistingSecret(path: string): void {
|
|
1689
|
+
if (existsSync(path)) {
|
|
1690
|
+
try { chmodSync(path, 0o600); } catch { /* best-effort */ }
|
|
1691
|
+
if (process.platform === "win32") {
|
|
1692
|
+
hardenSecretPath(path, { required: false });
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
/**
|
|
1697
|
+
* The schema's `.catch(undefined)` silently degrades an invalid persisted
|
|
1698
|
+
* `streamMode` to "auto"; surface that once so a hand-edited typo (e.g.
|
|
1699
|
+
* "legacy_tee") is discoverable instead of silently changing stream shape.
|
|
1700
|
+
*/
|
|
1701
|
+
function warnDegradedStreamMode(rawParsed: unknown, validated: OcxConfig): void {
|
|
1702
|
+
if (!rawParsed || typeof rawParsed !== "object") return;
|
|
1703
|
+
const raw = (rawParsed as Record<string, unknown>).streamMode;
|
|
1704
|
+
if (raw !== undefined && validated.streamMode === undefined) {
|
|
1705
|
+
console.warn(`⚠️ config.json streamMode ${JSON.stringify(raw)} is invalid (expected "auto", "legacy-tee", or "eager-relay") — falling back to "auto"`);
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/**
|
|
1710
|
+
* Load-time degradation for `retryOn429` (loadConfig only): one hand-edited invalid optional
|
|
1711
|
+
* field (e.g. `attempts: 0` or a string) must not trip the whole provider schema and hide every
|
|
1712
|
+
* provider/key behind a default config. Invalid fields are dropped with a warning; the management
|
|
1713
|
+
* write boundary still rejects invalid policies explicitly.
|
|
1714
|
+
*/
|
|
1715
|
+
function sanitizeRetryOn429ForLoad(parsed: unknown): void {
|
|
1716
|
+
if (!parsed || typeof parsed !== "object") return;
|
|
1717
|
+
const root = parsed as Record<string, unknown>;
|
|
1718
|
+
const providers = root.providers;
|
|
1719
|
+
if (!providers || typeof providers !== "object" || Array.isArray(providers)) return;
|
|
1720
|
+
for (const [name, provider] of Object.entries(providers as Record<string, unknown>)) {
|
|
1721
|
+
// This sanitizer runs BEFORE schema validation, so the provider name is untrusted: redact
|
|
1722
|
+
// secret-shaped names and JSON-escape control characters before it reaches any warning.
|
|
1723
|
+
const safeProviderName = JSON.stringify(redactSecretString(name));
|
|
1724
|
+
if (!provider || typeof provider !== "object" || Array.isArray(provider)) continue;
|
|
1725
|
+
const p = provider as Record<string, unknown>;
|
|
1726
|
+
const policy = p.retryOn429;
|
|
1727
|
+
if (policy === undefined) continue;
|
|
1728
|
+
if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
|
|
1729
|
+
delete p.retryOn429;
|
|
1730
|
+
// Never serialize the value: an accidental `retryOn429: "sk-..."` would leak the secret.
|
|
1731
|
+
console.warn(`⚠️ config.json providers.${safeProviderName}.retryOn429 (${typeof policy}) is invalid — ignoring the policy`);
|
|
1732
|
+
continue;
|
|
1733
|
+
}
|
|
1734
|
+
const policyRecord = policy as Record<string, unknown>;
|
|
1735
|
+
// An explicitly present but invalid master switch must not silently default to ENABLED:
|
|
1736
|
+
// drop the whole policy so a hand-edit that tried to disable retries stays disabled.
|
|
1737
|
+
if ("enabled" in policyRecord && typeof policyRecord.enabled !== "boolean") {
|
|
1738
|
+
delete p.retryOn429;
|
|
1739
|
+
console.warn(`⚠️ config.json providers.${safeProviderName}.retryOn429.enabled (${typeof policyRecord.enabled}) is invalid — ignoring the whole policy`);
|
|
1740
|
+
continue;
|
|
1741
|
+
}
|
|
1742
|
+
// Field checks derive from the shared policy schema so the bounds cannot drift
|
|
1743
|
+
// between the load-time sanitizer, the config schema, and the write boundary.
|
|
1744
|
+
const policyShape = retryOn429PolicySchema.shape;
|
|
1745
|
+
const hadPolicyEntries = Object.keys(policyRecord).length > 0;
|
|
1746
|
+
const cleaned: Record<string, unknown> = {};
|
|
1747
|
+
for (const [key, fieldSchema] of Object.entries(policyShape)) {
|
|
1748
|
+
const value = policyRecord[key];
|
|
1749
|
+
if (value === undefined) continue;
|
|
1750
|
+
if (fieldSchema.safeParse(value).success) cleaned[key] = value;
|
|
1751
|
+
// Log only the received type, never the value (provider config can hold secrets).
|
|
1752
|
+
else console.warn(`⚠️ config.json providers.${safeProviderName}.retryOn429.${key} (${typeof value}) is invalid — ignoring the field`);
|
|
1753
|
+
}
|
|
1754
|
+
const knownKeys = new Set(Object.keys(policyShape));
|
|
1755
|
+
for (const key of Object.keys(policyRecord)) {
|
|
1756
|
+
if (!knownKeys.has(key)) {
|
|
1757
|
+
// Redact the field NAME before logging: a malformed hand-edit can place a secret in a
|
|
1758
|
+
// property name (`retryOn429: { "sk-...": true }`). Ordinary typos (e.g. `attempt`)
|
|
1759
|
+
// stay readable, secret-shaped names become [REDACTED]. JSON-escape afterwards so a
|
|
1760
|
+
// control-character property name (newline/ANSI) can never forge a log line.
|
|
1761
|
+
console.warn(`⚠️ config.json providers.${safeProviderName}.retryOn429.${JSON.stringify(redactSecretString(key))} is not a recognized field — ignoring it`);
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
if (hadPolicyEntries && Object.keys(cleaned).length === 0) {
|
|
1765
|
+
// Every supplied field was invalid: drop the whole policy. Persisting `{}` here would
|
|
1766
|
+
// opt IN to retries with defaults, which is the opposite of what a malformed
|
|
1767
|
+
// disable-oriented edit (`retryOn429: { enabled: "false" }`, `attempts: 0`) asked for.
|
|
1768
|
+
delete p.retryOn429;
|
|
1769
|
+
console.warn(`⚠️ config.json providers.${safeProviderName}.retryOn429 has no valid fields left — removing the policy (an empty policy would enable retries with defaults)`);
|
|
1770
|
+
} else {
|
|
1771
|
+
// Preserve an intentionally empty `retryOn429: {}` (presence = opt-in with defaults).
|
|
1772
|
+
p.retryOn429 = cleaned;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
/**
|
|
1778
|
+
* Management write-boundary validation for `retryOn429` (fail closed). Unlike the
|
|
1779
|
+
* lenient load-time sanitizer, invalid values and unknown keys are rejected outright so
|
|
1780
|
+
* a POST/PATCH cannot persist a policy the proxy would then silently degrade. Reuses the
|
|
1781
|
+
* shared policy schema. Never echoes values, and secret-shaped unknown field names are
|
|
1782
|
+
* redacted (a malformed write can place a secret in a property name).
|
|
1783
|
+
*/
|
|
1784
|
+
export function retryOn429PolicyConfigError(policy: unknown): string | null {
|
|
1785
|
+
if (policy === undefined) return null;
|
|
1786
|
+
const result = retryOn429PolicySchema.safeParse(policy);
|
|
1787
|
+
if (result.success) return null;
|
|
1788
|
+
const first = result.error.issues[0];
|
|
1789
|
+
if (!first) return "retryOn429 is invalid";
|
|
1790
|
+
if (first.code === "unrecognized_keys") {
|
|
1791
|
+
const names = first.keys.map(key => JSON.stringify(redactSecretString(key))).join(", ");
|
|
1792
|
+
return `retryOn429 has unrecognized field${first.keys.length > 1 ? "s" : ""}: ${names}`;
|
|
1793
|
+
}
|
|
1794
|
+
if (first.path.length === 0) return `retryOn429 is invalid (${first.message})`;
|
|
1795
|
+
const field = String(first.path[first.path.length - 1]);
|
|
1796
|
+
return `retryOn429.${field} is invalid (${first.message})`;
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
/**
|
|
1800
|
+
* Load-time degradation for `providers.<name>.modelCosts`, mirroring
|
|
1801
|
+
* {@link sanitizeRetryOn429ForLoad}. A hand-edited malformed display-price row
|
|
1802
|
+
* must not fail the whole config parse — that would back up config.json and
|
|
1803
|
+
* fall back to defaults, dropping otherwise valid providers and the default
|
|
1804
|
+
* route for a typo in a non-runtime display field. Invalid rows are dropped
|
|
1805
|
+
* with a warning; strict rejection stays at the management/write boundary
|
|
1806
|
+
* (providerManagementConfigError).
|
|
1807
|
+
*/
|
|
1808
|
+
function sanitizeModelCostsForLoad(parsed: unknown): void {
|
|
1809
|
+
if (!parsed || typeof parsed !== "object") return;
|
|
1810
|
+
const root = parsed as Record<string, unknown>;
|
|
1811
|
+
const providers = root.providers;
|
|
1812
|
+
if (!providers || typeof providers !== "object" || Array.isArray(providers)) return;
|
|
1813
|
+
for (const [name, provider] of Object.entries(providers as Record<string, unknown>)) {
|
|
1814
|
+
// Runs before schema validation, so the provider name is untrusted: redact
|
|
1815
|
+
// secret-shaped names and JSON-escape control characters for the warning.
|
|
1816
|
+
const safeProviderName = JSON.stringify(redactSecretString(name));
|
|
1817
|
+
if (!provider || typeof provider !== "object" || Array.isArray(provider)) continue;
|
|
1818
|
+
const p = provider as Record<string, unknown>;
|
|
1819
|
+
const costs = p.modelCosts;
|
|
1820
|
+
if (costs === undefined) continue;
|
|
1821
|
+
if (!costs || typeof costs !== "object" || Array.isArray(costs)) {
|
|
1822
|
+
delete p.modelCosts;
|
|
1823
|
+
console.warn(`⚠️ config.json providers.${safeProviderName}.modelCosts (${typeof costs}) is invalid — ignoring the overlay`);
|
|
1824
|
+
continue;
|
|
1825
|
+
}
|
|
1826
|
+
const costsRecord = costs as Record<string, unknown>;
|
|
1827
|
+
const hadEntries = Object.keys(costsRecord).length > 0;
|
|
1828
|
+
let kept = 0;
|
|
1829
|
+
for (const [modelId, entry] of Object.entries(costsRecord)) {
|
|
1830
|
+
// Reuse the shared per-row shape contract so the load-time sanitizer
|
|
1831
|
+
// cannot drift from the schema and the write boundary.
|
|
1832
|
+
if (providerModelCostsConfigError({ [modelId]: entry }) === null) {
|
|
1833
|
+
kept++;
|
|
1834
|
+
continue;
|
|
1835
|
+
}
|
|
1836
|
+
delete costsRecord[modelId];
|
|
1837
|
+
// Redact the model id: a hand-edit can place a secret in a key name.
|
|
1838
|
+
console.warn(`⚠️ config.json providers.${safeProviderName}.modelCosts.${JSON.stringify(redactSecretString(modelId))} is invalid — ignoring the row`);
|
|
1839
|
+
}
|
|
1840
|
+
if (hadEntries && kept === 0) {
|
|
1841
|
+
delete p.modelCosts;
|
|
1842
|
+
console.warn(`⚠️ config.json providers.${safeProviderName}.modelCosts has no valid rows left — removing the overlay`);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
/**
|
|
1848
|
+
* Companion to {@link warnDegradedStreamMode} for a blank persisted `hostname`. The bind
|
|
1849
|
+
* falls back to loopback, which is the safe direction but not what the file asked for —
|
|
1850
|
+
* say so once instead of silently ignoring the field.
|
|
1851
|
+
*/
|
|
1852
|
+
function warnDegradedHostname(rawParsed: unknown, validated: OcxConfig): void {
|
|
1853
|
+
if (!rawParsed || typeof rawParsed !== "object") return;
|
|
1854
|
+
const raw = (rawParsed as Record<string, unknown>).hostname;
|
|
1855
|
+
if (raw !== undefined && validated.hostname === undefined) {
|
|
1856
|
+
console.warn(`⚠️ config.json hostname ${JSON.stringify(raw)} is not a usable bind address — falling back to 127.0.0.1`);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
/**
|
|
1861
|
+
* Companion to {@link warnDegradedStreamMode} for a malformed selection-order map.
|
|
1862
|
+
* Priority is a preference, so the schema drops the whole map rather than failing
|
|
1863
|
+
* the parse — say so once, otherwise the pool silently reverts to flat ordering.
|
|
1864
|
+
*/
|
|
1865
|
+
function degradedCodexAccountPriorityWarnings(rawParsed: unknown, validated: OcxConfig): string[] {
|
|
1866
|
+
const record = rawConfigRecord(rawParsed);
|
|
1867
|
+
const warnings: string[] = [];
|
|
1868
|
+
// The pin degrades silently otherwise, which reads as the manual selection simply
|
|
1869
|
+
// not having survived the restart.
|
|
1870
|
+
if (record?.activeCodexAccountPinned !== undefined && validated.activeCodexAccountPinned === undefined) {
|
|
1871
|
+
warnings.push("activeCodexAccountPinned is not a valid account id — the manually selected account is no longer pinned");
|
|
1872
|
+
}
|
|
1873
|
+
const raw = record?.codexAccountPriorities;
|
|
1874
|
+
if (raw !== undefined && validated.codexAccountPriorities === undefined) {
|
|
1875
|
+
warnings.push("codexAccountPriorities is invalid (expected account ids mapped to integers between -100 and 100) — account selection order is disabled");
|
|
1876
|
+
}
|
|
1877
|
+
return warnings;
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
function warnDegradedCodexAccountPriorities(rawParsed: unknown, validated: OcxConfig): void {
|
|
1881
|
+
for (const warning of degradedCodexAccountPriorityWarnings(rawParsed, validated)) {
|
|
1882
|
+
console.warn(`⚠️ config.json ${warning}`);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
/**
|
|
1887
|
+
* The apiKeys schema salvages entry by entry rather than failing the parse, so a
|
|
1888
|
+
* dropped key is otherwise invisible — and it will not be re-saved by the next
|
|
1889
|
+
* mutation. Say so out loud. Compares the raw array against the validated one,
|
|
1890
|
+
* the same shape as the degrade warnings above.
|
|
1891
|
+
*/
|
|
1892
|
+
/** One definition of "usable secret", shared by the schema and the warnings. */
|
|
1893
|
+
function isUsableApiKeySecret(value: unknown): value is string {
|
|
1894
|
+
return typeof value === "string" && value.length > 0 && value === value.trim();
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
/**
|
|
1898
|
+
* Give every salvaged key a stable, targetable id.
|
|
1899
|
+
*
|
|
1900
|
+
* Pure and deterministic on purpose. Two earlier spellings were wrong: minting a
|
|
1901
|
+
* UUID inside the schema transform handed out a different id on every parse, and
|
|
1902
|
+
* repairing-then-writing during `loadConfig` put a file write on the read path,
|
|
1903
|
+
* where it could clobber a concurrent legitimate save with a stale snapshot.
|
|
1904
|
+
*
|
|
1905
|
+
* So the replacement id is derived from the entry's position, which is already
|
|
1906
|
+
* how the file orders these rows: same file in, same ids out, no I/O and no
|
|
1907
|
+
* randomness. It is not derived from the secret — a public identifier should
|
|
1908
|
+
* never be a function of key material.
|
|
1909
|
+
*/
|
|
1910
|
+
function normalizeApiKeyIds(config: OcxConfig): OcxConfig {
|
|
1911
|
+
const keys = config.apiKeys;
|
|
1912
|
+
if (!keys?.length) return config;
|
|
1913
|
+
// Reserve every explicit id BEFORE synthesizing any, or a synthetic
|
|
1914
|
+
// `salvaged-1` assigned to row 1 would push a row that legitimately owns that
|
|
1915
|
+
// id onto `salvaged-2`. An id the user already has is the one thing this
|
|
1916
|
+
// repair must never take away.
|
|
1917
|
+
const reserved = new Set<string>();
|
|
1918
|
+
for (const entry of keys) {
|
|
1919
|
+
if (entry.id) reserved.add(entry.id);
|
|
1920
|
+
}
|
|
1921
|
+
const taken = new Set<string>(reserved);
|
|
1922
|
+
const kept = new Set<string>();
|
|
1923
|
+
keys.forEach((entry, index) => {
|
|
1924
|
+
// The first row holding an explicit id keeps it; later collisions are the
|
|
1925
|
+
// ones that move.
|
|
1926
|
+
if (entry.id && !kept.has(entry.id)) {
|
|
1927
|
+
kept.add(entry.id);
|
|
1928
|
+
return;
|
|
1929
|
+
}
|
|
1930
|
+
let candidate = `salvaged-${index + 1}`;
|
|
1931
|
+
let suffix = 1;
|
|
1932
|
+
while (taken.has(candidate)) candidate = `salvaged-${index + 1}-${++suffix}`;
|
|
1933
|
+
entry.id = candidate;
|
|
1934
|
+
taken.add(candidate);
|
|
1935
|
+
kept.add(candidate);
|
|
1936
|
+
});
|
|
1937
|
+
return config;
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
function warnDegradedApiKeys(rawParsed: unknown, validated: OcxConfig): void {
|
|
1941
|
+
if (!rawParsed || typeof rawParsed !== "object") return;
|
|
1942
|
+
const raw = (rawParsed as Record<string, unknown>).apiKeys;
|
|
1943
|
+
if (raw === undefined) return;
|
|
1944
|
+
if (!Array.isArray(raw)) {
|
|
1945
|
+
console.warn(`⚠️ config.json apiKeys is not an array — ignoring it; generate a new key from the API tab`);
|
|
1946
|
+
return;
|
|
1947
|
+
}
|
|
1948
|
+
const dropped = raw.length - (validated.apiKeys?.length ?? 0);
|
|
1949
|
+
if (dropped > 0) {
|
|
1950
|
+
console.warn(`⚠️ config.json apiKeys: skipped ${dropped} malformed entr${dropped === 1 ? "y" : "ies"} — the remaining keys still work`);
|
|
1951
|
+
}
|
|
1952
|
+
// Same-length repairs are invisible to the count above, and they are the ones
|
|
1953
|
+
// that show up as a blank name or an unknown date in the dashboard. Say so.
|
|
1954
|
+
const repaired = raw.filter(row => {
|
|
1955
|
+
if (!row || typeof row !== "object") return false;
|
|
1956
|
+
const entry = row as Record<string, unknown>;
|
|
1957
|
+
// Must match the schema exactly: a row whose key is unusable was DROPPED, and
|
|
1958
|
+
// saying "the key still works" about it would be a lie.
|
|
1959
|
+
if (!isUsableApiKeySecret(entry.key)) return false;
|
|
1960
|
+
return typeof entry.id !== "string" || !entry.id
|
|
1961
|
+
|| typeof entry.name !== "string"
|
|
1962
|
+
|| typeof entry.createdAt !== "string";
|
|
1963
|
+
}).length;
|
|
1964
|
+
if (repaired > 0) {
|
|
1965
|
+
console.warn(`⚠️ config.json apiKeys: repaired metadata on ${repaired} entr${repaired === 1 ? "y" : "ies"} — the key still works, but its name or date may read as unknown`);
|
|
1966
|
+
}
|
|
1967
|
+
// A duplicate id is repaired too, and it is not visible in either count above.
|
|
1968
|
+
const ids = raw.filter(row => row && typeof row === "object" && isUsableApiKeySecret((row as Record<string, unknown>).key))
|
|
1969
|
+
.map(row => (row as Record<string, unknown>).id)
|
|
1970
|
+
.filter((id): id is string => typeof id === "string" && !!id);
|
|
1971
|
+
const duplicates = ids.length - new Set(ids).size;
|
|
1972
|
+
if (duplicates > 0) {
|
|
1973
|
+
console.warn(`⚠️ config.json apiKeys: ${duplicates} entr${duplicates === 1 ? "y" : "ies"} shared an id — reassigned so each key can be renamed and revoked on its own`);
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
const CLAUDE_SUBAGENT_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
1978
|
+
|
|
1979
|
+
function isClaudeSubagentEffort(value: unknown): value is NonNullable<OcxClaudeCodeConfig["subagentEffort"]> {
|
|
1980
|
+
return typeof value === "string" && CLAUDE_SUBAGENT_EFFORTS.includes(value as typeof CLAUDE_SUBAGENT_EFFORTS[number]);
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
function rawClaudeSubagentEffort(rawParsed: unknown): unknown {
|
|
1984
|
+
const raw = rawConfigRecord(rawParsed);
|
|
1985
|
+
const claudeCode = raw?.claudeCode;
|
|
1986
|
+
if (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode)) return undefined;
|
|
1987
|
+
return (claudeCode as Record<string, unknown>).subagentEffort;
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
function normalizePersistedClaudeCode(claudeCode: unknown): OcxConfig["claudeCode"] {
|
|
1991
|
+
if (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode)) {
|
|
1992
|
+
return claudeCode as OcxConfig["claudeCode"];
|
|
1993
|
+
}
|
|
1994
|
+
const normalized = { ...claudeCode } as Record<string, unknown>;
|
|
1995
|
+
if (Object.hasOwn(normalized, "subagentEffort") && !isClaudeSubagentEffort(normalized.subagentEffort)) {
|
|
1996
|
+
delete normalized.subagentEffort;
|
|
1997
|
+
}
|
|
1998
|
+
// A hand-authored config never passes through the management validator, so coerce here too.
|
|
1999
|
+
// A malformed classifierFallbacks (a bare string, or an array with non-string entries) would
|
|
2000
|
+
// otherwise reach the resolver unchecked.
|
|
2001
|
+
if (Object.hasOwn(normalized, "classifierModel")) {
|
|
2002
|
+
const value = typeof normalized.classifierModel === "string" ? normalized.classifierModel.trim() : "";
|
|
2003
|
+
if (value.length > 0) normalized.classifierModel = value;
|
|
2004
|
+
else delete normalized.classifierModel;
|
|
2005
|
+
}
|
|
2006
|
+
if (Object.hasOwn(normalized, "classifierFallbacks")) {
|
|
2007
|
+
const raw = normalized.classifierFallbacks;
|
|
2008
|
+
const kept = Array.isArray(raw)
|
|
2009
|
+
? raw.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0).map(entry => entry.trim())
|
|
2010
|
+
: [];
|
|
2011
|
+
if (kept.length > 0) normalized.classifierFallbacks = kept;
|
|
2012
|
+
else delete normalized.classifierFallbacks;
|
|
2013
|
+
}
|
|
2014
|
+
return normalized as OcxConfig["claudeCode"];
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
function normalizeClaudeSubagentEffort(config: OcxConfig, _rawParsed: unknown): OcxConfig {
|
|
2018
|
+
// Unconditional. This used to short-circuit when `subagentEffort` was absent or already valid,
|
|
2019
|
+
// which meant a config whose ONLY defect was elsewhere in `claudeCode` was never normalized.
|
|
2020
|
+
// The specialized subagentEffort WARNING is a separate concern and stays exactly as it is.
|
|
2021
|
+
if (!config.claudeCode) return config;
|
|
2022
|
+
return { ...config, claudeCode: normalizePersistedClaudeCode(config.claudeCode) };
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
function warnDegradedClaudeSubagentEffort(rawParsed: unknown): void {
|
|
2026
|
+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
|
|
2027
|
+
if (rawEffort !== undefined && !isClaudeSubagentEffort(rawEffort)) {
|
|
2028
|
+
console.warn(`⚠️ config.json claudeCode.subagentEffort is invalid (expected ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}) — ignoring it. Other settings were preserved.`);
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
function normalizeSubagentRoles(config: OcxConfig, rawParsed: unknown): OcxConfig {
|
|
2033
|
+
const raw = rawConfigRecord(rawParsed);
|
|
2034
|
+
if (!raw || !Object.hasOwn(raw, "subagentRoles")) return config;
|
|
2035
|
+
const salvaged = salvageSubagentRoles(raw.subagentRoles);
|
|
2036
|
+
const normalized = { ...config };
|
|
2037
|
+
if (salvaged.roles === undefined) delete normalized.subagentRoles;
|
|
2038
|
+
else normalized.subagentRoles = salvaged.roles;
|
|
2039
|
+
return normalized;
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
function subagentRolesLoadWarnings(rawParsed: unknown): string[] {
|
|
2043
|
+
const raw = rawConfigRecord(rawParsed);
|
|
2044
|
+
if (!raw || !Object.hasOwn(raw, "subagentRoles")) return [];
|
|
2045
|
+
return salvageSubagentRoles(raw.subagentRoles).warnings;
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
function malformedSyncCodexAgentRolesWarning(rawParsed: unknown): string | null {
|
|
2049
|
+
const raw = rawConfigRecord(rawParsed);
|
|
2050
|
+
if (!raw || !Object.hasOwn(raw, "syncCodexAgentRoles")) return null;
|
|
2051
|
+
if (typeof raw.syncCodexAgentRoles === "boolean") return null;
|
|
2052
|
+
return "syncCodexAgentRoles ignored: expected a boolean; treating as false";
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
function normalizeSyncCodexAgentRoles(config: OcxConfig, rawParsed: unknown): OcxConfig {
|
|
2056
|
+
if (!malformedSyncCodexAgentRolesWarning(rawParsed)) return config;
|
|
2057
|
+
return { ...config, syncCodexAgentRoles: false };
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
function warnDegradedSyncCodexAgentRoles(rawParsed: unknown): void {
|
|
2061
|
+
const warning = malformedSyncCodexAgentRolesWarning(rawParsed);
|
|
2062
|
+
if (warning) console.warn(`⚠️ config.json ${warning}. Other settings were preserved.`);
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
function warnDegradedSubagentRoles(rawParsed: unknown): void {
|
|
2066
|
+
for (const warning of subagentRolesLoadWarnings(rawParsed)) {
|
|
2067
|
+
console.warn(`⚠️ config.json ${warning}. Other settings were preserved.`);
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
function subagentRolesError(value: unknown): string | null {
|
|
2072
|
+
const raw = rawConfigRecord(value);
|
|
2073
|
+
if (!raw || !Object.hasOwn(raw, "subagentRoles")) return null;
|
|
2074
|
+
const parsed = parseSubagentRoles(raw.subagentRoles);
|
|
2075
|
+
if (parsed.ok) return null;
|
|
2076
|
+
return `schema_invalid: ${parsed.error}`;
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
function malformedUpstreamHostCircuitThresholdWarning(rawParsed: unknown): string | null {
|
|
2080
|
+
const raw = rawConfigRecord(rawParsed);
|
|
2081
|
+
if (!raw || !Object.hasOwn(raw, "upstreamHostCircuitThreshold")) return null;
|
|
2082
|
+
const threshold = raw.upstreamHostCircuitThreshold;
|
|
2083
|
+
if (threshold === undefined) return null;
|
|
2084
|
+
if (typeof threshold === "number"
|
|
2085
|
+
&& Number.isInteger(threshold)
|
|
2086
|
+
&& threshold >= 0
|
|
2087
|
+
&& threshold <= UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD) return null;
|
|
2088
|
+
return `upstreamHostCircuitThreshold ignored: expected an integer from 0 to ${UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD}`;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
function warnDegradedUpstreamHostCircuitThreshold(rawParsed: unknown): void {
|
|
2092
|
+
const warning = malformedUpstreamHostCircuitThresholdWarning(rawParsed);
|
|
2093
|
+
if (warning) console.warn(`⚠️ config.json ${warning}. Other settings were preserved.`);
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
function malformedAgentTaskRecoveryWarning(rawParsed: unknown): string | null {
|
|
2097
|
+
const raw = rawConfigRecord(rawParsed);
|
|
2098
|
+
if (!raw || !Object.hasOwn(raw, "agentTaskRecovery")) return null;
|
|
2099
|
+
const result = agentTaskRecoverySchema.safeParse(raw.agentTaskRecovery);
|
|
2100
|
+
if (result.success) return null;
|
|
2101
|
+
const field = result.error.issues[0]?.path.join(".");
|
|
2102
|
+
return `agentTaskRecovery${field ? `.${field}` : ""} ignored: invalid experimental recovery configuration`;
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
function warnDegradedAgentTaskRecovery(rawParsed: unknown): void {
|
|
2106
|
+
const warning = malformedAgentTaskRecoveryWarning(rawParsed);
|
|
2107
|
+
if (warning) console.warn(`⚠️ config.json ${warning}. Other settings were preserved.`);
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
type NativeSubagentPersistedField = "injectionModel" | "injectionEffort" | "syncCodexSubagentDefaults";
|
|
2111
|
+
|
|
2112
|
+
function rawConfigRecord(rawParsed: unknown): Record<string, unknown> | null {
|
|
2113
|
+
return rawParsed !== null && typeof rawParsed === "object" && !Array.isArray(rawParsed)
|
|
2114
|
+
? rawParsed as Record<string, unknown>
|
|
2115
|
+
: null;
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
function malformedNativeSubagentFields(rawParsed: unknown): NativeSubagentPersistedField[] {
|
|
2119
|
+
const raw = rawConfigRecord(rawParsed);
|
|
2120
|
+
if (!raw) return [];
|
|
2121
|
+
const malformed: NativeSubagentPersistedField[] = [];
|
|
2122
|
+
if (Object.hasOwn(raw, "injectionModel") && typeof raw.injectionModel !== "string") {
|
|
2123
|
+
malformed.push("injectionModel");
|
|
2124
|
+
}
|
|
2125
|
+
if (Object.hasOwn(raw, "injectionEffort") && typeof raw.injectionEffort !== "string") {
|
|
2126
|
+
malformed.push("injectionEffort");
|
|
2127
|
+
}
|
|
2128
|
+
if (Object.hasOwn(raw, "syncCodexSubagentDefaults") && typeof raw.syncCodexSubagentDefaults !== "boolean") {
|
|
2129
|
+
malformed.push("syncCodexSubagentDefaults");
|
|
2130
|
+
}
|
|
2131
|
+
return malformed;
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
function malformedNativeSubagentFieldWarning(field: NativeSubagentPersistedField): string {
|
|
2135
|
+
const expected = field === "syncCodexSubagentDefaults" ? "a boolean" : "a string";
|
|
2136
|
+
return `${field} ignored: expected ${expected}`;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
function malformedCodexAccountPickerWarning(rawParsed: unknown): string | null {
|
|
2140
|
+
const raw = rawConfigRecord(rawParsed);
|
|
2141
|
+
if (!raw || !Object.hasOwn(raw, "codexAccountPickerEnabled")) return null;
|
|
2142
|
+
if (typeof raw.codexAccountPickerEnabled === "boolean") return null;
|
|
2143
|
+
return "codexAccountPickerEnabled ignored: expected a boolean";
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
function warnDegradedCodexAccountPicker(rawParsed: unknown): void {
|
|
2147
|
+
const warning = malformedCodexAccountPickerWarning(rawParsed);
|
|
2148
|
+
if (warning) console.warn(`⚠️ config.json ${warning}. Other settings were preserved.`);
|
|
2149
|
+
}
|
|
2150
|
+
|
|
2151
|
+
function nativeSubagentSyncDisabledReason(config: OcxConfig, rawParsed?: unknown): string | null {
|
|
2152
|
+
if (config.syncCodexSubagentDefaults !== true) return null;
|
|
2153
|
+
const malformed = malformedNativeSubagentFields(rawParsed);
|
|
2154
|
+
if (malformed.includes("injectionModel")) return "injectionModel must be a string";
|
|
2155
|
+
if (!config.injectionModel?.trim()) return "a nonblank injectionModel is required";
|
|
2156
|
+
if (malformed.includes("injectionEffort")) return "injectionEffort must be a string or omitted";
|
|
2157
|
+
if (config.injectionEffort !== undefined && !isCodexReasoningEffort(config.injectionEffort)) {
|
|
2158
|
+
return "injectionEffort must be a supported Codex reasoning effort";
|
|
2159
|
+
}
|
|
2160
|
+
return null;
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
function normalizeNativeSubagentSync(config: OcxConfig, rawParsed?: unknown): OcxConfig {
|
|
2164
|
+
if (!nativeSubagentSyncDisabledReason(config, rawParsed)) return config;
|
|
2165
|
+
const normalized = { ...config };
|
|
2166
|
+
delete normalized.syncCodexSubagentDefaults;
|
|
2167
|
+
return normalized;
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
function warnDegradedNativeSubagentConfig(rawParsed: unknown, config: OcxConfig): void {
|
|
2171
|
+
for (const field of malformedNativeSubagentFields(rawParsed)) {
|
|
2172
|
+
console.warn(`⚠️ config.json ${malformedNativeSubagentFieldWarning(field)}. Other settings were preserved.`);
|
|
2173
|
+
}
|
|
2174
|
+
const reason = nativeSubagentSyncDisabledReason(config, rawParsed);
|
|
2175
|
+
if (reason) {
|
|
2176
|
+
console.warn(`⚠️ config.json syncCodexSubagentDefaults was disabled: ${reason}. Other settings were preserved.`);
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
/**
|
|
2181
|
+
* Registry metadata can gain service-tier capability after a config was written. An explicit
|
|
2182
|
+
* `fastWire: null` remains authoritative on load and on whole-document writes; rejecting either
|
|
2183
|
+
* would discard or lock access to unrelated providers and API keys. Direct contradictions within
|
|
2184
|
+
* one provider row remain schema errors through the outer config refinement, where the dynamic
|
|
2185
|
+
* provider name can be redacted before it reaches diagnostics.
|
|
2186
|
+
*/
|
|
2187
|
+
function inheritedFastWireConflictProviderNames(
|
|
2188
|
+
config: Pick<OcxConfig, "providers">,
|
|
2189
|
+
): string[] {
|
|
2190
|
+
const conflicts: string[] = [];
|
|
2191
|
+
for (const [name, provider] of Object.entries(config.providers)) {
|
|
2192
|
+
if (provider.fastWire !== null || provider.supportsServiceTier === false) continue;
|
|
2193
|
+
const registry = providerMatchesRegistryTransport(name, provider)
|
|
2194
|
+
? getProviderRegistryEntry(name)
|
|
2195
|
+
: undefined;
|
|
2196
|
+
if (!registry) continue;
|
|
2197
|
+
const effectiveProviderCapability = provider.supportsServiceTier ?? registry.supportsServiceTier;
|
|
2198
|
+
const effectiveModelCapabilities = {
|
|
2199
|
+
...(registryModelServiceTierCapabilityApplies(registry, provider)
|
|
2200
|
+
? registry.modelSupportsServiceTier ?? {}
|
|
2201
|
+
: {}),
|
|
2202
|
+
...(provider.modelSupportsServiceTier ?? {}),
|
|
2203
|
+
};
|
|
2204
|
+
if (
|
|
2205
|
+
effectiveProviderCapability === true
|
|
2206
|
+
|| Object.values(effectiveModelCapabilities).some(value => value === true)
|
|
2207
|
+
) {
|
|
2208
|
+
conflicts.push(name);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
return conflicts;
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
function inheritedFastWireConflictWarning(name: string): string {
|
|
2215
|
+
return `providers.${redactSecretString(name)}.fastWire=null overrides service-tier capability inherited from the matching registry entry`;
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
function warnInheritedFastWireConflicts(configPath: string, config: OcxConfig): void {
|
|
2219
|
+
const names = inheritedFastWireConflictProviderNames(config);
|
|
2220
|
+
if (names.length === 0 || warnedInheritedFastWireConflicts.has(configPath)) return;
|
|
2221
|
+
warnedInheritedFastWireConflicts.add(configPath);
|
|
2222
|
+
console.warn(
|
|
2223
|
+
`⚠️ config.json ${names.map(inheritedFastWireConflictWarning).join("; ")}. `
|
|
2224
|
+
+ "The persisted providers and API keys were preserved.",
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
|
|
2228
|
+
/**
|
|
2229
|
+
* Load and validate config.json into an OcxConfig. Missing files reset to
|
|
2230
|
+
* defaults and clear stale overlays. Broken existing files also fall back to
|
|
2231
|
+
* default routing (after backup), but keep the last-good cost-overlay registry
|
|
2232
|
+
* until a valid config or a genuinely missing file is observed. A partially-
|
|
2233
|
+
* invalid config is merged with defaults so providers and pool accounts survive.
|
|
2234
|
+
*/
|
|
2235
|
+
export function loadConfig(): OcxConfig {
|
|
2236
|
+
const dir = getConfigDir();
|
|
2237
|
+
const configPath = getConfigPath();
|
|
2238
|
+
hardenConfigDir();
|
|
2239
|
+
hardenExistingSecret(configPath);
|
|
2240
|
+
hardenExistingSecret(join(dir, "auth.json"));
|
|
2241
|
+
if (!existsSync(configPath)) {
|
|
2242
|
+
return withRefreshedCostOverlays(getDefaultConfig());
|
|
2243
|
+
}
|
|
2244
|
+
try {
|
|
2245
|
+
const raw = readFileSync(configPath, "utf-8").replace(/^\uFEFF/, "");
|
|
2246
|
+
const parsed = JSON.parse(raw);
|
|
2247
|
+
sanitizeRetryOn429ForLoad(parsed);
|
|
2248
|
+
sanitizeModelCostsForLoad(parsed);
|
|
2249
|
+
const result = configSchema.safeParse(parsed);
|
|
2250
|
+
if (result.success) {
|
|
2251
|
+
const config = normalizeApiKeyIds(result.data as OcxConfig);
|
|
2252
|
+
warnInheritedFastWireConflicts(configPath, config);
|
|
2253
|
+
warnDegradedStreamMode(parsed, config);
|
|
2254
|
+
warnDegradedHostname(parsed, config);
|
|
2255
|
+
warnDegradedApiKeys(parsed, config);
|
|
2256
|
+
warnDegradedCodexAccountPriorities(parsed, config);
|
|
2257
|
+
warnDegradedClaudeSubagentEffort(parsed);
|
|
2258
|
+
warnDegradedSubagentRoles(parsed);
|
|
2259
|
+
warnDegradedSyncCodexAgentRoles(parsed);
|
|
2260
|
+
warnDegradedNativeSubagentConfig(parsed, config);
|
|
2261
|
+
warnDegradedCodexAccountPicker(parsed);
|
|
2262
|
+
warnDegradedUpstreamHostCircuitThreshold(parsed);
|
|
2263
|
+
warnDegradedAgentTaskRecovery(parsed);
|
|
2264
|
+
return withRefreshedCostOverlays(normalizeSyncCodexAgentRoles(normalizeSubagentRoles(normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, parsed), parsed), parsed), parsed));
|
|
2265
|
+
}
|
|
2266
|
+
// Schema validation failed — merge defaults into the raw object instead of
|
|
2267
|
+
// discarding it entirely, so pool accounts and providers survive a missing
|
|
2268
|
+
// field like defaultProvider.
|
|
2269
|
+
const defaults = getDefaultConfig();
|
|
2270
|
+
const merged = { ...defaults, ...parsed };
|
|
2271
|
+
// Ensure providers from both sides survive
|
|
2272
|
+
if (parsed.providers && defaults.providers) {
|
|
2273
|
+
merged.providers = { ...defaults.providers, ...parsed.providers };
|
|
2274
|
+
}
|
|
2275
|
+
const retryResult = configSchema.safeParse(merged);
|
|
2276
|
+
if (retryResult.success) {
|
|
2277
|
+
warnConfigRepaired(configPath, result.error);
|
|
2278
|
+
const config = normalizeApiKeyIds(retryResult.data as OcxConfig);
|
|
2279
|
+
warnInheritedFastWireConflicts(configPath, config);
|
|
2280
|
+
warnDegradedHostname(parsed, config);
|
|
2281
|
+
warnDegradedApiKeys(parsed, config);
|
|
2282
|
+
warnDegradedCodexAccountPriorities(parsed, config);
|
|
2283
|
+
warnDegradedClaudeSubagentEffort(parsed);
|
|
2284
|
+
warnDegradedSubagentRoles(parsed);
|
|
2285
|
+
warnDegradedSyncCodexAgentRoles(parsed);
|
|
2286
|
+
warnDegradedNativeSubagentConfig(parsed, config);
|
|
2287
|
+
warnDegradedCodexAccountPicker(parsed);
|
|
2288
|
+
warnDegradedUpstreamHostCircuitThreshold(parsed);
|
|
2289
|
+
warnDegradedAgentTaskRecovery(parsed);
|
|
2290
|
+
return withRefreshedCostOverlays(normalizeSyncCodexAgentRoles(normalizeSubagentRoles(normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, parsed), parsed), parsed), parsed));
|
|
2291
|
+
}
|
|
2292
|
+
// Still failing, but if every complaint is about one or more named entries
|
|
2293
|
+
// in an independent section, drop exactly those and keep the rest. Falling
|
|
2294
|
+
// back to defaults here would silently retire the operator's providers,
|
|
2295
|
+
// keys and prices over a mistake in one routing profile.
|
|
2296
|
+
const salvaged = salvageConfigCandidate(merged, retryResult.error);
|
|
2297
|
+
if (salvaged) {
|
|
2298
|
+
{
|
|
2299
|
+
warnDroppedConfigSections(configPath, salvaged.dropped, salvaged.issues);
|
|
2300
|
+
const config = normalizeApiKeyIds(salvaged.parsed);
|
|
2301
|
+
warnInheritedFastWireConflicts(configPath, config);
|
|
2302
|
+
warnDegradedHostname(parsed, config);
|
|
2303
|
+
warnDegradedApiKeys(parsed, config);
|
|
2304
|
+
warnDegradedCodexAccountPriorities(parsed, config);
|
|
2305
|
+
warnDegradedClaudeSubagentEffort(parsed);
|
|
2306
|
+
warnDegradedSubagentRoles(parsed);
|
|
2307
|
+
warnDegradedSyncCodexAgentRoles(parsed);
|
|
2308
|
+
warnDegradedNativeSubagentConfig(parsed, config);
|
|
2309
|
+
warnDegradedCodexAccountPicker(parsed);
|
|
2310
|
+
warnDegradedUpstreamHostCircuitThreshold(parsed);
|
|
2311
|
+
warnDegradedAgentTaskRecovery(parsed);
|
|
2312
|
+
return withRefreshedCostOverlays(normalizeSyncCodexAgentRoles(normalizeSubagentRoles(normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, parsed), parsed), parsed), parsed));
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
// Merge couldn't fix it — truly broken config
|
|
2316
|
+
warnAndBackupInvalidConfig(configPath, result.error);
|
|
2317
|
+
return getDefaultConfig();
|
|
2318
|
+
} catch (error) {
|
|
2319
|
+
warnAndBackupInvalidConfig(configPath, error);
|
|
2320
|
+
return getDefaultConfig();
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
/** Refresh the user cost-overlay registry from `config` and return it unchanged. */
|
|
2325
|
+
function withRefreshedCostOverlays(config: OcxConfig): OcxConfig {
|
|
2326
|
+
refreshUserCostOverlays(config);
|
|
2327
|
+
return config;
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
export type ConfigDiagnostics = {
|
|
2331
|
+
config: OcxConfig;
|
|
2332
|
+
source: "default" | "file" | "fallback";
|
|
2333
|
+
error: string | null;
|
|
2334
|
+
/** Non-fatal config concerns; absent when there are no warnings. */
|
|
2335
|
+
warnings?: string[];
|
|
2336
|
+
};
|
|
2337
|
+
|
|
2338
|
+
type ConfigFileSnapshot = {
|
|
2339
|
+
diagnostics: ConfigDiagnostics;
|
|
2340
|
+
/** Exact file contents, including a possible BOM, used as the optimistic revision. */
|
|
2341
|
+
raw?: string;
|
|
2342
|
+
};
|
|
2343
|
+
|
|
2344
|
+
function configPlaceholderWarnings(config: OcxConfig): string[] {
|
|
2345
|
+
const warnings: string[] = [];
|
|
2346
|
+
for (const [name, provider] of Object.entries(config.providers)) {
|
|
2347
|
+
const placeholder = provider.baseUrl.match(/\{[^}]*\}/)?.[0];
|
|
2348
|
+
if (placeholder) {
|
|
2349
|
+
warnings.push(`providers.${name}.baseUrl contains unresolved ${placeholder}; set the real provider URL`);
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
return warnings;
|
|
2353
|
+
}
|
|
2354
|
+
|
|
2355
|
+
function validFileConfigDiagnostics(config: OcxConfig, rawParsed: unknown): ConfigDiagnostics {
|
|
2356
|
+
// Unsafe hand-edited optional values are disabled in memory instead of rejecting
|
|
2357
|
+
// the entire config, which would hide unrelated providers/accounts. The next
|
|
2358
|
+
// ordinary save persists the normalized absence.
|
|
2359
|
+
const syncDisabledReason = nativeSubagentSyncDisabledReason(config, rawParsed);
|
|
2360
|
+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
|
|
2361
|
+
const normalized = normalizeSyncCodexAgentRoles(normalizeSubagentRoles(normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, rawParsed), rawParsed), rawParsed), rawParsed);
|
|
2362
|
+
const warnings = configPlaceholderWarnings(normalized);
|
|
2363
|
+
warnings.push(...inheritedFastWireConflictProviderNames(normalized).map(inheritedFastWireConflictWarning));
|
|
2364
|
+
warnings.push(...degradedCodexAccountPriorityWarnings(rawParsed, normalized));
|
|
2365
|
+
if (rawEffort !== undefined && !isClaudeSubagentEffort(rawEffort)) {
|
|
2366
|
+
warnings.push(`claudeCode.subagentEffort ignored: expected one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`);
|
|
2367
|
+
}
|
|
2368
|
+
warnings.push(...subagentRolesLoadWarnings(rawParsed));
|
|
2369
|
+
const agentRoleSyncWarning = malformedSyncCodexAgentRolesWarning(rawParsed);
|
|
2370
|
+
if (agentRoleSyncWarning) warnings.push(agentRoleSyncWarning);
|
|
2371
|
+
warnings.push(...malformedNativeSubagentFields(rawParsed).map(malformedNativeSubagentFieldWarning));
|
|
2372
|
+
const pickerWarning = malformedCodexAccountPickerWarning(rawParsed);
|
|
2373
|
+
if (pickerWarning) warnings.push(pickerWarning);
|
|
2374
|
+
const hostCircuitWarning = malformedUpstreamHostCircuitThresholdWarning(rawParsed);
|
|
2375
|
+
if (hostCircuitWarning) warnings.push(hostCircuitWarning);
|
|
2376
|
+
const recoveryWarning = malformedAgentTaskRecoveryWarning(rawParsed);
|
|
2377
|
+
if (recoveryWarning) warnings.push(recoveryWarning);
|
|
2378
|
+
if (syncDisabledReason) {
|
|
2379
|
+
warnings.push(`syncCodexSubagentDefaults ignored: ${syncDisabledReason}`);
|
|
2380
|
+
}
|
|
2381
|
+
return {
|
|
2382
|
+
config: normalized,
|
|
2383
|
+
source: "file",
|
|
2384
|
+
error: null,
|
|
2385
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
export function subagentDefaultSyncEffective(
|
|
2390
|
+
config: Pick<OcxConfig, "syncCodexSubagentDefaults" | "injectionModel">,
|
|
2391
|
+
): boolean {
|
|
2392
|
+
return config.syncCodexSubagentDefaults === true && Boolean(config.injectionModel?.trim());
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
function mergeConfigDefaults(parsed: unknown): unknown {
|
|
2396
|
+
if (!parsed || typeof parsed !== "object") return parsed;
|
|
2397
|
+
const defaults = getDefaultConfig();
|
|
2398
|
+
const raw = parsed as Record<string, unknown>;
|
|
2399
|
+
const merged: Record<string, unknown> = { ...defaults, ...raw };
|
|
2400
|
+
if (raw.providers && typeof raw.providers === "object" && defaults.providers) {
|
|
2401
|
+
merged.providers = { ...defaults.providers, ...(raw.providers as Record<string, unknown>) };
|
|
2402
|
+
}
|
|
2403
|
+
return merged;
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
function schemaDiagnosticsError(error: z.ZodError): string {
|
|
2407
|
+
const details = error.issues.map(issue => {
|
|
2408
|
+
const path = issue.path.join(".") || "config";
|
|
2409
|
+
return `${path}: ${issue.message}`;
|
|
2410
|
+
});
|
|
2411
|
+
return details.length > 0 ? `schema_invalid: ${details.join("; ")}` : "schema_invalid";
|
|
2412
|
+
}
|
|
2413
|
+
|
|
2414
|
+
/**
|
|
2415
|
+
* Reject a hostname the schema deliberately degrades on read. Load-time has to keep a
|
|
2416
|
+
* blank value non-fatal (see the `hostname` field comment), but an incoming write is a
|
|
2417
|
+
* live caller who can be told the value is wrong — silently rewriting it to loopback
|
|
2418
|
+
* would look like the bind succeeded on the address they asked for.
|
|
2419
|
+
*/
|
|
2420
|
+
function blankHostnameError(value: unknown): string | null {
|
|
2421
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
2422
|
+
const hostname = (value as Record<string, unknown>).hostname;
|
|
2423
|
+
if (hostname === undefined) return null;
|
|
2424
|
+
if (typeof hostname !== "string" || !hostname.trim()) {
|
|
2425
|
+
return "schema_invalid: hostname: must be a nonblank bind address";
|
|
2426
|
+
}
|
|
2427
|
+
return null;
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
function claudeSubagentEffortError(value: unknown): string | null {
|
|
2431
|
+
const effort = rawClaudeSubagentEffort(value);
|
|
2432
|
+
if (effort === undefined || isClaudeSubagentEffort(effort)) return null;
|
|
2433
|
+
return `schema_invalid: claudeCode.subagentEffort: must be one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`;
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
function appOwnedMemoryBudgetError(value: unknown): string | null {
|
|
2437
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
2438
|
+
const budget = (value as Record<string, unknown>).appOwnedMemoryBudgetMb;
|
|
2439
|
+
if (budget === undefined) return null;
|
|
2440
|
+
if (typeof budget !== "number" || !Number.isInteger(budget)
|
|
2441
|
+
|| budget < MIN_APP_OWNED_MEMORY_BUDGET_MB || budget > MAX_APP_OWNED_MEMORY_BUDGET_MB) {
|
|
2442
|
+
return `schema_invalid: appOwnedMemoryBudgetMb: must be an integer from ${MIN_APP_OWNED_MEMORY_BUDGET_MB} to ${MAX_APP_OWNED_MEMORY_BUDGET_MB}`;
|
|
2443
|
+
}
|
|
2444
|
+
return null;
|
|
2445
|
+
}
|
|
2446
|
+
|
|
2447
|
+
function upstreamHostCircuitThresholdError(value: unknown): string | null {
|
|
2448
|
+
const raw = rawConfigRecord(value);
|
|
2449
|
+
if (!raw || !Object.hasOwn(raw, "upstreamHostCircuitThreshold")) return null;
|
|
2450
|
+
const threshold = raw.upstreamHostCircuitThreshold;
|
|
2451
|
+
if (threshold === undefined) return null;
|
|
2452
|
+
if (typeof threshold === "number"
|
|
2453
|
+
&& Number.isInteger(threshold)
|
|
2454
|
+
&& threshold >= 0
|
|
2455
|
+
&& threshold <= UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD) return null;
|
|
2456
|
+
return `schema_invalid: upstreamHostCircuitThreshold: must be an integer from 0 to ${UPSTREAM_HOST_CIRCUIT_MAX_THRESHOLD}`;
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
function agentTaskRecoveryError(value: unknown): string | null {
|
|
2460
|
+
const raw = rawConfigRecord(value);
|
|
2461
|
+
if (!raw || !Object.hasOwn(raw, "agentTaskRecovery") || raw.agentTaskRecovery === undefined) return null;
|
|
2462
|
+
const result = agentTaskRecoverySchema.safeParse(raw.agentTaskRecovery);
|
|
2463
|
+
if (result.success) return null;
|
|
2464
|
+
const issue = result.error.issues[0];
|
|
2465
|
+
const field = issue?.path.join(".");
|
|
2466
|
+
return `schema_invalid: agentTaskRecovery${field ? `.${field}` : ""}: ${issue?.message ?? "invalid configuration"}`;
|
|
2467
|
+
}
|
|
2468
|
+
|
|
2469
|
+
/**
|
|
2470
|
+
* Same reasoning as {@link blankHostnameError}, and more urgent: the read path degrades a
|
|
2471
|
+
* malformed selection-order map to undefined, which on a write would drop every entry the
|
|
2472
|
+
* user had accumulated and still report success. A load-time degrade leaves the raw map in
|
|
2473
|
+
* the file to be repaired by hand; a degraded write erases it. One bad `ocx config set`
|
|
2474
|
+
* must not cost the whole map, so a live caller is told instead.
|
|
2475
|
+
*/
|
|
2476
|
+
function codexAccountPrioritiesError(value: unknown): string | null {
|
|
2477
|
+
const raw = rawConfigRecord(value);
|
|
2478
|
+
if (!raw) return null;
|
|
2479
|
+
if (raw.codexAccountPriorities !== undefined) {
|
|
2480
|
+
const parsed = codexAccountPrioritiesSchema.safeParse(raw.codexAccountPriorities);
|
|
2481
|
+
if (!parsed.success) {
|
|
2482
|
+
return schemaDiagnosticsError(parsed.error).replace("schema_invalid: ", "schema_invalid: codexAccountPriorities.");
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
// Tested as a string rather than coerced: `String(123)` matches the id pattern, so a
|
|
2486
|
+
// coercing guard waves a non-string pin through to the schema, where `.catch(undefined)`
|
|
2487
|
+
// drops it and reports the write as a success — the exact silent-degrade this guards.
|
|
2488
|
+
const pin = raw.activeCodexAccountPinned;
|
|
2489
|
+
if (pin !== undefined && (typeof pin !== "string" || !CODEX_ACCOUNT_PIN_PATTERN.test(pin))) {
|
|
2490
|
+
return "schema_invalid: activeCodexAccountPinned: must be an account id";
|
|
2491
|
+
}
|
|
2492
|
+
return null;
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
function googleAntigravityStaticCatalogVersionError(value: unknown): string | null {
|
|
2496
|
+
const raw = rawConfigRecord(value);
|
|
2497
|
+
if (!raw || !Object.hasOwn(raw, "googleAntigravityStaticCatalogVersion")) return null;
|
|
2498
|
+
const version = raw.googleAntigravityStaticCatalogVersion;
|
|
2499
|
+
if (version === undefined || version === 1 || version === 2) return null;
|
|
2500
|
+
return "schema_invalid: googleAntigravityStaticCatalogVersion: must be 1, 2, or omitted";
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
function codexAccountPickerEnabledError(value: unknown): string | null {
|
|
2504
|
+
const raw = rawConfigRecord(value);
|
|
2505
|
+
if (!raw) return null;
|
|
2506
|
+
const descriptor = Object.getOwnPropertyDescriptor(raw, "codexAccountPickerEnabled");
|
|
2507
|
+
if (!descriptor) {
|
|
2508
|
+
return "codexAccountPickerEnabled" in raw
|
|
2509
|
+
? "schema_invalid: codexAccountPickerEnabled: must be an own boolean data property or omitted"
|
|
2510
|
+
: null;
|
|
2511
|
+
}
|
|
2512
|
+
if (!("value" in descriptor)) {
|
|
2513
|
+
return "schema_invalid: codexAccountPickerEnabled: must be an own boolean data property or omitted";
|
|
2514
|
+
}
|
|
2515
|
+
const enabled = descriptor.value;
|
|
2516
|
+
if (enabled === undefined || typeof enabled === "boolean") return null;
|
|
2517
|
+
return "schema_invalid: codexAccountPickerEnabled: must be a boolean or omitted";
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
function emptyCompletionRetryError(value: unknown): string | null {
|
|
2521
|
+
const raw = rawConfigRecord(value);
|
|
2522
|
+
if (!raw || !Object.hasOwn(raw, "emptyCompletionRetry")) return null;
|
|
2523
|
+
const enabled = raw.emptyCompletionRetry;
|
|
2524
|
+
if (enabled === undefined || typeof enabled === "boolean") return null;
|
|
2525
|
+
return "schema_invalid: emptyCompletionRetry: must be a boolean or omitted";
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2528
|
+
/** Validate an in-memory config candidate without touching disk. Used by headless CLI import/set. */
|
|
2529
|
+
/**
|
|
2530
|
+
* Reject a loopback-listener port that collides with the proxy port (#1102).
|
|
2531
|
+
*
|
|
2532
|
+
* The schema can only check the shape of each field on its own; the two ports being distinct
|
|
2533
|
+
* is a relationship between them. Letting the pair through would surface as a startup failure
|
|
2534
|
+
* after the public listener already bound, which reads like an unrelated port conflict.
|
|
2535
|
+
*
|
|
2536
|
+
* This is write-time only, matching `blankHostnameError`: a live caller can be told the value
|
|
2537
|
+
* is wrong, whereas a hand-edited config on the read path degrades to undefined rather than
|
|
2538
|
+
* resetting the whole file.
|
|
2539
|
+
*/
|
|
2540
|
+
function loopbackListenerPortError(value: unknown): string | null {
|
|
2541
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
2542
|
+
const listener = (value as Record<string, unknown>).unauthenticatedLoopbackListener;
|
|
2543
|
+
if (listener === undefined) return null;
|
|
2544
|
+
if (!listener || typeof listener !== "object" || Array.isArray(listener)) {
|
|
2545
|
+
return "schema_invalid: unauthenticatedLoopbackListener: must be an object or omitted";
|
|
2546
|
+
}
|
|
2547
|
+
const entry = listener as Record<string, unknown>;
|
|
2548
|
+
// `enabled` must be a real boolean. The schema's `.catch(undefined)` would otherwise DELETE
|
|
2549
|
+
// a `"true"` string entry and report success, leaving an operator convinced they enabled an
|
|
2550
|
+
// unauthenticated listener that is in fact off. Load-time still degrades quietly — a hand
|
|
2551
|
+
// edit must not reset the file — but a live caller gets told.
|
|
2552
|
+
if (typeof entry.enabled !== "boolean") {
|
|
2553
|
+
return "schema_invalid: unauthenticatedLoopbackListener.enabled: must be a boolean";
|
|
2554
|
+
}
|
|
2555
|
+
if (entry.enabled !== true) return null;
|
|
2556
|
+
const listenerPort = entry.port;
|
|
2557
|
+
if (typeof listenerPort !== "number" || !Number.isInteger(listenerPort) || listenerPort < 1 || listenerPort > 65535) {
|
|
2558
|
+
return "schema_invalid: unauthenticatedLoopbackListener.port: must be an integer port when enabled";
|
|
2559
|
+
}
|
|
2560
|
+
const proxyPort = (value as Record<string, unknown>).port;
|
|
2561
|
+
if (typeof proxyPort === "number" && proxyPort === listenerPort) {
|
|
2562
|
+
return "schema_invalid: unauthenticatedLoopbackListener.port: must differ from the proxy port";
|
|
2563
|
+
}
|
|
2564
|
+
return null;
|
|
2565
|
+
}
|
|
2566
|
+
|
|
2567
|
+
export function validateConfigCandidate(value: unknown): { ok: true; config: OcxConfig } | { ok: false; error: string } {
|
|
2568
|
+
const boundaryError = blankHostnameError(value)
|
|
2569
|
+
?? claudeSubagentEffortError(value)
|
|
2570
|
+
?? subagentRolesError(value)
|
|
2571
|
+
?? appOwnedMemoryBudgetError(value)
|
|
2572
|
+
?? upstreamHostCircuitThresholdError(value)
|
|
2573
|
+
?? agentTaskRecoveryError(value)
|
|
2574
|
+
?? googleAntigravityStaticCatalogVersionError(value)
|
|
2575
|
+
?? codexAccountPrioritiesError(value)
|
|
2576
|
+
?? codexAccountPickerEnabledError(value)
|
|
2577
|
+
?? emptyCompletionRetryError(value)
|
|
2578
|
+
?? loopbackListenerPortError(value);
|
|
2579
|
+
if (boundaryError) return { ok: false, error: boundaryError };
|
|
2580
|
+
const result = configSchema.safeParse(value);
|
|
2581
|
+
if (result.success) {
|
|
2582
|
+
const config = normalizeApiKeyIds(result.data as OcxConfig);
|
|
2583
|
+
if (value && typeof value === "object" && !Array.isArray(value) && Object.hasOwn(value, "subagentRoles")) {
|
|
2584
|
+
const parsedRoles = parseSubagentRoles((value as { subagentRoles?: unknown }).subagentRoles);
|
|
2585
|
+
if (!parsedRoles.ok) return { ok: false, error: `schema_invalid: ${parsedRoles.error}` };
|
|
2586
|
+
config.subagentRoles = parsedRoles.roles;
|
|
2587
|
+
}
|
|
2588
|
+
return { ok: true, config };
|
|
2589
|
+
}
|
|
2590
|
+
return { ok: false, error: schemaDiagnosticsError(result.error) };
|
|
2591
|
+
}
|
|
2592
|
+
|
|
2593
|
+
function configDiagnosticsFromRaw(raw: string): ConfigDiagnostics {
|
|
2594
|
+
try {
|
|
2595
|
+
const parsed = JSON.parse(raw.replace(/^\uFEFF/, ""));
|
|
2596
|
+
// Same degradation as loadConfig: a hand-edited invalid retryOn429 must not trip the
|
|
2597
|
+
// schema and send the caller a default-config fallback (the config command could then
|
|
2598
|
+
// persist that fallback over the user's providers/keys).
|
|
2599
|
+
sanitizeRetryOn429ForLoad(parsed);
|
|
2600
|
+
sanitizeModelCostsForLoad(parsed);
|
|
2601
|
+
const result = configSchema.safeParse(parsed);
|
|
2602
|
+
if (result.success) {
|
|
2603
|
+
return validFileConfigDiagnostics(normalizeApiKeyIds(result.data as OcxConfig), parsed);
|
|
2604
|
+
}
|
|
2605
|
+
|
|
2606
|
+
const merged = mergeConfigDefaults(parsed);
|
|
2607
|
+
const retryResult = configSchema.safeParse(merged);
|
|
2608
|
+
if (retryResult.success) {
|
|
2609
|
+
return validFileConfigDiagnostics(normalizeApiKeyIds(retryResult.data as OcxConfig), parsed);
|
|
2610
|
+
}
|
|
2611
|
+
|
|
2612
|
+
// #1785: one invalid routing profile must not make diagnostics report the built-in
|
|
2613
|
+
// defaults AS the config, because a later config write persists those defaults over the
|
|
2614
|
+
// operator's providers, keys and prices.
|
|
2615
|
+
//
|
|
2616
|
+
// The failure is still reported. `source` stays "fallback" and `error` keeps the real
|
|
2617
|
+
// schema message -- diagnostics is the surface that tells callers the file is invalid,
|
|
2618
|
+
// and every consumer that must refuse an invalid config (provider reload, catalog sync,
|
|
2619
|
+
// cost reconcile, codex admission) gates on exactly those two fields. Only `config`
|
|
2620
|
+
// changes: it carries the salvaged document instead of factory defaults, so a caller
|
|
2621
|
+
// that ignores the error and writes it back preserves what the operator configured.
|
|
2622
|
+
const salvaged = salvageConfigCandidate(merged, retryResult.error);
|
|
2623
|
+
if (salvaged) {
|
|
2624
|
+
return {
|
|
2625
|
+
config: normalizeApiKeyIds(salvaged.parsed),
|
|
2626
|
+
source: "fallback",
|
|
2627
|
+
error: schemaDiagnosticsError(result.error),
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
|
|
2631
|
+
return { config: getDefaultConfig(), source: "fallback", error: schemaDiagnosticsError(result.error) };
|
|
2632
|
+
} catch {
|
|
2633
|
+
return { config: getDefaultConfig(), source: "fallback", error: "invalid_json" };
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
function readConfigFileSnapshot(): ConfigFileSnapshot {
|
|
2638
|
+
try {
|
|
2639
|
+
const raw = readFileSync(getConfigPath(), "utf-8");
|
|
2640
|
+
return { diagnostics: configDiagnosticsFromRaw(raw), raw };
|
|
2641
|
+
} catch (error) {
|
|
2642
|
+
if (isMissingPathError(error)) {
|
|
2643
|
+
return {
|
|
2644
|
+
diagnostics: { config: getDefaultConfig(), source: "default", error: null },
|
|
2645
|
+
};
|
|
2646
|
+
}
|
|
2647
|
+
return {
|
|
2648
|
+
diagnostics: { config: getDefaultConfig(), source: "fallback", error: "invalid_json" },
|
|
2649
|
+
};
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
|
|
2653
|
+
export function readConfigDiagnostics(): ConfigDiagnostics {
|
|
2654
|
+
return readConfigFileSnapshot().diagnostics;
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
/**
|
|
2658
|
+
* The persisted config, plus a digest of the EXACT bytes it was parsed from.
|
|
2659
|
+
*
|
|
2660
|
+
* A union rather than a nullable digest, because `{ kind: "read" }` with no
|
|
2661
|
+
* digest is a state that cannot occur — and a state that cannot occur should
|
|
2662
|
+
* not be a state that can be written down. Refusing it at runtime is a check
|
|
2663
|
+
* somebody eventually forgets; making it unrepresentable is not.
|
|
2664
|
+
*
|
|
2665
|
+
* Why a byte digest at all: the Codex write lock compares an authority snapshot
|
|
2666
|
+
* taken before the lock against one taken while holding it, and its config
|
|
2667
|
+
* component used to hash the PARSED object. Two files that differ only in
|
|
2668
|
+
* whitespace or key order parse identically, so a non-cooperating writer could
|
|
2669
|
+
* rewrite the file between admission and commit and the comparison would see
|
|
2670
|
+
* nothing. Hashing what was actually read closes that.
|
|
2671
|
+
*
|
|
2672
|
+
* `readConfigFileSnapshot` stays private on purpose. Its `raw` carries provider
|
|
2673
|
+
* API keys and admission tokens, and `privacy:scan` reads tracked source text,
|
|
2674
|
+
* not runtime values — so it would not catch a caller that logged or serialized
|
|
2675
|
+
* that string. The digest travels; the bytes do not.
|
|
2676
|
+
*/
|
|
2677
|
+
export type ConfigAdmissionSnapshot =
|
|
2678
|
+
| Readonly<{ kind: "read"; diagnostics: ConfigDiagnostics; contentSha256: string }>
|
|
2679
|
+
| Readonly<{ kind: "unreadable"; diagnostics: ConfigDiagnostics; contentSha256: null }>;
|
|
2680
|
+
|
|
2681
|
+
export function readConfigAdmissionSnapshot(): ConfigAdmissionSnapshot {
|
|
2682
|
+
let bytes: Buffer;
|
|
2683
|
+
try {
|
|
2684
|
+
// ONE read. Hashing the file and then reading it again to parse would leave
|
|
2685
|
+
// a window for the two to disagree, which is the exact hazard this exists
|
|
2686
|
+
// to detect — the check would become a second chance to be wrong.
|
|
2687
|
+
bytes = readFileSync(getConfigPath());
|
|
2688
|
+
} catch (error) {
|
|
2689
|
+
return {
|
|
2690
|
+
kind: "unreadable",
|
|
2691
|
+
diagnostics: isMissingPathError(error)
|
|
2692
|
+
? { config: getDefaultConfig(), source: "default", error: null }
|
|
2693
|
+
: { config: getDefaultConfig(), source: "fallback", error: "invalid_json" },
|
|
2694
|
+
contentSha256: null,
|
|
2695
|
+
};
|
|
2696
|
+
}
|
|
2697
|
+
return {
|
|
2698
|
+
kind: "read",
|
|
2699
|
+
// Decoded from the same buffer that was hashed, not re-read from disk.
|
|
2700
|
+
diagnostics: configDiagnosticsFromRaw(bytes.toString("utf-8")),
|
|
2701
|
+
contentSha256: createHash("sha256").update(bytes).digest("hex"),
|
|
2702
|
+
};
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
const CONFIG_MUTATION_DB_FILENAME = "config-mutation.sqlite";
|
|
2706
|
+
const CONFIG_MUTATION_DB_SIDECARS = ["-journal", "-wal", "-shm"] as const;
|
|
2707
|
+
let warnedConfigMutationDirectoryAcl = false;
|
|
2708
|
+
|
|
2709
|
+
export class ConfigMutationLockError extends Error {
|
|
2710
|
+
readonly code = "CONFIG_MUTATION_LOCK_UNAVAILABLE";
|
|
2711
|
+
|
|
2712
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
2713
|
+
super(message, options);
|
|
2714
|
+
this.name = "ConfigMutationLockError";
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
function configMutationDatabasePath(): string {
|
|
2719
|
+
const dir = getConfigDir();
|
|
2720
|
+
// First statement on purpose: a rejected mutation must leave nothing behind, not a
|
|
2721
|
+
// freshly created/chmod'd directory or database. See src/lib/test-home-guard.ts.
|
|
2722
|
+
assertNotRealHomeUnderTest(dir);
|
|
2723
|
+
if (!existsSync(dir)) {
|
|
2724
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
2725
|
+
} else {
|
|
2726
|
+
try { chmodSync(dir, 0o700); } catch { /* best-effort on existing dir */ }
|
|
2727
|
+
}
|
|
2728
|
+
if (windowsSecretAclApplies()) {
|
|
2729
|
+
try {
|
|
2730
|
+
// Distinct timeout memo from management-token directory harden: a required
|
|
2731
|
+
// management-dir timeout must not poison config mutation on the same home
|
|
2732
|
+
// (windows-latest server-management-auth cases).
|
|
2733
|
+
hardenSecretDir(dir, { required: true, timeoutMemoKey: `${dir}::config-mutation` });
|
|
2734
|
+
} catch (error) {
|
|
2735
|
+
if (!warnedConfigMutationDirectoryAcl) {
|
|
2736
|
+
warnedConfigMutationDirectoryAcl = true;
|
|
2737
|
+
const diagnostics = error instanceof Error ? error.message : "ACL hardening failed";
|
|
2738
|
+
console.warn(
|
|
2739
|
+
`[opencodex] Config mutation coordination directory ACL hardening did not complete; continuing without it. ${diagnostics}`,
|
|
2740
|
+
);
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
const path = join(dir, CONFIG_MUTATION_DB_FILENAME);
|
|
2745
|
+
recordOwnedConfigPath(dir, path);
|
|
2746
|
+
for (const suffix of CONFIG_MUTATION_DB_SIDECARS) {
|
|
2747
|
+
recordOwnedConfigPath(dir, `${path}${suffix}`);
|
|
2748
|
+
}
|
|
2749
|
+
return path;
|
|
2750
|
+
}
|
|
2751
|
+
|
|
2752
|
+
let configMutationLockDepth = 0;
|
|
2753
|
+
let configMutationDatabase: Database | null = null;
|
|
2754
|
+
|
|
2755
|
+
/**
|
|
2756
|
+
* Serialize synchronous config and Codex credential-generation commits across processes with an
|
|
2757
|
+
* OS-backed SQLite write transaction. `busy_timeout=0` is deliberate: runtime request paths must
|
|
2758
|
+
* fail immediately under contention rather than freeze the Bun event loop. Process exit releases
|
|
2759
|
+
* SQLite locks without stale-owner deletion or lease recovery races.
|
|
2760
|
+
*
|
|
2761
|
+
* Reentrancy is limited to the current synchronous call stack; never return a Promise from `fn`.
|
|
2762
|
+
*/
|
|
2763
|
+
export function withConfigMutationLockSync<T>(fn: () => T): T {
|
|
2764
|
+
if (configMutationLockDepth > 0) {
|
|
2765
|
+
configMutationLockDepth += 1;
|
|
2766
|
+
try {
|
|
2767
|
+
return fn();
|
|
2768
|
+
} finally {
|
|
2769
|
+
configMutationLockDepth -= 1;
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
const path = configMutationDatabasePath();
|
|
2773
|
+
let database: Database | undefined;
|
|
2774
|
+
let transactionOpen = false;
|
|
2775
|
+
try {
|
|
2776
|
+
database = new Database(path, { create: true });
|
|
2777
|
+
try { chmodSync(path, 0o600); } catch { /* platform may ignore chmod */ }
|
|
2778
|
+
database.exec("PRAGMA busy_timeout = 0; BEGIN IMMEDIATE");
|
|
2779
|
+
transactionOpen = true;
|
|
2780
|
+
initializeConfigGeneration(database);
|
|
2781
|
+
} catch (cause) {
|
|
2782
|
+
if (transactionOpen) {
|
|
2783
|
+
try { database?.exec("ROLLBACK"); } catch { /* close below still releases the OS lock */ }
|
|
2784
|
+
}
|
|
2785
|
+
try { database?.close(); } catch { /* acquisition already failed */ }
|
|
2786
|
+
const code = cause && typeof cause === "object" && "code" in cause
|
|
2787
|
+
? String((cause as { code?: unknown }).code)
|
|
2788
|
+
: "";
|
|
2789
|
+
throw new ConfigMutationLockError(
|
|
2790
|
+
code === "SQLITE_BUSY" ? "Config mutation already in progress" : "Could not acquire config mutation transaction",
|
|
2791
|
+
{ cause },
|
|
2792
|
+
);
|
|
2793
|
+
}
|
|
2794
|
+
|
|
2795
|
+
configMutationLockDepth = 1;
|
|
2796
|
+
configMutationDatabase = database;
|
|
2797
|
+
try {
|
|
2798
|
+
const value = fn();
|
|
2799
|
+
database.exec("COMMIT");
|
|
2800
|
+
transactionOpen = false;
|
|
2801
|
+
return value;
|
|
2802
|
+
} catch (error) {
|
|
2803
|
+
if (transactionOpen) {
|
|
2804
|
+
try { database.exec("ROLLBACK"); } catch { /* close below still releases the OS lock */ }
|
|
2805
|
+
transactionOpen = false;
|
|
2806
|
+
}
|
|
2807
|
+
throw error;
|
|
2808
|
+
} finally {
|
|
2809
|
+
configMutationLockDepth = 0;
|
|
2810
|
+
configMutationDatabase = null;
|
|
2811
|
+
try { database.close(); } catch { /* the OS lock is released with the handle */ }
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
function bumpGenerationForCooperatingConfigWrite(): void {
|
|
2816
|
+
if (!configMutationDatabase) {
|
|
2817
|
+
throw new Error("A cooperating config write requires the config mutation transaction.");
|
|
2818
|
+
}
|
|
2819
|
+
bumpCurrentConfigGeneration(configMutationDatabase);
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2822
|
+
export const readConfigGeneration: ReadConfigGeneration = () => {
|
|
2823
|
+
try {
|
|
2824
|
+
return readConfigGenerationAtPath(configMutationDatabasePath());
|
|
2825
|
+
} catch {
|
|
2826
|
+
return { kind: "unavailable", reason: "database" };
|
|
2827
|
+
}
|
|
2828
|
+
};
|
|
2829
|
+
|
|
2830
|
+
export function observeConfigGeneration(): ConfigGenerationObservation {
|
|
2831
|
+
return observeConfigGenerationAtPath(join(getConfigDir(), CONFIG_MUTATION_DB_FILENAME));
|
|
2832
|
+
}
|
|
2833
|
+
|
|
2834
|
+
/**
|
|
2835
|
+
* Read the generation from the transaction that is open RIGHT NOW.
|
|
2836
|
+
*
|
|
2837
|
+
* The observer cannot do this job. On the very first acquisition the
|
|
2838
|
+
* `BEGIN IMMEDIATE` that creates the table has not committed yet, so a separate
|
|
2839
|
+
* read-only connection cannot read a generation from it — measured, not
|
|
2840
|
+
* assumed. A caller that compared a pre-lock observation against an observer
|
|
2841
|
+
* re-read would therefore refuse every first write as stale.
|
|
2842
|
+
*
|
|
2843
|
+
* Throwing when no transaction is open is deliberate. Being called outside the
|
|
2844
|
+
* lock is broken plumbing, and returning a typed "unavailable" would let that
|
|
2845
|
+
* bug arrive disguised as an environmental failure — retried forever, on a
|
|
2846
|
+
* machine where nothing is wrong.
|
|
2847
|
+
*/
|
|
2848
|
+
export function readConfigGenerationInCurrentMutationTransaction(): ConfigGeneration {
|
|
2849
|
+
if (configMutationLockDepth < 1 || !configMutationDatabase) {
|
|
2850
|
+
throw new Error(
|
|
2851
|
+
"readConfigGenerationInCurrentMutationTransaction requires an open config mutation transaction.",
|
|
2852
|
+
);
|
|
2853
|
+
}
|
|
2854
|
+
return readConfigGenerationInTransaction(configMutationDatabase);
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
export const bumpConfigGeneration: BumpConfigGeneration = expected => {
|
|
2858
|
+
try {
|
|
2859
|
+
return bumpConfigGenerationAtPath(configMutationDatabasePath(), expected);
|
|
2860
|
+
} catch {
|
|
2861
|
+
return { kind: "unavailable", reason: "database" };
|
|
2862
|
+
}
|
|
2863
|
+
};
|
|
2864
|
+
|
|
2865
|
+
function configGenerationFailureReason(error: unknown): "busy" | "database" {
|
|
2866
|
+
const cause = error instanceof ConfigMutationLockError ? error.cause : error;
|
|
2867
|
+
const code = cause && typeof cause === "object" && "code" in cause
|
|
2868
|
+
? String((cause as { code?: unknown }).code)
|
|
2869
|
+
: "";
|
|
2870
|
+
const message = cause instanceof Error ? cause.message : "";
|
|
2871
|
+
return code === "SQLITE_BUSY"
|
|
2872
|
+
|| code === "SQLITE_LOCKED"
|
|
2873
|
+
|| /database (?:is|table is) locked/i.test(message)
|
|
2874
|
+
? "busy"
|
|
2875
|
+
: "database";
|
|
2876
|
+
}
|
|
2877
|
+
|
|
2878
|
+
export const withExpectedConfigGenerationSync: WithExpectedConfigGenerationSync = (
|
|
2879
|
+
expected,
|
|
2880
|
+
commit,
|
|
2881
|
+
) => {
|
|
2882
|
+
let callbackThrew = false;
|
|
2883
|
+
let callbackError: unknown;
|
|
2884
|
+
try {
|
|
2885
|
+
return withConfigMutationLockSync(() => {
|
|
2886
|
+
const database = configMutationDatabase;
|
|
2887
|
+
if (!database) throw new Error("Config mutation transaction database is unavailable.");
|
|
2888
|
+
const current = readConfigGenerationInTransaction(database);
|
|
2889
|
+
if (current.value !== expected.value) return { kind: "conflict", current };
|
|
2890
|
+
try {
|
|
2891
|
+
return { kind: "matched", generation: current, value: commit() };
|
|
2892
|
+
} catch (error) {
|
|
2893
|
+
callbackThrew = true;
|
|
2894
|
+
callbackError = error;
|
|
2895
|
+
throw error;
|
|
2896
|
+
}
|
|
2897
|
+
});
|
|
2898
|
+
} catch (error) {
|
|
2899
|
+
if (callbackThrew && error === callbackError) throw error;
|
|
2900
|
+
return { kind: "unavailable", reason: configGenerationFailureReason(error) };
|
|
2901
|
+
}
|
|
2902
|
+
};
|
|
2903
|
+
|
|
2904
|
+
/**
|
|
2905
|
+
* Atomic config.json write WITHOUT the mutation lock; callers must hold
|
|
2906
|
+
* `withConfigMutationLockSync`. Returns true when bytes changed. Refreshes the
|
|
2907
|
+
* cost-overlay registry from the persisted config so runtime estimates follow
|
|
2908
|
+
* every save path.
|
|
2909
|
+
*/
|
|
2910
|
+
function persistConfigUnlocked(config: OcxConfig): boolean {
|
|
2911
|
+
const configPath = getConfigPath();
|
|
2912
|
+
// External editors can add provider rows the live config deliberately does
|
|
2913
|
+
// not route with yet; merge them at the serialization boundary so an
|
|
2914
|
+
// unrelated in-process save cannot erase the provider or its overlay.
|
|
2915
|
+
const persisted = withPreservedDiskOnlyProviders(config);
|
|
2916
|
+
const bytes = JSON.stringify(persisted, null, 2) + "\n";
|
|
2917
|
+
let unchanged = false;
|
|
2918
|
+
try {
|
|
2919
|
+
unchanged = readFileSync(configPath, "utf8") === bytes;
|
|
2920
|
+
} catch (error) {
|
|
2921
|
+
if (!isMissingPathError(error)) throw error;
|
|
2922
|
+
}
|
|
2923
|
+
// Keep the runtime overlay registry in sync with EVERY persist path,
|
|
2924
|
+
// including byte-identical saves: a cooperating CLI process may have written
|
|
2925
|
+
// the same bytes (e.g. before a proxy notification), and Logs/Usage must
|
|
2926
|
+
// adopt the overlay without waiting for a changed save or restart.
|
|
2927
|
+
if (unchanged) {
|
|
2928
|
+
refreshUserCostOverlays(persisted);
|
|
2929
|
+
return false;
|
|
2930
|
+
}
|
|
2931
|
+
atomicWriteFile(configPath, bytes);
|
|
2932
|
+
// For changed saves, refresh only AFTER the write succeeded so a failed
|
|
2933
|
+
// write cannot leave estimates reflecting configuration never persisted.
|
|
2934
|
+
refreshUserCostOverlays(persisted);
|
|
2935
|
+
return true;
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
/** Persist `config` to config.json under the config-mutation lock. */
|
|
2939
|
+
export function saveConfig(config: OcxConfig): void {
|
|
2940
|
+
// Keep the real-home assertion ahead of even lock-directory preparation.
|
|
2941
|
+
assertNotRealHomeUnderTest(getConfigDir());
|
|
2942
|
+
withConfigMutationLockSync(() => {
|
|
2943
|
+
const projected = projectCustomModelCatalogMigration(readRawConfigJson(), config);
|
|
2944
|
+
if (persistConfigUnlocked(projected)) bumpGenerationForCooperatingConfigWrite();
|
|
2945
|
+
adoptCustomModelCatalogMigration(config, projected);
|
|
2946
|
+
});
|
|
2947
|
+
}
|
|
2948
|
+
|
|
2949
|
+
export type PersistedConfigMutation<T> = {
|
|
2950
|
+
changed: boolean;
|
|
2951
|
+
value: T;
|
|
2952
|
+
};
|
|
2953
|
+
|
|
2954
|
+
export type PersistedConfigMutationOutcome<T> =
|
|
2955
|
+
| { status: "committed" | "unchanged"; value: T }
|
|
2956
|
+
| { status: "unavailable"; reason: "missing" | "invalid" | "conflict" };
|
|
2957
|
+
|
|
2958
|
+
const CONFIG_MUTATION_MAX_REBASE_ATTEMPTS = 3;
|
|
2959
|
+
let persistedConfigMutationBeforeCommitForTests: (() => void) | null = null;
|
|
2960
|
+
|
|
2961
|
+
/** Test-only one-shot seam: inject a competing mutation after the first decision, before freshness revalidation. */
|
|
2962
|
+
export function setPersistedConfigMutationBeforeCommitForTests(hook: (() => void) | null): void {
|
|
2963
|
+
persistedConfigMutationBeforeCommitForTests = hook;
|
|
2964
|
+
}
|
|
2965
|
+
|
|
2966
|
+
function unavailableConfigMutationReason(snapshot: ConfigFileSnapshot): "missing" | "invalid" {
|
|
2967
|
+
return snapshot.diagnostics.source === "default" ? "missing" : "invalid";
|
|
2968
|
+
}
|
|
2969
|
+
|
|
2970
|
+
/**
|
|
2971
|
+
* Patch a schema-valid on-disk config under the shared mutation lock. Cooperating writers are
|
|
2972
|
+
* serialized; the callback is rerun on the newest snapshot so observed direct byte changes rebase
|
|
2973
|
+
* and credential predicates are re-evaluated immediately before the atomic commit. A writer that
|
|
2974
|
+
* ignores the coordinator can still change bytes after the final check because the filesystem has
|
|
2975
|
+
* no portable conditional rename. Missing or malformed config always fails closed and is never
|
|
2976
|
+
* recreated from a prior snapshot.
|
|
2977
|
+
*/
|
|
2978
|
+
export function mutatePersistedConfig<T>(
|
|
2979
|
+
mutate: (config: OcxConfig) => PersistedConfigMutation<T>,
|
|
2980
|
+
): PersistedConfigMutationOutcome<T> {
|
|
2981
|
+
// Avoid creating/opening the coordinator database for a read-path update that already knows
|
|
2982
|
+
// there is no valid config. The same check runs again under the transaction for authority.
|
|
2983
|
+
const observed = readConfigFileSnapshot();
|
|
2984
|
+
if (observed.diagnostics.source !== "file" || observed.raw === undefined) {
|
|
2985
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(observed) };
|
|
2986
|
+
}
|
|
2987
|
+
return withConfigMutationLockSync(() => {
|
|
2988
|
+
let base = readConfigFileSnapshot();
|
|
2989
|
+
for (let attempt = 0; attempt < CONFIG_MUTATION_MAX_REBASE_ATTEMPTS; attempt += 1) {
|
|
2990
|
+
if (base.diagnostics.source !== "file" || base.raw === undefined) {
|
|
2991
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(base) };
|
|
2992
|
+
}
|
|
2993
|
+
|
|
2994
|
+
const tentativeConfig = structuredClone(base.diagnostics.config);
|
|
2995
|
+
const tentative = mutate(tentativeConfig);
|
|
2996
|
+
if (!tentative.changed) return { status: "unchanged", value: tentative.value };
|
|
2997
|
+
|
|
2998
|
+
const hook = persistedConfigMutationBeforeCommitForTests;
|
|
2999
|
+
persistedConfigMutationBeforeCommitForTests = null;
|
|
3000
|
+
hook?.();
|
|
3001
|
+
|
|
3002
|
+
const latest = readConfigFileSnapshot();
|
|
3003
|
+
if (latest.diagnostics.source !== "file" || latest.raw === undefined) {
|
|
3004
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(latest) };
|
|
3005
|
+
}
|
|
3006
|
+
if (latest.raw !== base.raw) {
|
|
3007
|
+
base = latest;
|
|
3008
|
+
continue;
|
|
3009
|
+
}
|
|
3010
|
+
|
|
3011
|
+
// Re-run against a fresh clone even when config bytes are unchanged: a Codex credential
|
|
3012
|
+
// generation lives in a separate file and may have changed at the injected seam.
|
|
3013
|
+
const confirmedConfig = structuredClone(latest.diagnostics.config);
|
|
3014
|
+
const confirmed = mutate(confirmedConfig);
|
|
3015
|
+
if (!confirmed.changed) return { status: "unchanged", value: confirmed.value };
|
|
3016
|
+
|
|
3017
|
+
const commitBase = readConfigFileSnapshot();
|
|
3018
|
+
if (commitBase.diagnostics.source !== "file" || commitBase.raw === undefined) {
|
|
3019
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(commitBase) };
|
|
3020
|
+
}
|
|
3021
|
+
if (commitBase.raw !== latest.raw) {
|
|
3022
|
+
base = commitBase;
|
|
3023
|
+
continue;
|
|
3024
|
+
}
|
|
3025
|
+
|
|
3026
|
+
const projected = projectCustomModelCatalogMigration(
|
|
3027
|
+
commitBase.diagnostics.config,
|
|
3028
|
+
confirmedConfig,
|
|
3029
|
+
);
|
|
3030
|
+
if (persistConfigUnlocked(projected)) bumpGenerationForCooperatingConfigWrite();
|
|
3031
|
+
return { status: "committed", value: confirmed.value };
|
|
3032
|
+
}
|
|
3033
|
+
return { status: "unavailable", reason: "conflict" };
|
|
3034
|
+
});
|
|
3035
|
+
}
|
|
3036
|
+
|
|
3037
|
+
export function websocketsEnabled(config: Pick<OcxConfig, "websockets">): boolean {
|
|
3038
|
+
return config.websockets === true;
|
|
3039
|
+
}
|
|
3040
|
+
|
|
3041
|
+
// ---------------------------------------------------------------------------
|
|
3042
|
+
// Hand-edit protection for the `claudeCode` subtree (devlog 260726_claude_auth_auto/040 H1).
|
|
3043
|
+
//
|
|
3044
|
+
// `saveConfig` serializes the WHOLE config object, so ANY service-time save — a model
|
|
3045
|
+
// visibility toggle, a 429 key rotation on the request path — rewrites `claudeCode`
|
|
3046
|
+
// from whatever the long-lived server config happens to hold. A user who hand-edits
|
|
3047
|
+
// `config.json` while the proxy runs then watches their edit vanish for no visible
|
|
3048
|
+
// reason (issue #488). Enumerating `claudeCode` mutators cannot fix that; the guard has
|
|
3049
|
+
// to live in ONE save wrapper that every live-config writer goes through.
|
|
3050
|
+
// ---------------------------------------------------------------------------
|
|
3051
|
+
|
|
3052
|
+
/**
|
|
3053
|
+
* Baseline keyed on the CONFIG INSTANCE, never a module global: a second `loadConfig()`
|
|
3054
|
+
* elsewhere must not refresh the baseline the long-lived server config is judged
|
|
3055
|
+
* against, or a later stale save would masquerade as "our own change".
|
|
3056
|
+
*/
|
|
3057
|
+
const claudeCodeBaseline = new WeakMap<OcxConfig, unknown>();
|
|
3058
|
+
/**
|
|
3059
|
+
* Full live-config baseline used to rebase unrelated cooperating writes. The
|
|
3060
|
+
* Claude subtree and the bound listener fields remain on their dedicated
|
|
3061
|
+
* reconciliation paths below.
|
|
3062
|
+
*/
|
|
3063
|
+
const liveConfigBaseline = new WeakMap<OcxConfig, OcxConfig>();
|
|
3064
|
+
|
|
3065
|
+
/**
|
|
3066
|
+
* The live config retains the address of the socket Bun actually opened, while
|
|
3067
|
+
* this map retains the operator's desired address for the next process start.
|
|
3068
|
+
* Keeping them separate prevents an unrelated live save from restoring a stale
|
|
3069
|
+
* externally exposed bind after OAuth adopted a newer loopback disk config.
|
|
3070
|
+
*/
|
|
3071
|
+
type PersistedServerBinding = Pick<OcxConfig, "port" | "hostname">;
|
|
3072
|
+
|
|
3073
|
+
const persistedLiveServerBinding = new WeakMap<OcxConfig, PersistedServerBinding>();
|
|
3074
|
+
|
|
3075
|
+
/**
|
|
3076
|
+
* Arm the baseline for a long-lived config. MANDATORY at `startServer`, not lazy on
|
|
3077
|
+
* first save — arming lazily would lose exactly the hand edit made before that first
|
|
3078
|
+
* save, which is the case the guard exists for.
|
|
3079
|
+
*/
|
|
3080
|
+
export function armClaudeCodeBaseline(config: OcxConfig): void {
|
|
3081
|
+
liveConfigBaseline.set(config, structuredClone(config));
|
|
3082
|
+
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
|
|
3083
|
+
}
|
|
3084
|
+
|
|
3085
|
+
/**
|
|
3086
|
+
* Adopt one schema-validated provider that was read from the authoritative disk
|
|
3087
|
+
* config into a long-lived server config without rebasing any unrelated field.
|
|
3088
|
+
* Updating the matching baseline row keeps a later guarded save from treating the
|
|
3089
|
+
* adopted provider as an unsaved live edit that should defeat a newer disk change.
|
|
3090
|
+
*/
|
|
3091
|
+
export function adoptPersistedProviderIntoLiveConfig(
|
|
3092
|
+
config: OcxConfig,
|
|
3093
|
+
name: string,
|
|
3094
|
+
provider: OcxProviderConfig,
|
|
3095
|
+
persistedConfig?: OcxConfig,
|
|
3096
|
+
): void {
|
|
3097
|
+
config.providers[name] = structuredClone(provider);
|
|
3098
|
+
const baseline = liveConfigBaseline.get(config);
|
|
3099
|
+
if (baseline) baseline.providers[name] = structuredClone(provider);
|
|
3100
|
+
if (persistedConfig) refreshPreservedProviderOwner(config, persistedConfig);
|
|
3101
|
+
}
|
|
3102
|
+
|
|
3103
|
+
/** Test seam only: is this instance armed? */
|
|
3104
|
+
export function claudeCodeBaselineArmed(config: OcxConfig): boolean {
|
|
3105
|
+
return claudeCodeBaseline.has(config);
|
|
3106
|
+
}
|
|
3107
|
+
|
|
3108
|
+
/**
|
|
3109
|
+
* Structural compare of parsed subtrees. NOT `JSON.stringify`: key order must not
|
|
3110
|
+
* decide whether a user's hand edit survives.
|
|
3111
|
+
*/
|
|
3112
|
+
function deepEqual(a: unknown, b: unknown): boolean {
|
|
3113
|
+
if (a === b) return true;
|
|
3114
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
3115
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
3116
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
3117
|
+
return a.length === b.length && a.every((item, index) => deepEqual(item, b[index]));
|
|
3118
|
+
}
|
|
3119
|
+
const left = a as Record<string, unknown>;
|
|
3120
|
+
const right = b as Record<string, unknown>;
|
|
3121
|
+
// `undefined` values and absent keys are the same thing after a JSON round-trip.
|
|
3122
|
+
const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
|
|
3123
|
+
for (const key of keys) {
|
|
3124
|
+
if (left[key] === undefined && right[key] === undefined) continue;
|
|
3125
|
+
if (!deepEqual(left[key], right[key])) return false;
|
|
3126
|
+
}
|
|
3127
|
+
return true;
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
const MISSING_CONFIG_VALUE = Symbol("missing-config-value");
|
|
3131
|
+
type ConfigMergeValue = unknown | typeof MISSING_CONFIG_VALUE;
|
|
3132
|
+
|
|
3133
|
+
function isPlainConfigRecord(value: ConfigMergeValue): value is Record<string, unknown> {
|
|
3134
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
3135
|
+
const prototype = Object.getPrototypeOf(value);
|
|
3136
|
+
return prototype === Object.prototype || prototype === null;
|
|
3137
|
+
}
|
|
3138
|
+
|
|
3139
|
+
function ownConfigValue(record: Record<string, unknown>, key: string): ConfigMergeValue {
|
|
3140
|
+
return Object.hasOwn(record, key) ? record[key] : MISSING_CONFIG_VALUE;
|
|
3141
|
+
}
|
|
3142
|
+
|
|
3143
|
+
function cloneConfigValue(value: ConfigMergeValue): ConfigMergeValue {
|
|
3144
|
+
return value === MISSING_CONFIG_VALUE ? value : structuredClone(value);
|
|
3145
|
+
}
|
|
3146
|
+
|
|
3147
|
+
type IndexedCustomModels = {
|
|
3148
|
+
order: string[];
|
|
3149
|
+
byId: Map<string, Record<string, unknown>>;
|
|
3150
|
+
};
|
|
3151
|
+
|
|
3152
|
+
function indexCustomModels(value: ConfigMergeValue): IndexedCustomModels | null {
|
|
3153
|
+
if (!Array.isArray(value)) return null;
|
|
3154
|
+
const order: string[] = [];
|
|
3155
|
+
const byId = new Map<string, Record<string, unknown>>();
|
|
3156
|
+
for (const item of value) {
|
|
3157
|
+
if (!isPlainConfigRecord(item) || typeof item.id !== "string" || item.id.length === 0 || byId.has(item.id)) {
|
|
3158
|
+
return null;
|
|
3159
|
+
}
|
|
3160
|
+
order.push(item.id);
|
|
3161
|
+
byId.set(item.id, item);
|
|
3162
|
+
}
|
|
3163
|
+
return { order, byId };
|
|
3164
|
+
}
|
|
3165
|
+
|
|
3166
|
+
/**
|
|
3167
|
+
* Merge custom-model rows by their stable id instead of treating the array as
|
|
3168
|
+
* one opaque value. A row changed only on disk is adopted, a row changed only
|
|
3169
|
+
* in the live config is retained, and disjoint edits to the same row recurse
|
|
3170
|
+
* through the normal three-way object merge. A newer persisted row deletion
|
|
3171
|
+
* wins over a stale live edit to that row.
|
|
3172
|
+
*/
|
|
3173
|
+
function reconcileCustomModels(
|
|
3174
|
+
baseline: ConfigMergeValue,
|
|
3175
|
+
live: ConfigMergeValue,
|
|
3176
|
+
persisted: ConfigMergeValue,
|
|
3177
|
+
): ConfigMergeValue | null {
|
|
3178
|
+
const baselineRows = indexCustomModels(baseline);
|
|
3179
|
+
const liveRows = indexCustomModels(live);
|
|
3180
|
+
const persistedRows = indexCustomModels(persisted);
|
|
3181
|
+
if (!baselineRows || !liveRows || !persistedRows) return null;
|
|
3182
|
+
|
|
3183
|
+
const order = [...liveRows.order, ...persistedRows.order.filter(id => !liveRows.byId.has(id))];
|
|
3184
|
+
const merged: Array<Record<string, unknown>> = [];
|
|
3185
|
+
for (const id of order) {
|
|
3186
|
+
const baselineRow = baselineRows.byId.get(id) ?? MISSING_CONFIG_VALUE;
|
|
3187
|
+
const persistedRow = persistedRows.byId.get(id) ?? MISSING_CONFIG_VALUE;
|
|
3188
|
+
const row = baselineRow !== MISSING_CONFIG_VALUE && persistedRow === MISSING_CONFIG_VALUE
|
|
3189
|
+
? MISSING_CONFIG_VALUE
|
|
3190
|
+
: reconcileConfigValue(
|
|
3191
|
+
baselineRow,
|
|
3192
|
+
liveRows.byId.get(id) ?? MISSING_CONFIG_VALUE,
|
|
3193
|
+
persistedRow,
|
|
3194
|
+
);
|
|
3195
|
+
if (row !== MISSING_CONFIG_VALUE) merged.push(row as Record<string, unknown>);
|
|
3196
|
+
}
|
|
3197
|
+
return merged;
|
|
3198
|
+
}
|
|
3199
|
+
|
|
3200
|
+
function reconcileConfigRecord(
|
|
3201
|
+
live: Record<string, unknown>,
|
|
3202
|
+
baseline: Record<string, unknown>,
|
|
3203
|
+
persisted: Record<string, unknown>,
|
|
3204
|
+
skippedKeys?: ReadonlySet<string>,
|
|
3205
|
+
persistedDeletionsWin = false,
|
|
3206
|
+
): void {
|
|
3207
|
+
const keys = new Set([...Object.keys(baseline), ...Object.keys(live), ...Object.keys(persisted)]);
|
|
3208
|
+
for (const key of keys) {
|
|
3209
|
+
if (skippedKeys?.has(key)) continue;
|
|
3210
|
+
const baselineValue = ownConfigValue(baseline, key);
|
|
3211
|
+
const liveValue = ownConfigValue(live, key);
|
|
3212
|
+
const persistedValue = ownConfigValue(persisted, key);
|
|
3213
|
+
const merged = persistedDeletionsWin
|
|
3214
|
+
&& baselineValue !== MISSING_CONFIG_VALUE
|
|
3215
|
+
&& persistedValue === MISSING_CONFIG_VALUE
|
|
3216
|
+
? MISSING_CONFIG_VALUE
|
|
3217
|
+
: key === "customModels"
|
|
3218
|
+
? reconcileCustomModels(baselineValue, liveValue, persistedValue)
|
|
3219
|
+
?? reconcileConfigValue(baselineValue, liveValue, persistedValue)
|
|
3220
|
+
: reconcileConfigValue(baselineValue, liveValue, persistedValue, key === "providers");
|
|
3221
|
+
if (merged === MISSING_CONFIG_VALUE) delete live[key];
|
|
3222
|
+
else live[key] = merged;
|
|
3223
|
+
}
|
|
3224
|
+
}
|
|
3225
|
+
|
|
3226
|
+
function reconcileConfigValue(
|
|
3227
|
+
baseline: ConfigMergeValue,
|
|
3228
|
+
live: ConfigMergeValue,
|
|
3229
|
+
persisted: ConfigMergeValue,
|
|
3230
|
+
persistedChildDeletionsWin = false,
|
|
3231
|
+
): ConfigMergeValue {
|
|
3232
|
+
const liveChanged = !deepEqual(live, baseline);
|
|
3233
|
+
const persistedChanged = !deepEqual(persisted, baseline);
|
|
3234
|
+
|
|
3235
|
+
if (!liveChanged) {
|
|
3236
|
+
if (live !== MISSING_CONFIG_VALUE && Array.isArray(live) && Array.isArray(persisted)) {
|
|
3237
|
+
live.splice(0, live.length, ...structuredClone(persisted));
|
|
3238
|
+
return live;
|
|
3239
|
+
}
|
|
3240
|
+
if (isPlainConfigRecord(live) && isPlainConfigRecord(persisted)) {
|
|
3241
|
+
reconcileConfigRecord(
|
|
3242
|
+
live,
|
|
3243
|
+
isPlainConfigRecord(baseline) ? baseline : {},
|
|
3244
|
+
persisted,
|
|
3245
|
+
);
|
|
3246
|
+
return live;
|
|
3247
|
+
}
|
|
3248
|
+
return cloneConfigValue(persisted);
|
|
3249
|
+
}
|
|
3250
|
+
|
|
3251
|
+
if (!persistedChanged) return live;
|
|
3252
|
+
|
|
3253
|
+
if (isPlainConfigRecord(live)
|
|
3254
|
+
&& isPlainConfigRecord(persisted)
|
|
3255
|
+
&& (baseline === MISSING_CONFIG_VALUE || isPlainConfigRecord(baseline))) {
|
|
3256
|
+
reconcileConfigRecord(
|
|
3257
|
+
live,
|
|
3258
|
+
isPlainConfigRecord(baseline) ? baseline : {},
|
|
3259
|
+
persisted,
|
|
3260
|
+
undefined,
|
|
3261
|
+
persistedChildDeletionsWin,
|
|
3262
|
+
);
|
|
3263
|
+
}
|
|
3264
|
+
// Same-leaf conflicts prefer the pending live management mutation.
|
|
3265
|
+
return live;
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
/**
|
|
3269
|
+
* Reconcile an async OAuth disk commit into the shared live config without erasing
|
|
3270
|
+
* management mutations that have not saved yet. The baseline is a normalized disk
|
|
3271
|
+
* snapshot from immediately before login; disjoint object edits merge recursively,
|
|
3272
|
+
* while same-leaf conflicts prefer live state.
|
|
3273
|
+
*/
|
|
3274
|
+
export function reconcileLiveConfigFromDisk(config: OcxConfig, persistedBaseline: OcxConfig): void {
|
|
3275
|
+
const diagnostics = readConfigDiagnostics();
|
|
3276
|
+
if (diagnostics.source === "fallback") {
|
|
3277
|
+
throw new Error(`OAuth config reconciliation failed: ${diagnostics.error ?? "invalid config file"}`);
|
|
3278
|
+
}
|
|
3279
|
+
const persisted = diagnostics.config;
|
|
3280
|
+
const claudeGuardArmed = claudeCodeBaseline.has(config);
|
|
3281
|
+
const pendingLiveClaudeMutation = claudeGuardArmed
|
|
3282
|
+
&& !deepEqual(config.claudeCode, claudeCodeBaseline.get(config));
|
|
3283
|
+
|
|
3284
|
+
persistedLiveServerBinding.set(config, {
|
|
3285
|
+
port: persisted.port,
|
|
3286
|
+
...(persisted.hostname !== undefined ? { hostname: persisted.hostname } : {}),
|
|
3287
|
+
});
|
|
3288
|
+
|
|
3289
|
+
reconcileConfigRecord(
|
|
3290
|
+
config as unknown as Record<string, unknown>,
|
|
3291
|
+
persistedBaseline as unknown as Record<string, unknown>,
|
|
3292
|
+
persisted as unknown as Record<string, unknown>,
|
|
3293
|
+
new Set(["hostname", "port", ...(claudeGuardArmed ? ["claudeCode"] : [])]),
|
|
3294
|
+
);
|
|
3295
|
+
|
|
3296
|
+
if (claudeGuardArmed && !pendingLiveClaudeMutation) {
|
|
3297
|
+
if (persisted.claudeCode === undefined) delete config.claudeCode;
|
|
3298
|
+
else config.claudeCode = structuredClone(persisted.claudeCode);
|
|
3299
|
+
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
|
|
3300
|
+
}
|
|
3301
|
+
// The reconciliation may have adopted a providers.<name>.modelCosts edit made
|
|
3302
|
+
// by a cooperating process while the OAuth login was pending; keep the overlay
|
|
3303
|
+
// registry (and the usage-cache overlay version) in sync with the live config.
|
|
3304
|
+
refreshUserCostOverlays(config);
|
|
3305
|
+
}
|
|
3306
|
+
|
|
3307
|
+
/** The literal file, with no schema merge or default injection. */
|
|
3308
|
+
function readRawConfigJson(): Record<string, unknown> | undefined {
|
|
3309
|
+
try {
|
|
3310
|
+
const configPath = getConfigPath();
|
|
3311
|
+
if (!existsSync(configPath)) return undefined;
|
|
3312
|
+
const raw = readFileSync(configPath, "utf-8").replace(/^\uFEFF/, "");
|
|
3313
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
3314
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
|
|
3315
|
+
return parsed as Record<string, unknown>;
|
|
3316
|
+
} catch {
|
|
3317
|
+
// Unreadable or corrupt: behave exactly as before. Never fail a save over protection.
|
|
3318
|
+
return undefined;
|
|
3319
|
+
}
|
|
3320
|
+
}
|
|
3321
|
+
|
|
3322
|
+
/**
|
|
3323
|
+
* Read only schema-valid binding fields from the literal file. Missing fields mean
|
|
3324
|
+
* their schema defaults; malformed fields keep the last known persisted value.
|
|
3325
|
+
*/
|
|
3326
|
+
function readPersistedServerBinding(
|
|
3327
|
+
raw: Record<string, unknown>,
|
|
3328
|
+
baseline: PersistedServerBinding,
|
|
3329
|
+
): PersistedServerBinding {
|
|
3330
|
+
const port = raw.port === undefined
|
|
3331
|
+
? 10100
|
|
3332
|
+
: (typeof raw.port === "number"
|
|
3333
|
+
&& Number.isInteger(raw.port)
|
|
3334
|
+
&& raw.port >= 0
|
|
3335
|
+
&& raw.port <= 65535
|
|
3336
|
+
? raw.port
|
|
3337
|
+
: baseline.port);
|
|
3338
|
+
const hostname = raw.hostname === undefined
|
|
3339
|
+
? undefined
|
|
3340
|
+
: (typeof raw.hostname === "string" ? raw.hostname : baseline.hostname);
|
|
3341
|
+
return { port, ...(hostname !== undefined ? { hostname } : {}) };
|
|
3342
|
+
}
|
|
3343
|
+
|
|
3344
|
+
/**
|
|
3345
|
+
* The save entry point for every writer holding a LIVE server config.
|
|
3346
|
+
*
|
|
3347
|
+
* Conflict policy, chosen deliberately:
|
|
3348
|
+
* - disk changed, we did not → their hand edit wins;
|
|
3349
|
+
* - disk changed AND we changed → disjoint fields are merged, while a same-leaf
|
|
3350
|
+
* conflict keeps the live value;
|
|
3351
|
+
* - a provider or custom-model row deleted on disk stays deleted even if stale
|
|
3352
|
+
* live state edited that same row;
|
|
3353
|
+
* - file missing/unreadable → save what we have, no throw.
|
|
3354
|
+
*
|
|
3355
|
+
* Custom-model rows are merged by their stable `id`, preserving independent
|
|
3356
|
+
* edits and deletions across stale whole-config saves.
|
|
3357
|
+
*/
|
|
3358
|
+
export function saveConfigPreservingClaudeCode(config: OcxConfig): void {
|
|
3359
|
+
withConfigMutationLockSync(() => {
|
|
3360
|
+
const bindingBaseline = persistedLiveServerBinding.get(config);
|
|
3361
|
+
// One authoritative pre-write read feeds both the live-config reconciliation and
|
|
3362
|
+
// custom-model deletion migration. A second read could observe different bytes.
|
|
3363
|
+
const onDisk = readRawConfigJson();
|
|
3364
|
+
const baseline = liveConfigBaseline.get(config);
|
|
3365
|
+
if (baseline && onDisk !== undefined) {
|
|
3366
|
+
const persistedDiagnostics = configDiagnosticsFromRaw(JSON.stringify(onDisk));
|
|
3367
|
+
if (persistedDiagnostics.source === "file") {
|
|
3368
|
+
// Only keys this live config is actually known to have diverged on may be
|
|
3369
|
+
// rebased. The baseline is captured once when the server arms it, so any key
|
|
3370
|
+
// that appeared on disk afterwards — through saveConfig(), a hand edit, or
|
|
3371
|
+
// another process — is absent from the baseline as well as from the live
|
|
3372
|
+
// config. Reconciling those keys reads "live never changed this" and adopts
|
|
3373
|
+
// the disk value, which resurrects a field the live writer had deliberately
|
|
3374
|
+
// deleted (#1462 regression: PUT /api/grok/selection with an empty list).
|
|
3375
|
+
// Restrict the merge to keys the baseline knew about, plus keys the live
|
|
3376
|
+
// config still carries; a key that exists only on disk is left to the
|
|
3377
|
+
// ordinary whole-config write below.
|
|
3378
|
+
const rebaseableKeys = new Set([
|
|
3379
|
+
...Object.keys(baseline as unknown as Record<string, unknown>),
|
|
3380
|
+
...Object.keys(config as unknown as Record<string, unknown>),
|
|
3381
|
+
]);
|
|
3382
|
+
const skipped = new Set(["hostname", "port", "claudeCode"]);
|
|
3383
|
+
for (const key of Object.keys(persistedDiagnostics.config as unknown as Record<string, unknown>)) {
|
|
3384
|
+
if (!rebaseableKeys.has(key)) skipped.add(key);
|
|
3385
|
+
}
|
|
3386
|
+
reconcileConfigRecord(
|
|
3387
|
+
config as unknown as Record<string, unknown>,
|
|
3388
|
+
baseline as unknown as Record<string, unknown>,
|
|
3389
|
+
persistedDiagnostics.config as unknown as Record<string, unknown>,
|
|
3390
|
+
skipped,
|
|
3391
|
+
);
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
if (claudeCodeBaseline.has(config)) {
|
|
3395
|
+
if (onDisk !== undefined) {
|
|
3396
|
+
const baseline = claudeCodeBaseline.get(config);
|
|
3397
|
+
const persistedClaudeCode = normalizePersistedClaudeCode(onDisk.claudeCode);
|
|
3398
|
+
const diskChanged = !deepEqual(persistedClaudeCode, baseline);
|
|
3399
|
+
const weChanged = !deepEqual(config.claudeCode, baseline);
|
|
3400
|
+
if (diskChanged && !weChanged) {
|
|
3401
|
+
config.claudeCode = persistedClaudeCode;
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
}
|
|
3405
|
+
const projectedConfig = projectCustomModelCatalogMigration(
|
|
3406
|
+
onDisk,
|
|
3407
|
+
config,
|
|
3408
|
+
);
|
|
3409
|
+
const persistedBinding = bindingBaseline && onDisk
|
|
3410
|
+
? readPersistedServerBinding(onDisk, bindingBaseline)
|
|
3411
|
+
: bindingBaseline;
|
|
3412
|
+
if (persistedBinding) {
|
|
3413
|
+
const persistedConfig: OcxConfig = { ...projectedConfig, port: persistedBinding.port };
|
|
3414
|
+
if (persistedBinding.hostname === undefined) delete persistedConfig.hostname;
|
|
3415
|
+
else persistedConfig.hostname = persistedBinding.hostname;
|
|
3416
|
+
if (persistConfigUnlocked(persistedConfig)) bumpGenerationForCooperatingConfigWrite();
|
|
3417
|
+
persistedLiveServerBinding.set(config, persistedBinding);
|
|
3418
|
+
} else {
|
|
3419
|
+
if (persistConfigUnlocked(projectedConfig)) bumpGenerationForCooperatingConfigWrite();
|
|
3420
|
+
}
|
|
3421
|
+
adoptCustomModelCatalogMigration(config, projectedConfig);
|
|
3422
|
+
if (claudeCodeBaseline.has(config)) {
|
|
3423
|
+
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
|
|
3424
|
+
}
|
|
3425
|
+
if (liveConfigBaseline.has(config)) {
|
|
3426
|
+
liveConfigBaseline.set(config, structuredClone(config));
|
|
3427
|
+
}
|
|
3428
|
+
});
|
|
3429
|
+
}
|
|
3430
|
+
|
|
3431
|
+
export function codexAutoStartEnabled(config: Pick<OcxConfig, "codexAutoStart">): boolean {
|
|
3432
|
+
return config.codexAutoStart !== false;
|
|
3433
|
+
}
|
|
3434
|
+
|
|
3435
|
+
export const CODEX_SHIM_AUTO_RESTORE_ENV = "OPENCODEX_CODEX_SHIM_AUTO_RESTORE";
|
|
3436
|
+
|
|
3437
|
+
export function codexShimAutoRestoreEnabled(
|
|
3438
|
+
config: Pick<OcxConfig, "codexShimAutoRestore">,
|
|
3439
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
3440
|
+
): boolean {
|
|
3441
|
+
return config.codexShimAutoRestore !== false && env[CODEX_SHIM_AUTO_RESTORE_ENV] !== "0";
|
|
3442
|
+
}
|
|
3443
|
+
|
|
3444
|
+
export function multiAgentGuidanceEnabled(
|
|
3445
|
+
config: Pick<OcxConfig, "multiAgentGuidanceEnabled">,
|
|
3446
|
+
): boolean {
|
|
3447
|
+
return config.multiAgentGuidanceEnabled !== false;
|
|
3448
|
+
}
|
|
3449
|
+
|
|
3450
|
+
export function getDefaultConfig(): OcxConfig {
|
|
3451
|
+
// Fresh-install default: works out of the box with Codex's ChatGPT OAuth (no API key).
|
|
3452
|
+
// gpt-* requests forward the caller's incoming OAuth headers to the ChatGPT backend.
|
|
3453
|
+
// Adding extra providers (e.g. opencode-go) and switching defaultProvider is a user/runtime choice.
|
|
3454
|
+
return {
|
|
3455
|
+
port: 10100,
|
|
3456
|
+
emptyCompletionRetry: false,
|
|
3457
|
+
managementUsageMaxReadBytes: 64 * 1024 * 1024,
|
|
3458
|
+
appOwnedMemoryBudgetMb: DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES / (1024 * 1024),
|
|
3459
|
+
// Fresh/re-initialized configs are already written in the current three-tier
|
|
3460
|
+
// OpenAI shape. Mark them as such so startup does not mistake them for a
|
|
3461
|
+
// legacy config and collide with an immutable backup from an earlier setup.
|
|
3462
|
+
openaiProviderTierVersion: OPENAI_PROVIDER_TIER_VERSION,
|
|
3463
|
+
providers: {
|
|
3464
|
+
openai: {
|
|
3465
|
+
adapter: "openai-responses",
|
|
3466
|
+
baseUrl: "https://chatgpt.com/backend-api/codex",
|
|
3467
|
+
authMode: "forward",
|
|
3468
|
+
codexAccountMode: "pool",
|
|
3469
|
+
},
|
|
3470
|
+
},
|
|
3471
|
+
defaultProvider: "openai",
|
|
3472
|
+
subagentModels: [...DEFAULT_SUBAGENT_MODELS],
|
|
3473
|
+
multiAgentGuidanceEnabled: true,
|
|
3474
|
+
websockets: false,
|
|
3475
|
+
codexAutoStart: true,
|
|
3476
|
+
codexShimAutoRestore: true,
|
|
3477
|
+
};
|
|
3478
|
+
}
|
|
3479
|
+
|
|
3480
|
+
export function resolveEnvValue(value: string | undefined): string | undefined {
|
|
3481
|
+
if (!value) return undefined;
|
|
3482
|
+
const match = value.match(/^\$\{(\w+)\}$/);
|
|
3483
|
+
if (match) return process.env[match[1]];
|
|
3484
|
+
if (value.startsWith("$")) return process.env[value.slice(1)];
|
|
3485
|
+
return value;
|
|
3486
|
+
}
|
|
3487
|
+
|
|
3488
|
+
/**
|
|
3489
|
+
* Mirror `config.proxy` into HTTP(S)_PROXY env vars so Bun's native fetch routes every outbound
|
|
3490
|
+
* provider call through the proxy — no per-callsite changes (verified: Bun honors these plus
|
|
3491
|
+
* NO_PROXY). User-set env vars always win; localhost/127.0.0.1 are appended to NO_PROXY so the
|
|
3492
|
+
* CLI's own health checks and running-proxy API calls stay direct. Call once per process entry
|
|
3493
|
+
* that makes outbound provider requests (server start, catalog sync).
|
|
3494
|
+
*/
|
|
3495
|
+
export function applyProxyEnv(config: OcxConfig): void {
|
|
3496
|
+
const proxy = resolveEnvValue(config.proxy);
|
|
3497
|
+
if (!proxy) return;
|
|
3498
|
+
if (!process.env.HTTP_PROXY?.trim() && !process.env.http_proxy?.trim()) process.env.HTTP_PROXY = proxy;
|
|
3499
|
+
if (!process.env.HTTPS_PROXY?.trim() && !process.env.https_proxy?.trim()) process.env.HTTPS_PROXY = proxy;
|
|
3500
|
+
const existing = process.env.NO_PROXY ?? process.env.no_proxy ?? "";
|
|
3501
|
+
const entries = existing.split(",").map(s => s.trim()).filter(Boolean);
|
|
3502
|
+
const seen = new Set(entries.map(e => e.toLowerCase()));
|
|
3503
|
+
for (const host of ["localhost", "127.0.0.1", "::1", "[::1]"]) {
|
|
3504
|
+
if (!seen.has(host)) {
|
|
3505
|
+
entries.push(host);
|
|
3506
|
+
seen.add(host);
|
|
3507
|
+
}
|
|
3508
|
+
}
|
|
3509
|
+
process.env.NO_PROXY = entries.join(",");
|
|
3510
|
+
}
|
|
3511
|
+
|
|
3512
|
+
export function writePid(pid: number): void {
|
|
3513
|
+
const dir = getConfigDir();
|
|
3514
|
+
// Guard before ANY directory mutation (mkdir or chmod), not just the write.
|
|
3515
|
+
assertNotRealHomeUnderTest(dir);
|
|
3516
|
+
if (!existsSync(dir)) {
|
|
3517
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
3518
|
+
} else {
|
|
3519
|
+
hardenConfigDir();
|
|
3520
|
+
}
|
|
3521
|
+
atomicWriteFile(getPidPath(), String(pid));
|
|
3522
|
+
}
|
|
3523
|
+
|
|
3524
|
+
export type RuntimePortState = {
|
|
3525
|
+
pid: number;
|
|
3526
|
+
port: number;
|
|
3527
|
+
hostname?: string;
|
|
3528
|
+
/** Per-process proof key; protected by the config directory and never served. */
|
|
3529
|
+
attestationSecret?: string;
|
|
3530
|
+
};
|
|
3531
|
+
|
|
3532
|
+
function isValidRuntimePortState(value: unknown): value is RuntimePortState {
|
|
3533
|
+
if (!value || typeof value !== "object") return false;
|
|
3534
|
+
const state = value as Record<string, unknown>;
|
|
3535
|
+
const hostnameOk = state.hostname === undefined || typeof state.hostname === "string";
|
|
3536
|
+
const attestationOk = state.attestationSecret === undefined || isLocalAttestationSecret(state.attestationSecret);
|
|
3537
|
+
return Number.isSafeInteger(state.pid)
|
|
3538
|
+
&& Number(state.pid) > 0
|
|
3539
|
+
&& Number.isInteger(state.port)
|
|
3540
|
+
&& Number(state.port) > 0
|
|
3541
|
+
&& Number(state.port) <= 65535
|
|
3542
|
+
&& hostnameOk
|
|
3543
|
+
&& attestationOk;
|
|
3544
|
+
}
|
|
3545
|
+
|
|
3546
|
+
export function writeRuntimePort(state: RuntimePortState): void {
|
|
3547
|
+
const dir = getConfigDir();
|
|
3548
|
+
// Guard before ANY directory mutation (mkdir or chmod), not just the write.
|
|
3549
|
+
assertNotRealHomeUnderTest(dir);
|
|
3550
|
+
if (!existsSync(dir)) {
|
|
3551
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
3552
|
+
} else {
|
|
3553
|
+
hardenConfigDir();
|
|
3554
|
+
}
|
|
3555
|
+
atomicWriteFile(getRuntimePortPath(), JSON.stringify(state, null, 2) + "\n");
|
|
3556
|
+
}
|
|
3557
|
+
|
|
3558
|
+
export function readPid(): number | null {
|
|
3559
|
+
const pidPath = getPidPath();
|
|
3560
|
+
if (!existsSync(pidPath)) return null;
|
|
3561
|
+
try {
|
|
3562
|
+
const raw = readFileSync(pidPath, "utf-8").trim();
|
|
3563
|
+
const pid = parsePidFile(raw);
|
|
3564
|
+
if (pid === null) return null;
|
|
3565
|
+
try {
|
|
3566
|
+
process.kill(pid, 0);
|
|
3567
|
+
return isLikelyOcxStartProcess(pid) ? pid : null;
|
|
3568
|
+
} catch (e: unknown) {
|
|
3569
|
+
if ((e as NodeJS.ErrnoException).code === "EPERM") {
|
|
3570
|
+
return isLikelyOcxStartProcess(pid) ? pid : null;
|
|
3571
|
+
}
|
|
3572
|
+
return null;
|
|
3573
|
+
}
|
|
3574
|
+
} catch {
|
|
3575
|
+
return null;
|
|
3576
|
+
}
|
|
3577
|
+
}
|
|
3578
|
+
|
|
3579
|
+
export function readRuntimePort(expectedPid?: number): RuntimePortState | null {
|
|
3580
|
+
try {
|
|
3581
|
+
const parsed = JSON.parse(readFileSync(getRuntimePortPath(), "utf-8"));
|
|
3582
|
+
if (!isValidRuntimePortState(parsed)) return null;
|
|
3583
|
+
if (expectedPid !== undefined && parsed.pid !== expectedPid) return null;
|
|
3584
|
+
return parsed;
|
|
3585
|
+
} catch {
|
|
3586
|
+
return null;
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
|
|
3590
|
+
export function removePid(expectedPid?: number): void {
|
|
3591
|
+
if (expectedPid !== undefined && readPidFileValue() !== expectedPid) return;
|
|
3592
|
+
try {
|
|
3593
|
+
unlinkSync(getPidPath());
|
|
3594
|
+
} catch { /* ignore */ }
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
function warnConfigRepaired(configPath: string, error: z.ZodError): void {
|
|
3598
|
+
if (warnedConfigFallbacks.has(configPath)) return;
|
|
3599
|
+
warnedConfigFallbacks.add(configPath);
|
|
3600
|
+
const fields = error.issues.map(i => i.path.join(".") || "config").join(", ");
|
|
3601
|
+
console.error(`opencodex config at ${configPath}: repaired missing field(s) [${fields}] with defaults. Your providers and accounts are preserved.`);
|
|
3602
|
+
}
|
|
3603
|
+
|
|
3604
|
+
/**
|
|
3605
|
+
* Sections whose entries are independent of one another, so one bad entry is
|
|
3606
|
+
* safe to drop without changing what the rest mean.
|
|
3607
|
+
*
|
|
3608
|
+
* Both are validated entry-by-entry in the `superRefine` above, which raises
|
|
3609
|
+
* every finding as a *document*-level issue. That is what made a single routing
|
|
3610
|
+
* candidate naming a disabled provider discard the operator's whole config —
|
|
3611
|
+
* all eleven providers, every API key, and the entire `modelCosts` table —
|
|
3612
|
+
* while the proxy carried on serving from built-in defaults and reporting
|
|
3613
|
+
* healthy.
|
|
3614
|
+
*/
|
|
3615
|
+
const SALVAGEABLE_CONFIG_SECTIONS = ["routingProfiles", "combos"] as const;
|
|
3616
|
+
|
|
3617
|
+
/**
|
|
3618
|
+
* Drop just the named entries a parse failure blamed, so the rest of the
|
|
3619
|
+
* document survives.
|
|
3620
|
+
*
|
|
3621
|
+
* Returns `null` when the failure was not confined to those sections — the
|
|
3622
|
+
* caller then keeps its existing behaviour rather than guessing.
|
|
3623
|
+
*
|
|
3624
|
+
* The whole entry goes, not the individual offending candidate. A routing
|
|
3625
|
+
* profile that quietly loses one candidate still routes, just not where the
|
|
3626
|
+
* operator said it should, and a policy that silently changed shape is a worse
|
|
3627
|
+
* outcome than one that is plainly absent. Absent is also the loud option: a
|
|
3628
|
+
* dry-run against it answers `unknown_profile`, which — paired with the warning
|
|
3629
|
+
* this emits — points at the real mistake.
|
|
3630
|
+
*/
|
|
3631
|
+
function dropInvalidConfigSections(
|
|
3632
|
+
parsed: unknown,
|
|
3633
|
+
error: z.ZodError,
|
|
3634
|
+
): { candidate: Record<string, unknown>; dropped: string[] } | null {
|
|
3635
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
3636
|
+
|
|
3637
|
+
const doomed = new Map<string, Set<string>>();
|
|
3638
|
+
for (const issue of error.issues) {
|
|
3639
|
+
if (isUnsalvageableIssue(issue)) return null;
|
|
3640
|
+
const [section, id] = issue.path;
|
|
3641
|
+
if (typeof section !== "string" || typeof id !== "string") return null;
|
|
3642
|
+
if (!(SALVAGEABLE_CONFIG_SECTIONS as readonly string[]).includes(section)) return null;
|
|
3643
|
+
// A complaint about the container itself ("combos must be an object") is
|
|
3644
|
+
// not about one entry, so there is nothing selective to drop.
|
|
3645
|
+
if (issue.path.length < 2) return null;
|
|
3646
|
+
let ids = doomed.get(section);
|
|
3647
|
+
if (!ids) doomed.set(section, ids = new Set());
|
|
3648
|
+
ids.add(id);
|
|
3649
|
+
}
|
|
3650
|
+
if (doomed.size === 0) return null;
|
|
3651
|
+
|
|
3652
|
+
const candidate: Record<string, unknown> = { ...(parsed as Record<string, unknown>) };
|
|
3653
|
+
const dropped: string[] = [];
|
|
3654
|
+
for (const [section, ids] of doomed) {
|
|
3655
|
+
const current = candidate[section];
|
|
3656
|
+
if (!current || typeof current !== "object" || Array.isArray(current)) return null;
|
|
3657
|
+
const kept: Record<string, unknown> = {};
|
|
3658
|
+
for (const [key, value] of Object.entries(current as Record<string, unknown>)) {
|
|
3659
|
+
if (ids.has(key)) dropped.push(`${section}.${key}`);
|
|
3660
|
+
else kept[key] = value;
|
|
3661
|
+
}
|
|
3662
|
+
candidate[section] = kept;
|
|
3663
|
+
}
|
|
3664
|
+
return dropped.length > 0 ? { candidate, dropped } : null;
|
|
3665
|
+
}
|
|
3666
|
+
|
|
3667
|
+
/**
|
|
3668
|
+
* Salvage until the document parses, not just once.
|
|
3669
|
+
*
|
|
3670
|
+
* One pass is not enough because the sections depend on each other: routing
|
|
3671
|
+
* profiles are validated against the combo map, so dropping an invalid combo can
|
|
3672
|
+
* expose a profile that referenced it. A single-pass salvage sees that second
|
|
3673
|
+
* failure and gives up, discarding the whole config -- the exact outcome this
|
|
3674
|
+
* code exists to prevent.
|
|
3675
|
+
*
|
|
3676
|
+
* `rawDocument` is the operator's document before defaults were merged in. When
|
|
3677
|
+
* supplied, the same entries are deleted from it too, so a diagnostics caller can
|
|
3678
|
+
* still tell an absent optional setting from one we injected.
|
|
3679
|
+
*/
|
|
3680
|
+
|
|
3681
|
+
/**
|
|
3682
|
+
* Findings that must never be salvaged away.
|
|
3683
|
+
*
|
|
3684
|
+
* Salvage removes the entry a finding blamed, which is right for an ordinary
|
|
3685
|
+
* validation mistake and wrong for a namespace collision: the collision is a
|
|
3686
|
+
* *relationship* between a combo/profile and a Codex account selector, and it is
|
|
3687
|
+
* reported on the combo. Dropping that combo makes the document parse and quietly
|
|
3688
|
+
* admits the account selector the schema just refused, turning a hard admission
|
|
3689
|
+
* boundary into a config that loads. Refuse the whole document instead.
|
|
3690
|
+
*/
|
|
3691
|
+
const UNSALVAGEABLE_ISSUE_MESSAGES: readonly string[] = [
|
|
3692
|
+
CODEX_ACCOUNT_NAMESPACE_COMBO_ALIAS_COLLISION_ERROR,
|
|
3693
|
+
];
|
|
3694
|
+
|
|
3695
|
+
function isUnsalvageableIssue(issue: z.ZodIssue): boolean {
|
|
3696
|
+
return UNSALVAGEABLE_ISSUE_MESSAGES.some(message => issue.message.includes(message));
|
|
3697
|
+
}
|
|
3698
|
+
function salvageConfigCandidate(
|
|
3699
|
+
merged: unknown,
|
|
3700
|
+
initialError: z.ZodError,
|
|
3701
|
+
rawDocument?: unknown,
|
|
3702
|
+
): {
|
|
3703
|
+
candidate: Record<string, unknown>;
|
|
3704
|
+
rawCandidate: unknown;
|
|
3705
|
+
parsed: OcxConfig;
|
|
3706
|
+
dropped: string[];
|
|
3707
|
+
issues: z.ZodIssue[];
|
|
3708
|
+
} | null {
|
|
3709
|
+
let candidate: unknown = merged;
|
|
3710
|
+
let rawCandidate: unknown = rawDocument;
|
|
3711
|
+
let error = initialError;
|
|
3712
|
+
const dropped: string[] = [];
|
|
3713
|
+
const issues: z.ZodIssue[] = [];
|
|
3714
|
+
// Bounded by construction: every pass must remove at least one entry, and there
|
|
3715
|
+
// are only so many entries to remove.
|
|
3716
|
+
const budget = countSalvageableEntries(merged) + 1;
|
|
3717
|
+
for (let pass = 0; pass < budget; pass++) {
|
|
3718
|
+
const step = dropInvalidConfigSections(candidate, error);
|
|
3719
|
+
if (!step || step.dropped.length === 0) return null;
|
|
3720
|
+
dropped.push(...step.dropped);
|
|
3721
|
+
issues.push(...error.issues);
|
|
3722
|
+
candidate = step.candidate;
|
|
3723
|
+
rawCandidate = deleteEntryPaths(rawCandidate, step.dropped);
|
|
3724
|
+
const result = configSchema.safeParse(candidate);
|
|
3725
|
+
if (result.success) {
|
|
3726
|
+
return { candidate: step.candidate, rawCandidate, parsed: result.data as OcxConfig, dropped, issues };
|
|
3727
|
+
}
|
|
3728
|
+
error = result.error;
|
|
3729
|
+
}
|
|
3730
|
+
return null;
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3733
|
+
function countSalvageableEntries(document: unknown): number {
|
|
3734
|
+
if (!document || typeof document !== "object" || Array.isArray(document)) return 0;
|
|
3735
|
+
let total = 0;
|
|
3736
|
+
for (const section of SALVAGEABLE_CONFIG_SECTIONS) {
|
|
3737
|
+
const value = (document as Record<string, unknown>)[section];
|
|
3738
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
3739
|
+
total += Object.keys(value as Record<string, unknown>).length;
|
|
3740
|
+
}
|
|
3741
|
+
}
|
|
3742
|
+
return total;
|
|
3743
|
+
}
|
|
3744
|
+
|
|
3745
|
+
/** Delete `section.id` entries from a copy of the raw document. */
|
|
3746
|
+
function deleteEntryPaths(document: unknown, entryPaths: readonly string[]): unknown {
|
|
3747
|
+
if (!document || typeof document !== "object" || Array.isArray(document)) return document;
|
|
3748
|
+
const next: Record<string, unknown> = { ...(document as Record<string, unknown>) };
|
|
3749
|
+
for (const entryPath of entryPaths) {
|
|
3750
|
+
const separator = entryPath.indexOf(".");
|
|
3751
|
+
if (separator <= 0) continue;
|
|
3752
|
+
const section = entryPath.slice(0, separator);
|
|
3753
|
+
const id = entryPath.slice(separator + 1);
|
|
3754
|
+
const container = next[section];
|
|
3755
|
+
if (!container || typeof container !== "object" || Array.isArray(container)) continue;
|
|
3756
|
+
const kept: Record<string, unknown> = { ...(container as Record<string, unknown>) };
|
|
3757
|
+
delete kept[id];
|
|
3758
|
+
next[section] = kept;
|
|
3759
|
+
}
|
|
3760
|
+
return next;
|
|
3761
|
+
}
|
|
3762
|
+
|
|
3763
|
+
/**
|
|
3764
|
+
* Entry ids are operator-chosen and can be token-shaped, so nothing dynamic reaches
|
|
3765
|
+
* the log unredacted. Static section names stay readable -- they are the part that
|
|
3766
|
+
* tells the operator where to look.
|
|
3767
|
+
*/
|
|
3768
|
+
function redactEntryPath(entryPath: string): string {
|
|
3769
|
+
const separator = entryPath.indexOf(".");
|
|
3770
|
+
if (separator <= 0) return redactSecretString(entryPath);
|
|
3771
|
+
return entryPath.slice(0, separator) + "." + redactSecretString(entryPath.slice(separator + 1));
|
|
3772
|
+
}
|
|
3773
|
+
|
|
3774
|
+
function redactIssuePath(path: readonly PropertyKey[]): string {
|
|
3775
|
+
return path
|
|
3776
|
+
.map((segment, index) => (index === 0 && typeof segment === "string" ? segment : redactSecretString(String(segment))))
|
|
3777
|
+
.join(".");
|
|
3778
|
+
}
|
|
3779
|
+
|
|
3780
|
+
function warnDroppedConfigSections(configPath: string, dropped: string[], issues: readonly z.ZodIssue[]): void {
|
|
3781
|
+
if (warnedConfigFallbacks.has(configPath)) return;
|
|
3782
|
+
warnedConfigFallbacks.add(configPath);
|
|
3783
|
+
const reasons = issues
|
|
3784
|
+
.map(issue => `${redactIssuePath(issue.path)}: ${redactSecretString(issue.message)}`)
|
|
3785
|
+
.join("; ");
|
|
3786
|
+
console.error(
|
|
3787
|
+
`opencodex config at ${configPath}: dropped [${dropped.map(redactEntryPath).join(", ")}] and loaded the rest — ${reasons}. `
|
|
3788
|
+
+ "Everything else in your config, including providers and modelCosts, is preserved.",
|
|
3789
|
+
);
|
|
3790
|
+
}
|
|
3791
|
+
|
|
3792
|
+
export function readPidFileValue(): number | null {
|
|
3793
|
+
try {
|
|
3794
|
+
return parsePidFile(readFileSync(getPidPath(), "utf-8"));
|
|
3795
|
+
} catch {
|
|
3796
|
+
return null;
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3799
|
+
|
|
3800
|
+
export function removeRuntimePort(expectedPid?: number): void {
|
|
3801
|
+
if (expectedPid !== undefined && readRuntimePort(expectedPid) === null) return;
|
|
3802
|
+
try {
|
|
3803
|
+
unlinkSync(getRuntimePortPath());
|
|
3804
|
+
} catch { /* ignore */ }
|
|
3805
|
+
}
|
|
3806
|
+
|
|
3807
|
+
/**
|
|
3808
|
+
* Snapshot-guarded stale-state purge: remove the pid/runtime files only when their content
|
|
3809
|
+
* still matches what the caller saw BEFORE its liveness probe. A concurrent `ocx start` can
|
|
3810
|
+
* write fresh records mid-probe; an unconditional purge would erase the new proxy's state.
|
|
3811
|
+
*/
|
|
3812
|
+
export function removePidIfValueIs(snapshot: number | null): void {
|
|
3813
|
+
if (!existsSync(getPidPath())) return;
|
|
3814
|
+
if (readPidFileValue() !== snapshot) return;
|
|
3815
|
+
try {
|
|
3816
|
+
unlinkSync(getPidPath());
|
|
3817
|
+
} catch { /* ignore */ }
|
|
3818
|
+
}
|
|
3819
|
+
|
|
3820
|
+
export function removeRuntimePortIfPidIs(snapshotPid: number | null): void {
|
|
3821
|
+
const current = readRuntimePort();
|
|
3822
|
+
if ((current?.pid ?? null) !== snapshotPid) return;
|
|
3823
|
+
try {
|
|
3824
|
+
unlinkSync(getRuntimePortPath());
|
|
3825
|
+
} catch { /* ignore */ }
|
|
3826
|
+
}
|
|
3827
|
+
|
|
3828
|
+
export function parsePidFile(raw: string): number | null {
|
|
3829
|
+
const trimmed = raw.trim();
|
|
3830
|
+
if (!/^\d+$/.test(trimmed)) return null;
|
|
3831
|
+
const pid = Number.parseInt(trimmed, 10);
|
|
3832
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
3833
|
+
}
|
|
3834
|
+
|
|
3835
|
+
export function isOcxStartCommandLine(commandLine: string): boolean {
|
|
3836
|
+
const normalized = commandLine.toLowerCase().replace(/\\/g, "/");
|
|
3837
|
+
// "src/cli.ts" matches pre-restructure installs still running; "src/cli/index.ts" is current.
|
|
3838
|
+
// `@bitkyc08/.opencodex-*` is npm's in-place rename of the global package during
|
|
3839
|
+
// `npm install -g` — a Windows service wrapper can respawn from that temp tree
|
|
3840
|
+
// mid-update, and must still count as ocx for port reclaim.
|
|
3841
|
+
const hasOcxEntrypoint = normalized.includes("src/cli.ts")
|
|
3842
|
+
|| normalized.includes("src/cli/index.ts")
|
|
3843
|
+
|| /@[a-z0-9._-]+\/opencodex(?:[/'"\s]|$)/.test(normalized)
|
|
3844
|
+
|| /@[a-z0-9._-]+\/\.opencodex-/.test(normalized)
|
|
3845
|
+
|| /(?:^|[\s/"'])(?:ocx|opencodex)(?:\.cmd)?(?:$|[\s"'])/.test(normalized);
|
|
3846
|
+
return hasOcxEntrypoint && /(?:^|[\s"'])start(?:$|[\s"'])/.test(normalized);
|
|
3847
|
+
}
|
|
3848
|
+
|
|
3849
|
+
/** Per-process memo: waitForProxy/findLiveProxy used to spawn powershell on every 150ms poll. */
|
|
3850
|
+
const ocxStartProcessCache = new Map<number, boolean>();
|
|
3851
|
+
let ocxStartProcessSweepCursor = 0;
|
|
3852
|
+
let ocxStartProcessProbe: (pid: number) => void = pid => { process.kill(pid, 0); };
|
|
3853
|
+
|
|
3854
|
+
export function setOcxStartProcessProbeForTests(probe: ((pid: number) => void) | null): void {
|
|
3855
|
+
ocxStartProcessProbe = probe ?? (pid => { process.kill(pid, 0); });
|
|
3856
|
+
}
|
|
3857
|
+
|
|
3858
|
+
export function setOcxStartProcessCacheForTests(entries: Iterable<readonly [number, boolean]>): void {
|
|
3859
|
+
ocxStartProcessCache.clear();
|
|
3860
|
+
for (const [pid, value] of entries) ocxStartProcessCache.set(pid, value);
|
|
3861
|
+
ocxStartProcessSweepCursor = 0;
|
|
3862
|
+
}
|
|
3863
|
+
|
|
3864
|
+
export function sweepDeadOcxStartProcessCache(maxProbes = 64): number {
|
|
3865
|
+
const pids: number[] = [];
|
|
3866
|
+
let removed = 0;
|
|
3867
|
+
for (const pid of ocxStartProcessCache.keys()) {
|
|
3868
|
+
if (Number.isSafeInteger(pid) && pid > 0) pids.push(pid);
|
|
3869
|
+
else if (ocxStartProcessCache.delete(pid)) removed += 1;
|
|
3870
|
+
}
|
|
3871
|
+
if (pids.length === 0 || maxProbes <= 0) {
|
|
3872
|
+
ocxStartProcessSweepCursor = 0;
|
|
3873
|
+
return removed;
|
|
3874
|
+
}
|
|
3875
|
+
const probeCount = Math.min(Math.floor(maxProbes), pids.length);
|
|
3876
|
+
const start = ocxStartProcessSweepCursor % pids.length;
|
|
3877
|
+
for (let offset = 0; offset < probeCount; offset += 1) {
|
|
3878
|
+
const pid = pids[(start + offset) % pids.length]!;
|
|
3879
|
+
try {
|
|
3880
|
+
ocxStartProcessProbe(pid);
|
|
3881
|
+
} catch (error) {
|
|
3882
|
+
if ((error as NodeJS.ErrnoException).code !== "ESRCH") continue;
|
|
3883
|
+
if (ocxStartProcessCache.delete(pid)) removed += 1;
|
|
3884
|
+
}
|
|
3885
|
+
}
|
|
3886
|
+
ocxStartProcessSweepCursor = (start + probeCount) % pids.length;
|
|
3887
|
+
return removed;
|
|
3888
|
+
}
|
|
3889
|
+
|
|
3890
|
+
export function ocxStartProcessCacheSizeForTests(): number {
|
|
3891
|
+
return ocxStartProcessCache.size;
|
|
3892
|
+
}
|
|
3893
|
+
|
|
3894
|
+
function isLikelyOcxStartProcess(pid: number): boolean {
|
|
3895
|
+
const cached = ocxStartProcessCache.get(pid);
|
|
3896
|
+
if (cached !== undefined) return cached;
|
|
3897
|
+
const commandLine = readProcessCommandLine(pid);
|
|
3898
|
+
if (commandLine === undefined) return false;
|
|
3899
|
+
const ok = isOcxStartCommandLine(commandLine);
|
|
3900
|
+
ocxStartProcessCache.set(pid, ok);
|
|
3901
|
+
return ok;
|
|
3902
|
+
}
|
|
3903
|
+
|
|
3904
|
+
/**
|
|
3905
|
+
* Alive pid from the pid file without the expensive Windows command-line probe.
|
|
3906
|
+
* Safe for liveness polls: callers still identity-check /healthz before trusting the proxy.
|
|
3907
|
+
* Destructive stop/kill paths should keep using {@link readPid}, which verifies the cmdline.
|
|
3908
|
+
*/
|
|
3909
|
+
export function readAlivePid(): number | null {
|
|
3910
|
+
const pid = readPidFileValue();
|
|
3911
|
+
if (pid === null) return null;
|
|
3912
|
+
try {
|
|
3913
|
+
process.kill(pid, 0);
|
|
3914
|
+
return pid;
|
|
3915
|
+
} catch (e: unknown) {
|
|
3916
|
+
if ((e as NodeJS.ErrnoException).code === "EPERM") return pid;
|
|
3917
|
+
return null;
|
|
3918
|
+
}
|
|
3919
|
+
}
|
|
3920
|
+
|
|
3921
|
+
/**
|
|
3922
|
+
* Full identity check of a KNOWN candidate pid (alive + ocx-start command line).
|
|
3923
|
+
* Companion to {@link readAlivePid}: liveness discovery may be cheap, but any pid
|
|
3924
|
+
* handed to a destructive caller must pass this check — and must equal the candidate
|
|
3925
|
+
* it was asked about, so a pidfile rewrite between discovery and verification can
|
|
3926
|
+
* never swap in a different process (TOCTOU guard).
|
|
3927
|
+
*/
|
|
3928
|
+
export function verifyPidIdentity(candidatePid: number): number | null {
|
|
3929
|
+
try {
|
|
3930
|
+
process.kill(candidatePid, 0);
|
|
3931
|
+
} catch (e: unknown) {
|
|
3932
|
+
if ((e as NodeJS.ErrnoException).code !== "EPERM") return null;
|
|
3933
|
+
}
|
|
3934
|
+
return isLikelyOcxStartProcess(candidatePid) ? candidatePid : null;
|
|
3935
|
+
}
|
|
3936
|
+
|
|
3937
|
+
type ProcessCommandLineExec = (
|
|
3938
|
+
executable: string,
|
|
3939
|
+
args: string[],
|
|
3940
|
+
options: {
|
|
3941
|
+
encoding: BufferEncoding;
|
|
3942
|
+
stdio: ["ignore", "pipe", "ignore"];
|
|
3943
|
+
timeout: number;
|
|
3944
|
+
windowsHide: boolean;
|
|
3945
|
+
},
|
|
3946
|
+
) => string;
|
|
3947
|
+
|
|
3948
|
+
const defaultProcessCommandLineExec: ProcessCommandLineExec = (executable, args, options) =>
|
|
3949
|
+
execFileSync(executable, args, options);
|
|
3950
|
+
let processCommandLineExec = defaultProcessCommandLineExec;
|
|
3951
|
+
let processCommandLinePlatformForTests: NodeJS.Platform | null = null;
|
|
3952
|
+
|
|
3953
|
+
/** Test-only seam for verifying the exact system executable selected by pid identity probes. */
|
|
3954
|
+
export function setProcessCommandLineExecForTests(next: ProcessCommandLineExec | null): void {
|
|
3955
|
+
processCommandLineExec = next ?? defaultProcessCommandLineExec;
|
|
3956
|
+
}
|
|
3957
|
+
|
|
3958
|
+
/** Test-only seam so cross-platform tests do not mutate process.platform. */
|
|
3959
|
+
export function setProcessCommandLinePlatformForTests(next: NodeJS.Platform | null): void {
|
|
3960
|
+
processCommandLinePlatformForTests = next;
|
|
3961
|
+
}
|
|
3962
|
+
|
|
3963
|
+
function readProcessCommandLine(pid: number): string | undefined {
|
|
3964
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return undefined;
|
|
3965
|
+
const platform = processCommandLinePlatformForTests ?? process.platform;
|
|
3966
|
+
try {
|
|
3967
|
+
if (platform === "linux") {
|
|
3968
|
+
try {
|
|
3969
|
+
const output = readFileSync(`/proc/${pid}/cmdline`, "utf-8");
|
|
3970
|
+
const value = output.replace(/\0/g, " ").trim();
|
|
3971
|
+
if (value) return value;
|
|
3972
|
+
} catch {
|
|
3973
|
+
/* procfs unavailable — use the fixed ps fallback below */
|
|
3974
|
+
}
|
|
3975
|
+
}
|
|
3976
|
+
if (platform === "win32") {
|
|
3977
|
+
// Prefer WMIC over PowerShell: much faster cold start, and windowsHide avoids console flash.
|
|
3978
|
+
// Fall back to PowerShell when WMIC is absent (newer Windows images).
|
|
3979
|
+
const wmic = join(resolveTrustedWindowsSystemDirectory(), "wbem", "WMIC.exe");
|
|
3980
|
+
try {
|
|
3981
|
+
const output = processCommandLineExec(wmic, [
|
|
3982
|
+
"process", "where", `ProcessId=${pid}`, "get", "CommandLine", "/VALUE",
|
|
3983
|
+
], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, windowsHide: true });
|
|
3984
|
+
const match = /^CommandLine=(.*)$/m.exec(output.replace(/\r/g, ""));
|
|
3985
|
+
const value = match?.[1]?.trim();
|
|
3986
|
+
if (value) return value;
|
|
3987
|
+
} catch {
|
|
3988
|
+
/* WMIC missing or failed — fall through */
|
|
3989
|
+
}
|
|
3990
|
+
const output = processCommandLineExec(resolveTrustedWindowsPowerShellExe(), [
|
|
3991
|
+
"-NoProfile",
|
|
3992
|
+
"-NoLogo",
|
|
3993
|
+
"-NonInteractive",
|
|
3994
|
+
"-Command",
|
|
3995
|
+
`(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`,
|
|
3996
|
+
], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, windowsHide: true });
|
|
3997
|
+
return output.trim() || undefined;
|
|
3998
|
+
}
|
|
3999
|
+
for (const ps of ["/bin/ps", "/usr/bin/ps"]) {
|
|
4000
|
+
try {
|
|
4001
|
+
const output = processCommandLineExec(ps, ["-p", String(pid), "-o", "command="], {
|
|
4002
|
+
encoding: "utf-8",
|
|
4003
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
4004
|
+
timeout: 1000,
|
|
4005
|
+
windowsHide: true,
|
|
4006
|
+
});
|
|
4007
|
+
const value = output.trim();
|
|
4008
|
+
if (value) return value;
|
|
4009
|
+
} catch {
|
|
4010
|
+
/* try the other fixed system path */
|
|
4011
|
+
}
|
|
4012
|
+
}
|
|
4013
|
+
return undefined;
|
|
4014
|
+
} catch {
|
|
4015
|
+
return undefined;
|
|
4016
|
+
}
|
|
4017
|
+
}
|
|
4018
|
+
|
|
4019
|
+
function warnAndBackupInvalidConfig(configPath: string, error: unknown): void {
|
|
4020
|
+
if (warnedConfigFallbacks.has(configPath)) return;
|
|
4021
|
+
warnedConfigFallbacks.add(configPath);
|
|
4022
|
+
|
|
4023
|
+
const backupPath = backupInvalidConfig(configPath);
|
|
4024
|
+
const reason = error instanceof z.ZodError
|
|
4025
|
+
? error.issues.map(issue => `${issue.path.join(".") || "config"}: ${issue.message}`).join("; ")
|
|
4026
|
+
: error instanceof Error ? error.message : String(error);
|
|
4027
|
+
const backupNote = backupPath ? ` A backup was written to ${backupPath}.` : "";
|
|
4028
|
+
console.error(`Could not load opencodex config at ${configPath}: ${reason}. Using default config.${backupNote}`);
|
|
4029
|
+
}
|
|
4030
|
+
|
|
4031
|
+
export function backupInvalidConfig(configPath: string): string | null {
|
|
4032
|
+
if (!existsSync(configPath)) return null;
|
|
4033
|
+
const backupPath = `${configPath}.invalid-${new Date().toISOString().replace(/[:.]/g, "-")}`;
|
|
4034
|
+
try {
|
|
4035
|
+
copyFileSync(configPath, backupPath);
|
|
4036
|
+
try { chmodSync(backupPath, 0o600); } catch { /* best-effort */ }
|
|
4037
|
+
return backupPath;
|
|
4038
|
+
} catch {
|
|
4039
|
+
return null;
|
|
4040
|
+
}
|
|
4041
|
+
}
|