@iislee/opencodex 2.11.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/LICENSE +21 -0
- package/README.md +225 -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 +451 -0
- package/bin/package-main.mjs +9 -0
- package/gui/dist/assets/index-DTpMHS4F.js +67 -0
- package/gui/dist/assets/index-ZNVDE3C7.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/antigravity.svg +1 -0
- package/gui/dist/provider-icons/claude-color.svg +1 -0
- package/gui/dist/provider-icons/claude.svg +1 -0
- package/gui/dist/provider-icons/cloudflare-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/copilot-color.svg +1 -0
- package/gui/dist/provider-icons/copilot.svg +1 -0
- package/gui/dist/provider-icons/cursor-color.svg +2 -0
- package/gui/dist/provider-icons/cursor.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/gemini.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-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/kiro.svg +14 -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 +1 -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 +102 -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.ts +1003 -0
- package/src/adapters/azure.ts +36 -0
- package/src/adapters/base.ts +72 -0
- package/src/adapters/client-fingerprint.ts +59 -0
- package/src/adapters/cursor/arg-codec.ts +38 -0
- package/src/adapters/cursor/arg-normalize.ts +104 -0
- package/src/adapters/cursor/cursor-errors.ts +165 -0
- package/src/adapters/cursor/discovery.ts +276 -0
- package/src/adapters/cursor/effort-map.ts +127 -0
- package/src/adapters/cursor/exec-policy.ts +88 -0
- package/src/adapters/cursor/framing.ts +211 -0
- package/src/adapters/cursor/gen/agent_pb.ts +15274 -0
- package/src/adapters/cursor/kv-store.ts +52 -0
- package/src/adapters/cursor/live-models.ts +153 -0
- package/src/adapters/cursor/live-smoke-gate.ts +41 -0
- package/src/adapters/cursor/live-transport.ts +1214 -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 +55 -0
- package/src/adapters/cursor/native-exec-desktop.ts +184 -0
- package/src/adapters/cursor/native-exec-fs.ts +329 -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 +548 -0
- package/src/adapters/cursor/native-exec-tools.ts +118 -0
- package/src/adapters/cursor/native-exec.ts +576 -0
- package/src/adapters/cursor/protobuf-events.ts +563 -0
- package/src/adapters/cursor/protobuf-request.ts +714 -0
- package/src/adapters/cursor/request-builder.ts +255 -0
- package/src/adapters/cursor/thread-continuity.ts +67 -0
- package/src/adapters/cursor/tool-definitions.ts +505 -0
- package/src/adapters/cursor/transport-retry.ts +132 -0
- package/src/adapters/cursor/transport.ts +57 -0
- package/src/adapters/cursor/types.ts +52 -0
- package/src/adapters/cursor.ts +196 -0
- package/src/adapters/google-antigravity-replay.ts +303 -0
- package/src/adapters/google-antigravity-wire.ts +108 -0
- package/src/adapters/google-errors.ts +85 -0
- package/src/adapters/google-http.ts +100 -0
- package/src/adapters/google-tool-schema.ts +173 -0
- package/src/adapters/google-truncation.ts +13 -0
- package/src/adapters/google-wire-compiler.ts +232 -0
- package/src/adapters/google.ts +758 -0
- package/src/adapters/identity.ts +44 -0
- package/src/adapters/image.ts +23 -0
- package/src/adapters/kiro-constants.ts +16 -0
- package/src/adapters/kiro-errors.ts +197 -0
- package/src/adapters/kiro-events.ts +179 -0
- package/src/adapters/kiro-images.ts +129 -0
- package/src/adapters/kiro-retry.ts +312 -0
- package/src/adapters/kiro-thinking.ts +96 -0
- package/src/adapters/kiro-tool-fallback.ts +36 -0
- package/src/adapters/kiro-tools.ts +215 -0
- package/src/adapters/kiro-truncation.ts +33 -0
- package/src/adapters/kiro-wire.ts +129 -0
- package/src/adapters/kiro.ts +1898 -0
- package/src/adapters/mimo-free.ts +263 -0
- package/src/adapters/openai-chat.ts +1005 -0
- package/src/adapters/openai-responses.ts +1137 -0
- package/src/adapters/run-turn-queue.ts +114 -0
- package/src/adapters/tool-catalog-nudge.ts +71 -0
- package/src/adapters/upstream-http-error.ts +48 -0
- package/src/bridge.ts +1619 -0
- package/src/chat/inbound.ts +295 -0
- package/src/chat/outbound.ts +765 -0
- package/src/claude/agents-inject.ts +243 -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 +189 -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 +381 -0
- package/src/claude/desktop-health.ts +26 -0
- package/src/claude/desktop-profile.ts +263 -0
- package/src/claude/gateway-cache.ts +70 -0
- package/src/claude/inbound-debug.ts +163 -0
- package/src/claude/inbound.ts +509 -0
- package/src/claude/model-info.ts +151 -0
- package/src/claude/outbound.ts +872 -0
- package/src/cli/access.ts +108 -0
- package/src/cli/account-api.ts +268 -0
- package/src/cli/account-auth.ts +223 -0
- package/src/cli/account-extended.ts +350 -0
- package/src/cli/account.ts +275 -0
- package/src/cli/agent-driven.ts +70 -0
- package/src/cli/agent.ts +184 -0
- package/src/cli/catalog-prewarm.ts +27 -0
- package/src/cli/claude-desktop.ts +188 -0
- package/src/cli/claude.ts +286 -0
- package/src/cli/codex-shim-autorestore.ts +45 -0
- package/src/cli/combo.ts +119 -0
- package/src/cli/config-command.ts +145 -0
- package/src/cli/debug.ts +228 -0
- package/src/cli/doctor.ts +930 -0
- package/src/cli/export-command.ts +187 -0
- package/src/cli/help.ts +354 -0
- package/src/cli/index.ts +1113 -0
- package/src/cli/init.ts +224 -0
- package/src/cli/integrations.ts +142 -0
- package/src/cli/interactive-confirm.ts +133 -0
- package/src/cli/internal-dispatch.ts +20 -0
- package/src/cli/models-runtime.ts +212 -0
- package/src/cli/models.ts +336 -0
- package/src/cli/observe.ts +117 -0
- package/src/cli/opencode.ts +586 -0
- package/src/cli/pi.ts +188 -0
- package/src/cli/provider-runtime.ts +162 -0
- package/src/cli/provider.ts +463 -0
- package/src/cli/runtime-api.ts +325 -0
- package/src/cli/star-prompt.ts +155 -0
- package/src/cli/status-oauth.ts +78 -0
- package/src/cli/status.ts +321 -0
- package/src/cli/sync-cloud.ts +283 -0
- package/src/cli/system-command.ts +112 -0
- package/src/cli/tray-proxy.ts +52 -0
- package/src/cli/v2.ts +173 -0
- package/src/cli.ts +10 -0
- package/src/clients/config-export.ts +377 -0
- package/src/clients/effective-status.ts +385 -0
- package/src/clients/probes/agy.ts +55 -0
- package/src/clients/probes/cc-switch.ts +110 -0
- package/src/clients/probes/claude.ts +90 -0
- package/src/clients/probes/codex.ts +125 -0
- package/src/clients/probes/grok.ts +29 -0
- package/src/clients/probes/opencode.ts +109 -0
- package/src/clients/probes/paseo.ts +55 -0
- package/src/clients/probes/pi.ts +55 -0
- package/src/cloud/onedrive-auth.ts +666 -0
- package/src/cloud/onedrive-graph.ts +108 -0
- package/src/cloud/settings.ts +75 -0
- package/src/cloud/sync.ts +212 -0
- package/src/cloud/types.ts +56 -0
- package/src/cloud/vault.ts +89 -0
- package/src/codex/account-id.ts +34 -0
- package/src/codex/account-label.ts +34 -0
- package/src/codex/account-lifecycle.ts +55 -0
- package/src/codex/account-namespace-match.ts +63 -0
- package/src/codex/account-namespaces.ts +149 -0
- package/src/codex/account-pause.ts +20 -0
- package/src/codex/account-runtime-state.ts +31 -0
- package/src/codex/account-store.ts +517 -0
- package/src/codex/account-usability.ts +20 -0
- package/src/codex/app-server-processes.ts +756 -0
- package/src/codex/auth-api.ts +1540 -0
- package/src/codex/auth-collision.ts +107 -0
- package/src/codex/auth-context.ts +352 -0
- package/src/codex/autostart-health.ts +149 -0
- package/src/codex/catalog/aggregation.ts +378 -0
- package/src/codex/catalog/bundled.ts +251 -0
- package/src/codex/catalog/effort.ts +355 -0
- package/src/codex/catalog/metadata.ts +180 -0
- package/src/codex/catalog/parsing.ts +456 -0
- package/src/codex/catalog/provider-fetch.ts +902 -0
- package/src/codex/catalog/sync.ts +620 -0
- package/src/codex/catalog.ts +12 -0
- package/src/codex/data/upstream-models.json +830 -0
- package/src/codex/exec-invocation.ts +22 -0
- package/src/codex/features.ts +969 -0
- package/src/codex/history-migration-guardian.ts +102 -0
- package/src/codex/history-provider.ts +776 -0
- package/src/codex/home.ts +206 -0
- package/src/codex/inject.ts +799 -0
- package/src/codex/injected-marker.ts +72 -0
- package/src/codex/journal.ts +163 -0
- package/src/codex/main-account-cache.ts +32 -0
- package/src/codex/main-account.ts +40 -0
- package/src/codex/model-cache.ts +227 -0
- package/src/codex/paths.ts +65 -0
- package/src/codex/plugins-doctor.ts +242 -0
- package/src/codex/pool-rotation.ts +225 -0
- package/src/codex/project-config-warnings.ts +411 -0
- package/src/codex/quota.ts +411 -0
- package/src/codex/refresh.ts +53 -0
- package/src/codex/routing.ts +1477 -0
- package/src/codex/runtime.ts +538 -0
- package/src/codex/shim.ts +1189 -0
- package/src/codex/subagent-defaults.ts +550 -0
- package/src/codex/subagent-model-fallback.ts +469 -0
- package/src/codex/sync.ts +130 -0
- package/src/codex/warmup.ts +192 -0
- package/src/codex/websocket-registry.ts +100 -0
- package/src/combos/failover.ts +140 -0
- package/src/combos/index.ts +41 -0
- package/src/combos/request.ts +62 -0
- package/src/combos/resolve.ts +232 -0
- package/src/combos/types.ts +326 -0
- package/src/config.ts +2356 -0
- package/src/generated/jawcode-model-metadata.ts +104 -0
- package/src/github/star-state.ts +203 -0
- package/src/grok/inject.ts +545 -0
- package/src/grok/status.ts +121 -0
- package/src/grok/sync.ts +103 -0
- package/src/grok/usage-hook/report.mjs +348 -0
- package/src/grok/usage-hook.ts +278 -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 +829 -0
- package/src/images/plan.ts +133 -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/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 +173 -0
- package/src/lib/app-owned-memory.ts +265 -0
- package/src/lib/bounded-body.ts +202 -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 +71 -0
- package/src/lib/bun-stream-caps.ts +126 -0
- package/src/lib/config-ownership.ts +360 -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 +316 -0
- package/src/lib/errors.ts +364 -0
- package/src/lib/eventstream-decoder.ts +253 -0
- package/src/lib/gcp-adc.ts +341 -0
- package/src/lib/injection-debug-log.ts +58 -0
- package/src/lib/open-url.ts +25 -0
- package/src/lib/pinned-http.ts +151 -0
- package/src/lib/privacy.ts +20 -0
- package/src/lib/process-control.ts +165 -0
- package/src/lib/provider-outbound.ts +170 -0
- package/src/lib/provider-url.ts +14 -0
- package/src/lib/proxy-env.ts +18 -0
- package/src/lib/redact.ts +105 -0
- package/src/lib/retry-after.ts +55 -0
- package/src/lib/service-secrets.ts +25 -0
- package/src/lib/shadow-call.ts +30 -0
- package/src/lib/sidecar-tracker.ts +52 -0
- package/src/lib/sse-decoder.ts +323 -0
- package/src/lib/state-store-registrations.ts +109 -0
- package/src/lib/state-store-sweeper.ts +184 -0
- package/src/lib/test-home-guard.ts +90 -0
- package/src/lib/token-estimate.ts +69 -0
- package/src/lib/translator-budget.ts +356 -0
- package/src/lib/upstream-retry.ts +239 -0
- package/src/lib/win-exec.ts +115 -0
- package/src/lib/win-paths.ts +68 -0
- package/src/lib/windows-elevation.ts +705 -0
- package/src/lib/windows-secret-acl.ts +514 -0
- package/src/lib/winsw.ts +375 -0
- package/src/oauth/anthropic-routing.ts +594 -0
- package/src/oauth/anthropic.ts +177 -0
- package/src/oauth/callback-server.ts +294 -0
- package/src/oauth/chatgpt.ts +150 -0
- package/src/oauth/cursor.ts +211 -0
- package/src/oauth/github-copilot.ts +428 -0
- package/src/oauth/google-antigravity.ts +230 -0
- package/src/oauth/health.ts +399 -0
- package/src/oauth/index.ts +1174 -0
- package/src/oauth/key-providers.ts +108 -0
- package/src/oauth/kimi.ts +213 -0
- package/src/oauth/kiro-credentials.ts +726 -0
- package/src/oauth/kiro.ts +577 -0
- package/src/oauth/local-token-detect.ts +121 -0
- package/src/oauth/log.ts +48 -0
- package/src/oauth/login-cli.ts +163 -0
- package/src/oauth/pkce.ts +15 -0
- package/src/oauth/store.ts +630 -0
- package/src/oauth/token-guardian.ts +303 -0
- package/src/oauth/types.ts +62 -0
- package/src/oauth/xai.ts +241 -0
- package/src/pi/extensions.ts +72 -0
- package/src/pi/home.ts +42 -0
- package/src/pi/index.ts +40 -0
- package/src/pi/models.ts +278 -0
- package/src/pi/packages.ts +219 -0
- package/src/pi/settings.ts +365 -0
- package/src/pi/status.ts +68 -0
- package/src/pi/sync.ts +75 -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 +205 -0
- package/src/providers/api-keys.ts +140 -0
- package/src/providers/base-url-choices.ts +64 -0
- package/src/providers/context-cap.ts +65 -0
- package/src/providers/derive.ts +339 -0
- package/src/providers/free-directory.ts +184 -0
- package/src/providers/github-copilot-transport.ts +56 -0
- package/src/providers/key-failover.ts +203 -0
- package/src/providers/kiro-models.ts +67 -0
- package/src/providers/label.ts +19 -0
- package/src/providers/model-discovery.ts +356 -0
- package/src/providers/openai-sidecar.ts +175 -0
- package/src/providers/openai-tier-startup.ts +27 -0
- package/src/providers/openai-tiers.ts +301 -0
- package/src/providers/openai-virtual-models.ts +82 -0
- package/src/providers/openrouter-routing.ts +102 -0
- package/src/providers/provider-id-rewrite.ts +150 -0
- package/src/providers/quota.ts +1260 -0
- package/src/providers/registry.ts +1600 -0
- package/src/providers/slug-codec.ts +67 -0
- package/src/providers/xai-transport.ts +141 -0
- package/src/reasoning-effort.ts +135 -0
- package/src/responses/compaction.ts +117 -0
- package/src/responses/parser.ts +656 -0
- package/src/responses/reasoning-envelope.ts +52 -0
- package/src/responses/schema.ts +159 -0
- package/src/responses/spill-store.ts +394 -0
- package/src/responses/state.ts +895 -0
- package/src/responses/tool-groups.ts +19 -0
- package/src/router.ts +425 -0
- package/src/server/adapter-resolve.ts +80 -0
- package/src/server/auth-cors.ts +530 -0
- package/src/server/chat-completions.ts +368 -0
- package/src/server/claude-messages.ts +914 -0
- package/src/server/effort-policy.ts +172 -0
- package/src/server/gui-static.ts +123 -0
- package/src/server/image-retry.ts +42 -0
- package/src/server/images.ts +476 -0
- package/src/server/index.ts +1126 -0
- package/src/server/lifecycle.ts +227 -0
- package/src/server/live.ts +598 -0
- package/src/server/management/agent-settings-routes.ts +1169 -0
- package/src/server/management/api-access.ts +141 -0
- package/src/server/management/api-key-usage.ts +167 -0
- package/src/server/management/body.ts +35 -0
- package/src/server/management/clients-routes.ts +63 -0
- package/src/server/management/cloud-sync-routes.ts +266 -0
- package/src/server/management/combo-routes.ts +220 -0
- package/src/server/management/config-routes.ts +422 -0
- package/src/server/management/context.ts +31 -0
- package/src/server/management/logs-usage-routes.ts +707 -0
- package/src/server/management/model-routes.ts +525 -0
- package/src/server/management/oauth-account-routes.ts +563 -0
- package/src/server/management/provider-routes.ts +556 -0
- package/src/server/management/shared.ts +277 -0
- package/src/server/management/sidebar-routes.ts +90 -0
- package/src/server/management/system-restart.ts +179 -0
- package/src/server/management/system-routes.ts +117 -0
- package/src/server/management/usage-summary-cache.ts +86 -0
- package/src/server/management-api.ts +215 -0
- package/src/server/management-auth.ts +267 -0
- package/src/server/memory-watchdog.ts +156 -0
- package/src/server/port-reclaim.ts +307 -0
- package/src/server/ports.ts +116 -0
- package/src/server/proxy-liveness.ts +201 -0
- package/src/server/relay-eager.ts +313 -0
- package/src/server/relay.ts +1049 -0
- package/src/server/request-decompress.ts +132 -0
- package/src/server/request-log-conversation.ts +168 -0
- package/src/server/request-log.ts +1046 -0
- package/src/server/responses/collaboration.ts +354 -0
- package/src/server/responses/compact.ts +384 -0
- package/src/server/responses/core.ts +2758 -0
- package/src/server/responses/encrypted-payload.ts +308 -0
- package/src/server/responses/fetch-helpers.ts +157 -0
- package/src/server/responses/passthrough-error.ts +78 -0
- package/src/server/responses/terminal-guard.ts +230 -0
- package/src/server/responses/upstream-error.ts +48 -0
- package/src/server/responses-image-gen-repair.ts +132 -0
- package/src/server/responses-item-id-repair.ts +224 -0
- package/src/server/responses.ts +9 -0
- package/src/server/search.ts +136 -0
- package/src/server/sse-payload-rewrite.ts +175 -0
- package/src/server/startup-action-control.ts +308 -0
- package/src/server/startup-health-cache.ts +113 -0
- package/src/server/system-env.ts +413 -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 +471 -0
- package/src/service.ts +2554 -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 +290 -0
- package/src/tray/windows.ts +730 -0
- package/src/types.ts +1237 -0
- package/src/update/badge.ts +72 -0
- package/src/update/index.ts +407 -0
- package/src/update/job.ts +1520 -0
- package/src/update/notify.ts +257 -0
- package/src/update/npm-invocation.d.mts +23 -0
- package/src/update/npm-invocation.mjs +94 -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 +0 -0
- package/src/usage/debug.ts +97 -0
- package/src/usage/expected-prices.ts +164 -0
- package/src/usage/log.ts +658 -0
- package/src/usage/summary.ts +585 -0
- package/src/usage/totals.ts +14 -0
- package/src/vision/anthropic-describe.ts +185 -0
- package/src/vision/describe.ts +125 -0
- package/src/vision/index.ts +467 -0
- package/src/web-search/anthropic-executor.ts +189 -0
- package/src/web-search/executor.ts +105 -0
- package/src/web-search/format-result.ts +89 -0
- package/src/web-search/index.ts +196 -0
- package/src/web-search/loop.ts +664 -0
- package/src/web-search/parse.ts +220 -0
- package/src/web-search/progress-stream.ts +342 -0
- package/src/web-search/synthetic-tool.ts +47 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,2356 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { chmodSync, copyFileSync, existsSync, linkSync, mkdirSync, readFileSync, renameSync, truncateSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { Database } from "bun:sqlite";
|
|
7
|
+
import * as z from "zod/v4";
|
|
8
|
+
import {
|
|
9
|
+
CODEX_ACCOUNT_NAMESPACE_COMBO_ALIAS_COLLISION_ERROR,
|
|
10
|
+
codexAccountNamespaceForModel,
|
|
11
|
+
codexProviderNamespaceKey,
|
|
12
|
+
isValidCodexAccountNamespaceTarget,
|
|
13
|
+
MAIN_CODEX_ACCOUNT_NAMESPACE_TARGET,
|
|
14
|
+
} from "./codex/account-namespace-match";
|
|
15
|
+
import { COMBO_NAMESPACE, comboConfigIssues } from "./combos/types";
|
|
16
|
+
import {
|
|
17
|
+
forgetHardenedSecretPath,
|
|
18
|
+
hardenSecretDir,
|
|
19
|
+
hardenSecretPath,
|
|
20
|
+
hardenSecretPathAsync,
|
|
21
|
+
windowsSecretAclApplies,
|
|
22
|
+
} from "./lib/windows-secret-acl";
|
|
23
|
+
import { recordOwnedConfigPath } from "./lib/config-ownership";
|
|
24
|
+
import { assertNotRealHomeUnderTest } from "./lib/test-home-guard";
|
|
25
|
+
import { providerDestinationConfigError } from "./lib/destination-policy";
|
|
26
|
+
import { openRouterRoutingConfigError } from "./providers/openrouter-routing";
|
|
27
|
+
import {
|
|
28
|
+
isWirePinnedModel,
|
|
29
|
+
MODEL_ADAPTER_OVERRIDE_ALLOWED,
|
|
30
|
+
OPENAI_PROVIDER_TIER_VERSION,
|
|
31
|
+
REASONING_SUMMARY_DELIVERY_VALUES,
|
|
32
|
+
type OcxClaudeCodeConfig,
|
|
33
|
+
type OcxConfig,
|
|
34
|
+
type OcxApiKeyEntry,
|
|
35
|
+
type OcxProviderConfig,
|
|
36
|
+
} from "./types";
|
|
37
|
+
import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "./providers/openai-tiers";
|
|
38
|
+
import { parseDesktopProfile } from "./claude/desktop-profile";
|
|
39
|
+
import { isCodexReasoningEffort, modelRecordValue } from "./reasoning-effort";
|
|
40
|
+
import {
|
|
41
|
+
DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES,
|
|
42
|
+
MAX_APP_OWNED_MEMORY_BUDGET_MB,
|
|
43
|
+
MIN_APP_OWNED_MEMORY_BUDGET_MB,
|
|
44
|
+
} from "./lib/app-owned-memory";
|
|
45
|
+
|
|
46
|
+
let _atomicSeq = 0;
|
|
47
|
+
|
|
48
|
+
interface AtomicRenameIO {
|
|
49
|
+
platform: NodeJS.Platform;
|
|
50
|
+
rename: (source: string, destination: string) => void;
|
|
51
|
+
sleep: (milliseconds: number) => void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function renameAtomicFile(
|
|
55
|
+
source: string,
|
|
56
|
+
destination: string,
|
|
57
|
+
io: AtomicRenameIO = {
|
|
58
|
+
platform: process.platform,
|
|
59
|
+
rename: renameSync,
|
|
60
|
+
sleep: Bun.sleepSync,
|
|
61
|
+
},
|
|
62
|
+
): void {
|
|
63
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
64
|
+
try {
|
|
65
|
+
io.rename(source, destination);
|
|
66
|
+
return;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
69
|
+
const transientWindowsError = io.platform === "win32"
|
|
70
|
+
&& (code === "EBUSY" || code === "EPERM" || code === "EACCES");
|
|
71
|
+
if (!transientWindowsError || attempt >= 2) throw error;
|
|
72
|
+
io.sleep(25 * (attempt + 1));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Write a file atomically (temp + rename) so concurrent writers — e.g. `ocx stop` and the
|
|
79
|
+
* proxy's own shutdown handler both restoring Codex — can never leave a half-written file.
|
|
80
|
+
*/
|
|
81
|
+
export interface AtomicWriteIO {
|
|
82
|
+
write: (path: string, content: string) => void;
|
|
83
|
+
harden: (path: string) => void;
|
|
84
|
+
rename: (source: string, destination: string) => void;
|
|
85
|
+
truncate: (path: string) => void;
|
|
86
|
+
unlink: (path: string) => void;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export class AtomicWriteResidualTempError extends Error {
|
|
90
|
+
constructor(readonly tempPath: string, readonly hardened = true, options?: ErrorOptions) {
|
|
91
|
+
super(`Atomic config write left a ${hardened ? "hardened " : ""}zero-byte temporary file`, options);
|
|
92
|
+
this.name = "AtomicWriteResidualTempError";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export class AtomicWriteSecretResidualError extends Error {
|
|
97
|
+
constructor(readonly tempPath: string, options?: ErrorOptions) {
|
|
98
|
+
super("Atomic config write could not scrub or remove a secret-bearing temporary file", options);
|
|
99
|
+
this.name = "AtomicWriteSecretResidualError";
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isMissingPathError(error: unknown): boolean {
|
|
104
|
+
return (error as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function atomicWriteFile(path: string, content: string, io: AtomicWriteIO = {
|
|
108
|
+
write: (target, value) => writeFileSync(target, value, { encoding: "utf-8", mode: 0o600 }),
|
|
109
|
+
harden: target => {
|
|
110
|
+
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
111
|
+
if (process.platform === "win32") hardenSecretPath(target, { required: true });
|
|
112
|
+
},
|
|
113
|
+
rename: renameAtomicFile,
|
|
114
|
+
truncate: target => truncateSync(target, 0),
|
|
115
|
+
unlink: unlinkSync,
|
|
116
|
+
}): void {
|
|
117
|
+
recordOwnedConfigPath(resolveConfigDir(), path);
|
|
118
|
+
const tmp = `${path}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
119
|
+
let hardened = false;
|
|
120
|
+
try {
|
|
121
|
+
io.write(tmp, content);
|
|
122
|
+
io.harden(tmp);
|
|
123
|
+
hardened = true;
|
|
124
|
+
io.rename(tmp, path);
|
|
125
|
+
forgetHardenedSecretPath(tmp);
|
|
126
|
+
} catch (cause) {
|
|
127
|
+
let scrubbed = false;
|
|
128
|
+
try {
|
|
129
|
+
io.truncate(tmp);
|
|
130
|
+
scrubbed = true;
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (isMissingPathError(error)) scrubbed = true;
|
|
133
|
+
else {
|
|
134
|
+
try { io.write(tmp, ""); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
let removed = false;
|
|
138
|
+
try {
|
|
139
|
+
io.unlink(tmp);
|
|
140
|
+
removed = true;
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (isMissingPathError(error)) removed = true;
|
|
143
|
+
else {
|
|
144
|
+
try { io.unlink(tmp); removed = true; }
|
|
145
|
+
catch (retryError) { if (isMissingPathError(retryError)) removed = true; }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!removed && !scrubbed) throw new AtomicWriteSecretResidualError(tmp, { cause });
|
|
149
|
+
if (!removed && !hardened) {
|
|
150
|
+
try { io.harden(tmp); hardened = true; } catch { /* zero-byte residual is reported honestly */ }
|
|
151
|
+
}
|
|
152
|
+
if (removed) forgetHardenedSecretPath(tmp);
|
|
153
|
+
if (!removed) throw new AtomicWriteResidualTempError(tmp, hardened, { cause });
|
|
154
|
+
throw cause;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Async atomic-write I/O: harden may await icacls without blocking the event loop (#612). */
|
|
159
|
+
export interface AtomicWriteAsyncIO {
|
|
160
|
+
write: (path: string, content: string) => void | Promise<void>;
|
|
161
|
+
harden: (path: string) => void | Promise<void>;
|
|
162
|
+
rename: (source: string, destination: string) => void | Promise<void>;
|
|
163
|
+
truncate: (path: string) => void | Promise<void>;
|
|
164
|
+
unlink: (path: string) => void | Promise<void>;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function renameAtomicFileAsync(source: string, destination: string): Promise<void> {
|
|
168
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
169
|
+
try {
|
|
170
|
+
renameSync(source, destination);
|
|
171
|
+
return;
|
|
172
|
+
} catch (error) {
|
|
173
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
174
|
+
const transientWindowsError = process.platform === "win32"
|
|
175
|
+
&& (code === "EBUSY" || code === "EPERM" || code === "EACCES");
|
|
176
|
+
if (!transientWindowsError || attempt >= 2) throw error;
|
|
177
|
+
await Bun.sleep(25 * (attempt + 1));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Async atomic write (#612): same temp+harden+rename and residual-temp policy as
|
|
184
|
+
* atomicWriteFile, but Windows ACL harden yields the event loop. Timeout memo is keyed
|
|
185
|
+
* by the final destination path (not the unique temp, not the parent directory).
|
|
186
|
+
*/
|
|
187
|
+
export async function atomicWriteFileAsync(
|
|
188
|
+
path: string,
|
|
189
|
+
content: string,
|
|
190
|
+
io?: AtomicWriteAsyncIO,
|
|
191
|
+
): Promise<void> {
|
|
192
|
+
const effective: AtomicWriteAsyncIO = io ?? {
|
|
193
|
+
write: (target, value) => writeFileSync(target, value, { encoding: "utf-8", mode: 0o600 }),
|
|
194
|
+
harden: async target => {
|
|
195
|
+
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
196
|
+
if (process.platform === "win32") {
|
|
197
|
+
await hardenSecretPathAsync(target, { required: true, timeoutMemoKey: path });
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
rename: renameAtomicFileAsync,
|
|
201
|
+
truncate: target => truncateSync(target, 0),
|
|
202
|
+
unlink: unlinkSync,
|
|
203
|
+
};
|
|
204
|
+
const tmp = `${path}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
205
|
+
let hardened = false;
|
|
206
|
+
try {
|
|
207
|
+
await effective.write(tmp, content);
|
|
208
|
+
await effective.harden(tmp);
|
|
209
|
+
hardened = true;
|
|
210
|
+
await effective.rename(tmp, path);
|
|
211
|
+
forgetHardenedSecretPath(tmp);
|
|
212
|
+
} catch (cause) {
|
|
213
|
+
let scrubbed = false;
|
|
214
|
+
try {
|
|
215
|
+
await effective.truncate(tmp);
|
|
216
|
+
scrubbed = true;
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (isMissingPathError(error)) scrubbed = true;
|
|
219
|
+
else {
|
|
220
|
+
try { await effective.write(tmp, ""); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
let removed = false;
|
|
224
|
+
try {
|
|
225
|
+
await effective.unlink(tmp);
|
|
226
|
+
removed = true;
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (isMissingPathError(error)) removed = true;
|
|
229
|
+
else {
|
|
230
|
+
try { await effective.unlink(tmp); removed = true; }
|
|
231
|
+
catch (retryError) { if (isMissingPathError(retryError)) removed = true; }
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (!removed && !scrubbed) throw new AtomicWriteSecretResidualError(tmp, { cause });
|
|
235
|
+
if (!removed && !hardened) {
|
|
236
|
+
try { await effective.harden(tmp); hardened = true; } catch { /* zero-byte residual is reported honestly */ }
|
|
237
|
+
}
|
|
238
|
+
if (removed) forgetHardenedSecretPath(tmp);
|
|
239
|
+
if (!removed) throw new AtomicWriteResidualTempError(tmp, hardened, { cause });
|
|
240
|
+
throw cause;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export class OpenAiTierBackupCleanupError extends Error {
|
|
245
|
+
constructor() { super("OpenAI tier backup temporary cleanup failed"); this.name = "OpenAiTierBackupCleanupError"; }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export class OpenAiTierBackupRollbackError extends Error {
|
|
249
|
+
constructor() { super("OpenAI tier backup rollback failed"); this.name = "OpenAiTierBackupRollbackError"; }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export class OpenAiTierBackupCollisionError extends Error {
|
|
253
|
+
constructor() { super("Existing OpenAI tier backup differs from the current config"); this.name = "OpenAiTierBackupCollisionError"; }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export class OpenAiTierBackupSecretResidualError extends Error {
|
|
257
|
+
constructor(readonly tempPath: string, options?: ErrorOptions) {
|
|
258
|
+
super("OpenAI tier backup could not scrub or remove a secret-bearing temporary file", options);
|
|
259
|
+
this.name = "OpenAiTierBackupSecretResidualError";
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export interface OpenAiTierBackupIO {
|
|
264
|
+
exists(path: string): boolean;
|
|
265
|
+
read(path: string): Uint8Array;
|
|
266
|
+
createExclusive(path: string): void;
|
|
267
|
+
write(path: string, bytes: Uint8Array): void;
|
|
268
|
+
harden(path: string): void;
|
|
269
|
+
publishNoReplace(temp: string, backup: string): void;
|
|
270
|
+
truncate(path: string): void;
|
|
271
|
+
unlink(path: string): void;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function sameBytes(left: Uint8Array, right: Uint8Array): boolean {
|
|
275
|
+
return left.byteLength === right.byteLength && left.every((value, index) => value === right[index]);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function isAlreadyExistsError(error: unknown): boolean {
|
|
279
|
+
return (error as NodeJS.ErrnoException | undefined)?.code === "EEXIST";
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Classify an existing `.pre-openai-tiers-v2.bak` snapshot.
|
|
284
|
+
*
|
|
285
|
+
* - `"stale"`: unparseable JSON (not written by us / truncated) or already a
|
|
286
|
+
* post-migration (tier v2) snapshot — safe to delete or replace.
|
|
287
|
+
* - `"rollback"`: parses as a valid pre-migration (v1) config — a
|
|
288
|
+
* user-intentional rollback point that must never be silently destroyed.
|
|
289
|
+
*
|
|
290
|
+
* Shared by the startup migration backup path and `ocx init` cleanup so both
|
|
291
|
+
* apply the same preservation policy (issue #257 / sol review 260722).
|
|
292
|
+
*/
|
|
293
|
+
export function classifyOpenAiTierBackup(backupBytes: Uint8Array): "stale" | "rollback" {
|
|
294
|
+
try {
|
|
295
|
+
// Use Buffer.from to ensure proper UTF-8 decoding from Uint8Array/Buffer.
|
|
296
|
+
const parsed = JSON.parse(Buffer.from(backupBytes).toString("utf8")) as Record<string, unknown>;
|
|
297
|
+
return parsed.openaiProviderTierVersion === 2 ? "stale" : "rollback";
|
|
298
|
+
} catch {
|
|
299
|
+
// Unparseable: not a config file we created, treat as stale.
|
|
300
|
+
return "stale";
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function backupConfigBeforeOpenAiTierMigration(
|
|
305
|
+
configPath = getConfigPath(),
|
|
306
|
+
io: OpenAiTierBackupIO = {
|
|
307
|
+
exists: existsSync,
|
|
308
|
+
read: target => readFileSync(target),
|
|
309
|
+
createExclusive: target => { writeFileSync(target, new Uint8Array(), { flag: "wx", mode: 0o600 }); },
|
|
310
|
+
write: (target, bytes) => writeFileSync(target, bytes),
|
|
311
|
+
harden: target => {
|
|
312
|
+
try { chmodSync(target, 0o600); } catch { /* platform may ignore chmod */ }
|
|
313
|
+
// Soft-fail: a wedged/failed icacls on CI temp volumes must not abort
|
|
314
|
+
// startServer mid-suite (timeout + EBUSY cascade on shared TEST_DIR).
|
|
315
|
+
// chmod above still applies; live credential writes keep required:true.
|
|
316
|
+
if (process.platform === "win32") hardenSecretPath(target, { required: false });
|
|
317
|
+
},
|
|
318
|
+
publishNoReplace: (temp, backup) => linkSync(temp, backup),
|
|
319
|
+
truncate: target => truncateSync(target, 0),
|
|
320
|
+
unlink: unlinkSync,
|
|
321
|
+
},
|
|
322
|
+
): "absent" | "created" | "reused" {
|
|
323
|
+
const source = configPath;
|
|
324
|
+
if (!io.exists(source)) return "absent";
|
|
325
|
+
const original = io.read(source);
|
|
326
|
+
// v2 snapshot path. The historical `.pre-openai-tiers-v1.bak` is read only by restore
|
|
327
|
+
// docs/fixtures and is never reused or overwritten as the v2 snapshot.
|
|
328
|
+
const backup = `${source}.pre-openai-tiers-v2.bak`;
|
|
329
|
+
if (io.exists(backup)) {
|
|
330
|
+
if (!sameBytes(original, io.read(backup))) {
|
|
331
|
+
// The backup differs from the current config. Only treat it as stale when it is
|
|
332
|
+
// clearly not a user-intentional rollback point:
|
|
333
|
+
// - unparseable JSON: written by a different tool or truncated
|
|
334
|
+
// - already at tier version 2: the backup is from a post-migration config (e.g.
|
|
335
|
+
// ocx init wrote a fresh v2 config, making the old backup obsolete)
|
|
336
|
+
// A backup that parses as a valid pre-migration (v1) config is kept as-is and
|
|
337
|
+
// we throw a collision error, because silently replacing a user-created rollback
|
|
338
|
+
// point would be surprising and potentially destructive.
|
|
339
|
+
const backupBytes = io.read(backup);
|
|
340
|
+
if (classifyOpenAiTierBackup(backupBytes) === "rollback") {
|
|
341
|
+
throw new OpenAiTierBackupCollisionError();
|
|
342
|
+
}
|
|
343
|
+
console.warn("[openai-provider-migration] Replacing stale pre-migration backup (post-migration config was rewritten since last migration).");
|
|
344
|
+
io.unlink(backup);
|
|
345
|
+
} else {
|
|
346
|
+
return "reused";
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const temp = `${backup}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
|
|
350
|
+
let published = false;
|
|
351
|
+
let cleanupAttempted = false;
|
|
352
|
+
|
|
353
|
+
const scrubUnpublishedTemp = (): void => {
|
|
354
|
+
cleanupAttempted = true;
|
|
355
|
+
let scrubbed = false;
|
|
356
|
+
try {
|
|
357
|
+
io.truncate(temp);
|
|
358
|
+
scrubbed = true;
|
|
359
|
+
} catch (error) {
|
|
360
|
+
if (isMissingPathError(error)) scrubbed = true;
|
|
361
|
+
else {
|
|
362
|
+
try { io.write(temp, new Uint8Array()); scrubbed = true; } catch { /* removal may still succeed */ }
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
let removed = false;
|
|
366
|
+
try {
|
|
367
|
+
io.unlink(temp);
|
|
368
|
+
removed = true;
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (isMissingPathError(error)) {
|
|
371
|
+
removed = true;
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
try { io.unlink(temp); removed = true; }
|
|
375
|
+
catch (retryError) {
|
|
376
|
+
if (isMissingPathError(retryError)) {
|
|
377
|
+
removed = true;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (removed) forgetHardenedSecretPath(temp);
|
|
383
|
+
if (!removed && !scrubbed) throw new OpenAiTierBackupSecretResidualError(temp);
|
|
384
|
+
if (!removed) throw new OpenAiTierBackupCleanupError();
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
try {
|
|
388
|
+
io.createExclusive(temp);
|
|
389
|
+
io.write(temp, original);
|
|
390
|
+
io.harden(temp);
|
|
391
|
+
try {
|
|
392
|
+
io.publishNoReplace(temp, backup);
|
|
393
|
+
} catch (cause) {
|
|
394
|
+
if (!isAlreadyExistsError(cause)) throw cause;
|
|
395
|
+
const winner = io.read(backup);
|
|
396
|
+
if (!sameBytes(original, winner)) throw new OpenAiTierBackupCollisionError();
|
|
397
|
+
scrubUnpublishedTemp();
|
|
398
|
+
return "reused";
|
|
399
|
+
}
|
|
400
|
+
published = true;
|
|
401
|
+
try {
|
|
402
|
+
io.unlink(temp);
|
|
403
|
+
forgetHardenedSecretPath(temp);
|
|
404
|
+
} catch (firstError) {
|
|
405
|
+
if (isMissingPathError(firstError)) {
|
|
406
|
+
forgetHardenedSecretPath(temp);
|
|
407
|
+
} else try {
|
|
408
|
+
io.unlink(temp);
|
|
409
|
+
forgetHardenedSecretPath(temp);
|
|
410
|
+
} catch (secondError) {
|
|
411
|
+
if (isMissingPathError(secondError)) {
|
|
412
|
+
forgetHardenedSecretPath(temp);
|
|
413
|
+
return "created";
|
|
414
|
+
}
|
|
415
|
+
// temp and backup are hard links to the same inode. Roll back the backup
|
|
416
|
+
// link before any truncation so the downgrade snapshot is never zeroed.
|
|
417
|
+
try { io.unlink(backup); } catch { throw new OpenAiTierBackupRollbackError(); }
|
|
418
|
+
published = false;
|
|
419
|
+
scrubUnpublishedTemp();
|
|
420
|
+
throw new OpenAiTierBackupCleanupError();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return "created";
|
|
424
|
+
} catch (cause) {
|
|
425
|
+
if (!published && !cleanupAttempted) {
|
|
426
|
+
scrubUnpublishedTemp();
|
|
427
|
+
}
|
|
428
|
+
throw cause;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Expand a leading `~` to the home directory in user-supplied paths
|
|
434
|
+
* (OPENCODEX_HOME/CODEX_HOME set from GUIs/service files where no shell expanded it).
|
|
435
|
+
* `~user` and `%VAR%`/`$VAR` forms pass through untouched — those belong to the shell.
|
|
436
|
+
*/
|
|
437
|
+
export function expandUserPath(raw: string): string {
|
|
438
|
+
if (raw === "~") return homedir();
|
|
439
|
+
if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(homedir(), raw.slice(2));
|
|
440
|
+
return raw;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
let resolvedConfigDirCache: { raw: string | undefined; path: string } | null = null;
|
|
444
|
+
|
|
445
|
+
function resolveConfigDir(): string {
|
|
446
|
+
const raw = process.env["OPENCODEX_HOME"]?.trim() || undefined;
|
|
447
|
+
if (resolvedConfigDirCache && resolvedConfigDirCache.raw === raw) return resolvedConfigDirCache.path;
|
|
448
|
+
const path = raw ? resolve(expandUserPath(raw)) : join(homedir(), ".opencodex");
|
|
449
|
+
resolvedConfigDirCache = { raw, path };
|
|
450
|
+
return path;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function resolveConfigPath(): string {
|
|
454
|
+
return join(resolveConfigDir(), "config.json");
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function resolvePidPath(): string {
|
|
458
|
+
return join(resolveConfigDir(), "ocx.pid");
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function resolveRuntimePortPath(): string {
|
|
462
|
+
return join(resolveConfigDir(), "runtime-port.json");
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const warnedConfigFallbacks = new Set<string>();
|
|
466
|
+
let lastWarningReconciledGeneration = 0;
|
|
467
|
+
|
|
468
|
+
export function reconcileConfigWarningMemos(generation: number): number {
|
|
469
|
+
if (generation <= lastWarningReconciledGeneration) return 0;
|
|
470
|
+
const removed = warnedConfigFallbacks.size;
|
|
471
|
+
warnedConfigFallbacks.clear();
|
|
472
|
+
lastWarningReconciledGeneration = generation;
|
|
473
|
+
return removed;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const providerConfigSchema = z.object({
|
|
477
|
+
adapter: z.string().min(1),
|
|
478
|
+
baseUrl: z.string().min(1),
|
|
479
|
+
mcpMaxTools: z.number().int().positive().optional(),
|
|
480
|
+
mcpMaxSchemaBytes: z.number().int().positive().optional(),
|
|
481
|
+
mcpMaxResultBytes: z.number().int().positive().optional(),
|
|
482
|
+
apiKeyTransport: z.enum(["x-api-key", "bearer"]).optional(),
|
|
483
|
+
responsesPath: z.string().min(1).optional(),
|
|
484
|
+
statelessResponses: z.boolean().optional(),
|
|
485
|
+
allowPrivateNetwork: z.boolean().optional(),
|
|
486
|
+
codexAccountMode: z.enum(["pool", "direct"]).optional(),
|
|
487
|
+
responsesItemIdRepair: z.object({
|
|
488
|
+
message: z.array(z.string().min(1)).optional(),
|
|
489
|
+
reasoning: z.array(z.string().min(1)).optional(),
|
|
490
|
+
repairMissingTerminalIds: z.boolean().optional(),
|
|
491
|
+
}).strict().optional(),
|
|
492
|
+
}).passthrough();
|
|
493
|
+
|
|
494
|
+
const RESERVED_PROVIDER_NAMES = new Set(["__proto__", "prototype", "constructor"]);
|
|
495
|
+
const PROVIDER_NAME_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62}[A-Za-z0-9])?$/;
|
|
496
|
+
const HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
497
|
+
const SENSITIVE_PROVIDER_HEADERS = new Set([
|
|
498
|
+
"authorization",
|
|
499
|
+
"cookie",
|
|
500
|
+
"set-cookie",
|
|
501
|
+
"proxy-authorization",
|
|
502
|
+
"x-api-key",
|
|
503
|
+
"x-goog-api-key",
|
|
504
|
+
"x-amz-security-token",
|
|
505
|
+
]);
|
|
506
|
+
|
|
507
|
+
export function isValidProviderName(name: string): boolean {
|
|
508
|
+
const trimmed = name.trim();
|
|
509
|
+
return trimmed === name
|
|
510
|
+
&& PROVIDER_NAME_PATTERN.test(name)
|
|
511
|
+
&& !RESERVED_PROVIDER_NAMES.has(name.toLowerCase());
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export function hasOwnProvider(providers: Record<string, unknown>, name: string): boolean {
|
|
515
|
+
return Object.prototype.hasOwnProperty.call(providers, name);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export function providerBaseUrlConfigError(baseUrl: string): string | null {
|
|
519
|
+
try {
|
|
520
|
+
const parsed = new URL(baseUrl.trim());
|
|
521
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "baseUrl must be an http(s) URL";
|
|
522
|
+
if (parsed.username || parsed.password) return "baseUrl must not include embedded credentials";
|
|
523
|
+
if (parsed.search || parsed.hash) return "baseUrl must not include query strings or fragments";
|
|
524
|
+
} catch {
|
|
525
|
+
return "baseUrl must be a valid URL";
|
|
526
|
+
}
|
|
527
|
+
return null;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function providerResponsesPathConfigError(responsesPath: string | undefined): string | null {
|
|
531
|
+
if (responsesPath === undefined) return null;
|
|
532
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(responsesPath) || responsesPath.includes("://")) {
|
|
533
|
+
return "responsesPath must be a relative path without a URL scheme";
|
|
534
|
+
}
|
|
535
|
+
if (!responsesPath.startsWith("/")) return "responsesPath must start with /";
|
|
536
|
+
if (responsesPath.includes("?") || responsesPath.includes("#")) {
|
|
537
|
+
return "responsesPath must not include query strings or fragments";
|
|
538
|
+
}
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export function providerHeadersConfigError(headers: unknown): string | null {
|
|
543
|
+
if (headers === undefined) return null;
|
|
544
|
+
if (!headers || typeof headers !== "object" || Array.isArray(headers)) return "headers must be an object";
|
|
545
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
546
|
+
const normalized = name.trim().toLowerCase();
|
|
547
|
+
if (!normalized || !HEADER_NAME_PATTERN.test(name)) return "headers must use valid HTTP header names";
|
|
548
|
+
if (SENSITIVE_PROVIDER_HEADERS.has(normalized)) return `headers must not include sensitive header "${name}"; use apiKey/authMode instead`;
|
|
549
|
+
if (typeof value !== "string") return `header "${name}" value must be a string`;
|
|
550
|
+
if (/[\r\n]/.test(value)) return `header "${name}" value must not include line breaks`;
|
|
551
|
+
}
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Keep the configured API-key header style scoped to Anthropic-compatible key auth. */
|
|
556
|
+
export function apiKeyTransportConfigError(
|
|
557
|
+
provider: Pick<OcxProviderConfig, "adapter" | "authMode" | "apiKeyTransport">,
|
|
558
|
+
): string | null {
|
|
559
|
+
if (provider.apiKeyTransport === undefined) return null;
|
|
560
|
+
if (provider.apiKeyTransport !== "x-api-key" && provider.apiKeyTransport !== "bearer") {
|
|
561
|
+
return 'apiKeyTransport must be "x-api-key" or "bearer"';
|
|
562
|
+
}
|
|
563
|
+
if (provider.adapter !== "anthropic") {
|
|
564
|
+
return "apiKeyTransport is supported only by the anthropic adapter";
|
|
565
|
+
}
|
|
566
|
+
if (provider.authMode === "oauth" || provider.authMode === "forward" || provider.authMode === "local") {
|
|
567
|
+
return "apiKeyTransport requires Anthropic API-key authentication";
|
|
568
|
+
}
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
export function positiveIntegerRecordConfigError(value: unknown, field: string): string | null {
|
|
573
|
+
if (value === undefined) return null;
|
|
574
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
575
|
+
const prototype = Object.getPrototypeOf(value);
|
|
576
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
577
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
578
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
579
|
+
if (typeof entry !== "number" || !Number.isFinite(entry) || !Number.isInteger(entry) || entry <= 0) {
|
|
580
|
+
return `${field}.${key} must be a positive finite integer`;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
export function positiveIntegerConfigError(value: unknown, field: string): string | null {
|
|
587
|
+
if (value === undefined) return null;
|
|
588
|
+
if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
|
|
589
|
+
return `${field} must be a positive finite integer`;
|
|
590
|
+
}
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
export function booleanRecordConfigError(value: unknown, field: string): string | null {
|
|
595
|
+
if (value === undefined) return null;
|
|
596
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
597
|
+
const prototype = Object.getPrototypeOf(value);
|
|
598
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
599
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
600
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
601
|
+
if (typeof entry !== "boolean") return `${field}.${key} must be a boolean`;
|
|
602
|
+
}
|
|
603
|
+
return null;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
const REASONING_SUMMARY_DELIVERY_SET = new Set<string>(REASONING_SUMMARY_DELIVERY_VALUES);
|
|
607
|
+
|
|
608
|
+
export function reasoningSummaryDeliveryRecordConfigError(
|
|
609
|
+
value: unknown,
|
|
610
|
+
supportsReasoningSummaries: unknown,
|
|
611
|
+
field = "modelReasoningSummaryDelivery",
|
|
612
|
+
): string | null {
|
|
613
|
+
if (value === undefined) return null;
|
|
614
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
615
|
+
const prototype = Object.getPrototypeOf(value);
|
|
616
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
617
|
+
|
|
618
|
+
const supports = booleanRecordConfigError(supportsReasoningSummaries, "modelSupportsReasoningSummaries") === null
|
|
619
|
+
&& supportsReasoningSummaries && typeof supportsReasoningSummaries === "object"
|
|
620
|
+
? supportsReasoningSummaries as Record<string, boolean>
|
|
621
|
+
: undefined;
|
|
622
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
623
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
624
|
+
if (typeof entry !== "string" || !REASONING_SUMMARY_DELIVERY_SET.has(entry)) {
|
|
625
|
+
return `${field}.${key} must be one of: ${REASONING_SUMMARY_DELIVERY_VALUES.join(", ")}`;
|
|
626
|
+
}
|
|
627
|
+
if (modelRecordValue(supports, key) === false) {
|
|
628
|
+
return `${field}.${key} conflicts with modelSupportsReasoningSummaries=false`;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
return null;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Validate a provider's per-model wire override map (#404).
|
|
636
|
+
*
|
|
637
|
+
* Rejects, rather than silently ignoring, configurations the resolver would refuse:
|
|
638
|
+
* a value outside the allowed wires, a model the upstream pins to one wire, and any
|
|
639
|
+
* override on a canonical forward provider (where switching wires would drop the
|
|
640
|
+
* caller's forwarded credential). Silently dropping them would leave the user
|
|
641
|
+
* believing an override is in effect.
|
|
642
|
+
*/
|
|
643
|
+
export function modelAdapterRecordConfigError(
|
|
644
|
+
value: unknown,
|
|
645
|
+
field: string,
|
|
646
|
+
providerName: string,
|
|
647
|
+
provider: { adapter?: unknown; authMode?: unknown; baseUrl?: unknown },
|
|
648
|
+
): string | null {
|
|
649
|
+
if (value === undefined) return null;
|
|
650
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${field} must be a plain object`;
|
|
651
|
+
const prototype = Object.getPrototypeOf(value);
|
|
652
|
+
if (prototype !== Object.prototype && prototype !== null) return `${field} must be a plain object with own properties`;
|
|
653
|
+
const entries = Object.entries(value);
|
|
654
|
+
if (entries.length > 0 && isCanonicalOpenAiForwardProvider(provider as OcxProviderConfig)) {
|
|
655
|
+
return `${field} is not supported on the canonical ChatGPT forward provider`;
|
|
656
|
+
}
|
|
657
|
+
for (const [key, entry] of entries) {
|
|
658
|
+
if (!key.trim()) return `${field} keys must be nonblank model ids`;
|
|
659
|
+
if (typeof entry !== "string" || !MODEL_ADAPTER_OVERRIDE_ALLOWED.has(entry)) {
|
|
660
|
+
return `${field}.${key} must be one of: ${[...MODEL_ADAPTER_OVERRIDE_ALLOWED].join(", ")}`;
|
|
661
|
+
}
|
|
662
|
+
if (isWirePinnedModel(providerName, key.trim())) {
|
|
663
|
+
return `${field}.${key} cannot be overridden: the upstream only speaks one wire for this model`;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return null;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
const CODEX_ACCOUNT_NAMESPACES_RECORD_ERROR =
|
|
670
|
+
"codexAccountNamespaces must be a plain object mapping account selectors to Codex account ids";
|
|
671
|
+
const CODEX_ACCOUNT_NAMESPACE_KEY_ERROR =
|
|
672
|
+
"account selectors must use 1-64 letters, numbers, dots, underscores, or hyphens and cannot be reserved JavaScript object keys";
|
|
673
|
+
const CODEX_ACCOUNT_NAMESPACE_TARGET_ERROR =
|
|
674
|
+
"account selector targets must be @main or valid Codex pool-account ids";
|
|
675
|
+
const CODEX_ACCOUNT_NAMESPACE_ACCOUNT_ID_COLLISION_ERROR =
|
|
676
|
+
"account selectors must not collide with configured Codex pool-account ids or account selector targets";
|
|
677
|
+
|
|
678
|
+
function configuredCodexPoolAccountIds(value: unknown): Set<string> {
|
|
679
|
+
const accountIds = new Set<string>();
|
|
680
|
+
if (!Array.isArray(value)) return accountIds;
|
|
681
|
+
for (const account of value) {
|
|
682
|
+
if (!account || typeof account !== "object" || Array.isArray(account)) continue;
|
|
683
|
+
const { id, isMain } = account as { id?: unknown; isMain?: unknown };
|
|
684
|
+
if (typeof id === "string" && isMain !== true) accountIds.add(id);
|
|
685
|
+
}
|
|
686
|
+
return accountIds;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const codexAccountNamespacesSchema = z.custom<Record<string, unknown>>(
|
|
690
|
+
(value): value is Record<string, unknown> => !!value
|
|
691
|
+
&& typeof value === "object"
|
|
692
|
+
&& !Array.isArray(value)
|
|
693
|
+
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null),
|
|
694
|
+
{ error: CODEX_ACCOUNT_NAMESPACES_RECORD_ERROR },
|
|
695
|
+
).superRefine((accountNamespaces, ctx) => {
|
|
696
|
+
// Inspect raw own entries before z.record parses them; Zod omits __proto__ record keys.
|
|
697
|
+
for (const [namespace, accountId] of Object.entries(accountNamespaces)) {
|
|
698
|
+
if (!isValidProviderName(namespace)) {
|
|
699
|
+
ctx.addIssue({
|
|
700
|
+
code: "custom",
|
|
701
|
+
path: [namespace],
|
|
702
|
+
message: CODEX_ACCOUNT_NAMESPACE_KEY_ERROR,
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
if (!isValidCodexAccountNamespaceTarget(accountId)) {
|
|
706
|
+
ctx.addIssue({
|
|
707
|
+
code: "custom",
|
|
708
|
+
path: [namespace],
|
|
709
|
+
message: CODEX_ACCOUNT_NAMESPACE_TARGET_ERROR,
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}).pipe(z.record(z.string(), z.string()));
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Deliberately permissive. A user's config is not ours to invalidate: a strict
|
|
717
|
+
* entry fails the whole parse, and loadConfig's fallback then backs the file up
|
|
718
|
+
* and returns defaults — losing providers and pool accounts because one key name
|
|
719
|
+
* was too long. Length and charset rules live at the POST/PATCH boundary, where
|
|
720
|
+
* rejecting produces a 400 instead. `.passthrough()` keeps unknown per-key
|
|
721
|
+
* properties across a load -> mutate -> save round trip.
|
|
722
|
+
*
|
|
723
|
+
* Only `key` is load-bearing: admission compares that string and nothing else
|
|
724
|
+
* (src/server/auth-cors.ts isDataPlaneAdmissionSecret). So the secret is the one
|
|
725
|
+
* field that must be a usable string, and every piece of metadata around it
|
|
726
|
+
* degrades instead of taking the credential down with it. Dropping a working key
|
|
727
|
+
* because its `name` was hand-edited to a number would be a silent revocation —
|
|
728
|
+
* and on a remote bind, potentially a server that refuses to start.
|
|
729
|
+
*
|
|
730
|
+
* "Usable" matches admission exactly. The presented token is trimmed before the
|
|
731
|
+
* comparison but the stored value is not, so a key with surrounding whitespace
|
|
732
|
+
* can never match either form of itself. Keeping one would be worse than dropping
|
|
733
|
+
* it: `system-env.ts` and `cli/claude.ts` hand `apiKeys[0].key` to launched
|
|
734
|
+
* clients, so a junk first entry would mask a valid later one.
|
|
735
|
+
*/
|
|
736
|
+
const apiKeyEntrySchema = z.object({
|
|
737
|
+
key: z.string().refine(isUsableApiKeySecret),
|
|
738
|
+
// Degrades to "" here; every schema consumer then runs `normalizeApiKeyIds`,
|
|
739
|
+
// which fills it deterministically so the id is stable across loads.
|
|
740
|
+
id: z.string().catch(""),
|
|
741
|
+
name: z.string().catch(""),
|
|
742
|
+
createdAt: z.string().catch(""),
|
|
743
|
+
}).passthrough();
|
|
744
|
+
|
|
745
|
+
const configSchema = z.object({
|
|
746
|
+
port: z.number().int().min(0).max(65535).default(10100),
|
|
747
|
+
managementUsageMaxReadBytes: z.number().int().positive().default(64 * 1024 * 1024),
|
|
748
|
+
appOwnedMemoryBudgetMb: z.number().int()
|
|
749
|
+
.min(MIN_APP_OWNED_MEMORY_BUDGET_MB)
|
|
750
|
+
.max(MAX_APP_OWNED_MEMORY_BUDGET_MB)
|
|
751
|
+
.default(DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES / (1024 * 1024))
|
|
752
|
+
.catch(DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES / (1024 * 1024)),
|
|
753
|
+
// A blank hostname degrades to undefined rather than failing the parse. `getDefaultConfig()`
|
|
754
|
+
// carries no `hostname` key, so the backup-and-defaults repair path below cannot merge one
|
|
755
|
+
// away — a hand-edited `"hostname": ""` would fail twice and reset providers/apiKeys to
|
|
756
|
+
// defaults, which is strictly worse than the bind bug this validation exists for. Degrading
|
|
757
|
+
// is safe: startServer() already falls back to 127.0.0.1 for a missing hostname. Write-time
|
|
758
|
+
// rejection lives in validateConfigCandidate() so bad values still surface to the caller.
|
|
759
|
+
hostname: z.string().trim().min(1).optional().catch(undefined),
|
|
760
|
+
providers: z.record(z.string(), providerConfigSchema),
|
|
761
|
+
defaultProvider: z.string().min(1).default("openai"),
|
|
762
|
+
openaiProviderTierVersion: z.union([z.literal(1), z.literal(2)]).optional(),
|
|
763
|
+
// Invalid hand edits must not discard an otherwise usable config. Treat them as
|
|
764
|
+
// pre-migration so startup can safely re-run the one-time normalization.
|
|
765
|
+
googleAntigravityStaticCatalogVersion: z.literal(1).optional().catch(undefined),
|
|
766
|
+
providerContextCaps: z.record(z.string(), z.number().int().positive()).optional(),
|
|
767
|
+
contextCapValue: z.number().int().positive().optional(),
|
|
768
|
+
multiAgentGuidanceEnabled: z.boolean().optional(),
|
|
769
|
+
// These selections pre-date schema validation and used to pass through as
|
|
770
|
+
// unknown fields. Invalid hand edits must disable only the optional
|
|
771
|
+
// delegation/native-default feature, not reject the whole config and hide
|
|
772
|
+
// otherwise valid providers, accounts, or the configured listen port.
|
|
773
|
+
injectionModel: z.string().optional().catch(undefined),
|
|
774
|
+
injectionEffort: z.string().optional().catch(undefined),
|
|
775
|
+
syncCodexSubagentDefaults: z.boolean().optional().catch(undefined),
|
|
776
|
+
codexShimAutoRestore: z.boolean().optional(),
|
|
777
|
+
pausedCodexAccountIds: z.array(z.string().regex(/^[a-zA-Z0-9._-]{1,64}$/)).optional(),
|
|
778
|
+
codexAccountNamespaces: codexAccountNamespacesSchema.optional(),
|
|
779
|
+
// Model ids excluded from the Grok Build managed block (dashboard switches).
|
|
780
|
+
grokExcludedModels: z.array(z.string()).optional(),
|
|
781
|
+
// Invalid values degrade to undefined ("auto") instead of failing the whole
|
|
782
|
+
// parse: a hand-edited typo must never trip the backup-and-defaults repair
|
|
783
|
+
// path below and wipe providers/pool accounts. Warning emitted in loadConfig.
|
|
784
|
+
streamMode: z.enum(["auto", "legacy-tee", "eager-relay"]).optional().catch(undefined),
|
|
785
|
+
// Same degrade-don't-reject rationale as the fields above: a hand-edited
|
|
786
|
+
// non-string must not trip the backup-and-defaults repair path. Unset then
|
|
787
|
+
// takes the canonical sideband path (src/server/live.ts normalizeSidebandRoot).
|
|
788
|
+
experimentalRealtimeWsBaseUrl: z.string().optional().catch(undefined),
|
|
789
|
+
// Salvage element by element, and never fail the parse. Two spellings were
|
|
790
|
+
// measured on this zod version and both lose data:
|
|
791
|
+
// `z.array(entry).catch(undefined)` -> one bad entry discards EVERY key
|
|
792
|
+
// `z.array(z.unknown())` -> a non-array value still raises
|
|
793
|
+
// invalid_type, reaching the
|
|
794
|
+
// backup-and-defaults repair path
|
|
795
|
+
// Starting from `unknown` is what makes both survivable. A key the user still
|
|
796
|
+
// has deployed must not be collateral damage for one bad neighbour, and on a
|
|
797
|
+
// remote bind an emptied array is worse than cosmetic: assertServerAuthConfig
|
|
798
|
+
// refuses to start without a data credential.
|
|
799
|
+
apiKeys: z.unknown().optional().transform(value => {
|
|
800
|
+
if (value === undefined) return undefined;
|
|
801
|
+
if (!Array.isArray(value)) return undefined;
|
|
802
|
+
return value
|
|
803
|
+
.filter(row => apiKeyEntrySchema.safeParse(row).success)
|
|
804
|
+
.map(row => apiKeyEntrySchema.parse(row) as OcxApiKeyEntry);
|
|
805
|
+
}),
|
|
806
|
+
}).passthrough().superRefine((config, ctx) => {
|
|
807
|
+
const claudeCode = (config as { claudeCode?: unknown }).claudeCode;
|
|
808
|
+
if (claudeCode !== undefined && (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode))) {
|
|
809
|
+
ctx.addIssue({ code: "custom", path: ["claudeCode"], message: "claudeCode must be an object" });
|
|
810
|
+
} else if (claudeCode) {
|
|
811
|
+
const claude = claudeCode as { desktopProfile?: unknown };
|
|
812
|
+
if (claude.desktopProfile !== undefined) {
|
|
813
|
+
try {
|
|
814
|
+
parseDesktopProfile(claude.desktopProfile);
|
|
815
|
+
} catch (error) {
|
|
816
|
+
ctx.addIssue({
|
|
817
|
+
code: "custom",
|
|
818
|
+
path: ["claudeCode", "desktopProfile"],
|
|
819
|
+
message: error instanceof Error ? error.message : String(error),
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
const accountNamespaces = config.codexAccountNamespaces;
|
|
826
|
+
if (accountNamespaces) {
|
|
827
|
+
const configuredAccountIds = configuredCodexPoolAccountIds(config.codexAccounts);
|
|
828
|
+
const configuredProviderNamespaces = new Set([
|
|
829
|
+
COMBO_NAMESPACE,
|
|
830
|
+
OPENAI_CODEX_PROVIDER_ID,
|
|
831
|
+
...Object.keys(config.providers),
|
|
832
|
+
].map(codexProviderNamespaceKey));
|
|
833
|
+
const namespaceTargets = new Set(
|
|
834
|
+
Object.values(accountNamespaces)
|
|
835
|
+
.filter(accountId => accountId !== MAIN_CODEX_ACCOUNT_NAMESPACE_TARGET),
|
|
836
|
+
);
|
|
837
|
+
for (const namespace of Object.keys(accountNamespaces)) {
|
|
838
|
+
if (configuredProviderNamespaces.has(codexProviderNamespaceKey(namespace))) {
|
|
839
|
+
ctx.addIssue({
|
|
840
|
+
code: "custom",
|
|
841
|
+
path: ["codexAccountNamespaces", namespace],
|
|
842
|
+
message: "account selectors must not collide with configured provider or combo namespaces",
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
if (configuredAccountIds.has(namespace) || namespaceTargets.has(namespace)) {
|
|
846
|
+
ctx.addIssue({
|
|
847
|
+
code: "custom",
|
|
848
|
+
path: ["codexAccountNamespaces", namespace],
|
|
849
|
+
message: CODEX_ACCOUNT_NAMESPACE_ACCOUNT_ID_COLLISION_ERROR,
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
for (const name of Object.keys(config.providers)) {
|
|
855
|
+
if (!isValidProviderName(name)) {
|
|
856
|
+
ctx.addIssue({
|
|
857
|
+
code: "custom",
|
|
858
|
+
path: ["providers", name],
|
|
859
|
+
message: "provider names must use letters, numbers, dot, underscore, or hyphen and cannot be reserved JavaScript object keys",
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
const provider = config.providers[name];
|
|
863
|
+
const openRouterRoutingError = openRouterRoutingConfigError(provider);
|
|
864
|
+
if (openRouterRoutingError) {
|
|
865
|
+
ctx.addIssue({
|
|
866
|
+
code: "custom",
|
|
867
|
+
path: [
|
|
868
|
+
"providers",
|
|
869
|
+
name,
|
|
870
|
+
openRouterRoutingError.startsWith("modelOpenRouterRouting")
|
|
871
|
+
? "modelOpenRouterRouting"
|
|
872
|
+
: "openRouterRouting",
|
|
873
|
+
],
|
|
874
|
+
message: openRouterRoutingError,
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
if (Object.hasOwn(provider, "virtualModels")) {
|
|
878
|
+
ctx.addIssue({
|
|
879
|
+
code: "custom",
|
|
880
|
+
path: ["providers", name, "virtualModels"],
|
|
881
|
+
message: "virtualModels is registry-only and must not be persisted",
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
const baseUrlError = providerBaseUrlConfigError(provider.baseUrl);
|
|
885
|
+
if (baseUrlError) {
|
|
886
|
+
ctx.addIssue({
|
|
887
|
+
code: "custom",
|
|
888
|
+
path: ["providers", name, "baseUrl"],
|
|
889
|
+
message: baseUrlError,
|
|
890
|
+
});
|
|
891
|
+
} else {
|
|
892
|
+
const destinationError = providerDestinationConfigError(name, provider);
|
|
893
|
+
if (destinationError) {
|
|
894
|
+
ctx.addIssue({
|
|
895
|
+
code: "custom",
|
|
896
|
+
path: ["providers", name, "baseUrl"],
|
|
897
|
+
message: destinationError,
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const responsesPathError = providerResponsesPathConfigError(provider.responsesPath);
|
|
902
|
+
if (responsesPathError) {
|
|
903
|
+
ctx.addIssue({
|
|
904
|
+
code: "custom",
|
|
905
|
+
path: ["providers", name, "responsesPath"],
|
|
906
|
+
message: responsesPathError,
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
const headersError = providerHeadersConfigError((provider as { headers?: unknown }).headers);
|
|
910
|
+
if (headersError) {
|
|
911
|
+
ctx.addIssue({
|
|
912
|
+
code: "custom",
|
|
913
|
+
path: ["providers", name, "headers"],
|
|
914
|
+
message: headersError,
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
const apiKeyTransportError = apiKeyTransportConfigError(provider as OcxProviderConfig);
|
|
918
|
+
if (apiKeyTransportError) {
|
|
919
|
+
ctx.addIssue({
|
|
920
|
+
code: "custom",
|
|
921
|
+
path: ["providers", name, "apiKeyTransport"],
|
|
922
|
+
message: apiKeyTransportError,
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
const modelAdaptersError = modelAdapterRecordConfigError(
|
|
926
|
+
(provider as { modelAdapters?: unknown }).modelAdapters,
|
|
927
|
+
"modelAdapters",
|
|
928
|
+
name,
|
|
929
|
+
provider,
|
|
930
|
+
);
|
|
931
|
+
if (modelAdaptersError) {
|
|
932
|
+
ctx.addIssue({
|
|
933
|
+
code: "custom",
|
|
934
|
+
path: ["providers", name, "modelAdapters"],
|
|
935
|
+
message: modelAdaptersError,
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
const maxInputError = positiveIntegerRecordConfigError(
|
|
939
|
+
(provider as { modelMaxInputTokens?: unknown }).modelMaxInputTokens,
|
|
940
|
+
"modelMaxInputTokens",
|
|
941
|
+
);
|
|
942
|
+
if (maxInputError) {
|
|
943
|
+
ctx.addIssue({
|
|
944
|
+
code: "custom",
|
|
945
|
+
path: ["providers", name, "modelMaxInputTokens"],
|
|
946
|
+
message: maxInputError,
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
const reasoningSummariesError = booleanRecordConfigError(
|
|
950
|
+
(provider as { modelSupportsReasoningSummaries?: unknown }).modelSupportsReasoningSummaries,
|
|
951
|
+
"modelSupportsReasoningSummaries",
|
|
952
|
+
);
|
|
953
|
+
if (reasoningSummariesError) {
|
|
954
|
+
ctx.addIssue({
|
|
955
|
+
code: "custom",
|
|
956
|
+
path: ["providers", name, "modelSupportsReasoningSummaries"],
|
|
957
|
+
message: reasoningSummariesError,
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
const reasoningSummaryDeliveryError = reasoningSummaryDeliveryRecordConfigError(
|
|
961
|
+
(provider as { modelReasoningSummaryDelivery?: unknown }).modelReasoningSummaryDelivery,
|
|
962
|
+
(provider as { modelSupportsReasoningSummaries?: unknown }).modelSupportsReasoningSummaries,
|
|
963
|
+
);
|
|
964
|
+
if (reasoningSummaryDeliveryError) {
|
|
965
|
+
ctx.addIssue({
|
|
966
|
+
code: "custom",
|
|
967
|
+
path: ["providers", name, "modelReasoningSummaryDelivery"],
|
|
968
|
+
message: reasoningSummaryDeliveryError,
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
const defaultMaxOutputError = positiveIntegerConfigError(
|
|
972
|
+
(provider as { defaultMaxOutputTokens?: unknown }).defaultMaxOutputTokens,
|
|
973
|
+
"defaultMaxOutputTokens",
|
|
974
|
+
);
|
|
975
|
+
if (defaultMaxOutputError) {
|
|
976
|
+
ctx.addIssue({
|
|
977
|
+
code: "custom",
|
|
978
|
+
path: ["providers", name, "defaultMaxOutputTokens"],
|
|
979
|
+
message: defaultMaxOutputError,
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
const maxOutputError = positiveIntegerRecordConfigError(
|
|
983
|
+
(provider as { modelMaxOutputTokens?: unknown }).modelMaxOutputTokens,
|
|
984
|
+
"modelMaxOutputTokens",
|
|
985
|
+
);
|
|
986
|
+
if (maxOutputError) {
|
|
987
|
+
ctx.addIssue({
|
|
988
|
+
code: "custom",
|
|
989
|
+
path: ["providers", name, "modelMaxOutputTokens"],
|
|
990
|
+
message: maxOutputError,
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
if (Object.hasOwn(provider, "codexAccountMode") && provider.codexAccountMode !== undefined) {
|
|
994
|
+
// Persisted account mode is valid ONLY on the canonical built-in `openai` forward provider.
|
|
995
|
+
// Old openai-multi rows stay parseable (they never carry a mode) so startup can migrate them.
|
|
996
|
+
const canonicalOpenAiShape = name === "openai"
|
|
997
|
+
&& provider.adapter === "openai-responses"
|
|
998
|
+
&& (provider as { authMode?: unknown }).authMode === "forward"
|
|
999
|
+
&& typeof provider.baseUrl === "string"
|
|
1000
|
+
&& provider.baseUrl.replace(/\/+$/, "") === "https://chatgpt.com/backend-api/codex";
|
|
1001
|
+
if (!canonicalOpenAiShape) {
|
|
1002
|
+
ctx.addIssue({
|
|
1003
|
+
code: "custom",
|
|
1004
|
+
path: ["providers", name, "codexAccountMode"],
|
|
1005
|
+
message: "codexAccountMode is valid only on the canonical built-in openai provider",
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
if (!hasOwnProvider(config.providers, config.defaultProvider)) {
|
|
1011
|
+
ctx.addIssue({
|
|
1012
|
+
code: "custom",
|
|
1013
|
+
path: ["defaultProvider"],
|
|
1014
|
+
message: "defaultProvider must exist in providers",
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
const combos = (config as { combos?: unknown }).combos;
|
|
1018
|
+
if (combos !== undefined) {
|
|
1019
|
+
if (!combos || typeof combos !== "object" || Array.isArray(combos)) {
|
|
1020
|
+
ctx.addIssue({ code: "custom", path: ["combos"], message: "combos must be an object" });
|
|
1021
|
+
} else {
|
|
1022
|
+
for (const [id, raw] of Object.entries(combos as Record<string, unknown>)) {
|
|
1023
|
+
const alias = raw && typeof raw === "object" && !Array.isArray(raw)
|
|
1024
|
+
? (raw as { alias?: unknown }).alias
|
|
1025
|
+
: undefined;
|
|
1026
|
+
if (typeof alias === "string" && codexAccountNamespaceForModel(accountNamespaces, alias.trim())) {
|
|
1027
|
+
ctx.addIssue({
|
|
1028
|
+
code: "custom",
|
|
1029
|
+
path: ["combos", id, "alias"],
|
|
1030
|
+
message: CODEX_ACCOUNT_NAMESPACE_COMBO_ALIAS_COLLISION_ERROR,
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
// Pass the full map so cross-combo rules (alias uniqueness) apply at load time
|
|
1034
|
+
// too, not just via the management API; each combo is excluded from its own check.
|
|
1035
|
+
for (const issue of comboConfigIssues(id, raw, config.providers, {
|
|
1036
|
+
combos: combos as Record<string, import("./types").OcxComboConfig>,
|
|
1037
|
+
excludeComboId: id,
|
|
1038
|
+
})) {
|
|
1039
|
+
ctx.addIssue({
|
|
1040
|
+
code: "custom",
|
|
1041
|
+
path: ["combos", id, ...issue.path],
|
|
1042
|
+
message: issue.message,
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
});
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* Default featured subagent models (native GPT) seeded on a fresh install and when `subagentModels`
|
|
1052
|
+
* is unset. Codex's spawn_agent advertises the first 5 featured catalog entries, so this seed is a
|
|
1053
|
+
* deliberate 5-list: frontier gpt-5.5 first, the gpt-5.6 preview trio, and gpt-5.4-mini as the cheap
|
|
1054
|
+
* tier. gpt-5.4 / gpt-5.3-codex-spark stay selectable in the GUI's available list. The user can
|
|
1055
|
+
* remove any in the GUI — once they set the list (even to []), it is respected, so removals persist
|
|
1056
|
+
* (start-up only seeds the UNSET case). Kept to ids ChatGPT accepts; the start-up seed prefers the
|
|
1057
|
+
* live catalog's native slugs.
|
|
1058
|
+
*/
|
|
1059
|
+
export const DEFAULT_SUBAGENT_MODELS = ["gpt-5.5", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.4-mini"];
|
|
1060
|
+
|
|
1061
|
+
export function getConfigDir(): string {
|
|
1062
|
+
return resolveConfigDir();
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
export function getConfigPath(): string {
|
|
1066
|
+
return resolveConfigPath();
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
export function getPidPath(): string {
|
|
1070
|
+
return resolvePidPath();
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
export function getRuntimePortPath(): string {
|
|
1074
|
+
return resolveRuntimePortPath();
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
export function hardenConfigDir(): void {
|
|
1078
|
+
const dir = getConfigDir();
|
|
1079
|
+
if (existsSync(dir)) {
|
|
1080
|
+
try { chmodSync(dir, 0o700); } catch { /* best-effort */ }
|
|
1081
|
+
if (process.platform === "win32") {
|
|
1082
|
+
hardenSecretDir(dir, { required: false });
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
export function hardenExistingSecret(path: string): void {
|
|
1088
|
+
if (existsSync(path)) {
|
|
1089
|
+
try { chmodSync(path, 0o600); } catch { /* best-effort */ }
|
|
1090
|
+
if (process.platform === "win32") {
|
|
1091
|
+
hardenSecretPath(path, { required: false });
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* The schema's `.catch(undefined)` silently degrades an invalid persisted
|
|
1097
|
+
* `streamMode` to "auto"; surface that once so a hand-edited typo (e.g.
|
|
1098
|
+
* "legacy_tee") is discoverable instead of silently changing stream shape.
|
|
1099
|
+
*/
|
|
1100
|
+
function warnDegradedStreamMode(rawParsed: unknown, validated: OcxConfig): void {
|
|
1101
|
+
if (!rawParsed || typeof rawParsed !== "object") return;
|
|
1102
|
+
const raw = (rawParsed as Record<string, unknown>).streamMode;
|
|
1103
|
+
if (raw !== undefined && validated.streamMode === undefined) {
|
|
1104
|
+
console.warn(`⚠️ config.json streamMode ${JSON.stringify(raw)} is invalid (expected "auto", "legacy-tee", or "eager-relay") — falling back to "auto"`);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* Companion to {@link warnDegradedStreamMode} for a blank persisted `hostname`. The bind
|
|
1110
|
+
* falls back to loopback, which is the safe direction but not what the file asked for —
|
|
1111
|
+
* say so once instead of silently ignoring the field.
|
|
1112
|
+
*/
|
|
1113
|
+
function warnDegradedHostname(rawParsed: unknown, validated: OcxConfig): void {
|
|
1114
|
+
if (!rawParsed || typeof rawParsed !== "object") return;
|
|
1115
|
+
const raw = (rawParsed as Record<string, unknown>).hostname;
|
|
1116
|
+
if (raw !== undefined && validated.hostname === undefined) {
|
|
1117
|
+
console.warn(`⚠️ config.json hostname ${JSON.stringify(raw)} is not a usable bind address — falling back to 127.0.0.1`);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
/**
|
|
1122
|
+
* The apiKeys schema salvages entry by entry rather than failing the parse, so a
|
|
1123
|
+
* dropped key is otherwise invisible — and it will not be re-saved by the next
|
|
1124
|
+
* mutation. Say so out loud. Compares the raw array against the validated one,
|
|
1125
|
+
* the same shape as the degrade warnings above.
|
|
1126
|
+
*/
|
|
1127
|
+
/** One definition of "usable secret", shared by the schema and the warnings. */
|
|
1128
|
+
function isUsableApiKeySecret(value: unknown): value is string {
|
|
1129
|
+
return typeof value === "string" && value.length > 0 && value === value.trim();
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
/**
|
|
1133
|
+
* Give every salvaged key a stable, targetable id.
|
|
1134
|
+
*
|
|
1135
|
+
* Pure and deterministic on purpose. Two earlier spellings were wrong: minting a
|
|
1136
|
+
* UUID inside the schema transform handed out a different id on every parse, and
|
|
1137
|
+
* repairing-then-writing during `loadConfig` put a file write on the read path,
|
|
1138
|
+
* where it could clobber a concurrent legitimate save with a stale snapshot.
|
|
1139
|
+
*
|
|
1140
|
+
* So the replacement id is derived from the entry's position, which is already
|
|
1141
|
+
* how the file orders these rows: same file in, same ids out, no I/O and no
|
|
1142
|
+
* randomness. It is not derived from the secret — a public identifier should
|
|
1143
|
+
* never be a function of key material.
|
|
1144
|
+
*/
|
|
1145
|
+
function normalizeApiKeyIds(config: OcxConfig): OcxConfig {
|
|
1146
|
+
const keys = config.apiKeys;
|
|
1147
|
+
if (!keys?.length) return config;
|
|
1148
|
+
// Reserve every explicit id BEFORE synthesizing any, or a synthetic
|
|
1149
|
+
// `salvaged-1` assigned to row 1 would push a row that legitimately owns that
|
|
1150
|
+
// id onto `salvaged-2`. An id the user already has is the one thing this
|
|
1151
|
+
// repair must never take away.
|
|
1152
|
+
const reserved = new Set<string>();
|
|
1153
|
+
for (const entry of keys) {
|
|
1154
|
+
if (entry.id) reserved.add(entry.id);
|
|
1155
|
+
}
|
|
1156
|
+
const taken = new Set<string>(reserved);
|
|
1157
|
+
const kept = new Set<string>();
|
|
1158
|
+
keys.forEach((entry, index) => {
|
|
1159
|
+
// The first row holding an explicit id keeps it; later collisions are the
|
|
1160
|
+
// ones that move.
|
|
1161
|
+
if (entry.id && !kept.has(entry.id)) {
|
|
1162
|
+
kept.add(entry.id);
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
let candidate = `salvaged-${index + 1}`;
|
|
1166
|
+
let suffix = 1;
|
|
1167
|
+
while (taken.has(candidate)) candidate = `salvaged-${index + 1}-${++suffix}`;
|
|
1168
|
+
entry.id = candidate;
|
|
1169
|
+
taken.add(candidate);
|
|
1170
|
+
kept.add(candidate);
|
|
1171
|
+
});
|
|
1172
|
+
return config;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
function warnDegradedApiKeys(rawParsed: unknown, validated: OcxConfig): void {
|
|
1176
|
+
if (!rawParsed || typeof rawParsed !== "object") return;
|
|
1177
|
+
const raw = (rawParsed as Record<string, unknown>).apiKeys;
|
|
1178
|
+
if (raw === undefined) return;
|
|
1179
|
+
if (!Array.isArray(raw)) {
|
|
1180
|
+
console.warn(`⚠️ config.json apiKeys is not an array — ignoring it; generate a new key from the API tab`);
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
const dropped = raw.length - (validated.apiKeys?.length ?? 0);
|
|
1184
|
+
if (dropped > 0) {
|
|
1185
|
+
console.warn(`⚠️ config.json apiKeys: skipped ${dropped} malformed entr${dropped === 1 ? "y" : "ies"} — the remaining keys still work`);
|
|
1186
|
+
}
|
|
1187
|
+
// Same-length repairs are invisible to the count above, and they are the ones
|
|
1188
|
+
// that show up as a blank name or an unknown date in the dashboard. Say so.
|
|
1189
|
+
const repaired = raw.filter(row => {
|
|
1190
|
+
if (!row || typeof row !== "object") return false;
|
|
1191
|
+
const entry = row as Record<string, unknown>;
|
|
1192
|
+
// Must match the schema exactly: a row whose key is unusable was DROPPED, and
|
|
1193
|
+
// saying "the key still works" about it would be a lie.
|
|
1194
|
+
if (!isUsableApiKeySecret(entry.key)) return false;
|
|
1195
|
+
return typeof entry.id !== "string" || !entry.id
|
|
1196
|
+
|| typeof entry.name !== "string"
|
|
1197
|
+
|| typeof entry.createdAt !== "string";
|
|
1198
|
+
}).length;
|
|
1199
|
+
if (repaired > 0) {
|
|
1200
|
+
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`);
|
|
1201
|
+
}
|
|
1202
|
+
// A duplicate id is repaired too, and it is not visible in either count above.
|
|
1203
|
+
const ids = raw.filter(row => row && typeof row === "object" && isUsableApiKeySecret((row as Record<string, unknown>).key))
|
|
1204
|
+
.map(row => (row as Record<string, unknown>).id)
|
|
1205
|
+
.filter((id): id is string => typeof id === "string" && !!id);
|
|
1206
|
+
const duplicates = ids.length - new Set(ids).size;
|
|
1207
|
+
if (duplicates > 0) {
|
|
1208
|
+
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`);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
const CLAUDE_SUBAGENT_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
1213
|
+
|
|
1214
|
+
function isClaudeSubagentEffort(value: unknown): value is NonNullable<OcxClaudeCodeConfig["subagentEffort"]> {
|
|
1215
|
+
return typeof value === "string" && CLAUDE_SUBAGENT_EFFORTS.includes(value as typeof CLAUDE_SUBAGENT_EFFORTS[number]);
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
function rawClaudeSubagentEffort(rawParsed: unknown): unknown {
|
|
1219
|
+
const raw = rawConfigRecord(rawParsed);
|
|
1220
|
+
const claudeCode = raw?.claudeCode;
|
|
1221
|
+
if (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode)) return undefined;
|
|
1222
|
+
return (claudeCode as Record<string, unknown>).subagentEffort;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
function normalizePersistedClaudeCode(claudeCode: unknown): OcxConfig["claudeCode"] {
|
|
1226
|
+
if (!claudeCode || typeof claudeCode !== "object" || Array.isArray(claudeCode)) {
|
|
1227
|
+
return claudeCode as OcxConfig["claudeCode"];
|
|
1228
|
+
}
|
|
1229
|
+
const normalized = { ...claudeCode } as Record<string, unknown>;
|
|
1230
|
+
if (Object.hasOwn(normalized, "subagentEffort") && !isClaudeSubagentEffort(normalized.subagentEffort)) {
|
|
1231
|
+
delete normalized.subagentEffort;
|
|
1232
|
+
}
|
|
1233
|
+
return normalized as OcxConfig["claudeCode"];
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
function normalizeClaudeSubagentEffort(config: OcxConfig, rawParsed: unknown): OcxConfig {
|
|
1237
|
+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
|
|
1238
|
+
if (rawEffort === undefined || isClaudeSubagentEffort(rawEffort)) return config;
|
|
1239
|
+
return { ...config, claudeCode: normalizePersistedClaudeCode(config.claudeCode) };
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
function warnDegradedClaudeSubagentEffort(rawParsed: unknown): void {
|
|
1243
|
+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
|
|
1244
|
+
if (rawEffort !== undefined && !isClaudeSubagentEffort(rawEffort)) {
|
|
1245
|
+
console.warn(`⚠️ config.json claudeCode.subagentEffort is invalid (expected ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}) — ignoring it. Other settings were preserved.`);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
type NativeSubagentPersistedField = "injectionModel" | "injectionEffort" | "syncCodexSubagentDefaults";
|
|
1250
|
+
|
|
1251
|
+
function rawConfigRecord(rawParsed: unknown): Record<string, unknown> | null {
|
|
1252
|
+
return rawParsed !== null && typeof rawParsed === "object" && !Array.isArray(rawParsed)
|
|
1253
|
+
? rawParsed as Record<string, unknown>
|
|
1254
|
+
: null;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
function malformedNativeSubagentFields(rawParsed: unknown): NativeSubagentPersistedField[] {
|
|
1258
|
+
const raw = rawConfigRecord(rawParsed);
|
|
1259
|
+
if (!raw) return [];
|
|
1260
|
+
const malformed: NativeSubagentPersistedField[] = [];
|
|
1261
|
+
if (Object.hasOwn(raw, "injectionModel") && typeof raw.injectionModel !== "string") {
|
|
1262
|
+
malformed.push("injectionModel");
|
|
1263
|
+
}
|
|
1264
|
+
if (Object.hasOwn(raw, "injectionEffort") && typeof raw.injectionEffort !== "string") {
|
|
1265
|
+
malformed.push("injectionEffort");
|
|
1266
|
+
}
|
|
1267
|
+
if (Object.hasOwn(raw, "syncCodexSubagentDefaults") && typeof raw.syncCodexSubagentDefaults !== "boolean") {
|
|
1268
|
+
malformed.push("syncCodexSubagentDefaults");
|
|
1269
|
+
}
|
|
1270
|
+
return malformed;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
function malformedNativeSubagentFieldWarning(field: NativeSubagentPersistedField): string {
|
|
1274
|
+
const expected = field === "syncCodexSubagentDefaults" ? "a boolean" : "a string";
|
|
1275
|
+
return `${field} ignored: expected ${expected}`;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
function nativeSubagentSyncDisabledReason(config: OcxConfig, rawParsed?: unknown): string | null {
|
|
1279
|
+
if (config.syncCodexSubagentDefaults !== true) return null;
|
|
1280
|
+
const malformed = malformedNativeSubagentFields(rawParsed);
|
|
1281
|
+
if (malformed.includes("injectionModel")) return "injectionModel must be a string";
|
|
1282
|
+
if (!config.injectionModel?.trim()) return "a nonblank injectionModel is required";
|
|
1283
|
+
if (malformed.includes("injectionEffort")) return "injectionEffort must be a string or omitted";
|
|
1284
|
+
if (config.injectionEffort !== undefined && !isCodexReasoningEffort(config.injectionEffort)) {
|
|
1285
|
+
return "injectionEffort must be a supported Codex reasoning effort";
|
|
1286
|
+
}
|
|
1287
|
+
return null;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
function normalizeNativeSubagentSync(config: OcxConfig, rawParsed?: unknown): OcxConfig {
|
|
1291
|
+
if (!nativeSubagentSyncDisabledReason(config, rawParsed)) return config;
|
|
1292
|
+
const normalized = { ...config };
|
|
1293
|
+
delete normalized.syncCodexSubagentDefaults;
|
|
1294
|
+
return normalized;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
function warnDegradedNativeSubagentConfig(rawParsed: unknown, config: OcxConfig): void {
|
|
1298
|
+
for (const field of malformedNativeSubagentFields(rawParsed)) {
|
|
1299
|
+
console.warn(`⚠️ config.json ${malformedNativeSubagentFieldWarning(field)}. Other settings were preserved.`);
|
|
1300
|
+
}
|
|
1301
|
+
const reason = nativeSubagentSyncDisabledReason(config, rawParsed);
|
|
1302
|
+
if (reason) {
|
|
1303
|
+
console.warn(`⚠️ config.json syncCodexSubagentDefaults was disabled: ${reason}. Other settings were preserved.`);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
export function loadConfig(): OcxConfig {
|
|
1308
|
+
const dir = getConfigDir();
|
|
1309
|
+
const configPath = getConfigPath();
|
|
1310
|
+
hardenConfigDir();
|
|
1311
|
+
hardenExistingSecret(configPath);
|
|
1312
|
+
hardenExistingSecret(join(dir, "auth.json"));
|
|
1313
|
+
if (!existsSync(configPath)) {
|
|
1314
|
+
return getDefaultConfig();
|
|
1315
|
+
}
|
|
1316
|
+
try {
|
|
1317
|
+
const raw = readFileSync(configPath, "utf-8").replace(/^\uFEFF/, "");
|
|
1318
|
+
const parsed = JSON.parse(raw);
|
|
1319
|
+
const result = configSchema.safeParse(parsed);
|
|
1320
|
+
if (result.success) {
|
|
1321
|
+
const config = normalizeApiKeyIds(result.data as OcxConfig);
|
|
1322
|
+
warnDegradedStreamMode(parsed, config);
|
|
1323
|
+
warnDegradedHostname(parsed, config);
|
|
1324
|
+
warnDegradedApiKeys(parsed, config);
|
|
1325
|
+
warnDegradedClaudeSubagentEffort(parsed);
|
|
1326
|
+
warnDegradedNativeSubagentConfig(parsed, config);
|
|
1327
|
+
return normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, parsed), parsed);
|
|
1328
|
+
}
|
|
1329
|
+
// Schema validation failed — merge defaults into the raw object instead of
|
|
1330
|
+
// discarding it entirely, so pool accounts and providers survive a missing
|
|
1331
|
+
// field like defaultProvider.
|
|
1332
|
+
const defaults = getDefaultConfig();
|
|
1333
|
+
const merged = { ...defaults, ...parsed };
|
|
1334
|
+
// Ensure providers from both sides survive
|
|
1335
|
+
if (parsed.providers && defaults.providers) {
|
|
1336
|
+
merged.providers = { ...defaults.providers, ...parsed.providers };
|
|
1337
|
+
}
|
|
1338
|
+
const retryResult = configSchema.safeParse(merged);
|
|
1339
|
+
if (retryResult.success) {
|
|
1340
|
+
warnConfigRepaired(configPath, result.error);
|
|
1341
|
+
const config = normalizeApiKeyIds(retryResult.data as OcxConfig);
|
|
1342
|
+
warnDegradedHostname(parsed, config);
|
|
1343
|
+
warnDegradedApiKeys(parsed, config);
|
|
1344
|
+
warnDegradedClaudeSubagentEffort(parsed);
|
|
1345
|
+
warnDegradedNativeSubagentConfig(parsed, config);
|
|
1346
|
+
return normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, parsed), parsed);
|
|
1347
|
+
}
|
|
1348
|
+
// Merge couldn't fix it — truly broken config
|
|
1349
|
+
warnAndBackupInvalidConfig(configPath, result.error);
|
|
1350
|
+
return getDefaultConfig();
|
|
1351
|
+
} catch (error) {
|
|
1352
|
+
warnAndBackupInvalidConfig(configPath, error);
|
|
1353
|
+
return getDefaultConfig();
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
export type ConfigDiagnostics = {
|
|
1358
|
+
config: OcxConfig;
|
|
1359
|
+
source: "default" | "file" | "fallback";
|
|
1360
|
+
error: string | null;
|
|
1361
|
+
/** Non-fatal config concerns; absent when there are no warnings. */
|
|
1362
|
+
warnings?: string[];
|
|
1363
|
+
};
|
|
1364
|
+
|
|
1365
|
+
type ConfigFileSnapshot = {
|
|
1366
|
+
diagnostics: ConfigDiagnostics;
|
|
1367
|
+
/** Exact file contents, including a possible BOM, used as the optimistic revision. */
|
|
1368
|
+
raw?: string;
|
|
1369
|
+
};
|
|
1370
|
+
|
|
1371
|
+
function configPlaceholderWarnings(config: OcxConfig): string[] {
|
|
1372
|
+
const warnings: string[] = [];
|
|
1373
|
+
for (const [name, provider] of Object.entries(config.providers)) {
|
|
1374
|
+
const placeholder = provider.baseUrl.match(/\{[^}]*\}/)?.[0];
|
|
1375
|
+
if (placeholder) {
|
|
1376
|
+
warnings.push(`providers.${name}.baseUrl contains unresolved ${placeholder}; set the real provider URL`);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
return warnings;
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
function validFileConfigDiagnostics(config: OcxConfig, rawParsed: unknown): ConfigDiagnostics {
|
|
1383
|
+
// Unsafe hand-edited optional values are disabled in memory instead of rejecting
|
|
1384
|
+
// the entire config, which would hide unrelated providers/accounts. The next
|
|
1385
|
+
// ordinary save persists the normalized absence.
|
|
1386
|
+
const syncDisabledReason = nativeSubagentSyncDisabledReason(config, rawParsed);
|
|
1387
|
+
const rawEffort = rawClaudeSubagentEffort(rawParsed);
|
|
1388
|
+
const normalized = normalizeClaudeSubagentEffort(normalizeNativeSubagentSync(config, rawParsed), rawParsed);
|
|
1389
|
+
const warnings = configPlaceholderWarnings(normalized);
|
|
1390
|
+
if (rawEffort !== undefined && !isClaudeSubagentEffort(rawEffort)) {
|
|
1391
|
+
warnings.push(`claudeCode.subagentEffort ignored: expected one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`);
|
|
1392
|
+
}
|
|
1393
|
+
warnings.push(...malformedNativeSubagentFields(rawParsed).map(malformedNativeSubagentFieldWarning));
|
|
1394
|
+
if (syncDisabledReason) {
|
|
1395
|
+
warnings.push(`syncCodexSubagentDefaults ignored: ${syncDisabledReason}`);
|
|
1396
|
+
}
|
|
1397
|
+
return {
|
|
1398
|
+
config: normalized,
|
|
1399
|
+
source: "file",
|
|
1400
|
+
error: null,
|
|
1401
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
export function subagentDefaultSyncEffective(
|
|
1406
|
+
config: Pick<OcxConfig, "syncCodexSubagentDefaults" | "injectionModel">,
|
|
1407
|
+
): boolean {
|
|
1408
|
+
return config.syncCodexSubagentDefaults === true && Boolean(config.injectionModel?.trim());
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
function mergeConfigDefaults(parsed: unknown): unknown {
|
|
1412
|
+
if (!parsed || typeof parsed !== "object") return parsed;
|
|
1413
|
+
const defaults = getDefaultConfig();
|
|
1414
|
+
const raw = parsed as Record<string, unknown>;
|
|
1415
|
+
const merged: Record<string, unknown> = { ...defaults, ...raw };
|
|
1416
|
+
if (raw.providers && typeof raw.providers === "object" && defaults.providers) {
|
|
1417
|
+
merged.providers = { ...defaults.providers, ...(raw.providers as Record<string, unknown>) };
|
|
1418
|
+
}
|
|
1419
|
+
return merged;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
function schemaDiagnosticsError(error: z.ZodError): string {
|
|
1423
|
+
const details = error.issues.map(issue => {
|
|
1424
|
+
const path = issue.path.join(".") || "config";
|
|
1425
|
+
return `${path}: ${issue.message}`;
|
|
1426
|
+
});
|
|
1427
|
+
return details.length > 0 ? `schema_invalid: ${details.join("; ")}` : "schema_invalid";
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/**
|
|
1431
|
+
* Reject a hostname the schema deliberately degrades on read. Load-time has to keep a
|
|
1432
|
+
* blank value non-fatal (see the `hostname` field comment), but an incoming write is a
|
|
1433
|
+
* live caller who can be told the value is wrong — silently rewriting it to loopback
|
|
1434
|
+
* would look like the bind succeeded on the address they asked for.
|
|
1435
|
+
*/
|
|
1436
|
+
function blankHostnameError(value: unknown): string | null {
|
|
1437
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1438
|
+
const hostname = (value as Record<string, unknown>).hostname;
|
|
1439
|
+
if (hostname === undefined) return null;
|
|
1440
|
+
if (typeof hostname !== "string" || !hostname.trim()) {
|
|
1441
|
+
return "schema_invalid: hostname: must be a nonblank bind address";
|
|
1442
|
+
}
|
|
1443
|
+
return null;
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
function claudeSubagentEffortError(value: unknown): string | null {
|
|
1447
|
+
const effort = rawClaudeSubagentEffort(value);
|
|
1448
|
+
if (effort === undefined || isClaudeSubagentEffort(effort)) return null;
|
|
1449
|
+
return `schema_invalid: claudeCode.subagentEffort: must be one of ${CLAUDE_SUBAGENT_EFFORTS.join(", ")}`;
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
function appOwnedMemoryBudgetError(value: unknown): string | null {
|
|
1453
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1454
|
+
const budget = (value as Record<string, unknown>).appOwnedMemoryBudgetMb;
|
|
1455
|
+
if (budget === undefined) return null;
|
|
1456
|
+
if (typeof budget !== "number" || !Number.isInteger(budget)
|
|
1457
|
+
|| budget < MIN_APP_OWNED_MEMORY_BUDGET_MB || budget > MAX_APP_OWNED_MEMORY_BUDGET_MB) {
|
|
1458
|
+
return `schema_invalid: appOwnedMemoryBudgetMb: must be an integer from ${MIN_APP_OWNED_MEMORY_BUDGET_MB} to ${MAX_APP_OWNED_MEMORY_BUDGET_MB}`;
|
|
1459
|
+
}
|
|
1460
|
+
return null;
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
function googleAntigravityStaticCatalogVersionError(value: unknown): string | null {
|
|
1464
|
+
const raw = rawConfigRecord(value);
|
|
1465
|
+
if (!raw || !Object.hasOwn(raw, "googleAntigravityStaticCatalogVersion")) return null;
|
|
1466
|
+
const version = raw.googleAntigravityStaticCatalogVersion;
|
|
1467
|
+
if (version === undefined || version === 1) return null;
|
|
1468
|
+
return "schema_invalid: googleAntigravityStaticCatalogVersion: must be 1 or omitted";
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
/** Validate an in-memory config candidate without touching disk. Used by headless CLI import/set. */
|
|
1472
|
+
export function validateConfigCandidate(value: unknown): { ok: true; config: OcxConfig } | { ok: false; error: string } {
|
|
1473
|
+
const boundaryError = blankHostnameError(value)
|
|
1474
|
+
?? claudeSubagentEffortError(value)
|
|
1475
|
+
?? appOwnedMemoryBudgetError(value)
|
|
1476
|
+
?? googleAntigravityStaticCatalogVersionError(value);
|
|
1477
|
+
if (boundaryError) return { ok: false, error: boundaryError };
|
|
1478
|
+
const result = configSchema.safeParse(value);
|
|
1479
|
+
if (result.success) return { ok: true, config: normalizeApiKeyIds(result.data as OcxConfig) };
|
|
1480
|
+
return { ok: false, error: schemaDiagnosticsError(result.error) };
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
function configDiagnosticsFromRaw(raw: string): ConfigDiagnostics {
|
|
1484
|
+
try {
|
|
1485
|
+
const parsed = JSON.parse(raw.replace(/^\uFEFF/, ""));
|
|
1486
|
+
const result = configSchema.safeParse(parsed);
|
|
1487
|
+
if (result.success) {
|
|
1488
|
+
return validFileConfigDiagnostics(normalizeApiKeyIds(result.data as OcxConfig), parsed);
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
const retryResult = configSchema.safeParse(mergeConfigDefaults(parsed));
|
|
1492
|
+
if (retryResult.success) {
|
|
1493
|
+
return validFileConfigDiagnostics(normalizeApiKeyIds(retryResult.data as OcxConfig), parsed);
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
return { config: getDefaultConfig(), source: "fallback", error: schemaDiagnosticsError(result.error) };
|
|
1497
|
+
} catch {
|
|
1498
|
+
return { config: getDefaultConfig(), source: "fallback", error: "invalid_json" };
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
function readConfigFileSnapshot(): ConfigFileSnapshot {
|
|
1503
|
+
try {
|
|
1504
|
+
const raw = readFileSync(getConfigPath(), "utf-8");
|
|
1505
|
+
return { diagnostics: configDiagnosticsFromRaw(raw), raw };
|
|
1506
|
+
} catch (error) {
|
|
1507
|
+
if (isMissingPathError(error)) {
|
|
1508
|
+
return {
|
|
1509
|
+
diagnostics: { config: getDefaultConfig(), source: "default", error: null },
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
return {
|
|
1513
|
+
diagnostics: { config: getDefaultConfig(), source: "fallback", error: "invalid_json" },
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
export function readConfigDiagnostics(): ConfigDiagnostics {
|
|
1519
|
+
return readConfigFileSnapshot().diagnostics;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
const CONFIG_MUTATION_DB_FILENAME = "config-mutation.sqlite";
|
|
1523
|
+
const CONFIG_MUTATION_DB_SIDECARS = ["-journal", "-wal", "-shm"] as const;
|
|
1524
|
+
let warnedConfigMutationDirectoryAcl = false;
|
|
1525
|
+
|
|
1526
|
+
export class ConfigMutationLockError extends Error {
|
|
1527
|
+
readonly code = "CONFIG_MUTATION_LOCK_UNAVAILABLE";
|
|
1528
|
+
|
|
1529
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
1530
|
+
super(message, options);
|
|
1531
|
+
this.name = "ConfigMutationLockError";
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
function configMutationDatabasePath(): string {
|
|
1536
|
+
const dir = getConfigDir();
|
|
1537
|
+
// First statement on purpose: a rejected mutation must leave nothing behind, not a
|
|
1538
|
+
// freshly created/chmod'd directory or database. See src/lib/test-home-guard.ts.
|
|
1539
|
+
assertNotRealHomeUnderTest(dir);
|
|
1540
|
+
if (!existsSync(dir)) {
|
|
1541
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1542
|
+
} else {
|
|
1543
|
+
try { chmodSync(dir, 0o700); } catch { /* best-effort on existing dir */ }
|
|
1544
|
+
}
|
|
1545
|
+
if (windowsSecretAclApplies()) {
|
|
1546
|
+
try {
|
|
1547
|
+
// Distinct timeout memo from management-token directory harden: a required
|
|
1548
|
+
// management-dir timeout must not poison config mutation on the same home
|
|
1549
|
+
// (windows-latest server-management-auth cases).
|
|
1550
|
+
hardenSecretDir(dir, { required: true, timeoutMemoKey: `${dir}::config-mutation` });
|
|
1551
|
+
} catch (error) {
|
|
1552
|
+
if (!warnedConfigMutationDirectoryAcl) {
|
|
1553
|
+
warnedConfigMutationDirectoryAcl = true;
|
|
1554
|
+
const diagnostics = error instanceof Error ? error.message : "ACL hardening failed";
|
|
1555
|
+
console.warn(
|
|
1556
|
+
`[opencodex] Config mutation coordination directory ACL hardening did not complete; continuing without it. ${diagnostics}`,
|
|
1557
|
+
);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
const path = join(dir, CONFIG_MUTATION_DB_FILENAME);
|
|
1562
|
+
recordOwnedConfigPath(dir, path);
|
|
1563
|
+
for (const suffix of CONFIG_MUTATION_DB_SIDECARS) {
|
|
1564
|
+
recordOwnedConfigPath(dir, `${path}${suffix}`);
|
|
1565
|
+
}
|
|
1566
|
+
return path;
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
let configMutationLockDepth = 0;
|
|
1570
|
+
|
|
1571
|
+
/**
|
|
1572
|
+
* Serialize synchronous config and Codex credential-generation commits across processes with an
|
|
1573
|
+
* OS-backed SQLite write transaction. `busy_timeout=0` is deliberate: runtime request paths must
|
|
1574
|
+
* fail immediately under contention rather than freeze the Bun event loop. Process exit releases
|
|
1575
|
+
* SQLite locks without stale-owner deletion or lease recovery races.
|
|
1576
|
+
*
|
|
1577
|
+
* Reentrancy is limited to the current synchronous call stack; never return a Promise from `fn`.
|
|
1578
|
+
*/
|
|
1579
|
+
export function withConfigMutationLockSync<T>(fn: () => T): T {
|
|
1580
|
+
if (configMutationLockDepth > 0) {
|
|
1581
|
+
configMutationLockDepth += 1;
|
|
1582
|
+
try {
|
|
1583
|
+
return fn();
|
|
1584
|
+
} finally {
|
|
1585
|
+
configMutationLockDepth -= 1;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
const path = configMutationDatabasePath();
|
|
1589
|
+
let database: Database | undefined;
|
|
1590
|
+
let transactionOpen = false;
|
|
1591
|
+
try {
|
|
1592
|
+
database = new Database(path, { create: true });
|
|
1593
|
+
try { chmodSync(path, 0o600); } catch { /* platform may ignore chmod */ }
|
|
1594
|
+
database.exec("PRAGMA busy_timeout = 0; BEGIN IMMEDIATE");
|
|
1595
|
+
transactionOpen = true;
|
|
1596
|
+
} catch (cause) {
|
|
1597
|
+
try { database?.close(); } catch { /* acquisition already failed */ }
|
|
1598
|
+
const code = cause && typeof cause === "object" && "code" in cause
|
|
1599
|
+
? String((cause as { code?: unknown }).code)
|
|
1600
|
+
: "";
|
|
1601
|
+
throw new ConfigMutationLockError(
|
|
1602
|
+
code === "SQLITE_BUSY" ? "Config mutation already in progress" : "Could not acquire config mutation transaction",
|
|
1603
|
+
{ cause },
|
|
1604
|
+
);
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
configMutationLockDepth = 1;
|
|
1608
|
+
try {
|
|
1609
|
+
const value = fn();
|
|
1610
|
+
database.exec("COMMIT");
|
|
1611
|
+
transactionOpen = false;
|
|
1612
|
+
return value;
|
|
1613
|
+
} catch (error) {
|
|
1614
|
+
if (transactionOpen) {
|
|
1615
|
+
try { database.exec("ROLLBACK"); } catch { /* close below still releases the OS lock */ }
|
|
1616
|
+
transactionOpen = false;
|
|
1617
|
+
}
|
|
1618
|
+
throw error;
|
|
1619
|
+
} finally {
|
|
1620
|
+
configMutationLockDepth = 0;
|
|
1621
|
+
try { database.close(); } catch { /* the OS lock is released with the handle */ }
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
function persistConfigUnlocked(config: OcxConfig): void {
|
|
1626
|
+
const configPath = getConfigPath();
|
|
1627
|
+
atomicWriteFile(configPath, JSON.stringify(config, null, 2) + "\n");
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
export function saveConfig(config: OcxConfig): void {
|
|
1631
|
+
// Keep the real-home assertion ahead of even lock-directory preparation.
|
|
1632
|
+
assertNotRealHomeUnderTest(getConfigDir());
|
|
1633
|
+
withConfigMutationLockSync(() => persistConfigUnlocked(config));
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
export type PersistedConfigMutation<T> = {
|
|
1637
|
+
changed: boolean;
|
|
1638
|
+
value: T;
|
|
1639
|
+
};
|
|
1640
|
+
|
|
1641
|
+
export type PersistedConfigMutationOutcome<T> =
|
|
1642
|
+
| { status: "committed" | "unchanged"; value: T }
|
|
1643
|
+
| { status: "unavailable"; reason: "missing" | "invalid" | "conflict" };
|
|
1644
|
+
|
|
1645
|
+
const CONFIG_MUTATION_MAX_REBASE_ATTEMPTS = 3;
|
|
1646
|
+
let persistedConfigMutationBeforeCommitForTests: (() => void) | null = null;
|
|
1647
|
+
|
|
1648
|
+
/** Test-only one-shot seam: inject a competing mutation after the first decision, before freshness revalidation. */
|
|
1649
|
+
export function setPersistedConfigMutationBeforeCommitForTests(hook: (() => void) | null): void {
|
|
1650
|
+
persistedConfigMutationBeforeCommitForTests = hook;
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
function unavailableConfigMutationReason(snapshot: ConfigFileSnapshot): "missing" | "invalid" {
|
|
1654
|
+
return snapshot.diagnostics.source === "default" ? "missing" : "invalid";
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
/**
|
|
1658
|
+
* Patch a schema-valid on-disk config under the shared mutation lock. Cooperating writers are
|
|
1659
|
+
* serialized; the callback is rerun on the newest snapshot so observed direct byte changes rebase
|
|
1660
|
+
* and credential predicates are re-evaluated immediately before the atomic commit. A writer that
|
|
1661
|
+
* ignores the coordinator can still change bytes after the final check because the filesystem has
|
|
1662
|
+
* no portable conditional rename. Missing or malformed config always fails closed and is never
|
|
1663
|
+
* recreated from a prior snapshot.
|
|
1664
|
+
*/
|
|
1665
|
+
export function mutatePersistedConfig<T>(
|
|
1666
|
+
mutate: (config: OcxConfig) => PersistedConfigMutation<T>,
|
|
1667
|
+
): PersistedConfigMutationOutcome<T> {
|
|
1668
|
+
// Avoid creating/opening the coordinator database for a read-path update that already knows
|
|
1669
|
+
// there is no valid config. The same check runs again under the transaction for authority.
|
|
1670
|
+
const observed = readConfigFileSnapshot();
|
|
1671
|
+
if (observed.diagnostics.source !== "file" || observed.raw === undefined) {
|
|
1672
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(observed) };
|
|
1673
|
+
}
|
|
1674
|
+
return withConfigMutationLockSync(() => {
|
|
1675
|
+
let base = readConfigFileSnapshot();
|
|
1676
|
+
for (let attempt = 0; attempt < CONFIG_MUTATION_MAX_REBASE_ATTEMPTS; attempt += 1) {
|
|
1677
|
+
if (base.diagnostics.source !== "file" || base.raw === undefined) {
|
|
1678
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(base) };
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
const tentativeConfig = structuredClone(base.diagnostics.config);
|
|
1682
|
+
const tentative = mutate(tentativeConfig);
|
|
1683
|
+
if (!tentative.changed) return { status: "unchanged", value: tentative.value };
|
|
1684
|
+
|
|
1685
|
+
const hook = persistedConfigMutationBeforeCommitForTests;
|
|
1686
|
+
persistedConfigMutationBeforeCommitForTests = null;
|
|
1687
|
+
hook?.();
|
|
1688
|
+
|
|
1689
|
+
const latest = readConfigFileSnapshot();
|
|
1690
|
+
if (latest.diagnostics.source !== "file" || latest.raw === undefined) {
|
|
1691
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(latest) };
|
|
1692
|
+
}
|
|
1693
|
+
if (latest.raw !== base.raw) {
|
|
1694
|
+
base = latest;
|
|
1695
|
+
continue;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
// Re-run against a fresh clone even when config bytes are unchanged: a Codex credential
|
|
1699
|
+
// generation lives in a separate file and may have changed at the injected seam.
|
|
1700
|
+
const confirmedConfig = structuredClone(latest.diagnostics.config);
|
|
1701
|
+
const confirmed = mutate(confirmedConfig);
|
|
1702
|
+
if (!confirmed.changed) return { status: "unchanged", value: confirmed.value };
|
|
1703
|
+
|
|
1704
|
+
const commitBase = readConfigFileSnapshot();
|
|
1705
|
+
if (commitBase.diagnostics.source !== "file" || commitBase.raw === undefined) {
|
|
1706
|
+
return { status: "unavailable", reason: unavailableConfigMutationReason(commitBase) };
|
|
1707
|
+
}
|
|
1708
|
+
if (commitBase.raw !== latest.raw) {
|
|
1709
|
+
base = commitBase;
|
|
1710
|
+
continue;
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
persistConfigUnlocked(confirmedConfig);
|
|
1714
|
+
return { status: "committed", value: confirmed.value };
|
|
1715
|
+
}
|
|
1716
|
+
return { status: "unavailable", reason: "conflict" };
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
export function websocketsEnabled(config: Pick<OcxConfig, "websockets">): boolean {
|
|
1721
|
+
return config.websockets === true;
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
// ---------------------------------------------------------------------------
|
|
1725
|
+
// Hand-edit protection for the `claudeCode` subtree (devlog 260726_claude_auth_auto/040 H1).
|
|
1726
|
+
//
|
|
1727
|
+
// `saveConfig` serializes the WHOLE config object, so ANY service-time save — a model
|
|
1728
|
+
// visibility toggle, a 429 key rotation on the request path — rewrites `claudeCode`
|
|
1729
|
+
// from whatever the long-lived server config happens to hold. A user who hand-edits
|
|
1730
|
+
// `config.json` while the proxy runs then watches their edit vanish for no visible
|
|
1731
|
+
// reason (issue #488). Enumerating `claudeCode` mutators cannot fix that; the guard has
|
|
1732
|
+
// to live in ONE save wrapper that every live-config writer goes through.
|
|
1733
|
+
// ---------------------------------------------------------------------------
|
|
1734
|
+
|
|
1735
|
+
/**
|
|
1736
|
+
* Baseline keyed on the CONFIG INSTANCE, never a module global: a second `loadConfig()`
|
|
1737
|
+
* elsewhere must not refresh the baseline the long-lived server config is judged
|
|
1738
|
+
* against, or a later stale save would masquerade as "our own change".
|
|
1739
|
+
*/
|
|
1740
|
+
const claudeCodeBaseline = new WeakMap<OcxConfig, unknown>();
|
|
1741
|
+
|
|
1742
|
+
/**
|
|
1743
|
+
* The live config retains the address of the socket Bun actually opened, while
|
|
1744
|
+
* this map retains the operator's desired address for the next process start.
|
|
1745
|
+
* Keeping them separate prevents an unrelated live save from restoring a stale
|
|
1746
|
+
* externally exposed bind after OAuth adopted a newer loopback disk config.
|
|
1747
|
+
*/
|
|
1748
|
+
type PersistedServerBinding = Pick<OcxConfig, "port" | "hostname">;
|
|
1749
|
+
|
|
1750
|
+
const persistedLiveServerBinding = new WeakMap<OcxConfig, PersistedServerBinding>();
|
|
1751
|
+
|
|
1752
|
+
/**
|
|
1753
|
+
* Arm the baseline for a long-lived config. MANDATORY at `startServer`, not lazy on
|
|
1754
|
+
* first save — arming lazily would lose exactly the hand edit made before that first
|
|
1755
|
+
* save, which is the case the guard exists for.
|
|
1756
|
+
*/
|
|
1757
|
+
export function armClaudeCodeBaseline(config: OcxConfig): void {
|
|
1758
|
+
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
/** Test seam only: is this instance armed? */
|
|
1762
|
+
export function claudeCodeBaselineArmed(config: OcxConfig): boolean {
|
|
1763
|
+
return claudeCodeBaseline.has(config);
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
/**
|
|
1767
|
+
* Structural compare of parsed subtrees. NOT `JSON.stringify`: key order must not
|
|
1768
|
+
* decide whether a user's hand edit survives.
|
|
1769
|
+
*/
|
|
1770
|
+
function deepEqual(a: unknown, b: unknown): boolean {
|
|
1771
|
+
if (a === b) return true;
|
|
1772
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
1773
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
1774
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
1775
|
+
return a.length === b.length && a.every((item, index) => deepEqual(item, b[index]));
|
|
1776
|
+
}
|
|
1777
|
+
const left = a as Record<string, unknown>;
|
|
1778
|
+
const right = b as Record<string, unknown>;
|
|
1779
|
+
// `undefined` values and absent keys are the same thing after a JSON round-trip.
|
|
1780
|
+
const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
|
|
1781
|
+
for (const key of keys) {
|
|
1782
|
+
if (left[key] === undefined && right[key] === undefined) continue;
|
|
1783
|
+
if (!deepEqual(left[key], right[key])) return false;
|
|
1784
|
+
}
|
|
1785
|
+
return true;
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
const MISSING_CONFIG_VALUE = Symbol("missing-config-value");
|
|
1789
|
+
type ConfigMergeValue = unknown | typeof MISSING_CONFIG_VALUE;
|
|
1790
|
+
|
|
1791
|
+
function isPlainConfigRecord(value: ConfigMergeValue): value is Record<string, unknown> {
|
|
1792
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1793
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1794
|
+
return prototype === Object.prototype || prototype === null;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
function ownConfigValue(record: Record<string, unknown>, key: string): ConfigMergeValue {
|
|
1798
|
+
return Object.hasOwn(record, key) ? record[key] : MISSING_CONFIG_VALUE;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
function cloneConfigValue(value: ConfigMergeValue): ConfigMergeValue {
|
|
1802
|
+
return value === MISSING_CONFIG_VALUE ? value : structuredClone(value);
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
function reconcileConfigRecord(
|
|
1806
|
+
live: Record<string, unknown>,
|
|
1807
|
+
baseline: Record<string, unknown>,
|
|
1808
|
+
persisted: Record<string, unknown>,
|
|
1809
|
+
skippedKeys?: ReadonlySet<string>,
|
|
1810
|
+
): void {
|
|
1811
|
+
const keys = new Set([...Object.keys(baseline), ...Object.keys(live), ...Object.keys(persisted)]);
|
|
1812
|
+
for (const key of keys) {
|
|
1813
|
+
if (skippedKeys?.has(key)) continue;
|
|
1814
|
+
const merged = reconcileConfigValue(
|
|
1815
|
+
ownConfigValue(baseline, key),
|
|
1816
|
+
ownConfigValue(live, key),
|
|
1817
|
+
ownConfigValue(persisted, key),
|
|
1818
|
+
);
|
|
1819
|
+
if (merged === MISSING_CONFIG_VALUE) delete live[key];
|
|
1820
|
+
else live[key] = merged;
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
function reconcileConfigValue(
|
|
1825
|
+
baseline: ConfigMergeValue,
|
|
1826
|
+
live: ConfigMergeValue,
|
|
1827
|
+
persisted: ConfigMergeValue,
|
|
1828
|
+
): ConfigMergeValue {
|
|
1829
|
+
const liveChanged = !deepEqual(live, baseline);
|
|
1830
|
+
const persistedChanged = !deepEqual(persisted, baseline);
|
|
1831
|
+
|
|
1832
|
+
if (!liveChanged) {
|
|
1833
|
+
if (live !== MISSING_CONFIG_VALUE && Array.isArray(live) && Array.isArray(persisted)) {
|
|
1834
|
+
live.splice(0, live.length, ...structuredClone(persisted));
|
|
1835
|
+
return live;
|
|
1836
|
+
}
|
|
1837
|
+
if (isPlainConfigRecord(live) && isPlainConfigRecord(persisted)) {
|
|
1838
|
+
reconcileConfigRecord(
|
|
1839
|
+
live,
|
|
1840
|
+
isPlainConfigRecord(baseline) ? baseline : {},
|
|
1841
|
+
persisted,
|
|
1842
|
+
);
|
|
1843
|
+
return live;
|
|
1844
|
+
}
|
|
1845
|
+
return cloneConfigValue(persisted);
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
if (!persistedChanged) return live;
|
|
1849
|
+
|
|
1850
|
+
if (isPlainConfigRecord(live)
|
|
1851
|
+
&& isPlainConfigRecord(persisted)
|
|
1852
|
+
&& (baseline === MISSING_CONFIG_VALUE || isPlainConfigRecord(baseline))) {
|
|
1853
|
+
reconcileConfigRecord(
|
|
1854
|
+
live,
|
|
1855
|
+
isPlainConfigRecord(baseline) ? baseline : {},
|
|
1856
|
+
persisted,
|
|
1857
|
+
);
|
|
1858
|
+
}
|
|
1859
|
+
// Same-leaf conflicts prefer the pending live management mutation.
|
|
1860
|
+
return live;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
/**
|
|
1864
|
+
* Reconcile an async OAuth disk commit into the shared live config without erasing
|
|
1865
|
+
* management mutations that have not saved yet. The baseline is a normalized disk
|
|
1866
|
+
* snapshot from immediately before login; disjoint object edits merge recursively,
|
|
1867
|
+
* while same-leaf conflicts prefer live state.
|
|
1868
|
+
*/
|
|
1869
|
+
export function reconcileLiveConfigFromDisk(config: OcxConfig, persistedBaseline: OcxConfig): void {
|
|
1870
|
+
const diagnostics = readConfigDiagnostics();
|
|
1871
|
+
if (diagnostics.source === "fallback") {
|
|
1872
|
+
throw new Error(`OAuth config reconciliation failed: ${diagnostics.error ?? "invalid config file"}`);
|
|
1873
|
+
}
|
|
1874
|
+
const persisted = diagnostics.config;
|
|
1875
|
+
const claudeGuardArmed = claudeCodeBaseline.has(config);
|
|
1876
|
+
const pendingLiveClaudeMutation = claudeGuardArmed
|
|
1877
|
+
&& !deepEqual(config.claudeCode, claudeCodeBaseline.get(config));
|
|
1878
|
+
|
|
1879
|
+
persistedLiveServerBinding.set(config, {
|
|
1880
|
+
port: persisted.port,
|
|
1881
|
+
...(persisted.hostname !== undefined ? { hostname: persisted.hostname } : {}),
|
|
1882
|
+
});
|
|
1883
|
+
|
|
1884
|
+
reconcileConfigRecord(
|
|
1885
|
+
config as unknown as Record<string, unknown>,
|
|
1886
|
+
persistedBaseline as unknown as Record<string, unknown>,
|
|
1887
|
+
persisted as unknown as Record<string, unknown>,
|
|
1888
|
+
new Set(["hostname", "port", ...(claudeGuardArmed ? ["claudeCode"] : [])]),
|
|
1889
|
+
);
|
|
1890
|
+
|
|
1891
|
+
if (claudeGuardArmed && !pendingLiveClaudeMutation) {
|
|
1892
|
+
if (persisted.claudeCode === undefined) delete config.claudeCode;
|
|
1893
|
+
else config.claudeCode = structuredClone(persisted.claudeCode);
|
|
1894
|
+
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
/** The literal file, with no schema merge or default injection. */
|
|
1899
|
+
function readRawConfigJson(): Record<string, unknown> | undefined {
|
|
1900
|
+
try {
|
|
1901
|
+
const configPath = getConfigPath();
|
|
1902
|
+
if (!existsSync(configPath)) return undefined;
|
|
1903
|
+
const raw = readFileSync(configPath, "utf-8").replace(/^\uFEFF/, "");
|
|
1904
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
1905
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
|
|
1906
|
+
return parsed as Record<string, unknown>;
|
|
1907
|
+
} catch {
|
|
1908
|
+
// Unreadable or corrupt: behave exactly as before. Never fail a save over protection.
|
|
1909
|
+
return undefined;
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
/**
|
|
1914
|
+
* Read only schema-valid binding fields from the literal file. Missing fields mean
|
|
1915
|
+
* their schema defaults; malformed fields keep the last known persisted value.
|
|
1916
|
+
*/
|
|
1917
|
+
function readPersistedServerBinding(
|
|
1918
|
+
raw: Record<string, unknown>,
|
|
1919
|
+
baseline: PersistedServerBinding,
|
|
1920
|
+
): PersistedServerBinding {
|
|
1921
|
+
const port = raw.port === undefined
|
|
1922
|
+
? 10100
|
|
1923
|
+
: (typeof raw.port === "number"
|
|
1924
|
+
&& Number.isInteger(raw.port)
|
|
1925
|
+
&& raw.port >= 0
|
|
1926
|
+
&& raw.port <= 65535
|
|
1927
|
+
? raw.port
|
|
1928
|
+
: baseline.port);
|
|
1929
|
+
const hostname = raw.hostname === undefined
|
|
1930
|
+
? undefined
|
|
1931
|
+
: (typeof raw.hostname === "string" ? raw.hostname : baseline.hostname);
|
|
1932
|
+
return { port, ...(hostname !== undefined ? { hostname } : {}) };
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
/**
|
|
1936
|
+
* The save entry point for every writer holding a LIVE server config.
|
|
1937
|
+
*
|
|
1938
|
+
* Conflict policy, chosen deliberately:
|
|
1939
|
+
* - disk changed, we did not → their hand edit wins;
|
|
1940
|
+
* - disk changed AND we changed → our change wins and the baseline rebases, so the
|
|
1941
|
+
* user's next edit starts from the new value (a three-way merge is out of scope);
|
|
1942
|
+
* - file missing/unreadable → save what we have, no throw.
|
|
1943
|
+
*
|
|
1944
|
+
* Scope residual: only `claudeCode` is reconciled. A hand edit to `providers` is still
|
|
1945
|
+
* clobbered — recorded and asserted in tests so it cannot drift into an assumed
|
|
1946
|
+
* guarantee.
|
|
1947
|
+
*/
|
|
1948
|
+
export function saveConfigPreservingClaudeCode(config: OcxConfig): void {
|
|
1949
|
+
withConfigMutationLockSync(() => {
|
|
1950
|
+
const bindingBaseline = persistedLiveServerBinding.get(config);
|
|
1951
|
+
const onDisk = claudeCodeBaseline.has(config) || bindingBaseline
|
|
1952
|
+
? readRawConfigJson()
|
|
1953
|
+
: undefined;
|
|
1954
|
+
if (claudeCodeBaseline.has(config)) {
|
|
1955
|
+
if (onDisk !== undefined) {
|
|
1956
|
+
const baseline = claudeCodeBaseline.get(config);
|
|
1957
|
+
const persistedClaudeCode = normalizePersistedClaudeCode(onDisk.claudeCode);
|
|
1958
|
+
const diskChanged = !deepEqual(persistedClaudeCode, baseline);
|
|
1959
|
+
const weChanged = !deepEqual(config.claudeCode, baseline);
|
|
1960
|
+
if (diskChanged && !weChanged) {
|
|
1961
|
+
config.claudeCode = persistedClaudeCode;
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
const persistedBinding = bindingBaseline && onDisk
|
|
1966
|
+
? readPersistedServerBinding(onDisk, bindingBaseline)
|
|
1967
|
+
: bindingBaseline;
|
|
1968
|
+
if (persistedBinding) {
|
|
1969
|
+
const persistedConfig: OcxConfig = { ...config, port: persistedBinding.port };
|
|
1970
|
+
if (persistedBinding.hostname === undefined) delete persistedConfig.hostname;
|
|
1971
|
+
else persistedConfig.hostname = persistedBinding.hostname;
|
|
1972
|
+
persistConfigUnlocked(persistedConfig);
|
|
1973
|
+
persistedLiveServerBinding.set(config, persistedBinding);
|
|
1974
|
+
} else {
|
|
1975
|
+
persistConfigUnlocked(config);
|
|
1976
|
+
}
|
|
1977
|
+
if (claudeCodeBaseline.has(config)) {
|
|
1978
|
+
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
|
|
1979
|
+
}
|
|
1980
|
+
});
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
export function codexAutoStartEnabled(config: Pick<OcxConfig, "codexAutoStart">): boolean {
|
|
1984
|
+
return config.codexAutoStart !== false;
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
export const CODEX_SHIM_AUTO_RESTORE_ENV = "OPENCODEX_CODEX_SHIM_AUTO_RESTORE";
|
|
1988
|
+
|
|
1989
|
+
export function codexShimAutoRestoreEnabled(
|
|
1990
|
+
config: Pick<OcxConfig, "codexShimAutoRestore">,
|
|
1991
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
1992
|
+
): boolean {
|
|
1993
|
+
return config.codexShimAutoRestore !== false && env[CODEX_SHIM_AUTO_RESTORE_ENV] !== "0";
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
export function multiAgentGuidanceEnabled(
|
|
1997
|
+
config: Pick<OcxConfig, "multiAgentGuidanceEnabled">,
|
|
1998
|
+
): boolean {
|
|
1999
|
+
return config.multiAgentGuidanceEnabled !== false;
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
export function getDefaultConfig(): OcxConfig {
|
|
2003
|
+
// Fresh-install default: works out of the box with Codex's ChatGPT OAuth (no API key).
|
|
2004
|
+
// gpt-* requests forward the caller's incoming OAuth headers to the ChatGPT backend.
|
|
2005
|
+
// Adding extra providers (e.g. opencode-go) and switching defaultProvider is a user/runtime choice.
|
|
2006
|
+
return {
|
|
2007
|
+
port: 10100,
|
|
2008
|
+
managementUsageMaxReadBytes: 64 * 1024 * 1024,
|
|
2009
|
+
appOwnedMemoryBudgetMb: DEFAULT_APP_OWNED_MEMORY_BUDGET_BYTES / (1024 * 1024),
|
|
2010
|
+
// Fresh/re-initialized configs are already written in the current three-tier
|
|
2011
|
+
// OpenAI shape. Mark them as such so startup does not mistake them for a
|
|
2012
|
+
// legacy config and collide with an immutable backup from an earlier setup.
|
|
2013
|
+
openaiProviderTierVersion: OPENAI_PROVIDER_TIER_VERSION,
|
|
2014
|
+
providers: {
|
|
2015
|
+
openai: {
|
|
2016
|
+
adapter: "openai-responses",
|
|
2017
|
+
baseUrl: "https://chatgpt.com/backend-api/codex",
|
|
2018
|
+
authMode: "forward",
|
|
2019
|
+
codexAccountMode: "pool",
|
|
2020
|
+
},
|
|
2021
|
+
},
|
|
2022
|
+
defaultProvider: "openai",
|
|
2023
|
+
subagentModels: [...DEFAULT_SUBAGENT_MODELS],
|
|
2024
|
+
multiAgentGuidanceEnabled: true,
|
|
2025
|
+
websockets: false,
|
|
2026
|
+
codexAutoStart: true,
|
|
2027
|
+
codexShimAutoRestore: true,
|
|
2028
|
+
};
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
export function resolveEnvValue(value: string | undefined): string | undefined {
|
|
2032
|
+
if (!value) return undefined;
|
|
2033
|
+
const match = value.match(/^\$\{(\w+)\}$/);
|
|
2034
|
+
if (match) return process.env[match[1]];
|
|
2035
|
+
if (value.startsWith("$")) return process.env[value.slice(1)];
|
|
2036
|
+
return value;
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
/**
|
|
2040
|
+
* Mirror `config.proxy` into HTTP(S)_PROXY env vars so Bun's native fetch routes every outbound
|
|
2041
|
+
* provider call through the proxy — no per-callsite changes (verified: Bun honors these plus
|
|
2042
|
+
* NO_PROXY). User-set env vars always win; localhost/127.0.0.1 are appended to NO_PROXY so the
|
|
2043
|
+
* CLI's own health checks and running-proxy API calls stay direct. Call once per process entry
|
|
2044
|
+
* that makes outbound provider requests (server start, catalog sync).
|
|
2045
|
+
*/
|
|
2046
|
+
export function applyProxyEnv(config: OcxConfig): void {
|
|
2047
|
+
const proxy = resolveEnvValue(config.proxy);
|
|
2048
|
+
if (!proxy) return;
|
|
2049
|
+
if (!process.env.HTTP_PROXY?.trim() && !process.env.http_proxy?.trim()) process.env.HTTP_PROXY = proxy;
|
|
2050
|
+
if (!process.env.HTTPS_PROXY?.trim() && !process.env.https_proxy?.trim()) process.env.HTTPS_PROXY = proxy;
|
|
2051
|
+
const existing = process.env.NO_PROXY ?? process.env.no_proxy ?? "";
|
|
2052
|
+
const entries = existing.split(",").map(s => s.trim()).filter(Boolean);
|
|
2053
|
+
const seen = new Set(entries.map(e => e.toLowerCase()));
|
|
2054
|
+
for (const host of ["localhost", "127.0.0.1", "::1", "[::1]"]) {
|
|
2055
|
+
if (!seen.has(host)) {
|
|
2056
|
+
entries.push(host);
|
|
2057
|
+
seen.add(host);
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
process.env.NO_PROXY = entries.join(",");
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
export function writePid(pid: number): void {
|
|
2064
|
+
const dir = getConfigDir();
|
|
2065
|
+
if (!existsSync(dir)) {
|
|
2066
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
2067
|
+
} else {
|
|
2068
|
+
hardenConfigDir();
|
|
2069
|
+
}
|
|
2070
|
+
atomicWriteFile(getPidPath(), String(pid));
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
export type RuntimePortState = {
|
|
2074
|
+
pid: number;
|
|
2075
|
+
port: number;
|
|
2076
|
+
hostname?: string;
|
|
2077
|
+
};
|
|
2078
|
+
|
|
2079
|
+
function isValidRuntimePortState(value: unknown): value is RuntimePortState {
|
|
2080
|
+
if (!value || typeof value !== "object") return false;
|
|
2081
|
+
const state = value as Record<string, unknown>;
|
|
2082
|
+
const hostnameOk = state.hostname === undefined || typeof state.hostname === "string";
|
|
2083
|
+
return Number.isSafeInteger(state.pid)
|
|
2084
|
+
&& Number(state.pid) > 0
|
|
2085
|
+
&& Number.isInteger(state.port)
|
|
2086
|
+
&& Number(state.port) > 0
|
|
2087
|
+
&& Number(state.port) <= 65535
|
|
2088
|
+
&& hostnameOk;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
export function writeRuntimePort(state: RuntimePortState): void {
|
|
2092
|
+
const dir = getConfigDir();
|
|
2093
|
+
if (!existsSync(dir)) {
|
|
2094
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
2095
|
+
} else {
|
|
2096
|
+
hardenConfigDir();
|
|
2097
|
+
}
|
|
2098
|
+
atomicWriteFile(getRuntimePortPath(), JSON.stringify(state, null, 2) + "\n");
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
export function readPid(): number | null {
|
|
2102
|
+
const pidPath = getPidPath();
|
|
2103
|
+
if (!existsSync(pidPath)) return null;
|
|
2104
|
+
try {
|
|
2105
|
+
const raw = readFileSync(pidPath, "utf-8").trim();
|
|
2106
|
+
const pid = parsePidFile(raw);
|
|
2107
|
+
if (pid === null) return null;
|
|
2108
|
+
try {
|
|
2109
|
+
process.kill(pid, 0);
|
|
2110
|
+
return isLikelyOcxStartProcess(pid) ? pid : null;
|
|
2111
|
+
} catch (e: unknown) {
|
|
2112
|
+
if ((e as NodeJS.ErrnoException).code === "EPERM") {
|
|
2113
|
+
return isLikelyOcxStartProcess(pid) ? pid : null;
|
|
2114
|
+
}
|
|
2115
|
+
return null;
|
|
2116
|
+
}
|
|
2117
|
+
} catch {
|
|
2118
|
+
return null;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
export function readRuntimePort(expectedPid?: number): RuntimePortState | null {
|
|
2123
|
+
try {
|
|
2124
|
+
const parsed = JSON.parse(readFileSync(getRuntimePortPath(), "utf-8"));
|
|
2125
|
+
if (!isValidRuntimePortState(parsed)) return null;
|
|
2126
|
+
if (expectedPid !== undefined && parsed.pid !== expectedPid) return null;
|
|
2127
|
+
return parsed;
|
|
2128
|
+
} catch {
|
|
2129
|
+
return null;
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
export function removePid(expectedPid?: number): void {
|
|
2134
|
+
if (expectedPid !== undefined && readPidFileValue() !== expectedPid) return;
|
|
2135
|
+
try {
|
|
2136
|
+
unlinkSync(getPidPath());
|
|
2137
|
+
} catch { /* ignore */ }
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
function warnConfigRepaired(configPath: string, error: z.ZodError): void {
|
|
2141
|
+
if (warnedConfigFallbacks.has(configPath)) return;
|
|
2142
|
+
warnedConfigFallbacks.add(configPath);
|
|
2143
|
+
const fields = error.issues.map(i => i.path.join(".") || "config").join(", ");
|
|
2144
|
+
console.error(`opencodex config at ${configPath}: repaired missing field(s) [${fields}] with defaults. Your providers and accounts are preserved.`);
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
export function readPidFileValue(): number | null {
|
|
2148
|
+
try {
|
|
2149
|
+
return parsePidFile(readFileSync(getPidPath(), "utf-8"));
|
|
2150
|
+
} catch {
|
|
2151
|
+
return null;
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
export function removeRuntimePort(expectedPid?: number): void {
|
|
2156
|
+
if (expectedPid !== undefined && readRuntimePort(expectedPid) === null) return;
|
|
2157
|
+
try {
|
|
2158
|
+
unlinkSync(getRuntimePortPath());
|
|
2159
|
+
} catch { /* ignore */ }
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
/**
|
|
2163
|
+
* Snapshot-guarded stale-state purge: remove the pid/runtime files only when their content
|
|
2164
|
+
* still matches what the caller saw BEFORE its liveness probe. A concurrent `ocx start` can
|
|
2165
|
+
* write fresh records mid-probe; an unconditional purge would erase the new proxy's state.
|
|
2166
|
+
*/
|
|
2167
|
+
export function removePidIfValueIs(snapshot: number | null): void {
|
|
2168
|
+
if (!existsSync(getPidPath())) return;
|
|
2169
|
+
if (readPidFileValue() !== snapshot) return;
|
|
2170
|
+
try {
|
|
2171
|
+
unlinkSync(getPidPath());
|
|
2172
|
+
} catch { /* ignore */ }
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
export function removeRuntimePortIfPidIs(snapshotPid: number | null): void {
|
|
2176
|
+
const current = readRuntimePort();
|
|
2177
|
+
if ((current?.pid ?? null) !== snapshotPid) return;
|
|
2178
|
+
try {
|
|
2179
|
+
unlinkSync(getRuntimePortPath());
|
|
2180
|
+
} catch { /* ignore */ }
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
export function parsePidFile(raw: string): number | null {
|
|
2184
|
+
const trimmed = raw.trim();
|
|
2185
|
+
if (!/^\d+$/.test(trimmed)) return null;
|
|
2186
|
+
const pid = Number.parseInt(trimmed, 10);
|
|
2187
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
export function isOcxStartCommandLine(commandLine: string): boolean {
|
|
2191
|
+
const normalized = commandLine.toLowerCase().replace(/\\/g, "/");
|
|
2192
|
+
// "src/cli.ts" matches pre-restructure installs still running; "src/cli/index.ts" is current.
|
|
2193
|
+
// `@scope/.opencodex-*` is npm's in-place rename of the global package during
|
|
2194
|
+
// `npm install -g` — a Windows service wrapper can respawn from that temp tree
|
|
2195
|
+
// mid-update, and must still count as ocx for port reclaim.
|
|
2196
|
+
// Match both the upstream scope (@bitkyc08) and this fork's publish scope (@iislee).
|
|
2197
|
+
const hasOcxEntrypoint = normalized.includes("src/cli.ts")
|
|
2198
|
+
|| normalized.includes("src/cli/index.ts")
|
|
2199
|
+
|| normalized.includes("@bitkyc08/opencodex")
|
|
2200
|
+
|| normalized.includes("@iislee/opencodex")
|
|
2201
|
+
|| /@bitkyc08\/\.opencodex-/.test(normalized)
|
|
2202
|
+
|| /@iislee\/\.opencodex-/.test(normalized)
|
|
2203
|
+
|| /(?:^|[\s/"'])(?:ocx|opencodex)(?:\.cmd)?(?:$|[\s"'])/.test(normalized);
|
|
2204
|
+
return hasOcxEntrypoint && /(?:^|[\s"'])start(?:$|[\s"'])/.test(normalized);
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
/** Per-process memo: waitForProxy/findLiveProxy used to spawn powershell on every 150ms poll. */
|
|
2208
|
+
const ocxStartProcessCache = new Map<number, boolean>();
|
|
2209
|
+
let ocxStartProcessSweepCursor = 0;
|
|
2210
|
+
let ocxStartProcessProbe: (pid: number) => void = pid => { process.kill(pid, 0); };
|
|
2211
|
+
|
|
2212
|
+
export function setOcxStartProcessProbeForTests(probe: ((pid: number) => void) | null): void {
|
|
2213
|
+
ocxStartProcessProbe = probe ?? (pid => { process.kill(pid, 0); });
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
export function setOcxStartProcessCacheForTests(entries: Iterable<readonly [number, boolean]>): void {
|
|
2217
|
+
ocxStartProcessCache.clear();
|
|
2218
|
+
for (const [pid, value] of entries) ocxStartProcessCache.set(pid, value);
|
|
2219
|
+
ocxStartProcessSweepCursor = 0;
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
export function sweepDeadOcxStartProcessCache(maxProbes = 64): number {
|
|
2223
|
+
const pids: number[] = [];
|
|
2224
|
+
let removed = 0;
|
|
2225
|
+
for (const pid of ocxStartProcessCache.keys()) {
|
|
2226
|
+
if (Number.isSafeInteger(pid) && pid > 0) pids.push(pid);
|
|
2227
|
+
else if (ocxStartProcessCache.delete(pid)) removed += 1;
|
|
2228
|
+
}
|
|
2229
|
+
if (pids.length === 0 || maxProbes <= 0) {
|
|
2230
|
+
ocxStartProcessSweepCursor = 0;
|
|
2231
|
+
return removed;
|
|
2232
|
+
}
|
|
2233
|
+
const probeCount = Math.min(Math.floor(maxProbes), pids.length);
|
|
2234
|
+
const start = ocxStartProcessSweepCursor % pids.length;
|
|
2235
|
+
for (let offset = 0; offset < probeCount; offset += 1) {
|
|
2236
|
+
const pid = pids[(start + offset) % pids.length]!;
|
|
2237
|
+
try {
|
|
2238
|
+
ocxStartProcessProbe(pid);
|
|
2239
|
+
} catch (error) {
|
|
2240
|
+
if ((error as NodeJS.ErrnoException).code !== "ESRCH") continue;
|
|
2241
|
+
if (ocxStartProcessCache.delete(pid)) removed += 1;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
ocxStartProcessSweepCursor = (start + probeCount) % pids.length;
|
|
2245
|
+
return removed;
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
export function ocxStartProcessCacheSizeForTests(): number {
|
|
2249
|
+
return ocxStartProcessCache.size;
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
function isLikelyOcxStartProcess(pid: number): boolean {
|
|
2253
|
+
const cached = ocxStartProcessCache.get(pid);
|
|
2254
|
+
if (cached !== undefined) return cached;
|
|
2255
|
+
const commandLine = readProcessCommandLine(pid);
|
|
2256
|
+
if (commandLine === undefined) return false;
|
|
2257
|
+
const ok = isOcxStartCommandLine(commandLine);
|
|
2258
|
+
ocxStartProcessCache.set(pid, ok);
|
|
2259
|
+
return ok;
|
|
2260
|
+
}
|
|
2261
|
+
|
|
2262
|
+
/**
|
|
2263
|
+
* Alive pid from the pid file without the expensive Windows command-line probe.
|
|
2264
|
+
* Safe for liveness polls: callers still identity-check /healthz before trusting the proxy.
|
|
2265
|
+
* Destructive stop/kill paths should keep using {@link readPid}, which verifies the cmdline.
|
|
2266
|
+
*/
|
|
2267
|
+
export function readAlivePid(): number | null {
|
|
2268
|
+
const pid = readPidFileValue();
|
|
2269
|
+
if (pid === null) return null;
|
|
2270
|
+
try {
|
|
2271
|
+
process.kill(pid, 0);
|
|
2272
|
+
return pid;
|
|
2273
|
+
} catch (e: unknown) {
|
|
2274
|
+
if ((e as NodeJS.ErrnoException).code === "EPERM") return pid;
|
|
2275
|
+
return null;
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
/**
|
|
2280
|
+
* Full identity check of a KNOWN candidate pid (alive + ocx-start command line).
|
|
2281
|
+
* Companion to {@link readAlivePid}: liveness discovery may be cheap, but any pid
|
|
2282
|
+
* handed to a destructive caller must pass this check — and must equal the candidate
|
|
2283
|
+
* it was asked about, so a pidfile rewrite between discovery and verification can
|
|
2284
|
+
* never swap in a different process (TOCTOU guard).
|
|
2285
|
+
*/
|
|
2286
|
+
export function verifyPidIdentity(candidatePid: number): number | null {
|
|
2287
|
+
try {
|
|
2288
|
+
process.kill(candidatePid, 0);
|
|
2289
|
+
} catch (e: unknown) {
|
|
2290
|
+
if ((e as NodeJS.ErrnoException).code !== "EPERM") return null;
|
|
2291
|
+
}
|
|
2292
|
+
return isLikelyOcxStartProcess(candidatePid) ? candidatePid : null;
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
function readProcessCommandLine(pid: number): string | undefined {
|
|
2296
|
+
try {
|
|
2297
|
+
if (process.platform === "win32") {
|
|
2298
|
+
// Prefer WMIC over PowerShell: much faster cold start, and windowsHide avoids console flash.
|
|
2299
|
+
// Fall back to PowerShell when WMIC is absent (newer Windows images).
|
|
2300
|
+
const wmic = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\wbem\\WMIC.exe`;
|
|
2301
|
+
try {
|
|
2302
|
+
const output = execFileSync(wmic, [
|
|
2303
|
+
"process", "where", `ProcessId=${pid}`, "get", "CommandLine", "/VALUE",
|
|
2304
|
+
], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, windowsHide: true });
|
|
2305
|
+
const match = /^CommandLine=(.*)$/m.exec(output.replace(/\r/g, ""));
|
|
2306
|
+
const value = match?.[1]?.trim();
|
|
2307
|
+
if (value) return value;
|
|
2308
|
+
} catch {
|
|
2309
|
+
/* WMIC missing or failed — fall through */
|
|
2310
|
+
}
|
|
2311
|
+
const output = execFileSync("powershell.exe", [
|
|
2312
|
+
"-NoProfile",
|
|
2313
|
+
"-NoLogo",
|
|
2314
|
+
"-NonInteractive",
|
|
2315
|
+
"-WindowStyle",
|
|
2316
|
+
"Hidden",
|
|
2317
|
+
"-Command",
|
|
2318
|
+
`(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`,
|
|
2319
|
+
], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, windowsHide: true });
|
|
2320
|
+
return output.trim() || undefined;
|
|
2321
|
+
}
|
|
2322
|
+
const output = execFileSync("ps", ["-p", String(pid), "-o", "command="], {
|
|
2323
|
+
encoding: "utf-8",
|
|
2324
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
2325
|
+
timeout: 1000,
|
|
2326
|
+
windowsHide: true,
|
|
2327
|
+
});
|
|
2328
|
+
return output.trim() || undefined;
|
|
2329
|
+
} catch {
|
|
2330
|
+
return undefined;
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
function warnAndBackupInvalidConfig(configPath: string, error: unknown): void {
|
|
2335
|
+
if (warnedConfigFallbacks.has(configPath)) return;
|
|
2336
|
+
warnedConfigFallbacks.add(configPath);
|
|
2337
|
+
|
|
2338
|
+
const backupPath = backupInvalidConfig(configPath);
|
|
2339
|
+
const reason = error instanceof z.ZodError
|
|
2340
|
+
? error.issues.map(issue => `${issue.path.join(".") || "config"}: ${issue.message}`).join("; ")
|
|
2341
|
+
: error instanceof Error ? error.message : String(error);
|
|
2342
|
+
const backupNote = backupPath ? ` A backup was written to ${backupPath}.` : "";
|
|
2343
|
+
console.error(`Could not load opencodex config at ${configPath}: ${reason}. Using default config.${backupNote}`);
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
export function backupInvalidConfig(configPath: string): string | null {
|
|
2347
|
+
if (!existsSync(configPath)) return null;
|
|
2348
|
+
const backupPath = `${configPath}.invalid-${new Date().toISOString().replace(/[:.]/g, "-")}`;
|
|
2349
|
+
try {
|
|
2350
|
+
copyFileSync(configPath, backupPath);
|
|
2351
|
+
try { chmodSync(backupPath, 0o600); } catch { /* best-effort */ }
|
|
2352
|
+
return backupPath;
|
|
2353
|
+
} catch {
|
|
2354
|
+
return null;
|
|
2355
|
+
}
|
|
2356
|
+
}
|