@bitkyc08/opencodex 2.91.0 → 2.93.0-preview.20261027
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/bin/ocx.mjs +47 -8
- package/gui/dist/assets/App-CJZoq-uF.js +58 -0
- package/gui/dist/assets/{Tray-BuLy7hL1.js → Tray-BWQPcgZn.js} +1 -1
- package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
- package/gui/dist/assets/index-Xfct8owH.js +94 -0
- package/gui/dist/assets/quota-summary-DxToX1rV.js +1 -0
- package/gui/dist/index.html +2 -2
- package/gui/dist/provider-icons/workbuddy-color.svg +29 -0
- package/package.json +8 -7
- package/src/adapters/anthropic.ts +28 -5
- package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
- package/src/adapters/coding-agent/profile.ts +54 -16
- package/src/adapters/coding-agent/turn.ts +30 -2
- package/src/adapters/command-code.ts +114 -7
- package/src/adapters/cursor/native-exec-fs.ts +11 -9
- package/src/adapters/devin/live-models.ts +4 -0
- package/src/adapters/google-vertex-endpoint.ts +9 -1
- package/src/adapters/google-vertex-key-project.ts +223 -0
- package/src/adapters/google-wire-compiler.ts +1 -2
- package/src/adapters/google.ts +13 -3
- package/src/adapters/kiro/reasoning.ts +2 -0
- package/src/adapters/kiro-refusal.ts +6 -1
- package/src/adapters/kiro-wire.ts +1 -1
- package/src/adapters/openai-chat/messages.ts +8 -2
- package/src/adapters/openai-chat/passthrough.ts +35 -14
- package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
- package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
- package/src/adapters/openai-chat/required-tool-result.ts +64 -0
- package/src/adapters/openai-chat/tool-name-registry.ts +3 -1
- package/src/adapters/openai-chat.ts +9 -10
- package/src/adapters/openai-responses/passthrough.ts +7 -4
- package/src/adapters/openai-responses/reasoning.ts +13 -0
- package/src/adapters/openai-responses/request-strips.ts +60 -0
- package/src/adapters/qoder/adapter.ts +129 -8
- package/src/adapters/qoder/scaffold-guard.ts +5 -0
- package/src/adapters/reasoning-controls.ts +16 -0
- package/src/adapters/registry.ts +5 -0
- package/src/adapters/tool-call-id.ts +1 -3
- package/src/adapters/workbuddy-schema.ts +61 -0
- package/src/adapters/workbuddy.ts +68 -0
- package/src/bridge/errors.ts +27 -0
- package/src/bridge/response-json.ts +1 -1
- package/src/bridge/sse.ts +1 -1
- package/src/bridge.ts +1 -1
- package/src/chat/inbound.ts +4 -1
- package/src/chat/outbound.ts +20 -6
- package/src/chat/reasoning-details.ts +28 -5
- package/src/claude/desktop-first-party.ts +54 -4
- package/src/claude/desktop-picker.ts +11 -8
- package/src/claude/first-party-settings.ts +3 -1
- package/src/claude/inbound.ts +2 -1
- package/src/claude/intercept/local-ca.ts +2 -1
- package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
- package/src/claude/intercept/picker-ca-startup.ts +3 -1
- package/src/claude/intercept/picker-models.ts +6 -3
- package/src/claude/intercept/picker-runtime.ts +3 -2
- package/src/claude/intercept/runtime.ts +6 -3
- package/src/claude/model-info.ts +31 -8
- package/src/cli/account-api.ts +11 -0
- package/src/cli/capabilities-agents-routing.ts +3 -3
- package/src/cli/capabilities-base.ts +7 -1
- package/src/cli/capabilities-observe-system.ts +10 -0
- package/src/cli/claude-desktop.ts +9 -8
- package/src/cli/claude.ts +3 -2
- package/src/cli/codex-cli-update.ts +8 -0
- package/src/cli/codex-shim-autorestore.ts +9 -0
- package/src/cli/combo-result.ts +13 -0
- package/src/cli/combo-stats.ts +3 -0
- package/src/cli/combo.ts +83 -41
- package/src/cli/cross-home-owner.ts +13 -1
- package/src/cli/dispatch.ts +25 -6
- package/src/cli/ensure-desired-integrations.ts +8 -6
- package/src/cli/export-command.ts +4 -1
- package/src/cli/help.ts +2 -1
- package/src/cli/index.ts +45 -45
- package/src/cli/integration-plan-dto.ts +4 -0
- package/src/cli/launcher-context.ts +49 -2
- package/src/cli/link.ts +45 -32
- package/src/cli/opencode.ts +20 -9
- package/src/cli/provider.ts +2 -1
- package/src/cli/registry.ts +6 -4
- package/src/cli/root.ts +9 -0
- package/src/cli/status.ts +59 -1
- package/src/cli/stop-restore.ts +113 -0
- package/src/cli/sync-expectation.ts +60 -0
- package/src/cli/uninstall-integrations.ts +41 -7
- package/src/cli/usage-compare.ts +68 -12
- package/src/client/connect.ts +40 -3
- package/src/client/link-home.ts +10 -1
- package/src/client/link-ingress.ts +1 -1
- package/src/client/link-readiness.ts +97 -0
- package/src/client/link-relay-transport.ts +79 -11
- package/src/client/link-relay.ts +74 -15
- package/src/client/link-tunnel.ts +45 -18
- package/src/client/machine-api.ts +3 -1
- package/src/client/machine-listener.ts +20 -2
- package/src/client/runtime.ts +20 -2
- package/src/client/sync-expectation.ts +118 -0
- package/src/clients/config-export/agent-clients.ts +96 -0
- package/src/clients/config-export/contracts.ts +25 -7
- package/src/clients/config-export/qoder.ts +38 -23
- package/src/clients/config-export/reasoning-metadata.ts +55 -8
- package/src/clients/config-export.ts +12 -0
- package/src/clients/lazycodex.ts +7 -2
- package/src/clients/reasoning-controls.ts +49 -0
- package/src/codex/account-store.ts +17 -3
- package/src/codex/app-server-restart-service.ts +6 -5
- package/src/codex/auth-api/account-identity.ts +14 -0
- package/src/codex/auth-api/account-list.ts +29 -2
- package/src/codex/auth-api/http.ts +13 -0
- package/src/codex/auth-api/main-account-probe.ts +2 -2
- package/src/codex/auth-api/pool-mode-gate.ts +16 -3
- package/src/codex/auth-api/pool-quota-probe.ts +15 -0
- package/src/codex/auth-context.ts +15 -12
- package/src/codex/catalog/build-entries.ts +22 -0
- package/src/codex/catalog/configured-tiers.ts +70 -0
- package/src/codex/catalog/effort.ts +52 -11
- package/src/codex/catalog/gather-capture.ts +5 -2
- package/src/codex/catalog/heal-observation.ts +155 -13
- package/src/codex/catalog/metadata.ts +6 -0
- package/src/codex/catalog/model-hints.ts +60 -11
- package/src/codex/catalog/model-visibility.ts +3 -2
- package/src/codex/catalog/native-models.ts +18 -3
- package/src/codex/catalog/parsing.ts +10 -8
- package/src/codex/catalog/pinned-models.ts +2 -1
- package/src/codex/catalog/provider-models.ts +18 -13
- package/src/codex/catalog/retained-sync.ts +2 -1
- package/src/codex/catalog/routed-gather.ts +19 -20
- package/src/codex/catalog/write-audit.ts +3 -2
- package/src/codex/catalog-self-heal.ts +43 -23
- package/src/codex/chatgpt-refresh-failure.ts +6 -2
- package/src/codex/cli-install-provenance.ts +418 -0
- package/src/codex/cli-installation-targets.ts +5 -1
- package/src/codex/cli-update-plan.ts +43 -16
- package/src/codex/collision-identity.ts +30 -5
- package/src/codex/convergence.ts +4 -3
- package/src/codex/data/roster-pinned-models.json +177 -1
- package/src/codex/desired-state.ts +6 -1
- package/src/codex/desktop-app/picker-freshness.ts +10 -8
- package/src/codex/desktop-compatibility/installed-build.ts +88 -12
- package/src/codex/desktop-compatibility/runtime.ts +29 -5
- package/src/codex/desktop-compatibility/usage-activation.ts +2 -1
- package/src/codex/desktop-compatibility/usage-controller.ts +9 -1
- package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
- package/src/codex/inject/config-toml.ts +0 -18
- package/src/codex/inject/plan.ts +18 -3
- package/src/codex/inject/remove.ts +6 -2
- package/src/codex/inject.ts +1 -1
- package/src/codex/journal.ts +61 -1
- package/src/codex/model-entitlements.ts +1 -1
- package/src/codex/native-main-owner.ts +27 -1
- package/src/codex/native-profile-store.ts +2 -1
- package/src/codex/pool-credit-policy.ts +35 -1
- package/src/codex/pool-refresh-backoff.ts +3 -1
- package/src/codex/quota-types.ts +3 -0
- package/src/codex/quota.ts +24 -4
- package/src/codex/role-auto-assign.ts +6 -2
- package/src/codex/subagent-defaults.ts +49 -4
- package/src/codex/user-identity.ts +35 -6
- package/src/codex/windows-current-sid.ts +162 -0
- package/src/combos/failover.ts +17 -2
- package/src/combos/jev-decision-contract.ts +22 -1
- package/src/combos/jev-quota-activation.ts +5 -1
- package/src/combos/jev-quota-route.ts +1 -1
- package/src/combos/jev-quota.ts +9 -1
- package/src/combos/jev-service-exchange.ts +3 -1
- package/src/combos/jev-session-pin-config.ts +51 -0
- package/src/combos/jev.ts +101 -9
- package/src/combos/resolve.ts +45 -1
- package/src/combos/types.ts +43 -0
- package/src/config/load-degrade.ts +5 -0
- package/src/config/paths.ts +19 -3
- package/src/config/pending-teardown.ts +22 -1
- package/src/config/provider-validation.ts +22 -4
- package/src/config/removed-opencode-free.ts +11 -0
- package/src/config/schema/leaf-validators.ts +6 -0
- package/src/generated/compatibility-version.json +467 -311
- package/src/generated/model-metadata.ts +5 -5
- package/src/images/loop.ts +16 -2
- package/src/integrations/catalog-refresh.ts +1 -1
- package/src/integrations/hermes-profiles.ts +251 -0
- package/src/integrations/merge.ts +8 -0
- package/src/integrations/mutation-plan.ts +19 -4
- package/src/integrations/registry.ts +5 -0
- package/src/integrations/state.ts +36 -1
- package/src/integrations/writer.ts +18 -4
- package/src/lib/bun-path-runtime.mjs +2 -1
- package/src/lib/decision-quota-sink.ts +10 -0
- package/src/lib/errors.ts +62 -0
- package/src/lib/eventstream-decoder.ts +81 -37
- package/src/lib/opaque-proxy-tunnel.ts +32 -8
- package/src/lib/pinned-http.ts +35 -2
- package/src/lib/process-control.ts +13 -1
- package/src/lib/socks5-fetch.ts +59 -64
- package/src/lib/socks5-upload-waiter.ts +50 -0
- package/src/lib/sse-decoder.ts +7 -2
- package/src/lib/state-store-sweeper.ts +40 -14
- package/src/lib/translator-budget.ts +4 -4
- package/src/lib/upstream-retry.ts +4 -1
- package/src/lib/windows-native-principal-worker.ts +14 -0
- package/src/lib/windows-native-principal.ts +188 -0
- package/src/lib/windows-secret-acl.ts +39 -3
- package/src/lib/windows-user-principal.ts +62 -18
- package/src/link/diagnostics.ts +193 -0
- package/src/link/relay-auth.ts +6 -0
- package/src/link/ssh-config.ts +35 -3
- package/src/link/status-projection.ts +39 -0
- package/src/link/supervisor.ts +45 -12
- package/src/link/tunnel-history.ts +109 -0
- package/src/link/tunnel-state.ts +80 -17
- package/src/messaging/remote-files.ts +24 -1
- package/src/oauth/generic-account-failover.ts +91 -7
- package/src/oauth/index.ts +15 -0
- package/src/oauth/model-discovery-auth.ts +5 -0
- package/src/oauth/store.ts +4 -1
- package/src/oauth/token-guardian.ts +7 -0
- package/src/oauth/types.ts +9 -0
- package/src/oauth/workbuddy.ts +139 -0
- package/src/providers/account-quota-disk.ts +12 -4
- package/src/providers/antigravity-quota-identity.ts +37 -0
- package/src/providers/base-url-choices.ts +8 -5
- package/src/providers/codebuddy-models.ts +6 -0
- package/src/providers/codex-capacity.ts +3 -1
- package/src/providers/derive.ts +51 -3
- package/src/providers/kiro-models.ts +3 -0
- package/src/providers/mimo-thinking.ts +12 -0
- package/src/providers/model-discovery.ts +2 -0
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/model-rename-migration.ts +10 -0
- package/src/providers/openai-sidecar-credit.ts +2 -2
- package/src/providers/quota/account-cache.ts +3 -2
- package/src/providers/quota/antigravity.ts +25 -14
- package/src/providers/quota/report-cache.ts +13 -4
- package/src/providers/quota/vendor-probes-key.ts +60 -0
- package/src/providers/quota/workbuddy.ts +83 -0
- package/src/providers/quota-decision-antigravity.ts +64 -0
- package/src/providers/quota-decision-publication.ts +11 -0
- package/src/providers/quota-decision-snapshot.ts +21 -4
- package/src/providers/quota-types.ts +2 -0
- package/src/providers/quota.ts +3 -1
- package/src/providers/reasoning-capabilities.ts +76 -0
- package/src/providers/registry/entries-core.ts +23 -12
- package/src/providers/registry/entries-extended.ts +83 -27
- package/src/providers/registry/model-ids.ts +5 -0
- package/src/providers/registry/model-seeds.ts +120 -56
- package/src/providers/registry/types.ts +29 -2
- package/src/providers/resolved-model-policy.ts +30 -10
- package/src/providers/routed-config.ts +24 -1
- package/src/providers/stale-model-roster-migration.ts +123 -18
- package/src/providers/workbuddy-credit-balance.ts +81 -0
- package/src/providers/workbuddy-models.ts +37 -0
- package/src/providers/workbuddy.ts +60 -0
- package/src/remote-control/workspace-pi-runtime.ts +11 -6
- package/src/responses/compaction-summary.ts +45 -0
- package/src/responses/muse-tool-name-alias.ts +1 -2
- package/src/responses/parser.ts +3 -2
- package/src/responses/reasoning-replay-cache.ts +18 -14
- package/src/responses/schema.ts +1 -0
- package/src/responses/thought-signature-replay.ts +10 -2
- package/src/router.ts +2 -0
- package/src/routing/analytics.ts +2 -3
- package/src/routing/capability.ts +8 -2
- package/src/routing/fallback-policy.ts +3 -3
- package/src/routing/history/ingest.ts +28 -3
- package/src/server/auth-cors.ts +4 -2
- package/src/server/chat-completions.ts +21 -1
- package/src/server/chat-native-eligibility.ts +7 -0
- package/src/server/chat-native-reasoning.ts +24 -7
- package/src/server/chat-native.ts +13 -2
- package/src/server/claude-messages.ts +3 -0
- package/src/server/direct-local-http.ts +5 -2
- package/src/server/effort-policy.ts +5 -1
- package/src/server/index/link-relay-sessions.ts +9 -5
- package/src/server/index/live-sideband.ts +18 -15
- package/src/server/index/optional-listeners.ts +4 -0
- package/src/server/index/serve-options.ts +5 -4
- package/src/server/local-management-read-client.ts +3 -1
- package/src/server/management/agent-settings-routes.ts +27 -15
- package/src/server/management/combo-routes.ts +14 -4
- package/src/server/management/config-routes.ts +2 -2
- package/src/server/management/decision-discovery.ts +12 -2
- package/src/server/management/hermes-profile-routes.ts +156 -0
- package/src/server/management/integration-routes.ts +85 -24
- package/src/server/management/link-routes.ts +5 -2
- package/src/server/management/model-routes.ts +2 -2
- package/src/server/management/model-row-export-metadata.ts +25 -6
- package/src/server/management/model-rows.ts +15 -20
- package/src/server/management/native-integration-routes.ts +11 -8
- package/src/server/management/provider-routes.ts +1 -1
- package/src/server/management/route-registry.ts +4 -0
- package/src/server/management-api.ts +5 -0
- package/src/server/models-capabilities.ts +21 -3
- package/src/server/port-reclaim.ts +51 -9
- package/src/server/request-log-conversation.ts +49 -0
- package/src/server/request-log.ts +2 -0
- package/src/server/responses/adapter-delivery.ts +11 -1
- package/src/server/responses/adapter-dispatch.ts +2 -2
- package/src/server/responses/anthropic-thinking-recovery.ts +1 -0
- package/src/server/responses/codex-ws-exchange.ts +39 -9
- package/src/server/responses/codex-ws-session.ts +38 -4
- package/src/server/responses/codex-ws-wire.ts +6 -1
- package/src/server/responses/combo-required-tool-contract.ts +103 -0
- package/src/server/responses/combo-stream-preflight.ts +8 -1
- package/src/server/responses/compact.ts +14 -5
- package/src/server/responses/context-overflow.ts +8 -1
- package/src/server/responses/core-combo-failure.ts +10 -0
- package/src/server/responses/core-combo.ts +74 -44
- package/src/server/responses/core-lifetime.ts +5 -2
- package/src/server/responses/core-normalize.ts +17 -4
- package/src/server/responses/core-opaque-recovery.ts +1 -0
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/core-replay.ts +2 -1
- package/src/server/responses/jev-combo-choice.ts +39 -0
- package/src/server/responses/jev-session-pin.ts +203 -0
- package/src/server/responses/main-hard-lock-routing.ts +60 -44
- package/src/server/responses/passthrough-delivery.ts +44 -2
- package/src/server/responses/policy-fallback.ts +6 -1
- package/src/server/responses/request-compression.ts +12 -7
- package/src/server/responses/request-prepare.ts +32 -7
- package/src/server/responses/request-sidecar-auth.ts +2 -0
- package/src/server/responses/request-transport.ts +25 -6
- package/src/server/responses/response-effects.ts +22 -10
- package/src/server/responses/run-turn-execution.ts +2 -4
- package/src/server/responses/sidecar-execution.ts +13 -7
- package/src/server/responses-phase-inference.ts +267 -0
- package/src/server/sse-payload-rewrite.ts +14 -1
- package/src/server/stop-teardown.ts +36 -1
- package/src/server/ws-bridge.ts +1 -1
- package/src/service/definition.ts +20 -8
- package/src/service/desktop-supervision.d.mts +7 -4
- package/src/service/desktop-supervision.mjs +90 -13
- package/src/service/ownership-mutation-lease.mjs +21 -7
- package/src/types/config.ts +14 -2
- package/src/types/provider.ts +29 -7
- package/src/types/request.ts +11 -0
- package/src/types/wire.ts +1 -0
- package/src/types.ts +1 -0
- package/src/update/bind-probe.ts +29 -0
- package/src/update/codex-cli-update-launch-policy.d.mts +9 -0
- package/src/update/codex-cli-update-launch-policy.mjs +30 -0
- package/src/update/job.ts +10 -29
- package/src/update/npm-install-job.ps1 +173 -0
- package/src/update/npm-install.mjs +70 -0
- package/src/update/stop-contract.d.mts +1 -0
- package/src/update/stop-contract.mjs +14 -0
- package/src/update/stop-decision.d.mts +1 -1
- package/src/update/stop-decision.mjs +13 -3
- package/src/update/teardown-handover.ts +166 -0
- package/src/update/transactional-install.d.mts +14 -3
- package/src/update/transactional-install.mjs +33 -7
- package/src/usage/expected-prices.ts +64 -31
- package/src/usage/jev-stats.ts +54 -14
- package/src/usage/timeline.ts +19 -9
- package/src/vision/eligibility.ts +15 -5
- package/src/vision/plan.ts +2 -2
- package/src/web-search/loop.ts +16 -2
- package/gui/dist/assets/App-nZ34cR5G.js +0 -58
- package/gui/dist/assets/index-DGXS51sp.js +0 -94
- package/gui/dist/assets/index-DPeB9HpV.css +0 -1
- package/gui/dist/assets/quota-summary-DO1Sx5TM.js +0 -1
|
@@ -7,6 +7,7 @@ import { buildCodingAgentToolCatalog, CodingAgentToolCatalogError } from "../cod
|
|
|
7
7
|
import { baseScopedEnv, runCodingAgentTurn, type CodingAgentDeps, type CodingAgentToolBridgeInput, type CodingAgentFailure } from "../coding-agent/turn";
|
|
8
8
|
import { QODER_PROFILES, resolveQoderProfile, type QoderProfile } from "./profiles";
|
|
9
9
|
import { QoderScaffoldFilter, QODER_SCAFFOLD_ERROR_CODE, qoderScaffoldErrorMessage } from "./scaffold-guard";
|
|
10
|
+
import { ToolEnvelopeEchoFilter } from "../../lib/tool-envelope-echo-filter";
|
|
10
11
|
|
|
11
12
|
export type QoderAdapterDeps = CodingAgentDeps;
|
|
12
13
|
|
|
@@ -50,6 +51,8 @@ function classifyQoderFailure(failure: CodingAgentFailure): Extract<AdapterEvent
|
|
|
50
51
|
|
|
51
52
|
const QODER_MCP_SERVER_NAME = "opencodex";
|
|
52
53
|
const QODER_MCP_SERVER_PATH = fileURLToPath(new URL("../coding-agent/mcp-server.ts", import.meta.url));
|
|
54
|
+
const MAX_PENDING_BOUNDARY_CHARS = 64 * 1024;
|
|
55
|
+
const MAX_PENDING_BOUNDARY_EVENTS = 1024;
|
|
53
56
|
|
|
54
57
|
export function buildQoderChildEnv(profile: QoderProfile, apiKey: string, systemPrompt?: string): Record<string, string> {
|
|
55
58
|
// Each build reads its own brand prefix with no fallback: qodercn ignores QODER_EXPOSE_TOKEN_USAGE.
|
|
@@ -79,6 +82,8 @@ export function buildQoderArgs(parsed: OcxParsedRequest, provider: OcxProviderCo
|
|
|
79
82
|
|
|
80
83
|
/**
|
|
81
84
|
* Wrap the turn's outbound channel with the scaffolding guard (#4190).
|
|
85
|
+
* Vendor-cleaned assistant text also uses the shared replay-envelope recognizer
|
|
86
|
+
* (#7517), so internal history scaffolding cannot become a successful answer.
|
|
82
87
|
*
|
|
83
88
|
* The vendor CLI can put its own agent layer into the text channel despite built-in tools
|
|
84
89
|
* being disabled, and the shared stream-json parser forwards a text delta
|
|
@@ -93,11 +98,18 @@ export function buildQoderArgs(parsed: OcxParsedRequest, provider: OcxProviderCo
|
|
|
93
98
|
export function guardQoderScaffolding(emit: (event: AdapterEvent) => void): (event: AdapterEvent) => void {
|
|
94
99
|
const textFilter = new QoderScaffoldFilter();
|
|
95
100
|
const thinkingFilter = new QoderScaffoldFilter();
|
|
101
|
+
let replayFilter = new ToolEnvelopeEchoFilter();
|
|
96
102
|
let closed = false;
|
|
103
|
+
let boundaries: { offset: number; event: AdapterEvent }[] = [];
|
|
104
|
+
let boundaryChars = 0;
|
|
105
|
+
let textCarry = "";
|
|
97
106
|
|
|
98
107
|
const refuse = (reason: string): void => {
|
|
99
108
|
if (closed) return;
|
|
100
109
|
closed = true;
|
|
110
|
+
boundaries = [];
|
|
111
|
+
boundaryChars = 0;
|
|
112
|
+
textCarry = "";
|
|
101
113
|
emit({
|
|
102
114
|
type: "error",
|
|
103
115
|
message: qoderScaffoldErrorMessage(reason),
|
|
@@ -110,26 +122,134 @@ export function guardQoderScaffolding(emit: (event: AdapterEvent) => void): (eve
|
|
|
110
122
|
});
|
|
111
123
|
};
|
|
112
124
|
|
|
125
|
+
const forwardText = (text: string, refuseOnMatch = true): void => {
|
|
126
|
+
const safe = replayFilter.feed(text);
|
|
127
|
+
// An overflowing fenced hold can release an unverified marker. Refuse it
|
|
128
|
+
// before publication rather than leaking the envelope under a memory cap.
|
|
129
|
+
if (replayFilter.unverifiedMarker) {
|
|
130
|
+
if (refuseOnMatch) refuse("replayed tool envelope");
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (safe) emit({ type: "text_delta", text: safe });
|
|
134
|
+
if (replayFilter.matched && refuseOnMatch) refuse("replayed tool envelope");
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
/*
|
|
138
|
+
* Any other event ends the text block before it. Settle text the replay filter
|
|
139
|
+
* still holds so the event cannot overtake it, and refuse before publishing the
|
|
140
|
+
* event when that text completes an envelope. Heartbeats carry no content and
|
|
141
|
+
* must not split a marker. The next text block starts at a line start, so an
|
|
142
|
+
* envelope opening it is recognized even when the previous block ended mid-line.
|
|
143
|
+
*/
|
|
144
|
+
const settleText = (refuseOnMatch = true): boolean => {
|
|
145
|
+
const tail = replayFilter.finish();
|
|
146
|
+
if (replayFilter.matched || replayFilter.unverifiedMarker) {
|
|
147
|
+
if (refuseOnMatch) refuse("replayed tool envelope");
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
if (tail) emit({ type: "text_delta", text: tail });
|
|
151
|
+
replayFilter = new ToolEnvelopeEchoFilter();
|
|
152
|
+
return true;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const forwardEvent = (event: AdapterEvent): void => {
|
|
156
|
+
// A vendor prefix can still turn a replay marker into ordinary prose. Keep
|
|
157
|
+
// its event cuts until the vendor filter resolves it instead of flushing it.
|
|
158
|
+
const offset = textFilter.pendingTextLength + textCarry.length;
|
|
159
|
+
if (offset > 0) {
|
|
160
|
+
const size = event.type === "thinking_delta" ? event.thinking.length : JSON.stringify(event).length;
|
|
161
|
+
if (boundaryChars + size > MAX_PENDING_BOUNDARY_CHARS
|
|
162
|
+
|| boundaries.length >= MAX_PENDING_BOUNDARY_EVENTS) {
|
|
163
|
+
refuse("an unresolved text boundary exceeding its buffer limit");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
boundaryChars += size;
|
|
167
|
+
const last = boundaries.at(-1);
|
|
168
|
+
if (last?.offset === offset
|
|
169
|
+
&& last.event.type === "thinking_delta" && event.type === "thinking_delta") {
|
|
170
|
+
last.event = { type: "thinking_delta", thinking: last.event.thinking + event.thinking };
|
|
171
|
+
} else boundaries.push({ offset, event });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (settleText() && (event.type !== "thinking_delta" || event.thinking)) emit(event);
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const drainBoundaries = (text: string, refuseOnMatch = true): void => {
|
|
178
|
+
const queued = boundaries;
|
|
179
|
+
boundaries = [];
|
|
180
|
+
boundaryChars = 0;
|
|
181
|
+
let at = 0;
|
|
182
|
+
for (const boundary of queued) {
|
|
183
|
+
// A suppressed prefix contributes no text; surviving prefixes keep their offsets.
|
|
184
|
+
let end = text ? Math.min(text.length, Math.max(at, boundary.offset)) : 0;
|
|
185
|
+
const before = text.charCodeAt(end - 1), after = text.charCodeAt(end);
|
|
186
|
+
// A scalar completed by a later input belongs before events between its halves.
|
|
187
|
+
if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end++;
|
|
188
|
+
forwardText(text.slice(at, end), refuseOnMatch);
|
|
189
|
+
if (closed || !settleText(refuseOnMatch)) return;
|
|
190
|
+
if (boundary.event.type !== "thinking_delta" || boundary.event.thinking) emit(boundary.event);
|
|
191
|
+
at = end;
|
|
192
|
+
}
|
|
193
|
+
if (!closed) forwardText(text.slice(at), refuseOnMatch);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const prepareText = (text: string, terminal = false): string => {
|
|
197
|
+
let complete = textCarry + text;
|
|
198
|
+
textCarry = "";
|
|
199
|
+
const last = complete.charCodeAt(complete.length - 1);
|
|
200
|
+
if (!terminal && last >= 0xd800 && last <= 0xdbff) {
|
|
201
|
+
textCarry = complete.slice(-1);
|
|
202
|
+
complete = complete.slice(0, -1);
|
|
203
|
+
}
|
|
204
|
+
return complete.toWellFormed();
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const pushText = (text: string, refuseOnMatch = true): string | null => {
|
|
208
|
+
let at = 0;
|
|
209
|
+
while (boundaries.length && at < text.length) {
|
|
210
|
+
const width = text.codePointAt(at)! > 0xffff ? 2 : 1;
|
|
211
|
+
const cleaned = textFilter.push(text.slice(at, at + width));
|
|
212
|
+
at += width;
|
|
213
|
+
if (cleaned.fail) {
|
|
214
|
+
if (refuseOnMatch) refuse(cleaned.fail);
|
|
215
|
+
return cleaned.fail;
|
|
216
|
+
}
|
|
217
|
+
// A pending vendor suffix is one marker prefix, starting with its only
|
|
218
|
+
// '<'. Its first release resolves the entire suffix and its saved cuts.
|
|
219
|
+
if (cleaned.text || textFilter.pendingTextLength === 0) drainBoundaries(cleaned.text, refuseOnMatch);
|
|
220
|
+
if (closed) return null;
|
|
221
|
+
}
|
|
222
|
+
const cleaned = textFilter.push(text.slice(at));
|
|
223
|
+
if (cleaned.text) forwardText(cleaned.text, refuseOnMatch);
|
|
224
|
+
if (cleaned.fail && refuseOnMatch) refuse(cleaned.fail);
|
|
225
|
+
return cleaned.fail;
|
|
226
|
+
};
|
|
227
|
+
|
|
113
228
|
return (event: AdapterEvent): void => {
|
|
114
229
|
if (closed) return;
|
|
115
230
|
if (event.type === "text_delta") {
|
|
116
|
-
|
|
117
|
-
if (cleaned.text) emit({ ...event, text: cleaned.text });
|
|
118
|
-
if (cleaned.fail) refuse(cleaned.fail);
|
|
231
|
+
if (event.text) pushText(prepareText(event.text));
|
|
119
232
|
return;
|
|
120
233
|
}
|
|
121
234
|
if (event.type === "thinking_delta") {
|
|
122
235
|
const cleaned = thinkingFilter.push(event.thinking);
|
|
123
|
-
|
|
236
|
+
forwardEvent({ ...event, thinking: cleaned.text });
|
|
124
237
|
if (cleaned.fail) refuse(cleaned.fail);
|
|
125
238
|
return;
|
|
126
239
|
}
|
|
127
240
|
if (event.type === "done" || event.type === "error" || event.type === "incomplete") {
|
|
241
|
+
const carryFailure = textCarry ? pushText(prepareText("", true), false) : null;
|
|
128
242
|
const tail = textFilter.flush();
|
|
129
243
|
const reasoning = thinkingFilter.flush();
|
|
130
|
-
|
|
131
|
-
if (
|
|
132
|
-
const
|
|
244
|
+
drainBoundaries(tail.text, false);
|
|
245
|
+
if (closed) return;
|
|
246
|
+
const replayTail = replayFilter.finish();
|
|
247
|
+
if (replayTail && !replayFilter.unverifiedMarker) emit({ type: "text_delta", text: replayTail });
|
|
248
|
+
if (reasoning.text && !replayFilter.matched && !replayFilter.unverifiedMarker) {
|
|
249
|
+
emit({ type: "thinking_delta", thinking: reasoning.text });
|
|
250
|
+
}
|
|
251
|
+
const fail = carryFailure ?? tail.fail ?? reasoning.fail
|
|
252
|
+
?? (replayFilter.matched || replayFilter.unverifiedMarker ? "replayed tool envelope" : null);
|
|
133
253
|
// A vendor error already carries the better explanation for why the turn ended;
|
|
134
254
|
// only a terminal that claims success is replaced.
|
|
135
255
|
if (fail && event.type !== "error") {
|
|
@@ -140,7 +260,8 @@ export function guardQoderScaffolding(emit: (event: AdapterEvent) => void): (eve
|
|
|
140
260
|
emit(event);
|
|
141
261
|
return;
|
|
142
262
|
}
|
|
143
|
-
emit(event);
|
|
263
|
+
if (event.type === "heartbeat") emit(event);
|
|
264
|
+
else forwardEvent(event);
|
|
144
265
|
};
|
|
145
266
|
}
|
|
146
267
|
|
|
@@ -138,6 +138,11 @@ export class QoderScaffoldFilter {
|
|
|
138
138
|
/** Open reminder blocks; only the closer that unwinds the last one ends suppression. */
|
|
139
139
|
private suppressDepth = 0;
|
|
140
140
|
|
|
141
|
+
/** Unpublished marker-prefix characters; excludes suppressed block content. */
|
|
142
|
+
get pendingTextLength(): number {
|
|
143
|
+
return this.pending.length;
|
|
144
|
+
}
|
|
145
|
+
|
|
141
146
|
push(chunk: string): ScaffoldFilterResult {
|
|
142
147
|
if (this.failed || !chunk) return { text: "", fail: null };
|
|
143
148
|
let cleared = "";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { registryEntryForProviderDestination } from "../providers/registry";
|
|
2
|
+
import { resolveReasoningCapabilities } from "../providers/reasoning-capabilities";
|
|
3
|
+
import { modelInList, type OcxProviderConfig } from "../types";
|
|
4
|
+
|
|
5
|
+
/** A thinking toggle is serialized only on a provider-declared wire. */
|
|
6
|
+
export function declaresThinkingToggleWire(provider: OcxProviderConfig, modelId: string): boolean {
|
|
7
|
+
return modelInList(provider.thinkingToggleModels, modelId)
|
|
8
|
+
|| modelInList(registryEntryForProviderDestination(provider)?.thinkingToggleModels, modelId);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Explicitly unavailable controls constrain both translated and native requests. */
|
|
12
|
+
export function reasoningControlsAreUnsupported(provider: OcxProviderConfig, modelId: string): boolean {
|
|
13
|
+
const capabilities = resolveReasoningCapabilities(provider, modelId);
|
|
14
|
+
return capabilities.supportsReasoning === false
|
|
15
|
+
|| (capabilities.supportsThinkingToggle === false && capabilities.supportsReasoningEffort === false);
|
|
16
|
+
}
|
package/src/adapters/registry.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createAnthropicAdapter } from "./anthropic";
|
|
2
|
+
import { createWorkBuddyAdapter } from "./workbuddy";
|
|
2
3
|
import { createDshAccountAdapter } from "./dsh-account";
|
|
3
4
|
import { createAzureAdapter } from "./azure";
|
|
4
5
|
import type { ProviderAdapter } from "./base";
|
|
@@ -74,6 +75,10 @@ type InheritedAdapterDefinition = {
|
|
|
74
75
|
type AdapterDefinition = DirectAdapterDefinition | InheritedAdapterDefinition;
|
|
75
76
|
|
|
76
77
|
export const ADAPTER_REGISTRY = {
|
|
78
|
+
"workbuddy-ai": {
|
|
79
|
+
contractParent: "openai-chat",
|
|
80
|
+
create: (provider: OcxProviderConfig) => withUniqueToolCallIds(createWorkBuddyAdapter(provider)),
|
|
81
|
+
},
|
|
77
82
|
codebuddy: {
|
|
78
83
|
wire: "codebuddy",
|
|
79
84
|
mutation: "codex-owned",
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
|
|
3
1
|
/**
|
|
4
2
|
* Anthropic rejects a `tool_use.id` longer than this. Collision disambiguation has to fit
|
|
5
3
|
* inside it too, which is why candidates are assembled from parts instead of sliced at the end.
|
|
@@ -27,7 +25,7 @@ function toolCallIdComponents(rawId: string | undefined): { cleaned: string; has
|
|
|
27
25
|
const raw = rawId ?? "";
|
|
28
26
|
if (raw.length === 0) return undefined;
|
|
29
27
|
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
30
|
-
const hash =
|
|
28
|
+
const hash = Bun.SHA256.hash(raw, "hex").slice(0, TOOL_CALL_ID_HASH_WIDTH);
|
|
31
29
|
return { cleaned, hash };
|
|
32
30
|
}
|
|
33
31
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const schemaMaps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
|
|
2
|
+
const schemaLists = new Set(["anyOf", "oneOf", "allOf", "prefixItems"]);
|
|
3
|
+
const schemaValues = new Set(["items", "additionalProperties", "unevaluatedProperties", "contains", "not", "if", "then", "else", "propertyNames"]);
|
|
4
|
+
const jsonTypes = new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
|
|
5
|
+
|
|
6
|
+
/** Normalize schemas only; defaults, examples and property names are data, never schemas. */
|
|
7
|
+
export function workBuddySchema(value: unknown, depth = 0): Record<string, unknown> {
|
|
8
|
+
if (depth > 64) throw new Error("WorkBuddy AI tool schema exceeds maximum depth");
|
|
9
|
+
if (value === false) return { not: {} };
|
|
10
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
11
|
+
const input = value as Record<string, unknown>, out = { ...input };
|
|
12
|
+
for (const [key, child] of Object.entries(input)) {
|
|
13
|
+
if (schemaMaps.has(key) && child && typeof child === "object" && !Array.isArray(child)) {
|
|
14
|
+
out[key] = Object.fromEntries(Object.entries(child).map(([name, schema]) => [name, workBuddySchema(schema, depth + 1)]));
|
|
15
|
+
} else if (schemaLists.has(key) && Array.isArray(child)) {
|
|
16
|
+
out[key] = child.map(schema => workBuddySchema(schema, depth + 1));
|
|
17
|
+
} else if (schemaValues.has(key)) {
|
|
18
|
+
if ((key === "additionalProperties" || key === "unevaluatedProperties") && typeof child === "boolean") continue;
|
|
19
|
+
out[key] = key === "items" && Array.isArray(child)
|
|
20
|
+
? { anyOf: child.map(schema => workBuddySchema(schema, depth + 1)) } : workBuddySchema(child, depth + 1);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (typeof out.pattern === "string") out.pattern = out.pattern.replace(/\\\\|\\0(?![0-9])/g, match => match === "\\0" ? "\\u0000" : match);
|
|
24
|
+
if (out.required !== undefined && !Array.isArray(out.required)) delete out.required;
|
|
25
|
+
if (typeof out.type === "string") {
|
|
26
|
+
out.type = out.type.toLowerCase();
|
|
27
|
+
if (!jsonTypes.has(out.type as string)) delete out.type;
|
|
28
|
+
}
|
|
29
|
+
if (Array.isArray(out.enum)) {
|
|
30
|
+
if (!out.enum.length) delete out.enum;
|
|
31
|
+
else if (out.type === undefined) {
|
|
32
|
+
const groups = new Map<string, unknown[]>();
|
|
33
|
+
for (const item of out.enum) {
|
|
34
|
+
const type = item === null ? "null" : Array.isArray(item) ? "array" : typeof item;
|
|
35
|
+
const values = groups.get(type) ?? []; values.push(item); groups.set(type, values);
|
|
36
|
+
}
|
|
37
|
+
if (groups.size === 1) out.type = groups.keys().next().value;
|
|
38
|
+
else {
|
|
39
|
+
const union = { anyOf: [...groups].map(([type, values]) => ({ type, enum: values })) };
|
|
40
|
+
out.allOf = [...(Array.isArray(out.allOf) ? out.allOf : []), union];
|
|
41
|
+
delete out.enum;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function workBuddyToolParameters(value: unknown): Record<string, unknown> {
|
|
49
|
+
const out = workBuddySchema(value);
|
|
50
|
+
const properties: Record<string, unknown> = { ...(out.properties as Record<string, unknown> ?? {}) };
|
|
51
|
+
const required = new Set(Array.isArray(out.required) ? out.required.filter(x => typeof x === "string") : []);
|
|
52
|
+
for (const key of ["anyOf", "oneOf", "allOf"]) {
|
|
53
|
+
for (const variant of Array.isArray(out[key]) ? out[key] : []) {
|
|
54
|
+
const row = variant as Record<string, unknown>;
|
|
55
|
+
Object.assign(properties, row.properties);
|
|
56
|
+
if (key === "allOf" && Array.isArray(row.required)) for (const field of row.required) if (typeof field === "string") required.add(field);
|
|
57
|
+
}
|
|
58
|
+
delete out[key];
|
|
59
|
+
}
|
|
60
|
+
return { ...out, type: "object", properties, ...(required.size ? { required: [...required] } : {}) };
|
|
61
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { createHmac, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import type { ProviderAdapter } from "./base";
|
|
3
|
+
import { workBuddyToolParameters } from "./workbuddy-schema";
|
|
4
|
+
import { retainTranslatedEvent, releaseTranslatedEvent } from "../lib/translator-budget";
|
|
5
|
+
import { createOpenAIChatAdapter } from "./openai-chat";
|
|
6
|
+
import type { AdapterEvent, OcxProviderConfig } from "../types";
|
|
7
|
+
import { assertWorkBuddyDestination, WORKBUDDY_BASE_URL, workBuddyHeaders } from "../providers/workbuddy";
|
|
8
|
+
|
|
9
|
+
const sessionSalt = randomBytes(32);
|
|
10
|
+
const opaqueId = (value: unknown) => createHmac("sha256", sessionSalt).update(JSON.stringify(value)).digest("hex").slice(0, 32);
|
|
11
|
+
|
|
12
|
+
export function createWorkBuddyAdapter(provider: OcxProviderConfig): ProviderAdapter {
|
|
13
|
+
const base = createOpenAIChatAdapter({ ...provider, adapter: "openai-chat", baseUrl: WORKBUDDY_BASE_URL, headers: undefined });
|
|
14
|
+
return {
|
|
15
|
+
...base, name: "workbuddy-ai",
|
|
16
|
+
async buildRequest(parsed, incoming) {
|
|
17
|
+
assertWorkBuddyDestination(provider.baseUrl);
|
|
18
|
+
if (!provider.apiKey || !parsed._workbuddyAuthContext) throw new Error("WorkBuddy AI account unavailable; run ocx login workbuddy-ai");
|
|
19
|
+
const req = await base.buildRequest({ ...parsed, stream: true }, incoming);
|
|
20
|
+
const body = JSON.parse(req.body);
|
|
21
|
+
const messages = body.messages as Array<Record<string, unknown>>;
|
|
22
|
+
for (const message of messages) if (message.role === "developer") message.role = "system";
|
|
23
|
+
if (messages[0]?.role !== "system") messages.unshift({ role: "system", content: "You are a helpful assistant." });
|
|
24
|
+
if (body.max_completion_tokens !== undefined) { body.max_tokens = body.max_completion_tokens; delete body.max_completion_tokens; }
|
|
25
|
+
if (body.tool_choice === "none") { delete body.tools; delete body.tool_choice; }
|
|
26
|
+
else if (body.tool_choice?.type === "function") body.tool_choice = body.tool_choice.function.name;
|
|
27
|
+
for (const tool of body.tools ?? []) {
|
|
28
|
+
if (tool.type === "function") tool.function.parameters = workBuddyToolParameters(tool.function.parameters);
|
|
29
|
+
}
|
|
30
|
+
const users = messages.map((m, index) => ({ m, index })).filter(({ m }) => m.role === "user");
|
|
31
|
+
const session = parsed._codexOwnThreadId || parsed._clientThreadId
|
|
32
|
+
|| (!parsed._promptCacheKeyIsSharedCohort ? parsed.options.promptCacheKey : undefined)
|
|
33
|
+
|| incoming.headers.get("session_id") || incoming.headers.get("x-session-id");
|
|
34
|
+
const conversation = session || users[0]?.m.content;
|
|
35
|
+
const latest = users.at(-1);
|
|
36
|
+
const requestId = randomUUID().replaceAll("-", "");
|
|
37
|
+
const headers = {
|
|
38
|
+
"Content-Type": "application/json", Accept: "text/event-stream",
|
|
39
|
+
...workBuddyHeaders(provider.apiKey, parsed._workbuddyAuthContext),
|
|
40
|
+
"X-Request-ID": requestId, "X-Conversation-Message-ID": requestId,
|
|
41
|
+
"X-Conversation-Request-ID": latest ? opaqueId([conversation, latest.index, latest.m.content]) : requestId,
|
|
42
|
+
...(conversation ? { "X-Conversation-ID": opaqueId(conversation) } : {}),
|
|
43
|
+
};
|
|
44
|
+
return { ...req, url: `${WORKBUDDY_BASE_URL}/chat/completions`, headers, body: JSON.stringify(body), redirect: "error" as const };
|
|
45
|
+
},
|
|
46
|
+
async parseResponse(response, budget, tier) {
|
|
47
|
+
const events: AdapterEvent[] = [];
|
|
48
|
+
try {
|
|
49
|
+
for await (const event of base.parseStream(response, budget, tier)) {
|
|
50
|
+
retainTranslatedEvent(event, budget, events.at(-1));
|
|
51
|
+
events.push(event);
|
|
52
|
+
}
|
|
53
|
+
return events;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
for (const event of events) releaseTranslatedEvent(event, budget);
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
formatErrorBody(status, _headers, payload) {
|
|
60
|
+
let code: unknown;
|
|
61
|
+
try { code = JSON.parse(payload)?.code; } catch { /* Only structured numeric codes are public. */ }
|
|
62
|
+
if (Number(code) === 11128) return "WorkBuddy AI rejected this client channel (11128).";
|
|
63
|
+
if (Number(code) === 11140) return "WorkBuddy AI restricted this account (11140); contact WorkBuddy support.";
|
|
64
|
+
if (Number(code) === 14018) return "WorkBuddy AI credits exhausted (14018).";
|
|
65
|
+
return `WorkBuddy AI request failed (HTTP ${status}).`;
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
package/src/bridge/errors.ts
CHANGED
|
@@ -12,6 +12,10 @@ import {
|
|
|
12
12
|
cyberPolicyErrorType,
|
|
13
13
|
CYBER_POLICY_ERROR_CODE,
|
|
14
14
|
isCyberPolicyCode,
|
|
15
|
+
isModelNotInPlanRefusal,
|
|
16
|
+
markVerifiedModelNotInPlanResponse,
|
|
17
|
+
MODEL_NOT_IN_PLAN_CODE,
|
|
18
|
+
REQUIRED_TOOL_CONTRACT_CODE,
|
|
15
19
|
SPEND_LEDGER_STORAGE_UNAVAILABLE_CODE,
|
|
16
20
|
UNDECLARED_TOOL_CALL_ERROR_CODE,
|
|
17
21
|
type OcxErrorPayload,
|
|
@@ -54,6 +58,11 @@ export function formatErrorResponse(
|
|
|
54
58
|
// survives so the Anthropic translator can classify it instead of folding it into a
|
|
55
59
|
// retryable overload (and so clients see the SSE path's rejection identity).
|
|
56
60
|
if (options?.code === UNDECLARED_TOOL_CALL_ERROR_CODE) error.code = options.code;
|
|
61
|
+
if (options?.code === REQUIRED_TOOL_CONTRACT_CODE && error.code !== CYBER_POLICY_ERROR_CODE) error.code = options.code;
|
|
62
|
+
// A plan refusal keeps its wire code so clients can branch on it. The code is not provenance:
|
|
63
|
+
// run-turn combo children pass an adapter event's own code here, so only the boundary that
|
|
64
|
+
// verified the refusal marks the envelope (`markVerifiedModelNotInPlanResponse`).
|
|
65
|
+
if (options?.code === MODEL_NOT_IN_PLAN_CODE) error.code = options.code;
|
|
57
66
|
// Only the allowlisted transport verdicts survive this formatter. Do not forward
|
|
58
67
|
// arbitrary provider codes, and preserve the existing cyber-policy precedence.
|
|
59
68
|
const replayBlocked = error.code !== CYBER_POLICY_ERROR_CODE
|
|
@@ -80,6 +89,7 @@ export function formatErrorResponse(
|
|
|
80
89
|
// and no wait of its own does not stop a client that retries every 429 by default.
|
|
81
90
|
const refusal = isReplayRefusalCode(error.code) && replayBlocked;
|
|
82
91
|
if (refusal) applyReplayRefusalClientHeaders(headers);
|
|
92
|
+
if (error.code === REQUIRED_TOOL_CONTRACT_CODE && finalStatus === 400) applyReplayRefusalClientHeaders(headers);
|
|
83
93
|
const response = new Response(JSON.stringify({ error }), {
|
|
84
94
|
status: finalStatus,
|
|
85
95
|
headers,
|
|
@@ -92,6 +102,23 @@ export function formatErrorResponse(
|
|
|
92
102
|
return response;
|
|
93
103
|
}
|
|
94
104
|
|
|
105
|
+
/**
|
|
106
|
+
* `formatErrorResponse` for an upstream failure that may be the adapter-normalized plan refusal
|
|
107
|
+
* (#7684). Only a verified refusal (`isModelNotInPlanRefusal` on the response the adapter marked)
|
|
108
|
+
* keeps `model_not_in_plan` and carries the in-memory mark policy fallback reads; the wire code
|
|
109
|
+
* alone is never provenance. Every other failure formats exactly as `formatErrorResponse` does.
|
|
110
|
+
*/
|
|
111
|
+
export function formatUpstreamFailureResponse(
|
|
112
|
+
source: Response,
|
|
113
|
+
sourceCode: string | undefined,
|
|
114
|
+
...[status, type, message, options]: Parameters<typeof formatErrorResponse>
|
|
115
|
+
): Response {
|
|
116
|
+
if (!isModelNotInPlanRefusal(source, sourceCode)) return formatErrorResponse(status, type, message, options);
|
|
117
|
+
const failure = formatErrorResponse(status, type, message, { ...options, code: MODEL_NOT_IN_PLAN_CODE });
|
|
118
|
+
markVerifiedModelNotInPlanResponse(failure);
|
|
119
|
+
return failure;
|
|
120
|
+
}
|
|
121
|
+
|
|
95
122
|
/**
|
|
96
123
|
* A spent usage window, in the shape the Codex client treats as final (#6991): HTTP 429 with
|
|
97
124
|
* `error.type: "usage_limit_reached"` and, when the reset is known, `resets_at` in epoch
|
|
@@ -253,7 +253,7 @@ function buildResponseJSONWithBudget(
|
|
|
253
253
|
const text = stripCitationMarkers(currentTextStr);
|
|
254
254
|
const sourceBytes = pendingWebSources.reduce((sum, source) => sum + bytesOf(JSON.stringify(source)), 0);
|
|
255
255
|
const annotations = pendingWebSources.map(s => ({
|
|
256
|
-
type: "url_citation", url: s.url,
|
|
256
|
+
type: "url_citation", url: s.url, title: s.title || s.url, start_index: 0, end_index: 0,
|
|
257
257
|
}));
|
|
258
258
|
pendingWebSources = [];
|
|
259
259
|
const item = {
|
package/src/bridge/sse.ts
CHANGED
|
@@ -488,7 +488,7 @@ export function bridgeToResponsesSSE(
|
|
|
488
488
|
const takeWebAnnotations = (): { type: string; url: string; title?: string; start_index: number; end_index: number }[] => {
|
|
489
489
|
if (pendingWebSources.length === 0) return [];
|
|
490
490
|
const anns = pendingWebSources.map(s => ({
|
|
491
|
-
type: "url_citation", url: s.url,
|
|
491
|
+
type: "url_citation", url: s.url, title: s.title || s.url, start_index: 0, end_index: 0,
|
|
492
492
|
}));
|
|
493
493
|
const annotationBytes = bytesOf(JSON.stringify(anns));
|
|
494
494
|
const reservation = budget?.reserveTransient(annotationBytes, { kind: "retained_collectors" });
|
package/src/bridge.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { adapterFailureFromMessage } from "./lib/errors";
|
|
2
2
|
|
|
3
|
-
export { formatErrorResponse, formatUsageLimitReachedResponse } from "./bridge/errors";
|
|
3
|
+
export { formatErrorResponse, formatUpstreamFailureResponse, formatUsageLimitReachedResponse } from "./bridge/errors";
|
|
4
4
|
export { setOwnedBudgetAbandonedMsForTests } from "./bridge/internal";
|
|
5
5
|
export { buildResponseJSON } from "./bridge/response-json";
|
|
6
6
|
export { bridgeToResponsesSSE } from "./bridge/sse";
|
package/src/chat/inbound.ts
CHANGED
|
@@ -672,9 +672,12 @@ function applyChatSettings(raw: ChatCompletionsRoutingBody, body: Rec): void {
|
|
|
672
672
|
|
|
673
673
|
const effort = resolveReasoningEffort(raw);
|
|
674
674
|
const summary = resolveReasoningSummary(raw);
|
|
675
|
-
|
|
675
|
+
const enabled = isRec(raw.reasoning) && typeof raw.reasoning.enabled === "boolean" ? raw.reasoning.enabled
|
|
676
|
+
: isRec(raw.thinking) && ["enabled", "disabled"].includes(String(raw.thinking.type)) ? raw.thinking.type === "enabled" : undefined;
|
|
677
|
+
if (effort || summary !== undefined || enabled !== undefined) {
|
|
676
678
|
body.reasoning = {
|
|
677
679
|
...(effort ? { effort } : {}),
|
|
680
|
+
...(enabled !== undefined ? { enabled } : {}),
|
|
678
681
|
summary: summary ?? "auto",
|
|
679
682
|
};
|
|
680
683
|
}
|
package/src/chat/outbound.ts
CHANGED
|
@@ -19,9 +19,11 @@ import {
|
|
|
19
19
|
CYBER_POLICY_ERROR_CODE,
|
|
20
20
|
isCyberPolicyCode,
|
|
21
21
|
isCyberPolicyMessage,
|
|
22
|
+
isTerminalRefusalCode,
|
|
22
23
|
UNDECLARED_TOOL_CALL_ERROR_CODE,
|
|
23
24
|
} from "../lib/errors";
|
|
24
25
|
import { redactSecretString } from "../lib/redact";
|
|
26
|
+
import { truncationReasonFor } from "../responses/truncated-stop-reason";
|
|
25
27
|
import { createSseBlockBuffer, sseDataPayload } from "../server/sse-payload-rewrite";
|
|
26
28
|
import { reasoningDetailEntriesForItem } from "./reasoning-details";
|
|
27
29
|
|
|
@@ -202,6 +204,10 @@ export function chatCompletionsStreamErrorPayload(
|
|
|
202
204
|
// The guard's deterministic refusal keeps its wire identity past classifyError's
|
|
203
205
|
// generic 5xx remap — same code the buffered Chat error and the SSE frame carry.
|
|
204
206
|
classified.code = UNDECLARED_TOOL_CALL_ERROR_CODE;
|
|
207
|
+
} else if (isTerminalRefusalCode(details?.code)) {
|
|
208
|
+
// A terminal refusal (e.g. `invalid_prompt` for a plan refusal on a later sidecar iteration)
|
|
209
|
+
// is a client error; its code survives so the client sees the refusal, not a server fault.
|
|
210
|
+
classified.code = details!.code!;
|
|
205
211
|
} else if (details?.code !== undefined && details.code !== null && !classified.code) {
|
|
206
212
|
classified.code = details.code;
|
|
207
213
|
}
|
|
@@ -229,7 +235,9 @@ export function chatCompletionsFailedResponse(error: Rec): { message: string; de
|
|
|
229
235
|
code,
|
|
230
236
|
...(code === "translation_buffer_limit"
|
|
231
237
|
? { status: 502, type: "upstream_error" }
|
|
232
|
-
|
|
238
|
+
// A terminal refusal code is a 400-class verdict; inferring status from its wording
|
|
239
|
+
// turned a permanent refusal into a retryable 502.
|
|
240
|
+
: { type, ...(isTerminalRefusalCode(code) ? { status: 400 } : {}) }),
|
|
233
241
|
},
|
|
234
242
|
};
|
|
235
243
|
}
|
|
@@ -243,8 +251,14 @@ export function chatCompletionsIncompleteOutcome(
|
|
|
243
251
|
reason: unknown,
|
|
244
252
|
message: unknown,
|
|
245
253
|
): { finishReason: "length" | "content_filter" } | { failMessage: string } {
|
|
246
|
-
|
|
247
|
-
|
|
254
|
+
// Upstream Responses endpoints do not all use OpenAI's `max_output_tokens`: Volcengine Ark
|
|
255
|
+
// (Coding Plan `/responses`) sends `incomplete_details.reason: "length"` for a hit output cap.
|
|
256
|
+
// Read the reason through the shared truncation vocabulary so such a turn ends with
|
|
257
|
+
// finish_reason "length" instead of a 502. Proxy reasons (adapter_eof, upstream_stall_timeout,
|
|
258
|
+
// missing_terminal_event) are not in that vocabulary and still fail.
|
|
259
|
+
const truncation = typeof reason === "string" ? truncationReasonFor(reason) : undefined;
|
|
260
|
+
if (truncation === "max_output_tokens") return { finishReason: "length" };
|
|
261
|
+
if (truncation === "content_filter") return { finishReason: "content_filter" };
|
|
248
262
|
const why = typeof reason === "string" ? reason : "unknown";
|
|
249
263
|
return {
|
|
250
264
|
failMessage: typeof message === "string" && message.length > 0
|
|
@@ -871,8 +885,8 @@ export function responsesJsonToChatCompletion(json: unknown, model: string, tran
|
|
|
871
885
|
const incomplete = isRec(body.incomplete_details) ? body.incomplete_details : {};
|
|
872
886
|
let incompleteFinish: "length" | "content_filter" | undefined;
|
|
873
887
|
if (body.status === "incomplete") {
|
|
874
|
-
|
|
875
|
-
|
|
888
|
+
const outcome = chatCompletionsIncompleteOutcome(incomplete.reason, undefined);
|
|
889
|
+
if ("finishReason" in outcome) incompleteFinish = outcome.finishReason;
|
|
876
890
|
else throw new ChatCompletionsStreamError("upstream response ended without a supported completion boundary", {
|
|
877
891
|
code: "upstream_incomplete", type: "upstream_error",
|
|
878
892
|
});
|
|
@@ -1052,7 +1066,7 @@ export async function collectChatCompletion(
|
|
|
1052
1066
|
const code = typeof parsed.error.code === "string" ? parsed.error.code : null;
|
|
1053
1067
|
const status = code === "translation_buffer_limit"
|
|
1054
1068
|
? 502
|
|
1055
|
-
: code
|
|
1069
|
+
: isTerminalRefusalCode(code) || isCyberPolicyMessage(message)
|
|
1056
1070
|
? 400
|
|
1057
1071
|
: streamErrorStatus(message);
|
|
1058
1072
|
const streamError = new ChatCompletionsStreamError(message, {
|
|
@@ -32,6 +32,32 @@ function isRec(value: unknown): value is Rec {
|
|
|
32
32
|
/** OpenRouter's `format` for Anthropic thinking entries. */
|
|
33
33
|
export const ANTHROPIC_REASONING_DETAIL_FORMAT = "anthropic-claude-v1";
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* One `reasoning.text` detail the inbound replay accepts as Anthropic state: Anthropic's format
|
|
37
|
+
* marker or no format at all, a text the client saw, and a signature with Anthropic's spelling.
|
|
38
|
+
* A client spelling the same signed block without OpenRouter's marker carries the same opaque
|
|
39
|
+
* state, so the native passthrough boundary must see it too.
|
|
40
|
+
*/
|
|
41
|
+
function isAnthropicSignedReasoningText(detail: Rec): detail is Rec & { text: string; signature: string } {
|
|
42
|
+
if (detail.type !== "reasoning.text") return false;
|
|
43
|
+
if (detail.format !== undefined && detail.format !== ANTHROPIC_REASONING_DETAIL_FORMAT) return false;
|
|
44
|
+
const signature = typeof detail.signature === "string" ? detail.signature : undefined;
|
|
45
|
+
return typeof detail.text === "string" && isLikelyRealAnthropicThinkingSignature(signature);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Whether a Chat body contains provider-issued Anthropic state that another provider must not
|
|
50
|
+
* see: a `reasoning_details` entry carrying Anthropic's format marker, or an unmarked signed
|
|
51
|
+
* `reasoning.text` entry the inbound replay would accept.
|
|
52
|
+
*/
|
|
53
|
+
export function chatBodyCarriesAnthropicReasoningState(body: Rec): boolean {
|
|
54
|
+
if (!Array.isArray(body.messages)) return false;
|
|
55
|
+
return body.messages.some(message => isRec(message)
|
|
56
|
+
&& Array.isArray(message.reasoning_details)
|
|
57
|
+
&& message.reasoning_details.some(detail => isRec(detail)
|
|
58
|
+
&& (detail.format === ANTHROPIC_REASONING_DETAIL_FORMAT || isAnthropicSignedReasoningText(detail))));
|
|
59
|
+
}
|
|
60
|
+
|
|
35
61
|
/** One closed reasoning item, as either outbound path sees it. */
|
|
36
62
|
export interface ReasoningDetailSource {
|
|
37
63
|
/** The thinking text the client was shown for this item. */
|
|
@@ -125,11 +151,8 @@ export function signedReasoningInputItems(details: unknown): Rec[] | undefined {
|
|
|
125
151
|
redacted.push(raw.data);
|
|
126
152
|
continue;
|
|
127
153
|
}
|
|
128
|
-
if (raw
|
|
129
|
-
|
|
130
|
-
const signature = typeof raw.signature === "string" ? raw.signature : undefined;
|
|
131
|
-
if (typeof raw.text !== "string" || !isLikelyRealAnthropicThinkingSignature(signature)) return undefined;
|
|
132
|
-
items.push(reasoningInputItem(raw.text, { sig: signature, ...(redacted.length > 0 ? { red: redacted } : {}) }));
|
|
154
|
+
if (!isAnthropicSignedReasoningText(raw)) return undefined;
|
|
155
|
+
items.push(reasoningInputItem(raw.text, { sig: raw.signature, ...(redacted.length > 0 ? { red: redacted } : {}) }));
|
|
133
156
|
redacted = [];
|
|
134
157
|
}
|
|
135
158
|
if (redacted.length > 0) items.push(reasoningInputItem("", { red: redacted }));
|