diff --git a/src/adapters/devin/cloud-direct/tool-schema.ts b/src/adapters/devin/cloud-direct/tool-schema.ts index 1a376f6750c..705ce5bedd4 100644 --- a/src/adapters/devin/cloud-direct/tool-schema.ts +++ b/src/adapters/devin/cloud-direct/tool-schema.ts @@ -9,12 +9,28 @@ * accept type arrays, so only the Gemini family is rewritten, and only that one * keyword: the full Google subset sanitizer would strip keywords this backend * accepts. + * + * Claude models behind the same wire answer `invalid_argument` for a root + * `oneOf` (#8302), as Anthropic rejects a root composition in any + * `input_schema`. Claude uids get the same root flattening as Claude Chat + * gateways; a schema without a root composition is passed through unchanged. */ +import { flattenClaudeRootToolParameters } from '../../openai-chat/tool-schema.js'; export function isDevinGeminiModelUid(modelUid: string): boolean { return /^gemini-/i.test(modelUid) || /^MODEL_GOOGLE_GEMINI_/i.test(modelUid); } +export function isDevinClaudeModelUid(modelUid: string): boolean { + return /^claude-/i.test(modelUid) || /^MODEL_CLAUDE_/i.test(modelUid); +} + +const ROOT_COMPOSITION_KEYS = ['oneOf', 'anyOf', 'allOf'] as const; + +function hasRootComposition(parameters: unknown): boolean { + return isSchema(parameters) && ROOT_COMPOSITION_KEYS.some((key) => Array.isArray(parameters[key])); +} + /** Keys whose values are instance data, not subschemas. */ const DATA_KEYS = new Set(['enum', 'const', 'default', 'examples', 'example']); /** Keys whose values map arbitrary names (which may be "enum" or "default") to subschemas. */ @@ -79,7 +95,9 @@ function rewrite(node: unknown): unknown { return splitTypeArray(out, types); } -/** Rewrite type arrays for Gemini uids; every other model gets the schema unchanged. */ +/** Rewrite type arrays for Gemini uids and root compositions for Claude uids; others are unchanged. */ export function normalizeDevinToolParameters(modelUid: string, parameters: unknown): unknown { - return isDevinGeminiModelUid(modelUid) ? rewrite(parameters) : parameters; + if (isDevinGeminiModelUid(modelUid)) return rewrite(parameters); + if (isDevinClaudeModelUid(modelUid) && hasRootComposition(parameters)) return flattenClaudeRootToolParameters(parameters); + return parameters; } diff --git a/src/adapters/openai-chat/tool-schema.ts b/src/adapters/openai-chat/tool-schema.ts index e502358e7ab..2d10a5905a5 100644 --- a/src/adapters/openai-chat/tool-schema.ts +++ b/src/adapters/openai-chat/tool-schema.ts @@ -162,6 +162,15 @@ function isClaudeModelId(modelId: string | undefined): boolean { return tail.startsWith("claude-"); } +/** + * The Claude root flattening above, for other wires that front Claude with a translated tool + * schema (Devin's GetChatMessage). Root oneOf/anyOf/allOf branches merge into one object; + * nested schemas, property values and literal data are copied as they are. + */ +export function flattenClaudeRootToolParameters(parameters: unknown): Record { + return ensureZenRootObjectSchema(parameters, false); +} + function isAzureOpenAiChatTarget(provider: OcxProviderConfig): boolean { try { const host = new URL(provider.baseUrl).hostname.toLowerCase(); diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md index f1cc933c626..39e147b36a9 100644 --- a/structure/providers-and-adapters.md +++ b/structure/providers-and-adapters.md @@ -212,7 +212,7 @@ rewrite rules and the routed-id settlement. | `src/adapters/azure.ts` | Azure OpenAI bridge; optional `minMaxOutputTokens` raises only smaller explicit positive integer output budgets. Unset preserves caller caps. Serialization and pre-admission spend estimates share `effectiveAzureOutputBudget`; see the [spend contract](transports/responses-spend.md#durable-spend-reservations). | | `src/adapters/cursor.ts`, `src/adapters/cursor/` | Cursor protobuf transport: discovery, request builder, event decoding, MCP, thread continuity, native-exec policy. | | `src/adapters/zed.ts`, `src/providers/zed.ts`, `src/oauth/zed.ts` | Zed Hosted AI native-app RSA login, account-scoped short-lived LLM-token exchange, bounded live model discovery, and provider-envelope translation through the existing Anthropic, Google, Responses, and Chat builders. Buffered delivery retains events under the shared translator budget and cancels delegated streams on early exit. The Responses delegate applies destination compatibility, strips OpenAI-private fields and unsupported built-in tools, reconciles removed tool choices through the shared hosted-tool policy, and maps OpenAI `developer` messages to Zed-supported `system` messages before wrapping the request. `src/adapters/zed-openai-stream.ts` translates the OpenAI stream: the current turn's `additional_tools` are promoted on a detached copy before replay repair, interleaved function and custom calls stay buffered until the oldest open call's authoritative item end or successful response terminal because adapter deltas are unkeyed, and end of stream or an incomplete response flushes only arguments that already arrived, marking unfinished calls incomplete. Text and reasoning wait behind an open call; invisible heartbeats report buffered progress. Item aliases share one execution identity and conflicting reuse fails closed. Missing tool names fail the turn, and no output follows a terminal error. Per-item reasoning and done-only text fallback suppress completed replays. A completed compaction item keeps its ciphertext on the done event and transfers that retained lease. Arguments, full snapshots, dedupe identities, queued events, text and opaque usage are budgeted and released on failure or cancellation; typed and untyped native error envelopes scrub every diagnostic string, including code/type, with the captured credential scrubber and discard diagnostic metadata before delegation. Untyped error envelopes terminate the OpenAI relay. Argument-done frames confirm bytes only; item status or successful response completion authorizes executable closure. Authoritative custom snapshots and every later delta agree byte-for-byte regardless of emission order; extensions or contradictions close outstanding calls incomplete and fail the turn. Function arguments compare ordered lexical JSON tokens for complete snapshots and replay fingerprints: whitespace outside strings is ignored, strings compare decoded Unicode units, number literals remain exact, and object-key order (including duplicate members) stays significant; compatible whitespace-adjusted prefixes append only a validated suffix and preserve delivered bytes. `src/adapters/zed-tool-arguments.ts` owns lexical reconciliation and domain-separated replay fingerprints. `src/adapters/zed-json-tokens.ts` scans JSON iteratively with a 65,536-container nesting limit, reporting a clear limit failure above it. Late fragments scan only new source units against retained authoritative tokens, including calls held behind another call; `tests/providers/zed-argument-consistency.test.ts` covers late, buffered and JSON/SSE cases. Failed terminals close outstanding calls incomplete and replay queued text/reasoning before the original error. Diagnostic usage retains only finite nonnegative numeric token counters through `src/adapters/zed-diagnostic-usage.ts`, including nested cache/reasoning counters; opaque extensions are discarded. `tests/providers/zed-failure-relay.test.ts` covers JSON/SSE failure projection and completion conflicts. `src/adapters/zed-additional-tools.ts` owns tool promotion, while `src/adapters/openai-responses/usage.ts` shares usage projection with Responses compaction. `tests/providers/zed-openai-contract.test.ts` covers the relay and client-boundary regressions. Experimental and unofficial; the Zed terms risk is intentionally surfaced in user docs and release review. | -| `src/adapters/devin.ts`, `src/adapters/devin/cloud-direct/` | Devin runTurn transport over Cognition Connect-RPC. Assistant reasoning replays as ChatMessagePrompt #11 thinking, #12 signature and #18 signature type (`src/adapters/devin/reasoning-signature.ts`): the #10/#21 pair arrives after the visible answer and becomes its own signature-only reasoning item, so a single unsigned thinking block plus exactly one signature-only block is replayed as one signed prompt, and a signature-only turn (GPT, Gemini) is replayed rather than dropped. An Anthropic signature is replayed, but because the streamed thinking is a summary the signature may not cover, a turn Cognition refuses with `invalid_argument` before any visible output (reasoning alone does not count) is retried once with Anthropic signatures withheld and the thinking text kept. `GetChatMessage` uses the Responses provider executor and shared physical-send budget; catalog, JWT, and `src/web-search/devin-executor.ts` native search support RPCs remain outside inference-send accounting. Provider-stated pre-output 429 reset delays are surfaced immediately by default, releasing shared active-turn capacity. A positive `OPENCODEX_DEVIN_STATED_RESET_WAIT_MS` explicitly enables bounded waiting and up to two replays on standalone turns, which hold that capacity until completion or cancellation. Combo children bypass that wait and surface a pre-output 429 so the next target can run. During an opted-in standalone wait, safe heartbeats commit the response preflight and keep the stream's stall watchdog fed. Invalid values fail closed to the immediate-refusal behavior. A recorded tenant host is used only for the stored account whose credential owns the transmitted key, searched in the configured provider id and then its deprecated alias; a configured, forwarded, or unmatched key uses the configured base URL or the US default. Native search previews the current route by effective adapter without mutating combo selection state, pins one admitted active-account snapshot for the request, and calls `GetWebSearchResults`, so it starts no CLI or second model. The wire model UID comes from the catalog's family metadata (`ClientModelConfig` #23/#30/#31): a family id with no effort anchors on the family's default member and selects the nearest enabled rung, rounding up first; an effort moves only the effort axis, to the lowest rung at or above it (else the highest below) while Fast Mode, 1M Context and the other axes stay at the anchor's values unless the caller asked for `fast` or a `1m` value; not lowering a requested effort outranks keeping those axes (an unranked member counts as lower), a disabled row the caller named is kept when the request still selects it so the preflight names that refusal, and resolution never leaves the family. Rows without family metadata fall back to suffix resolution, whose variant scan matches the collapsed base rather than a string prefix. With no caller or configured output cap, the selected row's catalog `maxOutputTokens` fills CompletionConfiguration #2; #3 is `max_newlines` and is sent at a fixed value, never a context window. The leading system text is sent as `GetChatMessage` #2, a failed tool result sets ChatMessagePrompt #9 and keeps an in-band `ERROR:` marker, and Gemini uids have JSON-Schema type arrays expressed as type-only `anyOf` branches in tool parameters. Shared constraints remain on the surrounding node, so nested schemas have one wire representation while outer enum/const, boolean constraints (including `not`, `oneOf`, and `allOf`) on null, and existing null-branch restrictions retain their conjunctive meaning. A null-only type keeps its null constraint even when an outer enum/const excludes null, preserving an unsatisfiable schema without producing an empty anyOf. Schema resource identifiers, anchors, definition maps, and existing anyOf branches remain on their original node. The type constraint is appended to existing allOf entries without shifting their indices, so JSON Pointer targets and reference scopes remain unchanged. A pre-output `invalid_argument` on a history whose word-piece estimate, using the sanitized and truncated tool descriptions actually sent on the wire, reaches 95% of the selected UID's catalog input window, capped by configured provider and model limits (512 KiB of text only when no window is known) is surfaced as `context_length_exceeded` so Codex compacts; a small request with the same code stays a plain 400. Known limit: a malformed schema on a history already at or above that 95% threshold is also reported as overflow because the upstream returns the same `invalid_argument`. The `COGNITION_BLOCKLIST_REWRITES` sanitizer rewrites exact phrases Cognition refuses with `permission_denied`; it runs only on instruction surfaces — tool descriptions and the #2 system prompt — while message text, replayed thinking (#11), and tool-call arguments stay byte-exact, because a rewrite there would silently change literal content such as patches or quoted file bytes; a trigger inside a data field surfaces as the upstream `permission_denied` instead (the Codex `` escalation boilerplate is the recorded #2 case). | +| `src/adapters/devin.ts`, `src/adapters/devin/cloud-direct/` | Devin runTurn transport over Cognition Connect-RPC. Assistant reasoning replays as ChatMessagePrompt #11 thinking, #12 signature and #18 signature type (`src/adapters/devin/reasoning-signature.ts`): the #10/#21 pair arrives after the visible answer and becomes its own signature-only reasoning item, so a single unsigned thinking block plus exactly one signature-only block is replayed as one signed prompt, and a signature-only turn (GPT, Gemini) is replayed rather than dropped. An Anthropic signature is replayed, but because the streamed thinking is a summary the signature may not cover, a turn Cognition refuses with `invalid_argument` before any visible output (reasoning alone does not count) is retried once with Anthropic signatures withheld and the thinking text kept. `GetChatMessage` uses the Responses provider executor and shared physical-send budget; catalog, JWT, and `src/web-search/devin-executor.ts` native search support RPCs remain outside inference-send accounting. Provider-stated pre-output 429 reset delays are surfaced immediately by default, releasing shared active-turn capacity. A positive `OPENCODEX_DEVIN_STATED_RESET_WAIT_MS` explicitly enables bounded waiting and up to two replays on standalone turns, which hold that capacity until completion or cancellation. Combo children bypass that wait and surface a pre-output 429 so the next target can run. During an opted-in standalone wait, safe heartbeats commit the response preflight and keep the stream's stall watchdog fed. Invalid values fail closed to the immediate-refusal behavior. A recorded tenant host is used only for the stored account whose credential owns the transmitted key, searched in the configured provider id and then its deprecated alias; a configured, forwarded, or unmatched key uses the configured base URL or the US default. Native search previews the current route by effective adapter without mutating combo selection state, pins one admitted active-account snapshot for the request, and calls `GetWebSearchResults`, so it starts no CLI or second model. The wire model UID comes from the catalog's family metadata (`ClientModelConfig` #23/#30/#31): a family id with no effort anchors on the family's default member and selects the nearest enabled rung, rounding up first; an effort moves only the effort axis, to the lowest rung at or above it (else the highest below) while Fast Mode, 1M Context and the other axes stay at the anchor's values unless the caller asked for `fast` or a `1m` value; not lowering a requested effort outranks keeping those axes (an unranked member counts as lower), a disabled row the caller named is kept when the request still selects it so the preflight names that refusal, and resolution never leaves the family. Rows without family metadata fall back to suffix resolution, whose variant scan matches the collapsed base rather than a string prefix. With no caller or configured output cap, the selected row's catalog `maxOutputTokens` fills CompletionConfiguration #2; #3 is `max_newlines` and is sent at a fixed value, never a context window. The leading system text is sent as `GetChatMessage` #2, a failed tool result sets ChatMessagePrompt #9 and keeps an in-band `ERROR:` marker, and Gemini uids have JSON-Schema type arrays expressed as type-only `anyOf` branches in tool parameters. Shared constraints remain on the surrounding node, so nested schemas have one wire representation while outer enum/const, boolean constraints (including `not`, `oneOf`, and `allOf`) on null, and existing null-branch restrictions retain their conjunctive meaning. A null-only type keeps its null constraint even when an outer enum/const excludes null, preserving an unsatisfiable schema without producing an empty anyOf. Schema resource identifiers, anchors, definition maps, and existing anyOf branches remain on their original node. The type constraint is appended to existing allOf entries without shifting their indices, so JSON Pointer targets and reference scopes remain unchanged. Claude uids (`claude-*`, `MODEL_CLAUDE_*`) whose tool parameters have a root `oneOf`, `anyOf` or `allOf` get the same root flattening as Claude Chat gateways (`flattenClaudeRootToolParameters` in `src/adapters/openai-chat/tool-schema.ts`), because Cognition refuses a root composition for Claude with `invalid_argument`; every other Claude schema is sent unchanged. A pre-output `invalid_argument` on a history whose word-piece estimate, using the sanitized and truncated tool descriptions actually sent on the wire, reaches 95% of the selected UID's catalog input window, capped by configured provider and model limits (512 KiB of text only when no window is known) is surfaced as `context_length_exceeded` so Codex compacts; a small request with the same code stays a plain 400. Known limit: a malformed schema on a history already at or above that 95% threshold is also reported as overflow because the upstream returns the same `invalid_argument`. The `COGNITION_BLOCKLIST_REWRITES` sanitizer rewrites exact phrases Cognition refuses with `permission_denied`; it runs only on instruction surfaces — tool descriptions and the #2 system prompt — while message text, replayed thinking (#11), and tool-call arguments stay byte-exact, because a rewrite there would silently change literal content such as patches or quoted file bytes; a trigger inside a data field surfaces as the upstream `permission_denied` instead (the Codex `` escalation boilerplate is the recorded #2 case). | | `src/adapters/kiro.ts` and `src/adapters/kiro/` | Kiro event/tool/thinking/truncation/retry handling, including an egress-aware completion fallback, fixed public HTTP 5xx text, and closed-set status/code diagnostics. The original path is a facade over leaves for wire identity, reasoning, conversation state, token estimation, payload assembly, streaming, and the adapter. | | `src/adapters/mimo-free.ts` | Mimo Free transport (client identity + JWT). Concurrent requests share one JWT bootstrap bound only to its timeout; each request stops waiting on its own abort without cancelling the others. Its registry entry is `deprecated`: existing saved providers keep the adapter and their stored configuration, while new-provider discovery (presets, the init menu, the featured list, and key logins) excludes it and `provider add` warns before creating one. | | `src/adapters/command-code.ts`, `src/adapters/command-code-tool-text.ts`, `src/adapters/command-code-restored-schema.ts` | Command Code OAuth NDJSON translation. For every `xiaomi/mimo-` model, text, native calls, reasoning, and terminal decisions share one byte-bounded queue with linear queue visits. Markup is deduplicated against matching native calls; text-only restoration requires one contiguous bare text block, a clean finish, a declared tool, and arguments validated against supported schema constraints. A parameter-free (freeform) block may omit `` but must end with ``; parameter blocks keep the canonical close. Markup appended after prose, including a marker in a later delta of the same text block, is held as a tail that can never mint a call: possible trailing marker prefixes stay in the same byte-accounted probe across deltas and release as text on a mismatch, boundary or end; a same-content native call strips a completed envelope as an echo, and anything else releases as presentation text so quoted examples stay inert. A tail waits only while a native input it could echo is open, counting the first later input of its own tool, so it is released as soon as those close without a match. Native, reasoning, and other intervening events interrupt a still-probing block but leave a held block held in arrival order, and the queued byte bound still flushes an unresolved envelope as text. An envelope the strict parser rejects but that opens with ``, closes with ``, and names a declared function is dropped when a native call for that same function arrives and on a clean finish; markup that parses but fits no supported schema is still released as text. Regex patterns, other unsupported constraints, and abnormal finishes fail closed. `tests/providers/command-code-tool-text-prose-split.test.ts` covers the prose boundary, the interleaved-event hold, and both drop paths. On OAuth rows the native fetch path normalizes only a 400 whose JSON is `success: false`, `error.code: "BAD_REQUEST"`, and message begins `You have insufficient credits to make this request.` to 429, adding `x-opencodex-refusal: insufficient-credits` and preserving the upstream status in `x-opencodex-upstream-status: 400`; ordinary 400s, other statuses, malformed or oversized bodies, and malformed UTF-8 stay untouched. Key and forward rows keep the 400, because a canonical key row has a same-key 429 retry ladder (`rateLimitRetryPolicyFor`) that would replay a credential with no credits left. A genuine upstream 429 keeps its own `Retry-After` and a 402 stays a 402 even when its body repeats the credit wording; `tests/providers/command-code-credit-failover.test.ts` pins that boundary and `tests/providers/command-code-credit-rotation.test.ts` drives the refusal through dispatch to the sibling account. On every auth mode a 403 whose JSON is `success: false`, `error.code: "FORBIDDEN"`, and message begins `MODEL_NOT_IN_PLAN` (then `:` or the end) becomes a 400 `invalid_request_error` with code `model_not_in_plan`, fixed copy naming the model, `x-opencodex-refusal: model-not-in-plan` and `x-opencodex-upstream-status: 403` (#7684): Codex reconnects on any 403 through its retry budget but ends the turn on a 400. The upstream detail is never quoted, so its free text cannot reach logs or steer the quota and reasoning-effort classifiers, and the effort repair skips the refusal. `isModelNotInPlanRefusal` in `src/lib/errors.ts` trusts the code only on a response object the adapter marked in memory, since an upstream can forge both the code and the diagnostic header; `formatErrorResponse` keeps it as the wire code, only the verifying boundaries (`formatUpstreamFailureResponse` in `src/bridge/errors.ts`, called by `adapter-dispatch.ts`, and `consumeComboFailure`) mark the envelope in memory (carried across the `src/server/responses/core-lifetime.ts` wrappers), `consumeComboFailure` drops an unmarked echo in any spelling failover folds into that code, and `comboFailureDecision` in `src/combos/failover.ts` hops past the refusal only with that caller-supplied provenance (combo or policy fallback; never a bare, passthrough or streamed code) while `comboFailureCooldownScope` cools only that target. The web-search and image sidecar loops keep a verified refusal's fixed copy without a wire-model name, code and mark in their own error envelope (`verifiedPlanRefusalMessage`), and `src/server/responses/sidecar-execution.ts` carries the mark across its stream wrappers; a later iteration's refusal inside an already committed 200 stream ends as `invalid_prompt` (`MODEL_NOT_IN_PLAN_STREAM_CODE`) with `retryable: false` and the same copy, because Codex reconnects on any other `response.failed` code. No account, key or provider cooldown is recorded. `tests/providers/command-code-plan-denial.test.ts` covers lookalikes, malformed bodies, abort, the Responses, Chat and Messages inbound paths, combo and policy hops, and an unmarked echo. | diff --git a/tests/providers/devin-chat-wire-fixes.test.ts b/tests/providers/devin-chat-wire-fixes.test.ts index eceadc3b438..c7bf5eaa524 100644 --- a/tests/providers/devin-chat-wire-fixes.test.ts +++ b/tests/providers/devin-chat-wire-fixes.test.ts @@ -495,6 +495,48 @@ describe("Gemini tool schema type arrays", () => { }); }); +describe("Claude root composition (#8302)", () => { + // The issue's probe: Claude behind GetChatMessage answers invalid_argument for a root oneOf. + const probe = { + oneOf: [ + { type: "object", properties: { a: { type: "string" } }, required: ["a"], additionalProperties: false }, + { type: "object", properties: { b: { type: "string" } }, required: ["b"], additionalProperties: false }, + ], + }; + const flat = (uid: string, parameters: unknown) => normalizeDevinToolParameters(uid, parameters) as Record; + + test("claude uids flatten a root oneOf into one object schema", () => { + const out = flat("claude-opus-5-5", probe); + expect(out.oneOf).toBeUndefined(); + expect(out.type).toBe("object"); + expect(out.properties).toEqual({ a: { type: "string" }, b: { type: "string" } }); + // oneOf branches are alternatives, so neither branch's required list holds for every call. + expect(out.required).toBeUndefined(); + }); + + test("root anyOf and allOf flatten too; allOf keeps its required names", () => { + const anyOf = flat("claude-sonnet-5-low", { anyOf: probe.oneOf }); + expect(anyOf.anyOf).toBeUndefined(); + expect(Object.keys(anyOf.properties as object)).toEqual(["a", "b"]); + const allOf = flat("MODEL_CLAUDE_4_SONNET", { allOf: probe.oneOf }); + expect(allOf.allOf).toBeUndefined(); + expect(allOf.required).toEqual(["a", "b"]); + }); + + test("the encoded claude request carries no root composition", () => { + const tools = [{ name: "probe", description: "Probe tool.", parameters: probe }]; + const claude = build([{ role: "user", content: "x" }], { tools, modelUid: "claude-opus-5-5" }); + expect(claude.includes(Buffer.from('"oneOf"'))).toBe(false); + expect(claude.includes(Buffer.from('"properties":{"a":{"type":"string"},"b":{"type":"string"}}'))).toBe(true); + }); + + test("claude schemas without a root composition, and non-claude uids, are untouched", () => { + const plain = { type: "object", properties: { x: { oneOf: [{ type: "string" }, { type: "number" }] } } }; + expect(normalizeDevinToolParameters("claude-opus-5-5", plain)).toBe(plain); + expect(normalizeDevinToolParameters("swe-2", probe)).toBe(probe); + }); +}); + describe("oversized history classification", () => { // One word piece per "word ", so `words` is the estimate. const history = (words: number): ChatHistoryItem[] => [{ role: "user", content: "word ".repeat(words) }];