@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
|
@@ -0,0 +1,1169 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import type { CatalogModel } from "../../codex/catalog";
|
|
4
|
+
import { catalogModelSlug, invalidateCodexModelsCache, nativeModelRows, uniqueCatalogModelsForPublicList } from "../../codex/catalog";
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_SUBAGENT_MODELS,
|
|
7
|
+
codexAutoStartEnabled,
|
|
8
|
+
hasOwnProvider,
|
|
9
|
+
isValidProviderName,
|
|
10
|
+
loadConfig,
|
|
11
|
+
multiAgentGuidanceEnabled,
|
|
12
|
+
providerBaseUrlConfigError,
|
|
13
|
+
providerHeadersConfigError,
|
|
14
|
+
saveConfigPreservingClaudeCode,
|
|
15
|
+
subagentDefaultSyncEffective,
|
|
16
|
+
} from "../../config";
|
|
17
|
+
import {
|
|
18
|
+
clearLoginState,
|
|
19
|
+
getLoginStatus,
|
|
20
|
+
isPublicOAuthProvider,
|
|
21
|
+
listOAuthProviders,
|
|
22
|
+
startLoginFlow,
|
|
23
|
+
submitManualLoginCode,
|
|
24
|
+
upsertOAuthProvider,
|
|
25
|
+
} from "../../oauth";
|
|
26
|
+
import { removeCredential } from "../../oauth/store";
|
|
27
|
+
import { providerDestinationResolvedError } from "../../lib/destination-policy";
|
|
28
|
+
import { enrichProviderFromCatalog, listKeyLoginProviders } from "../../oauth/key-providers";
|
|
29
|
+
import { deriveProviderPresets } from "../../providers/derive";
|
|
30
|
+
import { providerCodexAccountMode } from "../../providers/registry";
|
|
31
|
+
import { routedSlug, slugEquals } from "../../providers/slug-codec";
|
|
32
|
+
import { clearProviderQuotaCache, fetchProviderQuotaReports } from "../../providers/quota";
|
|
33
|
+
import { isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers";
|
|
34
|
+
import { clearThreadAccountMap } from "../../codex/routing";
|
|
35
|
+
import { primeCodexPoolQuotas } from "../../codex/auth-api";
|
|
36
|
+
import { DEFAULT_PROVIDER_CONTEXT_CAP, globalContextCapValue, providerContextCap, providerContextCaps, setAllProviderContextCaps, setGlobalContextCapValue, setProviderContextCap } from "../../providers/context-cap";
|
|
37
|
+
import { resolveCodexHomeDir } from "../../codex/home";
|
|
38
|
+
import { readUsageEntries } from "../../usage/log";
|
|
39
|
+
import { getUsageDebugLogEntries } from "../../usage/debug";
|
|
40
|
+
import { parseRange, parseUsageSurface, summarizeUsage } from "../../usage/summary";
|
|
41
|
+
import { stripCodexRuntimeProviderFields } from "../../codex/auth-context";
|
|
42
|
+
import { getProviderRegistryEntry } from "../../providers/registry";
|
|
43
|
+
import { getDebugLogEntries } from "../../lib/debug-log-buffer";
|
|
44
|
+
import { getInjectionDebugLogEntries } from "../../lib/injection-debug-log";
|
|
45
|
+
import {
|
|
46
|
+
clearDebugSettings,
|
|
47
|
+
clearDebugSetting,
|
|
48
|
+
getDebugSettings,
|
|
49
|
+
setDebugSettings,
|
|
50
|
+
type DebugFlag,
|
|
51
|
+
} from "../../lib/debug-settings";
|
|
52
|
+
import type { OcxClaudeCodeConfig, OcxConfig, OcxCustomModel, OcxProviderConfig } from "../../types";
|
|
53
|
+
import { drainAndShutdown } from "../lifecycle";
|
|
54
|
+
import { filterRequestLogs, getRequestLogEntries, type RequestLogEntry } from "../request-log";
|
|
55
|
+
import { estimateComboCost, estimateRequestCost, normalizeCostTokens, tokensPerSecond } from "../../usage/cost";
|
|
56
|
+
import type { PersistedUsageAttempt } from "../../usage/log";
|
|
57
|
+
import { isAllowedRequestOrigin, jsonResponse, providerManagementConfigError, publicProviderBaseUrl, safeConfigDTO } from "../auth-cors";
|
|
58
|
+
import { applySystemEnvToggle } from "../system-env";
|
|
59
|
+
|
|
60
|
+
import { isPlainRecord, parseDebugLogQuery, tokPerSecondResult, unavailableCostReason, costResult, requestLogDto, stripRegistryOnlyStaticHeaders, fetchAllModels, fetchGrokCandidateModels, buildClaudeDesktopState } from "./shared";
|
|
61
|
+
import type { MetricUnavailableReason, TokPerSecondResult, CostEstimateReason, CostResult, MetricSource } from "./shared";
|
|
62
|
+
import { readManagementJsonBody, rethrowManagementBodyTooLarge } from "./body";
|
|
63
|
+
|
|
64
|
+
const GROK_APPLY_JOIN_MS = 120_000;
|
|
65
|
+
export const GROK_APPLY_TERMINAL_MS = 10 * 60_000;
|
|
66
|
+
const grokApplyEncoder = new TextEncoder();
|
|
67
|
+
let grokApplyFlight: { startedAt: number; promise: Promise<unknown>; bytes: number } | null = null;
|
|
68
|
+
let grokApplyHighWaterBytes = 0;
|
|
69
|
+
let grokApplyTestHooks: { now?: () => number; run?: () => Promise<unknown> } | null = null;
|
|
70
|
+
|
|
71
|
+
class GrokApplyBusyError extends Error {}
|
|
72
|
+
|
|
73
|
+
export function grokApplyFlightSnapshot(): { currentBytes: number; highWaterBytes: number; active: number } {
|
|
74
|
+
return {
|
|
75
|
+
currentBytes: grokApplyFlight?.bytes ?? 0,
|
|
76
|
+
highWaterBytes: grokApplyHighWaterBytes,
|
|
77
|
+
active: grokApplyFlight ? 1 : 0,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function runGrokApplyFlight(): Promise<unknown> {
|
|
82
|
+
const at = grokApplyTestHooks?.now?.() ?? Date.now();
|
|
83
|
+
const current = grokApplyFlight;
|
|
84
|
+
if (current) {
|
|
85
|
+
const age = at - current.startedAt;
|
|
86
|
+
if (age < GROK_APPLY_JOIN_MS) return current.promise;
|
|
87
|
+
if (age <= GROK_APPLY_TERMINAL_MS) return Promise.reject(new GrokApplyBusyError("grok_apply_busy"));
|
|
88
|
+
// A permanently hung operation must not monopolize the singleton forever. Its
|
|
89
|
+
// eventual finally is identity-checked, so it cannot clear a replacement flight.
|
|
90
|
+
if (grokApplyFlight === current) grokApplyFlight = null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const flight = { startedAt: at, promise: Promise.resolve() as Promise<unknown>, bytes: 0 };
|
|
94
|
+
flight.promise = (grokApplyTestHooks?.run ?? (async () => {
|
|
95
|
+
const [{ syncGrokConfig }, { readRuntimePort }] = await Promise.all([
|
|
96
|
+
import("../../grok/sync"),
|
|
97
|
+
import("../../config"),
|
|
98
|
+
]);
|
|
99
|
+
const currentConfig = loadConfig();
|
|
100
|
+
const runtime = readRuntimePort(process.pid);
|
|
101
|
+
const port = runtime?.port ?? currentConfig.port;
|
|
102
|
+
const hostname = runtime?.hostname ?? currentConfig.hostname;
|
|
103
|
+
flight.bytes = grokApplyEncoder.encode(JSON.stringify(currentConfig)).byteLength
|
|
104
|
+
+ grokApplyEncoder.encode(hostname ?? "").byteLength;
|
|
105
|
+
grokApplyHighWaterBytes = Math.max(grokApplyHighWaterBytes, flight.bytes);
|
|
106
|
+
return syncGrokConfig(port, currentConfig, hostname !== undefined ? { hostname } : {});
|
|
107
|
+
}))().finally(() => {
|
|
108
|
+
if (grokApplyFlight === flight) grokApplyFlight = null;
|
|
109
|
+
});
|
|
110
|
+
grokApplyFlight = flight;
|
|
111
|
+
return flight.promise;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function runGrokApplyFlightForTests(): Promise<unknown> {
|
|
115
|
+
return runGrokApplyFlight();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function setGrokApplyFlightTestHooks(
|
|
119
|
+
hooks: { now?: () => number; run?: () => Promise<unknown> } | null,
|
|
120
|
+
): void {
|
|
121
|
+
grokApplyTestHooks = hooks;
|
|
122
|
+
grokApplyFlight = null;
|
|
123
|
+
grokApplyHighWaterBytes = 0;
|
|
124
|
+
}
|
|
125
|
+
import type { ManagementContext } from "./context";
|
|
126
|
+
|
|
127
|
+
export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise<Response | null> {
|
|
128
|
+
const { req, url, config, deps, refreshCodexCatalogBestEffort, syncClaudeAgentDefsBestEffort } = ctx;
|
|
129
|
+
|
|
130
|
+
/** Best-effort Desktop 3P config auto-reconcile when providers change. */
|
|
131
|
+
async function autoApplyDesktopBestEffort(): Promise<void> {
|
|
132
|
+
try {
|
|
133
|
+
if (config.claudeCode?.desktopAutoApply === false) return;
|
|
134
|
+
if (!config.claudeCode?.desktopProfile) return;
|
|
135
|
+
const { writeDesktop3pConfig } = await import("../../claude/desktop-3p");
|
|
136
|
+
const { filterCatalogVisibleModels, desktopVisibleNativeSlugs } = await import("../../codex/catalog");
|
|
137
|
+
const allModels = await fetchAllModels(config);
|
|
138
|
+
const routed = filterCatalogVisibleModels(allModels, config).map(m => ({ provider: m.provider, id: m.id, contextWindow: m.contextWindow }));
|
|
139
|
+
const result = writeDesktop3pConfig(
|
|
140
|
+
config.port ?? 10100,
|
|
141
|
+
[...desktopVisibleNativeSlugs(config)],
|
|
142
|
+
routed,
|
|
143
|
+
config.apiKeys?.[0]?.key,
|
|
144
|
+
"static",
|
|
145
|
+
config.claudeCode.desktopProfile,
|
|
146
|
+
);
|
|
147
|
+
if (result.written && result.fingerprint) {
|
|
148
|
+
config.claudeCode = { ...config.claudeCode, desktopProfile: { ...config.claudeCode.desktopProfile, appliedFingerprint: result.fingerprint, appliedAt: new Date().toISOString() } };
|
|
149
|
+
saveConfigPreservingClaudeCode(config);
|
|
150
|
+
}
|
|
151
|
+
} catch { /* best-effort */ }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// multi_agent_v2 surface toggle. GET reports the flag + the agents.max_threads
|
|
155
|
+
// boot conflict; PUT flips it via the official `codex features` CLI and RESYNCS
|
|
156
|
+
// the catalog so multi-agent surface metadata stays fresh. The catalog build
|
|
157
|
+
// itself never writes config — this endpoint is the only server-side mutation
|
|
158
|
+
// surface for the flag.
|
|
159
|
+
if (url.pathname === "/api/v2" && req.method === "GET") {
|
|
160
|
+
const {
|
|
161
|
+
isMultiAgentV2Enabled, hasAgentsMaxThreads, getLogicalMaxThreads,
|
|
162
|
+
getAgentsEnabled, getAgentsMaxDepth, getSubagentDeveloperInstructions,
|
|
163
|
+
} = await import("../../codex/features");
|
|
164
|
+
const enabled = isMultiAgentV2Enabled();
|
|
165
|
+
return jsonResponse({
|
|
166
|
+
enabled,
|
|
167
|
+
agentsMaxThreadsConflict: enabled && hasAgentsMaxThreads(),
|
|
168
|
+
maxConcurrentThreadsPerSession: getLogicalMaxThreads(),
|
|
169
|
+
multiAgentMode: config.multiAgentMode ?? "default",
|
|
170
|
+
agentsEnabled: getAgentsEnabled(),
|
|
171
|
+
agentsMaxDepth: getAgentsMaxDepth(),
|
|
172
|
+
subagentDeveloperInstructions: getSubagentDeveloperInstructions(),
|
|
173
|
+
// max_depth is V1-only upstream; this is the global-flag statement, derived
|
|
174
|
+
// server-side so no client can present it as an effective V2 limit.
|
|
175
|
+
agentsMaxDepthAppliesWhenV2Disabled: !enabled,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
if (url.pathname === "/api/v2" && req.method === "PUT") {
|
|
179
|
+
let body: {
|
|
180
|
+
enabled?: unknown;
|
|
181
|
+
maxConcurrentThreadsPerSession?: unknown;
|
|
182
|
+
multiAgentMode?: unknown;
|
|
183
|
+
agentsEnabled?: unknown;
|
|
184
|
+
agentsMaxDepth?: unknown;
|
|
185
|
+
subagentDeveloperInstructions?: unknown;
|
|
186
|
+
};
|
|
187
|
+
try { body = await readManagementJsonBody(req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid JSON body" }, 400); }
|
|
188
|
+
const wantsFlag = body.enabled !== undefined;
|
|
189
|
+
const wantsThreads = body.maxConcurrentThreadsPerSession !== undefined;
|
|
190
|
+
const wantsMode = body.multiAgentMode !== undefined;
|
|
191
|
+
const wantsAgentsEnabled = body.agentsEnabled !== undefined;
|
|
192
|
+
const wantsMaxDepth = body.agentsMaxDepth !== undefined;
|
|
193
|
+
const wantsSubagentInstructions = body.subagentDeveloperInstructions !== undefined;
|
|
194
|
+
if (!wantsFlag && !wantsThreads && !wantsMode && !wantsAgentsEnabled && !wantsMaxDepth && !wantsSubagentInstructions) {
|
|
195
|
+
return jsonResponse({ error: "body must set enabled, multiAgentMode, maxConcurrentThreadsPerSession, agentsEnabled, agentsMaxDepth, and/or subagentDeveloperInstructions" }, 400);
|
|
196
|
+
}
|
|
197
|
+
if (wantsFlag && typeof body.enabled !== "boolean") return jsonResponse({ error: "body.enabled must be a boolean" }, 400);
|
|
198
|
+
if (wantsMode && body.multiAgentMode !== "v1" && body.multiAgentMode !== "default" && body.multiAgentMode !== "v2") {
|
|
199
|
+
return jsonResponse({ error: "body.multiAgentMode must be 'v1', 'default', or 'v2'" }, 400);
|
|
200
|
+
}
|
|
201
|
+
if (wantsThreads && (typeof body.maxConcurrentThreadsPerSession !== "number" || !Number.isInteger(body.maxConcurrentThreadsPerSession) || body.maxConcurrentThreadsPerSession < 1)) {
|
|
202
|
+
return jsonResponse({ error: "body.maxConcurrentThreadsPerSession must be an integer >= 1" }, 400);
|
|
203
|
+
}
|
|
204
|
+
// Validate every new field BEFORE any write, so each 400 leaves config untouched.
|
|
205
|
+
// null unsets the key; "" is a meaningful value for instructions and must not be
|
|
206
|
+
// collapsed by a falsy check. The i32 preflight mirrors the upstream Option<i32>
|
|
207
|
+
// contract — out-of-range would otherwise surface as a mid-sequence write failure.
|
|
208
|
+
if (wantsAgentsEnabled && body.agentsEnabled !== null && typeof body.agentsEnabled !== "boolean") {
|
|
209
|
+
return jsonResponse({ error: "body.agentsEnabled must be a boolean or null" }, 400);
|
|
210
|
+
}
|
|
211
|
+
if (wantsMaxDepth && body.agentsMaxDepth !== null
|
|
212
|
+
&& (typeof body.agentsMaxDepth !== "number" || !Number.isInteger(body.agentsMaxDepth)
|
|
213
|
+
|| body.agentsMaxDepth < -2_147_483_648 || body.agentsMaxDepth > 2_147_483_647)) {
|
|
214
|
+
return jsonResponse({ error: "body.agentsMaxDepth must be an integer within signed i32 range, or null" }, 400);
|
|
215
|
+
}
|
|
216
|
+
if (wantsSubagentInstructions && body.subagentDeveloperInstructions !== null && typeof body.subagentDeveloperInstructions !== "string") {
|
|
217
|
+
return jsonResponse({ error: "body.subagentDeveloperInstructions must be a string or null" }, 400);
|
|
218
|
+
}
|
|
219
|
+
const mode = wantsMode ? body.multiAgentMode as "v1" | "default" | "v2" : undefined;
|
|
220
|
+
const modeFlag = mode === "v2" ? true : mode === "v1" ? false : undefined;
|
|
221
|
+
if (wantsFlag && modeFlag !== undefined && body.enabled !== modeFlag) {
|
|
222
|
+
return jsonResponse({ error: `body.enabled conflicts with multiAgentMode '${mode}'` }, 400);
|
|
223
|
+
}
|
|
224
|
+
const {
|
|
225
|
+
isMultiAgentV2Enabled, hasAgentsMaxThreads, getLogicalMaxThreads, transitionMultiAgentV2,
|
|
226
|
+
getAgentsEnabled, getAgentsMaxDepth, getSubagentDeveloperInstructions,
|
|
227
|
+
setAgentsEnabled, setAgentsMaxDepth, setSubagentDeveloperInstructions,
|
|
228
|
+
} = await import("../../codex/features");
|
|
229
|
+
const warnings: string[] = [];
|
|
230
|
+
const requestedFlag = wantsFlag ? body.enabled as boolean : modeFlag;
|
|
231
|
+
if (requestedFlag !== undefined || wantsThreads) {
|
|
232
|
+
const targetFlag = requestedFlag ?? isMultiAgentV2Enabled();
|
|
233
|
+
let toggle = deps.toggleCodexMultiAgentV2;
|
|
234
|
+
if (!toggle) {
|
|
235
|
+
const { execFileSync } = await import("node:child_process");
|
|
236
|
+
const { codexFeaturesInvocation } = await import("../../cli/v2");
|
|
237
|
+
toggle = (enabled: boolean) => {
|
|
238
|
+
const inv = codexFeaturesInvocation(enabled ? "enable" : "disable");
|
|
239
|
+
execFileSync(inv.file, inv.args,
|
|
240
|
+
{ stdio: ["ignore", "pipe", "pipe"], timeout: 15_000, windowsHide: true, ...inv.options });
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const result = transitionMultiAgentV2(targetFlag, toggle, {
|
|
244
|
+
...(wantsThreads ? { threadLimit: body.maxConcurrentThreadsPerSession as number } : {}),
|
|
245
|
+
});
|
|
246
|
+
if (!result.ok) return jsonResponse({ error: `multi_agent_v2 transition failed: ${result.error}` }, 502);
|
|
247
|
+
if (result.changed && result.threadLimit !== null) warnings.push(`Thread limit ${result.threadLimit} preserved for ${targetFlag ? "v2" : "v1"}.`);
|
|
248
|
+
}
|
|
249
|
+
if (wantsMode) {
|
|
250
|
+
if (mode === "default") delete config.multiAgentMode;
|
|
251
|
+
else config.multiAgentMode = mode;
|
|
252
|
+
saveConfigPreservingClaudeCode(config);
|
|
253
|
+
warnings.push(`Multi-agent mode set to '${mode}'. Applies to new sessions.`);
|
|
254
|
+
}
|
|
255
|
+
// New-key scalar writes: each writer is individually atomic, so apply them in
|
|
256
|
+
// sequence after the transition. A failure here is a persistence failure (the
|
|
257
|
+
// writers' ok:false result or a throw from the underlying atomic write helper),
|
|
258
|
+
// reported as 502 naming the failed key plus the writes that already landed.
|
|
259
|
+
// NOTE: do not name that helper literally here — tests/grok-writer-boundary.test.ts
|
|
260
|
+
// asserts this route file contains no direct write primitive, and matches on the
|
|
261
|
+
// symbol name even inside a comment.
|
|
262
|
+
const scalarWrites: Array<{ field: string; run: () => { ok: true; changed: boolean } | { ok: false; error: string } }> = [];
|
|
263
|
+
if (wantsAgentsEnabled) scalarWrites.push({ field: "agentsEnabled", run: () => setAgentsEnabled(body.agentsEnabled as boolean | null) });
|
|
264
|
+
if (wantsMaxDepth) scalarWrites.push({ field: "agentsMaxDepth", run: () => setAgentsMaxDepth(body.agentsMaxDepth as number | null) });
|
|
265
|
+
if (wantsSubagentInstructions) scalarWrites.push({ field: "subagentDeveloperInstructions", run: () => setSubagentDeveloperInstructions(body.subagentDeveloperInstructions as string | null) });
|
|
266
|
+
const landed: string[] = [];
|
|
267
|
+
for (const write of scalarWrites) {
|
|
268
|
+
try {
|
|
269
|
+
const result = write.run();
|
|
270
|
+
if (!result.ok) {
|
|
271
|
+
return jsonResponse({ error: `writing ${write.field} failed: ${result.error}${landed.length > 0 ? ` (already applied: ${landed.join(", ")})` : ""}` }, 502);
|
|
272
|
+
}
|
|
273
|
+
landed.push(write.field);
|
|
274
|
+
} catch (err) {
|
|
275
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
276
|
+
return jsonResponse({ error: `writing ${write.field} failed: ${message}${landed.length > 0 ? ` (already applied: ${landed.join(", ")})` : ""}` }, 502);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
// Derived from fresh post-write readers (readConfigText is uncached): upstream
|
|
280
|
+
// lets an enabled multi_agent_v2 feature override [agents].enabled = false, so
|
|
281
|
+
// warn rather than reject — silently accepting would imply multi-agent is off.
|
|
282
|
+
if (getAgentsEnabled() === false && isMultiAgentV2Enabled()) {
|
|
283
|
+
warnings.push("agents.enabled = false has no effect while features.multi_agent_v2 is enabled; upstream keeps V2 active.");
|
|
284
|
+
}
|
|
285
|
+
await refreshCodexCatalogBestEffort();
|
|
286
|
+
if (requestedFlag !== undefined) warnings.push("Applies to new sessions; restart the Codex app or wait out its picker cache to see the ladder change.");
|
|
287
|
+
const enabled = isMultiAgentV2Enabled();
|
|
288
|
+
return jsonResponse({
|
|
289
|
+
ok: true,
|
|
290
|
+
enabled,
|
|
291
|
+
agentsMaxThreadsConflict: enabled && hasAgentsMaxThreads(),
|
|
292
|
+
maxConcurrentThreadsPerSession: getLogicalMaxThreads(),
|
|
293
|
+
multiAgentMode: config.multiAgentMode ?? "default",
|
|
294
|
+
agentsEnabled: getAgentsEnabled(),
|
|
295
|
+
agentsMaxDepth: getAgentsMaxDepth(),
|
|
296
|
+
subagentDeveloperInstructions: getSubagentDeveloperInstructions(),
|
|
297
|
+
agentsMaxDepthAppliesWhenV2Disabled: !enabled,
|
|
298
|
+
warnings,
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Subagent prompt injection model: single native or routed model whose info is
|
|
303
|
+
// dynamically injected into the v1 proactive prompt, plus an optional reasoning
|
|
304
|
+
// effort the prompt tells the agent to pass to spawn_agent. GET returns the current
|
|
305
|
+
// picks + available models/efforts; PUT sets or clears them.
|
|
306
|
+
if (url.pathname === "/api/injection-model" && req.method === "GET") {
|
|
307
|
+
const models = await fetchAllModels(config);
|
|
308
|
+
const disabled = new Set(config.disabledModels ?? []);
|
|
309
|
+
const { listCatalogNativeSlugs } = await import("../../codex/catalog");
|
|
310
|
+
const { CODEX_REASONING_LEVELS } = await import("../../reasoning-effort");
|
|
311
|
+
const nativeModels = listCatalogNativeSlugs()
|
|
312
|
+
.filter(slug => !disabled.has(slug))
|
|
313
|
+
.map(slug => ({ provider: "openai", model: slug, namespaced: slug }));
|
|
314
|
+
const routedModels = uniqueCatalogModelsForPublicList(models)
|
|
315
|
+
.map(m => ({ provider: m.provider, model: m.id, namespaced: catalogModelSlug(m) }))
|
|
316
|
+
.filter(m => ![...disabled].some(stored => (
|
|
317
|
+
stored === m.namespaced || slugEquals(stored, m.provider, m.model)
|
|
318
|
+
)));
|
|
319
|
+
return jsonResponse({
|
|
320
|
+
multiAgentGuidanceEnabled: multiAgentGuidanceEnabled(config),
|
|
321
|
+
syncCodexSubagentDefaults: subagentDefaultSyncEffective(config),
|
|
322
|
+
model: config.injectionModel ?? null,
|
|
323
|
+
effort: config.injectionEffort ?? null,
|
|
324
|
+
prompt: config.injectionPrompt ?? null,
|
|
325
|
+
efforts: CODEX_REASONING_LEVELS.map(l => l.effort),
|
|
326
|
+
available: [...nativeModels, ...routedModels],
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
if (url.pathname === "/api/injection-model" && req.method === "PUT") {
|
|
330
|
+
let parsedBody: unknown;
|
|
331
|
+
try { parsedBody = await readManagementJsonBody(req); } catch (error) {
|
|
332
|
+
rethrowManagementBodyTooLarge(error);
|
|
333
|
+
return jsonResponse({ error: "invalid JSON body" }, 400);
|
|
334
|
+
}
|
|
335
|
+
if (!parsedBody || typeof parsedBody !== "object" || Array.isArray(parsedBody)) {
|
|
336
|
+
return jsonResponse({ error: "body must be a JSON object" }, 400);
|
|
337
|
+
}
|
|
338
|
+
const body = parsedBody as {
|
|
339
|
+
multiAgentGuidanceEnabled?: unknown;
|
|
340
|
+
syncCodexSubagentDefaults?: unknown;
|
|
341
|
+
model?: unknown;
|
|
342
|
+
effort?: unknown;
|
|
343
|
+
prompt?: unknown;
|
|
344
|
+
};
|
|
345
|
+
const { isCodexReasoningEffort } = await import("../../reasoning-effort");
|
|
346
|
+
|
|
347
|
+
let nextEnabled = config.multiAgentGuidanceEnabled;
|
|
348
|
+
// Start from the effective state reported by GET. A stale hand-edited
|
|
349
|
+
// `true` without a model must not spring back on during a model-only PUT.
|
|
350
|
+
let nextSyncCodexSubagentDefaults = subagentDefaultSyncEffective(config);
|
|
351
|
+
let nextModel = config.injectionModel;
|
|
352
|
+
let nextEffort = config.injectionEffort;
|
|
353
|
+
let nextPrompt = config.injectionPrompt;
|
|
354
|
+
|
|
355
|
+
if ("multiAgentGuidanceEnabled" in body) {
|
|
356
|
+
if (typeof body.multiAgentGuidanceEnabled !== "boolean") {
|
|
357
|
+
return jsonResponse({ error: "multiAgentGuidanceEnabled must be a boolean" }, 400);
|
|
358
|
+
}
|
|
359
|
+
nextEnabled = body.multiAgentGuidanceEnabled;
|
|
360
|
+
}
|
|
361
|
+
if ("syncCodexSubagentDefaults" in body) {
|
|
362
|
+
if (typeof body.syncCodexSubagentDefaults !== "boolean") {
|
|
363
|
+
return jsonResponse({ error: "syncCodexSubagentDefaults must be a boolean" }, 400);
|
|
364
|
+
}
|
|
365
|
+
nextSyncCodexSubagentDefaults = body.syncCodexSubagentDefaults;
|
|
366
|
+
}
|
|
367
|
+
if ("model" in body) {
|
|
368
|
+
if (body.model === null || body.model === "") nextModel = undefined;
|
|
369
|
+
else if (typeof body.model === "string" && body.model.trim().length > 0) nextModel = body.model;
|
|
370
|
+
else return jsonResponse({ error: "model must be a nonblank string or null" }, 400);
|
|
371
|
+
}
|
|
372
|
+
if ("effort" in body) {
|
|
373
|
+
if (body.effort === null || body.effort === "") nextEffort = undefined;
|
|
374
|
+
else if (typeof body.effort === "string" && isCodexReasoningEffort(body.effort)) {
|
|
375
|
+
nextEffort = body.effort;
|
|
376
|
+
} else {
|
|
377
|
+
return jsonResponse({ error: `unknown reasoning effort "${String(body.effort)}"` }, 400);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if ("prompt" in body) {
|
|
381
|
+
if (typeof body.prompt === "string" && body.prompt.trim().length > 0) nextPrompt = body.prompt;
|
|
382
|
+
else if (body.prompt === null || body.prompt === "") nextPrompt = undefined;
|
|
383
|
+
else return jsonResponse({ error: "prompt must be a string or null" }, 400);
|
|
384
|
+
}
|
|
385
|
+
// Clearing the model always clears model-dependent settings before sync/effort gates.
|
|
386
|
+
if (!nextModel) {
|
|
387
|
+
nextEffort = undefined;
|
|
388
|
+
nextSyncCodexSubagentDefaults = false;
|
|
389
|
+
}
|
|
390
|
+
if (body.syncCodexSubagentDefaults === true && !nextModel?.trim()) {
|
|
391
|
+
return jsonResponse({ error: "syncCodexSubagentDefaults requires an injection model" }, 400);
|
|
392
|
+
}
|
|
393
|
+
if (nextSyncCodexSubagentDefaults && nextEffort !== undefined && !isCodexReasoningEffort(nextEffort)) {
|
|
394
|
+
return jsonResponse({ error: "syncCodexSubagentDefaults requires a supported Codex reasoning effort" }, 400);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
config.multiAgentGuidanceEnabled = nextEnabled;
|
|
398
|
+
if (nextSyncCodexSubagentDefaults) config.syncCodexSubagentDefaults = true;
|
|
399
|
+
else delete config.syncCodexSubagentDefaults;
|
|
400
|
+
if (nextModel) config.injectionModel = nextModel;
|
|
401
|
+
else delete config.injectionModel;
|
|
402
|
+
if (nextEffort) config.injectionEffort = nextEffort;
|
|
403
|
+
else delete config.injectionEffort;
|
|
404
|
+
if (nextPrompt) config.injectionPrompt = nextPrompt;
|
|
405
|
+
else delete config.injectionPrompt;
|
|
406
|
+
|
|
407
|
+
saveConfigPreservingClaudeCode(config);
|
|
408
|
+
return jsonResponse({
|
|
409
|
+
ok: true,
|
|
410
|
+
multiAgentGuidanceEnabled: multiAgentGuidanceEnabled(config),
|
|
411
|
+
syncCodexSubagentDefaults: subagentDefaultSyncEffective(config),
|
|
412
|
+
model: config.injectionModel ?? null,
|
|
413
|
+
effort: config.injectionEffort ?? null,
|
|
414
|
+
prompt: config.injectionPrompt ?? null,
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// Hard reasoning-effort caps (devlog/260710_subagent_effort_intercept): a global ceiling and a
|
|
419
|
+
// sub-agent-only ceiling, enforced per-request in handleResponses (src/server/effort-policy.ts).
|
|
420
|
+
// Key semantics per field: absent -> unchanged; null/"" -> clear; ladder value -> set; else 400.
|
|
421
|
+
if (url.pathname === "/api/effort-caps" && req.method === "GET") {
|
|
422
|
+
const { CODEX_REASONING_LEVELS } = await import("../../reasoning-effort");
|
|
423
|
+
return jsonResponse({
|
|
424
|
+
effortCap: config.effortCap ?? null,
|
|
425
|
+
subagentEffortCap: config.subagentEffortCap ?? null,
|
|
426
|
+
efforts: CODEX_REASONING_LEVELS.map(l => l.effort),
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
if (url.pathname === "/api/effort-caps" && req.method === "PUT") {
|
|
430
|
+
let body: { effortCap?: unknown; subagentEffortCap?: unknown };
|
|
431
|
+
try { body = await readManagementJsonBody(req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid JSON body" }, 400); }
|
|
432
|
+
const { isCodexReasoningEffort } = await import("../../reasoning-effort");
|
|
433
|
+
for (const key of ["effortCap", "subagentEffortCap"] as const) {
|
|
434
|
+
if (!(key in body)) continue;
|
|
435
|
+
const value = body[key];
|
|
436
|
+
if (value === null || value === "") { delete config[key]; continue; }
|
|
437
|
+
if (typeof value !== "string" || !isCodexReasoningEffort(value)) {
|
|
438
|
+
return jsonResponse({ error: `unknown reasoning effort "${String(value)}"` }, 400);
|
|
439
|
+
}
|
|
440
|
+
config[key] = value;
|
|
441
|
+
}
|
|
442
|
+
saveConfigPreservingClaudeCode(config);
|
|
443
|
+
return jsonResponse({ ok: true, effortCap: config.effortCap ?? null, subagentEffortCap: config.subagentEffortCap ?? null });
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// Subagent model picker: which ≤5 routed models Codex's spawn_agent advertises (it shows the
|
|
447
|
+
// first 5 routed catalog entries). PUT reorders the injected catalog so the chosen ones lead.
|
|
448
|
+
if (url.pathname === "/api/subagent-models" && req.method === "GET") {
|
|
449
|
+
const models = await fetchAllModels(config);
|
|
450
|
+
const disabled = new Set(config.disabledModels ?? []);
|
|
451
|
+
// Native gpt (passthrough) are also valid subagent picks — they're picker-visible models in the
|
|
452
|
+
// catalog, just buried by priority. List them first so the user can feature them over routed.
|
|
453
|
+
const { listCatalogNativeSlugs } = await import("../../codex/catalog");
|
|
454
|
+
const visibleRouted = [...new Set(models
|
|
455
|
+
.filter(m => ![...disabled].some(stored =>
|
|
456
|
+
stored === catalogModelSlug(m) || slugEquals(stored, m.provider, m.id)
|
|
457
|
+
))
|
|
458
|
+
.map(catalogModelSlug))];
|
|
459
|
+
const available = [
|
|
460
|
+
...listCatalogNativeSlugs().filter(ns => !disabled.has(ns)),
|
|
461
|
+
...visibleRouted,
|
|
462
|
+
];
|
|
463
|
+
// #857: let CLI/GUI show when a running Codex app-server keeps an older
|
|
464
|
+
// in-memory catalog than the one on disk.
|
|
465
|
+
const { collectCodexAppServerCatalogState } = await import("../../codex/app-server-processes");
|
|
466
|
+
const catalogState = collectCodexAppServerCatalogState();
|
|
467
|
+
return jsonResponse({ chosen: config.subagentModels ?? [], available, catalogState });
|
|
468
|
+
}
|
|
469
|
+
if (url.pathname === "/api/subagent-models" && req.method === "PUT") {
|
|
470
|
+
let body: { models?: unknown };
|
|
471
|
+
try { body = await readManagementJsonBody(req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid JSON body" }, 400); }
|
|
472
|
+
const chosen = Array.isArray(body.models) ? body.models.filter((m): m is string => typeof m === "string").slice(0, 5) : [];
|
|
473
|
+
config.subagentModels = chosen;
|
|
474
|
+
const { saveConfigPreservingClaudeCode: save } = await import("../../config");
|
|
475
|
+
save(config);
|
|
476
|
+
await refreshCodexCatalogBestEffort();
|
|
477
|
+
await syncClaudeAgentDefsBestEffort();
|
|
478
|
+
await autoApplyDesktopBestEffort();
|
|
479
|
+
return jsonResponse({ ok: true, applied: chosen });
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// Priority-ordered subagent model fallback chain for quota-aware spawn routing.
|
|
483
|
+
if (url.pathname === "/api/subagent-model-fallback" && req.method === "GET") {
|
|
484
|
+
const models = await fetchAllModels(config);
|
|
485
|
+
const disabled = new Set(config.disabledModels ?? []);
|
|
486
|
+
const { listCatalogNativeSlugs } = await import("../../codex/catalog");
|
|
487
|
+
const visibleRouted = [...new Set(models
|
|
488
|
+
.filter(m => ![...disabled].some(stored =>
|
|
489
|
+
stored === catalogModelSlug(m) || slugEquals(stored, m.provider, m.id)
|
|
490
|
+
))
|
|
491
|
+
.map(catalogModelSlug))];
|
|
492
|
+
const available = [
|
|
493
|
+
...listCatalogNativeSlugs().filter(ns => !disabled.has(ns)),
|
|
494
|
+
...visibleRouted,
|
|
495
|
+
];
|
|
496
|
+
return jsonResponse({
|
|
497
|
+
models: config.subagentModelFallback ?? [],
|
|
498
|
+
pollMs: config.subagentModelFallbackPollMs ?? 60_000,
|
|
499
|
+
available,
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
if (url.pathname === "/api/subagent-model-fallback" && req.method === "PUT") {
|
|
503
|
+
let body: { models?: unknown; pollMs?: unknown };
|
|
504
|
+
try {
|
|
505
|
+
body = await readManagementJsonBody(req);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
rethrowManagementBodyTooLarge(error);
|
|
508
|
+
return jsonResponse({ error: "invalid JSON body" }, 400);
|
|
509
|
+
}
|
|
510
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
511
|
+
return jsonResponse({ error: "invalid JSON body" }, 400);
|
|
512
|
+
}
|
|
513
|
+
let nextModels = config.subagentModelFallback;
|
|
514
|
+
let nextPollMs = config.subagentModelFallbackPollMs;
|
|
515
|
+
if ("models" in body) {
|
|
516
|
+
if (!Array.isArray(body.models)) return jsonResponse({ error: "models must be an array" }, 400);
|
|
517
|
+
const models: string[] = [];
|
|
518
|
+
for (let i = 0; i < body.models.length; i++) {
|
|
519
|
+
const entry = body.models[i];
|
|
520
|
+
if (typeof entry !== "string" || entry.trim().length === 0) {
|
|
521
|
+
return jsonResponse({
|
|
522
|
+
error: `models[${i}] must be a non-empty string`,
|
|
523
|
+
index: i,
|
|
524
|
+
value: entry,
|
|
525
|
+
}, 400);
|
|
526
|
+
}
|
|
527
|
+
models.push(entry.trim());
|
|
528
|
+
}
|
|
529
|
+
nextModels = models.length > 0 ? models : undefined;
|
|
530
|
+
}
|
|
531
|
+
if ("pollMs" in body) {
|
|
532
|
+
const pollMs = body.pollMs;
|
|
533
|
+
if (pollMs === null || pollMs === "") nextPollMs = undefined;
|
|
534
|
+
else if (typeof pollMs === "number" && Number.isInteger(pollMs) && pollMs >= 5_000 && pollMs <= 600_000) {
|
|
535
|
+
nextPollMs = pollMs;
|
|
536
|
+
} else {
|
|
537
|
+
return jsonResponse({ error: "pollMs must be an integer between 5000 and 600000" }, 400);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (nextModels !== undefined) config.subagentModelFallback = nextModels;
|
|
541
|
+
else delete config.subagentModelFallback;
|
|
542
|
+
if (nextPollMs !== undefined) config.subagentModelFallbackPollMs = nextPollMs;
|
|
543
|
+
else delete config.subagentModelFallbackPollMs;
|
|
544
|
+
saveConfigPreservingClaudeCode(config);
|
|
545
|
+
return jsonResponse({
|
|
546
|
+
ok: true,
|
|
547
|
+
models: config.subagentModelFallback ?? [],
|
|
548
|
+
pollMs: config.subagentModelFallbackPollMs ?? 60_000,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// Grok Build: view of the managed fence in ~/.grok/config.toml plus the candidate
|
|
553
|
+
// catalog and the user's selection. The fence itself is still written ONLY by
|
|
554
|
+
// injectGrokConfig — the write routes below carry no path/host/port/body input.
|
|
555
|
+
if (url.pathname === "/api/grok" && req.method === "GET") {
|
|
556
|
+
try {
|
|
557
|
+
const { readGrokStatus } = await import("../../grok/status");
|
|
558
|
+
// `candidates` is the full visible catalog the fence WOULD carry, so the page can
|
|
559
|
+
// show a switch for a model the user has already excluded. Aliases come from
|
|
560
|
+
// `status.models` — the writer's output — never computed client-side.
|
|
561
|
+
return jsonResponse({
|
|
562
|
+
...readGrokStatus(),
|
|
563
|
+
candidates: await fetchGrokCandidateModels(config),
|
|
564
|
+
excluded: config.grokExcludedModels ?? [],
|
|
565
|
+
});
|
|
566
|
+
} catch (error) {
|
|
567
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// Writes CONFIG only. ~/.grok/config.toml is still written exclusively by
|
|
572
|
+
// injectGrokConfig, through the apply route below — this route cannot touch that file.
|
|
573
|
+
if (url.pathname === "/api/grok/selection" && req.method === "PUT") {
|
|
574
|
+
let body: { excluded?: unknown };
|
|
575
|
+
try { body = await readManagementJsonBody(req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid JSON body" }, 400); }
|
|
576
|
+
const raw = body.excluded;
|
|
577
|
+
if (!Array.isArray(raw) || raw.some(entry => typeof entry !== "string" || entry.length === 0)) {
|
|
578
|
+
return jsonResponse({ error: "excluded must be an array of model ids" }, 400);
|
|
579
|
+
}
|
|
580
|
+
// Dedupe + sort so the stored list is stable, and cap it so a hostile client
|
|
581
|
+
// cannot grow config.json without bound.
|
|
582
|
+
const excluded = [...new Set(raw as string[])].sort();
|
|
583
|
+
if (excluded.length > 2000) return jsonResponse({ error: "excluded list is too large" }, 400);
|
|
584
|
+
if (excluded.length === 0) delete config.grokExcludedModels;
|
|
585
|
+
else config.grokExcludedModels = excluded;
|
|
586
|
+
saveConfigPreservingClaudeCode(config);
|
|
587
|
+
return jsonResponse({ ok: true, excluded });
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// Re-runs the SAME sync the CLI runs. All guards (no-grok-home, non-loopback refusal,
|
|
591
|
+
// orphaned marker, backup, alias reservation) live in injectGrokConfig and are not
|
|
592
|
+
// duplicated here. Accepts no body: every input comes from persisted state.
|
|
593
|
+
if (url.pathname === "/api/grok/apply" && req.method === "POST") {
|
|
594
|
+
try {
|
|
595
|
+
const result = await runGrokApplyFlight() as Awaited<ReturnType<typeof import("../../grok/sync")["syncGrokConfig"]>>;
|
|
596
|
+
// A policy skip (non-loopback, no ~/.grok) is not a server error: report it as a
|
|
597
|
+
// result the page can explain rather than a 500 the user cannot act on.
|
|
598
|
+
return jsonResponse({
|
|
599
|
+
ok: result.ok,
|
|
600
|
+
changed: result.changed,
|
|
601
|
+
message: result.message,
|
|
602
|
+
...(result.skippedReason ? { skippedReason: result.skippedReason } : {}),
|
|
603
|
+
}, result.ok ? 200 : 500);
|
|
604
|
+
} catch (error) {
|
|
605
|
+
if (error instanceof GrokApplyBusyError) return jsonResponse({ error: "grok_apply_busy" }, 409);
|
|
606
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// Pi coding agent: status, models inject/remove, curated settings, packages, extensions.
|
|
611
|
+
// models.json only ever mutates providers.opencodex; package installs shell out to `pi`.
|
|
612
|
+
if (url.pathname === "/api/pi" && req.method === "GET") {
|
|
613
|
+
try {
|
|
614
|
+
const { readPiStatus, piInstallHint } = await import("../../pi/status");
|
|
615
|
+
const status = await readPiStatus();
|
|
616
|
+
return jsonResponse({
|
|
617
|
+
...status,
|
|
618
|
+
hint: piInstallHint(status),
|
|
619
|
+
port: Number(url.port) || config.port,
|
|
620
|
+
});
|
|
621
|
+
} catch (error) {
|
|
622
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
if (url.pathname === "/api/pi/apply" && req.method === "POST") {
|
|
626
|
+
try {
|
|
627
|
+
const { syncPiConfig } = await import("../../pi/sync");
|
|
628
|
+
const { findLiveProxy } = await import("../proxy-liveness");
|
|
629
|
+
const live = await findLiveProxy();
|
|
630
|
+
const port = live?.port ?? config.port;
|
|
631
|
+
const hostname = live?.hostname ?? config.hostname;
|
|
632
|
+
const result = await syncPiConfig(port, config, { hostname });
|
|
633
|
+
return jsonResponse({
|
|
634
|
+
ok: result.ok,
|
|
635
|
+
changed: result.changed,
|
|
636
|
+
message: result.message,
|
|
637
|
+
modelCount: result.modelCount,
|
|
638
|
+
modelsPath: result.modelsPath,
|
|
639
|
+
...(result.skippedReason ? { skippedReason: result.skippedReason } : {}),
|
|
640
|
+
}, result.ok ? 200 : 500);
|
|
641
|
+
} catch (error) {
|
|
642
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (url.pathname === "/api/pi/remove" && req.method === "POST") {
|
|
646
|
+
try {
|
|
647
|
+
const { removePiModels } = await import("../../pi/models");
|
|
648
|
+
const result = removePiModels();
|
|
649
|
+
return jsonResponse({
|
|
650
|
+
ok: result.ok,
|
|
651
|
+
changed: result.changed,
|
|
652
|
+
message: result.message,
|
|
653
|
+
modelsPath: result.modelsPath,
|
|
654
|
+
}, result.ok ? 200 : 500);
|
|
655
|
+
} catch (error) {
|
|
656
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
if (url.pathname === "/api/pi/settings" && req.method === "GET") {
|
|
660
|
+
try {
|
|
661
|
+
const { readPiSettings } = await import("../../pi/settings");
|
|
662
|
+
return jsonResponse(readPiSettings());
|
|
663
|
+
} catch (error) {
|
|
664
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if (url.pathname === "/api/pi/settings" && req.method === "PUT") {
|
|
668
|
+
let body: unknown;
|
|
669
|
+
try {
|
|
670
|
+
body = await readManagementJsonBody(req);
|
|
671
|
+
} catch (error) {
|
|
672
|
+
rethrowManagementBodyTooLarge(error);
|
|
673
|
+
return jsonResponse({ error: "invalid JSON body" }, 400);
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
const { writePiSettings } = await import("../../pi/settings");
|
|
677
|
+
const result = writePiSettings(body);
|
|
678
|
+
return jsonResponse({
|
|
679
|
+
ok: result.ok,
|
|
680
|
+
changed: result.changed,
|
|
681
|
+
message: result.message,
|
|
682
|
+
settingsPath: result.settingsPath,
|
|
683
|
+
...(result.settings ? { settings: result.settings } : {}),
|
|
684
|
+
}, result.ok ? 200 : 400);
|
|
685
|
+
} catch (error) {
|
|
686
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (url.pathname === "/api/pi/packages" && req.method === "GET") {
|
|
690
|
+
try {
|
|
691
|
+
const { listPiPackagesDetailed } = await import("../../pi/packages");
|
|
692
|
+
return jsonResponse(await listPiPackagesDetailed());
|
|
693
|
+
} catch (error) {
|
|
694
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
if (url.pathname === "/api/pi/packages/install" && req.method === "POST") {
|
|
698
|
+
let body: { source?: unknown };
|
|
699
|
+
try {
|
|
700
|
+
body = await readManagementJsonBody(req);
|
|
701
|
+
} catch (error) {
|
|
702
|
+
rethrowManagementBodyTooLarge(error);
|
|
703
|
+
return jsonResponse({ error: "invalid JSON body" }, 400);
|
|
704
|
+
}
|
|
705
|
+
if (typeof body.source !== "string") return jsonResponse({ error: "source is required" }, 400);
|
|
706
|
+
try {
|
|
707
|
+
const { installPiPackage } = await import("../../pi/packages");
|
|
708
|
+
const result = await installPiPackage(body.source);
|
|
709
|
+
return jsonResponse(result, result.ok ? 200 : 400);
|
|
710
|
+
} catch (error) {
|
|
711
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
if (url.pathname === "/api/pi/packages/remove" && req.method === "POST") {
|
|
715
|
+
let body: { source?: unknown };
|
|
716
|
+
try {
|
|
717
|
+
body = await readManagementJsonBody(req);
|
|
718
|
+
} catch (error) {
|
|
719
|
+
rethrowManagementBodyTooLarge(error);
|
|
720
|
+
return jsonResponse({ error: "invalid JSON body" }, 400);
|
|
721
|
+
}
|
|
722
|
+
if (typeof body.source !== "string") return jsonResponse({ error: "source is required" }, 400);
|
|
723
|
+
try {
|
|
724
|
+
const { removePiPackage } = await import("../../pi/packages");
|
|
725
|
+
const result = await removePiPackage(body.source);
|
|
726
|
+
return jsonResponse(result, result.ok ? 200 : 400);
|
|
727
|
+
} catch (error) {
|
|
728
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
if (url.pathname === "/api/pi/extensions" && req.method === "GET") {
|
|
732
|
+
try {
|
|
733
|
+
const { readPiExtensions } = await import("../../pi/extensions");
|
|
734
|
+
return jsonResponse(readPiExtensions());
|
|
735
|
+
} catch (error) {
|
|
736
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// Claude Desktop profile: routed/native model assignments for the Desktop 3P config.
|
|
741
|
+
if (url.pathname === "/api/claude-desktop" && req.method === "GET") {
|
|
742
|
+
try {
|
|
743
|
+
const state = await buildClaudeDesktopState(config);
|
|
744
|
+
const runtimePort = Number(url.port) || config.port;
|
|
745
|
+
return jsonResponse({ ...state, port: runtimePort });
|
|
746
|
+
} catch (error) {
|
|
747
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (url.pathname === "/api/claude-desktop" && req.method === "PUT") {
|
|
751
|
+
let body: { profile?: unknown };
|
|
752
|
+
try { body = await readManagementJsonBody(req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid JSON body" }, 400); }
|
|
753
|
+
try {
|
|
754
|
+
const { parseDesktopProfile, reconcileDesktopProfile } = await import("../../claude/desktop-profile");
|
|
755
|
+
const parsed = parseDesktopProfile(body.profile);
|
|
756
|
+
const current = await buildClaudeDesktopState(config);
|
|
757
|
+
for (const model of current.models.filter(item => !item.available)) {
|
|
758
|
+
const before = current.profile.assignments[model.route];
|
|
759
|
+
const after = parsed.assignments[model.route];
|
|
760
|
+
if (JSON.stringify(before) !== JSON.stringify(after)) {
|
|
761
|
+
throw new Error(`현재 사용할 수 없는 모델은 옮길 수 없습니다: ${model.route}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
for (const family of ["opus", "fable", "sonnet", "haiku"] as const) {
|
|
765
|
+
const nextDefault = parsed.defaults[family];
|
|
766
|
+
const target = nextDefault ? current.models.find(model => model.route === nextDefault) : undefined;
|
|
767
|
+
if (target && !target.available && current.profile.defaults[family] !== nextDefault) {
|
|
768
|
+
throw new Error(`현재 사용할 수 없는 모델은 기본값으로 지정할 수 없습니다: ${nextDefault}`);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
const state = await buildClaudeDesktopState(config, parsed);
|
|
772
|
+
config.claudeCode = { ...(config.claudeCode ?? {}), desktopProfile: reconcileDesktopProfile(state.profile, state.models) };
|
|
773
|
+
saveConfigPreservingClaudeCode(config);
|
|
774
|
+
const saved = await buildClaudeDesktopState(config);
|
|
775
|
+
const runtimePort = Number(url.port) || config.port;
|
|
776
|
+
return jsonResponse({ ok: true, ...saved, port: runtimePort });
|
|
777
|
+
} catch (error) {
|
|
778
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (url.pathname === "/api/claude-desktop/apply" && req.method === "POST") {
|
|
782
|
+
try {
|
|
783
|
+
// #859: the CLI delegates here so the registry is built in the serving
|
|
784
|
+
// process. Accept an optional mode; default stays static for back-compat.
|
|
785
|
+
let mode: "static" | "hybrid" | "discovery" = "static";
|
|
786
|
+
const rawBody = await req.text();
|
|
787
|
+
let parsed: unknown;
|
|
788
|
+
if (rawBody.trim()) {
|
|
789
|
+
try {
|
|
790
|
+
parsed = JSON.parse(rawBody);
|
|
791
|
+
} catch {
|
|
792
|
+
return jsonResponse({ error: "invalid JSON body" }, 400);
|
|
793
|
+
}
|
|
794
|
+
const requested = (parsed as { mode?: unknown } | null)?.mode;
|
|
795
|
+
if (requested !== undefined) {
|
|
796
|
+
if (requested === "static" || requested === "hybrid" || requested === "discovery") {
|
|
797
|
+
mode = requested;
|
|
798
|
+
} else {
|
|
799
|
+
return jsonResponse({ error: "mode must be static, hybrid, or discovery" }, 400);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
// #859: a delegated CLI apply carries the profile it just saved — the
|
|
804
|
+
// daemon's own config can be older, and building state from it would
|
|
805
|
+
// apply (and persist) the stale profile over the newer one.
|
|
806
|
+
const bodyProfile = (parsed as { profile?: unknown } | null)?.profile;
|
|
807
|
+
let profileOverride: Parameters<typeof buildClaudeDesktopState>[1];
|
|
808
|
+
if (bodyProfile !== undefined) {
|
|
809
|
+
const { parseDesktopProfile } = await import("../../claude/desktop-profile");
|
|
810
|
+
try {
|
|
811
|
+
profileOverride = parseDesktopProfile(bodyProfile);
|
|
812
|
+
} catch (error) {
|
|
813
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
const state = await buildClaudeDesktopState(config, profileOverride);
|
|
817
|
+
config.claudeCode = { ...(config.claudeCode ?? {}), desktopProfile: state.profile };
|
|
818
|
+
saveConfigPreservingClaudeCode(config);
|
|
819
|
+
const { writeDesktop3pConfig } = await import("../../claude/desktop-3p");
|
|
820
|
+
const { desktopVisibleNativeSlugs } = await import("../../codex/catalog");
|
|
821
|
+
const routed = state.models
|
|
822
|
+
.filter(model => model.available && !model.route.startsWith("native/"))
|
|
823
|
+
.map(model => {
|
|
824
|
+
const slash = model.route.indexOf("/");
|
|
825
|
+
return { provider: model.route.slice(0, slash), id: model.route.slice(slash + 1), contextWindow: model.contextWindow };
|
|
826
|
+
});
|
|
827
|
+
const result = writeDesktop3pConfig(
|
|
828
|
+
Number(url.port) || config.port,
|
|
829
|
+
[...desktopVisibleNativeSlugs(config)],
|
|
830
|
+
routed,
|
|
831
|
+
config.apiKeys?.[0]?.key,
|
|
832
|
+
mode,
|
|
833
|
+
state.profile,
|
|
834
|
+
);
|
|
835
|
+
if (!result.written) return jsonResponse({ error: result.reason ?? "Claude Desktop apply failed", saved: true, path: result.path }, 500);
|
|
836
|
+
// Persist applied fingerprint + timestamp so GUI can show saved-vs-applied state.
|
|
837
|
+
if (result.fingerprint) {
|
|
838
|
+
config.claudeCode = { ...(config.claudeCode ?? {}), desktopProfile: { ...state.profile, appliedFingerprint: result.fingerprint, appliedAt: new Date().toISOString() } };
|
|
839
|
+
saveConfigPreservingClaudeCode(config);
|
|
840
|
+
}
|
|
841
|
+
return jsonResponse({ ok: true, saved: true, applied: true, path: result.path, fingerprint: result.fingerprint });
|
|
842
|
+
} catch (error) {
|
|
843
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// Desktop applied-state + health status.
|
|
848
|
+
if (url.pathname === "/api/claude-desktop/status" && req.method === "GET") {
|
|
849
|
+
try {
|
|
850
|
+
const { readFileSync: readFile, existsSync } = await import("node:fs");
|
|
851
|
+
const { createHash } = await import("node:crypto");
|
|
852
|
+
const { join } = await import("node:path");
|
|
853
|
+
const { resolveDesktop3pConfigLibraryPath } = await import("../../claude/desktop-3p");
|
|
854
|
+
const libraryPath = resolveDesktop3pConfigLibraryPath();
|
|
855
|
+
const metaPath = join(libraryPath, "_meta.json");
|
|
856
|
+
let onDiskFingerprint: string | null = null;
|
|
857
|
+
let configPath: string | null = null;
|
|
858
|
+
// Desktop serves ONLY the profile named by _meta.json's appliedId, so an
|
|
859
|
+
// opencodex entry that merely EXISTS does not mean Desktop is using it.
|
|
860
|
+
// null = undeterminable (no metadata / unreadable / no appliedId).
|
|
861
|
+
let activeProfile: boolean | null = null;
|
|
862
|
+
if (existsSync(metaPath)) {
|
|
863
|
+
try {
|
|
864
|
+
const meta = JSON.parse(readFile(metaPath, "utf8"));
|
|
865
|
+
const entry = Array.isArray(meta.entries) ? meta.entries.find((e: { name?: string }) => e?.name === "opencodex") : undefined;
|
|
866
|
+
const appliedId = typeof meta.appliedId === "string" ? meta.appliedId : null;
|
|
867
|
+
// A readable appliedId with no opencodex entry is a KNOWN false, not unknown.
|
|
868
|
+
activeProfile = appliedId === null ? null : (entry?.id ? appliedId === entry.id : false);
|
|
869
|
+
if (entry?.id) {
|
|
870
|
+
configPath = join(libraryPath, `${entry.id}.json`);
|
|
871
|
+
if (existsSync(configPath)) {
|
|
872
|
+
const onDisk = readFile(configPath, "utf8");
|
|
873
|
+
onDiskFingerprint = createHash("sha256").update(onDisk).digest("hex").slice(0, 16);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
} catch { /* unreadable metadata */ }
|
|
877
|
+
}
|
|
878
|
+
const savedFingerprint = config.claudeCode?.desktopProfile?.appliedFingerprint ?? null;
|
|
879
|
+
const appliedAt = config.claudeCode?.desktopProfile?.appliedAt ?? null;
|
|
880
|
+
const stale = savedFingerprint !== null && onDiskFingerprint !== null && savedFingerprint !== onDiskFingerprint;
|
|
881
|
+
const { getDesktopHealth } = await import("../../claude/desktop-health");
|
|
882
|
+
const health = getDesktopHealth();
|
|
883
|
+
return jsonResponse({
|
|
884
|
+
applied: savedFingerprint !== null,
|
|
885
|
+
appliedAt,
|
|
886
|
+
savedFingerprint,
|
|
887
|
+
onDiskFingerprint,
|
|
888
|
+
configPath,
|
|
889
|
+
stale,
|
|
890
|
+
activeProfile,
|
|
891
|
+
health,
|
|
892
|
+
});
|
|
893
|
+
} catch (error) {
|
|
894
|
+
return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// Claude Code inbound settings (GUI "Claude ON" toggle + Claude page).
|
|
899
|
+
if (url.pathname === "/api/claude-code" && req.method === "GET") {
|
|
900
|
+
const models = await fetchAllModels(config);
|
|
901
|
+
const { listCatalogNativeSlugs } = await import("../../codex/catalog");
|
|
902
|
+
const { claudeCodeAlias, claudeCodeNativeAlias } = await import("../../claude/alias");
|
|
903
|
+
const { buildClaudeContextWindows, effectiveModelEnv } = await import("../../claude/context-windows");
|
|
904
|
+
const { visibleNativeSlugs } = await import("../../codex/catalog");
|
|
905
|
+
const disabled = new Set(config.disabledModels ?? []);
|
|
906
|
+
const isDisabled = (provider: string, id: string) =>
|
|
907
|
+
[...disabled].some(stored => slugEquals(stored, provider, id));
|
|
908
|
+
const available = [
|
|
909
|
+
...listCatalogNativeSlugs().filter(ns => !disabled.has(ns)),
|
|
910
|
+
// Claude-facing values stay RAW native selectors (resolved inbound via routeModel,
|
|
911
|
+
// which accepts the raw full-slash form); only the disabled check goes tolerant.
|
|
912
|
+
...models.filter(m => !isDisabled(m.provider, m.id)).map(m => `${m.provider}/${m.id}`),
|
|
913
|
+
];
|
|
914
|
+
const aliases: { id: string; display_name: string }[] = [];
|
|
915
|
+
for (const slug of listCatalogNativeSlugs()) {
|
|
916
|
+
// Readable CLI-surface alias with hash fallback (devlog 050 / audit 051 #2) —
|
|
917
|
+
// the same shared helper the /v1/models ?ids=cli path uses.
|
|
918
|
+
if (!disabled.has(slug)) aliases.push({ id: claudeCodeNativeAlias(slug), display_name: `${slug} (native)` });
|
|
919
|
+
}
|
|
920
|
+
for (const m of models) {
|
|
921
|
+
if (isDisabled(m.provider, m.id)) continue;
|
|
922
|
+
aliases.push({ id: claudeCodeAlias(m.provider, m.id), display_name: `${m.id} (${m.provider})` });
|
|
923
|
+
}
|
|
924
|
+
const contextWindows = buildClaudeContextWindows([...visibleNativeSlugs(config)], models);
|
|
925
|
+
const webSearchOverride = config.claudeCode?.webSearchSidecar;
|
|
926
|
+
const visionOverride = config.claudeCode?.visionSidecar;
|
|
927
|
+
// Auto is a RESOLUTION, recomputed per request — never stored state. Detection is
|
|
928
|
+
// daemon-side, so it cannot see a key exported only in the user's terminal; the
|
|
929
|
+
// GUI labels the badge with detectionScope for exactly that reason.
|
|
930
|
+
const { defaultAuthDetectDeps, detectClaudeAuth, ownAdmissionTokens } = await import("../../claude/auth-detect");
|
|
931
|
+
const { authModeIntent, resolveClaudeAuthMode } = await import("../../claude/auth-mode");
|
|
932
|
+
const authDetection = detectClaudeAuth(defaultAuthDetectDeps(process.env, ownAdmissionTokens(config)));
|
|
933
|
+
const resolvedAuthMode = resolveClaudeAuthMode(config, authDetection);
|
|
934
|
+
return jsonResponse({
|
|
935
|
+
enabled: config.claudeCode?.enabled !== false,
|
|
936
|
+
// Three-state intent (devlog 260726_claude_auth_auto): an absent key is AUTO, not
|
|
937
|
+
// subscription. The old coercion made every save convert an untouched auto config
|
|
938
|
+
// into a sticky manual subscription with no way back.
|
|
939
|
+
authMode: authModeIntent(config),
|
|
940
|
+
/** Does the opencodex dummy marker get injected — NOT a claim about native auth. */
|
|
941
|
+
markerMode: resolvedAuthMode.markerMode,
|
|
942
|
+
authModeOrigin: resolvedAuthMode.origin,
|
|
943
|
+
...(resolvedAuthMode.foundBy ? { authFoundBy: resolvedAuthMode.foundBy } : {}),
|
|
944
|
+
authDetectionUnknown: authDetection.presence === "unknown",
|
|
945
|
+
// Separate axis: with an admission key configured a token is injected regardless
|
|
946
|
+
// of mode, so the GUI must never present subscription as "no token anywhere".
|
|
947
|
+
admissionKeyActive: (config.apiKeys?.length ?? 0) > 0,
|
|
948
|
+
detectionScope: "daemon",
|
|
949
|
+
model: config.claudeCode?.model ?? "",
|
|
950
|
+
smallFastModel: config.claudeCode?.smallFastModel ?? "",
|
|
951
|
+
tierModels: config.claudeCode?.tierModels ?? {},
|
|
952
|
+
modelMap: config.claudeCode?.modelMap ?? {},
|
|
953
|
+
systemEnv: config.claudeCode?.systemEnv === true,
|
|
954
|
+
autoConnectSupported: process.platform === "darwin",
|
|
955
|
+
maxContextTokens: config.claudeCode?.maxContextTokens ?? null,
|
|
956
|
+
alwaysEnableEffort: config.claudeCode?.alwaysEnableEffort === true,
|
|
957
|
+
autoContext: config.claudeCode?.autoContext !== false,
|
|
958
|
+
autoCompactWindow: config.claudeCode?.autoCompactWindow ?? null,
|
|
959
|
+
blockedSkills: config.claudeCode?.blockedSkills ?? null,
|
|
960
|
+
injectAgents: config.claudeCode?.injectAgents !== false,
|
|
961
|
+
...(webSearchOverride && Object.keys(webSearchOverride).length > 0
|
|
962
|
+
? { webSearchSidecar: { backend: webSearchOverride.backend, model: webSearchOverride.model } }
|
|
963
|
+
: {}),
|
|
964
|
+
...(visionOverride && Object.keys(visionOverride).length > 0
|
|
965
|
+
? { visionSidecar: { backend: visionOverride.backend, model: visionOverride.model } }
|
|
966
|
+
: {}),
|
|
967
|
+
fastMode: config.fastMode,
|
|
968
|
+
contextWindows,
|
|
969
|
+
effectiveModelEnv: effectiveModelEnv(config.claudeCode, contextWindows),
|
|
970
|
+
available,
|
|
971
|
+
aliases,
|
|
972
|
+
port: config.port,
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
if (url.pathname === "/api/claude-code" && req.method === "PUT") {
|
|
976
|
+
// NOTE: model / tierModels / maxContextTokens / alwaysEnableEffort are
|
|
977
|
+
// CONFIG-ONLY back-compat fields — the GUI no longer offers controls for them
|
|
978
|
+
// (default model is owned by Claude Code's /model picker; roster agents
|
|
979
|
+
// supersede tiers; auto-context supersedes the max-context pair; effort rides
|
|
980
|
+
// regardless on 2.1.207). PUT keeps validating them so hand-written configs
|
|
981
|
+
// and older GUIs stay safe; GUI saves omit them and the spread preserves them.
|
|
982
|
+
let parsedBody: unknown;
|
|
983
|
+
try { parsedBody = await readManagementJsonBody(req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid JSON body" }, 400); }
|
|
984
|
+
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
|
|
985
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
986
|
+
const prototype = Object.getPrototypeOf(value);
|
|
987
|
+
return prototype === Object.prototype || prototype === null;
|
|
988
|
+
};
|
|
989
|
+
if (!isPlainObject(parsedBody)) return jsonResponse({ error: "body must be an object" }, 400);
|
|
990
|
+
const body = parsedBody as { enabled?: unknown; authMode?: unknown; model?: unknown; smallFastModel?: unknown; modelMap?: unknown; systemEnv?: unknown; fastMode?: unknown; maxContextTokens?: unknown; alwaysEnableEffort?: unknown; tierModels?: unknown; autoContext?: unknown; autoCompactWindow?: unknown; blockedSkills?: unknown; injectAgents?: unknown; webSearchSidecar?: unknown; visionSidecar?: unknown };
|
|
991
|
+
for (const field of ["webSearchSidecar", "visionSidecar"] as const) {
|
|
992
|
+
const section = body[field];
|
|
993
|
+
if (section === undefined || section === null) continue;
|
|
994
|
+
if (!isPlainObject(section)) return jsonResponse({ error: `${field} must be an object or null` }, 400);
|
|
995
|
+
if (section.backend !== undefined && section.backend !== null
|
|
996
|
+
&& section.backend !== "openai" && section.backend !== "anthropic") {
|
|
997
|
+
return jsonResponse({ error: `${field}.backend must be openai, anthropic, or null` }, 400);
|
|
998
|
+
}
|
|
999
|
+
if (section.model !== undefined && typeof section.model !== "string") {
|
|
1000
|
+
return jsonResponse({ error: `${field}.model must be a string` }, 400);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
const next = { ...(config.claudeCode ?? {}) };
|
|
1004
|
+
for (const field of ["webSearchSidecar", "visionSidecar"] as const) {
|
|
1005
|
+
const section = body[field];
|
|
1006
|
+
if (section === undefined) continue;
|
|
1007
|
+
if (section === null || Object.keys(section as Record<string, unknown>).length === 0) {
|
|
1008
|
+
delete next[field];
|
|
1009
|
+
continue;
|
|
1010
|
+
}
|
|
1011
|
+
const requested = section as { backend?: "openai" | "anthropic" | null; model?: string };
|
|
1012
|
+
const override: NonNullable<OcxClaudeCodeConfig[typeof field]> = { ...next[field] };
|
|
1013
|
+
if (requested.backend === null) delete override.backend;
|
|
1014
|
+
else if (requested.backend !== undefined) override.backend = requested.backend;
|
|
1015
|
+
if (requested.model === "") delete override.model;
|
|
1016
|
+
else if (requested.model !== undefined) override.model = requested.model;
|
|
1017
|
+
if (Object.keys(override).length > 0) next[field] = override;
|
|
1018
|
+
else delete next[field];
|
|
1019
|
+
}
|
|
1020
|
+
if (body.enabled !== undefined) {
|
|
1021
|
+
if (typeof body.enabled !== "boolean") return jsonResponse({ error: "enabled must be a boolean" }, 400);
|
|
1022
|
+
next.enabled = body.enabled;
|
|
1023
|
+
}
|
|
1024
|
+
if (body.authMode !== undefined) {
|
|
1025
|
+
// Three-state intent: "proxy" and "subscription" are stored literally and stick
|
|
1026
|
+
// forever; "auto" DELETES the key so the mode is resolved from detected Claude
|
|
1027
|
+
// auth on every launch. The 260720 round-trip contract survives as a superset —
|
|
1028
|
+
// storing "subscription" literally is also backward-safe, since older readers
|
|
1029
|
+
// only ever recognised "proxy".
|
|
1030
|
+
if (body.authMode !== "proxy" && body.authMode !== "subscription" && body.authMode !== "auto") {
|
|
1031
|
+
return jsonResponse({ error: "authMode must be \"auto\", \"proxy\", or \"subscription\"" }, 400);
|
|
1032
|
+
}
|
|
1033
|
+
if (body.authMode === "auto") delete next.authMode;
|
|
1034
|
+
else next.authMode = body.authMode;
|
|
1035
|
+
}
|
|
1036
|
+
if (body.systemEnv !== undefined) {
|
|
1037
|
+
if (typeof body.systemEnv !== "boolean") return jsonResponse({ error: "systemEnv must be a boolean" }, 400);
|
|
1038
|
+
next.systemEnv = body.systemEnv;
|
|
1039
|
+
}
|
|
1040
|
+
if (body.alwaysEnableEffort !== undefined) {
|
|
1041
|
+
if (typeof body.alwaysEnableEffort !== "boolean") return jsonResponse({ error: "alwaysEnableEffort must be a boolean" }, 400);
|
|
1042
|
+
if (body.alwaysEnableEffort) next.alwaysEnableEffort = true;
|
|
1043
|
+
else delete next.alwaysEnableEffort;
|
|
1044
|
+
}
|
|
1045
|
+
if (body.maxContextTokens !== undefined) {
|
|
1046
|
+
// CONFIG-ONLY back-compat (GUI control removed — superseded by auto-context):
|
|
1047
|
+
// null clears; otherwise a positive integer (devlog 136 B6).
|
|
1048
|
+
if (body.maxContextTokens === null) {
|
|
1049
|
+
delete next.maxContextTokens;
|
|
1050
|
+
} else if (typeof body.maxContextTokens !== "number" || !Number.isInteger(body.maxContextTokens) || body.maxContextTokens <= 0) {
|
|
1051
|
+
return jsonResponse({ error: "maxContextTokens must be a positive integer or null" }, 400);
|
|
1052
|
+
} else {
|
|
1053
|
+
next.maxContextTokens = body.maxContextTokens;
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
if (body.autoContext !== undefined) {
|
|
1057
|
+
// Default-on boolean (devlog 260712 020): true = drop the key, false = store.
|
|
1058
|
+
if (typeof body.autoContext !== "boolean") return jsonResponse({ error: "autoContext must be a boolean" }, 400);
|
|
1059
|
+
if (body.autoContext) delete next.autoContext;
|
|
1060
|
+
else next.autoContext = false;
|
|
1061
|
+
}
|
|
1062
|
+
if (body.injectAgents !== undefined) {
|
|
1063
|
+
// Default-on boolean (devlog 260712 070): true = drop the key, false = store.
|
|
1064
|
+
if (typeof body.injectAgents !== "boolean") return jsonResponse({ error: "injectAgents must be a boolean" }, 400);
|
|
1065
|
+
if (body.injectAgents) delete next.injectAgents;
|
|
1066
|
+
else next.injectAgents = false;
|
|
1067
|
+
}
|
|
1068
|
+
if (body.autoCompactWindow !== undefined) {
|
|
1069
|
+
// null resets to the 350k default; otherwise the binary-accepted range
|
|
1070
|
+
// 100_000..1_000_000 (2.1.207 pSo/yDs — audit 021 #1).
|
|
1071
|
+
if (body.autoCompactWindow === null) {
|
|
1072
|
+
delete next.autoCompactWindow;
|
|
1073
|
+
} else if (typeof body.autoCompactWindow !== "number" || !Number.isInteger(body.autoCompactWindow) || body.autoCompactWindow < 100_000 || body.autoCompactWindow > 1_000_000) {
|
|
1074
|
+
return jsonResponse({ error: "autoCompactWindow must be an integer between 100000 and 1000000, or null" }, 400);
|
|
1075
|
+
} else {
|
|
1076
|
+
next.autoCompactWindow = body.autoCompactWindow;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
if (body.blockedSkills !== undefined) {
|
|
1080
|
+
// null resets to the default (["claude-api"]); an array (possibly empty = off)
|
|
1081
|
+
// must contain non-empty strings (devlog 060).
|
|
1082
|
+
if (body.blockedSkills === null) {
|
|
1083
|
+
delete next.blockedSkills;
|
|
1084
|
+
} else if (!Array.isArray(body.blockedSkills) || body.blockedSkills.some(s => typeof s !== "string" || s.trim() === "")) {
|
|
1085
|
+
return jsonResponse({ error: "blockedSkills must be an array of non-empty strings, or null" }, 400);
|
|
1086
|
+
} else {
|
|
1087
|
+
next.blockedSkills = (body.blockedSkills as string[]).map(s => s.trim());
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
if (body.tierModels !== undefined) {
|
|
1091
|
+
// CONFIG-ONLY back-compat (GUI pickers removed — roster agents supersede tiers).
|
|
1092
|
+
if (body.tierModels === null) {
|
|
1093
|
+
delete next.tierModels;
|
|
1094
|
+
} else if (!isPlainObject(body.tierModels)) {
|
|
1095
|
+
return jsonResponse({ error: "tierModels must be an object with string values, or null" }, 400);
|
|
1096
|
+
} else {
|
|
1097
|
+
for (const [tier, value] of Object.entries(body.tierModels)) {
|
|
1098
|
+
if (typeof value !== "string") return jsonResponse({ error: `tierModels.${tier} must be a string` }, 400);
|
|
1099
|
+
}
|
|
1100
|
+
const tierModels = body.tierModels as Record<string, string>;
|
|
1101
|
+
const tiers: Record<string, string> = {};
|
|
1102
|
+
for (const tier of ["opus", "sonnet", "haiku", "fable"] as const) {
|
|
1103
|
+
const value = tierModels[tier];
|
|
1104
|
+
if (value !== undefined && value.trim() !== "") tiers[tier] = value.trim();
|
|
1105
|
+
}
|
|
1106
|
+
if (Object.keys(tiers).length > 0) next.tierModels = tiers;
|
|
1107
|
+
else delete next.tierModels;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
if (body.fastMode !== undefined) {
|
|
1111
|
+
if (body.fastMode !== true && body.fastMode !== false && body.fastMode !== null) {
|
|
1112
|
+
return jsonResponse({ error: "fastMode must be true, false, or null" }, 400);
|
|
1113
|
+
}
|
|
1114
|
+
config.fastMode = body.fastMode === null ? undefined : body.fastMode;
|
|
1115
|
+
}
|
|
1116
|
+
for (const field of ["model", "smallFastModel"] as const) {
|
|
1117
|
+
const value = body[field];
|
|
1118
|
+
if (value === undefined) continue;
|
|
1119
|
+
if (typeof value !== "string") return jsonResponse({ error: `${field} must be a string` }, 400);
|
|
1120
|
+
if (value.trim() === "") delete next[field];
|
|
1121
|
+
else next[field] = value.trim();
|
|
1122
|
+
}
|
|
1123
|
+
if (body.modelMap !== undefined) {
|
|
1124
|
+
if (body.modelMap === null) {
|
|
1125
|
+
delete next.modelMap;
|
|
1126
|
+
} else {
|
|
1127
|
+
if (!isPlainObject(body.modelMap)) {
|
|
1128
|
+
return jsonResponse({ error: "modelMap must be an object of string->string, or null" }, 400);
|
|
1129
|
+
}
|
|
1130
|
+
const map: Record<string, string> = {};
|
|
1131
|
+
for (const [k, v] of Object.entries(body.modelMap)) {
|
|
1132
|
+
if (typeof v !== "string" || k.trim() === "" || v.trim() === "") {
|
|
1133
|
+
return jsonResponse({ error: "modelMap entries must be non-empty strings" }, 400);
|
|
1134
|
+
}
|
|
1135
|
+
map[k.trim()] = v.trim();
|
|
1136
|
+
}
|
|
1137
|
+
if (Object.keys(map).length > 0) next.modelMap = map;
|
|
1138
|
+
else delete next.modelMap;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
config.claudeCode = next;
|
|
1142
|
+
// Stamp the migration sentinel on EVERY persist of this block. The migration reads
|
|
1143
|
+
// "a claudeCode block with no authMode" as a pre-upgrade subscriber and pins it to
|
|
1144
|
+
// literal subscription — correct for a config written before `auto` existed, fatal
|
|
1145
|
+
// for one written after. Without this, choosing Auto (which DELETES authMode) or
|
|
1146
|
+
// merely toggling Claude on (App.tsx PUTs `{enabled}` alone and creates the block)
|
|
1147
|
+
// would be converted into a sticky manual subscription by the next startServer, and
|
|
1148
|
+
// auto would survive exactly one proxy lifetime with no way back.
|
|
1149
|
+
if (!next.authModeMigratedAt) next.authModeMigratedAt = new Date().toISOString();
|
|
1150
|
+
const { saveConfigPreservingClaudeCode: save } = await import("../../config");
|
|
1151
|
+
save(config);
|
|
1152
|
+
const warnings: string[] = [];
|
|
1153
|
+
// authMode changes must reconcile the injected system env too: switching back to
|
|
1154
|
+
// Subscription has to remove the opencodex-owned dummy ANTHROPIC_AUTH_TOKEN
|
|
1155
|
+
// (audit R1 blocker #1/#2, devlog 260720_claude_authmode_persist).
|
|
1156
|
+
if (body.systemEnv !== undefined || body.authMode !== undefined) {
|
|
1157
|
+
try {
|
|
1158
|
+
await applySystemEnvToggle(config, config.port);
|
|
1159
|
+
} catch (err) {
|
|
1160
|
+
warnings.push(`Failed to apply system environment setting: ${err instanceof Error ? err.message : String(err)}`);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
// Keep the file-backed live registry symmetric: OFF prunes immediately, while
|
|
1164
|
+
// ON and config changes restore definitions without requiring a restart.
|
|
1165
|
+
await syncClaudeAgentDefsBestEffort();
|
|
1166
|
+
return jsonResponse({ ok: true, enabled: next.enabled !== false, warnings });
|
|
1167
|
+
}
|
|
1168
|
+
return null;
|
|
1169
|
+
}
|