Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs-site/src/content/docs/es/guides/claude-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -822,11 +822,12 @@ Claude Code declara la herramienta tipada `advisor_*`, como `advisor_20260301` c
- Otros destinos, incluidos GPT, Gemini y gateways sin esa opción, omiten la declaración y ejecutan sin asesor. No bloquea destinos de combos o alternativas.
- Si el [Advisor de OpenCodex](/es/reference/configuration/advisor/) está activo, controla el nombre `advisor` y no se reenvía la herramienta declarada; el registro indica `advisor-tool-shadowed-by-proxy-advisor`.
- Si la clave del cliente no admite el `model` declarado, se omite con `advisor-tool-outside-model-scope`; el carril Messages nativo administrado rechaza la solicitud.
- Si la política capturada para la solicitud tiene un límite de gasto en tokens aplicable por raíz, identidad o grupo de proveedor, se omiten la declaración del Advisor alojado, su historial completado y la beta. El turno principal continúa. En solicitudes enrutadas directamente, el registro indica `advisor-tool-withheld-by-spend-policy`. Se usa la política capturada para esa solicitud, con la cuenta y el grupo seleccionados; los cambios posteriores de configuración no alteran la decisión. Sin un límite aplicable se mantienen las reglas de reenvío anteriores.
- `server_tool_use` y `advisor_tool_result` llegan sin cambios, incluidos ID `srvtoolu_`, en streaming y sin él. Incluye `advisor_result`, `advisor_redacted_result` cifrado y `advisor_tool_result_error`. El contenido cifrado no se lee, reescribe ni registra.
- Al reenviar un intercambio completo en el historial, se conserva en su posición, con beta, solo hacia destinos que admiten la declaración. La entrada debe ser un objeto vacío y el resultado una de esas tres variantes; el resto se descarta.
- Una llamada pendiente al terminar con `pause_turn` o `tool_use` de cliente no se muestra ni reanuda. La siguiente solicitud conserva declaración y beta para consultar de nuevo.
- Si OpenCodex controla Advisor, también excluye los intercambios anteriores de Claude durante todo el turno para no cambiar el prompt a mitad.
- Los tokens del asesor se informan por separado y no se suman a los registros de uso, gasto de clave ni uso devuelto a Claude Code. Consulta su coste en Anthropic.
- OpenCodex no contabiliza por separado los tokens del asesor alojado en los registros de uso, el gasto de clave ni el uso devuelto a Claude Code. Por eso los límites de tokens omiten esta herramienta opcional. Si se reenvía sin límite, consulta su coste en Anthropic.

