@yansigit/opencodex 2.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS_INSTALL.md +109 -0
- package/LICENSE +21 -0
- package/README.md +303 -0
- package/assets/architecture.png +0 -0
- package/assets/banner.png +0 -0
- package/assets/claude-code-models.gif +0 -0
- package/assets/codex-app-picker.png +0 -0
- package/bin/ocx.mjs +587 -0
- package/bin/package-main.mjs +9 -0
- package/gui/dist/assets/index-BNJ7r4Gd.js +102 -0
- package/gui/dist/assets/index-CGoDO3uO.css +1 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/icons.svg +24 -0
- package/gui/dist/index.html +25 -0
- package/gui/dist/logo.png +0 -0
- package/gui/dist/provider-icons/alibaba-color.svg +1 -0
- package/gui/dist/provider-icons/antigravity-color.svg +1 -0
- package/gui/dist/provider-icons/claude-color.svg +1 -0
- package/gui/dist/provider-icons/cline-color.svg +16 -0
- package/gui/dist/provider-icons/cloudflare-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/commandcode-color.svg +1 -0
- package/gui/dist/provider-icons/copilot-color.svg +1 -0
- package/gui/dist/provider-icons/cursor-color.svg +2 -0
- package/gui/dist/provider-icons/deepseek-color.svg +1 -0
- package/gui/dist/provider-icons/discord.svg +1 -0
- package/gui/dist/provider-icons/firepass-color.svg +1 -0
- package/gui/dist/provider-icons/fireworks-color.svg +1 -0
- package/gui/dist/provider-icons/gemini-color.svg +1 -0
- package/gui/dist/provider-icons/github-copilot-color.svg +1 -0
- package/gui/dist/provider-icons/gitlab-duo-color.svg +1 -0
- package/gui/dist/provider-icons/grok.svg +1 -0
- package/gui/dist/provider-icons/groq-color.svg +1 -0
- package/gui/dist/provider-icons/huggingface-color.svg +1 -0
- package/gui/dist/provider-icons/kimi-color.svg +1 -0
- package/gui/dist/provider-icons/kiro-color.svg +15 -0
- package/gui/dist/provider-icons/lm-studio-color.svg +1 -0
- package/gui/dist/provider-icons/mistral-color.svg +1 -0
- package/gui/dist/provider-icons/moonshot-color.svg +1 -0
- package/gui/dist/provider-icons/nvidia-color.svg +1 -0
- package/gui/dist/provider-icons/ollama-color.svg +1 -0
- package/gui/dist/provider-icons/openai.svg +1 -0
- package/gui/dist/provider-icons/opencode.svg +2 -0
- package/gui/dist/provider-icons/openrouter-color.svg +1 -0
- package/gui/dist/provider-icons/pi.svg +21 -0
- package/gui/dist/provider-icons/qianfan-color.svg +1 -0
- package/gui/dist/provider-icons/qwen-portal-color.svg +1 -0
- package/gui/dist/provider-icons/telegram.svg +1 -0
- package/gui/dist/provider-icons/vercel-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/vllm-color.svg +1 -0
- package/gui/dist/provider-icons/xiaomi-color.svg +1 -0
- package/package.json +108 -0
- package/src/AGENTS.md +28 -0
- package/src/adapters/anthropic-image-guard.ts +251 -0
- package/src/adapters/anthropic-image-normalize.ts +518 -0
- package/src/adapters/anthropic-output-schema.ts +137 -0
- package/src/adapters/anthropic.ts +1327 -0
- package/src/adapters/azure.ts +36 -0
- package/src/adapters/base.ts +121 -0
- package/src/adapters/client-fingerprint.ts +65 -0
- package/src/adapters/cline-pass-deepseek-v4-tool-replay.ts +69 -0
- package/src/adapters/command-code.ts +601 -0
- package/src/adapters/cursor/arg-codec.ts +38 -0
- package/src/adapters/cursor/arg-normalize.ts +104 -0
- package/src/adapters/cursor/checkpoint-store.ts +303 -0
- package/src/adapters/cursor/cursor-errors.ts +288 -0
- package/src/adapters/cursor/discovery.ts +333 -0
- package/src/adapters/cursor/effort-map.ts +151 -0
- package/src/adapters/cursor/exec-policy.ts +88 -0
- package/src/adapters/cursor/framing.ts +250 -0
- package/src/adapters/cursor/gen/agent_pb.ts +15274 -0
- package/src/adapters/cursor/h2-pool.ts +123 -0
- package/src/adapters/cursor/http1-bidi.ts +361 -0
- package/src/adapters/cursor/images.ts +704 -0
- package/src/adapters/cursor/kv-store.ts +52 -0
- package/src/adapters/cursor/live-models.ts +269 -0
- package/src/adapters/cursor/live-smoke-gate.ts +41 -0
- package/src/adapters/cursor/live-transport.ts +1653 -0
- package/src/adapters/cursor/mcp-config.ts +42 -0
- package/src/adapters/cursor/mcp-manager.ts +333 -0
- package/src/adapters/cursor/message-mapper.ts +49 -0
- package/src/adapters/cursor/native-exec-common.ts +76 -0
- package/src/adapters/cursor/native-exec-desktop.ts +184 -0
- package/src/adapters/cursor/native-exec-fs.ts +332 -0
- package/src/adapters/cursor/native-exec-mcp.ts +153 -0
- package/src/adapters/cursor/native-exec-network.ts +43 -0
- package/src/adapters/cursor/native-exec-shell.ts +547 -0
- package/src/adapters/cursor/native-exec-tools.ts +118 -0
- package/src/adapters/cursor/native-exec.ts +663 -0
- package/src/adapters/cursor/protobuf-events.ts +1381 -0
- package/src/adapters/cursor/protobuf-request.ts +1032 -0
- package/src/adapters/cursor/request-builder.ts +461 -0
- package/src/adapters/cursor/thread-continuity.ts +67 -0
- package/src/adapters/cursor/tool-definitions.ts +735 -0
- package/src/adapters/cursor/tool-result-normalize.ts +92 -0
- package/src/adapters/cursor/transport-retry.ts +132 -0
- package/src/adapters/cursor/transport.ts +79 -0
- package/src/adapters/cursor/types.ts +79 -0
- package/src/adapters/cursor.ts +322 -0
- package/src/adapters/google-antigravity-hosts.ts +48 -0
- package/src/adapters/google-antigravity-replay.ts +827 -0
- package/src/adapters/google-antigravity-tools.ts +105 -0
- package/src/adapters/google-antigravity-wire.ts +141 -0
- package/src/adapters/google-errors.ts +92 -0
- package/src/adapters/google-http.ts +460 -0
- package/src/adapters/google-tool-schema.ts +238 -0
- package/src/adapters/google-truncation.ts +24 -0
- package/src/adapters/google-wire-compiler.ts +232 -0
- package/src/adapters/google.ts +1377 -0
- package/src/adapters/identity.ts +77 -0
- package/src/adapters/image.ts +23 -0
- package/src/adapters/kiro-constants.ts +16 -0
- package/src/adapters/kiro-errors.ts +208 -0
- package/src/adapters/kiro-events.ts +197 -0
- package/src/adapters/kiro-images.ts +129 -0
- package/src/adapters/kiro-retry.ts +312 -0
- package/src/adapters/kiro-thinking.ts +112 -0
- package/src/adapters/kiro-tool-fallback.ts +36 -0
- package/src/adapters/kiro-tools.ts +224 -0
- package/src/adapters/kiro-truncation.ts +33 -0
- package/src/adapters/kiro-wire.ts +129 -0
- package/src/adapters/kiro.ts +1936 -0
- package/src/adapters/mimo-free.ts +280 -0
- package/src/adapters/openai-chat-url.ts +11 -0
- package/src/adapters/openai-chat.ts +1980 -0
- package/src/adapters/openai-responses-url.ts +16 -0
- package/src/adapters/openai-responses.ts +1911 -0
- package/src/adapters/registry.ts +175 -0
- package/src/adapters/responses-tool-schema.ts +67 -0
- package/src/adapters/run-turn-queue.ts +114 -0
- package/src/adapters/tool-call-id.ts +119 -0
- package/src/adapters/tool-catalog-nudge.ts +154 -0
- package/src/adapters/upstream-http-error.ts +48 -0
- package/src/adapters/xai-web-search.ts +185 -0
- package/src/bridge.ts +1986 -0
- package/src/chat/inbound.ts +319 -0
- package/src/chat/outbound.ts +821 -0
- package/src/claude/agents-inject.ts +266 -0
- package/src/claude/alias.ts +149 -0
- package/src/claude/auth-detect.ts +229 -0
- package/src/claude/auth-mode-migration.ts +32 -0
- package/src/claude/auth-mode.ts +62 -0
- package/src/claude/context-windows.ts +205 -0
- package/src/claude/desktop-3p-guard.ts +35 -0
- package/src/claude/desktop-3p-paths.ts +84 -0
- package/src/claude/desktop-3p.ts +615 -0
- package/src/claude/desktop-health.ts +26 -0
- package/src/claude/desktop-profile.ts +263 -0
- package/src/claude/gateway-cache.ts +107 -0
- package/src/claude/inbound-debug.ts +163 -0
- package/src/claude/inbound.ts +578 -0
- package/src/claude/model-info.ts +174 -0
- package/src/claude/outbound.ts +926 -0
- package/src/cli/access.ts +108 -0
- package/src/cli/account-api.ts +302 -0
- package/src/cli/account-auth.ts +250 -0
- package/src/cli/account-catalog-refresh.ts +14 -0
- package/src/cli/account-extended.ts +737 -0
- package/src/cli/account-main.ts +317 -0
- package/src/cli/account.ts +299 -0
- package/src/cli/agent-driven.ts +70 -0
- package/src/cli/agent.ts +290 -0
- package/src/cli/catalog-prewarm.ts +27 -0
- package/src/cli/claude-agent-startup-sync.ts +73 -0
- package/src/cli/claude-desktop.ts +213 -0
- package/src/cli/claude.ts +355 -0
- package/src/cli/codex-log-guard-doctor.ts +103 -0
- package/src/cli/codex-shim-autorestore.ts +47 -0
- package/src/cli/codex-shim-readiness.ts +76 -0
- package/src/cli/combo.ts +127 -0
- package/src/cli/config-command.ts +209 -0
- package/src/cli/debug.ts +228 -0
- package/src/cli/dispatch.ts +585 -0
- package/src/cli/doctor.ts +1202 -0
- package/src/cli/ensure-desired-integrations.ts +152 -0
- package/src/cli/export-command.ts +213 -0
- package/src/cli/help.ts +101 -0
- package/src/cli/index.ts +973 -0
- package/src/cli/init.ts +211 -0
- package/src/cli/integrations.ts +260 -0
- package/src/cli/interactive-confirm.ts +133 -0
- package/src/cli/lab.ts +607 -0
- package/src/cli/launcher-context.ts +77 -0
- package/src/cli/minimax.ts +497 -0
- package/src/cli/models-runtime.ts +245 -0
- package/src/cli/models.ts +422 -0
- package/src/cli/observe.ts +206 -0
- package/src/cli/opencode.ts +588 -0
- package/src/cli/provider-replit.ts +232 -0
- package/src/cli/provider-runtime.ts +179 -0
- package/src/cli/provider.ts +492 -0
- package/src/cli/ready.ts +301 -0
- package/src/cli/registry.ts +422 -0
- package/src/cli/replit-gateway-key-input.ts +138 -0
- package/src/cli/root.ts +86 -0
- package/src/cli/route-policy.ts +92 -0
- package/src/cli/runtime-api.ts +328 -0
- package/src/cli/star-prompt.ts +211 -0
- package/src/cli/status-oauth.ts +78 -0
- package/src/cli/status.ts +328 -0
- package/src/cli/system-command.ts +112 -0
- package/src/cli/system-restart-client.ts +146 -0
- package/src/cli/tray-proxy.ts +199 -0
- package/src/cli/v2.ts +268 -0
- package/src/cli.ts +10 -0
- package/src/clients/config-export.ts +1704 -0
- package/src/codex/account-id.ts +34 -0
- package/src/codex/account-label.ts +47 -0
- package/src/codex/account-lifecycle.ts +172 -0
- package/src/codex/account-namespace-match.ts +63 -0
- package/src/codex/account-namespaces.ts +195 -0
- package/src/codex/account-pause.ts +20 -0
- package/src/codex/account-priority.ts +83 -0
- package/src/codex/account-runtime-state.ts +31 -0
- package/src/codex/account-store.ts +544 -0
- package/src/codex/account-usability.ts +43 -0
- package/src/codex/admission.ts +256 -0
- package/src/codex/affinity-debug.ts +162 -0
- package/src/codex/agent-roles-sync.ts +225 -0
- package/src/codex/agent-roles.ts +238 -0
- package/src/codex/app-server-processes.ts +1143 -0
- package/src/codex/app-server-restart-service.ts +232 -0
- package/src/codex/auth-api.ts +2147 -0
- package/src/codex/auth-collision.ts +109 -0
- package/src/codex/auth-context.ts +665 -0
- package/src/codex/autostart-health.ts +156 -0
- package/src/codex/catalog/account-models.ts +67 -0
- package/src/codex/catalog/aggregation.ts +436 -0
- package/src/codex/catalog/bundled.ts +549 -0
- package/src/codex/catalog/effort.ts +446 -0
- package/src/codex/catalog/filesystem-evidence.ts +302 -0
- package/src/codex/catalog/kinds.ts +2 -0
- package/src/codex/catalog/metadata.ts +664 -0
- package/src/codex/catalog/native-models.ts +72 -0
- package/src/codex/catalog/parsing.ts +650 -0
- package/src/codex/catalog/provider-fetch.ts +2064 -0
- package/src/codex/catalog/sync.ts +1883 -0
- package/src/codex/catalog-admission.ts +199 -0
- package/src/codex/catalog-refresh-status.ts +105 -0
- package/src/codex/catalog-write-serialization.ts +242 -0
- package/src/codex/catalog.ts +14 -0
- package/src/codex/codex-write-lock.ts +384 -0
- package/src/codex/convergence-types.ts +614 -0
- package/src/codex/convergence.ts +651 -0
- package/src/codex/coordinator-doctor.ts +332 -0
- package/src/codex/custom-model-catalog-migration.ts +176 -0
- package/src/codex/data/upstream-models.json +830 -0
- package/src/codex/desired-state.ts +230 -0
- package/src/codex/exec-invocation.ts +22 -0
- package/src/codex/features.ts +1566 -0
- package/src/codex/generation.ts +202 -0
- package/src/codex/history-job.ts +407 -0
- package/src/codex/history-lock.ts +242 -0
- package/src/codex/history-migration-guardian.ts +108 -0
- package/src/codex/history-provider.ts +979 -0
- package/src/codex/history-transition.ts +105 -0
- package/src/codex/history-worker.ts +220 -0
- package/src/codex/home.ts +206 -0
- package/src/codex/inject-coordination.ts +290 -0
- package/src/codex/inject.ts +1733 -0
- package/src/codex/injected-marker.ts +106 -0
- package/src/codex/integration-record.ts +266 -0
- package/src/codex/internal/catalog-writer.ts +203 -0
- package/src/codex/internal/history-writer.ts +80 -0
- package/src/codex/journal.ts +225 -0
- package/src/codex/log-guard/inspect.ts +506 -0
- package/src/codex/log-guard/lock.ts +150 -0
- package/src/codex/log-guard/maintenance.ts +403 -0
- package/src/codex/log-guard/path-safety.ts +88 -0
- package/src/codex/log-guard/policy.ts +44 -0
- package/src/codex/log-guard/processes.ts +205 -0
- package/src/codex/log-guard/protection.ts +489 -0
- package/src/codex/log-guard/sqlite-errors.ts +9 -0
- package/src/codex/main-account-cache.ts +56 -0
- package/src/codex/main-account.ts +68 -0
- package/src/codex/management-convergence.ts +167 -0
- package/src/codex/model-cache.ts +273 -0
- package/src/codex/model-entitlements.ts +353 -0
- package/src/codex/native-main-admission.ts +47 -0
- package/src/codex/native-main-auth-temp.ts +187 -0
- package/src/codex/native-main-claim.ts +178 -0
- package/src/codex/native-main-lock-file.ts +162 -0
- package/src/codex/native-main-owner.ts +329 -0
- package/src/codex/native-profile-api.ts +247 -0
- package/src/codex/native-profile-manager.ts +1531 -0
- package/src/codex/native-profile-processes.ts +121 -0
- package/src/codex/native-profile-recovery.ts +99 -0
- package/src/codex/native-profile-stage-store.ts +387 -0
- package/src/codex/native-profile-startup.ts +492 -0
- package/src/codex/native-profile-store.ts +855 -0
- package/src/codex/native-profile-types.ts +120 -0
- package/src/codex/native-residue.ts +682 -0
- package/src/codex/paths.ts +144 -0
- package/src/codex/plan-from-token.ts +140 -0
- package/src/codex/plan.ts +40 -0
- package/src/codex/plugins-doctor.ts +242 -0
- package/src/codex/pool-rotation.ts +295 -0
- package/src/codex/project-config-warnings.ts +425 -0
- package/src/codex/prompt-journal.ts +352 -0
- package/src/codex/prompt-layers.ts +967 -0
- package/src/codex/prompt-lock.ts +143 -0
- package/src/codex/quota-rejection.ts +298 -0
- package/src/codex/quota.ts +573 -0
- package/src/codex/refresh.ts +62 -0
- package/src/codex/reset-credit-recovery.ts +1044 -0
- package/src/codex/routing.ts +1888 -0
- package/src/codex/runtime.ts +659 -0
- package/src/codex/shim.ts +2170 -0
- package/src/codex/subagent-defaults.ts +550 -0
- package/src/codex/subagent-model-fallback.ts +784 -0
- package/src/codex/sync.ts +319 -0
- package/src/codex/transition-state.ts +612 -0
- package/src/codex/upstream-host-health.ts +368 -0
- package/src/codex/user-identity.ts +557 -0
- package/src/codex/warmup.ts +298 -0
- package/src/codex/websocket-registry.ts +100 -0
- package/src/codex/write-coordination.ts +114 -0
- package/src/combos/failover.ts +160 -0
- package/src/combos/index.ts +45 -0
- package/src/combos/request.ts +94 -0
- package/src/combos/resolve.ts +232 -0
- package/src/combos/types.ts +398 -0
- package/src/config/provider-name.ts +24 -0
- package/src/config.ts +4041 -0
- package/src/fork/register.ts +3 -0
- package/src/generated/compatibility-version.json +3116 -0
- package/src/generated/model-metadata.ts +106 -0
- package/src/github/star-state.ts +203 -0
- package/src/grok/inject.ts +530 -0
- package/src/grok/inspect.ts +45 -0
- package/src/grok/status.ts +121 -0
- package/src/grok/sync.ts +66 -0
- package/src/images/artifacts.ts +516 -0
- package/src/images/fulfill-video.ts +163 -0
- package/src/images/fulfill.ts +149 -0
- package/src/images/index.ts +4 -0
- package/src/images/loop.ts +955 -0
- package/src/images/plan.ts +143 -0
- package/src/images/synthetic-tool.ts +133 -0
- package/src/images/types.ts +41 -0
- package/src/images/xai-client.ts +141 -0
- package/src/images/xai-video-client.ts +163 -0
- package/src/index.ts +22 -0
- package/src/integrations/config-io.ts +269 -0
- package/src/integrations/journal.ts +315 -0
- package/src/integrations/merge.ts +135 -0
- package/src/integrations/mutation-flight.ts +71 -0
- package/src/integrations/native/ownership-preflight.ts +202 -0
- package/src/integrations/omp-yaml-source.ts +358 -0
- package/src/integrations/owned-refresh.ts +74 -0
- package/src/integrations/ownership.ts +111 -0
- package/src/integrations/registry.ts +159 -0
- package/src/integrations/serialize.ts +314 -0
- package/src/integrations/state.ts +361 -0
- package/src/integrations/store.ts +103 -0
- package/src/integrations/writer-lock.ts +98 -0
- package/src/integrations/writer.ts +691 -0
- package/src/lab/artifacts/sanitize.ts +586 -0
- package/src/lab/artifacts/secure-fs.ts +475 -0
- package/src/lab/artifacts/store.ts +310 -0
- package/src/lab/automation/budgets.ts +78 -0
- package/src/lab/automation/config-persistence.ts +256 -0
- package/src/lab/automation/constants.ts +39 -0
- package/src/lab/automation/cooldown.ts +103 -0
- package/src/lab/automation/dispatch.ts +211 -0
- package/src/lab/automation/index.ts +13 -0
- package/src/lab/automation/orchestrator.ts +499 -0
- package/src/lab/automation/persistence.ts +512 -0
- package/src/lab/automation/planner.ts +371 -0
- package/src/lab/automation/policy.ts +136 -0
- package/src/lab/automation/queue.ts +191 -0
- package/src/lab/automation/recovery.ts +24 -0
- package/src/lab/automation/route-context.ts +21 -0
- package/src/lab/automation/run-key.ts +44 -0
- package/src/lab/automation/runs-query.ts +34 -0
- package/src/lab/automation/types.ts +160 -0
- package/src/lab/conformance/assertion.ts +325 -0
- package/src/lab/conformance/digest.ts +22 -0
- package/src/lab/conformance/executor.ts +741 -0
- package/src/lab/conformance/fixture-provider.ts +27 -0
- package/src/lab/conformance/fixtures/live-v1-cases.json +175 -0
- package/src/lab/conformance/fixtures/protocol-v1-cases.json +461 -0
- package/src/lab/conformance/harness-budget.ts +47 -0
- package/src/lab/conformance/index.ts +5 -0
- package/src/lab/conformance/jcs.ts +64 -0
- package/src/lab/conformance/json-pointer.ts +39 -0
- package/src/lab/conformance/manifest.ts +180 -0
- package/src/lab/conformance/mcp-stub.ts +179 -0
- package/src/lab/conformance/negative-controls.ts +164 -0
- package/src/lab/conformance/observation.ts +355 -0
- package/src/lab/conformance/runner.ts +68 -0
- package/src/lab/conformance/sse-normalize.ts +59 -0
- package/src/lab/conformance/suite-manifest.ts +78 -0
- package/src/lab/conformance/types.ts +214 -0
- package/src/lab/constants.ts +126 -0
- package/src/lab/digest.ts +64 -0
- package/src/lab/events/errors.ts +9 -0
- package/src/lab/events/limits.ts +117 -0
- package/src/lab/events/types.ts +229 -0
- package/src/lab/events/validate.ts +781 -0
- package/src/lab/fabric/constants.ts +40 -0
- package/src/lab/fabric/executor.ts +492 -0
- package/src/lab/fabric/index.ts +80 -0
- package/src/lab/fabric/manifest.ts +222 -0
- package/src/lab/fabric/observe.ts +489 -0
- package/src/lab/fabric/patch.ts +79 -0
- package/src/lab/fabric/producer-child.ts +139 -0
- package/src/lab/fabric/producer-isolate.ts +276 -0
- package/src/lab/fabric/producer-protocol.ts +61 -0
- package/src/lab/fabric/scratch.ts +439 -0
- package/src/lab/fabric/subject.ts +106 -0
- package/src/lab/fabric/types.ts +134 -0
- package/src/lab/fabric/verifier.ts +98 -0
- package/src/lab/index.ts +54 -0
- package/src/lab/ledger/artifact-refs.ts +127 -0
- package/src/lab/ledger/invalidation.ts +136 -0
- package/src/lab/ledger/purge.ts +310 -0
- package/src/lab/ledger/store.ts +532 -0
- package/src/lab/live/credential-lease.ts +53 -0
- package/src/lab/live/destination.ts +155 -0
- package/src/lab/live/executor.ts +336 -0
- package/src/lab/live/inert-tools.ts +56 -0
- package/src/lab/live/manifest.ts +85 -0
- package/src/lab/live/mcp-loopback.ts +57 -0
- package/src/lab/live/runner.ts +19 -0
- package/src/lab/live/sandbox.ts +61 -0
- package/src/lab/live/suite-manifest.ts +41 -0
- package/src/lab/live/transport.ts +118 -0
- package/src/lab/live/types.ts +197 -0
- package/src/lab/observe/from-conformance.ts +301 -0
- package/src/lab/observe/from-live.ts +117 -0
- package/src/lab/paths.ts +153 -0
- package/src/lab/projection/rebuild.ts +495 -0
- package/src/lab/projection/schema.ts +135 -0
- package/src/lab/projection/verdicts.ts +474 -0
- package/src/lab/projection/verification.ts +412 -0
- package/src/lab/public/bundle.ts +217 -0
- package/src/lab/public/community-authority.ts +175 -0
- package/src/lab/public/community-files.ts +29 -0
- package/src/lab/public/community.ts +479 -0
- package/src/lab/public/file-safety.ts +155 -0
- package/src/lab/public/ids.ts +26 -0
- package/src/lab/public/index.ts +16 -0
- package/src/lab/public/mutation-lock.ts +424 -0
- package/src/lab/public/operator.ts +353 -0
- package/src/lab/public/origin-purge.ts +79 -0
- package/src/lab/public/origin.ts +203 -0
- package/src/lab/public/privacy.ts +143 -0
- package/src/lab/public/private-file.ts +261 -0
- package/src/lab/public/project.ts +124 -0
- package/src/lab/public/purge-test-fault.ts +21 -0
- package/src/lab/public/purge.ts +223 -0
- package/src/lab/public/registry.ts +44 -0
- package/src/lab/public/revocation.ts +252 -0
- package/src/lab/public/signature.ts +243 -0
- package/src/lab/public/storage.ts +105 -0
- package/src/lab/public/strict-json.ts +206 -0
- package/src/lab/public/time.ts +26 -0
- package/src/lab/public/types.ts +172 -0
- package/src/lab/public/validate.ts +391 -0
- package/src/lab/query/catalog.ts +101 -0
- package/src/lab/query/connection.ts +107 -0
- package/src/lab/query/constants.ts +4 -0
- package/src/lab/query/cursor.ts +132 -0
- package/src/lab/query/dto-map.ts +277 -0
- package/src/lab/query/errors.ts +22 -0
- package/src/lab/query/freshness.ts +53 -0
- package/src/lab/query/index.ts +45 -0
- package/src/lab/query/latest-observation.ts +59 -0
- package/src/lab/query/passive-production.ts +159 -0
- package/src/lab/query/queries.ts +444 -0
- package/src/lab/query/types.ts +266 -0
- package/src/lab/subject/behavior-fingerprint.ts +77 -0
- package/src/lab/subject/installation-salt.ts +112 -0
- package/src/lab/subject/protocol-subject.ts +80 -0
- package/src/lab/subject/route-subject.ts +74 -0
- package/src/lib/abort.ts +146 -0
- package/src/lib/admin-secrets.ts +25 -0
- package/src/lib/admission.ts +83 -0
- package/src/lib/app-owned-memory-stores.ts +195 -0
- package/src/lib/app-owned-memory.ts +265 -0
- package/src/lib/bounded-body.ts +346 -0
- package/src/lib/bun-binary-validator.d.mts +3 -0
- package/src/lib/bun-binary-validator.mjs +18 -0
- package/src/lib/bun-runtime.ts +184 -0
- package/src/lib/bun-stream-caps.ts +130 -0
- package/src/lib/codex-restart-contract.ts +120 -0
- package/src/lib/config-ownership.ts +364 -0
- package/src/lib/crash-guard.ts +344 -0
- package/src/lib/debug-log-buffer.ts +83 -0
- package/src/lib/debug-settings.ts +108 -0
- package/src/lib/debug.ts +31 -0
- package/src/lib/destination-policy.ts +380 -0
- package/src/lib/errors.ts +406 -0
- package/src/lib/eventstream-decoder.ts +253 -0
- package/src/lib/fabric-task-execution-authority.ts +7 -0
- package/src/lib/fabric-task-host.ts +29 -0
- package/src/lib/gcp-adc.ts +341 -0
- package/src/lib/injection-debug-log.ts +58 -0
- package/src/lib/lab-activation.ts +223 -0
- package/src/lib/lab-live-execution-authority.ts +13 -0
- package/src/lib/lab-live-host.ts +30 -0
- package/src/lib/lab-live-pinned-sender.ts +56 -0
- package/src/lib/lab-live-route-production.ts +130 -0
- package/src/lib/lab-passive-linker-registration.ts +26 -0
- package/src/lib/local-management-attestation.ts +51 -0
- package/src/lib/local-management-capability.ts +100 -0
- package/src/lib/local-provider-reload-contract.ts +100 -0
- package/src/lib/open-url.ts +25 -0
- package/src/lib/optional-shutdown-hooks.ts +57 -0
- package/src/lib/pinned-http.ts +270 -0
- package/src/lib/privacy.ts +20 -0
- package/src/lib/process-control.ts +168 -0
- package/src/lib/provider-outbound.ts +210 -0
- package/src/lib/provider-url.ts +14 -0
- package/src/lib/proxy-env.ts +18 -0
- package/src/lib/redact.ts +521 -0
- package/src/lib/retry-after.ts +55 -0
- package/src/lib/self-launch-argv.ts +15 -0
- package/src/lib/server-resource-ownership.ts +71 -0
- package/src/lib/service-secrets.ts +25 -0
- package/src/lib/shadow-call.ts +61 -0
- package/src/lib/sidecar-tracker.ts +52 -0
- package/src/lib/sse-decoder.ts +364 -0
- package/src/lib/state-store-registrations.ts +119 -0
- package/src/lib/state-store-sweeper.ts +184 -0
- package/src/lib/system-restart-contract.ts +73 -0
- package/src/lib/test-home-guard.ts +90 -0
- package/src/lib/token-estimate.ts +86 -0
- package/src/lib/tool-argument-integers.ts +202 -0
- package/src/lib/translator-budget.ts +400 -0
- package/src/lib/upstream-http-version.ts +57 -0
- package/src/lib/upstream-reachability.ts +95 -0
- package/src/lib/upstream-retry.ts +392 -0
- package/src/lib/win-exec.ts +115 -0
- package/src/lib/win-paths.ts +68 -0
- package/src/lib/windows-atomic-replace.ts +156 -0
- package/src/lib/windows-elevation.ts +773 -0
- package/src/lib/windows-secret-acl.ts +854 -0
- package/src/lib/windows-service-wrappers.ts +72 -0
- package/src/lib/windows-text.ts +106 -0
- package/src/lib/windows-user-principal.ts +341 -0
- package/src/lib/winsw.ts +403 -0
- package/src/oauth/account-import/google-antigravity-adapter.ts +74 -0
- package/src/oauth/account-import/index.ts +15 -0
- package/src/oauth/account-import/parser.ts +83 -0
- package/src/oauth/account-import/registry.ts +18 -0
- package/src/oauth/account-import/service.ts +75 -0
- package/src/oauth/account-import/types.ts +91 -0
- package/src/oauth/anthropic-routing.ts +594 -0
- package/src/oauth/anthropic.ts +188 -0
- package/src/oauth/antigravity-routing.ts +151 -0
- package/src/oauth/callback-server.ts +300 -0
- package/src/oauth/chatgpt.ts +161 -0
- package/src/oauth/command-code.ts +239 -0
- package/src/oauth/cursor.ts +252 -0
- package/src/oauth/github-copilot.ts +428 -0
- package/src/oauth/google-antigravity.ts +262 -0
- package/src/oauth/health.ts +407 -0
- package/src/oauth/index.ts +1504 -0
- package/src/oauth/key-providers.ts +124 -0
- package/src/oauth/kimi.ts +227 -0
- package/src/oauth/kiro-credentials.ts +726 -0
- package/src/oauth/kiro.ts +621 -0
- package/src/oauth/local-token-detect.ts +130 -0
- package/src/oauth/log.ts +50 -0
- package/src/oauth/login-cli.ts +223 -0
- package/src/oauth/nous.ts +798 -0
- package/src/oauth/pkce.ts +15 -0
- package/src/oauth/store.ts +728 -0
- package/src/oauth/token-guardian.ts +309 -0
- package/src/oauth/types.ts +62 -0
- package/src/oauth/xai.ts +241 -0
- package/src/providers/alibaba-region-backup.ts +75 -0
- package/src/providers/alibaba-region-migration.ts +156 -0
- package/src/providers/alibaba-region-startup.ts +36 -0
- package/src/providers/antigravity-models.ts +695 -0
- package/src/providers/antigravity-quota.ts +216 -0
- package/src/providers/api-keys.ts +140 -0
- package/src/providers/base-url-choices.ts +74 -0
- package/src/providers/codex-capacity.ts +292 -0
- package/src/providers/command-code-efforts.ts +144 -0
- package/src/providers/context-cap.ts +82 -0
- package/src/providers/cursor-pool.ts +72 -0
- package/src/providers/derive.ts +586 -0
- package/src/providers/fastwire.ts +501 -0
- package/src/providers/free-directory.ts +187 -0
- package/src/providers/github-copilot-transport.ts +56 -0
- package/src/providers/google-vertex-location.ts +14 -0
- package/src/providers/key-failover.ts +271 -0
- package/src/providers/kiro-models.ts +67 -0
- package/src/providers/label.ts +19 -0
- package/src/providers/model-discovery-limits.ts +16 -0
- package/src/providers/model-discovery.ts +449 -0
- package/src/providers/model-rename-migration.ts +255 -0
- package/src/providers/model-rename-startup.ts +28 -0
- package/src/providers/openai-sidecar.ts +243 -0
- package/src/providers/openai-tier-startup.ts +56 -0
- package/src/providers/openai-tiers.ts +423 -0
- package/src/providers/openai-virtual-models.ts +83 -0
- package/src/providers/opencode-zen-rate-limit.ts +102 -0
- package/src/providers/openrouter-routing.ts +102 -0
- package/src/providers/provider-id-rewrite.ts +185 -0
- package/src/providers/quota.ts +2345 -0
- package/src/providers/registry.ts +2918 -0
- package/src/providers/replit/constants.ts +27 -0
- package/src/providers/replit/derive.ts +85 -0
- package/src/providers/replit/headers.ts +28 -0
- package/src/providers/replit/origin.ts +55 -0
- package/src/providers/replit/pair-install-response.ts +72 -0
- package/src/providers/replit/probe.ts +199 -0
- package/src/providers/replit/setup.ts +350 -0
- package/src/providers/request-pacing.ts +310 -0
- package/src/providers/service-tier.ts +277 -0
- package/src/providers/slug-codec.ts +103 -0
- package/src/providers/static-model-discovery.ts +86 -0
- package/src/providers/xai-responses-opt-in.ts +15 -0
- package/src/providers/xai-transport.ts +148 -0
- package/src/reasoning-effort.ts +183 -0
- package/src/responses/compaction.ts +142 -0
- package/src/responses/custom-tool-compat.ts +266 -0
- package/src/responses/hosted-tool-policy.ts +9 -0
- package/src/responses/namespace-tool-compat.ts +355 -0
- package/src/responses/parser.ts +838 -0
- package/src/responses/provider-continuation.ts +98 -0
- package/src/responses/provider-opaque-metadata.ts +73 -0
- package/src/responses/reasoning-envelope.ts +60 -0
- package/src/responses/reasoning-replay-cache.ts +426 -0
- package/src/responses/schema.ts +165 -0
- package/src/responses/spill-store.ts +459 -0
- package/src/responses/state.ts +1433 -0
- package/src/responses/thought-signature-replay.ts +347 -0
- package/src/responses/tool-groups.ts +19 -0
- package/src/responses/tool-search-compat.ts +301 -0
- package/src/responses/truncated-stop-reason.ts +60 -0
- package/src/router.ts +761 -0
- package/src/routing/analytics.ts +378 -0
- package/src/routing/capability.ts +244 -0
- package/src/routing/compatibility/assemble.ts +73 -0
- package/src/routing/compatibility/behavior.ts +278 -0
- package/src/routing/compatibility/catalog.ts +99 -0
- package/src/routing/compatibility/endpoint.ts +52 -0
- package/src/routing/compatibility/lab-evidence-provider.ts +130 -0
- package/src/routing/compatibility/policy.ts +181 -0
- package/src/routing/compatibility/provider-slot.ts +56 -0
- package/src/routing/compatibility/reader.ts +110 -0
- package/src/routing/compatibility/subject.ts +191 -0
- package/src/routing/compatibility/types.ts +64 -0
- package/src/routing/compatibility/version.ts +104 -0
- package/src/routing/cost.ts +77 -0
- package/src/routing/evaluator.ts +495 -0
- package/src/routing/health.ts +412 -0
- package/src/routing/history/cursor.ts +43 -0
- package/src/routing/history/indexer.ts +605 -0
- package/src/routing/history/schema.ts +72 -0
- package/src/routing/profile-namespace.ts +15 -0
- package/src/routing/profile.ts +547 -0
- package/src/routing/quota.ts +145 -0
- package/src/routing/request-evidence.ts +45 -0
- package/src/routing/trace.ts +776 -0
- package/src/server/adapter-resolve.ts +53 -0
- package/src/server/auth-cors.ts +751 -0
- package/src/server/background-lifecycle.ts +182 -0
- package/src/server/chat-completions.ts +442 -0
- package/src/server/chat-native-sse.ts +331 -0
- package/src/server/chat-native.ts +426 -0
- package/src/server/claude-messages.ts +1030 -0
- package/src/server/direct-local-http.ts +347 -0
- package/src/server/effort-policy.ts +190 -0
- package/src/server/github-copilot-responses-repair.ts +338 -0
- package/src/server/gui-static.ts +152 -0
- package/src/server/image-retry.ts +42 -0
- package/src/server/images.ts +568 -0
- package/src/server/index.ts +1813 -0
- package/src/server/lifecycle.ts +498 -0
- package/src/server/live.ts +717 -0
- package/src/server/local-management-read-client.ts +90 -0
- package/src/server/local-provider-reload-client.ts +137 -0
- package/src/server/management/agent-settings-routes.ts +1433 -0
- package/src/server/management/api-access.ts +141 -0
- package/src/server/management/api-key-usage.ts +193 -0
- package/src/server/management/body.ts +41 -0
- package/src/server/management/combo-routes.ts +263 -0
- package/src/server/management/config-routes.ts +835 -0
- package/src/server/management/context.ts +113 -0
- package/src/server/management/integration-routes.ts +498 -0
- package/src/server/management/lab-automation-routes.ts +206 -0
- package/src/server/management/lab-routes.ts +563 -0
- package/src/server/management/logs-usage-routes.ts +586 -0
- package/src/server/management/model-routes.ts +560 -0
- package/src/server/management/model-rows.ts +163 -0
- package/src/server/management/native-integration-routes.ts +769 -0
- package/src/server/management/oauth-account-routes.ts +637 -0
- package/src/server/management/provider-capability-config.ts +48 -0
- package/src/server/management/provider-routes.ts +1033 -0
- package/src/server/management/replit-provider-routes.ts +86 -0
- package/src/server/management/request-history-routes.ts +191 -0
- package/src/server/management/routing-analytics-routes.ts +74 -0
- package/src/server/management/routing-profile-routes.ts +385 -0
- package/src/server/management/shared.ts +286 -0
- package/src/server/management/sidebar-routes.ts +106 -0
- package/src/server/management/storage-log-guard-routes.ts +186 -0
- package/src/server/management/sync-response.ts +69 -0
- package/src/server/management/system-restart.ts +435 -0
- package/src/server/management/system-routes.ts +194 -0
- package/src/server/management/usage-summary-cache.ts +94 -0
- package/src/server/management/vision-sidecar-options.ts +167 -0
- package/src/server/management/web-search-sidecar-options.ts +120 -0
- package/src/server/management-api.ts +314 -0
- package/src/server/management-auth.ts +482 -0
- package/src/server/memory-watchdog.ts +156 -0
- package/src/server/passive-route-linker.ts +66 -0
- package/src/server/port-reclaim.ts +307 -0
- package/src/server/ports.ts +156 -0
- package/src/server/proxy-liveness.ts +328 -0
- package/src/server/readiness.ts +99 -0
- package/src/server/relay-eager.ts +353 -0
- package/src/server/relay.ts +1209 -0
- package/src/server/request-decompress.ts +239 -0
- package/src/server/request-log-conversation.ts +168 -0
- package/src/server/request-log.ts +1259 -0
- package/src/server/responses/agent-task-recovery-cache.ts +143 -0
- package/src/server/responses/agent-task-recovery.ts +465 -0
- package/src/server/responses/collaboration.ts +551 -0
- package/src/server/responses/compact.ts +771 -0
- package/src/server/responses/core.ts +5389 -0
- package/src/server/responses/empty-completion-guard.ts +276 -0
- package/src/server/responses/encrypted-payload.ts +331 -0
- package/src/server/responses/fetch-helpers.ts +232 -0
- package/src/server/responses/input-admission.ts +185 -0
- package/src/server/responses/pacing-overload.ts +13 -0
- package/src/server/responses/passthrough-error.ts +78 -0
- package/src/server/responses/policy-fallback.ts +178 -0
- package/src/server/responses/responses-field-backfill.ts +251 -0
- package/src/server/responses/terminal-guard.ts +251 -0
- package/src/server/responses/upstream-error.ts +53 -0
- package/src/server/responses/ws-upstream.ts +308 -0
- package/src/server/responses-custom-tool-repair.ts +282 -0
- package/src/server/responses-image-gen-repair.ts +132 -0
- package/src/server/responses-item-id-repair.ts +272 -0
- package/src/server/responses-json-events.ts +90 -0
- package/src/server/responses-model-rewrite.ts +29 -0
- package/src/server/responses-reasoning-summary-rewrite.ts +178 -0
- package/src/server/responses-snapshot-repair.ts +621 -0
- package/src/server/responses-terminal-repair.ts +342 -0
- package/src/server/responses-tool-search-repair.ts +267 -0
- package/src/server/responses-undeclared-tool-guard.ts +153 -0
- package/src/server/responses.ts +25 -0
- package/src/server/search.ts +201 -0
- package/src/server/sse-frame-buffer.ts +292 -0
- package/src/server/sse-payload-rewrite.ts +263 -0
- package/src/server/startup-action-control.ts +315 -0
- package/src/server/startup-health-cache.ts +131 -0
- package/src/server/system-env.ts +484 -0
- package/src/server/windows-tcp-drop.ts +184 -0
- package/src/server/windows-tray-control.ts +41 -0
- package/src/server/ws-bridge.ts +472 -0
- package/src/service-manager-probe.ts +892 -0
- package/src/service.ts +3575 -0
- package/src/sidecar/auth.ts +92 -0
- package/src/sidecar/candidates.ts +83 -0
- package/src/stall-timeout.ts +20 -0
- package/src/storage/cleanup-job.ts +57 -0
- package/src/storage/cleanup.ts +3085 -0
- package/src/storage/policy-job.ts +457 -0
- package/src/storage/policy-scheduler.ts +40 -0
- package/src/storage/policy-worker.ts +59 -0
- package/src/storage/policy.ts +527 -0
- package/src/storage/restore-job.ts +299 -0
- package/src/storage/restore-worker.ts +58 -0
- package/src/storage/scanner.ts +238 -0
- package/src/storage/storage-mutation-coordinator.ts +139 -0
- package/src/storage/worker-lifecycle.ts +215 -0
- package/src/tray/assets/opencodex-tray-offline.ico +0 -0
- package/src/tray/assets/opencodex-tray-online.ico +0 -0
- package/src/tray/assets/opencodex-tray-warning.ico +0 -0
- package/src/tray/assets/opencodex-tray.png +0 -0
- package/src/tray/windows-tray.ps1 +364 -0
- package/src/tray/windows.ts +757 -0
- package/src/types/accounts.ts +37 -0
- package/src/types/config.ts +876 -0
- package/src/types/provider.ts +545 -0
- package/src/types/request.ts +384 -0
- package/src/types/tools.ts +131 -0
- package/src/types/wire.ts +80 -0
- package/src/types.ts +106 -0
- package/src/update/badge.ts +72 -0
- package/src/update/index.ts +415 -0
- package/src/update/job.ts +1887 -0
- package/src/update/notify.ts +263 -0
- package/src/update/npm-cache-preflight.d.mts +47 -0
- package/src/update/npm-cache-preflight.mjs +201 -0
- package/src/update/npm-invocation.d.mts +23 -0
- package/src/update/npm-invocation.mjs +94 -0
- package/src/update/transactional-install.d.mts +22 -0
- package/src/update/transactional-install.mjs +259 -0
- package/src/update/tray-update-plan.d.mts +18 -0
- package/src/update/tray-update-plan.mjs +38 -0
- package/src/usage/cost.ts +625 -0
- package/src/usage/debug.ts +97 -0
- package/src/usage/expected-prices.ts +416 -0
- package/src/usage/log.ts +1223 -0
- package/src/usage/summary.ts +753 -0
- package/src/usage/totals.ts +14 -0
- package/src/usage/user-cost-overlay-reconciler.ts +313 -0
- package/src/usage/user-cost-overlays.ts +314 -0
- package/src/vision/anthropic-describe.ts +189 -0
- package/src/vision/backends.ts +97 -0
- package/src/vision/describe.ts +131 -0
- package/src/vision/eligibility.ts +250 -0
- package/src/vision/index.ts +681 -0
- package/src/vision/reasoning.ts +55 -0
- package/src/vision/routed-describe.ts +175 -0
- package/src/vision/timeout-bounds.ts +9 -0
- package/src/web-search/anthropic-executor.ts +195 -0
- package/src/web-search/backends.ts +108 -0
- package/src/web-search/exa-executor.ts +88 -0
- package/src/web-search/executor.ts +113 -0
- package/src/web-search/format-result.ts +89 -0
- package/src/web-search/gemini-executor.ts +141 -0
- package/src/web-search/index.ts +331 -0
- package/src/web-search/loop.ts +896 -0
- package/src/web-search/parse.ts +315 -0
- package/src/web-search/progress-stream.ts +342 -0
- package/src/web-search/sources.ts +60 -0
- package/src/web-search/synthetic-tool.ts +47 -0
- package/src/web-search/xai-executor.ts +219 -0
|
@@ -0,0 +1,1911 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { IncomingMeta, ProviderAdapter } from "./base";
|
|
3
|
+
import { namespacedToolName, type AdapterEvent, type OcxParsedRequest, type OcxProviderConfig, type OcxUsage, type TierDecision } from "../types";
|
|
4
|
+
import { catalogModelSupportsReasoningSummaries } from "../codex/catalog";
|
|
5
|
+
import { COMPACT_PROMPT, compactionItemToText, decodeCompactionSummary, isCompactionItemType } from "../responses/compaction";
|
|
6
|
+
import { collectResponsesToolGroups } from "../responses/tool-groups";
|
|
7
|
+
import { isHostedToolUnsupportedForModel } from "../responses/hosted-tool-policy";
|
|
8
|
+
import { decodeServerSentEvents } from "../lib/sse-decoder";
|
|
9
|
+
import {
|
|
10
|
+
CODEX_FORWARD_BASE_URL,
|
|
11
|
+
destinationDecodesNativeCompactionBlob,
|
|
12
|
+
isCanonicalOpenAiForwardProvider,
|
|
13
|
+
isOpenAiOperatedResponsesDestination,
|
|
14
|
+
} from "../providers/openai-tiers";
|
|
15
|
+
import { OCX_REASONING_PREFIX } from "../responses/reasoning-envelope";
|
|
16
|
+
import { modelRecordValue } from "../reasoning-effort";
|
|
17
|
+
import type { TranslatorBudget } from "../lib/translator-budget";
|
|
18
|
+
import { rewriteRoutedCustomToolsForUpstream } from "../responses/custom-tool-compat";
|
|
19
|
+
import { rewriteRoutedToolSearchForUpstream } from "../responses/tool-search-compat";
|
|
20
|
+
import { rewriteRoutedNamespaceToolsForUpstream } from "../responses/namespace-tool-compat";
|
|
21
|
+
import { openaiResponsesUrl } from "./openai-responses-url";
|
|
22
|
+
import { normalizeXaiResponsesWebSearch } from "./xai-web-search";
|
|
23
|
+
import {
|
|
24
|
+
createAdapterTierMetadata,
|
|
25
|
+
} from "../providers/fastwire";
|
|
26
|
+
|
|
27
|
+
// Headers relayed verbatim from the caller in OAuth-passthrough ("forward") mode.
|
|
28
|
+
// Exported so the web-search sidecar reuses the exact same forwarded-auth set for its ChatGPT call.
|
|
29
|
+
export const FORWARD_HEADERS = [
|
|
30
|
+
"authorization",
|
|
31
|
+
"chatgpt-account-id",
|
|
32
|
+
"openai-beta",
|
|
33
|
+
"originator",
|
|
34
|
+
"session_id",
|
|
35
|
+
"session-id",
|
|
36
|
+
"thread-id",
|
|
37
|
+
"x-client-request-id",
|
|
38
|
+
"x-codex-beta-features",
|
|
39
|
+
"x-codex-installation-id",
|
|
40
|
+
"x-codex-parent-thread-id",
|
|
41
|
+
"x-codex-turn-metadata",
|
|
42
|
+
"x-codex-turn-state",
|
|
43
|
+
"x-codex-window-id",
|
|
44
|
+
"x-oai-attestation",
|
|
45
|
+
"x-openai-subagent",
|
|
46
|
+
"x-responsesapi-include-timing-metrics",
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
export function sanitizeReasoningInputContent(
|
|
50
|
+
body: unknown,
|
|
51
|
+
opts?: {
|
|
52
|
+
preserveRawReasoningContent?: boolean;
|
|
53
|
+
dropNullContentChannel?: boolean;
|
|
54
|
+
stripEncryptedContent?: boolean;
|
|
55
|
+
},
|
|
56
|
+
): unknown {
|
|
57
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return body;
|
|
58
|
+
const raw = body as Record<string, unknown>;
|
|
59
|
+
if (!Array.isArray(raw.input)) return body;
|
|
60
|
+
|
|
61
|
+
let changed = false;
|
|
62
|
+
const input = raw.input.map(item => {
|
|
63
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return item;
|
|
64
|
+
const rec = item as Record<string, unknown>;
|
|
65
|
+
if (rec.type !== "reasoning") return item;
|
|
66
|
+
const hasRawContent = Array.isArray(rec.content) && rec.content.length > 0;
|
|
67
|
+
// ocxr1 envelopes are proxy-minted (Anthropic signatures), not OpenAI encryption — the native
|
|
68
|
+
// backend cannot decrypt them and would reject the request. Strip regardless of content shape.
|
|
69
|
+
const hasOcxEnvelope = typeof rec.encrypted_content === "string" && rec.encrypted_content.startsWith(OCX_REASONING_PREFIX);
|
|
70
|
+
const hasOutputStatus = Object.prototype.hasOwnProperty.call(rec, "status");
|
|
71
|
+
const hasEncryptedContent = Object.prototype.hasOwnProperty.call(rec, "encrypted_content");
|
|
72
|
+
const stripEncryptedContent = hasOcxEnvelope
|
|
73
|
+
|| (opts?.stripEncryptedContent === true && hasEncryptedContent);
|
|
74
|
+
// Codex serializes an absent reasoning content channel as `"content": null`. The field is
|
|
75
|
+
// optional and null carries nothing, but a strict gateway rejects the item on its declared type
|
|
76
|
+
// — xAI answers `Could not decode the compaction blob`, naming the sibling `encrypted_content`
|
|
77
|
+
// rather than the field it actually refused, which is why this reads as a blob failure. Drop the
|
|
78
|
+
// key so the item matches the shape the upstream issued.
|
|
79
|
+
//
|
|
80
|
+
// Gated to routed destinations. An OpenAI-operated backend binds the blob to the item's exact
|
|
81
|
+
// shape, so deleting a field there invalidates it (`The encrypted content ... could not be
|
|
82
|
+
// verified`); the two requirements are exactly opposed, and a live regression proved it. That
|
|
83
|
+
// gate is also why this drop may touch an item that keeps its blob: xAI demonstrably accepts its
|
|
84
|
+
// own blob without the null channel, and the destinations that bind blobs to item shape never
|
|
85
|
+
// reach this branch. This is independent of the output-only status removal below.
|
|
86
|
+
const dropNullContentChannel = opts?.dropNullContentChannel === true
|
|
87
|
+
&& "content" in rec && !Array.isArray(rec.content);
|
|
88
|
+
// `status` is output-only. Measured OpenAI reasoning items never contain it, and Grok accepts
|
|
89
|
+
// its own encrypted_content with status removed. Keeping a foreign status beside a retained
|
|
90
|
+
// blob makes OpenAI reject the field before blob validation, starving the provenance recovery
|
|
91
|
+
// of the opaque-blob error it needs. Content blanking remains the separate pre-existing rule.
|
|
92
|
+
const stripOutputStatus = hasOutputStatus;
|
|
93
|
+
const blankContent = !dropNullContentChannel
|
|
94
|
+
&& !opts?.preserveRawReasoningContent
|
|
95
|
+
&& (hasRawContent || hasOcxEnvelope);
|
|
96
|
+
if (!blankContent && !stripOutputStatus && !stripEncryptedContent && !dropNullContentChannel) {
|
|
97
|
+
return item;
|
|
98
|
+
}
|
|
99
|
+
changed = true;
|
|
100
|
+
const next: Record<string, unknown> = { ...rec };
|
|
101
|
+
if (dropNullContentChannel) delete next.content;
|
|
102
|
+
if (stripOutputStatus) delete next.status;
|
|
103
|
+
if (stripEncryptedContent) delete next.encrypted_content;
|
|
104
|
+
// Routed models can produce raw `reasoning_text` output items. Codex echoes those in later
|
|
105
|
+
// native GPT requests, but ChatGPT's Responses backend accepts reasoning input only with empty
|
|
106
|
+
// `content`; keep summaries/ids and drop the raw content so native passthrough does not 400.
|
|
107
|
+
// DeepSeek's Responses API instead ACCEPTS plaintext reasoning replay (its compatibility
|
|
108
|
+
// guide merges reasoning items into the adjacent assistant message), so providers flagged
|
|
109
|
+
// `preserveResponsesReasoningContent` keep it — deleting valid replay content there breaks
|
|
110
|
+
// continuations after tool calls (issue #875 family).
|
|
111
|
+
if (blankContent) next.content = [];
|
|
112
|
+
return next;
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
return changed ? { ...raw, input } : body;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function stripUnsupportedReasoningSummaryDelivery(body: unknown, modelId: string): unknown {
|
|
119
|
+
if (catalogModelSupportsReasoningSummaries(modelId) !== false) return body;
|
|
120
|
+
if (!isPlainObject(body) || !isPlainObject(body.stream_options)) return body;
|
|
121
|
+
if (!("reasoning_summary_delivery" in body.stream_options)) return body;
|
|
122
|
+
|
|
123
|
+
const streamOptions = { ...body.stream_options };
|
|
124
|
+
delete streamOptions.reasoning_summary_delivery;
|
|
125
|
+
const next = { ...body };
|
|
126
|
+
if (Object.keys(streamOptions).length > 0) next.stream_options = streamOptions;
|
|
127
|
+
else delete next.stream_options;
|
|
128
|
+
return next;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function stripInvalidItemIds(body: unknown): unknown {
|
|
132
|
+
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
133
|
+
|
|
134
|
+
const validPrefixes: Record<string, string> = {
|
|
135
|
+
message: "msg_",
|
|
136
|
+
agent_message: "amsg_",
|
|
137
|
+
reasoning: "rs_",
|
|
138
|
+
function_call: "fc_",
|
|
139
|
+
custom_tool_call: "ctc_",
|
|
140
|
+
tool_search_call: "tsc_",
|
|
141
|
+
web_search_call: "ws_",
|
|
142
|
+
};
|
|
143
|
+
let changed = false;
|
|
144
|
+
const input = body.input.map(item => {
|
|
145
|
+
if (!isPlainObject(item) || typeof item.type !== "string") return item;
|
|
146
|
+
const validPrefix = validPrefixes[item.type];
|
|
147
|
+
if (!validPrefix) return item;
|
|
148
|
+
if (typeof item.id === "string" && item.id.startsWith(validPrefix)) return item;
|
|
149
|
+
if (!("id" in item)) return item;
|
|
150
|
+
changed = true;
|
|
151
|
+
const next = { ...item };
|
|
152
|
+
delete next.id;
|
|
153
|
+
return next;
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
return changed ? { ...body, input } : body;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Codex-private tool fields that only the ChatGPT backend understands.
|
|
161
|
+
*
|
|
162
|
+
* A third-party Responses gateway validates its schema and rejects the whole request before
|
|
163
|
+
* inference — xAI answers `Argument not supported: external_web_access` — so these are removed at
|
|
164
|
+
* the noncanonical boundary while the tool and every public option stay.
|
|
165
|
+
*
|
|
166
|
+
* Keep this a table. Each private bit Codex attaches has so far arrived as its own bespoke strip
|
|
167
|
+
* with its own traversal, and the traversals disagreed about which containers they covered; a new
|
|
168
|
+
* one should be a row here instead. `toolTypes` omitted means the field is private on any tool.
|
|
169
|
+
*/
|
|
170
|
+
const CANONICAL_ONLY_TOOL_FIELDS: readonly { field: string; toolTypes?: ReadonlySet<string>; capabilityGated?: boolean }[] = [
|
|
171
|
+
// ChatGPT's browsing policy bit. The public hosted tool is enabled by its presence alone.
|
|
172
|
+
// OWNERSHIP: official OpenAI API-key traffic and unclassified gateways ACCEPT this field, so
|
|
173
|
+
// it is only stripped when the provider capability denies it (supportsOpenAiWebSearchToolFields
|
|
174
|
+
// === false), matching stripOpenAiOnlyWebSearchFields; see
|
|
175
|
+
// tests/responses-routed-web-search-fields.test.ts.
|
|
176
|
+
{ field: "external_web_access", toolTypes: new Set(["web_search", "web_search_preview"]), capabilityGated: true },
|
|
177
|
+
// Deferred-discovery marker. `activateDeferredTool` clears it only for tools a `tool_search_output`
|
|
178
|
+
// already loaded, so a still-deferred declaration — including one promoted out of a namespace
|
|
179
|
+
// group — otherwise reaches the wire carrying it.
|
|
180
|
+
{ field: "defer_loading" },
|
|
181
|
+
];
|
|
182
|
+
|
|
183
|
+
function stripCanonicalOnlyToolFields(body: unknown, includeCapabilityGated: boolean): unknown {
|
|
184
|
+
if (!isPlainObject(body)) return body;
|
|
185
|
+
|
|
186
|
+
const rewriteTools = (tools: unknown[]): unknown[] => {
|
|
187
|
+
let changed = false;
|
|
188
|
+
const rewritten = tools.map(tool => {
|
|
189
|
+
if (!isPlainObject(tool)) return tool;
|
|
190
|
+
let next = tool;
|
|
191
|
+
for (const { field, toolTypes, capabilityGated } of CANONICAL_ONLY_TOOL_FIELDS) {
|
|
192
|
+
if (capabilityGated && !includeCapabilityGated) continue;
|
|
193
|
+
if (!Object.hasOwn(next, field)) continue;
|
|
194
|
+
if (toolTypes && (typeof next.type !== "string" || !toolTypes.has(next.type))) continue;
|
|
195
|
+
const { [field]: _private, ...rest } = next;
|
|
196
|
+
next = rest;
|
|
197
|
+
}
|
|
198
|
+
if (next === tool) return tool;
|
|
199
|
+
changed = true;
|
|
200
|
+
return next;
|
|
201
|
+
});
|
|
202
|
+
return changed ? rewritten : tools;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
let rewrittenBody = body;
|
|
206
|
+
if (Array.isArray(body.tools)) {
|
|
207
|
+
const tools = rewriteTools(body.tools);
|
|
208
|
+
if (tools !== body.tools) rewrittenBody = { ...rewrittenBody, tools };
|
|
209
|
+
}
|
|
210
|
+
if (!Array.isArray(body.input)) return rewrittenBody;
|
|
211
|
+
|
|
212
|
+
let input: unknown[] | undefined;
|
|
213
|
+
for (let index = 0; index < body.input.length; index += 1) {
|
|
214
|
+
const item = body.input[index];
|
|
215
|
+
if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) continue;
|
|
216
|
+
const tools = rewriteTools(item.tools);
|
|
217
|
+
if (tools === item.tools) continue;
|
|
218
|
+
input ??= [...body.input];
|
|
219
|
+
input[index] = { ...item, tools };
|
|
220
|
+
}
|
|
221
|
+
return input ? { ...rewrittenBody, input } : rewrittenBody;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* When `store` is false, the upstream API does not persist response items. Any item ID
|
|
226
|
+
* forwarded in `input` is then interpreted as a reference to a stored item that does not
|
|
227
|
+
* exist, producing a 404. Strip all item IDs in this case — `call_id` pairing is unaffected.
|
|
228
|
+
* Matches codex-rs behavior (core/src/client.rs:918-925).
|
|
229
|
+
*/
|
|
230
|
+
function stripItemIdsWhenUnstored(body: unknown): unknown {
|
|
231
|
+
if (!isPlainObject(body) || body.store !== false) return body;
|
|
232
|
+
if (!Array.isArray(body.input)) return body;
|
|
233
|
+
|
|
234
|
+
let changed = false;
|
|
235
|
+
const input = body.input.map(item => {
|
|
236
|
+
if (!isPlainObject(item) || !("id" in item)) return item;
|
|
237
|
+
changed = true;
|
|
238
|
+
const next = { ...item };
|
|
239
|
+
delete next.id;
|
|
240
|
+
return next;
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
return changed ? { ...body, input } : body;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Normalize replayed compaction items for the destination backend.
|
|
248
|
+
*
|
|
249
|
+
* A compaction item carries an `encrypted_content` blob the client replays verbatim on every later
|
|
250
|
+
* turn, and only the backend that minted it can decode it. Proxy-minted `ocx1:` envelopes are
|
|
251
|
+
* transparent base64 rather than encryption, so no upstream can read them and they always become
|
|
252
|
+
* plain user messages. Native blobs have multiple possible minters, so a destination's ability to
|
|
253
|
+
* decode its own blobs does not make a blob from a previous serving identity portable. On a known
|
|
254
|
+
* identity mismatch the blob degrades to the same note the bridged parser uses, even when the
|
|
255
|
+
* destination normally accepts native blobs. Without a known mismatch, the destination capability
|
|
256
|
+
* keeps the existing behavior.
|
|
257
|
+
*
|
|
258
|
+
* A bare `context_compaction` marker carries no blob and is forwarded untouched.
|
|
259
|
+
*/
|
|
260
|
+
function scrubOcxCompactionItems(
|
|
261
|
+
body: unknown,
|
|
262
|
+
destinationDecodesNativeBlob: boolean,
|
|
263
|
+
threadServingIdentityChanged: boolean,
|
|
264
|
+
): unknown {
|
|
265
|
+
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
266
|
+
|
|
267
|
+
let changed = false;
|
|
268
|
+
const input = body.input.map(item => {
|
|
269
|
+
if (!isPlainObject(item) || !isCompactionItemType(item.type)) return item;
|
|
270
|
+
const encrypted = typeof item.encrypted_content === "string" ? item.encrypted_content : undefined;
|
|
271
|
+
if (encrypted === undefined) return item;
|
|
272
|
+
if (
|
|
273
|
+
decodeCompactionSummary(encrypted) === null
|
|
274
|
+
&& destinationDecodesNativeBlob
|
|
275
|
+
&& !threadServingIdentityChanged
|
|
276
|
+
) return item;
|
|
277
|
+
changed = true;
|
|
278
|
+
return {
|
|
279
|
+
type: "message",
|
|
280
|
+
role: "user",
|
|
281
|
+
content: [{ type: "input_text", text: compactionItemToText(encrypted) }],
|
|
282
|
+
};
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
return changed ? { ...body, input } : body;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Strip unsupported `reasoning` sub-parameters for native slugs that reject them (e.g. Spark).
|
|
290
|
+
* codex-rs injects `reasoning.context` and `reasoning.summary` based on catalog flags; Spark's
|
|
291
|
+
* backend rejects both. The catalog fix prevents `use_responses_lite` from being set, but this
|
|
292
|
+
* is a defense-in-depth guard so stale on-disk catalogs don't break until the user runs `ocx sync`.
|
|
293
|
+
*/
|
|
294
|
+
function stripUnsupportedReasoningParams(body: unknown): unknown {
|
|
295
|
+
if (!isPlainObject(body)) return body;
|
|
296
|
+
const model = typeof body.model === "string" ? body.model : "";
|
|
297
|
+
if (!model.includes("codex-spark")) return body;
|
|
298
|
+
if (!isPlainObject(body.reasoning)) return body;
|
|
299
|
+
const reasoning = body.reasoning as Record<string, unknown>;
|
|
300
|
+
// Spark supports reasoning.effort but rejects context, summary, and generate_summary.
|
|
301
|
+
const { context: _ctx, summary: _sum, generate_summary: _gs, ...rest } = reasoning;
|
|
302
|
+
if (_ctx === undefined && _sum === undefined && _gs === undefined) return body;
|
|
303
|
+
return { ...body, reasoning: Object.keys(rest).length > 0 ? rest : undefined };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* GPT-5.6 replaced the legacy 24-hour retention field with `prompt_cache_options.ttl`, and the
|
|
308
|
+
* ChatGPT backend 400s the whole request when the retired field is present (issue #2092).
|
|
309
|
+
*
|
|
310
|
+
* The retired field is NOT translated to the replacement: 5.6 carries a different TTL contract,
|
|
311
|
+
* and implicit caching still applies when the caller sent no replacement options. Inventing a
|
|
312
|
+
* value here would silently change a caching decision the caller never made.
|
|
313
|
+
*
|
|
314
|
+
* Deliberately narrow on both axes, because a wider strip is a behavior change rather than a fix:
|
|
315
|
+
* only the gpt-5.6 family (an older model may still honor the field), and only on the canonical
|
|
316
|
+
* ChatGPT backend, which is the deployment that rejects it. Matching is exact-or-dashed-prefix so
|
|
317
|
+
* a future `gpt-5.60` is not swept up by a bare `startsWith`.
|
|
318
|
+
*/
|
|
319
|
+
function stripDeprecatedPromptCacheRetention(body: unknown, modelId: unknown): unknown {
|
|
320
|
+
if (!isPlainObject(body)) return body;
|
|
321
|
+
if (typeof modelId !== "string") return body;
|
|
322
|
+
if (modelId !== "gpt-5.6" && !modelId.startsWith("gpt-5.6-")) return body;
|
|
323
|
+
if (!Object.hasOwn(body, "prompt_cache_retention")) return body;
|
|
324
|
+
const { prompt_cache_retention: _retention, ...rest } = body;
|
|
325
|
+
return rest;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* A false model capability prevents Codex from emitting summary fields after the catalog refresh.
|
|
330
|
+
* Strip them here as well so an already-running client with a stale catalog cannot keep sending an
|
|
331
|
+
* upstream-rejected `reasoning_summary_delivery` value (issue #323).
|
|
332
|
+
*/
|
|
333
|
+
function stripDisabledReasoningSummaries(
|
|
334
|
+
body: unknown,
|
|
335
|
+
provider: OcxProviderConfig,
|
|
336
|
+
modelId: string,
|
|
337
|
+
): unknown {
|
|
338
|
+
if (modelRecordValue(provider.modelSupportsReasoningSummaries, modelId) !== false || !isPlainObject(body)) {
|
|
339
|
+
return body;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
let changed = false;
|
|
343
|
+
let streamOptions = body.stream_options;
|
|
344
|
+
if (isPlainObject(streamOptions) && Object.hasOwn(streamOptions, "reasoning_summary_delivery")) {
|
|
345
|
+
const { reasoning_summary_delivery: _delivery, ...rest } = streamOptions;
|
|
346
|
+
streamOptions = rest;
|
|
347
|
+
changed = true;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
let reasoning = body.reasoning;
|
|
351
|
+
if (isPlainObject(reasoning)) {
|
|
352
|
+
const { summary: _summary, generate_summary: _generateSummary, ...rest } = reasoning;
|
|
353
|
+
if (_summary !== undefined || _generateSummary !== undefined) {
|
|
354
|
+
reasoning = rest;
|
|
355
|
+
changed = true;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (!changed) return body;
|
|
360
|
+
return {
|
|
361
|
+
...body,
|
|
362
|
+
...(isPlainObject(streamOptions) && Object.keys(streamOptions).length > 0
|
|
363
|
+
? { stream_options: streamOptions }
|
|
364
|
+
: { stream_options: undefined }),
|
|
365
|
+
...(isPlainObject(reasoning) && Object.keys(reasoning).length > 0
|
|
366
|
+
? { reasoning }
|
|
367
|
+
: { reasoning: undefined }),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Normalize only the delivery enum Codex already emitted. Do not inject a field into callers that
|
|
373
|
+
* did not request summaries, and leave every unconfigured provider/model byte-for-byte unchanged.
|
|
374
|
+
*/
|
|
375
|
+
function normalizeConfiguredReasoningSummaryDelivery(
|
|
376
|
+
body: unknown,
|
|
377
|
+
provider: OcxProviderConfig,
|
|
378
|
+
modelId: string,
|
|
379
|
+
): unknown {
|
|
380
|
+
const delivery = modelRecordValue(provider.modelReasoningSummaryDelivery, modelId);
|
|
381
|
+
if (delivery === undefined || !isPlainObject(body) || !isPlainObject(body.stream_options)) return body;
|
|
382
|
+
if (!Object.hasOwn(body.stream_options, "reasoning_summary_delivery")) return body;
|
|
383
|
+
if (body.stream_options.reasoning_summary_delivery === delivery) return body;
|
|
384
|
+
return {
|
|
385
|
+
...body,
|
|
386
|
+
stream_options: {
|
|
387
|
+
...body.stream_options,
|
|
388
|
+
reasoning_summary_delivery: delivery,
|
|
389
|
+
},
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Comprehensive Spark compatibility layer. codex-rs emits five tool types (function,
|
|
395
|
+
* namespace, tool_search, web_search, custom) plus extensions (defer_loading,
|
|
396
|
+
* parallel_tool_calls, tool_search_call/output items). Spark's serving path only
|
|
397
|
+
* supports flat function tools and hosted web_search. This function:
|
|
398
|
+
* - Flattens namespace tools → promotes inner functions to top level
|
|
399
|
+
* - Drops unsupported tool types (tool_search, custom)
|
|
400
|
+
* - Strips defer_loading from function tools
|
|
401
|
+
* - Strips namespace from input items
|
|
402
|
+
* - Drops tool_search_call/tool_search_output input items
|
|
403
|
+
* - Sets parallel_tool_calls to false
|
|
404
|
+
*/
|
|
405
|
+
function stripSparkCompatibility(body: unknown): unknown {
|
|
406
|
+
if (!isPlainObject(body)) return body;
|
|
407
|
+
const model = typeof body.model === "string" ? body.model : "";
|
|
408
|
+
if (!model.includes("codex-spark")) return body;
|
|
409
|
+
|
|
410
|
+
let changed = false;
|
|
411
|
+
|
|
412
|
+
const SPARK_SAFE_TOOL_TYPES = new Set(["function", "web_search", "web_search_preview"]);
|
|
413
|
+
|
|
414
|
+
let tools = body.tools;
|
|
415
|
+
if (Array.isArray(tools)) {
|
|
416
|
+
const flattened: unknown[] = [];
|
|
417
|
+
for (const t of tools) {
|
|
418
|
+
if (isPlainObject(t) && t.type === "namespace") {
|
|
419
|
+
changed = true;
|
|
420
|
+
if (Array.isArray(t.tools)) {
|
|
421
|
+
for (const inner of t.tools) flattened.push(inner);
|
|
422
|
+
}
|
|
423
|
+
} else if (isPlainObject(t) && typeof t.type === "string" && !SPARK_SAFE_TOOL_TYPES.has(t.type)) {
|
|
424
|
+
changed = true;
|
|
425
|
+
} else {
|
|
426
|
+
flattened.push(t);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
// Strip defer_loading from promoted/remaining function tools.
|
|
430
|
+
tools = flattened.map(t => {
|
|
431
|
+
if (isPlainObject(t) && t.type === "function" && "defer_loading" in t) {
|
|
432
|
+
const { defer_loading: _, ...rest } = t;
|
|
433
|
+
changed = true;
|
|
434
|
+
return rest;
|
|
435
|
+
}
|
|
436
|
+
return t;
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Clean input items: strip namespace, drop tool_search_call/tool_search_output.
|
|
441
|
+
const SPARK_UNSUPPORTED_INPUT_TYPES = new Set([
|
|
442
|
+
"tool_search_call", "tool_search_output",
|
|
443
|
+
"custom_tool_call", "custom_tool_call_output",
|
|
444
|
+
]);
|
|
445
|
+
let input = body.input;
|
|
446
|
+
if (Array.isArray(input)) {
|
|
447
|
+
const cleaned: unknown[] = [];
|
|
448
|
+
for (const item of input) {
|
|
449
|
+
if (isPlainObject(item) && typeof item.type === "string" && SPARK_UNSUPPORTED_INPUT_TYPES.has(item.type)) {
|
|
450
|
+
changed = true;
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
// Process additional_tools items: filter their inner tools array the same way.
|
|
454
|
+
if (isPlainObject(item) && item.type === "additional_tools" && Array.isArray(item.tools)) {
|
|
455
|
+
const innerTools = item.tools as unknown[];
|
|
456
|
+
const filteredInner: unknown[] = [];
|
|
457
|
+
for (const t of innerTools) {
|
|
458
|
+
if (isPlainObject(t) && t.type === "namespace") {
|
|
459
|
+
changed = true;
|
|
460
|
+
if (Array.isArray(t.tools)) {
|
|
461
|
+
for (const fn of t.tools) filteredInner.push(fn);
|
|
462
|
+
}
|
|
463
|
+
} else if (isPlainObject(t) && typeof t.type === "string" && !SPARK_SAFE_TOOL_TYPES.has(t.type)) {
|
|
464
|
+
changed = true; // drop custom, tool_search, etc.
|
|
465
|
+
} else {
|
|
466
|
+
filteredInner.push(t);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
// Strip defer_loading from remaining function tools.
|
|
470
|
+
const cleanedInner = filteredInner.map(t => {
|
|
471
|
+
if (isPlainObject(t) && t.type === "function" && "defer_loading" in t) {
|
|
472
|
+
const { defer_loading: _, ...rest } = t;
|
|
473
|
+
changed = true;
|
|
474
|
+
return rest;
|
|
475
|
+
}
|
|
476
|
+
return t;
|
|
477
|
+
});
|
|
478
|
+
cleaned.push({ ...item, tools: cleanedInner });
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (isPlainObject(item) && "namespace" in item) {
|
|
482
|
+
const { namespace: _, ...rest } = item;
|
|
483
|
+
changed = true;
|
|
484
|
+
cleaned.push(rest);
|
|
485
|
+
} else {
|
|
486
|
+
cleaned.push(item);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (changed) input = cleaned;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// Force parallel_tool_calls off for Spark.
|
|
493
|
+
const extraOverrides: Record<string, unknown> = {};
|
|
494
|
+
if (body.parallel_tool_calls === true) { extraOverrides.parallel_tool_calls = false; changed = true; }
|
|
495
|
+
|
|
496
|
+
return changed
|
|
497
|
+
? { ...body, ...(tools !== body.tools ? { tools } : {}), ...(input !== body.input ? { input } : {}), ...extraOverrides }
|
|
498
|
+
: body;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
502
|
+
return !!v && typeof v === "object" && !Array.isArray(v);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function normalizeFunctionToolSchema(tool: unknown): unknown {
|
|
506
|
+
if (!isPlainObject(tool) || tool.type !== "function") return tool;
|
|
507
|
+
if (isPlainObject(tool.parameters) && tool.parameters.type === "object") return tool;
|
|
508
|
+
return {
|
|
509
|
+
...tool,
|
|
510
|
+
parameters: { ...(isPlainObject(tool.parameters) ? tool.parameters : {}), type: "object" },
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function normalizeToolSchemas(body: unknown): unknown {
|
|
515
|
+
if (!isPlainObject(body)) return body;
|
|
516
|
+
|
|
517
|
+
const normalizeTools = (tools: unknown[]): unknown[] => {
|
|
518
|
+
let changed = false;
|
|
519
|
+
const normalized = tools.map((tool) => {
|
|
520
|
+
const fixed = normalizeFunctionToolSchema(tool);
|
|
521
|
+
if (fixed !== tool) changed = true;
|
|
522
|
+
return fixed;
|
|
523
|
+
});
|
|
524
|
+
return changed ? normalized : tools;
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
let normalizedBody = body;
|
|
528
|
+
if (Array.isArray(body.tools)) {
|
|
529
|
+
const tools = normalizeTools(body.tools);
|
|
530
|
+
if (tools !== body.tools) normalizedBody = { ...normalizedBody, tools };
|
|
531
|
+
}
|
|
532
|
+
if (Array.isArray(normalizedBody.input)) {
|
|
533
|
+
let inputChanged = false;
|
|
534
|
+
const input = normalizedBody.input.map((item) => {
|
|
535
|
+
if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) return item;
|
|
536
|
+
const tools = normalizeTools(item.tools);
|
|
537
|
+
if (tools === item.tools) return item;
|
|
538
|
+
inputChanged = true;
|
|
539
|
+
return { ...item, tools };
|
|
540
|
+
});
|
|
541
|
+
if (inputChanged) normalizedBody = { ...normalizedBody, input };
|
|
542
|
+
}
|
|
543
|
+
return normalizedBody;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function activateDeferredTool(tool: Record<string, unknown>): Record<string, unknown> {
|
|
547
|
+
const { defer_loading: _, ...activeTool } = tool;
|
|
548
|
+
if (tool.type !== "namespace" || !Array.isArray(tool.tools)) return activeTool;
|
|
549
|
+
return {
|
|
550
|
+
...activeTool,
|
|
551
|
+
tools: tool.tools.map(inner => isPlainObject(inner) ? activateDeferredTool(inner) : inner),
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function mergeLoadedTools(declaredTools: unknown[], loadedTools: unknown[]): unknown[] {
|
|
556
|
+
const merged = [...declaredTools];
|
|
557
|
+
let changed = false;
|
|
558
|
+
|
|
559
|
+
for (const candidate of loadedTools) {
|
|
560
|
+
if (!isPlainObject(candidate) || typeof candidate.name !== "string") continue;
|
|
561
|
+
const loaded = activateDeferredTool(candidate);
|
|
562
|
+
if (loaded.type === "namespace" && Array.isArray(loaded.tools)) {
|
|
563
|
+
const namespaceIndex = merged.findIndex(tool =>
|
|
564
|
+
isPlainObject(tool) && tool.type === "namespace" && tool.name === loaded.name
|
|
565
|
+
);
|
|
566
|
+
if (namespaceIndex < 0) {
|
|
567
|
+
merged.push(loaded);
|
|
568
|
+
changed = true;
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
const namespace = merged[namespaceIndex];
|
|
573
|
+
if (!isPlainObject(namespace)) continue;
|
|
574
|
+
const namespaceTools = Array.isArray(namespace.tools) ? namespace.tools : [];
|
|
575
|
+
const nextNamespaceTools = [...namespaceTools];
|
|
576
|
+
let namespaceChanged = "defer_loading" in namespace;
|
|
577
|
+
for (const tool of loaded.tools) {
|
|
578
|
+
if (!isPlainObject(tool) || typeof tool.name !== "string") continue;
|
|
579
|
+
const declaredIndex = nextNamespaceTools.findIndex(declared =>
|
|
580
|
+
isPlainObject(declared) && declared.name === tool.name
|
|
581
|
+
);
|
|
582
|
+
if (declaredIndex < 0) {
|
|
583
|
+
nextNamespaceTools.push(tool);
|
|
584
|
+
namespaceChanged = true;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
const declared = nextNamespaceTools[declaredIndex];
|
|
588
|
+
if (isPlainObject(declared) && "defer_loading" in declared) {
|
|
589
|
+
nextNamespaceTools[declaredIndex] = activateDeferredTool(declared);
|
|
590
|
+
namespaceChanged = true;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (!namespaceChanged) continue;
|
|
594
|
+
const { defer_loading: _, ...activeNamespace } = namespace;
|
|
595
|
+
merged[namespaceIndex] = { ...activeNamespace, tools: nextNamespaceTools };
|
|
596
|
+
changed = true;
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const declaredIndex = merged.findIndex(tool =>
|
|
601
|
+
isPlainObject(tool) && tool.type !== "namespace" && tool.name === loaded.name
|
|
602
|
+
);
|
|
603
|
+
if (declaredIndex < 0) {
|
|
604
|
+
merged.push(loaded);
|
|
605
|
+
changed = true;
|
|
606
|
+
} else {
|
|
607
|
+
const declared = merged[declaredIndex];
|
|
608
|
+
if (isPlainObject(declared) && "defer_loading" in declared) {
|
|
609
|
+
merged[declaredIndex] = activateDeferredTool(declared);
|
|
610
|
+
changed = true;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
return changed ? merged : declaredTools;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Client-executed tool search only changes Codex's parsed tool context. Routed passthrough keeps
|
|
620
|
+
* serializing the raw request, so activate those returned definitions for upstreams that do not
|
|
621
|
+
* implement the native deferred-loading handshake themselves.
|
|
622
|
+
*/
|
|
623
|
+
function promoteClientLoadedTools(body: unknown): unknown {
|
|
624
|
+
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
625
|
+
|
|
626
|
+
const loadedTools = body.input.flatMap(item =>
|
|
627
|
+
isPlainObject(item) && item.type === "tool_search_output" && Array.isArray(item.tools)
|
|
628
|
+
? item.tools
|
|
629
|
+
: []
|
|
630
|
+
);
|
|
631
|
+
if (loadedTools.length === 0) return body;
|
|
632
|
+
|
|
633
|
+
if (Array.isArray(body.tools)) {
|
|
634
|
+
const tools = mergeLoadedTools(body.tools, loadedTools);
|
|
635
|
+
return tools === body.tools ? body : { ...body, tools };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const additionalToolsIndex = body.input.findIndex(item =>
|
|
639
|
+
isPlainObject(item) && item.type === "additional_tools" && Array.isArray(item.tools)
|
|
640
|
+
);
|
|
641
|
+
if (additionalToolsIndex < 0) return { ...body, tools: mergeLoadedTools([], loadedTools) };
|
|
642
|
+
|
|
643
|
+
const additionalTools = body.input[additionalToolsIndex];
|
|
644
|
+
if (!isPlainObject(additionalTools) || !Array.isArray(additionalTools.tools)) return body;
|
|
645
|
+
const tools = mergeLoadedTools(additionalTools.tools, loadedTools);
|
|
646
|
+
if (tools === additionalTools.tools) return body;
|
|
647
|
+
const input = [...body.input];
|
|
648
|
+
input[additionalToolsIndex] = { ...additionalTools, tools };
|
|
649
|
+
return { ...body, input };
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
const MAX_RESPONSES_CALL_ID_LENGTH = 64;
|
|
653
|
+
const REPAIRED_CALL_ID_PREFIX = "call_ocx_";
|
|
654
|
+
const REPAIRED_CALL_ID_DIGEST_LENGTH = MAX_RESPONSES_CALL_ID_LENGTH - REPAIRED_CALL_ID_PREFIX.length;
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* The ChatGPT Responses backend rejects input `call_id` values longer than 64 characters. Codex
|
|
658
|
+
* sidechat/fork replay can namespace call ids from routed providers past that limit. Forward mode
|
|
659
|
+
* already sends explicit replay input without `previous_response_id`, so it is safe to replace each
|
|
660
|
+
* oversized id and every matching call/output occurrence with one deterministic request-local alias.
|
|
661
|
+
* Raw API-key continuations are intentionally excluded because an output-only continuation may
|
|
662
|
+
* reference a call stored upstream under the original id. Proxy-expanded API-key replays are
|
|
663
|
+
* explicit and stateless here, so they are safe to repair too.
|
|
664
|
+
*/
|
|
665
|
+
function repairOversizedReplayCallIds(body: unknown): unknown {
|
|
666
|
+
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
667
|
+
|
|
668
|
+
const occupied = new Set<string>();
|
|
669
|
+
for (const item of body.input) {
|
|
670
|
+
if (!isPlainObject(item) || typeof item.call_id !== "string") continue;
|
|
671
|
+
if (item.call_id.length <= MAX_RESPONSES_CALL_ID_LENGTH) occupied.add(item.call_id);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
const aliases = new Map<string, string>();
|
|
675
|
+
let changed = false;
|
|
676
|
+
const input = body.input.map(item => {
|
|
677
|
+
if (!isPlainObject(item) || typeof item.call_id !== "string") return item;
|
|
678
|
+
const original = item.call_id;
|
|
679
|
+
if (original.length <= MAX_RESPONSES_CALL_ID_LENGTH) return item;
|
|
680
|
+
|
|
681
|
+
let alias = aliases.get(original);
|
|
682
|
+
if (!alias) {
|
|
683
|
+
let salt = 0;
|
|
684
|
+
do {
|
|
685
|
+
const hashInput = salt === 0 ? original : `${original}\0${salt}`;
|
|
686
|
+
const digest = createHash("sha256").update(hashInput).digest("hex");
|
|
687
|
+
alias = `${REPAIRED_CALL_ID_PREFIX}${digest.slice(0, REPAIRED_CALL_ID_DIGEST_LENGTH)}`;
|
|
688
|
+
salt += 1;
|
|
689
|
+
} while (occupied.has(alias));
|
|
690
|
+
aliases.set(original, alias);
|
|
691
|
+
occupied.add(alias);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
changed = true;
|
|
695
|
+
return { ...item, call_id: alias };
|
|
696
|
+
});
|
|
697
|
+
|
|
698
|
+
return changed ? { ...body, input } : body;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/** Flatten a Responses tool-output `output` value (string or content-part array) to plain text. */
|
|
702
|
+
function toolOutputText(output: unknown): string {
|
|
703
|
+
if (typeof output === "string") return output;
|
|
704
|
+
if (!Array.isArray(output)) return JSON.stringify(output ?? "");
|
|
705
|
+
return output.map(part => {
|
|
706
|
+
if (!isPlainObject(part)) return "";
|
|
707
|
+
if (typeof part.text === "string") return part.text;
|
|
708
|
+
if (part.type === "refusal" && typeof part.refusal === "string") return `[refusal] ${part.refusal}`;
|
|
709
|
+
return "";
|
|
710
|
+
}).filter(Boolean).join("\n");
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Repair a forward-mode input array whose continuation context was lost. When the replay
|
|
715
|
+
* expansion misses (proxy restart, unrecorded prior turn), previous_response_id is stripped
|
|
716
|
+
* (the ChatGPT backend rejects it), so the delta may carry items that reference now-absent
|
|
717
|
+
* prior items and 400 upstream:
|
|
718
|
+
* - `function_call`/`local_shell_call`/`custom_tool_call` without their paired output item
|
|
719
|
+
* ("No tool output found for tool call <call_id>"). A stateless upstream cannot resolve
|
|
720
|
+
* the pair from its own storage, so a placeholder output is synthesized to keep the
|
|
721
|
+
* turn continuable without pretending the result was real. Synthetic outputs are
|
|
722
|
+
* emitted after the complete parallel call batch, in call order alongside any real
|
|
723
|
+
* outputs, so the adjacency normalizer can still recognize the batch as one
|
|
724
|
+
* reasoning-bearing assistant turn (#1477). Gated on
|
|
725
|
+
* `synthesizeMissingCallOutputs` (stateless AND non-forward wires); forward replay keeps
|
|
726
|
+
* fail-closed behavior.
|
|
727
|
+
* - `function_call_output`/`custom_tool_call_output` without their paired call item
|
|
728
|
+
* ("No tool call found for function call output with call_id ..."). Converted to user
|
|
729
|
+
* messages so the result text survives. `function_call_output` also pairs with
|
|
730
|
+
* `local_shell_call` (codex-rs emits shell outputs as function_call_output).
|
|
731
|
+
* - `reasoning` items ("Item 'rs_*' ... was provided without its required following item").
|
|
732
|
+
* Dropped, but only when `dropReasoning` (unexpanded miss): on a replay hit the prior
|
|
733
|
+
* reasoning chain is intact and must be preserved.
|
|
734
|
+
* Runs on every forward request; with intact pairs it returns the original reference.
|
|
735
|
+
*/
|
|
736
|
+
/**
|
|
737
|
+
* Backfill `queries` on a replayed single-query `web_search_call`.
|
|
738
|
+
*
|
|
739
|
+
* `webSearchAction()` in the bridge now emits both keys, but that only helps items
|
|
740
|
+
* created after the fix. A conversation that already recorded
|
|
741
|
+
* `{type:"search", query:"..."}` replays that stored item on every subsequent turn, and
|
|
742
|
+
* DeepSeek's native Responses parser requires `queries` — so upgrading alone leaves
|
|
743
|
+
* those threads permanently 400ing with `missing field 'queries'` (#930).
|
|
744
|
+
*
|
|
745
|
+
* Runs on every Responses request, on both `input` items and the `action` nested inside
|
|
746
|
+
* them. Returns the original reference when nothing needs repair, so the common path
|
|
747
|
+
* allocates nothing.
|
|
748
|
+
*/
|
|
749
|
+
function backfillWebSearchQueries(body: unknown): unknown {
|
|
750
|
+
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
751
|
+
let changed = false;
|
|
752
|
+
const input = body.input.map(item => {
|
|
753
|
+
if (!isPlainObject(item) || item.type !== "web_search_call") return item;
|
|
754
|
+
const action = item.action;
|
|
755
|
+
if (!isPlainObject(action) || action.type !== "search") return item;
|
|
756
|
+
if (typeof action.query !== "string" || Array.isArray(action.queries)) return item;
|
|
757
|
+
changed = true;
|
|
758
|
+
return { ...item, action: { ...action, queries: [action.query] } };
|
|
759
|
+
});
|
|
760
|
+
return changed ? { ...body, input } : body;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function repairOrphanedInputItems(body: unknown, dropReasoning: boolean, synthesizeMissingCallOutputs = false): unknown {
|
|
764
|
+
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
765
|
+
const input = body.input;
|
|
766
|
+
|
|
767
|
+
const functionCallIds = new Set<string>();
|
|
768
|
+
const customCallIds = new Set<string>();
|
|
769
|
+
const functionOutputIds = new Set<string>();
|
|
770
|
+
const customOutputIds = new Set<string>();
|
|
771
|
+
for (const item of input) {
|
|
772
|
+
if (!isPlainObject(item) || typeof item.call_id !== "string") continue;
|
|
773
|
+
if (item.type === "function_call" || item.type === "local_shell_call") functionCallIds.add(item.call_id);
|
|
774
|
+
else if (item.type === "custom_tool_call") customCallIds.add(item.call_id);
|
|
775
|
+
else if (item.type === "function_call_output") functionOutputIds.add(item.call_id);
|
|
776
|
+
else if (item.type === "custom_tool_call_output") customOutputIds.add(item.call_id);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
let changed = false;
|
|
780
|
+
const repaired: unknown[] = [];
|
|
781
|
+
const syntheticKeys = new Set<string>();
|
|
782
|
+
const pendingSyntheticOutputs: unknown[] = [];
|
|
783
|
+
const flushPendingSyntheticOutputs = (): void => {
|
|
784
|
+
if (pendingSyntheticOutputs.length === 0) return;
|
|
785
|
+
repaired.push(...pendingSyntheticOutputs);
|
|
786
|
+
pendingSyntheticOutputs.length = 0;
|
|
787
|
+
};
|
|
788
|
+
for (const item of input) {
|
|
789
|
+
if (!isPlainObject(item)) { flushPendingSyntheticOutputs(); repaired.push(item); continue; }
|
|
790
|
+
if (dropReasoning && item.type === "reasoning") { changed = true; continue; }
|
|
791
|
+
const isFnOutput = item.type === "function_call_output";
|
|
792
|
+
const isCustomOutput = item.type === "custom_tool_call_output";
|
|
793
|
+
if (isFnOutput || isCustomOutput) {
|
|
794
|
+
flushPendingSyntheticOutputs();
|
|
795
|
+
const callId = typeof item.call_id === "string" ? item.call_id : "";
|
|
796
|
+
const paired = isFnOutput ? functionCallIds.has(callId) : customCallIds.has(callId);
|
|
797
|
+
if (!paired) {
|
|
798
|
+
changed = true;
|
|
799
|
+
repaired.push({
|
|
800
|
+
type: "message",
|
|
801
|
+
role: "user",
|
|
802
|
+
content: [{ type: "input_text", text: `[tool output for ${callId || "unknown call"}]\n${toolOutputText(item.output)}` }],
|
|
803
|
+
});
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
const isFnCall = item.type === "function_call" || item.type === "local_shell_call";
|
|
808
|
+
const isCustomCall = item.type === "custom_tool_call";
|
|
809
|
+
if (isFnCall || isCustomCall) {
|
|
810
|
+
repaired.push(item);
|
|
811
|
+
if (synthesizeMissingCallOutputs) {
|
|
812
|
+
const callId = typeof item.call_id === "string" ? item.call_id : "";
|
|
813
|
+
const hasOutput = isFnCall ? functionOutputIds.has(callId) : customOutputIds.has(callId);
|
|
814
|
+
if (!hasOutput && callId) {
|
|
815
|
+
changed = true;
|
|
816
|
+
const name = typeof item.name === "string" && item.name.length > 0 ? item.name : callId;
|
|
817
|
+
const text = `[ocx] no tool result was recorded for "${name}"; execution status unknown — do not treat this as success, failure, or user-provided input.`;
|
|
818
|
+
syntheticKeys.add(`${isFnCall ? "function" : "custom"}:${callId}`);
|
|
819
|
+
pendingSyntheticOutputs.push(isFnCall
|
|
820
|
+
? { type: "function_call_output", call_id: callId, output: text }
|
|
821
|
+
: { type: "custom_tool_call_output", call_id: callId, output: text });
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
flushPendingSyntheticOutputs();
|
|
827
|
+
repaired.push(item);
|
|
828
|
+
}
|
|
829
|
+
flushPendingSyntheticOutputs();
|
|
830
|
+
|
|
831
|
+
const callKeyOf = (item: unknown): string | null => {
|
|
832
|
+
if (!isPlainObject(item) || typeof item.call_id !== "string") return null;
|
|
833
|
+
if (item.type === "function_call" || item.type === "local_shell_call") return `function:${item.call_id}`;
|
|
834
|
+
if (item.type === "custom_tool_call") return `custom:${item.call_id}`;
|
|
835
|
+
return null;
|
|
836
|
+
};
|
|
837
|
+
const outputKeyOf = (item: unknown): string | null => {
|
|
838
|
+
if (!isPlainObject(item) || typeof item.call_id !== "string") return null;
|
|
839
|
+
if (item.type === "function_call_output") return `function:${item.call_id}`;
|
|
840
|
+
if (item.type === "custom_tool_call_output") return `custom:${item.call_id}`;
|
|
841
|
+
return null;
|
|
842
|
+
};
|
|
843
|
+
const reorderBatchOutputs = (items: unknown[]): unknown[] => {
|
|
844
|
+
const ordered: unknown[] = [];
|
|
845
|
+
const claimedOutputIndexes = new Set<number>();
|
|
846
|
+
const outputIndexesByKey = new Map<string, { indexes: number[]; offset: number }>();
|
|
847
|
+
for (let outputIndex = 0; outputIndex < items.length; outputIndex += 1) {
|
|
848
|
+
const outputKey = outputKeyOf(items[outputIndex]);
|
|
849
|
+
if (outputKey === null) continue;
|
|
850
|
+
const bucket = outputIndexesByKey.get(outputKey);
|
|
851
|
+
if (bucket) bucket.indexes.push(outputIndex);
|
|
852
|
+
else outputIndexesByKey.set(outputKey, { indexes: [outputIndex], offset: 0 });
|
|
853
|
+
}
|
|
854
|
+
let index = 0;
|
|
855
|
+
while (index < items.length) {
|
|
856
|
+
if (claimedOutputIndexes.has(index)) { index += 1; continue; }
|
|
857
|
+
const key = callKeyOf(items[index]);
|
|
858
|
+
if (key === null) { ordered.push(items[index]); index += 1; continue; }
|
|
859
|
+
const batch: unknown[] = [];
|
|
860
|
+
const batchKeys: string[] = [];
|
|
861
|
+
let cursor = index;
|
|
862
|
+
while (cursor < items.length) {
|
|
863
|
+
const nextKey = callKeyOf(items[cursor]);
|
|
864
|
+
if (nextKey === null) break;
|
|
865
|
+
batch.push(items[cursor]);
|
|
866
|
+
batchKeys.push(nextKey);
|
|
867
|
+
cursor += 1;
|
|
868
|
+
}
|
|
869
|
+
const hasSynthetic = batchKeys.some(batchKey => syntheticKeys.has(batchKey));
|
|
870
|
+
if (!hasSynthetic) {
|
|
871
|
+
ordered.push(...batch);
|
|
872
|
+
index = cursor;
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
const batchOutputs: unknown[] = [];
|
|
876
|
+
for (const batchKey of batchKeys) {
|
|
877
|
+
const bucket = outputIndexesByKey.get(batchKey);
|
|
878
|
+
if (!bucket) continue;
|
|
879
|
+
while (bucket.offset < bucket.indexes.length && bucket.indexes[bucket.offset]! < cursor) {
|
|
880
|
+
bucket.offset += 1;
|
|
881
|
+
}
|
|
882
|
+
while (bucket.offset < bucket.indexes.length) {
|
|
883
|
+
const outputIndex = bucket.indexes[bucket.offset]!;
|
|
884
|
+
bucket.offset += 1;
|
|
885
|
+
if (claimedOutputIndexes.has(outputIndex)) continue;
|
|
886
|
+
claimedOutputIndexes.add(outputIndex);
|
|
887
|
+
batchOutputs.push(items[outputIndex]);
|
|
888
|
+
break;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
ordered.push(...batch, ...batchOutputs);
|
|
892
|
+
index = cursor;
|
|
893
|
+
}
|
|
894
|
+
return ordered;
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
return changed ? { ...body, input: reorderBatchOutputs(repaired) } : body;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* Make unambiguous Responses tool batches contiguous for upstream parsers that require it.
|
|
902
|
+
*
|
|
903
|
+
* [Decision Log]
|
|
904
|
+
* - 목적과 의도: Keep Codex hook-injected developer context without splitting a parallel tool-call turn away from its reasoning or making a strict upstream reject matching results.
|
|
905
|
+
* - 기존 구현 및 제약 조건: The orphan repair verifies only pair presence, while the original pair-by-pair reorder turned `reasoning, call A, call B, output A, output B` into two assistant turns and made DeepSeek reject call B for missing reasoning (#1477).
|
|
906
|
+
* - 검토한 주요 대안: Disable parallel calls (DeepSeek always enables them); duplicate reasoning per call; reorder each pair; or normalize the complete unambiguous call batch.
|
|
907
|
+
* - 선택한 방식: Treat calls emitted before the first matched result as one batch, emit all calls followed by their matched outputs, and preserve intervening non-tool items immediately after the batch.
|
|
908
|
+
* - 다른 대안 대신 이 방식을 선택한 이유: Batch normalization matches the Responses parallel-call shape without fabricating reasoning, while the provider gate and unique-pair requirement keep the blast radius narrow.
|
|
909
|
+
* - 장점, 단점 및 영향: DeepSeek keeps one reasoning-bearing assistant turn for parallel calls and still accepts hook-interleaved single calls; tolerant providers stay byte/order equivalent, and duplicate, missing, or backwards call/result pairs are not guessed.
|
|
910
|
+
*/
|
|
911
|
+
function normalizeResponsesToolResultAdjacency(body: unknown): unknown {
|
|
912
|
+
if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
|
|
913
|
+
const input = body.input;
|
|
914
|
+
const calls = new Map<string, number[]>();
|
|
915
|
+
const outputs = new Map<string, number[]>();
|
|
916
|
+
|
|
917
|
+
const appendIndex = (map: Map<string, number[]>, key: string, index: number): void => {
|
|
918
|
+
const existing = map.get(key);
|
|
919
|
+
if (existing) existing.push(index);
|
|
920
|
+
else map.set(key, [index]);
|
|
921
|
+
};
|
|
922
|
+
|
|
923
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
924
|
+
const item = input[index];
|
|
925
|
+
if (!isPlainObject(item) || typeof item.call_id !== "string" || item.call_id.length === 0) continue;
|
|
926
|
+
if (item.type === "function_call" || item.type === "local_shell_call") {
|
|
927
|
+
appendIndex(calls, `function:${item.call_id}`, index);
|
|
928
|
+
} else if (item.type === "custom_tool_call") {
|
|
929
|
+
appendIndex(calls, `custom:${item.call_id}`, index);
|
|
930
|
+
} else if (item.type === "function_call_output") {
|
|
931
|
+
appendIndex(outputs, `function:${item.call_id}`, index);
|
|
932
|
+
} else if (item.type === "custom_tool_call_output") {
|
|
933
|
+
appendIndex(outputs, `custom:${item.call_id}`, index);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
const pairs: Array<{ callIndex: number; outputIndex: number }> = [];
|
|
938
|
+
for (const [key, callIndices] of calls) {
|
|
939
|
+
const outputIndices = outputs.get(key);
|
|
940
|
+
if (!outputIndices) return body;
|
|
941
|
+
if (callIndices.length !== 1 || outputIndices.length !== 1) return body;
|
|
942
|
+
const callIndex = callIndices[0]!;
|
|
943
|
+
const outputIndex = outputIndices[0]!;
|
|
944
|
+
if (outputIndex <= callIndex) return body;
|
|
945
|
+
pairs.push({ callIndex, outputIndex });
|
|
946
|
+
}
|
|
947
|
+
// Reject any collected output that lacks exactly one matching call. A lone or
|
|
948
|
+
// duplicated output is ambiguous, and normalizing on top of it could sever a
|
|
949
|
+
// result from the reasoning-bearing call turn it belongs to.
|
|
950
|
+
for (const [key, outputIndices] of outputs) {
|
|
951
|
+
const callIndices = calls.get(key);
|
|
952
|
+
if (!callIndices || callIndices.length !== 1 || outputIndices.length !== 1) return body;
|
|
953
|
+
}
|
|
954
|
+
pairs.sort((left, right) => left.callIndex - right.callIndex);
|
|
955
|
+
|
|
956
|
+
const movedIndices = new Set<number>();
|
|
957
|
+
const batchAt = new Map<number, unknown[]>();
|
|
958
|
+
for (let cursor = 0; cursor < pairs.length;) {
|
|
959
|
+
const group = [pairs[cursor]!];
|
|
960
|
+
let firstOutputIndex = pairs[cursor]!.outputIndex;
|
|
961
|
+
let next = cursor + 1;
|
|
962
|
+
while (next < pairs.length && pairs[next]!.callIndex < firstOutputIndex) {
|
|
963
|
+
group.push(pairs[next]!);
|
|
964
|
+
firstOutputIndex = Math.min(firstOutputIndex, pairs[next]!.outputIndex);
|
|
965
|
+
next += 1;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// Within one reasoning turn the outputs must appear in the same order as their
|
|
969
|
+
// calls. If they are reversed, normalizing would fabricate a new output order;
|
|
970
|
+
// leave the ambiguous history untouched instead.
|
|
971
|
+
for (let groupIndex = 1; groupIndex < group.length; groupIndex += 1) {
|
|
972
|
+
if (group[groupIndex]!.outputIndex < group[groupIndex - 1]!.outputIndex) return body;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
const batch = [
|
|
976
|
+
...group.map(pair => input[pair.callIndex]),
|
|
977
|
+
...group.map(pair => input[pair.outputIndex]),
|
|
978
|
+
];
|
|
979
|
+
const anchor = group[0]!.callIndex;
|
|
980
|
+
const alreadyContiguous = batch.every((item, offset) => input[anchor + offset] === item);
|
|
981
|
+
if (!alreadyContiguous) {
|
|
982
|
+
batchAt.set(anchor, batch);
|
|
983
|
+
for (const pair of group) {
|
|
984
|
+
movedIndices.add(pair.callIndex);
|
|
985
|
+
movedIndices.add(pair.outputIndex);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
cursor = next;
|
|
989
|
+
}
|
|
990
|
+
if (batchAt.size === 0) return body;
|
|
991
|
+
|
|
992
|
+
const normalized: unknown[] = [];
|
|
993
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
994
|
+
const batch = batchAt.get(index);
|
|
995
|
+
if (batch) normalized.push(...batch);
|
|
996
|
+
if (!movedIndices.has(index)) normalized.push(input[index]);
|
|
997
|
+
}
|
|
998
|
+
return { ...body, input: normalized };
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/**
|
|
1002
|
+
* Remove `previous_response_id` before forwarding. Two triggers:
|
|
1003
|
+
* - the proxy expanded the request into a full input replay (the id is now redundant), or
|
|
1004
|
+
* - the target is the ChatGPT backend (`authMode: "forward"`), whose Codex REST endpoint
|
|
1005
|
+
* categorically rejects the parameter with `{"detail":"Unsupported parameter:
|
|
1006
|
+
* previous_response_id"}` (strict allowlist; it also rejects `metadata` and
|
|
1007
|
+
* `max_output_tokens`). Codex only sends the id on WS turns, and ocx converts those to
|
|
1008
|
+
* internal HTTP requests, so forwarding it upstream is a guaranteed 400 — stripping is
|
|
1009
|
+
* strictly better even when the local replay state missed. API-key mode keeps the field on
|
|
1010
|
+
* unexpanded requests: the platform `/v1/responses` supports real server-side storage.
|
|
1011
|
+
*/
|
|
1012
|
+
function stripPreviousResponseId(body: unknown, strip: boolean): unknown {
|
|
1013
|
+
if (!strip || !isPlainObject(body) || !Object.prototype.hasOwnProperty.call(body, "previous_response_id")) return body;
|
|
1014
|
+
const { previous_response_id: _previousResponseId, ...rest } = body;
|
|
1015
|
+
return rest;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/** Apply the settled tier only to a fresh outbound object; `_rawBody` remains caller-owned. */
|
|
1019
|
+
function applyTierDecisionToResponsesBody(body: unknown, decision: TierDecision | undefined): unknown {
|
|
1020
|
+
if (!decision || decision.kind === "forward-caller" || !isPlainObject(body)) return body;
|
|
1021
|
+
const next: Record<string, unknown> = { ...body };
|
|
1022
|
+
if (decision.kind === "set") next.service_tier = decision.value;
|
|
1023
|
+
else delete next.service_tier;
|
|
1024
|
+
return next;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/**
|
|
1028
|
+
* Drop request parameters a stateless Responses upstream cannot implement, and pin
|
|
1029
|
+
* `store` false.
|
|
1030
|
+
*
|
|
1031
|
+
* `previous_response_id` is listed here as well as in `stripPreviousResponseId`
|
|
1032
|
+
* because that helper's strip is conditional on replay expansion, and it keeps the
|
|
1033
|
+
* field for API-key providers on the premise that the platform offers real
|
|
1034
|
+
* server-side storage. DeepSeek documents the opposite: "the API is stateless:
|
|
1035
|
+
* responses and conversations are not stored on the server", so the field can never
|
|
1036
|
+
* be honoured regardless of expansion state.
|
|
1037
|
+
*
|
|
1038
|
+
* `prompt` is a reference to a server-stored prompt template — the most stateful
|
|
1039
|
+
* field in the accepted schema.
|
|
1040
|
+
*
|
|
1041
|
+
* `service_tier` is deliberately NOT dropped: the final TierDecision is applied to a
|
|
1042
|
+
* detached outbound body before this sanitizer chain, and silently deleting a configured knob is
|
|
1043
|
+
* worse than forwarding a parameter the upstream ignores.
|
|
1044
|
+
*
|
|
1045
|
+
* MUST run before the composed sanitize chain below: `stripItemIdsWhenUnstored` keys
|
|
1046
|
+
* off `store === false`, and a stateless upstream cannot resolve a stored item id.
|
|
1047
|
+
* Returns a copy, so `parsed._rawBody` keeps the client's original `store` value and
|
|
1048
|
+
* the local replay cache still records the turn.
|
|
1049
|
+
*/
|
|
1050
|
+
function stripStatefulResponsesParams(body: unknown): unknown {
|
|
1051
|
+
if (!isPlainObject(body)) return body;
|
|
1052
|
+
const drop = ["previous_response_id", "conversation", "background", "metadata", "prompt"] as const;
|
|
1053
|
+
const present = drop.some(key => Object.prototype.hasOwnProperty.call(body, key));
|
|
1054
|
+
if (!present && body.store === false) return body;
|
|
1055
|
+
const next: Record<string, unknown> = { ...body };
|
|
1056
|
+
for (const key of drop) delete next[key];
|
|
1057
|
+
next.store = false;
|
|
1058
|
+
return next;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* Remove top-level parameters the ChatGPT backend (`authMode: "forward"`) rejects
|
|
1063
|
+
* with `{"detail":"Unsupported parameter: …"}` (strict allowlist). Codex CLI never
|
|
1064
|
+
* sends these — it controls output length via `reasoning.effort` — but third-party
|
|
1065
|
+
* Responses API clients (GJC, SDK wrappers) include `max_output_tokens` per the
|
|
1066
|
+
* public spec. `metadata` is likewise absent from the allowlist. No-op when the
|
|
1067
|
+
* body carries neither field, keeping the common Codex path allocation-free.
|
|
1068
|
+
*/
|
|
1069
|
+
function stripUnsupportedForwardParams(body: unknown): unknown {
|
|
1070
|
+
if (!isPlainObject(body)) return body;
|
|
1071
|
+
const hasMot = Object.prototype.hasOwnProperty.call(body, "max_output_tokens");
|
|
1072
|
+
const hasMeta = Object.prototype.hasOwnProperty.call(body, "metadata");
|
|
1073
|
+
if (!hasMot && !hasMeta) return body;
|
|
1074
|
+
const { max_output_tokens: _mot, metadata: _meta, ...rest } = body;
|
|
1075
|
+
return rest;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
const IMAGE_GEN_NAMESPACE = "image_gen";
|
|
1079
|
+
const HOSTED_IMAGE_GENERATION_TOOL = "image_generation";
|
|
1080
|
+
const IMAGE_GEN_DOTTED_PREFIX = `${IMAGE_GEN_NAMESPACE}.`;
|
|
1081
|
+
const IMAGE_GEN_WIRE_PREFIX = `${IMAGE_GEN_NAMESPACE}__`;
|
|
1082
|
+
|
|
1083
|
+
/** Remove a supported client prefix before constructing the canonical image-gen wire alias. */
|
|
1084
|
+
function imageGenLocalName(name: string): string {
|
|
1085
|
+
if (name.startsWith(IMAGE_GEN_DOTTED_PREFIX)) return name.slice(IMAGE_GEN_DOTTED_PREFIX.length);
|
|
1086
|
+
if (name.startsWith(IMAGE_GEN_WIRE_PREFIX)) return name.slice(IMAGE_GEN_WIRE_PREFIX.length);
|
|
1087
|
+
return name;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/** Build the flat public-Responses name used only on the upstream wire. */
|
|
1091
|
+
function imageGenWireName(name: string): string {
|
|
1092
|
+
return namespacedToolName(IMAGE_GEN_NAMESPACE, imageGenLocalName(name));
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/** Match client image-gen declarations across namespace, legacy dotted, and canonical wire forms. */
|
|
1096
|
+
function isImageGenClientName(name: string): boolean {
|
|
1097
|
+
return name === IMAGE_GEN_NAMESPACE
|
|
1098
|
+
|| name.startsWith(IMAGE_GEN_DOTTED_PREFIX)
|
|
1099
|
+
|| name.startsWith(IMAGE_GEN_WIRE_PREFIX);
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/** Identify declarations that should activate image-gen request normalization. */
|
|
1103
|
+
function declaresImageGenClientTool(tool: unknown): boolean {
|
|
1104
|
+
if (!isPlainObject(tool) || typeof tool.name !== "string") return false;
|
|
1105
|
+
if (tool.type === "namespace") return tool.name === IMAGE_GEN_NAMESPACE;
|
|
1106
|
+
return isImageGenClientName(tool.name);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/** Rewrite client image-gen selectors to the hosted tool without widening caller restrictions. */
|
|
1110
|
+
function preferHostedImageGenToolChoice(toolChoice: unknown): unknown {
|
|
1111
|
+
if (!isPlainObject(toolChoice)) return toolChoice;
|
|
1112
|
+
if ((toolChoice.type === "function" || toolChoice.type === "custom") && typeof toolChoice.name === "string") {
|
|
1113
|
+
return isImageGenClientName(toolChoice.name) ? { type: HOSTED_IMAGE_GENERATION_TOOL } : toolChoice;
|
|
1114
|
+
}
|
|
1115
|
+
if (toolChoice.type !== "allowed_tools" || !Array.isArray(toolChoice.tools)) return toolChoice;
|
|
1116
|
+
const hasHostedImageTool = toolChoice.tools.some(tool => isPlainObject(tool) && tool.type === HOSTED_IMAGE_GENERATION_TOOL);
|
|
1117
|
+
let changed = false;
|
|
1118
|
+
let addedHostedImageTool = false;
|
|
1119
|
+
const tools: unknown[] = [];
|
|
1120
|
+
for (const tool of toolChoice.tools) {
|
|
1121
|
+
const isClientImageTool = isPlainObject(tool)
|
|
1122
|
+
&& (tool.type === "function" || tool.type === "custom")
|
|
1123
|
+
&& typeof tool.name === "string"
|
|
1124
|
+
&& isImageGenClientName(tool.name);
|
|
1125
|
+
if (!isClientImageTool) {
|
|
1126
|
+
tools.push(tool);
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
changed = true;
|
|
1130
|
+
if (!hasHostedImageTool && !addedHostedImageTool) {
|
|
1131
|
+
tools.push({ type: HOSTED_IMAGE_GENERATION_TOOL });
|
|
1132
|
+
addedHostedImageTool = true;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
return changed ? { ...toolChoice, tools } : toolChoice;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/**
|
|
1139
|
+
* Some Responses-compatible gateways reserve the hosted image namespace even when the request
|
|
1140
|
+
* does not explicitly declare `image_generation`. For an explicitly configured model, remove only
|
|
1141
|
+
* colliding client declarations so the gateway's hosted tool can take precedence.
|
|
1142
|
+
*/
|
|
1143
|
+
function preferConfiguredHostedTools(
|
|
1144
|
+
body: unknown,
|
|
1145
|
+
provider: OcxProviderConfig,
|
|
1146
|
+
modelId: string,
|
|
1147
|
+
selectedModelId?: string,
|
|
1148
|
+
): unknown {
|
|
1149
|
+
// A virtual model's advertised id takes precedence over its resolved wire-model id.
|
|
1150
|
+
// Read own properties only: a routed model id of `constructor`/`toString` would
|
|
1151
|
+
// otherwise resolve to an inherited Object.prototype function and throw on the
|
|
1152
|
+
// membership test below, failing the request before it is dispatched.
|
|
1153
|
+
const preferenceMap = provider.modelPreferHostedTools;
|
|
1154
|
+
const ownPreference = (key: string | undefined): string[] | undefined => {
|
|
1155
|
+
if (!key || !preferenceMap || !Object.prototype.hasOwnProperty.call(preferenceMap, key)) return undefined;
|
|
1156
|
+
const entry = preferenceMap[key];
|
|
1157
|
+
return Array.isArray(entry) ? entry : undefined;
|
|
1158
|
+
};
|
|
1159
|
+
const preferredTools = ownPreference(selectedModelId) ?? ownPreference(modelId);
|
|
1160
|
+
if (!preferredTools?.includes(HOSTED_IMAGE_GENERATION_TOOL) || !isPlainObject(body)) return body;
|
|
1161
|
+
|
|
1162
|
+
const stripGroup = (tools: unknown[]): unknown[] => {
|
|
1163
|
+
const filtered = tools.filter(tool => !declaresImageGenClientTool(tool));
|
|
1164
|
+
return filtered.length === tools.length ? tools : filtered;
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
let changed = false;
|
|
1168
|
+
let tools = body.tools;
|
|
1169
|
+
let strippedTopLevelImageGenTool = false;
|
|
1170
|
+
if (Array.isArray(body.tools)) {
|
|
1171
|
+
tools = stripGroup(body.tools);
|
|
1172
|
+
strippedTopLevelImageGenTool = tools !== body.tools;
|
|
1173
|
+
changed ||= strippedTopLevelImageGenTool;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
let input = body.input;
|
|
1177
|
+
const strippedAdditionalToolsIndices = new Set<number>();
|
|
1178
|
+
if (Array.isArray(body.input)) {
|
|
1179
|
+
let nestedChanged = false;
|
|
1180
|
+
const mappedInput = body.input.map((item, index) => {
|
|
1181
|
+
if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) return item;
|
|
1182
|
+
const nestedTools = stripGroup(item.tools);
|
|
1183
|
+
if (nestedTools === item.tools) return item;
|
|
1184
|
+
strippedAdditionalToolsIndices.add(index);
|
|
1185
|
+
nestedChanged = true;
|
|
1186
|
+
return { ...item, tools: nestedTools };
|
|
1187
|
+
});
|
|
1188
|
+
if (nestedChanged) {
|
|
1189
|
+
input = mappedInput;
|
|
1190
|
+
changed = true;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
const hasToolChoice = Object.hasOwn(body, "tool_choice");
|
|
1195
|
+
const toolChoice = hasToolChoice ? preferHostedImageGenToolChoice(body.tool_choice) : body.tool_choice;
|
|
1196
|
+
const toolChoiceChanged = hasToolChoice && toolChoice !== body.tool_choice;
|
|
1197
|
+
const hasHostedImageGenTool = (toolGroup: unknown): boolean => Array.isArray(toolGroup)
|
|
1198
|
+
&& toolGroup.some(tool => isPlainObject(tool) && tool.type === HOSTED_IMAGE_GENERATION_TOOL);
|
|
1199
|
+
const hasHostedImageGenDeclaration = hasHostedImageGenTool(tools)
|
|
1200
|
+
|| (Array.isArray(input) && input.some(item => isPlainObject(item)
|
|
1201
|
+
&& item.type === "additional_tools"
|
|
1202
|
+
&& hasHostedImageGenTool(item.tools)));
|
|
1203
|
+
if ((strippedTopLevelImageGenTool || strippedAdditionalToolsIndices.size > 0) && !hasHostedImageGenDeclaration) {
|
|
1204
|
+
if (strippedTopLevelImageGenTool && Array.isArray(tools)) {
|
|
1205
|
+
tools = [...tools, { type: HOSTED_IMAGE_GENERATION_TOOL }];
|
|
1206
|
+
} else if (strippedAdditionalToolsIndices.size > 0 && Array.isArray(input)) {
|
|
1207
|
+
// Restore into the FIRST stripped container only. Tool declarations are
|
|
1208
|
+
// request-scoped, not container-scoped — the containers are separate carriers for
|
|
1209
|
+
// one tool set, so a single hosted declaration covers the request. An earlier
|
|
1210
|
+
// revision restored into every stripped container and put `image_generation` on
|
|
1211
|
+
// the wire twice; review caught it.
|
|
1212
|
+
const firstStripped = Math.min(...strippedAdditionalToolsIndices);
|
|
1213
|
+
input = input.map((item, index) => index === firstStripped
|
|
1214
|
+
&& isPlainObject(item)
|
|
1215
|
+
&& Array.isArray(item.tools)
|
|
1216
|
+
? { ...item, tools: [...item.tools, { type: HOSTED_IMAGE_GENERATION_TOOL }] }
|
|
1217
|
+
: item);
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
changed ||= toolChoiceChanged;
|
|
1221
|
+
if (!changed) return body;
|
|
1222
|
+
const next: Record<string, unknown> = {
|
|
1223
|
+
...body,
|
|
1224
|
+
...(Array.isArray(body.tools) ? { tools } : {}),
|
|
1225
|
+
...(Array.isArray(body.input) ? { input } : {}),
|
|
1226
|
+
};
|
|
1227
|
+
if (toolChoiceChanged) next.tool_choice = toolChoice;
|
|
1228
|
+
return next;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
/**
|
|
1232
|
+
* Lower one complete Codex image-gen namespace to public Responses function tools.
|
|
1233
|
+
*
|
|
1234
|
+
* The public API reserves the `image_gen` namespace and restricts function names to a flat safe
|
|
1235
|
+
* alphabet. `image_gen__<tool>` is therefore an upstream-only alias; client-facing responses are
|
|
1236
|
+
* restored to explicit `{ namespace: "image_gen", name: "<tool>" }` calls by the server. Only a
|
|
1237
|
+
* non-empty namespace containing named function tools is safe to lower. Malformed, empty, and
|
|
1238
|
+
* future namespace shapes stay untouched instead of silently losing client capabilities.
|
|
1239
|
+
*/
|
|
1240
|
+
function flattenImageGenNamespace(tool: unknown): Record<string, unknown>[] | undefined {
|
|
1241
|
+
if (
|
|
1242
|
+
!isPlainObject(tool)
|
|
1243
|
+
|| tool.type !== "namespace"
|
|
1244
|
+
|| tool.name !== IMAGE_GEN_NAMESPACE
|
|
1245
|
+
|| !Array.isArray(tool.tools)
|
|
1246
|
+
|| tool.tools.length === 0
|
|
1247
|
+
) return undefined;
|
|
1248
|
+
|
|
1249
|
+
for (const innerTool of tool.tools) {
|
|
1250
|
+
if (
|
|
1251
|
+
!isPlainObject(innerTool)
|
|
1252
|
+
|| innerTool.type !== "function"
|
|
1253
|
+
|| typeof innerTool.name !== "string"
|
|
1254
|
+
|| innerTool.name.length === 0
|
|
1255
|
+
) return undefined;
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
return tool.tools.map(innerTool => {
|
|
1259
|
+
const functionTool = innerTool as Record<string, unknown> & { name: string };
|
|
1260
|
+
return {
|
|
1261
|
+
...functionTool,
|
|
1262
|
+
name: imageGenWireName(functionTool.name),
|
|
1263
|
+
};
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/** Convert a legacy dotted function declaration while preserving all other function metadata. */
|
|
1268
|
+
function normalizeFlatImageGenFunction(tool: unknown): unknown {
|
|
1269
|
+
if (
|
|
1270
|
+
!isPlainObject(tool)
|
|
1271
|
+
|| tool.type !== "function"
|
|
1272
|
+
|| typeof tool.name !== "string"
|
|
1273
|
+
|| !tool.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)
|
|
1274
|
+
) return tool;
|
|
1275
|
+
return { ...tool, name: imageGenWireName(tool.name) };
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/** Return the image-gen function name used for stable cross-container deduplication. */
|
|
1279
|
+
function imageGenFunctionName(tool: unknown): string | undefined {
|
|
1280
|
+
if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
|
|
1281
|
+
return undefined;
|
|
1282
|
+
}
|
|
1283
|
+
return isImageGenClientName(tool.name) ? tool.name : undefined;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
/** True only when a declaration can yield a callable upstream-safe image-gen function alias. */
|
|
1287
|
+
function declaresUsableImageGenAlias(tool: unknown): boolean {
|
|
1288
|
+
if (flattenImageGenNamespace(tool)) return true;
|
|
1289
|
+
if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
|
|
1290
|
+
return false;
|
|
1291
|
+
}
|
|
1292
|
+
if (tool.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)) {
|
|
1293
|
+
return tool.name.length > IMAGE_GEN_DOTTED_PREFIX.length;
|
|
1294
|
+
}
|
|
1295
|
+
return tool.name.startsWith(IMAGE_GEN_WIRE_PREFIX)
|
|
1296
|
+
&& tool.name.length > IMAGE_GEN_WIRE_PREFIX.length;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
/** Collect client tool-choice names and the exact upstream aliases declared for them. */
|
|
1300
|
+
function imageGenToolChoiceAliases(toolGroups: unknown[][]): Map<string, string> {
|
|
1301
|
+
const aliases = new Map<string, string>();
|
|
1302
|
+
|
|
1303
|
+
for (const group of toolGroups) {
|
|
1304
|
+
for (const tool of group) {
|
|
1305
|
+
const flattened = flattenImageGenNamespace(tool);
|
|
1306
|
+
if (flattened) {
|
|
1307
|
+
for (const candidate of flattened) {
|
|
1308
|
+
const wireName = candidate.name as string;
|
|
1309
|
+
aliases.set(`${IMAGE_GEN_DOTTED_PREFIX}${imageGenLocalName(wireName)}`, wireName);
|
|
1310
|
+
aliases.set(wireName, wireName);
|
|
1311
|
+
}
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
|
|
1315
|
+
continue;
|
|
1316
|
+
}
|
|
1317
|
+
if (
|
|
1318
|
+
tool.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)
|
|
1319
|
+
&& tool.name.length > IMAGE_GEN_DOTTED_PREFIX.length
|
|
1320
|
+
) {
|
|
1321
|
+
aliases.set(tool.name, imageGenWireName(tool.name));
|
|
1322
|
+
} else if (
|
|
1323
|
+
tool.name.startsWith(IMAGE_GEN_WIRE_PREFIX)
|
|
1324
|
+
&& tool.name.length > IMAGE_GEN_WIRE_PREFIX.length
|
|
1325
|
+
) {
|
|
1326
|
+
aliases.set(tool.name, tool.name);
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
return aliases;
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
/** Rewrite function selectors only when their corresponding declaration receives a wire alias. */
|
|
1335
|
+
function normalizeImageGenToolChoice(
|
|
1336
|
+
toolChoice: unknown,
|
|
1337
|
+
aliases: ReadonlyMap<string, string>,
|
|
1338
|
+
): unknown {
|
|
1339
|
+
if (!isPlainObject(toolChoice)) return toolChoice;
|
|
1340
|
+
|
|
1341
|
+
if (toolChoice.type === "function" && typeof toolChoice.name === "string") {
|
|
1342
|
+
const alias = aliases.get(toolChoice.name);
|
|
1343
|
+
return alias && alias !== toolChoice.name ? { ...toolChoice, name: alias } : toolChoice;
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
if (toolChoice.type !== "allowed_tools" || !Array.isArray(toolChoice.tools)) return toolChoice;
|
|
1347
|
+
let changed = false;
|
|
1348
|
+
const tools = toolChoice.tools.map(tool => {
|
|
1349
|
+
if (!isPlainObject(tool) || tool.type !== "function" || typeof tool.name !== "string") {
|
|
1350
|
+
return tool;
|
|
1351
|
+
}
|
|
1352
|
+
const alias = aliases.get(tool.name);
|
|
1353
|
+
if (!alias || alias === tool.name) return tool;
|
|
1354
|
+
changed = true;
|
|
1355
|
+
return { ...tool, name: alias };
|
|
1356
|
+
});
|
|
1357
|
+
return changed ? { ...toolChoice, tools } : toolChoice;
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
/** Identify replayed image-gen calls that require upstream wire encoding. */
|
|
1361
|
+
function declaresImageGenFunctionCall(item: unknown): boolean {
|
|
1362
|
+
if (!isPlainObject(item) || item.type !== "function_call" || typeof item.name !== "string") {
|
|
1363
|
+
return false;
|
|
1364
|
+
}
|
|
1365
|
+
return item.namespace === IMAGE_GEN_NAMESPACE || isImageGenClientName(item.name);
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
/** Encode native or legacy replay calls to the same flat name used by tool declarations. */
|
|
1369
|
+
function normalizeImageGenFunctionCall(item: unknown): unknown {
|
|
1370
|
+
if (!declaresImageGenFunctionCall(item) || !isPlainObject(item) || typeof item.name !== "string") {
|
|
1371
|
+
return item;
|
|
1372
|
+
}
|
|
1373
|
+
if (item.namespace === IMAGE_GEN_NAMESPACE) {
|
|
1374
|
+
const { namespace: _namespace, ...rest } = item;
|
|
1375
|
+
return { ...rest, name: imageGenWireName(item.name) };
|
|
1376
|
+
}
|
|
1377
|
+
if (item.name.startsWith(IMAGE_GEN_DOTTED_PREFIX)) {
|
|
1378
|
+
return { ...item, name: imageGenWireName(item.name) };
|
|
1379
|
+
}
|
|
1380
|
+
return item;
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
/**
|
|
1384
|
+
* Normalize Codex's private image-gen tool declaration for API-key Responses providers.
|
|
1385
|
+
*
|
|
1386
|
+
* A complete `image_gen` namespace is flattened to safe `image_gen__<tool>` aliases even when it is
|
|
1387
|
+
* the only image tool in the request. Replayed client calls are encoded to the same alias, including
|
|
1388
|
+
* legacy dotted calls from older compatibility attempts. When a usable alias replaces a client
|
|
1389
|
+
* image-gen declaration, the duplicate hosted `image_generation` entry is removed. Duplicate aliases
|
|
1390
|
+
* are resolved in stable container order: top-level tools first, then Responses Lite
|
|
1391
|
+
* `additional_tools` entries.
|
|
1392
|
+
*
|
|
1393
|
+
* This function is called only on the API-key path. ChatGPT forward mode understands the private
|
|
1394
|
+
* namespace and must keep it. Copy-on-write preserves the original request reference when no
|
|
1395
|
+
* namespace is flattened, hosted tool removed, or duplicate function discarded.
|
|
1396
|
+
*/
|
|
1397
|
+
function normalizeImageGenClientTools(body: unknown): unknown {
|
|
1398
|
+
if (!isPlainObject(body)) return body;
|
|
1399
|
+
|
|
1400
|
+
const toolGroups = collectResponsesToolGroups(body);
|
|
1401
|
+
const hasImageGenClientTool = toolGroups.some(group => group.some(declaresImageGenClientTool))
|
|
1402
|
+
|| (Array.isArray(body.input) && body.input.some(declaresImageGenFunctionCall));
|
|
1403
|
+
if (!hasImageGenClientTool) return body;
|
|
1404
|
+
const hasUsableImageGenAlias = toolGroups.some(group => group.some(declaresUsableImageGenAlias));
|
|
1405
|
+
const toolChoiceAliases = imageGenToolChoiceAliases(toolGroups);
|
|
1406
|
+
|
|
1407
|
+
const seenFunctionNames = new Set<string>();
|
|
1408
|
+
const normalizeGroup = (tools: unknown[]): unknown[] => {
|
|
1409
|
+
const normalized: unknown[] = [];
|
|
1410
|
+
let groupChanged = false;
|
|
1411
|
+
|
|
1412
|
+
for (const tool of tools) {
|
|
1413
|
+
if (
|
|
1414
|
+
hasUsableImageGenAlias
|
|
1415
|
+
&& isPlainObject(tool)
|
|
1416
|
+
&& tool.type === HOSTED_IMAGE_GENERATION_TOOL
|
|
1417
|
+
) {
|
|
1418
|
+
groupChanged = true;
|
|
1419
|
+
continue;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
const flattened = flattenImageGenNamespace(tool);
|
|
1423
|
+
const candidates = flattened ?? [tool];
|
|
1424
|
+
if (flattened) groupChanged = true;
|
|
1425
|
+
|
|
1426
|
+
for (const candidate of candidates) {
|
|
1427
|
+
const normalizedCandidate = normalizeFlatImageGenFunction(candidate);
|
|
1428
|
+
if (normalizedCandidate !== candidate) groupChanged = true;
|
|
1429
|
+
const functionName = imageGenFunctionName(normalizedCandidate);
|
|
1430
|
+
if (functionName && seenFunctionNames.has(functionName)) {
|
|
1431
|
+
groupChanged = true;
|
|
1432
|
+
continue;
|
|
1433
|
+
}
|
|
1434
|
+
if (functionName) seenFunctionNames.add(functionName);
|
|
1435
|
+
normalized.push(normalizedCandidate);
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
return groupChanged ? normalized : tools;
|
|
1440
|
+
};
|
|
1441
|
+
|
|
1442
|
+
let changed = false;
|
|
1443
|
+
let tools = body.tools;
|
|
1444
|
+
if (Array.isArray(body.tools)) {
|
|
1445
|
+
tools = normalizeGroup(body.tools);
|
|
1446
|
+
changed ||= tools !== body.tools;
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
let input = body.input;
|
|
1450
|
+
if (Array.isArray(body.input)) {
|
|
1451
|
+
let nestedChanged = false;
|
|
1452
|
+
const mappedInput = body.input.map(item => {
|
|
1453
|
+
if (isPlainObject(item) && item.type === "additional_tools" && Array.isArray(item.tools)) {
|
|
1454
|
+
const nestedTools = normalizeGroup(item.tools);
|
|
1455
|
+
if (nestedTools === item.tools) return item;
|
|
1456
|
+
nestedChanged = true;
|
|
1457
|
+
return { ...item, tools: nestedTools };
|
|
1458
|
+
}
|
|
1459
|
+
const normalizedCall = normalizeImageGenFunctionCall(item);
|
|
1460
|
+
if (normalizedCall !== item) nestedChanged = true;
|
|
1461
|
+
return normalizedCall;
|
|
1462
|
+
});
|
|
1463
|
+
if (nestedChanged) {
|
|
1464
|
+
input = mappedInput;
|
|
1465
|
+
changed = true;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
const toolChoice = normalizeImageGenToolChoice(body.tool_choice, toolChoiceAliases);
|
|
1470
|
+
changed ||= toolChoice !== body.tool_choice;
|
|
1471
|
+
|
|
1472
|
+
if (!changed) return body;
|
|
1473
|
+
return {
|
|
1474
|
+
...body,
|
|
1475
|
+
...(Array.isArray(body.tools) ? { tools } : {}),
|
|
1476
|
+
...(Array.isArray(body.input) ? { input } : {}),
|
|
1477
|
+
...(Object.prototype.hasOwnProperty.call(body, "tool_choice") ? { tool_choice: toolChoice } : {}),
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* Remove hosted tool entries the target native slug rejects, so the OAuth-passthrough body never
|
|
1483
|
+
* carries a tool the upstream model 400s on. No-op (returns the original reference) when nothing
|
|
1484
|
+
* matches, keeping the common path allocation-free.
|
|
1485
|
+
*/
|
|
1486
|
+
function stripUnsupportedHostedTools(body: unknown): unknown {
|
|
1487
|
+
if (!isPlainObject(body) || !Array.isArray(body.tools)) return body;
|
|
1488
|
+
const model = typeof body.model === "string" ? body.model : "";
|
|
1489
|
+
const tools = body.tools.filter(t => {
|
|
1490
|
+
const type = isPlainObject(t) && typeof t.type === "string" ? t.type : undefined;
|
|
1491
|
+
return !type || !isHostedToolUnsupportedForModel(model, type);
|
|
1492
|
+
});
|
|
1493
|
+
return tools.length === body.tools.length ? body : { ...body, tools };
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
/**
|
|
1497
|
+
* OpenAI hosted web_search config fields that a capability-classified Responses
|
|
1498
|
+
* upstream may reject wholesale. xAI's /v1/responses 400s the entire request on
|
|
1499
|
+
* `external_web_access` and `search_context_size` ("Argument not supported"),
|
|
1500
|
+
* which killed every routed Grok turn whose client (Codex) attaches its
|
|
1501
|
+
* default web_search tool config (probe 2026-08-21: both fields 400
|
|
1502
|
+
* individually; `user_location` and `filters` are accepted and kept).
|
|
1503
|
+
* The caller decides whether to apply this compatibility transform from explicit
|
|
1504
|
+
* provider capability metadata; an unclassified upstream keeps the fields.
|
|
1505
|
+
*/
|
|
1506
|
+
const OPENAI_ONLY_WEB_SEARCH_FIELDS = ["external_web_access", "search_context_size"] as const;
|
|
1507
|
+
|
|
1508
|
+
function stripOpenAiOnlyWebSearchFieldsFromTools(tools: unknown[]): {
|
|
1509
|
+
tools: unknown[];
|
|
1510
|
+
changed: boolean;
|
|
1511
|
+
} {
|
|
1512
|
+
let changed = false;
|
|
1513
|
+
const stripped = tools.map(tool => {
|
|
1514
|
+
if (!isPlainObject(tool) || (tool.type !== "web_search" && tool.type !== "web_search_preview")) {
|
|
1515
|
+
return tool;
|
|
1516
|
+
}
|
|
1517
|
+
if (!OPENAI_ONLY_WEB_SEARCH_FIELDS.some(field => Object.hasOwn(tool, field))) return tool;
|
|
1518
|
+
const { external_web_access: _access, search_context_size: _size, ...rest } = tool;
|
|
1519
|
+
changed = true;
|
|
1520
|
+
return rest;
|
|
1521
|
+
});
|
|
1522
|
+
return { tools: changed ? stripped : tools, changed };
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
export function stripOpenAiOnlyWebSearchFields(body: unknown): unknown {
|
|
1526
|
+
if (!isPlainObject(body)) return body;
|
|
1527
|
+
|
|
1528
|
+
let next: Record<string, unknown> = body;
|
|
1529
|
+
let changed = false;
|
|
1530
|
+
if (Array.isArray(body.tools)) {
|
|
1531
|
+
const stripped = stripOpenAiOnlyWebSearchFieldsFromTools(body.tools);
|
|
1532
|
+
if (stripped.changed) {
|
|
1533
|
+
next = { ...next, tools: stripped.tools };
|
|
1534
|
+
changed = true;
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
if (Array.isArray(body.input)) {
|
|
1539
|
+
let inputChanged = false;
|
|
1540
|
+
const input = body.input.map(item => {
|
|
1541
|
+
if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) {
|
|
1542
|
+
return item;
|
|
1543
|
+
}
|
|
1544
|
+
const stripped = stripOpenAiOnlyWebSearchFieldsFromTools(item.tools);
|
|
1545
|
+
if (!stripped.changed) return item;
|
|
1546
|
+
inputChanged = true;
|
|
1547
|
+
return { ...item, tools: stripped.tools };
|
|
1548
|
+
});
|
|
1549
|
+
if (inputChanged) {
|
|
1550
|
+
next = { ...next, input };
|
|
1551
|
+
changed = true;
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
return changed ? next : body;
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
/** Replace every `input_image` part under a routed-compaction body with a short marker. */
|
|
1559
|
+
function stripInputImagesDeep(value: unknown): unknown {
|
|
1560
|
+
if (Array.isArray(value)) return value.map(stripInputImagesDeep);
|
|
1561
|
+
if (!isPlainObject(value)) return value;
|
|
1562
|
+
if (value.type === "input_image") {
|
|
1563
|
+
return { type: "input_text", text: "[image omitted for compaction]" };
|
|
1564
|
+
}
|
|
1565
|
+
const out: Record<string, unknown> = {};
|
|
1566
|
+
for (const [key, entry] of Object.entries(value)) out[key] = stripInputImagesDeep(entry);
|
|
1567
|
+
return out;
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
/**
|
|
1571
|
+
* Rewrite a compaction turn for an upstream that does not speak Codex's private
|
|
1572
|
+
* `compaction_trigger` item: drop the trigger and the whole tool surface, and ask
|
|
1573
|
+
* for the handoff summary in plain terms instead (#422).
|
|
1574
|
+
*
|
|
1575
|
+
* The adapter builds from `parsed._rawBody`, so the summarizer prompt that
|
|
1576
|
+
* handleResponses() pushed onto `parsed.context` never reaches the wire — it has to
|
|
1577
|
+
* be applied here. Images go too: a summary needs no pixels, and a text-only
|
|
1578
|
+
* gateway would reject them.
|
|
1579
|
+
*/
|
|
1580
|
+
function buildRoutedCompactionBody(body: unknown): unknown {
|
|
1581
|
+
if (!isPlainObject(body)) return body;
|
|
1582
|
+
// `text` goes with the tool fields: the summary must be prose, not schema-constrained JSON.
|
|
1583
|
+
const { tools: _tools, tool_choice: _toolChoice, parallel_tool_calls: _parallel, text: _text, ...rest } = body;
|
|
1584
|
+
const input = Array.isArray(body.input) ? body.input : [];
|
|
1585
|
+
const kept = input.filter(item => !isPlainObject(item)
|
|
1586
|
+
// `additional_tools` is how Codex Desktop's responses-lite shape carries tools;
|
|
1587
|
+
// leaving it in would break the no-tools invariant even with `tools` removed.
|
|
1588
|
+
|| (item.type !== "compaction_trigger" && item.type !== "additional_tools"));
|
|
1589
|
+
return {
|
|
1590
|
+
...rest,
|
|
1591
|
+
input: [
|
|
1592
|
+
...(stripInputImagesDeep(kept) as unknown[]),
|
|
1593
|
+
{ type: "message", role: "user", content: [{ type: "input_text", text: COMPACT_PROMPT }] },
|
|
1594
|
+
],
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
/** Read the Responses `usage` block, if the gateway sent one. */
|
|
1599
|
+
function usageFromResponsesPayload(payload: unknown): OcxUsage | undefined {
|
|
1600
|
+
if (!isPlainObject(payload) || !isPlainObject(payload.usage)) return undefined;
|
|
1601
|
+
const usage = payload.usage;
|
|
1602
|
+
const inputTokens = typeof usage.input_tokens === "number" ? usage.input_tokens : 0;
|
|
1603
|
+
const outputTokens = typeof usage.output_tokens === "number" ? usage.output_tokens : 0;
|
|
1604
|
+
if (inputTokens === 0 && outputTokens === 0) return undefined;
|
|
1605
|
+
return {
|
|
1606
|
+
inputTokens,
|
|
1607
|
+
outputTokens,
|
|
1608
|
+
...(typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {}),
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
function responsesPayloadText(response: unknown): string {
|
|
1613
|
+
if (!isPlainObject(response) || !Array.isArray(response.output)) return "";
|
|
1614
|
+
return response.output
|
|
1615
|
+
.filter(item => isPlainObject(item) && item.type === "message")
|
|
1616
|
+
.flatMap(item => (Array.isArray((item as Record<string, unknown>).content)
|
|
1617
|
+
? (item as { content: unknown[] }).content
|
|
1618
|
+
: []))
|
|
1619
|
+
.filter(part => isPlainObject(part) && part.type === "output_text")
|
|
1620
|
+
.map(part => String((part as { text?: unknown }).text ?? ""))
|
|
1621
|
+
.join("");
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
function responsesErrorMessage(payload: unknown): string {
|
|
1625
|
+
if (!isPlainObject(payload)) return "upstream compaction failed";
|
|
1626
|
+
const err = payload.error;
|
|
1627
|
+
if (typeof err === "string") return err;
|
|
1628
|
+
if (isPlainObject(err) && typeof err.message === "string") return err.message;
|
|
1629
|
+
const incomplete = payload.incomplete_details;
|
|
1630
|
+
if (isPlainObject(incomplete) && typeof incomplete.reason === "string") return incomplete.reason;
|
|
1631
|
+
return "upstream compaction failed";
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
export function createResponsesPassthroughAdapter(provider: OcxProviderConfig): ProviderAdapter & { passthrough: true } {
|
|
1635
|
+
return {
|
|
1636
|
+
name: "openai-responses",
|
|
1637
|
+
passthrough: true as const,
|
|
1638
|
+
|
|
1639
|
+
buildRequest(parsed: OcxParsedRequest, incoming: IncomingMeta) {
|
|
1640
|
+
const translatorBudget = incoming.translatorBudget;
|
|
1641
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
1642
|
+
let url: string;
|
|
1643
|
+
|
|
1644
|
+
if (provider.authMode === "forward") {
|
|
1645
|
+
const mayForwardCallerCredentials = isCanonicalOpenAiForwardProvider(provider);
|
|
1646
|
+
// OAuth passthrough: ChatGPT backend path is `${baseUrl}/responses` (no /v1).
|
|
1647
|
+
const baseUrl = mayForwardCallerCredentials
|
|
1648
|
+
? CODEX_FORWARD_BASE_URL
|
|
1649
|
+
: provider.baseUrl.replace(/\/+$/, "");
|
|
1650
|
+
url = `${baseUrl}/responses`;
|
|
1651
|
+
if (provider.headers) Object.assign(headers, provider.headers); // static headers first…
|
|
1652
|
+
const runtimeProvider = provider as {
|
|
1653
|
+
_codexAccountOverride?: { accessToken: string; chatgptAccountId: string };
|
|
1654
|
+
_codexAccountRequired?: boolean;
|
|
1655
|
+
};
|
|
1656
|
+
if (
|
|
1657
|
+
mayForwardCallerCredentials
|
|
1658
|
+
&& runtimeProvider._codexAccountRequired
|
|
1659
|
+
&& !runtimeProvider._codexAccountOverride
|
|
1660
|
+
) {
|
|
1661
|
+
throw new Error("Codex pool account auth is required but unavailable");
|
|
1662
|
+
}
|
|
1663
|
+
if (mayForwardCallerCredentials) {
|
|
1664
|
+
for (const h of FORWARD_HEADERS) {
|
|
1665
|
+
const v = incoming?.headers.get(h);
|
|
1666
|
+
if (v) headers[h] = v; // …so forwarded auth always wins.
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
const override = runtimeProvider._codexAccountOverride;
|
|
1670
|
+
if (override && mayForwardCallerCredentials) {
|
|
1671
|
+
headers["authorization"] = `Bearer ${override.accessToken}`;
|
|
1672
|
+
headers["chatgpt-account-id"] = override.chatgptAccountId;
|
|
1673
|
+
}
|
|
1674
|
+
} else {
|
|
1675
|
+
if (provider.responsesPath === undefined) {
|
|
1676
|
+
url = openaiResponsesUrl(provider.baseUrl);
|
|
1677
|
+
} else {
|
|
1678
|
+
const base = provider.baseUrl.replace(/\/$/, "");
|
|
1679
|
+
url = `${base}${provider.responsesPath}`;
|
|
1680
|
+
}
|
|
1681
|
+
if (provider.apiKey) headers["Authorization"] = `Bearer ${provider.apiKey}`;
|
|
1682
|
+
if (provider.headers) Object.assign(headers, provider.headers);
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
const forward = provider.authMode === "forward";
|
|
1686
|
+
let convertedRoutedCustomToolNames: Set<string> | undefined;
|
|
1687
|
+
let convertedRoutedToolSearchNames: Set<string> | undefined;
|
|
1688
|
+
let convertedRoutedNamespaceToolAliases: Map<string, { namespace: string; name: string }> | undefined;
|
|
1689
|
+
const unexpandedMiss = !!parsed.previousResponseId && parsed._previousResponseInputExpanded !== true;
|
|
1690
|
+
let outBody = stripPreviousResponseId(
|
|
1691
|
+
parsed._rawBody,
|
|
1692
|
+
forward || parsed._previousResponseInputExpanded === true,
|
|
1693
|
+
);
|
|
1694
|
+
// stripPreviousResponseId() intentionally returns its input on a no-op. Detach before the
|
|
1695
|
+
// tier write so a force-fast/default decision can never mutate parsed._rawBody.
|
|
1696
|
+
outBody = applyTierDecisionToResponsesBody(outBody, parsed.options?.tierDecision);
|
|
1697
|
+
const stateless = provider.statelessResponses === true;
|
|
1698
|
+
if (stateless) outBody = stripStatefulResponsesParams(outBody);
|
|
1699
|
+
// A replay miss can leave a function_call_output whose paired function_call sat
|
|
1700
|
+
// in the prefix that was never expanded. A stateless upstream cannot resolve the
|
|
1701
|
+
// pair from its own storage either, so it needs the same repair the forward
|
|
1702
|
+
// backend gets — dropping previous_response_id is not much use if the body that
|
|
1703
|
+
// reaches the wire is unparseable.
|
|
1704
|
+
if (forward || stateless) {
|
|
1705
|
+
outBody = repairOrphanedInputItems(outBody, unexpandedMiss, stateless && !forward);
|
|
1706
|
+
}
|
|
1707
|
+
if (provider.requiresAdjacentResponsesToolResults === true) {
|
|
1708
|
+
outBody = normalizeResponsesToolResultAdjacency(outBody);
|
|
1709
|
+
}
|
|
1710
|
+
if (forward) {
|
|
1711
|
+
outBody = stripUnsupportedForwardParams(outBody);
|
|
1712
|
+
// Only the canonical ChatGPT backend rejects the retired field; a self-hosted or
|
|
1713
|
+
// third-party forward gateway may still accept it, so this must not be widened.
|
|
1714
|
+
if (isCanonicalOpenAiForwardProvider(provider)) {
|
|
1715
|
+
outBody = stripDeprecatedPromptCacheRetention(outBody, parsed.modelId);
|
|
1716
|
+
}
|
|
1717
|
+
} else {
|
|
1718
|
+
outBody = preferConfiguredHostedTools(
|
|
1719
|
+
outBody,
|
|
1720
|
+
provider,
|
|
1721
|
+
parsed.modelId,
|
|
1722
|
+
parsed._openAiVirtualSelectedModelId,
|
|
1723
|
+
);
|
|
1724
|
+
outBody = normalizeImageGenClientTools(outBody);
|
|
1725
|
+
}
|
|
1726
|
+
if (forward || parsed._previousResponseInputExpanded === true) {
|
|
1727
|
+
outBody = repairOversizedReplayCallIds(outBody);
|
|
1728
|
+
}
|
|
1729
|
+
outBody = stripUnsupportedReasoningSummaryDelivery(outBody, parsed.modelId);
|
|
1730
|
+
// Repair stored history from before the bridge emitted both keys: a conversation
|
|
1731
|
+
// that already recorded a single-query web_search_call replays it every turn, and
|
|
1732
|
+
// a strict parser rejects the whole request over it (#930).
|
|
1733
|
+
outBody = backfillWebSearchQueries(outBody);
|
|
1734
|
+
if (!isCanonicalOpenAiForwardProvider(provider)) {
|
|
1735
|
+
outBody = promoteClientLoadedTools(outBody);
|
|
1736
|
+
}
|
|
1737
|
+
if (!isCanonicalOpenAiForwardProvider(provider)) {
|
|
1738
|
+
const rewritten = rewriteRoutedCustomToolsForUpstream(
|
|
1739
|
+
outBody,
|
|
1740
|
+
provider.supportsResponsesCustomTools,
|
|
1741
|
+
);
|
|
1742
|
+
outBody = rewritten.body;
|
|
1743
|
+
convertedRoutedCustomToolNames = rewritten.names;
|
|
1744
|
+
}
|
|
1745
|
+
if (!isCanonicalOpenAiForwardProvider(provider)) {
|
|
1746
|
+
// Run after custom-tool lowering so the search compatibility layer can choose a
|
|
1747
|
+
// collision-free public function name against the final routed function catalog.
|
|
1748
|
+
const rewritten = rewriteRoutedToolSearchForUpstream(outBody);
|
|
1749
|
+
outBody = rewritten.body;
|
|
1750
|
+
convertedRoutedToolSearchNames = rewritten.names;
|
|
1751
|
+
}
|
|
1752
|
+
if (!isCanonicalOpenAiForwardProvider(provider)) {
|
|
1753
|
+
// Codex 0.147 emits private namespace tool groups, while public/third-party Responses
|
|
1754
|
+
// gateways accept only flat tool variants. Run after custom/tool-search lowering so
|
|
1755
|
+
// namespace children already carry their final public kind before they are promoted.
|
|
1756
|
+
const rewritten = rewriteRoutedNamespaceToolsForUpstream(outBody);
|
|
1757
|
+
outBody = rewritten.body;
|
|
1758
|
+
convertedRoutedNamespaceToolAliases = rewritten.aliases;
|
|
1759
|
+
// Preserve xAI's cached-only fail-closed semantics and image-search mapping before the
|
|
1760
|
+
// generic capability fallback removes the private OpenAI fields.
|
|
1761
|
+
outBody = normalizeXaiResponsesWebSearch(outBody, provider);
|
|
1762
|
+
// xAI and explicitly classified compatible gateways reject these OpenAI web_search
|
|
1763
|
+
// extensions. Keep them for OpenAI API-key traffic and unclassified gateways.
|
|
1764
|
+
if (provider.supportsOpenAiWebSearchToolFields === false) {
|
|
1765
|
+
outBody = stripOpenAiOnlyWebSearchFields(outBody);
|
|
1766
|
+
}
|
|
1767
|
+
// Last, so promoted namespace children are also cleared of Codex-private fields.
|
|
1768
|
+
outBody = stripCanonicalOnlyToolFields(outBody, provider.supportsOpenAiWebSearchToolFields === false);
|
|
1769
|
+
}
|
|
1770
|
+
// Same predicate as the routedCompaction gate in handleResponses(): an authMode check would
|
|
1771
|
+
// let a noncanonical custom forward provider skip this rewrite while the server still routes
|
|
1772
|
+
// it as a summarizer turn (#422). The compaction body build removes the tool surface and must
|
|
1773
|
+
// therefore be the last routed transform: anything before it may depend on the declarations;
|
|
1774
|
+
// anything after it cannot.
|
|
1775
|
+
if (parsed._compactionRequest === true && !isCanonicalOpenAiForwardProvider(provider)) {
|
|
1776
|
+
outBody = buildRoutedCompactionBody(outBody);
|
|
1777
|
+
}
|
|
1778
|
+
const threadServingIdentityChanged = parsed._stripReasoningEncryptedContent === true;
|
|
1779
|
+
const sanitizedBody = normalizeToolSchemas(stripSparkCompatibility(stripUnsupportedReasoningParams(stripItemIdsWhenUnstored(stripInvalidItemIds(stripUnsupportedHostedTools(sanitizeReasoningInputContent(scrubOcxCompactionItems(
|
|
1780
|
+
outBody,
|
|
1781
|
+
destinationDecodesNativeCompactionBlob(provider),
|
|
1782
|
+
threadServingIdentityChanged,
|
|
1783
|
+
), {
|
|
1784
|
+
preserveRawReasoningContent: provider.preserveResponsesReasoningContent === true,
|
|
1785
|
+
dropNullContentChannel: !isOpenAiOperatedResponsesDestination(provider),
|
|
1786
|
+
stripEncryptedContent: threadServingIdentityChanged,
|
|
1787
|
+
})))))));
|
|
1788
|
+
const finalBody = stripDisabledReasoningSummaries(
|
|
1789
|
+
normalizeConfiguredReasoningSummaryDelivery(sanitizedBody, provider, parsed.modelId),
|
|
1790
|
+
provider,
|
|
1791
|
+
parsed.modelId,
|
|
1792
|
+
);
|
|
1793
|
+
const actualServiceTier = isPlainObject(finalBody) && typeof finalBody.service_tier === "string"
|
|
1794
|
+
? finalBody.service_tier
|
|
1795
|
+
: null;
|
|
1796
|
+
const tierLog = createAdapterTierMetadata(
|
|
1797
|
+
parsed.options?.tierObservation,
|
|
1798
|
+
parsed.options?.tierDecision,
|
|
1799
|
+
actualServiceTier === null ? null : "service-tier",
|
|
1800
|
+
actualServiceTier,
|
|
1801
|
+
);
|
|
1802
|
+
const body = JSON.stringify(finalBody);
|
|
1803
|
+
const releaseBodyObservation = translatorBudget.observeExternallyCapped(
|
|
1804
|
+
"passthrough_serialization",
|
|
1805
|
+
new TextEncoder().encode(body).byteLength,
|
|
1806
|
+
);
|
|
1807
|
+
return {
|
|
1808
|
+
url,
|
|
1809
|
+
method: "POST",
|
|
1810
|
+
headers,
|
|
1811
|
+
body,
|
|
1812
|
+
releaseBodyObservation,
|
|
1813
|
+
...(convertedRoutedCustomToolNames ? { convertedRoutedCustomToolNames } : {}),
|
|
1814
|
+
...(convertedRoutedToolSearchNames ? { convertedRoutedToolSearchNames } : {}),
|
|
1815
|
+
...(convertedRoutedNamespaceToolAliases ? { convertedRoutedNamespaceToolAliases } : {}),
|
|
1816
|
+
...(tierLog ? { tierLog } : {}),
|
|
1817
|
+
};
|
|
1818
|
+
},
|
|
1819
|
+
|
|
1820
|
+
// The passthrough normally relays the upstream stream verbatim and never parses.
|
|
1821
|
+
// The exception is a routed compaction turn: the server drives this adapter like
|
|
1822
|
+
// an ordinary one so the bridge can build the single compaction item (#422).
|
|
1823
|
+
async *parseStream(response: Response, budget: TranslatorBudget): AsyncGenerator<AdapterEvent> {
|
|
1824
|
+
if (!response.body) {
|
|
1825
|
+
yield { type: "error", message: "passthrough adapter received no response body" };
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
const budgetEncoder = new TextEncoder();
|
|
1829
|
+
let deltas = "";
|
|
1830
|
+
let doneText = "";
|
|
1831
|
+
let snapshot = "";
|
|
1832
|
+
let usage: OcxUsage | undefined;
|
|
1833
|
+
for await (const event of decodeServerSentEvents(response.body, { translatorBudget: budget })) {
|
|
1834
|
+
let payload: unknown;
|
|
1835
|
+
try { payload = JSON.parse(event.data); } catch { continue; }
|
|
1836
|
+
if (!isPlainObject(payload)) continue;
|
|
1837
|
+
switch (payload.type) {
|
|
1838
|
+
case "response.output_text.delta":
|
|
1839
|
+
if (typeof payload.delta === "string") {
|
|
1840
|
+
const next = deltas + payload.delta;
|
|
1841
|
+
const previousBytes = budgetEncoder.encode(deltas).byteLength;
|
|
1842
|
+
const reservation = budget.reserveTransient(budgetEncoder.encode(next).byteLength, { kind: "retained_collectors" });
|
|
1843
|
+
deltas = next;
|
|
1844
|
+
reservation.commitRetained();
|
|
1845
|
+
budget.releaseRetained(previousBytes, { kind: "retained_collectors" });
|
|
1846
|
+
}
|
|
1847
|
+
break;
|
|
1848
|
+
case "response.output_text.done":
|
|
1849
|
+
if (typeof payload.text === "string") {
|
|
1850
|
+
const next = doneText + payload.text;
|
|
1851
|
+
const previousBytes = budgetEncoder.encode(doneText).byteLength;
|
|
1852
|
+
const reservation = budget.reserveTransient(budgetEncoder.encode(next).byteLength, { kind: "retained_collectors" });
|
|
1853
|
+
doneText = next;
|
|
1854
|
+
reservation.commitRetained();
|
|
1855
|
+
budget.releaseRetained(previousBytes, { kind: "retained_collectors" });
|
|
1856
|
+
}
|
|
1857
|
+
break;
|
|
1858
|
+
case "response.failed":
|
|
1859
|
+
case "error":
|
|
1860
|
+
yield { type: "error", message: responsesErrorMessage(payload.response ?? payload) };
|
|
1861
|
+
return;
|
|
1862
|
+
case "response.incomplete":
|
|
1863
|
+
yield { type: "incomplete", reason: responsesErrorMessage(payload.response ?? payload) };
|
|
1864
|
+
return;
|
|
1865
|
+
case "response.completed":
|
|
1866
|
+
{
|
|
1867
|
+
const next = responsesPayloadText(payload.response);
|
|
1868
|
+
const previousBytes = budgetEncoder.encode(snapshot).byteLength;
|
|
1869
|
+
const reservation = budget.reserveTransient(budgetEncoder.encode(next).byteLength, { kind: "retained_collectors" });
|
|
1870
|
+
snapshot = next;
|
|
1871
|
+
reservation.commitRetained();
|
|
1872
|
+
budget.releaseRetained(previousBytes, { kind: "retained_collectors" });
|
|
1873
|
+
}
|
|
1874
|
+
usage = usageFromResponsesPayload(payload.response);
|
|
1875
|
+
break;
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
// Gateways differ in which of these they emit; prefer the authoritative
|
|
1879
|
+
// completed snapshot so text is never double-counted.
|
|
1880
|
+
const text = snapshot || doneText || deltas;
|
|
1881
|
+
if (text) yield { type: "text_delta", text };
|
|
1882
|
+
budget.releaseRetained(budgetEncoder.encode(deltas).byteLength + budgetEncoder.encode(doneText).byteLength + budgetEncoder.encode(snapshot).byteLength, { kind: "retained_collectors" });
|
|
1883
|
+
yield { type: "done", ...(usage ? { usage } : {}) };
|
|
1884
|
+
},
|
|
1885
|
+
|
|
1886
|
+
async parseResponse(response: Response, budget: TranslatorBudget): Promise<AdapterEvent[]> {
|
|
1887
|
+
let payload: unknown;
|
|
1888
|
+
try { payload = await response.json(); } catch {
|
|
1889
|
+
return [{ type: "error", message: "malformed upstream compaction response" }];
|
|
1890
|
+
}
|
|
1891
|
+
budget.chargeRetained(new TextEncoder().encode(JSON.stringify(payload)).byteLength, { kind: "retained_collectors" });
|
|
1892
|
+
if (!isPlainObject(payload)) {
|
|
1893
|
+
return [{ type: "error", message: "malformed upstream compaction response" }];
|
|
1894
|
+
}
|
|
1895
|
+
if (payload.error || payload.status === "failed") {
|
|
1896
|
+
return [{ type: "error", message: responsesErrorMessage(payload) }];
|
|
1897
|
+
}
|
|
1898
|
+
if (payload.status === "incomplete") {
|
|
1899
|
+
return [{ type: "incomplete", reason: responsesErrorMessage(payload) }];
|
|
1900
|
+
}
|
|
1901
|
+
const text = responsesPayloadText(payload);
|
|
1902
|
+
if (!text) {
|
|
1903
|
+
// A completed turn with no usable text cannot become a summary; saying so is
|
|
1904
|
+
// better than installing an empty compaction as replacement history.
|
|
1905
|
+
return [{ type: "error", message: "upstream compaction returned no summary text" }];
|
|
1906
|
+
}
|
|
1907
|
+
const usage = usageFromResponsesPayload(payload);
|
|
1908
|
+
return [{ type: "text_delta", text }, { type: "done", ...(usage ? { usage } : {}) }];
|
|
1909
|
+
},
|
|
1910
|
+
};
|
|
1911
|
+
}
|