@iislee/opencodex 2.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +225 -0
- package/assets/architecture.png +0 -0
- package/assets/banner.png +0 -0
- package/assets/claude-code-models.gif +0 -0
- package/assets/codex-app-picker.png +0 -0
- package/bin/ocx.mjs +451 -0
- package/bin/package-main.mjs +9 -0
- package/gui/dist/assets/index-DTpMHS4F.js +67 -0
- package/gui/dist/assets/index-ZNVDE3C7.css +1 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/icons.svg +24 -0
- package/gui/dist/index.html +25 -0
- package/gui/dist/logo.png +0 -0
- package/gui/dist/provider-icons/alibaba-color.svg +1 -0
- package/gui/dist/provider-icons/antigravity-color.svg +1 -0
- package/gui/dist/provider-icons/antigravity.svg +1 -0
- package/gui/dist/provider-icons/claude-color.svg +1 -0
- package/gui/dist/provider-icons/claude.svg +1 -0
- package/gui/dist/provider-icons/cloudflare-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/copilot-color.svg +1 -0
- package/gui/dist/provider-icons/copilot.svg +1 -0
- package/gui/dist/provider-icons/cursor-color.svg +2 -0
- package/gui/dist/provider-icons/cursor.svg +2 -0
- package/gui/dist/provider-icons/deepseek-color.svg +1 -0
- package/gui/dist/provider-icons/discord.svg +1 -0
- package/gui/dist/provider-icons/firepass-color.svg +1 -0
- package/gui/dist/provider-icons/fireworks-color.svg +1 -0
- package/gui/dist/provider-icons/gemini-color.svg +1 -0
- package/gui/dist/provider-icons/gemini.svg +1 -0
- package/gui/dist/provider-icons/github-copilot-color.svg +1 -0
- package/gui/dist/provider-icons/gitlab-duo-color.svg +1 -0
- package/gui/dist/provider-icons/grok-color.svg +1 -0
- package/gui/dist/provider-icons/grok.svg +1 -0
- package/gui/dist/provider-icons/groq-color.svg +1 -0
- package/gui/dist/provider-icons/huggingface-color.svg +1 -0
- package/gui/dist/provider-icons/kimi-color.svg +1 -0
- package/gui/dist/provider-icons/kiro-color.svg +15 -0
- package/gui/dist/provider-icons/kiro.svg +14 -0
- package/gui/dist/provider-icons/lm-studio-color.svg +1 -0
- package/gui/dist/provider-icons/mistral-color.svg +1 -0
- package/gui/dist/provider-icons/moonshot-color.svg +1 -0
- package/gui/dist/provider-icons/nvidia-color.svg +1 -0
- package/gui/dist/provider-icons/ollama-color.svg +1 -0
- package/gui/dist/provider-icons/openai.svg +1 -0
- package/gui/dist/provider-icons/opencode.svg +1 -0
- package/gui/dist/provider-icons/openrouter-color.svg +1 -0
- package/gui/dist/provider-icons/pi.svg +21 -0
- package/gui/dist/provider-icons/qianfan-color.svg +1 -0
- package/gui/dist/provider-icons/qwen-portal-color.svg +1 -0
- package/gui/dist/provider-icons/telegram.svg +1 -0
- package/gui/dist/provider-icons/vercel-ai-gateway-color.svg +1 -0
- package/gui/dist/provider-icons/vllm-color.svg +1 -0
- package/gui/dist/provider-icons/xiaomi-color.svg +1 -0
- package/package.json +102 -0
- package/src/AGENTS.md +28 -0
- package/src/adapters/anthropic-image-guard.ts +251 -0
- package/src/adapters/anthropic-image-normalize.ts +518 -0
- package/src/adapters/anthropic.ts +1003 -0
- package/src/adapters/azure.ts +36 -0
- package/src/adapters/base.ts +72 -0
- package/src/adapters/client-fingerprint.ts +59 -0
- package/src/adapters/cursor/arg-codec.ts +38 -0
- package/src/adapters/cursor/arg-normalize.ts +104 -0
- package/src/adapters/cursor/cursor-errors.ts +165 -0
- package/src/adapters/cursor/discovery.ts +276 -0
- package/src/adapters/cursor/effort-map.ts +127 -0
- package/src/adapters/cursor/exec-policy.ts +88 -0
- package/src/adapters/cursor/framing.ts +211 -0
- package/src/adapters/cursor/gen/agent_pb.ts +15274 -0
- package/src/adapters/cursor/kv-store.ts +52 -0
- package/src/adapters/cursor/live-models.ts +153 -0
- package/src/adapters/cursor/live-smoke-gate.ts +41 -0
- package/src/adapters/cursor/live-transport.ts +1214 -0
- package/src/adapters/cursor/mcp-config.ts +42 -0
- package/src/adapters/cursor/mcp-manager.ts +333 -0
- package/src/adapters/cursor/message-mapper.ts +49 -0
- package/src/adapters/cursor/native-exec-common.ts +55 -0
- package/src/adapters/cursor/native-exec-desktop.ts +184 -0
- package/src/adapters/cursor/native-exec-fs.ts +329 -0
- package/src/adapters/cursor/native-exec-mcp.ts +153 -0
- package/src/adapters/cursor/native-exec-network.ts +43 -0
- package/src/adapters/cursor/native-exec-shell.ts +548 -0
- package/src/adapters/cursor/native-exec-tools.ts +118 -0
- package/src/adapters/cursor/native-exec.ts +576 -0
- package/src/adapters/cursor/protobuf-events.ts +563 -0
- package/src/adapters/cursor/protobuf-request.ts +714 -0
- package/src/adapters/cursor/request-builder.ts +255 -0
- package/src/adapters/cursor/thread-continuity.ts +67 -0
- package/src/adapters/cursor/tool-definitions.ts +505 -0
- package/src/adapters/cursor/transport-retry.ts +132 -0
- package/src/adapters/cursor/transport.ts +57 -0
- package/src/adapters/cursor/types.ts +52 -0
- package/src/adapters/cursor.ts +196 -0
- package/src/adapters/google-antigravity-replay.ts +303 -0
- package/src/adapters/google-antigravity-wire.ts +108 -0
- package/src/adapters/google-errors.ts +85 -0
- package/src/adapters/google-http.ts +100 -0
- package/src/adapters/google-tool-schema.ts +173 -0
- package/src/adapters/google-truncation.ts +13 -0
- package/src/adapters/google-wire-compiler.ts +232 -0
- package/src/adapters/google.ts +758 -0
- package/src/adapters/identity.ts +44 -0
- package/src/adapters/image.ts +23 -0
- package/src/adapters/kiro-constants.ts +16 -0
- package/src/adapters/kiro-errors.ts +197 -0
- package/src/adapters/kiro-events.ts +179 -0
- package/src/adapters/kiro-images.ts +129 -0
- package/src/adapters/kiro-retry.ts +312 -0
- package/src/adapters/kiro-thinking.ts +96 -0
- package/src/adapters/kiro-tool-fallback.ts +36 -0
- package/src/adapters/kiro-tools.ts +215 -0
- package/src/adapters/kiro-truncation.ts +33 -0
- package/src/adapters/kiro-wire.ts +129 -0
- package/src/adapters/kiro.ts +1898 -0
- package/src/adapters/mimo-free.ts +263 -0
- package/src/adapters/openai-chat.ts +1005 -0
- package/src/adapters/openai-responses.ts +1137 -0
- package/src/adapters/run-turn-queue.ts +114 -0
- package/src/adapters/tool-catalog-nudge.ts +71 -0
- package/src/adapters/upstream-http-error.ts +48 -0
- package/src/bridge.ts +1619 -0
- package/src/chat/inbound.ts +295 -0
- package/src/chat/outbound.ts +765 -0
- package/src/claude/agents-inject.ts +243 -0
- package/src/claude/alias.ts +149 -0
- package/src/claude/auth-detect.ts +229 -0
- package/src/claude/auth-mode-migration.ts +32 -0
- package/src/claude/auth-mode.ts +62 -0
- package/src/claude/context-windows.ts +189 -0
- package/src/claude/desktop-3p-guard.ts +35 -0
- package/src/claude/desktop-3p-paths.ts +84 -0
- package/src/claude/desktop-3p.ts +381 -0
- package/src/claude/desktop-health.ts +26 -0
- package/src/claude/desktop-profile.ts +263 -0
- package/src/claude/gateway-cache.ts +70 -0
- package/src/claude/inbound-debug.ts +163 -0
- package/src/claude/inbound.ts +509 -0
- package/src/claude/model-info.ts +151 -0
- package/src/claude/outbound.ts +872 -0
- package/src/cli/access.ts +108 -0
- package/src/cli/account-api.ts +268 -0
- package/src/cli/account-auth.ts +223 -0
- package/src/cli/account-extended.ts +350 -0
- package/src/cli/account.ts +275 -0
- package/src/cli/agent-driven.ts +70 -0
- package/src/cli/agent.ts +184 -0
- package/src/cli/catalog-prewarm.ts +27 -0
- package/src/cli/claude-desktop.ts +188 -0
- package/src/cli/claude.ts +286 -0
- package/src/cli/codex-shim-autorestore.ts +45 -0
- package/src/cli/combo.ts +119 -0
- package/src/cli/config-command.ts +145 -0
- package/src/cli/debug.ts +228 -0
- package/src/cli/doctor.ts +930 -0
- package/src/cli/export-command.ts +187 -0
- package/src/cli/help.ts +354 -0
- package/src/cli/index.ts +1113 -0
- package/src/cli/init.ts +224 -0
- package/src/cli/integrations.ts +142 -0
- package/src/cli/interactive-confirm.ts +133 -0
- package/src/cli/internal-dispatch.ts +20 -0
- package/src/cli/models-runtime.ts +212 -0
- package/src/cli/models.ts +336 -0
- package/src/cli/observe.ts +117 -0
- package/src/cli/opencode.ts +586 -0
- package/src/cli/pi.ts +188 -0
- package/src/cli/provider-runtime.ts +162 -0
- package/src/cli/provider.ts +463 -0
- package/src/cli/runtime-api.ts +325 -0
- package/src/cli/star-prompt.ts +155 -0
- package/src/cli/status-oauth.ts +78 -0
- package/src/cli/status.ts +321 -0
- package/src/cli/sync-cloud.ts +283 -0
- package/src/cli/system-command.ts +112 -0
- package/src/cli/tray-proxy.ts +52 -0
- package/src/cli/v2.ts +173 -0
- package/src/cli.ts +10 -0
- package/src/clients/config-export.ts +377 -0
- package/src/clients/effective-status.ts +385 -0
- package/src/clients/probes/agy.ts +55 -0
- package/src/clients/probes/cc-switch.ts +110 -0
- package/src/clients/probes/claude.ts +90 -0
- package/src/clients/probes/codex.ts +125 -0
- package/src/clients/probes/grok.ts +29 -0
- package/src/clients/probes/opencode.ts +109 -0
- package/src/clients/probes/paseo.ts +55 -0
- package/src/clients/probes/pi.ts +55 -0
- package/src/cloud/onedrive-auth.ts +666 -0
- package/src/cloud/onedrive-graph.ts +108 -0
- package/src/cloud/settings.ts +75 -0
- package/src/cloud/sync.ts +212 -0
- package/src/cloud/types.ts +56 -0
- package/src/cloud/vault.ts +89 -0
- package/src/codex/account-id.ts +34 -0
- package/src/codex/account-label.ts +34 -0
- package/src/codex/account-lifecycle.ts +55 -0
- package/src/codex/account-namespace-match.ts +63 -0
- package/src/codex/account-namespaces.ts +149 -0
- package/src/codex/account-pause.ts +20 -0
- package/src/codex/account-runtime-state.ts +31 -0
- package/src/codex/account-store.ts +517 -0
- package/src/codex/account-usability.ts +20 -0
- package/src/codex/app-server-processes.ts +756 -0
- package/src/codex/auth-api.ts +1540 -0
- package/src/codex/auth-collision.ts +107 -0
- package/src/codex/auth-context.ts +352 -0
- package/src/codex/autostart-health.ts +149 -0
- package/src/codex/catalog/aggregation.ts +378 -0
- package/src/codex/catalog/bundled.ts +251 -0
- package/src/codex/catalog/effort.ts +355 -0
- package/src/codex/catalog/metadata.ts +180 -0
- package/src/codex/catalog/parsing.ts +456 -0
- package/src/codex/catalog/provider-fetch.ts +902 -0
- package/src/codex/catalog/sync.ts +620 -0
- package/src/codex/catalog.ts +12 -0
- package/src/codex/data/upstream-models.json +830 -0
- package/src/codex/exec-invocation.ts +22 -0
- package/src/codex/features.ts +969 -0
- package/src/codex/history-migration-guardian.ts +102 -0
- package/src/codex/history-provider.ts +776 -0
- package/src/codex/home.ts +206 -0
- package/src/codex/inject.ts +799 -0
- package/src/codex/injected-marker.ts +72 -0
- package/src/codex/journal.ts +163 -0
- package/src/codex/main-account-cache.ts +32 -0
- package/src/codex/main-account.ts +40 -0
- package/src/codex/model-cache.ts +227 -0
- package/src/codex/paths.ts +65 -0
- package/src/codex/plugins-doctor.ts +242 -0
- package/src/codex/pool-rotation.ts +225 -0
- package/src/codex/project-config-warnings.ts +411 -0
- package/src/codex/quota.ts +411 -0
- package/src/codex/refresh.ts +53 -0
- package/src/codex/routing.ts +1477 -0
- package/src/codex/runtime.ts +538 -0
- package/src/codex/shim.ts +1189 -0
- package/src/codex/subagent-defaults.ts +550 -0
- package/src/codex/subagent-model-fallback.ts +469 -0
- package/src/codex/sync.ts +130 -0
- package/src/codex/warmup.ts +192 -0
- package/src/codex/websocket-registry.ts +100 -0
- package/src/combos/failover.ts +140 -0
- package/src/combos/index.ts +41 -0
- package/src/combos/request.ts +62 -0
- package/src/combos/resolve.ts +232 -0
- package/src/combos/types.ts +326 -0
- package/src/config.ts +2356 -0
- package/src/generated/jawcode-model-metadata.ts +104 -0
- package/src/github/star-state.ts +203 -0
- package/src/grok/inject.ts +545 -0
- package/src/grok/status.ts +121 -0
- package/src/grok/sync.ts +103 -0
- package/src/grok/usage-hook/report.mjs +348 -0
- package/src/grok/usage-hook.ts +278 -0
- package/src/images/artifacts.ts +516 -0
- package/src/images/fulfill-video.ts +163 -0
- package/src/images/fulfill.ts +149 -0
- package/src/images/index.ts +4 -0
- package/src/images/loop.ts +829 -0
- package/src/images/plan.ts +133 -0
- package/src/images/synthetic-tool.ts +133 -0
- package/src/images/types.ts +41 -0
- package/src/images/xai-client.ts +141 -0
- package/src/images/xai-video-client.ts +163 -0
- package/src/index.ts +22 -0
- package/src/lib/abort.ts +146 -0
- package/src/lib/admin-secrets.ts +25 -0
- package/src/lib/admission.ts +83 -0
- package/src/lib/app-owned-memory-stores.ts +173 -0
- package/src/lib/app-owned-memory.ts +265 -0
- package/src/lib/bounded-body.ts +202 -0
- package/src/lib/bun-binary-validator.d.mts +3 -0
- package/src/lib/bun-binary-validator.mjs +18 -0
- package/src/lib/bun-runtime.ts +71 -0
- package/src/lib/bun-stream-caps.ts +126 -0
- package/src/lib/config-ownership.ts +360 -0
- package/src/lib/crash-guard.ts +344 -0
- package/src/lib/debug-log-buffer.ts +83 -0
- package/src/lib/debug-settings.ts +108 -0
- package/src/lib/debug.ts +31 -0
- package/src/lib/destination-policy.ts +316 -0
- package/src/lib/errors.ts +364 -0
- package/src/lib/eventstream-decoder.ts +253 -0
- package/src/lib/gcp-adc.ts +341 -0
- package/src/lib/injection-debug-log.ts +58 -0
- package/src/lib/open-url.ts +25 -0
- package/src/lib/pinned-http.ts +151 -0
- package/src/lib/privacy.ts +20 -0
- package/src/lib/process-control.ts +165 -0
- package/src/lib/provider-outbound.ts +170 -0
- package/src/lib/provider-url.ts +14 -0
- package/src/lib/proxy-env.ts +18 -0
- package/src/lib/redact.ts +105 -0
- package/src/lib/retry-after.ts +55 -0
- package/src/lib/service-secrets.ts +25 -0
- package/src/lib/shadow-call.ts +30 -0
- package/src/lib/sidecar-tracker.ts +52 -0
- package/src/lib/sse-decoder.ts +323 -0
- package/src/lib/state-store-registrations.ts +109 -0
- package/src/lib/state-store-sweeper.ts +184 -0
- package/src/lib/test-home-guard.ts +90 -0
- package/src/lib/token-estimate.ts +69 -0
- package/src/lib/translator-budget.ts +356 -0
- package/src/lib/upstream-retry.ts +239 -0
- package/src/lib/win-exec.ts +115 -0
- package/src/lib/win-paths.ts +68 -0
- package/src/lib/windows-elevation.ts +705 -0
- package/src/lib/windows-secret-acl.ts +514 -0
- package/src/lib/winsw.ts +375 -0
- package/src/oauth/anthropic-routing.ts +594 -0
- package/src/oauth/anthropic.ts +177 -0
- package/src/oauth/callback-server.ts +294 -0
- package/src/oauth/chatgpt.ts +150 -0
- package/src/oauth/cursor.ts +211 -0
- package/src/oauth/github-copilot.ts +428 -0
- package/src/oauth/google-antigravity.ts +230 -0
- package/src/oauth/health.ts +399 -0
- package/src/oauth/index.ts +1174 -0
- package/src/oauth/key-providers.ts +108 -0
- package/src/oauth/kimi.ts +213 -0
- package/src/oauth/kiro-credentials.ts +726 -0
- package/src/oauth/kiro.ts +577 -0
- package/src/oauth/local-token-detect.ts +121 -0
- package/src/oauth/log.ts +48 -0
- package/src/oauth/login-cli.ts +163 -0
- package/src/oauth/pkce.ts +15 -0
- package/src/oauth/store.ts +630 -0
- package/src/oauth/token-guardian.ts +303 -0
- package/src/oauth/types.ts +62 -0
- package/src/oauth/xai.ts +241 -0
- package/src/pi/extensions.ts +72 -0
- package/src/pi/home.ts +42 -0
- package/src/pi/index.ts +40 -0
- package/src/pi/models.ts +278 -0
- package/src/pi/packages.ts +219 -0
- package/src/pi/settings.ts +365 -0
- package/src/pi/status.ts +68 -0
- package/src/pi/sync.ts +75 -0
- package/src/providers/alibaba-region-backup.ts +75 -0
- package/src/providers/alibaba-region-migration.ts +156 -0
- package/src/providers/alibaba-region-startup.ts +36 -0
- package/src/providers/antigravity-models.ts +205 -0
- package/src/providers/api-keys.ts +140 -0
- package/src/providers/base-url-choices.ts +64 -0
- package/src/providers/context-cap.ts +65 -0
- package/src/providers/derive.ts +339 -0
- package/src/providers/free-directory.ts +184 -0
- package/src/providers/github-copilot-transport.ts +56 -0
- package/src/providers/key-failover.ts +203 -0
- package/src/providers/kiro-models.ts +67 -0
- package/src/providers/label.ts +19 -0
- package/src/providers/model-discovery.ts +356 -0
- package/src/providers/openai-sidecar.ts +175 -0
- package/src/providers/openai-tier-startup.ts +27 -0
- package/src/providers/openai-tiers.ts +301 -0
- package/src/providers/openai-virtual-models.ts +82 -0
- package/src/providers/openrouter-routing.ts +102 -0
- package/src/providers/provider-id-rewrite.ts +150 -0
- package/src/providers/quota.ts +1260 -0
- package/src/providers/registry.ts +1600 -0
- package/src/providers/slug-codec.ts +67 -0
- package/src/providers/xai-transport.ts +141 -0
- package/src/reasoning-effort.ts +135 -0
- package/src/responses/compaction.ts +117 -0
- package/src/responses/parser.ts +656 -0
- package/src/responses/reasoning-envelope.ts +52 -0
- package/src/responses/schema.ts +159 -0
- package/src/responses/spill-store.ts +394 -0
- package/src/responses/state.ts +895 -0
- package/src/responses/tool-groups.ts +19 -0
- package/src/router.ts +425 -0
- package/src/server/adapter-resolve.ts +80 -0
- package/src/server/auth-cors.ts +530 -0
- package/src/server/chat-completions.ts +368 -0
- package/src/server/claude-messages.ts +914 -0
- package/src/server/effort-policy.ts +172 -0
- package/src/server/gui-static.ts +123 -0
- package/src/server/image-retry.ts +42 -0
- package/src/server/images.ts +476 -0
- package/src/server/index.ts +1126 -0
- package/src/server/lifecycle.ts +227 -0
- package/src/server/live.ts +598 -0
- package/src/server/management/agent-settings-routes.ts +1169 -0
- package/src/server/management/api-access.ts +141 -0
- package/src/server/management/api-key-usage.ts +167 -0
- package/src/server/management/body.ts +35 -0
- package/src/server/management/clients-routes.ts +63 -0
- package/src/server/management/cloud-sync-routes.ts +266 -0
- package/src/server/management/combo-routes.ts +220 -0
- package/src/server/management/config-routes.ts +422 -0
- package/src/server/management/context.ts +31 -0
- package/src/server/management/logs-usage-routes.ts +707 -0
- package/src/server/management/model-routes.ts +525 -0
- package/src/server/management/oauth-account-routes.ts +563 -0
- package/src/server/management/provider-routes.ts +556 -0
- package/src/server/management/shared.ts +277 -0
- package/src/server/management/sidebar-routes.ts +90 -0
- package/src/server/management/system-restart.ts +179 -0
- package/src/server/management/system-routes.ts +117 -0
- package/src/server/management/usage-summary-cache.ts +86 -0
- package/src/server/management-api.ts +215 -0
- package/src/server/management-auth.ts +267 -0
- package/src/server/memory-watchdog.ts +156 -0
- package/src/server/port-reclaim.ts +307 -0
- package/src/server/ports.ts +116 -0
- package/src/server/proxy-liveness.ts +201 -0
- package/src/server/relay-eager.ts +313 -0
- package/src/server/relay.ts +1049 -0
- package/src/server/request-decompress.ts +132 -0
- package/src/server/request-log-conversation.ts +168 -0
- package/src/server/request-log.ts +1046 -0
- package/src/server/responses/collaboration.ts +354 -0
- package/src/server/responses/compact.ts +384 -0
- package/src/server/responses/core.ts +2758 -0
- package/src/server/responses/encrypted-payload.ts +308 -0
- package/src/server/responses/fetch-helpers.ts +157 -0
- package/src/server/responses/passthrough-error.ts +78 -0
- package/src/server/responses/terminal-guard.ts +230 -0
- package/src/server/responses/upstream-error.ts +48 -0
- package/src/server/responses-image-gen-repair.ts +132 -0
- package/src/server/responses-item-id-repair.ts +224 -0
- package/src/server/responses.ts +9 -0
- package/src/server/search.ts +136 -0
- package/src/server/sse-payload-rewrite.ts +175 -0
- package/src/server/startup-action-control.ts +308 -0
- package/src/server/startup-health-cache.ts +113 -0
- package/src/server/system-env.ts +413 -0
- package/src/server/windows-tcp-drop.ts +184 -0
- package/src/server/windows-tray-control.ts +41 -0
- package/src/server/ws-bridge.ts +471 -0
- package/src/service.ts +2554 -0
- package/src/stall-timeout.ts +20 -0
- package/src/storage/cleanup-job.ts +57 -0
- package/src/storage/cleanup.ts +3085 -0
- package/src/storage/policy-job.ts +457 -0
- package/src/storage/policy-scheduler.ts +40 -0
- package/src/storage/policy-worker.ts +59 -0
- package/src/storage/policy.ts +527 -0
- package/src/storage/restore-job.ts +299 -0
- package/src/storage/restore-worker.ts +58 -0
- package/src/storage/scanner.ts +238 -0
- package/src/storage/storage-mutation-coordinator.ts +139 -0
- package/src/storage/worker-lifecycle.ts +215 -0
- package/src/tray/assets/opencodex-tray-offline.ico +0 -0
- package/src/tray/assets/opencodex-tray-online.ico +0 -0
- package/src/tray/assets/opencodex-tray-warning.ico +0 -0
- package/src/tray/assets/opencodex-tray.png +0 -0
- package/src/tray/windows-tray.ps1 +290 -0
- package/src/tray/windows.ts +730 -0
- package/src/types.ts +1237 -0
- package/src/update/badge.ts +72 -0
- package/src/update/index.ts +407 -0
- package/src/update/job.ts +1520 -0
- package/src/update/notify.ts +257 -0
- package/src/update/npm-invocation.d.mts +23 -0
- package/src/update/npm-invocation.mjs +94 -0
- package/src/update/tray-update-plan.d.mts +18 -0
- package/src/update/tray-update-plan.mjs +38 -0
- package/src/usage/cost.ts +0 -0
- package/src/usage/debug.ts +97 -0
- package/src/usage/expected-prices.ts +164 -0
- package/src/usage/log.ts +658 -0
- package/src/usage/summary.ts +585 -0
- package/src/usage/totals.ts +14 -0
- package/src/vision/anthropic-describe.ts +185 -0
- package/src/vision/describe.ts +125 -0
- package/src/vision/index.ts +467 -0
- package/src/web-search/anthropic-executor.ts +189 -0
- package/src/web-search/executor.ts +105 -0
- package/src/web-search/format-result.ts +89 -0
- package/src/web-search/index.ts +196 -0
- package/src/web-search/loop.ts +664 -0
- package/src/web-search/parse.ts +220 -0
- package/src/web-search/progress-stream.ts +342 -0
- package/src/web-search/synthetic-tool.ts +47 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime-state-first proxy liveness with identity checking.
|
|
3
|
+
*
|
|
4
|
+
* Historically `ensure`/`start` probed only `config.port` and accepted ANY 2xx /healthz:
|
|
5
|
+
* a proxy that started on a fallback port was invisible (duplicate starts, Codex synced
|
|
6
|
+
* back to a dead port), and a foreign app answering 200 on the configured port counted
|
|
7
|
+
* as "our proxy". Liveness now (1) prefers the pid + runtime-port record and (2) requires
|
|
8
|
+
* the /healthz body to identify as opencodex.
|
|
9
|
+
*
|
|
10
|
+
* Lives outside cli.ts (which dispatches argv at module top level) so tests can import it.
|
|
11
|
+
*/
|
|
12
|
+
import { loadConfig, readAlivePid, readRuntimePort, verifyPidIdentity } from "../config";
|
|
13
|
+
|
|
14
|
+
export interface HealthzIdentity {
|
|
15
|
+
service?: unknown;
|
|
16
|
+
status?: unknown;
|
|
17
|
+
version?: unknown;
|
|
18
|
+
uptime?: unknown;
|
|
19
|
+
pid?: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface LivenessIo {
|
|
23
|
+
fetchFn?: typeof fetch;
|
|
24
|
+
readPidFn?: () => number | null;
|
|
25
|
+
/**
|
|
26
|
+
* Full identity check of the passed candidate pid; must return the SAME pid or null.
|
|
27
|
+
* Destructive callers only ever receive pids that passed this gate.
|
|
28
|
+
*/
|
|
29
|
+
verifyPidFn?: (candidatePid: number) => number | null;
|
|
30
|
+
readRuntimeFn?: (pid?: number) => { pid?: number; port: number; hostname?: string } | null;
|
|
31
|
+
configFn?: () => { port?: number; hostname?: string };
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/**
|
|
34
|
+
* How many times to retry a probe that failed with a transport error (timeout /
|
|
35
|
+
* connection refused). Definitive answers (non-OK HTTP, foreign /healthz body, pid
|
|
36
|
+
* mismatch) do not retry. Default 1 = no retry. Stop paths should pass 2–3 (#764).
|
|
37
|
+
*/
|
|
38
|
+
attempts?: number;
|
|
39
|
+
sleepFn?: (ms: number) => Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Absolute wall-clock deadline for discovery. When set, each probe attempt aborts
|
|
42
|
+
* once the remaining budget cannot cover another fetch — so multi-candidate
|
|
43
|
+
* `findLiveProxy` under `SERVICE_STOP_LIVENESS` cannot overrun the stop-path
|
|
44
|
+
* verification window (#764 / CodeRabbit).
|
|
45
|
+
*/
|
|
46
|
+
deadlineAt?: number;
|
|
47
|
+
nowFn?: () => number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Default probe options for service stop / orphan cleanup — a just-bound proxy can miss a single 750ms probe. */
|
|
51
|
+
export const SERVICE_STOP_LIVENESS: Pick<LivenessIo, "timeoutMs" | "attempts"> = {
|
|
52
|
+
timeoutMs: 1500,
|
|
53
|
+
attempts: 3,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export interface LiveProxy {
|
|
57
|
+
pid: number | null;
|
|
58
|
+
port: number;
|
|
59
|
+
/** Raw bind hostname the probe succeeded against; compose URLs via `probeHostname`. */
|
|
60
|
+
hostname?: string;
|
|
61
|
+
/** Whether the successful probe used runtime-port metadata or the configured listen port. */
|
|
62
|
+
source: "runtime" | "config";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Host to probe for a given bind hostname: wildcards answer on IPv4 loopback, and raw
|
|
67
|
+
* IPv6 addresses must be bracketed or the composed URL is invalid.
|
|
68
|
+
*/
|
|
69
|
+
export function probeHostname(hostname: string | undefined): string {
|
|
70
|
+
const trimmed = (hostname ?? "").trim();
|
|
71
|
+
if (!trimmed || trimmed === "0.0.0.0" || trimmed === "::" || trimmed === "[::]") return "127.0.0.1";
|
|
72
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) return trimmed;
|
|
73
|
+
return trimmed.includes(":") ? `[${trimmed}]` : trimmed;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* True when a /healthz body identifies an opencodex proxy. Accepts the explicit
|
|
78
|
+
* `service: "opencodex"` marker, plus the legacy `{status, version, uptime}` trio so a
|
|
79
|
+
* still-running pre-identity proxy (e.g. right after `ocx update`) is not mistaken for a
|
|
80
|
+
* foreign server and shadow-started over.
|
|
81
|
+
*/
|
|
82
|
+
export function isOpencodexHealthz(body: HealthzIdentity | null): boolean {
|
|
83
|
+
if (!body) return false;
|
|
84
|
+
if (body.service === "opencodex") return true;
|
|
85
|
+
if (body.service !== undefined) return false;
|
|
86
|
+
return body.status === "ok" && typeof body.version === "string" && typeof body.uptime === "number";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Identity-checked /healthz probe; null when unreachable, non-OK, or not our proxy. */
|
|
90
|
+
export async function proxyIdentityAt(
|
|
91
|
+
port: number,
|
|
92
|
+
opts: { hostname?: string; expectedPid?: number } = {},
|
|
93
|
+
io: LivenessIo = {},
|
|
94
|
+
): Promise<{ pid: number | null } | null> {
|
|
95
|
+
const fetchFn = io.fetchFn ?? fetch;
|
|
96
|
+
const sleepFn = io.sleepFn ?? ((ms: number) => new Promise<void>(r => setTimeout(r, ms)));
|
|
97
|
+
const nowFn = io.nowFn ?? Date.now;
|
|
98
|
+
const baseTimeoutMs = io.timeoutMs ?? 750;
|
|
99
|
+
const requestedAttempts = Math.trunc(io.attempts ?? 1);
|
|
100
|
+
const attempts = Number.isNaN(requestedAttempts)
|
|
101
|
+
? 1
|
|
102
|
+
: Math.max(1, Math.min(requestedAttempts, 5));
|
|
103
|
+
|
|
104
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
105
|
+
const remainingMs = io.deadlineAt === undefined ? baseTimeoutMs : io.deadlineAt - nowFn();
|
|
106
|
+
if (remainingMs <= 0) return null;
|
|
107
|
+
const timeoutMs = Math.min(baseTimeoutMs, remainingMs);
|
|
108
|
+
try {
|
|
109
|
+
const res = await fetchFn(`http://${probeHostname(opts.hostname)}:${port}/healthz`, {
|
|
110
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
111
|
+
});
|
|
112
|
+
if (!res.ok) return null;
|
|
113
|
+
const body = (await res.json().catch(() => null)) as HealthzIdentity | null;
|
|
114
|
+
if (!isOpencodexHealthz(body)) return null;
|
|
115
|
+
const pid = typeof body?.pid === "number" ? body.pid : null;
|
|
116
|
+
if (opts.expectedPid !== undefined && pid !== null && pid !== opts.expectedPid) return null;
|
|
117
|
+
return { pid };
|
|
118
|
+
} catch {
|
|
119
|
+
// Transport failure (timeout / refused) — retry while budget remains; a proxy that
|
|
120
|
+
// has only just begun listening can miss a single short probe (#764).
|
|
121
|
+
if (attempt >= attempts) return null;
|
|
122
|
+
if (io.deadlineAt !== undefined && io.deadlineAt - nowFn() <= 0) return null;
|
|
123
|
+
await sleepFn(100);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Locate the live proxy: pid file → runtime-port record → identity probe. Falls back to
|
|
131
|
+
* the configured port ONLY when no runtime record answers, so a fallback-port proxy is
|
|
132
|
+
* found and a foreign listener on the configured port is rejected.
|
|
133
|
+
*/
|
|
134
|
+
export async function findLiveProxy(io: LivenessIo = {}): Promise<LiveProxy | null> {
|
|
135
|
+
// Prefer the cheap alive-pid check: the Windows cmdline probe (WMIC/PowerShell) is too
|
|
136
|
+
// expensive for waitForProxy's 150ms poll loop, and /healthz identity is the real trust gate.
|
|
137
|
+
const readPidFn = io.readPidFn ?? readAlivePid;
|
|
138
|
+
const verifyPidFn = io.verifyPidFn ?? verifyPidIdentity;
|
|
139
|
+
const readRuntimeFn = io.readRuntimeFn ?? readRuntimePort;
|
|
140
|
+
const configFn = io.configFn ?? loadConfig;
|
|
141
|
+
|
|
142
|
+
// The cheap pid is discovery-only. Before it can appear in a returned (killable) result
|
|
143
|
+
// it must pass the full identity check AND the verifier must echo the exact candidate —
|
|
144
|
+
// a pidfile rewrite between discovery and verification can never swap in another process.
|
|
145
|
+
const killablePid = (candidate: number | null): number | null => {
|
|
146
|
+
if (candidate === null) return null;
|
|
147
|
+
const verified = verifyPidFn(candidate);
|
|
148
|
+
return verified === candidate ? verified : null;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const verifiedReportedPid = (reported: number | null): number | null => {
|
|
152
|
+
if (reported === null) return null;
|
|
153
|
+
if (!Number.isSafeInteger(reported) || reported <= 0) return null;
|
|
154
|
+
const verified = verifyPidFn(reported);
|
|
155
|
+
return verified === reported ? verified : null;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const pid = readPidFn();
|
|
159
|
+
let probedPort: number | null = null;
|
|
160
|
+
if (pid) {
|
|
161
|
+
const runtime = readRuntimeFn(pid);
|
|
162
|
+
if (runtime?.port) {
|
|
163
|
+
probedPort = runtime.port;
|
|
164
|
+
const identity = await proxyIdentityAt(runtime.port, { hostname: runtime.hostname, expectedPid: pid }, io);
|
|
165
|
+
if (identity) {
|
|
166
|
+
// healthz confirmed the pid itself → trusted; a pidless legacy body did not,
|
|
167
|
+
// so the cheap pid must pass full identity verification before it is returned.
|
|
168
|
+
const trusted = identity.pid === pid ? pid : killablePid(pid);
|
|
169
|
+
return { pid: trusted, port: runtime.port, hostname: runtime.hostname, source: "runtime" };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Orphan recovery: the pid file can be lost/corrupt while the proxy is alive (crash of a
|
|
175
|
+
// sibling command, manual deletion). The runtime record still says where it listens —
|
|
176
|
+
// identity-probe it so ensure/update/stop see the live proxy instead of shadowing it.
|
|
177
|
+
const record = readRuntimeFn();
|
|
178
|
+
if (record?.port && record.port !== probedPort) {
|
|
179
|
+
const expectedPid = typeof record.pid === "number" ? record.pid : undefined;
|
|
180
|
+
const identity = await proxyIdentityAt(record.port, { hostname: record.hostname, expectedPid }, io);
|
|
181
|
+
// Only the healthz-reported pid is authoritative here. The record's pid may be stale
|
|
182
|
+
// (its process dead, the port reused by a pidless legacy proxy) — synthesizing it
|
|
183
|
+
// would hand destructive callers (stopProxy → kill fallback) a reusable pid.
|
|
184
|
+
if (identity) {
|
|
185
|
+
return { pid: verifiedReportedPid(identity.pid), port: record.port, hostname: record.hostname, source: "runtime" };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const config = configFn();
|
|
190
|
+
const port = config.port ?? 10100;
|
|
191
|
+
const identity = await proxyIdentityAt(port, { hostname: config.hostname }, io);
|
|
192
|
+
if (identity) {
|
|
193
|
+
return {
|
|
194
|
+
pid: verifiedReportedPid(identity.pid) ?? killablePid(pid),
|
|
195
|
+
port,
|
|
196
|
+
hostname: config.hostname,
|
|
197
|
+
source: "config",
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Eager bounded single-reader SSE relay (#314 mitigation, WP2).
|
|
3
|
+
*
|
|
4
|
+
* Replaces the tee()+background-inspection passthrough shape on runtimes where
|
|
5
|
+
* the Bun#32111 async-pull cancel fix is present (src/lib/bun-stream-caps.ts):
|
|
6
|
+
* ONE eager producer loop reads upstream, feeds every chunk through the shared
|
|
7
|
+
* SSE inspector (terminal outcome, quota, request log, context cache), and
|
|
8
|
+
* enqueues it into a byte-bounded client queue. When the queue is full the
|
|
9
|
+
* producer pauses — no unbounded tee branch queue can build up behind a slow
|
|
10
|
+
* client.
|
|
11
|
+
*
|
|
12
|
+
* Honesty caveats (audit M5): full leak relief additionally assumes the
|
|
13
|
+
* runtime carries the Bun#29831 fetch receive-backpressure fix and that Bun's
|
|
14
|
+
* native Response sink pull-paces a JS ReadableStream. Neither is provable in
|
|
15
|
+
* bun:test (a JS reader always paces); both remain "awaiting Windows user
|
|
16
|
+
* verification".
|
|
17
|
+
*
|
|
18
|
+
* #44 cancel semantics: after client cancel the relay keeps reading upstream in
|
|
19
|
+
* DISCARD-DRAIN mode (inspection only) until a terminal is seen or the bounded
|
|
20
|
+
* drain window (ms/bytes) expires — a genuinely reached terminal records as
|
|
21
|
+
* completed/failed, never downgraded to cancel. Only when no terminal arrives
|
|
22
|
+
* within bounds does onClientCancel fire. This bounds today's unbounded tee
|
|
23
|
+
* drain; the tradeoff is that client-cancel log finalization may be delayed by
|
|
24
|
+
* up to the drain window.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { buildFailedTailPayload } from "./relay";
|
|
28
|
+
import {
|
|
29
|
+
nextSseBlock,
|
|
30
|
+
replaceSseDataPayload,
|
|
31
|
+
sseDataPayload,
|
|
32
|
+
type SsePayloadRewrite,
|
|
33
|
+
} from "./sse-payload-rewrite";
|
|
34
|
+
import type { TranslatorBudget } from "../lib/translator-budget";
|
|
35
|
+
|
|
36
|
+
export type EagerRelayHooks = {
|
|
37
|
+
/** Feed one upstream chunk through SSE inspection (createSseInspector.feed). */
|
|
38
|
+
inspectChunk: (chunk: Uint8Array) => void;
|
|
39
|
+
/**
|
|
40
|
+
* Optional inline client-facing payload rewrite, framed to complete SSE
|
|
41
|
+
* blocks inside the single reader. This is what lets win32 rewrite traffic
|
|
42
|
+
* (image_gen restore, item-id repair) use this relay instead of the
|
|
43
|
+
* Bun#32111-unsafe tee()+JS-pull chain (#864).
|
|
44
|
+
*/
|
|
45
|
+
rewritePayload?: SsePayloadRewrite;
|
|
46
|
+
/** Flush inspection at upstream end (createSseInspector.finish). */
|
|
47
|
+
finishInspection: () => void;
|
|
48
|
+
/** Drop inspector-owned frame/item state during producer teardown. */
|
|
49
|
+
disposeInspection?: () => void;
|
|
50
|
+
/** True once inspection has reported a protocol terminal (inspector.reported). */
|
|
51
|
+
sawTerminal: () => boolean;
|
|
52
|
+
/** Record a synthetic terminal (caller decides incomplete vs failed-502). */
|
|
53
|
+
onSynthetic: (kind: "incomplete" | "failed") => void;
|
|
54
|
+
/** Client cancelled and NO terminal arrived within the drain bounds. */
|
|
55
|
+
onClientCancel: () => void;
|
|
56
|
+
/** Exactly once, after the producer fully stops (unregisterTurn parity). */
|
|
57
|
+
onDone: () => void;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export type EagerRelayOptions = {
|
|
61
|
+
/** Bounded client queue in bytes; producer pauses above it. Default 8 MiB. */
|
|
62
|
+
maxQueueBytes?: number;
|
|
63
|
+
/** Transient-budget owner for the inline-rewrite frame buffer. */
|
|
64
|
+
rewriteBudget?: TranslatorBudget;
|
|
65
|
+
/** Post-cancel discard-drain wall-clock bound. Default 15 000 ms. */
|
|
66
|
+
postCancelDrainMs?: number;
|
|
67
|
+
/** Post-cancel discard-drain byte bound. Default 32 MiB. */
|
|
68
|
+
postCancelDrainBytes?: number;
|
|
69
|
+
/** Injectable clock for tests. */
|
|
70
|
+
now?: () => number;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const DEFAULT_MAX_QUEUE_BYTES = 8 * 1024 * 1024;
|
|
74
|
+
const DEFAULT_DRAIN_MS = 15_000;
|
|
75
|
+
const DEFAULT_DRAIN_BYTES = 32 * 1024 * 1024;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Relay `body` to the returned stream with eager bounded reading and inline
|
|
79
|
+
* inspection. `upstream` is aborted on cancel-drain expiry and observed for
|
|
80
|
+
* shutdown teardown (its abort wakes a paused producer and suppresses
|
|
81
|
+
* synthetic terminals — audit M3).
|
|
82
|
+
*/
|
|
83
|
+
export function relaySseEagerBounded(
|
|
84
|
+
body: ReadableStream<Uint8Array>,
|
|
85
|
+
upstream: AbortController,
|
|
86
|
+
hooks: EagerRelayHooks,
|
|
87
|
+
opts?: EagerRelayOptions,
|
|
88
|
+
): ReadableStream<Uint8Array> {
|
|
89
|
+
const maxQueueBytes = opts?.maxQueueBytes ?? DEFAULT_MAX_QUEUE_BYTES;
|
|
90
|
+
const drainMs = opts?.postCancelDrainMs ?? DEFAULT_DRAIN_MS;
|
|
91
|
+
const drainBytes = opts?.postCancelDrainBytes ?? DEFAULT_DRAIN_BYTES;
|
|
92
|
+
const now = opts?.now ?? Date.now;
|
|
93
|
+
|
|
94
|
+
const reader = body.getReader();
|
|
95
|
+
const rewrite = hooks.rewritePayload;
|
|
96
|
+
const rewriteDecoder = rewrite ? new TextDecoder() : null;
|
|
97
|
+
const rewriteEncoder = rewrite ? new TextEncoder() : null;
|
|
98
|
+
const rewriteBudget = opts?.rewriteBudget;
|
|
99
|
+
let frameBuffer = "";
|
|
100
|
+
let frameBufferBytes = 0;
|
|
101
|
+
/** Frame complete SSE blocks and rewrite each block's data payload in place. */
|
|
102
|
+
const rewriteOutbound = (value: Uint8Array): Uint8Array => {
|
|
103
|
+
let out = "";
|
|
104
|
+
const fragment = rewriteDecoder!.decode(value, { stream: true });
|
|
105
|
+
if (rewriteBudget) {
|
|
106
|
+
const nextBytes = frameBufferBytes + rewriteEncoder!.encode(fragment).byteLength;
|
|
107
|
+
const reservation = rewriteBudget.reserveTransient(nextBytes, { kind: "live_transient" });
|
|
108
|
+
try {
|
|
109
|
+
frameBuffer += fragment;
|
|
110
|
+
reservation.commitRetained();
|
|
111
|
+
rewriteBudget.releaseRetained(frameBufferBytes, { kind: "live_transient" });
|
|
112
|
+
frameBufferBytes = nextBytes;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
reservation.release();
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
} else {
|
|
118
|
+
frameBuffer += fragment;
|
|
119
|
+
frameBufferBytes += value.byteLength;
|
|
120
|
+
}
|
|
121
|
+
for (;;) {
|
|
122
|
+
const next = nextSseBlock(frameBuffer);
|
|
123
|
+
if (!next) break;
|
|
124
|
+
const payload = sseDataPayload(next.block);
|
|
125
|
+
const rewrittenPayload = payload === null ? null : rewrite!(payload);
|
|
126
|
+
// Replace only on an actual change: replaceSseDataPayload collapses
|
|
127
|
+
// multi-data-line events and normalizes newline style even when the
|
|
128
|
+
// payload is identical, which corrupts valid streams.
|
|
129
|
+
const block = payload !== null && rewrittenPayload !== payload
|
|
130
|
+
? replaceSseDataPayload(next.block, rewrittenPayload!)
|
|
131
|
+
: next.block;
|
|
132
|
+
out += block + next.delimiter;
|
|
133
|
+
frameBuffer = next.rest;
|
|
134
|
+
}
|
|
135
|
+
if (rewriteBudget) {
|
|
136
|
+
const remaining = rewriteEncoder!.encode(frameBuffer).byteLength;
|
|
137
|
+
rewriteBudget.releaseRetained(frameBufferBytes - remaining, { kind: "live_transient" });
|
|
138
|
+
frameBufferBytes = remaining;
|
|
139
|
+
} else {
|
|
140
|
+
frameBufferBytes = rewriteEncoder!.encode(frameBuffer).byteLength;
|
|
141
|
+
}
|
|
142
|
+
return rewriteEncoder!.encode(out);
|
|
143
|
+
};
|
|
144
|
+
/** Flush any trailing partial block at upstream end (rewrite applied, matching the pull relay). */
|
|
145
|
+
const flushRewriteTail = (): Uint8Array => {
|
|
146
|
+
if (!rewrite) return new Uint8Array(0);
|
|
147
|
+
// Decoder-flushed bytes logically follow everything already decoded.
|
|
148
|
+
let tail = frameBuffer + rewriteDecoder!.decode();
|
|
149
|
+
const payload = sseDataPayload(tail);
|
|
150
|
+
if (payload !== null) {
|
|
151
|
+
const rewrittenPayload = rewrite(payload);
|
|
152
|
+
if (rewrittenPayload !== payload) tail = replaceSseDataPayload(tail, rewrittenPayload);
|
|
153
|
+
}
|
|
154
|
+
frameBuffer = "";
|
|
155
|
+
if (rewriteBudget && frameBufferBytes > 0) {
|
|
156
|
+
rewriteBudget.releaseRetained(frameBufferBytes, { kind: "live_transient" });
|
|
157
|
+
}
|
|
158
|
+
frameBufferBytes = 0;
|
|
159
|
+
return rewriteEncoder!.encode(tail);
|
|
160
|
+
};
|
|
161
|
+
let queuedBytes = 0;
|
|
162
|
+
let cancelled = false;
|
|
163
|
+
let done = false;
|
|
164
|
+
// Pause gate: resolved by client pull, client cancel, or upstream abort so a
|
|
165
|
+
// paused producer ALWAYS resumes (audit blocker 2 — no deadlock; onDone and
|
|
166
|
+
// turn unregistration stay reachable, drainAndShutdown never hangs).
|
|
167
|
+
let wake: (() => void) | null = null;
|
|
168
|
+
const wakeUp = () => { const w = wake; wake = null; w?.(); };
|
|
169
|
+
const paused = () => new Promise<void>(resolve => { wake = resolve; });
|
|
170
|
+
upstream.signal.addEventListener("abort", wakeUp, { once: true });
|
|
171
|
+
|
|
172
|
+
let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null;
|
|
173
|
+
let doneFired = false;
|
|
174
|
+
let drainTimer: ReturnType<typeof setTimeout> | null = null;
|
|
175
|
+
const fireDone = () => {
|
|
176
|
+
if (doneFired) return;
|
|
177
|
+
doneFired = true;
|
|
178
|
+
if (drainTimer) { clearTimeout(drainTimer); drainTimer = null; }
|
|
179
|
+
try { hooks.onDone(); } catch { /* lifecycle callbacks must not break teardown */ }
|
|
180
|
+
};
|
|
181
|
+
// A silent upstream after cancel would park the drain loop in reader.read();
|
|
182
|
+
// the wall-clock bound must fire regardless, so cancel arms a hard timer that
|
|
183
|
+
// aborts upstream at the deadline (the abort wakes the read).
|
|
184
|
+
const armDrainTimer = () => {
|
|
185
|
+
if (drainTimer) return;
|
|
186
|
+
drainTimer = setTimeout(() => {
|
|
187
|
+
drainTimer = null;
|
|
188
|
+
upstream.abort(new Error("post-cancel drain window expired"));
|
|
189
|
+
}, drainMs);
|
|
190
|
+
(drainTimer as { unref?: () => void }).unref?.();
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const producer = async () => {
|
|
194
|
+
let syntheticKind: "incomplete" | "failed" | null = null;
|
|
195
|
+
// reader.read() is not intrinsically tied to the upstream AbortController
|
|
196
|
+
// (a fetch body usually rejects on abort, but that coupling is the fetch
|
|
197
|
+
// implementation's, not the stream's). Race every read against the abort
|
|
198
|
+
// signal so cancel-drain expiry and shutdown teardown ALWAYS break the
|
|
199
|
+
// loop even on a silent upstream.
|
|
200
|
+
const aborted: Promise<"aborted"> = new Promise(resolve => {
|
|
201
|
+
if (upstream.signal.aborted) resolve("aborted");
|
|
202
|
+
else upstream.signal.addEventListener("abort", () => resolve("aborted"), { once: true });
|
|
203
|
+
});
|
|
204
|
+
try {
|
|
205
|
+
for (;;) {
|
|
206
|
+
const result = await Promise.race([reader.read(), aborted]);
|
|
207
|
+
if (result === "aborted") break;
|
|
208
|
+
const { done: upstreamDone, value } = result;
|
|
209
|
+
if (upstreamDone) {
|
|
210
|
+
hooks.finishInspection();
|
|
211
|
+
if (rewrite) {
|
|
212
|
+
const tail = flushRewriteTail();
|
|
213
|
+
if (tail.byteLength > 0 && !cancelled) {
|
|
214
|
+
queuedBytes += tail.byteLength;
|
|
215
|
+
try { controllerRef?.enqueue(tail); } catch { /* client already gone */ }
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (!hooks.sawTerminal() && !cancelled && !upstream.signal.aborted) {
|
|
219
|
+
syntheticKind = "incomplete";
|
|
220
|
+
}
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
hooks.inspectChunk(value);
|
|
224
|
+
if (cancelled) {
|
|
225
|
+
// Discard-drain: inspection only, nothing queued. Stop at terminal
|
|
226
|
+
// or when the bounded window expires.
|
|
227
|
+
drainedBytes += value.byteLength;
|
|
228
|
+
if (hooks.sawTerminal() || drainedBytes >= drainBytes || now() >= drainDeadline) {
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const outbound = rewrite ? rewriteOutbound(value) : value;
|
|
234
|
+
if (outbound.byteLength === 0) continue;
|
|
235
|
+
queuedBytes += outbound.byteLength;
|
|
236
|
+
try {
|
|
237
|
+
controllerRef?.enqueue(outbound);
|
|
238
|
+
} catch {
|
|
239
|
+
// Controller already torn down (client went away without cancel()).
|
|
240
|
+
cancelled = true;
|
|
241
|
+
drainDeadline = now() + drainMs;
|
|
242
|
+
armDrainTimer();
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
while (queuedBytes > maxQueueBytes && !cancelled && !upstream.signal.aborted) {
|
|
246
|
+
await paused();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
} catch (err) {
|
|
250
|
+
// Upstream read failure. Distinguish genuine mid-stream reset from
|
|
251
|
+
// abort-driven teardown (shutdown/cancel-expiry) — audit M3.
|
|
252
|
+
if (!hooks.sawTerminal() && !cancelled && !upstream.signal.aborted) {
|
|
253
|
+
// Serializing `err` can run user-defined accessors (Error.message
|
|
254
|
+
// getters, toString) that re-entrantly cancel the client or abort the
|
|
255
|
+
// upstream. Build the tail FIRST, then re-check eligibility before
|
|
256
|
+
// committing to the synthetic terminal (adversarial review blocker).
|
|
257
|
+
const tail = new TextEncoder().encode(
|
|
258
|
+
`\n\nevent: response.failed\ndata: ${buildFailedTailPayload(err)}\n\ndata: [DONE]\n\n`,
|
|
259
|
+
);
|
|
260
|
+
if (!hooks.sawTerminal() && !cancelled && !upstream.signal.aborted) {
|
|
261
|
+
syntheticKind = "failed";
|
|
262
|
+
queuedBytes += tail.byteLength;
|
|
263
|
+
try { controllerRef?.enqueue(tail); } catch { /* client already torn down */ }
|
|
264
|
+
try { controllerRef?.close(); } catch { /* client already torn down */ }
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
} finally {
|
|
268
|
+
// Release any retained rewrite-buffer bytes on every teardown path
|
|
269
|
+
// (error, cancel, upstream abort) — consumption/EOF release alone
|
|
270
|
+
// leaves them charged.
|
|
271
|
+
if (rewriteBudget && frameBufferBytes > 0) {
|
|
272
|
+
try { rewriteBudget.releaseRetained(frameBufferBytes, { kind: "live_transient" }); } catch { /* teardown must not throw */ }
|
|
273
|
+
frameBufferBytes = 0;
|
|
274
|
+
}
|
|
275
|
+
if (syntheticKind) hooks.onSynthetic(syntheticKind);
|
|
276
|
+
if (cancelled && !hooks.sawTerminal()) {
|
|
277
|
+
hooks.onClientCancel();
|
|
278
|
+
}
|
|
279
|
+
if (cancelled || upstream.signal.aborted || syntheticKind === "failed") {
|
|
280
|
+
upstream.abort();
|
|
281
|
+
reader.cancel().catch(() => {});
|
|
282
|
+
}
|
|
283
|
+
if (!cancelled) {
|
|
284
|
+
try { controllerRef?.close(); } catch { /* already closed/errored */ }
|
|
285
|
+
}
|
|
286
|
+
try { hooks.disposeInspection?.(); } catch { /* inspection teardown must not block lifecycle cleanup */ }
|
|
287
|
+
fireDone();
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
let drainedBytes = 0;
|
|
292
|
+
let drainDeadline = Number.POSITIVE_INFINITY;
|
|
293
|
+
|
|
294
|
+
return new ReadableStream<Uint8Array>({
|
|
295
|
+
start(controller) {
|
|
296
|
+
controllerRef = controller;
|
|
297
|
+
void producer();
|
|
298
|
+
},
|
|
299
|
+
pull() {
|
|
300
|
+
// The client consumed from the queue; approximate accounting: reset on
|
|
301
|
+
// pull below cap. desiredSize reflects internal queue in chunks, not
|
|
302
|
+
// bytes, so we track bytes ourselves and drain optimistically.
|
|
303
|
+
queuedBytes = 0;
|
|
304
|
+
wakeUp();
|
|
305
|
+
},
|
|
306
|
+
cancel() {
|
|
307
|
+
cancelled = true;
|
|
308
|
+
drainDeadline = now() + drainMs;
|
|
309
|
+
armDrainTimer();
|
|
310
|
+
wakeUp();
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
}
|