**Afinidad OpenAI/ChatGPT nativa.** `prompt_cache_key` sirve a la afinidad de caché; `session_id` solo procede de identidad de sesión, nunca de la clave compartida. Si `metadata.user_id` es una cadena JSON con otras claves, se elimina el token por turno `tk` antes del hash, manteniendo identidad entre turnos remotos. Cadenas que no sean objetos JSON, arrays o un objeto con solo `tk` se hashean sin cambios; `user` sigue derivándose de la cadena original. Sin cadena y con sistema, se usa el hash de modelo resuelto, sistema y esquemas de herramientas: identifica un grupo de solicitudes, no una sesión.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo
| `noVisionModels?` | `string[]` | Los modelos solo de texto enviados a través del sidecar de visión toleran una etiqueta Ollama `:size`. |
| `escapeBuiltinToolNames?` | `boolean` | Escápese de los nombres de herramientas incorporados para las puertas de enlace compatibles con Anthropic y restaure las llamadas devueltas. |
| `anthropicEofTolerance?` | `boolean` | Deje que una puerta de enlace compatible con Anthropic complete un flujo que termina antes de `message_stop`, solo cuando se recibió texto visible o una entrada completa de la herramienta JSON-objeto. Desactivado por defecto. |
| `forwardAdvisorTool?` | `boolean` | Herramienta Advisor tipada de Claude Code, `advisor_20260301`, en Messages traducido. Ausente: solo un adaptador `anthropic` con `https://api.anthropic.com` recibe declaración, intercambios completados y beta `advisor-tool-2026-03-01`. `true` los permite en un gateway Anthropic compatible que ejecute Advisor; `false` impide reenviarlos incluso al oficial. Otros destinos omiten la herramienta. Un Advisor de OpenCodex activo controla el nombre `advisor`. Consulta [Advisor de Anthropic](/es/guides/claude-code/#anthropics-advisor-tool-on-translated-routes). Guardar con el mismo destino conserva un valor omitido; moverlo lo elimina. `PATCH` acepta booleano o `null`. |
| `forwardAdvisorTool?` | `boolean` | Herramienta Advisor tipada de Claude Code, `advisor_20260301`, en Messages traducido. Ausente: solo un adaptador `anthropic` con `https://api.anthropic.com` recibe declaración, intercambios completados y beta `advisor-tool-2026-03-01`. `true` los permite en un gateway Anthropic compatible que ejecute Advisor; `false` impide reenviarlos incluso al oficial. Otros destinos omiten la herramienta. Un Advisor de OpenCodex activo controla el nombre `advisor`. Un límite de gasto en tokens aplicable a la solicitud también omite la declaración, el historial completado de Advisor y la beta. Consulta [Advisor de Anthropic](/es/guides/claude-code/#anthropics-advisor-tool-on-translated-routes). Guardar con el mismo destino conserva un valor omitido; moverlo lo elimina. `PATCH` acepta booleano o `null`. |
| `googleMode?` | `"ai-studio" \| "vertex" \| "cloud-code-assist"` | Google transporte/modo auth. Por defecto `ai-studio`. |
| `googleToolSchemaPolicy?` | `"compatible" \| "reject-lossy"` | Google solamente. Omitted/ `compatible` conserva el esquema de herramienta compatible y la reparación no directa existente de 400. `reject-lossy` rechaza la pérdida inicial del esquema o una comparación limitada indeterminada antes del envío y retiene una reparación de Vertex o Cloud Code Assist que abriría restricciones. Direct AI Studio nunca realiza esa reparación. |
| `directGeminiWireRenames?` | `boolean` | Google solamente. Se aplica en el modo AI Studio, incluidas las URL personalizadas compatibles con Google. Omitida o `true` mantiene el nombre del cable `-tiered` para Gemini Flash ids ( `gemini-3.7-flash` -? `gemini-3.7-flash-tiered` ); `false` envía los identificadores desnudos solicitados al cable sin cambios. Las rutas Vertex y OpenCode Zen con clave canónica conservan el ID del modelo solicitado independientemente de esta configuración; El enrutamiento de Cloud Code Assist no cambia. Establecer `false` cuando el configurado aguas arriba todavía sirve a los ID desnudos. |
Expand Down
12 changes: 9 additions & 3 deletions docs-site/src/content/docs/guides/claude-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,12 @@ request and returns a `server_tool_use` block named `advisor` followed by an
- A declaration whose `model` the caller's API key scope does not admit is not forwarded, and the
request log records `advisor-tool-outside-model-scope`. The managed native Messages lane
refuses such a request instead.
- If the request's captured policy has an applicable root, identity or provider-pool token spend
ceiling, the hosted Advisor declaration, completed history and beta are withheld. The main turn
continues. On directly routed requests the log records `advisor-tool-withheld-by-spend-policy`.
This uses the policy captured for that request, including
its selected account and pool; later configuration changes do not alter the decision. Requests
without an applicable ceiling keep the forwarding rules above.
- The `server_tool_use` and `advisor_tool_result` blocks reach Claude Code unchanged, with their
`srvtoolu_` ids, for streaming and non-streaming requests. That covers the plaintext
`advisor_result`, the encrypted `advisor_redacted_result` and `advisor_tool_result_error`.
Expand All @@ -1119,9 +1125,9 @@ request and returns a `server_tool_use` block named `advisor` followed by an
declaration and the beta, so the model can consult again.
- When the OpenCodex Advisor owns the name for a turn, Claude Code's earlier Advisor exchanges are
also withheld for every request of that turn, so the prompt does not change partway through it.
- Anthropic reports the advisor model's tokens separately from the main model's usage, and
OpenCodex does not add them to its usage log, key spend or the usage Claude Code receives.
Check Anthropic's console for the advisor cost.
- OpenCodex does not independently account for the hosted advisor model's tokens in its usage log,
key spend or the usage Claude Code receives. This is why token ceilings withhold that optional
tool. When it is forwarded without a ceiling, check Anthropic's console for the advisor cost.

### Unicode-property patterns in tool schemas

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity
| `noVisionModels?` | `string[]` | Text-only models sent through the vision sidecar; matching tolerates an Ollama `:size` tag. |
| `escapeBuiltinToolNames?` | `boolean` | Escape built-in tool names for Anthropic-compatible gateways and restore them in returned calls. |
| `anthropicEofTolerance?` | `boolean` | Let an Anthropic-compatible gateway complete a stream that ends before `message_stop`, only when visible text or a complete JSON-object tool input was received. Off by default. |
| `forwardAdvisorTool?` | `boolean` | Claude Code's typed Advisor server tool (`advisor_20260301`) on the translated Messages path. Omitted: only an `anthropic`-adapter provider on first-party `https://api.anthropic.com` receives the declaration, the client's completed Advisor exchanges and the `advisor-tool-2026-03-01` beta. `true`: an Anthropic-compatible gateway that runs the Advisor receives them too. `false`: never forwarded, including first-party. Other destinations drop the declaration and the turn runs without advice. An active OpenCodex Advisor owns the `advisor` name for its turns. See [Anthropic's Advisor tool on translated routes](/guides/claude-code/#anthropics-advisor-tool-on-translated-routes). A same-destination save keeps an omitted value and a destination move drops it; `PATCH` accepts a boolean or `null` to clear it. |
| `forwardAdvisorTool?` | `boolean` | Claude Code's typed Advisor server tool (`advisor_20260301`) on the translated Messages path. Omitted: only an `anthropic`-adapter provider on first-party `https://api.anthropic.com` receives the declaration, the client's completed Advisor exchanges and the `advisor-tool-2026-03-01` beta. `true`: an Anthropic-compatible gateway that runs the Advisor receives them too. `false`: never forwarded, including first-party. Other destinations drop the declaration and the turn runs without advice. An active OpenCodex Advisor owns the `advisor` name for its turns. An applicable request token spend ceiling also withholds the declaration, completed Advisor history and beta. See [Anthropic's Advisor tool on translated routes](/guides/claude-code/#anthropics-advisor-tool-on-translated-routes). A same-destination save keeps an omitted value and a destination move drops it; `PATCH` accepts a boolean or `null` to clear it. |
| `googleMode?` | `"ai-studio" \| "vertex" \| "cloud-code-assist"` | Google transport/auth mode. Default `ai-studio`. |
| `googleToolSchemaPolicy?` | `"compatible" \| "reject-lossy"` | Google only. Omitted/`compatible` preserves the compatible tool schema and existing non-direct 400 repair. `reject-lossy` rejects initial schema loss or an indeterminate bounded comparison before dispatch and withholds a Vertex or Cloud Code Assist repair that would open constraints. Direct AI Studio never performs that repair. |
| `directGeminiWireRenames?` | `boolean` | Google only. Applies in AI Studio mode, including custom Google-compatible URLs. Omitted or `true` keeps the `-tiered` wire rename for Gemini Flash ids (`gemini-3.7-flash` -> `gemini-3.7-flash-tiered`); `false` sends the requested bare ids to the wire unchanged. Vertex and canonical keyed OpenCode Zen routes preserve the requested model ID regardless of this setting; Cloud Code Assist routing is unchanged. Set `false` when the configured upstream still serves the bare ids. |
Expand Down
26 changes: 18 additions & 8 deletions src/adapters/anthropic/advisor-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,26 @@ function runHasOtherServerTool(run: readonly Rec[]): boolean {
return run.some(block => block.type === "server_tool_use" && block.name !== ADVISOR_SERVER_TOOL_NAME);
}

/**
* Withhold the caller's Advisor for a turn the proxy Advisor joins: its declaration and every
* replayed run that contains an Advisor call. The synthetic `advisor` owns the name for the whole
* turn, so a later leg that drops the synthetic tool (consultations exhausted) must not bring the
* history or the beta back and change the prompt mid-turn. Returns whether a declaration was withheld.
*/
export function withholdAdvisorServerTools(parsed: {
type AdvisorServerToolState = {
_anthropicServerTools?: readonly Rec[];
_anthropicServerReplay?: ReadonlyMap<string, readonly Rec[]>;
}): boolean {
};

/** A declaration or completed replay can enable the hosted Advisor on this turn. */
export function hasAdvisorServerTools(parsed: AdvisorServerToolState): boolean {
if (hasAdvisorDeclaration(parsed._anthropicServerTools)) return true;
for (const run of parsed._anthropicServerReplay?.values() ?? []) {
if (runHasAdvisor(run)) return true;
}
return false;
}

/**
* Withhold the caller's hosted Advisor for the whole turn: its declaration and every replayed run
* that contains an Advisor call. Later legs must not restore its history or beta, whether a spend
* ceiling withheld it or the proxy Advisor owns its name. Returns whether a declaration was withheld.
*/
export function withholdAdvisorServerTools(parsed: AdvisorServerToolState): boolean {
const declared = hasAdvisorDeclaration(parsed._anthropicServerTools);
if (declared) parsed._anthropicServerTools = parsed._anthropicServerTools!.filter(tool => !isAdvisorServerToolType(tool.type));
const replay = parsed._anthropicServerReplay;
Expand Down
5 changes: 5 additions & 0 deletions src/lib/request-execution-budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ export interface RequestSendObserver {
readonly enforced?: boolean;
readonly policyStarted?: boolean;
readonly spendAdmissionPolicy?: SpendAdmissionPolicy;
/** Capture/query original ceilings for a selected target without starting accounting. */
hasCapturedSpendCeiling?(target?: SpendScopes): boolean;
/** Capture request policy at its first admission or actual physical start. */
startRequest?(target?: SpendScopes & { targetKey?: string }): void;
ensureSeed?(target: SpendScopes & { targetKey?: string; auxiliary?: boolean; estimate?: { inputTokens: number; outputCeilingTokens: number }; explicitEstimate?: boolean }, proof?: SpendReservationProof): SpendSeed | undefined;
Expand All @@ -192,6 +194,8 @@ export interface RequestExecutionBudget extends TransientSendBudget {
readonly workflowCountObserved?: boolean;
readonly spendPolicyStarted?: boolean;
readonly spendAdmissionPolicy?: SpendAdmissionPolicy;
/** Optional hosted work checks the original ceilings even before an account was selected. */
hasCapturedSpendCeiling?(target?: SpendScopes): boolean;
startRequest?(target?: SpendScopes & { targetKey?: string }): void;
claimPhysicalSend?(auxiliary?: boolean): number | undefined;
/** A validated explicit successor still pays root/spend admission, not the recovery allowance. */
Expand Down Expand Up @@ -491,6 +495,7 @@ function createRequestExecutionBudgetWithLedger(
get workflowCountObserved(): boolean { return observer?.beforePhysicalSend !== undefined; },
get spendPolicyStarted(): boolean { return observer?.policyStarted === true; },
get spendAdmissionPolicy(): SpendAdmissionPolicy | undefined { return observer?.spendAdmissionPolicy; },
hasCapturedSpendCeiling(target) { return observer?.hasCapturedSpendCeiling?.(target) ?? observer?.enforced === true; },
startRequest(target) {
observer?.startRequest?.(target);
if (observer?.enforced && counter.physicalLimit === undefined) {
Expand Down
2 changes: 2 additions & 0 deletions src/protocols/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ export const PROTOCOL_REASON_CODES = [
"advisor-tool-shadowed-by-proxy-advisor",
/** A typed Advisor declaration named a model outside the caller's admission scope and was not forwarded. */
"advisor-tool-outside-model-scope",
/** The request enforces token spend ceilings, so the separately unaccounted hosted Advisor was withheld. */
"advisor-tool-withheld-by-spend-policy",
] as const;
export type ProtocolReasonCode = (typeof PROTOCOL_REASON_CODES)[number];

Expand Down
1 change: 1 addition & 0 deletions src/server/responses/request-send-budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ function adapterDispatchBudgetView(
get spendEnforced() { return budget.spendEnforced; },
get spendPolicyStarted() { return budget.spendPolicyStarted; },
get spendAdmissionPolicy() { return budget.spendAdmissionPolicy; },
hasCapturedSpendCeiling: target => budget.hasCapturedSpendCeiling?.(target) ?? budget.spendEnforced === true,
startRequest: target => budget.startRequest?.(target),
claimPhysicalSend: auxiliary => auxiliary ? budget.claimPhysicalSend?.(true) : budget.claimPhysicalSend?.(),
claimContinuationPhysicalSend: () => budget.claimContinuationPhysicalSend?.(),
Expand Down
12 changes: 11 additions & 1 deletion src/server/responses/request-spend-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,21 @@ import type { RequestLogContext } from "../request-log";

type PhysicalSpendTarget = SpendScopes & { targetKey?: string };
const targets = new WeakMap<RequestLogContext, () => PhysicalSpendTarget>();
const hostedAdvisorTargets = new WeakMap<RequestLogContext, () => PhysicalSpendTarget>();

/** A prepared candidate can own admission without overwriting the last physical send's log. */
export function bindResponsesSpendTarget(context: RequestLogContext, target?: () => PhysicalSpendTarget): void {
if (target) targets.set(context, target);
else targets.delete(context);
else { targets.delete(context); hostedAdvisorTargets.delete(context); }
}

/** Optional hosted work checks an admitted identity without changing main-model accounting. */
export function bindResponsesHostedAdvisorSpendTarget(context: RequestLogContext, target: () => PhysicalSpendTarget): void {
hostedAdvisorTargets.set(context, target);
}

export function responsesHostedAdvisorSpendTarget(context: RequestLogContext, fallbackPool?: string): PhysicalSpendTarget {
return hostedAdvisorTargets.get(context)?.() ?? responsesSpendTarget(context, fallbackPool);
}

/** Resolve late, after queued negotiation; ordinary callers retain their original pool fallback. */
Expand Down
Loading
Loading