Skip to content
Merged
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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ The loader returns a `fetch` function that:
1. Adds `Authorization: Bearer <apiKey>` and `Content-Type: application/json` headers.
2. Only intercepts requests to the configured OmniRoute base URL (with safe prefix matching).
3. Sanitizes Gemini tool schemas by stripping `$schema`, `$ref`, `ref`, and `additionalProperties` keywords when the model name includes "gemini".
4. Strips `reasoning_effort`/`reasoningEffort` from identified Claude title-generation requests (OpenCode's hidden title prompt) to avoid Anthropic OAuth temperature/thinking validation errors, while preserving reasoning options for normal Claude chat requests.

### Caching Strategy

Expand Down
135 changes: 122 additions & 13 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -969,7 +969,7 @@ function createFetchInterceptor(
headers.set('Authorization', `Bearer ${config.apiKey}`);
headers.set('Content-Type', 'application/json');

const sanitizedBody = await sanitizeGeminiToolSchemas(input, init, url);
const sanitizedBody = await sanitizeRequestPayload(input, init, url);

// Clone init to avoid mutating original
const modifiedInit: RequestInit = {
Expand Down Expand Up @@ -1131,8 +1131,12 @@ function cloneMutableResponseHeaders(headers: Headers): Headers {
}

const GEMINI_SCHEMA_KEYS_TO_REMOVE = new Set(['$schema', '$ref', 'ref', 'additionalProperties']);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness: title-prompt detection requires exact-case substrings 'You are a title generator' AND 'thread title' via .every(). If OpenCode rewords the hidden prompt (casing, phrasing, ordering), the fix silently stops working. Please use case-insensitive matching and/or a softer heuristic, and add debug logging when a Claude request is seen but title markers don't match.

const TITLE_PROMPT_REQUIRED_MARKERS = [
'you are a title generator',
'thread title',
];

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Runtime behavior: JSON parse errors are swallowed and the original body is forwarded unchanged. Consider whether malformed JSON should fail closed (throw/reject) or at least log a warning.

async function sanitizeGeminiToolSchemas(
async function sanitizeRequestPayload(
input: RequestInfo | URL,
init: RequestInit | undefined,
url: string,
Expand All @@ -1149,32 +1153,137 @@ async function sanitizeGeminiToolSchemas(
let payload: unknown;
try {
payload = JSON.parse(rawBody);
} catch {
} catch (error) {
warn(`Failed to parse request body as JSON; forwarding unchanged: ${sanitizeForLog(String(error))}`);
return undefined;
}

if (!isRecord(payload)) {
return undefined;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance: sanitizeRequestPayload calls structuredClone(payload) for every /chat/completions and /responses request, even when neither Claude nor Gemini. The original code only cloned for Gemini. Please perform cheap model/type checks before cloning, or clone only inside the mutating helpers.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merge conflict risk: PR #27 modifies the fetch interceptor response handling in the same region (around lines 913-950). These PRs will likely conflict; please rebase after #27 lands and ensure request-body sanitization and response usage normalization compose correctly.

}

const mayMutate = isClaudeModel(payload.model) || isGeminiModel(payload.model);
const workingPayload = mayMutate ? structuredClone(payload) : payload;
let changed = false;

changed = stripClaudeTitleReasoningEffort(workingPayload) || changed;
changed = sanitizeGeminiToolSchemas(workingPayload) || changed;

return changed ? JSON.stringify(workingPayload) : undefined;
}

function stripClaudeTitleReasoningEffort(payload: Record<string, unknown>): boolean {
const model = payload.model;
if (typeof model !== 'string' || !model.toLowerCase().includes('gemini')) {
return undefined;
if (!isClaudeModel(model)) {
return false;
}
if (!isOpenCodeTitlePrompt(payload)) {
debug('Claude request detected but title markers not found; preserving reasoning effort');
return false;
}

let changed = false;
if ('reasoning_effort' in payload) {
delete payload.reasoning_effort;
changed = true;
}
if ('reasoningEffort' in payload) {
delete payload.reasoningEffort;
changed = true;
}

if (changed) {
debug('Removed reasoning effort from Claude title request');
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic: isClaudeModel misses a bare claude model id (no slash/dash) and matches /claude- anywhere, which could false-positive on non-Claude providers whose names contain 'claude'. Please whitelist known OmniRoute Claude prefixes explicitly and document the /claude- case if intentional.

return changed;
}

function isClaudeModel(model: unknown): boolean {
if (typeof model !== 'string') return false;
const lower = model.toLowerCase();
// OmniRoute canonical aliases: claude/<model> and anthropic/<model>
if (lower.startsWith('claude/') || lower.startsWith('anthropic/')) return true;
// Provider-prefixed IDs where the provider slug ends with the model family,
// e.g. aws/us-claude-sonnet-4-6 or openrouter/claude-3-5-sonnet
if (/\bclaude[-/]/.test(lower)) return true;
return false;
}

function isGeminiModel(model: unknown): boolean {
return typeof model === 'string' && model.toLowerCase().includes('gemini');
}

function isOpenCodeTitlePrompt(payload: Record<string, unknown>): boolean {
if (contentContainsTitlePrompt(payload.instructions)) return true;
if (contentContainsTitlePrompt(payload.system)) return true;

const messages = payload.messages;
if (Array.isArray(messages)) {
return messages.some((message) => {
if (!isRecord(message) || message.role !== 'system') return false;
return contentContainsTitlePrompt(message.content);
});
}

const input = payload.input;
if (Array.isArray(input)) {
return input.some((item) => {
if (!isRecord(item) || item.role !== 'system') return false;
return contentContainsTitlePrompt(item.content);
});
}

return false;
}
Comment on lines +1217 to +1238

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If payload.messages is an array, the function immediately returns the result of messages.some(...). If it does not match, the function returns false and completely skips checking payload.input (even if payload.input is present and contains the title prompt). It is more robust to only return true if a match is found, and otherwise continue checking the remaining fields.

function isOpenCodeTitlePrompt(payload: Record<string, unknown>): boolean {
  if (contentContainsTitlePrompt(payload.instructions)) return true;

  const messages = payload.messages;
  if (Array.isArray(messages)) {
    const hasPrompt = messages.some((message) => {
      if (!isRecord(message) || message.role !== 'system') return false;
      return contentContainsTitlePrompt(message.content);
    });
    if (hasPrompt) return true;
  }

  const input = payload.input;
  if (Array.isArray(input)) {
    const hasPrompt = input.some((item) => {
      if (!isRecord(item) || item.role !== 'system') return false;
      return contentContainsTitlePrompt(item.content);
    });
    if (hasPrompt) return true;
  }

  return false;
}


function contentContainsTitlePrompt(content: unknown): boolean {
const text = contentToText(content);
if (!text) return false;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness: contentToText recursively joins arrays without bounding recursion depth. Deeply nested content arrays could blow the stack. Please add a max-depth guard or use iterative flattening.

const normalized = text.toLowerCase();
return TITLE_PROMPT_REQUIRED_MARKERS.every((marker) => normalized.includes(marker));
}

const MAX_CONTENT_DEPTH = 10;

function contentToText(content: unknown, depth = 0): string {
if (depth > MAX_CONTENT_DEPTH) return '';
if (typeof content === 'string') return content;

if (Array.isArray(content)) {
return content.map((item) => contentToText(item, depth + 1)).filter(Boolean).join('\n');
}

if (!isRecord(content)) return '';
const text = content.text;
if (typeof text === 'string') return text;
const value = content.value;
if (typeof value === 'string') return value;
const contentValue = content.content;
if (contentValue !== undefined) return contentToText(contentValue, depth + 1);
return '';
}

/**
* Sanitizes Gemini tool schemas in place.
* Mutates `payload` and returns `true` if any keys were removed.
*/
function sanitizeGeminiToolSchemas(payload: Record<string, unknown>): boolean {
const model = payload.model;
if (!isGeminiModel(model)) {
return false;
}

const tools = payload.tools;
if (!Array.isArray(tools) || tools.length === 0) {
return undefined;
return false;
}

const clonedPayload = structuredClone(payload);
const changed = sanitizeToolSchemaContainer(clonedPayload);
if (!changed) {
return undefined;
const changed = sanitizeToolSchemaContainer(payload);
if (changed) {
debug('Sanitized Gemini tool schema keywords');
}

debug('Sanitized Gemini tool schema keywords');
return JSON.stringify(clonedPayload);
return changed;
}

async function getRawJsonBody(
Expand Down
Loading