mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-12 02:02:13 +03:00
* feat(dashboard): add RADAR_ENABLED flag (default off) * feat(db): radar feed cache + settings with encrypted supporter key * feat(radar): signed feed sync with pinned key and version floor - feedSchema.ts: Zod v4 schema mirroring the server feed format (discriminated union on budget.kind, enum constraints, etc.) - pinnedKeys.ts: Ed25519 SPKI-DER pinned key + env override for forks - verify.ts: signature verification over exact wire bytes, never throws - sync.ts: full download/verify/validate/cache pipeline with injectable deps, feature-flag gate, opt-in gate, version floor (numeric compare), and sanitized error reasons (no stack traces) - 40 tests covering: contract hash, key handling, sig verification, schema validation, version compare, all sync paths (disabled, opt_out, invalid_signature, invalid_schema, stale, updated, error), auth header injection, and cache-untouched assertions for every failure mode * feat(radar): read-time overlay merge rules over the free catalog Pure function applyFeed() merges the cached Radar feed over the static baseline catalog at read time, honoring 4 rules: 1. Feed never overwrites a local override field. 2. enabled:false disables the entry with disabledBy:"radar" provenance. 3. User-added entry NOT in the feed survives untouched. 4. User deletion tombstone prevents feed resurrection. getRadarCatalog() accessor in index.ts: flag off / no cache / corrupt payload all fall back to baseline. Valid cache applies the overlay and returns feed metadata (version, tier, fetchedAt). TDD: 19 tests (4 rules + dedup + origin + accessor flag/cache/corrupt/ valid/bad-feed + baselineToMergedEntries converter). * feat(dashboard): radar catalog and guided setup screens - API routes: GET /api/radar/catalog, POST /api/radar/sync, POST /api/radar/settings - All gated on RADAR_ENABLED flag (404 when off) - Error responses via buildErrorBody(), never raw stack/message - Settings never echoes clear supporter key (masked omr_****<last4>) - Sync delegates to syncRadar() server-side, never proxies feed URL - Dashboard pages: - /dashboard/radar: 4 states (flag off, opt-in pending, empty, populated) - /dashboard/radar/setup?provider=X: guided setup with steps, key URL, test connection - Uses existing Card component and next-intl patterns - Sidebar: radar entry in costs group with icon - i18n: pt-BR and en keys for radarPage and radarSetupPage namespaces - Tests: - radar-api-routes.test.ts: 11 tests (flag-off 404, flag-on shape, error sanitization) - radar-page-state.test.ts: 5 tests (pure state logic) - All 90 radar tests pass (including prior 74) * docs(radar): module doc and flag-off inertia test Add docs/frameworks/RADAR.md covering the flag gate, the separate data-sync opt-in and privacy promise, the Ed25519 signature/pinned-key security model, tiers, the read-time overlay merge rules, and the self-hosting env vars — plus index entries in CLAUDE.md/AGENTS.md/docs/README.md/REPOSITORY_MAP.md. Document RADAR_FEED_URL and RADAR_FEED_PUBKEY in .env.example and docs/reference/ENVIRONMENT.md to satisfy check:env-doc-sync, which was failing on this branch since the sync.ts commit added the reads. Add tests/unit/radar-inertia.test.ts as the single canonical place asserting the "RADAR_ENABLED off => zero behavioral delta" claim end to end: the three /api/radar/* routes 404, the flag resolves to the definition default with no override, getRadarCatalog() returns exactly the baseline without touching the cache, and computeFreeModelTotals() keeps its pinned values with the Radar module imported alongside it. * fix(db): renumber radar migration to 135 after collision with 134 The base branch introduced 134_proxy_logs_egress_ip while this branch carried 134_radar_cache_settings; the migration runner rejects duplicate numeric prefixes. This migration has never been applied to a real database (the PR is unmerged), so no retroactive isSchemaAlreadyApplied guard is needed. * i18n(radar): translate radar catalog and setup strings to all locales The UI-coverage ratchet measures (present - placeholder) / total_en, so the __MISSING__ sentinels that i18n:sync-ui writes do not count as covered — only real translations restore the metric. Scoped to this PR's namespaces (radarPage, radarSetupPage, sidebar.radar*) instead of a bulk sync, which would have pulled ~978 unrelated pending keys into this diff. Placeholders and code identifiers verified preserved across all 1682 strings. * fix(radar): trust the served-tier header instead of the signed body field The signed feed body always carries tier:"live" by design (one signed artifact per version — rewriting the field server-side per request would break the exact-bytes Ed25519 signature). The server now returns the tier ACTUALLY served via the x-omniroute-feed-tier response header, so free users on a delayed community snapshot no longer see "Ao vivo (tempo real)" in the UI. sync.ts now reads and validates that header (falling back to the body's tier only when the header is absent or holds an unrecognized value) and stores the served tier in the cache; index.ts already surfaces cache.tier to the UI unchanged. * test(combo): shorten an assert message that exceeded the line limit The assertion added by #9507 was 104 chars, so prettier reformatted it into five lines on the next commit that touched the file, pushing it past its frozen size (3449) and failing check:file-size. The message is shortened (the issue reference stays in the comment directly above); the assertion itself is unchanged, and the file is back to 3448 lines and prettier-clean. * i18n(radar): use the canonical zh-TW glossary terms The machine translation produced retired renderings the glossary gate blocks: 供應商 for provider (canonical 提供者) and 文檔 for documentation (canonical 文件). Fixed across the 11 affected radar strings; tests/unit/i18n-glossary-consistency-check.test.ts is back to 17/17. * fix(radar): point the default feed URL at the domain that exists radar.omniroute.dev was a placeholder for a domain that was never registered, so an out-of-the-box sync would fail DNS resolution for every user. The live feed is served from radar.omniroute.online (the subdomain the design always specified), now behind Cloudflare TLS. Forks still override it via RADAR_FEED_URL. --------- Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
465 lines
17 KiB
TypeScript
465 lines
17 KiB
TypeScript
/**
|
|
* Claude Code identity helpers used by the native `claude` provider when
|
|
* authenticating with an OAuth token. Anthropic's user:sessions:claude_code
|
|
* scope expects request shape that matches a real claude-cli session;
|
|
* everything in this module exists to produce that shape.
|
|
*
|
|
* Pinned to a captured claude-cli release. Bump in lockstep when a newer
|
|
* release is captured.
|
|
*/
|
|
|
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
|
|
import {
|
|
CLAUDE_CODE_CLIENT_VERSION,
|
|
CLAUDE_CODE_SDK_PACKAGE_VERSION,
|
|
} from "@/shared/constants/claudeCodeClient";
|
|
|
|
// ---------- Versions ------------------------------------------------------
|
|
|
|
export const CLAUDE_CODE_VERSION = CLAUDE_CODE_CLIENT_VERSION;
|
|
/** Bundled @anthropic-ai/sdk version for the pinned CLI release. */
|
|
export const CLAUDE_CODE_STAINLESS_VERSION = CLAUDE_CODE_SDK_PACKAGE_VERSION;
|
|
|
|
// ---------- Stainless OS / Arch / Runtime --------------------------------
|
|
|
|
export function stainlessOS(): string {
|
|
switch (process.platform) {
|
|
case "win32":
|
|
return "Windows";
|
|
case "darwin":
|
|
return "MacOS";
|
|
case "linux":
|
|
return "Linux";
|
|
case "freebsd":
|
|
return "FreeBSD";
|
|
default:
|
|
return "Unknown";
|
|
}
|
|
}
|
|
|
|
export function stainlessArch(): string {
|
|
switch (process.arch) {
|
|
case "x64":
|
|
return "x64";
|
|
case "arm64":
|
|
return "arm64";
|
|
case "ia32":
|
|
return "x32";
|
|
default:
|
|
return process.arch;
|
|
}
|
|
}
|
|
|
|
export function stainlessRuntimeVersion(): string {
|
|
return process.version;
|
|
}
|
|
|
|
// ---------- Bounded-map helper -------------------------------------------
|
|
|
|
const IDENTITY_CACHE_LIMIT = 10_000;
|
|
const BOOTSTRAP_FETCH_TIMEOUT_MS = 10_000;
|
|
|
|
/** Insert with FIFO eviction once a Map reaches `max`. JS Maps preserve insertion order. */
|
|
function setBounded<K, V>(m: Map<K, V>, key: K, value: V, max: number): void {
|
|
if (!m.has(key) && m.size >= max) {
|
|
const oldest = m.keys().next().value as K | undefined;
|
|
if (oldest !== undefined) m.delete(oldest);
|
|
}
|
|
m.set(key, value);
|
|
}
|
|
|
|
// ---------- Upstream session-id passthrough ------------------------------
|
|
|
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
|
|
export function passthroughUpstreamSessionId(
|
|
clientHeaders: Record<string, string | undefined> | null | undefined
|
|
): string | null {
|
|
if (!clientHeaders) return null;
|
|
const raw =
|
|
clientHeaders["x-claude-code-session-id"] ?? clientHeaders["X-Claude-Code-Session-Id"];
|
|
if (typeof raw !== "string") return null;
|
|
const v = raw.trim();
|
|
return UUID_RE.test(v) ? v : null;
|
|
}
|
|
|
|
// ---------- Session ID (per OAuth account, process lifetime) -------------
|
|
|
|
const sessionCache = new Map<string, string>();
|
|
|
|
/** Same value MUST be emitted as both X-Claude-Code-Session-Id and metadata.user_id.session_id. */
|
|
export function getSessionId(seed: string): string {
|
|
let id = sessionCache.get(seed);
|
|
if (id) return id;
|
|
id = randomUUID();
|
|
setBounded(sessionCache, seed, id, IDENTITY_CACHE_LIMIT);
|
|
return id;
|
|
}
|
|
|
|
// ---------- Device ID (cliUserID) ----------------------------------------
|
|
|
|
/** Real CLI uses crypto.randomBytes(32).toString("hex"), persisted to ~/.claude.json. */
|
|
export function generateCliUserID(): string {
|
|
return randomBytes(32).toString("hex");
|
|
}
|
|
|
|
const lazyCliUserIDCache = new Map<string, string>();
|
|
|
|
const HEX64_RE = /^[a-f0-9]{64}$/i;
|
|
|
|
/**
|
|
* Resolve the cliUserID for an account, in priority order:
|
|
* 1. providerSpecificData.cliUserID — persisted at OAuth provisioning.
|
|
* 2. providerSpecificData.userID — alt key (matches real CLI's own).
|
|
* 3. lazy-random — fresh randomBytes(32), cached for the process lifetime.
|
|
*
|
|
* Never deterministic from the access token.
|
|
*/
|
|
export function resolveCliUserID(
|
|
providerSpecificData: Record<string, unknown> | undefined,
|
|
seed: string
|
|
): string {
|
|
const cli = providerSpecificData?.cliUserID;
|
|
if (typeof cli === "string" && HEX64_RE.test(cli)) return cli;
|
|
const alt = providerSpecificData?.userID;
|
|
if (typeof alt === "string" && HEX64_RE.test(alt)) return alt;
|
|
let cached = lazyCliUserIDCache.get(seed);
|
|
if (cached) return cached;
|
|
cached = generateCliUserID();
|
|
setBounded(lazyCliUserIDCache, seed, cached, IDENTITY_CACHE_LIMIT);
|
|
return cached;
|
|
}
|
|
|
|
// ---------- Account UUID -------------------------------------------------
|
|
|
|
const ACCOUNT_FETCH_RETRY_MS = 5 * 60 * 1000;
|
|
const accountUuidCache = new Map<string, { uuid: string | null; fetchedAt: number }>();
|
|
const inflightFetches = new Set<string>();
|
|
|
|
export type ClaudeBootstrap = {
|
|
account_uuid: string | null;
|
|
account_email: string | null;
|
|
organization_uuid: string | null;
|
|
organization_name: string | null;
|
|
organization_type: string | null;
|
|
organization_rate_limit_tier: string | null;
|
|
};
|
|
|
|
/** GET /api/claude_cli/bootstrap with the same headers real CLI uses. */
|
|
export async function fetchClaudeBootstrap(accessToken: string): Promise<ClaudeBootstrap | null> {
|
|
const ctrl = new AbortController();
|
|
const timer = setTimeout(() => ctrl.abort(), BOOTSTRAP_FETCH_TIMEOUT_MS);
|
|
try {
|
|
const res = await fetch("https://api.anthropic.com/api/claude_cli/bootstrap", {
|
|
method: "GET",
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`,
|
|
Accept: "application/json",
|
|
"User-Agent": `claude-cli/${CLAUDE_CODE_VERSION} (external, cli)`,
|
|
"anthropic-beta": "oauth-2025-04-20",
|
|
},
|
|
signal: ctrl.signal,
|
|
});
|
|
if (!res.ok) return null;
|
|
const data: unknown = await res.json().catch(() => null);
|
|
const acct =
|
|
data && typeof data === "object" ? (data as Record<string, unknown>).oauth_account : null;
|
|
if (!acct || typeof acct !== "object") return null;
|
|
const account = acct as Record<string, unknown>;
|
|
const stringOrNull = (value: unknown) => (typeof value === "string" ? value : null);
|
|
return {
|
|
account_uuid: stringOrNull(account.account_uuid),
|
|
account_email: stringOrNull(account.account_email),
|
|
organization_uuid: stringOrNull(account.organization_uuid),
|
|
organization_name: stringOrNull(account.organization_name),
|
|
organization_type: stringOrNull(account.organization_type),
|
|
organization_rate_limit_tier: stringOrNull(account.organization_rate_limit_tier),
|
|
};
|
|
} catch {
|
|
return null;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
async function backgroundFetchAccountUUID(accessToken: string, seed: string): Promise<void> {
|
|
if (inflightFetches.has(seed)) return;
|
|
const cached = accountUuidCache.get(seed);
|
|
if (cached?.uuid) return;
|
|
if (cached && Date.now() - cached.fetchedAt < ACCOUNT_FETCH_RETRY_MS) return;
|
|
inflightFetches.add(seed);
|
|
try {
|
|
const bootstrap = await fetchClaudeBootstrap(accessToken);
|
|
setBounded(
|
|
accountUuidCache,
|
|
seed,
|
|
{ uuid: bootstrap?.account_uuid ?? null, fetchedAt: Date.now() },
|
|
IDENTITY_CACHE_LIMIT
|
|
);
|
|
} finally {
|
|
inflightFetches.delete(seed);
|
|
}
|
|
}
|
|
|
|
/** Format-correct UUIDv4 from a 64-hex hash (deterministic fallback shape). */
|
|
export function uuidV4FromHash(hex64: string): string {
|
|
return [
|
|
hex64.slice(0, 8),
|
|
hex64.slice(8, 12),
|
|
"4" + hex64.slice(13, 16),
|
|
((parseInt(hex64.charAt(16), 16) & 0x3) | 0x8).toString(16) + hex64.slice(17, 20),
|
|
hex64.slice(20, 32),
|
|
].join("-");
|
|
}
|
|
|
|
/**
|
|
* Resolve account_uuid in priority order:
|
|
* 1. providerSpecificData.accountUUID / account_uuid (real, from bootstrap).
|
|
* 2. in-memory cache from a background bootstrap fetch.
|
|
* 3. deterministic UUIDv4 derived from the access token (shape-correct fallback).
|
|
*
|
|
* Triggers a background bootstrap fetch when no real UUID is known yet.
|
|
*/
|
|
export function resolveAccountUUID(
|
|
providerSpecificData: Record<string, unknown> | undefined,
|
|
seed: string,
|
|
accessToken?: string
|
|
): string {
|
|
const camel = providerSpecificData?.accountUUID;
|
|
if (typeof camel === "string" && camel.length >= 32) return camel;
|
|
const snake = providerSpecificData?.account_uuid;
|
|
if (typeof snake === "string" && snake.length >= 32) return snake;
|
|
|
|
const cached = accountUuidCache.get(seed);
|
|
if (cached?.uuid) return cached.uuid;
|
|
|
|
if (accessToken) void backgroundFetchAccountUUID(accessToken, seed);
|
|
|
|
// CodeQL: This is intentionally SHA-256 for deterministic UUID generation from
|
|
// a seed string — NOT password hashing. The output is a format-correct UUIDv4
|
|
// used as a fallback account identifier; no secrets are being protected.
|
|
// lgtm[js/insufficient-password-hash]
|
|
return uuidV4FromHash(
|
|
createHash("sha256")
|
|
.update("account:" + seed)
|
|
.digest("hex") // nosemgrep: insufficient-password-hash
|
|
);
|
|
}
|
|
|
|
// ---------- metadata.user_id (the JSON-stringified blob) -----------------
|
|
|
|
/** Real CLI emits this exact key order: device_id, account_uuid, session_id. */
|
|
export function buildUserIdJson(opts: {
|
|
deviceId: string;
|
|
accountUUID: string;
|
|
sessionId: string;
|
|
}): string {
|
|
return JSON.stringify({
|
|
device_id: opts.deviceId,
|
|
account_uuid: opts.accountUUID,
|
|
session_id: opts.sessionId,
|
|
});
|
|
}
|
|
|
|
export function parseUpstreamMetadataUserId(
|
|
body: Record<string, unknown> | null | undefined
|
|
): { device_id: string; account_uuid: string; session_id: string } | null {
|
|
if (!body) return null;
|
|
const md = body.metadata as Record<string, unknown> | undefined;
|
|
const raw = md?.user_id;
|
|
if (typeof raw !== "string" || raw.length === 0) return null;
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!parsed || typeof parsed !== "object") return null;
|
|
const { device_id, account_uuid, session_id } = parsed as Record<string, unknown>;
|
|
if (
|
|
typeof device_id !== "string" ||
|
|
!HEX64_RE.test(device_id) ||
|
|
typeof account_uuid !== "string" ||
|
|
!UUID_RE.test(account_uuid) ||
|
|
typeof session_id !== "string" ||
|
|
!UUID_RE.test(session_id)
|
|
) {
|
|
return null;
|
|
}
|
|
return { device_id, account_uuid, session_id };
|
|
}
|
|
|
|
// ---------- anthropic-beta selector --------------------------------------
|
|
|
|
/**
|
|
* Models that support the heavy-agent beta tier (effort, advanced-tool-use).
|
|
* Only Opus/Sonnet are eligible — Haiku with OAuth authentication rejects
|
|
* heavy agent flags (issue #2454). Matches real Claude Code captures.
|
|
*/
|
|
const HEAVY_AGENT_BETA_MODEL_PREFIXES = ["claude-opus", "claude-sonnet"];
|
|
/**
|
|
* Models that support the context-1m beta tier. Only Opus is eligible;
|
|
* Sonnet trips long-context credit gates under OAuth full-agent traffic.
|
|
* Opus 5 is excluded because its 1M context window is native.
|
|
*/
|
|
const CONTEXT_1M_BETA_MODEL_PREFIXES = ["claude-opus"];
|
|
const CONTEXT_1M_NATIVE_MODEL_PREFIXES = ["claude-opus-5"];
|
|
|
|
function matchesModelPrefix(model: unknown, prefixes: string[]): boolean {
|
|
if (typeof model !== "string") return false;
|
|
const normalized = model.toLowerCase();
|
|
return prefixes.some((prefix) => normalized.includes(prefix));
|
|
}
|
|
|
|
function isHeavyAgentModel(model: unknown): boolean {
|
|
return matchesModelPrefix(model, HEAVY_AGENT_BETA_MODEL_PREFIXES);
|
|
}
|
|
|
|
function isContext1mModel(model: unknown): boolean {
|
|
return (
|
|
matchesModelPrefix(model, CONTEXT_1M_BETA_MODEL_PREFIXES) &&
|
|
!matchesModelPrefix(model, CONTEXT_1M_NATIVE_MODEL_PREFIXES)
|
|
);
|
|
}
|
|
|
|
export function shouldUseMidConversationSystem(
|
|
body: Record<string, unknown> | null | undefined,
|
|
model?: string | null
|
|
): boolean {
|
|
const payload = body || {};
|
|
const hasSystem =
|
|
!!payload.system &&
|
|
(typeof payload.system === "string" ||
|
|
(Array.isArray(payload.system) && payload.system.length > 0));
|
|
const hasTools = Array.isArray(payload.tools) && payload.tools.length > 0;
|
|
const effectiveModel = model ?? (typeof payload.model === "string" ? payload.model : "");
|
|
|
|
return (
|
|
hasSystem && hasTools && matchesModelPrefix(effectiveModel, CONTEXT_1M_BETA_MODEL_PREFIXES)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Pick the anthropic-beta flag set that matches the request shape. Real CLI
|
|
* uses three patterns: minimal probe, structured-output, and full agent.
|
|
* Sending the full set on every shape is itself a fingerprint.
|
|
*
|
|
* The heavy-agent flags are gated on the model as well as the shape. In direct
|
|
* Claude Code captures, Sonnet receives effort/advanced-tool-use but not
|
|
* context-1m; sending context-1m to Sonnet trips Anthropic's long-context credit
|
|
* gate for accounts where direct Claude Code works.
|
|
*/
|
|
export function selectBetaFlags(
|
|
body: Record<string, unknown> | null | undefined,
|
|
model?: string | null,
|
|
// The client's inbound `anthropic-beta` header, when present. Real Claude Code
|
|
// clients negotiate their own beta set; forcing thinking/effort betas they never
|
|
// requested produced malformed opus tool_use streams (#3415). When this is a
|
|
// non-empty string we respect it and do NOT force those betas. For opaque clients
|
|
// (no header — the OAuth identity cloak) the full set is retained unchanged.
|
|
clientBeta?: string | null
|
|
): string {
|
|
const b = body || {};
|
|
const clientBetaSet =
|
|
typeof clientBeta === "string" && clientBeta.trim().length > 0
|
|
? new Set(
|
|
clientBeta
|
|
.split(",")
|
|
.map((f) => f.trim())
|
|
.filter(Boolean)
|
|
)
|
|
: null;
|
|
// When the client negotiated its own anthropic-beta, only emit the thinking / heavy
|
|
// betas it actually asked for. Opaque clients (clientBetaSet === null) keep them all.
|
|
const allowThinking =
|
|
clientBetaSet === null || clientBetaSet.has("interleaved-thinking-2025-05-14");
|
|
// effort-2025-11-24 must NOT imply advanced-tool-use-2025-11-20 (#9505): Claude
|
|
// Code sends effort on every request and never sends ATU, so treating effort as
|
|
// a proxy for ATU force-injects the heavy-agent pair the client never negotiated —
|
|
// the same class of mutation #3415 closed. Opaque clients keep the full set.
|
|
const allowHeavy = clientBetaSet === null || clientBetaSet.has("advanced-tool-use-2025-11-20");
|
|
const hasSystem =
|
|
!!b.system &&
|
|
(typeof b.system === "string" || (Array.isArray(b.system) && b.system.length > 0));
|
|
const tools = b.tools as unknown[] | undefined;
|
|
const hasTools = Array.isArray(tools) && tools.length > 0;
|
|
const outputCfg = b.output_config as Record<string, unknown> | undefined;
|
|
const hasStructuredOutput =
|
|
!!(outputCfg && (outputCfg.format as { type?: string } | undefined)?.type === "json_schema") ||
|
|
!!(b.response_format as { type?: string } | undefined)?.type;
|
|
const isFullAgent = hasTools && hasSystem;
|
|
const effectiveModel = model ?? (typeof b.model === "string" ? b.model : "");
|
|
const isHeavyAgent = isFullAgent && isHeavyAgentModel(effectiveModel);
|
|
const isOpusAgent = shouldUseMidConversationSystem(b, effectiveModel);
|
|
const isContext1m = isFullAgent && isContext1mModel(effectiveModel);
|
|
|
|
const flags: string[] = [];
|
|
if (isFullAgent) flags.push("claude-code-20250219");
|
|
flags.push("oauth-2025-04-20");
|
|
if (isContext1m) flags.push("context-1m-2025-08-07");
|
|
if (isOpusAgent) flags.push("mid-conversation-system-2026-04-07");
|
|
// Thinking betas: gated on the client header (#3415). interleaved-thinking forces
|
|
// interleaved-thinking semantics that conflict with a tool_choice-forced turn,
|
|
// producing malformed opus tool_use streams when the client never asked for it.
|
|
if (allowThinking) {
|
|
flags.push(
|
|
"interleaved-thinking-2025-05-14",
|
|
"redact-thinking-2026-02-12",
|
|
"thinking-token-count-2026-05-13"
|
|
);
|
|
}
|
|
flags.push("context-management-2025-06-27", "prompt-caching-scope-2026-01-05");
|
|
if (hasStructuredOutput || isFullAgent) flags.push("advisor-tool-2026-03-01");
|
|
if (hasStructuredOutput && !isFullAgent) flags.push("structured-outputs-2025-12-15");
|
|
// extended-cache-ttl is sent for all full-agent shapes (incl. Haiku); the
|
|
// heavier afk-mode / advanced-tool-use / effort flags are Opus/Sonnet-only.
|
|
if (isFullAgent) {
|
|
flags.push("extended-cache-ttl-2025-04-11", "cache-diagnosis-2026-04-07");
|
|
}
|
|
if (isHeavyAgent && allowHeavy) {
|
|
flags.push("advanced-tool-use-2025-11-20", "effort-2025-11-24");
|
|
}
|
|
return flags.join(",");
|
|
}
|
|
|
|
// ---------- Tool-name normalisation --------------------------------------
|
|
|
|
const TOOL_PREFIX = "proxy_";
|
|
|
|
/** Strip OmniRoute's `proxy_` tool-name prefix; real CLI never sends it. */
|
|
export function stripProxyToolPrefix(body: Record<string, unknown>): void {
|
|
const stripName = (n: unknown): string | undefined => {
|
|
if (typeof n !== "string") return undefined;
|
|
return n.startsWith(TOOL_PREFIX) ? n.slice(TOOL_PREFIX.length) : n;
|
|
};
|
|
|
|
const tools = body.tools as Array<Record<string, unknown>> | undefined;
|
|
if (Array.isArray(tools)) {
|
|
for (const t of tools) {
|
|
const stripped = stripName(t.name);
|
|
if (stripped !== undefined) t.name = stripped;
|
|
}
|
|
}
|
|
|
|
const tc = body.tool_choice as Record<string, unknown> | undefined;
|
|
if (tc && typeof tc.name === "string") {
|
|
const stripped = stripName(tc.name);
|
|
if (stripped !== undefined) tc.name = stripped;
|
|
}
|
|
|
|
const messages = body.messages as Array<Record<string, unknown>> | undefined;
|
|
if (Array.isArray(messages)) {
|
|
for (const m of messages) {
|
|
const content = m.content;
|
|
if (!Array.isArray(content)) continue;
|
|
for (const block of content as Array<Record<string, unknown>>) {
|
|
if (block?.type === "tool_use") {
|
|
const stripped = stripName(block.name);
|
|
if (stripped !== undefined) block.name = stripped;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|