Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(custom-endpoints): declare the request shape in a `wire` block
Jack Rudenkoa2259c7270e9
diff --git a/packages/cli/src/config-schema.test.ts b/packages/cli/src/config-schema.test.tsindex 315a256f..95cc7e47 100644--- a/packages/cli/src/config-schema.test.ts+++ b/packages/cli/src/config-schema.test.ts@@ -199,3 +199,80 @@ describe("CustomEndpointSchema (discriminated union)", () => {).toThrow();});});++describe("custom endpoint declared wire", () => {+ const wire = {+ tokenParam: "max_tokens",+ reasoning: {+ enable: [{ path: "/chat_template_kwargs/enable_thinking", value: true }],+ disable: [{ path: "/chat_template_kwargs/enable_thinking", value: false }],+ effort: {+ path: "/reasoning_effort",+ values: { low: "small", high: "large" },+ default: "low",+ },+ },+ };+ for (const kind of ["simple", "complex"] as const) {+ const endpoint = (transport: string, declared: unknown): unknown =>+ kind === "simple"+ ? {+ kind,+ url: "https://example.invalid/v1",+ format: transport,+ apiKey: "fake",+ wire: declared,+ }+ : {+ kind,+ displayName: "Test",+ baseUrl: "https://example.invalid",+ transport,+ apiKey: "fake",+ wire: declared,+ };+ test.each(["chat-completions", "responses"])(`${kind} openai accepts %s`, (api) => {+ const input = endpoint("openai", { ...wire, api });+ expect(input).toEqual(CustomEndpointSchema.parse(input));+ });+ test(`${kind} anthropic accepts Messages and none`, () => {+ const input = endpoint("anthropic", { api: "anthropic-messages", tokenParam: "none" });+ expect(input).toEqual(CustomEndpointSchema.parse(input));+ });+ test(`${kind} rejects an API incompatible with its transport`, () => {+ expect(+ CustomEndpointSchema.safeParse(endpoint("openai", { api: "anthropic-messages" })).success+ ).toBe(false);+ expect(+ CustomEndpointSchema.safeParse(endpoint("anthropic", { api: "responses" })).success+ ).toBe(false);+ if (kind === "complex") {+ expect(+ CustomEndpointSchema.safeParse(endpoint("litellm", { api: "responses" })).success+ ).toBe(false);+ expect(+ CustomEndpointSchema.safeParse(endpoint("litellm", { api: "chat-completions" })).success+ ).toBe(true);+ }+ });+ test.each(["enable", "disable", "effort"])(+ `${kind} %s pointer requires a leading slash`,+ (field) => {+ const value =+ field === "effort" ? { path: "reasoning_effort" } : [{ path: "thinking", value: true }];+ expect(+ CustomEndpointSchema.safeParse(endpoint("openai", { reasoning: { [field]: value } }))+ .success+ ).toBe(false);+ }+ );+ test(`${kind} accepts empty wire and identity effort declaration`, () => {+ expect(CustomEndpointSchema.safeParse(endpoint("openai", {})).success).toBe(true);+ expect(+ CustomEndpointSchema.safeParse(+ endpoint("openai", { reasoning: { effort: { path: "/effort" } } })+ ).success+ ).toBe(true);+ });+ }+});diff --git a/packages/cli/src/config-schema.ts b/packages/cli/src/config-schema.tsindex 6f84850c..a38902f6 100644--- a/packages/cli/src/config-schema.ts+++ b/packages/cli/src/config-schema.ts@@ -74,6 +74,69 @@ function requireKeyUnlessNoAuth<}}+const WireValueSchema = z.union([z.string(), z.number(), z.boolean()]);++/** RFC 6901 pointer into the request body root, e.g. `/reasoning/effort`. */+const WirePointerSchema = z.string().startsWith("/");++const WireAssignmentSchema = z.object({ path: WirePointerSchema, value: WireValueSchema });++/**+ * How a custom endpoint is called, declared by the user — the same vocabulary+ * the cloud models catalog publishes per connection (`wire`), because a custom+ * endpoint has no catalog connection and claudish never guesses one from the+ * model name. Every field is optional; the documented defaults are:+ *+ * api the transport's API (openai → chat-completions, anthropic →+ * anthropic-messages); an openai endpoint may say "responses"+ * tokenParam max_tokens (chat, messages) / max_output_tokens (responses);+ * "none" sends no output limit+ * reasoning nothing sent. Declare `effort.path` (and optionally `values`,+ * mapping claudish's effort names none…max to the endpoint's own+ * values; identity when omitted), `enable`, `disable`.+ */+export const CustomEndpointWireSchema = z.object({+ api: z.enum(["chat-completions", "responses", "anthropic-messages"]).optional(),+ tokenParam: z+ .enum(["max_tokens", "max_completion_tokens", "max_output_tokens", "none"])+ .optional(),+ reasoning: z+ .object({+ enable: z.array(WireAssignmentSchema).optional(),+ disable: z.array(WireAssignmentSchema).optional(),+ effort: z+ .object({+ path: WirePointerSchema,+ values: z.record(z.string(), WireValueSchema).optional(),+ default: z.string().optional(),+ })+ .optional(),+ })+ .optional(),+});++/** A declared `wire.api` must be one the endpoint's transport can speak. */+function requireWireApiForTransport(+ transport: string,+ wire: z.infer<typeof CustomEndpointWireSchema> | undefined,+ ctx: z.RefinementCtx+): void {+ const api = wire?.api;+ if (!api) return;+ const allowed: Record<string, string[]> = {+ openai: ["chat-completions", "responses"],+ litellm: ["chat-completions"],+ anthropic: ["anthropic-messages"],+ };+ if (allowed[transport] && !allowed[transport].includes(api)) {+ ctx.addIssue({+ code: "custom",+ path: ["wire", "api"],+ message: `wire.api "${api}" is not spoken by the ${transport} transport (use ${allowed[transport].join(" or ")})`,+ });+ }+}+// "Simple" custom endpoint: just URL + format + key.// Reuses existing OpenAI/Anthropic format converters and a generic transport.export const CustomEndpointSimpleSchema = z@@ -91,8 +154,12 @@ export const CustomEndpointSimpleSchema = zauthScheme: CustomEndpointAuthSchemeSchema.optional(),modelPrefix: z.string().optional(),models: z.array(z.string()).optional(),+ wire: CustomEndpointWireSchema.optional(),})- .superRefine(requireKeyUnlessNoAuth);+ .superRefine((ep, ctx) => {+ requireKeyUnlessNoAuth(ep, ctx);+ requireWireApiForTransport(ep.format, ep.wire, ctx);+ });// "Complex" custom endpoint: a runtime PROVIDER_PROFILES entry.// All ProviderProfile fields, with reasonable defaults documented in Phase 3.@@ -111,8 +178,12 @@ export const CustomEndpointComplexSchema = z.optional(),modelPrefix: z.string().optional(),models: z.array(z.string()).optional(),+ wire: CustomEndpointWireSchema.optional(),})- .superRefine(requireKeyUnlessNoAuth);+ .superRefine((ep, ctx) => {+ requireKeyUnlessNoAuth(ep, ctx);+ requireWireApiForTransport(ep.transport, ep.wire, ctx);+ });export const CustomEndpointSchema = z.discriminatedUnion("kind", [CustomEndpointSimpleSchema,@@ -150,6 +221,7 @@ export const PredefinedEndpointsConfigSchema = z.object({enable: z.array(z.string()).optional(),});+export type CustomEndpointWire = z.infer<typeof CustomEndpointWireSchema>;export type CustomEndpointSimple = z.infer<typeof CustomEndpointSimpleSchema>;export type CustomEndpointComplex = z.infer<typeof CustomEndpointComplexSchema>;export type CustomEndpoint = z.infer<typeof CustomEndpointSchema>;diff --git a/packages/cli/src/providers/custom-endpoints-loader.ts b/packages/cli/src/providers/custom-endpoints-loader.tsindex df47108b..1a17a4f6 100644--- a/packages/cli/src/providers/custom-endpoints-loader.ts+++ b/packages/cli/src/providers/custom-endpoints-loader.ts@@ -23,6 +23,8 @@import { z } from "zod";import { AnthropicAPIFormat } from "../adapters/anthropic-api-format.js";+import type { BaseAPIFormat } from "../adapters/base-api-format.js";+import { CodexAPIFormat } from "../adapters/codex-api-format.js";import { LiteLLMAPIFormat } from "../adapters/litellm-api-format.js";import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";import { credentials } from "../auth/credentials/authority.js";@@ -37,6 +39,8 @@ import { ComposedHandler } from "../handlers/composed-handler.js";import type { RemoteProvider } from "../handlers/shared/remote-provider-types.js";import type { ModelHandler } from "../handlers/types.js";import type { ClaudishProfileConfig } from "../profile-config.js";+import type { WireApi } from "./connection-wire.js";+import { declaredConnection, declaredWire } from "./declared-wire.js";import { clearEndpointUnavailable, recordEndpointUnavailable } from "./endpoint-diagnostics.js";import {type RouteTier,@@ -464,23 +468,30 @@ function buildSimpleHandler(baseUrl: string): ModelHandler | null {const finalModel = ep.modelPrefix ? `${ep.modelPrefix}${ctx.modelName}` : ctx.modelName;+ // The request is shaped from what the endpoint DECLARES (its `wire` block,+ // or the documented defaults), never from the model name.+ const wire = declaredWire(+ ep.format === "openai" ? "chat-completions" : "anthropic-messages",+ ep.wire+ );+ const connection = declaredConnection(ctx.provider.name, finalModel, baseUrl, wire);if (ep.format === "openai") {const remoteProvider: RemoteProvider = {name: ctx.provider.name,baseUrl,- apiPath: "/chat/completions",+ apiPath: wire.api === "responses" ? "/responses" : "/chat/completions",apiKeyEnvVar: ctx.provider.apiKeyEnvVar,prefixes: ctx.provider.prefixes ?? [],headers: ctx.provider.headers,authScheme: "bearer",};const transport = new OpenAIProviderTransport(remoteProvider, finalModel, apiKey);- const adapter = new OpenAIAPIFormat(finalModel);return new ComposedHandler(transport, ctx.targetModel, finalModel, ctx.port, {- adapter,+ adapter: openAiFamilyAdapter(wire.api, finalModel),tokenStrategy: "delta-aware",...ctx.sharedOpts,+ connection,});}@@ -499,9 +510,17 @@ function buildSimpleHandler(return new ComposedHandler(transport, ctx.targetModel, finalModel, ctx.port, {adapter,...ctx.sharedOpts,+ connection,});}+/** Chat Completions or the generic Responses body, as the declared wire says. */+function openAiFamilyAdapter(api: WireApi, model: string): BaseAPIFormat {+ return api === "responses"+ ? new CodexAPIFormat(model, undefined, { codexExtras: false })+ : new OpenAIAPIFormat(model);+}+function buildComplexHandler(ep: CustomEndpointComplex,ctx: ProfileContext,@@ -509,7 +528,13 @@ function buildComplexHandler(baseUrl: string): ModelHandler | null {const finalModel = ep.modelPrefix ? `${ep.modelPrefix}${ctx.modelName}` : ctx.modelName;- const apiPath = ep.apiPath ?? "/v1/chat/completions";+ const wire = declaredWire(+ ep.transport === "anthropic" ? "anthropic-messages" : "chat-completions",+ ep.wire+ );+ const connection = declaredConnection(ctx.provider.name, finalModel, baseUrl, wire);+ const apiPath =+ ep.apiPath ?? (wire.api === "responses" ? "/v1/responses" : "/v1/chat/completions");switch (ep.transport) {case "litellm": {@@ -518,6 +543,7 @@ function buildComplexHandler(return new ComposedHandler(transport, ctx.targetModel, finalModel, ctx.port, {adapter,...ctx.sharedOpts,+ connection,});}case "openai": {@@ -532,11 +558,11 @@ function buildComplexHandler(streamFormatOverride: ep.streamFormat,};const transport = new OpenAIProviderTransport(remoteProvider, finalModel, apiKey);- const adapter = new OpenAIAPIFormat(finalModel);return new ComposedHandler(transport, ctx.targetModel, finalModel, ctx.port, {- adapter,+ adapter: openAiFamilyAdapter(wire.api, finalModel),tokenStrategy: "delta-aware",...ctx.sharedOpts,+ connection,});}case "anthropic": {@@ -555,6 +581,7 @@ function buildComplexHandler(return new ComposedHandler(transport, ctx.targetModel, finalModel, ctx.port, {adapter,...ctx.sharedOpts,+ connection,});}case "gemini":diff --git a/packages/cli/src/providers/declared-wire.test.ts b/packages/cli/src/providers/declared-wire.test.tsnew file mode 100644index 00000000..df595cda--- /dev/null+++ b/packages/cli/src/providers/declared-wire.test.ts@@ -0,0 +1,86 @@+import { expect, test } from "bun:test";+import { declaredConnection, declaredWire } from "./declared-wire.js";+import { shapeRequestFromWire } from "./wire-request.js";++test.each([+ ["chat-completions", "max_tokens"],+ ["anthropic-messages", "max_tokens"],+ ["responses", "max_output_tokens"],+] as const)("%s defaults to %s without reasoning", (api, tokenParam) => {+ const wire = declaredWire(api, undefined);+ expect(wire).toMatchObject({+ status: "known",+ api,+ tokenParam,+ reasoning: { status: "unknown" },+ });+ const body = {};+ shapeRequestFromWire(body, wire, { maxTokens: 512, hasTools: false });+ expect(body).toEqual({ [tokenParam]: 512 });+});++test("declared API overrides the transport and selects its token default", () => {+ expect(declaredWire("chat-completions", { api: "responses" })).toMatchObject({+ api: "responses",+ tokenParam: "max_output_tokens",+ });+});+test("explicit token field is honored and none removes the limit", () => {+ expect(declaredWire("chat-completions", { tokenParam: "max_completion_tokens" }).tokenParam).toBe(+ "max_completion_tokens"+ );+ const wire = declaredWire("responses", { tokenParam: "none" });+ expect(wire.tokenParam).toEqual({ status: "not_applicable" });+ const body: Record<string, unknown> = { max_tokens: 42 };+ shapeRequestFromWire(body, wire, { maxTokens: 512, hasTools: false });+ expect(body).toEqual({});+});+test("declared effort uses identity values and its default", () => {+ const wire = declaredWire("chat-completions", {+ reasoning: { effort: { path: "/reasoning_effort", default: "medium" } },+ });+ expect(wire.reasoning).toMatchObject({+ status: "supported",+ effort: {+ path: "/reasoning_effort",+ default: "medium",+ values: {+ none: "none",+ minimal: "minimal",+ low: "low",+ medium: "medium",+ high: "high",+ xhigh: "xhigh",+ max: "max",+ },+ },+ });+ const body = {};+ shapeRequestFromWire(body, wire, { hasTools: false });+ expect(body).toEqual({ reasoning_effort: "medium" });+});+test("enable and disable declarations are retained without inventing effort", () => {+ const reasoning = {+ enable: [{ path: "/thinking", value: true }],+ disable: [{ path: "/thinking", value: false }],+ };+ expect(declaredWire("chat-completions", { reasoning }).reasoning).toEqual({+ status: "supported",+ ...reasoning,+ effort: { status: "unknown" },+ mode: { status: "unknown" },+ });+});+test("declared connection identifies its endpoint and generation", () => {+ const wire = declaredWire("responses", undefined);+ expect(+ declaredConnection("custom", "qwen3-thinking", "https://example.invalid/v1", wire)+ ).toMatchObject({+ provider: "custom",+ modelId: "qwen3-thinking",+ externalModelId: "qwen3-thinking",+ generationId: "declared",+ wire,+ profile: { apis: { responses: { baseUrl: "https://example.invalid/v1" } } },+ });+});diff --git a/packages/cli/src/providers/declared-wire.ts b/packages/cli/src/providers/declared-wire.tsnew file mode 100644index 00000000..1f839756--- /dev/null+++ b/packages/cli/src/providers/declared-wire.ts@@ -0,0 +1,75 @@+/**+ * The wire of a custom endpoint: what its config DECLARES, never what a model+ * name suggests. A custom endpoint has no catalog connection, so the user's+ * `wire` block (config-schema.ts `CustomEndpointWireSchema`) plays that role,+ * and the request is shaped by the same step 5w a catalog connection uses.+ *+ * Defaults (documented in the schema): the API follows the transport; the+ * output limit is `max_tokens`, or `max_output_tokens` on Responses; no+ * reasoning field is sent unless declared; no mode or speed is offered.+ */+import type { CustomEndpointWire as DeclaredWire } from "../config-schema.js";+import type { ResolvedConnection } from "./connection-resolver.js";+import type { KnownWire, WireApi, WireAssignment, WireValue } from "./connection-wire.js";+import { WIRE_EFFORT_ORDER } from "./wire-request.js";++export function declaredWire(transportApi: WireApi, declared: DeclaredWire | undefined): KnownWire {+ const api: WireApi = declared?.api ?? transportApi;+ const tokenParam: KnownWire["tokenParam"] =+ declared?.tokenParam === "none"+ ? { status: "not_applicable" }+ : (declared?.tokenParam ?? (api === "responses" ? "max_output_tokens" : "max_tokens"));++ const r = declared?.reasoning;+ const assignments = (list: WireAssignment[] | undefined) =>+ list && list.length > 0 ? list : ({ status: "unknown" } as const);+ const reasoning: KnownWire["reasoning"] =+ r && (r.effort || r.enable?.length || r.disable?.length)+ ? {+ status: "supported",+ enable: assignments(r.enable),+ disable: assignments(r.disable),+ effort: r.effort+ ? {+ path: r.effort.path,+ values:+ r.effort.values ??+ (Object.fromEntries(WIRE_EFFORT_ORDER.map((name) => [name, name])) as Record<+ string,+ WireValue+ >),+ default: r.effort.default ?? { status: "unknown" },+ }+ : { status: "unknown" },+ mode: { status: "unknown" },+ }+ : { status: "unknown" };++ return {+ status: "known",+ api,+ tokenParam,+ toolsWithReasoning: { status: "unknown" },+ reasoning,+ speed: { status: "unknown" },+ evidence: [],+ };+}++/** A connection for a custom endpoint, carrying its declared wire. */+export function declaredConnection(+ endpointName: string,+ model: string,+ baseUrl: string,+ wire: KnownWire+): ResolvedConnection {+ return {+ provider: endpointName,+ modelId: model,+ route: { routeId: "custom-endpoint", routeProfileId: endpointName },+ externalModelId: model,+ wire,+ profile: { kind: "custom", apis: { [wire.api]: { baseUrl } } },+ generationId: "declared",+ };+}