@byokkit/cmd-provider-anthropic 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/chunk-4XYJWEC6.js +127 -0
- package/dist/chunk-4XYJWEC6.js.map +1 -0
- package/dist/chunk-V3B4JGF6.js +127 -0
- package/dist/chunk-V3B4JGF6.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +464 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +121 -0
- package/dist/models.js +15 -0
- package/dist/models.js.map +1 -0
- package/dist/server/index.d.ts +19 -0
- package/dist/server/index.js +242 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +44 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../harness/src/mcp/protocol.ts","../../harness/src/mcp/oauth.ts","../../harness/src/provider/oauth-helpers.ts","../src/anthropic-oauth-fetch.ts"],"sourcesContent":["// @byokkit/cmd-provider-anthropic — the real Command Code Anthropic OAuth flow ported into a\n// harness ProviderModule. Anthropic uses MANUAL CODE-PASTE (no localhost redirect): the user opens\n// an authorize URL with `code=true`, Anthropic shows a `code#state` string, the user pastes it back,\n// and we exchange it for tokens against a JSON token endpoint. Routing stays on the server-side\n// gateway (`/alpha/generate`); this module only owns auth (login + refresh) + the request headers\n// the gateway expects. Behavior MATCHES packages/command/src/auth/anthropic.ts (parity).\n//\n// Functional only (no class/this/new except Map/Set/Error). PKCE is reused from the harness; the\n// token POST stays local because Anthropic requires a provider-specific JSON shape (`state` on\n// authorization_code) for parity with command's original implementation.\n\nimport {randomBytes} from 'node:crypto';\nimport {createAnthropic} from '@ai-sdk/anthropic';\nimport {\n\ttype Credential,\n\ttype CredentialStore,\n\tgeneratePkce,\n\ttype OAuthFetchImpl,\n\ttype ProviderModule,\n\ttype ProviderOAuthResult,\n\ttype RequestAuth,\n\ttype TokenResult,\n} from '@commandcode/harness/provider-kit';\nimport {ANTHROPIC_MODEL_SPECS, matchesAnthropicModel} from './models.js';\nimport {createAnthropicOAuthFetch} from './anthropic-oauth-fetch.js';\n\n// ── Constants (mirror packages/command/src/auth/anthropic.ts exactly) ─────────────\nconst CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';\nconst AUTHORIZE_URL = 'https://claude.ai/oauth/authorize';\nconst TOKEN_URL = 'https://console.anthropic.com/v1/oauth/token';\nconst REDIRECT_URI = 'https://console.anthropic.com/oauth/code/callback';\nconst SCOPE = 'org:create_api_key user:profile user:inference';\n\n// The provider id + the EXACT header names/value Command Code's /alpha/generate server expects.\n// These mirror packages/shared HEADERS (OAUTH_TOKEN='x-oauth-token', OAUTH_PROVIDER='x-oauth-provider')\n// and PROVIDER.ANTHROPIC ('anthropic'). command-auth-headers.ts sends `Bearer <token>` for the token.\nexport const ANTHROPIC_PROVIDER_ID = 'anthropic';\nexport const OAUTH_TOKEN_HEADER = 'x-oauth-token';\nexport const OAUTH_PROVIDER_HEADER = 'x-oauth-provider';\nexport const OAUTH_PROVIDER_VALUE = 'anthropic';\nconst ANTHROPIC_BASE_URL = 'https://api.anthropic.com';\n\n// Refresh this many ms before the token actually expires (command uses the same 5-min buffer).\nconst EXPIRY_SKEW_MS = 5 * 60 * 1000;\n\n// What createAnthropicProvider takes — both injectable for tests; default to global fetch + Date.now.\nexport interface AnthropicProviderOptions {\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n}\n\ninterface AnthropicTokenResponse {\n\treadonly access_token?: string;\n\treadonly refresh_token?: string;\n\treadonly expires_in?: number;\n\treadonly token_type?: string;\n\treadonly scope?: string;\n}\n\nfunction defaultFetch(): OAuthFetchImpl {\n\treturn globalThis.fetch as unknown as OAuthFetchImpl;\n}\n\n// Build the `code=true` manual-paste authorize URL. Field order mirrors command's URLSearchParams so\n// the produced URL is byte-for-byte equivalent. (We hand-encode rather than `new URLSearchParams` to\n// stay within the no-`new` rule; Object.entries preserves insertion order for string keys.)\nfunction buildAuthorizeUrl(params: {\n\treadonly challenge: string;\n\treadonly state: string;\n}): string {\n\tconst query = encodeQuery({\n\t\tcode: 'true',\n\t\tclient_id: CLIENT_ID,\n\t\tresponse_type: 'code',\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: SCOPE,\n\t\tcode_challenge: params.challenge,\n\t\tcode_challenge_method: 'S256',\n\t\tstate: params.state,\n\t});\n\treturn `${AUTHORIZE_URL}?${query}`;\n}\n\nfunction encodeQuery(params: Record<string, string>): string {\n\treturn Object.entries(params)\n\t\t.map(\n\t\t\t([key, value]) =>\n\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t)\n\t\t.join('&');\n}\n\nfunction generateState(): string {\n\treturn randomBytes(32).toString('base64url');\n}\n\n// Harness TokenResult → harness Credential (the on-disk credential shape).\nfunction toCredential(token: TokenResult): Credential {\n\treturn {\n\t\tkind: 'oauth',\n\t\ttoken: token.accessToken,\n\t\trefreshToken: token.refreshToken,\n\t\texpiresAt: token.expiresAt,\n\t};\n}\n\nfunction isStale(credential: Credential, nowMs: number): boolean {\n\treturn (\n\t\ttypeof credential.expiresAt === 'number' &&\n\t\tcredential.expiresAt - EXPIRY_SKEW_MS <= nowMs\n\t);\n}\n\nfunction toTokenResult(\n\traw: AnthropicTokenResponse,\n\tparams: {\n\t\treadonly fallbackRefreshToken?: string;\n\t\treadonly now: () => number;\n\t},\n): TokenResult {\n\tif (!raw.access_token) {\n\t\tthrow new Error('OAuth token response had no access_token');\n\t}\n\treturn {\n\t\taccessToken: raw.access_token,\n\t\trefreshToken: raw.refresh_token ?? params.fallbackRefreshToken,\n\t\texpiresAt:\n\t\t\ttypeof raw.expires_in === 'number'\n\t\t\t\t? params.now() + raw.expires_in * 1000\n\t\t\t\t: undefined,\n\t\ttokenType: raw.token_type,\n\t\tscope: raw.scope,\n\t};\n}\n\nasync function postAnthropicToken(params: {\n\treadonly body: Record<string, string>;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now: () => number;\n\treadonly fallbackRefreshToken?: string;\n}): Promise<TokenResult> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst response = await fetchImpl(TOKEN_URL, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/json',\n\t\t},\n\t\tbody: JSON.stringify(params.body),\n\t});\n\tif (response.ok === false) {\n\t\tconst error = response.text ? await response.text() : '';\n\t\tthrow new Error(`Token exchange failed: ${error}`);\n\t}\n\treturn toTokenResult((await response.json()) as AnthropicTokenResponse, {\n\t\tnow: params.now,\n\t\tfallbackRefreshToken: params.fallbackRefreshToken,\n\t});\n}\n\n// Create the Anthropic provider module. Pure factory: every effectful dependency (fetch, clock) is\n// injectable, so the whole flow is unit-testable with no real network.\nexport function createAnthropicProvider(\n\toptions: AnthropicProviderOptions = {},\n): ProviderModule {\n\tconst {fetchImpl, now} = options;\n\tconst clock = now ?? ((): number => Date.now());\n\n\t// Hit Anthropic's JSON token endpoint and normalize to a Credential. Anthropic expects the same\n\t// request shape as command's original implementation, including `state` on authorization_code.\n\tconst refreshCredential = async (\n\t\tcredential: Credential,\n\t): Promise<Credential> => {\n\t\tif (!credential.refreshToken) {\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot refresh Anthropic OAuth: no refresh token stored',\n\t\t\t);\n\t\t}\n\t\tconst token = await postAnthropicToken({\n\t\t\tbody: {\n\t\t\t\tgrant_type: 'refresh_token',\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\trefresh_token: credential.refreshToken,\n\t\t\t},\n\t\t\tfetchImpl,\n\t\t\tnow: clock,\n\t\t\tfallbackRefreshToken: credential.refreshToken,\n\t\t});\n\t\treturn toCredential(token);\n\t};\n\n\t// Single-flight refresh: concurrent loader calls for a stale token share ONE refresh. On failure\n\t// we keep the existing (still-working) token instead of dropping it — command does the same so a\n\t// transient refresh error never silently logs the user out.\n\tconst inFlight = new Map<string, Promise<Credential>>();\n\tconst refreshOnce = async (params: {\n\t\treadonly credential: Credential;\n\t\treadonly store: CredentialStore;\n\t}): Promise<Credential> => {\n\t\tconst existing = inFlight.get(ANTHROPIC_PROVIDER_ID);\n\t\tif (existing) return existing;\n\t\tconst pending = (async (): Promise<Credential> => {\n\t\t\ttry {\n\t\t\t\tconst next = await refreshCredential(params.credential);\n\t\t\t\tawait params.store.set({\n\t\t\t\t\tprovider: ANTHROPIC_PROVIDER_ID,\n\t\t\t\t\tcredential: next,\n\t\t\t\t});\n\t\t\t\treturn next;\n\t\t\t} catch {\n\t\t\t\treturn params.credential; // keep the working token on failure (parity)\n\t\t\t} finally {\n\t\t\t\tinFlight.delete(ANTHROPIC_PROVIDER_ID);\n\t\t\t}\n\t\t})();\n\t\tinFlight.set(ANTHROPIC_PROVIDER_ID, pending);\n\t\treturn pending;\n\t};\n\n\treturn {\n\t\tid: ANTHROPIC_PROVIDER_ID,\n\t\tdisplayName: 'Anthropic',\n\t\t// The full Anthropic catalog (windows/efforts/interleaved-thinking) — overlays the\n\t\t// harness's fallback mirror so this package is the runtime source of truth.\n\t\tmodels: ANTHROPIC_MODEL_SPECS,\n\t\t// Claims BYO/dated claude-* ids the catalog doesn't enumerate, so interleaved-thinking\n\t\t// finalization still applies to them (the heuristic that used to live in core).\n\t\tmatchesModelId: matchesAnthropicModel,\n\t\t// Requests go straight to api.anthropic.com, run locally through @ai-sdk/anthropic. ALL\n\t\t// OAuth wire behavior (Authorization bearer, the oauth beta set, brand rewrite, billing\n\t\t// block, cc_ tool prefixing) lives in the custom fetch the auth.loader returns — the SDK\n\t\t// model itself stays stock. The dummy apiKey only satisfies the SDK's key check; the\n\t\t// OAuth fetch strips x-api-key off every request. Neither the OAuth token nor prompts\n\t\t// pass through Command Code's API.\n\t\ttransport: {\n\t\t\tkind: 'aisdk',\n\t\t\tbuildModel: ({model, auth}) =>\n\t\t\t\tcreateAnthropic({\n\t\t\t\t\tbaseURL: `${ANTHROPIC_BASE_URL}/v1`,\n\t\t\t\t\tapiKey: 'commandcode-oauth',\n\t\t\t\t\t...(auth.fetch\n\t\t\t\t\t\t? {fetch: auth.fetch as typeof globalThis.fetch}\n\t\t\t\t\t\t: fetchImpl\n\t\t\t\t\t\t\t? {fetch: fetchImpl as typeof globalThis.fetch}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t})(model),\n\t\t},\n\t\tauth: {\n\t\t\tmethods: [\n\t\t\t\t{\n\t\t\t\t\tkind: 'oauth',\n\t\t\t\t\tlabel: 'OAuth (paste code)',\n\t\t\t\t\t// Manual code-paste: open the `code=true` authorize URL, then resolve once the user\n\t\t\t\t\t// pastes the `code#state` Anthropic shows them. `prompt` present ⇒ the harness collects\n\t\t\t\t\t// the pasted value and forwards it to callback() (no localhost redirect server).\n\t\t\t\t\tauthorize: async (): Promise<ProviderOAuthResult> => {\n\t\t\t\t\t\tconst pkce = generatePkce();\n\t\t\t\t\t\tconst state = generateState();\n\t\t\t\t\t\tconst url = buildAuthorizeUrl({\n\t\t\t\t\t\t\tchallenge: pkce.challenge,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: 'pending',\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\tinstructions:\n\t\t\t\t\t\t\t\t'Open the URL and approve access, then copy the authorization code Anthropic shows you (it looks like `code#state`) and paste it back here.',\n\t\t\t\t\t\t\tprompt: {label: 'Paste the authorization code'},\n\t\t\t\t\t\t\tcallback: async (input?: {\n\t\t\t\t\t\t\t\treadonly code?: string;\n\t\t\t\t\t\t\t}): Promise<Credential> => {\n\t\t\t\t\t\t\t\tconst pasted = (input?.code ?? '').trim();\n\t\t\t\t\t\t\t\tif (!pasted) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t'No authorization code provided',\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Anthropic returns `code#state`. Split off the code (command uses [0]); if a\n\t\t\t\t\t\t\t\t// state segment is present, verify it matches the one we sent (CSRF defense —\n\t\t\t\t\t\t\t\t// stronger than command, which trusts its own captured state).\n\t\t\t\t\t\t\t\tconst hashIndex = pasted.indexOf('#');\n\t\t\t\t\t\t\t\tconst code = (\n\t\t\t\t\t\t\t\t\thashIndex === -1\n\t\t\t\t\t\t\t\t\t\t? pasted\n\t\t\t\t\t\t\t\t\t\t: pasted.slice(0, hashIndex)\n\t\t\t\t\t\t\t\t).trim();\n\t\t\t\t\t\t\t\tconst pastedState =\n\t\t\t\t\t\t\t\t\thashIndex === -1\n\t\t\t\t\t\t\t\t\t\t? ''\n\t\t\t\t\t\t\t\t\t\t: pasted.slice(hashIndex + 1).trim();\n\t\t\t\t\t\t\t\tif (!code) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t'No authorization code provided',\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (pastedState && pastedState !== state) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t'OAuth state parameter mismatch',\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst token = await postAnthropicToken({\n\t\t\t\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\t\t\t\tgrant_type: 'authorization_code',\n\t\t\t\t\t\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t\t\t\t\t\t\tcode,\n\t\t\t\t\t\t\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\t\t\t\t\t\t\tcode_verifier: pkce.verifier,\n\t\t\t\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tfetchImpl,\n\t\t\t\t\t\t\t\t\tnow: clock,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\treturn toCredential(token);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\trefresh: async (params: {\n\t\t\t\t\t\treadonly credential: Credential;\n\t\t\t\t\t}): Promise<Credential> =>\n\t\t\t\t\t\trefreshCredential(params.credential),\n\t\t\t\t},\n\t\t\t],\n\t\t\t// Turn a stored credential into request headers, refreshing first if it is within the skew\n\t\t\t// window. Returns the exact header set command-auth-headers.ts emits for Anthropic.\n\t\t\tloader: async (params: {\n\t\t\t\treadonly credential: Credential | null;\n\t\t\t\treadonly store: CredentialStore;\n\t\t\t}): Promise<RequestAuth> => {\n\t\t\t\tconst {credential, store} = params;\n\t\t\t\tif (\n\t\t\t\t\t!credential ||\n\t\t\t\t\tcredential.kind !== 'oauth' ||\n\t\t\t\t\t!credential.token\n\t\t\t\t) {\n\t\t\t\t\treturn {};\n\t\t\t\t}\n\t\t\t\tconst active =\n\t\t\t\t\tcredential.refreshToken && isStale(credential, clock())\n\t\t\t\t\t\t? await refreshOnce({credential, store})\n\t\t\t\t\t\t: credential;\n\t\t\t\tif (!active.token) return {};\n\t\t\t\treturn {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\tAuthorization: `Bearer ${active.token}`,\n\t\t\t\t\t},\n\t\t\t\t\tfetch: createAnthropicOAuthFetch(\n\t\t\t\t\t\tactive.token,\n\t\t\t\t\t\tfetchImpl as typeof globalThis.fetch | undefined,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t};\n}\n\n// Default export: a ready-to-register module using global fetch + Date.now. The harness's\n// loadProviderModules accepts either a ProviderModule object (this) or a factory.\nconst anthropicProvider: ProviderModule = createAnthropicProvider();\nexport default anthropicProvider;\n","// Shared MCP protocol helpers — the JSON-RPC shapes and the MCP→harness conversions\n// used by BOTH transports (stdio + http). Kept in one place so a tool result is\n// interpreted identically regardless of transport (text/image/audio/resource/\n// resource_link content, structuredContent, the legacy toolResult field, and the\n// tool-level `isError` flag → a failed ToolRunResult).\n\nimport type {\n\tToolResultContent,\n\tToolRunResult,\n\tToolSchema,\n} from '../core/index.js';\n\n// MCP protocol version we negotiate. Bumped from the legacy 2024-11-05 to the\n// current revision so servers gating on the newer protocol initialize cleanly.\nexport const MCP_PROTOCOL_VERSION = '2025-03-26';\n\nexport const MCP_CLIENT_INFO = {name: 'commandcode', version: '0.1.0'} as const;\n\n// A hung server (initialized but never replies) must not block the agent forever.\n// Env-overridable via MCP_TOOL_TIMEOUT (milliseconds) — the same knob Claude Code\n// exposes — so slow-but-legitimate servers (big exports, long queries) can be\n// accommodated without a rebuild.\nexport const DEFAULT_MCP_REQUEST_TIMEOUT_MS = 80_000;\n\n// A server description is prompt real estate: an unbounded one (some servers ship\n// multi-KB walls of docs per tool) can blow the system prompt. Cap mirrors Claude\n// Code's MAX_DESCRIPTION_CHARACTERS.\nexport const MCP_MAX_DESCRIPTION_CHARS = 2_048;\n\n// Resolve the per-request timeout: a positive integer MCP_TOOL_TIMEOUT (ms) wins,\n// anything else (absent, zero, junk) falls back to the default. parseInt +\n// positivity mirrors Claude Code's env handling.\nexport function resolveMcpTimeoutMs(params?: {\n\treadonly envValue?: string;\n}): number {\n\tconst raw =\n\t\tparams?.envValue ??\n\t\t(typeof process !== 'undefined'\n\t\t\t? process.env.MCP_TOOL_TIMEOUT\n\t\t\t: undefined);\n\tconst parsed = Number.parseInt(raw ?? '', 10);\n\tif (Number.isFinite(parsed) && parsed > 0) return parsed;\n\treturn DEFAULT_MCP_REQUEST_TIMEOUT_MS;\n}\n\nexport interface JsonRpcResponse {\n\treadonly id?: number;\n\treadonly result?: unknown;\n\treadonly error?: {readonly message?: string; readonly code?: number};\n\t// Present on notifications (no id) — routed by the transports for\n\t// progress + tools/list_changed handling.\n\treadonly method?: string;\n\treadonly params?: Record<string, unknown>;\n}\n\n// MCP tool annotations (spec 2025-03-26 §Tool.annotations). Hints, not\n// guarantees: readOnlyHint drives our concurrency/read-only classification the\n// way codex + Claude Code use it; destructive/openWorld are surfaced for\n// permission UIs. All default to \"absent\" — an unannotated tool is treated as\n// potentially mutating (fail closed).\nexport interface McpToolAnnotations {\n\treadonly title?: string;\n\treadonly readOnlyHint?: boolean;\n\treadonly destructiveHint?: boolean;\n\treadonly idempotentHint?: boolean;\n\treadonly openWorldHint?: boolean;\n}\n\nexport interface McpToolDef {\n\treadonly name: string;\n\treadonly description?: string;\n\t// Open-ended: a server may declare any JSON Schema keyword here ($defs,\n\t// definitions, additionalProperties, …) and mcpToolDefToSchema forwards the\n\t// ones it doesn't own. Dropping them is what broke strict providers.\n\treadonly inputSchema?: {\n\t\treadonly properties?: Record<string, unknown>;\n\t\treadonly required?: readonly string[];\n\t\treadonly type?: unknown;\n\t\treadonly $schema?: unknown;\n\t\treadonly [keyword: string]: unknown;\n\t};\n\t// Declared result shape (spec §Tool.outputSchema). Carried for future\n\t// structured-output validation; not enforced today.\n\treadonly outputSchema?: Record<string, unknown>;\n\treadonly annotations?: McpToolAnnotations;\n}\n\nexport function mcpToolDefToSchema(def: McpToolDef): ToolSchema {\n\t// Fall back to a synthesized description (never empty) so the model still\n\t// has something to select on and providers that reject empty tool\n\t// descriptions don't error. Uses `||` (not `??`) so an explicit empty\n\t// string also falls back — some servers send `description: ''` rather than\n\t// omitting it. Mirrors command's tool-adapter default.\n\tconst raw = def.description || `MCP tool: ${def.name}`;\n\t// Cap runaway descriptions — they're system-prompt bytes on every request.\n\tconst description =\n\t\traw.length > MCP_MAX_DESCRIPTION_CHARS\n\t\t\t? `${raw.slice(0, MCP_MAX_DESCRIPTION_CHARS)}… [truncated]`\n\t\t\t: raw;\n\t// annotations.title is the human display name (spec: precedence over name\n\t// for UIs). ToolSchema.label is display-only — toWireTools strips it, so\n\t// the model never sees it and the wire name stays the sanitized one.\n\tconst title = def.annotations?.title;\n\t// Forward the server's remaining schema keywords instead of rebuilding the\n\t// wrapper from just properties/required. Cherry-picking those two dropped the\n\t// sibling `$defs` bucket while leaving the `$ref`s that point into it, and a\n\t// dangling ref makes Moonshot (Kimi) reject the whole request as \"not a valid\n\t// moonshot flavored json schema\". `type` is re-asserted below (tools are always\n\t// object-shaped) and `$schema` is dropped — a meta-key providers don't want.\n\tconst {\n\t\t$schema: _metaSchema,\n\t\ttype: _declaredType,\n\t\tproperties: _properties,\n\t\trequired: _required,\n\t\t...extraKeywords\n\t} = def.inputSchema ?? {};\n\treturn {\n\t\tname: def.name,\n\t\t...(title ? {label: title} : {}),\n\t\tdescription,\n\t\tinput_schema: {\n\t\t\t...extraKeywords,\n\t\t\ttype: 'object',\n\t\t\tproperties: def.inputSchema?.properties ?? {},\n\t\t\trequired: [...(def.inputSchema?.required ?? [])],\n\t\t},\n\t};\n}\n\n// ── result content transformation ────────────────────────────────────────────\n\ninterface McpContentBlock {\n\treadonly type?: string;\n\treadonly text?: string;\n\treadonly data?: string;\n\treadonly mimeType?: string;\n\treadonly name?: string;\n\treadonly description?: string;\n\treadonly uri?: string;\n\treadonly resource?: {\n\t\treadonly uri?: string;\n\t\treadonly text?: string;\n\t\treadonly blob?: string;\n\t\treadonly mimeType?: string;\n\t};\n}\n\n// Where a decoded MCP binary payload landed (audio blocks, non-image resource\n// blobs). The persister writes RAW BYTES — never base64 text — so downstream\n// native readers get valid PDFs/archives/media.\nexport interface McpPersistedBinary {\n\treadonly filepath: string;\n\treadonly size: number;\n}\n\nexport type McpBinaryPersistResult =\n\t| McpPersistedBinary\n\t| {readonly error: string};\n\nexport type McpBinaryPersister = (params: {\n\treadonly bytes: Uint8Array;\n\treadonly mimeType?: string;\n}) => McpBinaryPersistResult;\n\nexport interface McpResultOptions {\n\t// Provenance for resource prefixes (\"[Resource from <server> at <uri>]\").\n\treadonly serverName?: string;\n\t// Sink for binary payloads. Absent → binary content becomes a short\n\t// placeholder note instead of flooding the context with base64.\n\treadonly persistBinary?: McpBinaryPersister;\n}\n\n// Image MIME types the model can actually view — everything else persists as a\n// file notice (matches Claude Code's IMAGE_MIME_TYPES allowlist).\nconst VIEWABLE_IMAGE_MIME_TYPES = new Set([\n\t'image/png',\n\t'image/jpeg',\n\t'image/gif',\n\t'image/webp',\n]);\n\nfunction formatByteSize(sizeInBytes: number): string {\n\tconst kilobytes = sizeInBytes / 1_024;\n\tif (kilobytes < 1) return `${sizeInBytes} bytes`;\n\tif (kilobytes < 1_024)\n\t\treturn `${kilobytes.toFixed(1).replace(/\\.0$/, '')}KB`;\n\tconst megabytes = kilobytes / 1_024;\n\treturn `${megabytes.toFixed(1).replace(/\\.0$/, '')}MB`;\n}\n\nfunction decodeBase64(data: string): Uint8Array {\n\treturn new Uint8Array(Buffer.from(data, 'base64'));\n}\n\n// Persist decoded bytes and describe the outcome as one text block. A persist\n// failure (or missing persister) degrades to a placeholder — never base64 into\n// the model context, never a thrown error that loses sibling blocks.\nfunction persistedBinaryText(params: {\n\treadonly data: string;\n\treadonly mimeType?: string;\n\treadonly sourcePrefix: string;\n\treadonly options?: McpResultOptions;\n}): ToolResultContent {\n\tconst bytes = decodeBase64(params.data);\n\tconst mime = params.mimeType ?? 'unknown type';\n\tconst persist = params.options?.persistBinary;\n\tif (!persist) {\n\t\treturn {\n\t\t\ttype: 'text',\n\t\t\ttext: `${params.sourcePrefix}Binary content (${mime}, ${formatByteSize(\n\t\t\t\tbytes.byteLength,\n\t\t\t)}) omitted — no binary store configured.`,\n\t\t};\n\t}\n\tconst persisted = persist({bytes, mimeType: params.mimeType});\n\tif ('error' in persisted) {\n\t\treturn {\n\t\t\ttype: 'text',\n\t\t\ttext: `${params.sourcePrefix}Binary content (${mime}, ${formatByteSize(\n\t\t\t\tbytes.byteLength,\n\t\t\t)}) could not be saved to disk: ${persisted.error}`,\n\t\t};\n\t}\n\treturn {\n\t\ttype: 'text',\n\t\ttext: `${params.sourcePrefix}Binary content (${mime}, ${formatByteSize(\n\t\t\tpersisted.size,\n\t\t)}) saved to ${persisted.filepath}`,\n\t};\n}\n\nfunction resourcePrefix(params: {\n\treadonly uri: string;\n\treadonly options?: McpResultOptions;\n}): string {\n\tconst server = params.options?.serverName;\n\tif (server) return `[Resource from ${server} at ${params.uri}] `;\n\treturn `[Resource: ${params.uri}] `;\n}\n\n// One MCP content block → harness ToolResultContent blocks. Text passes through;\n// images become base64 image blocks (the model can see them); audio + non-image\n// resource blobs persist to disk (a location notice, never inline base64);\n// resource text/links are summarized with provenance. May emit multiple blocks\n// (a resource image = provenance text + image).\nfunction blockToContents(\n\tblock: McpContentBlock,\n\toptions?: McpResultOptions,\n): readonly ToolResultContent[] {\n\tif (block.type === 'text' && typeof block.text === 'string') {\n\t\treturn [{type: 'text', text: block.text}];\n\t}\n\tif (block.type === 'image' && typeof block.data === 'string') {\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: 'image',\n\t\t\t\tsource: {\n\t\t\t\t\ttype: 'base64',\n\t\t\t\t\tmedia_type: block.mimeType ?? 'image/png',\n\t\t\t\t\tdata: block.data,\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\t}\n\tif (block.type === 'audio' && typeof block.data === 'string') {\n\t\tconst server = options?.serverName;\n\t\treturn [\n\t\t\tpersistedBinaryText({\n\t\t\t\tdata: block.data,\n\t\t\t\tmimeType: block.mimeType,\n\t\t\t\tsourcePrefix: server ? `[Audio from ${server}] ` : '[Audio] ',\n\t\t\t\toptions,\n\t\t\t}),\n\t\t];\n\t}\n\tif (block.type === 'resource') {\n\t\treturn resourceToContents(block, options);\n\t}\n\tif (block.type === 'resource_link' && typeof block.uri === 'string') {\n\t\tconst name = block.name ?? block.uri;\n\t\tconst description = block.description ? ` (${block.description})` : '';\n\t\treturn [\n\t\t\t{\n\t\t\t\ttype: 'text',\n\t\t\t\ttext: `[Resource link: ${name}] ${block.uri}${description}`,\n\t\t\t},\n\t\t];\n\t}\n\t// Unknown block shape — preserve it verbatim so nothing is silently dropped.\n\treturn [{type: 'text', text: JSON.stringify(block)}];\n}\n\nfunction resourceToContents(\n\tblock: McpContentBlock,\n\toptions?: McpResultOptions,\n): readonly ToolResultContent[] {\n\tconst resource = block.resource;\n\tconst uri = resource?.uri ?? 'unknown';\n\tconst prefix = resourcePrefix({uri, options});\n\tif (resource && typeof resource.text === 'string') {\n\t\treturn [{type: 'text', text: `${prefix}${resource.text}`}];\n\t}\n\tif (resource && typeof resource.blob === 'string') {\n\t\t// A viewable image blob stays a real image block (with a provenance text\n\t\t// block ahead of it); everything else persists to disk.\n\t\tconst mime = resource.mimeType ?? '';\n\t\tif (VIEWABLE_IMAGE_MIME_TYPES.has(mime)) {\n\t\t\treturn [\n\t\t\t\t{type: 'text', text: prefix.trimEnd()},\n\t\t\t\t{\n\t\t\t\t\ttype: 'image',\n\t\t\t\t\tsource: {\n\t\t\t\t\t\ttype: 'base64',\n\t\t\t\t\t\tmedia_type: mime,\n\t\t\t\t\t\tdata: resource.blob,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\t\t}\n\t\treturn [\n\t\t\tpersistedBinaryText({\n\t\t\t\tdata: resource.blob,\n\t\t\t\tmimeType: resource.mimeType,\n\t\t\t\tsourcePrefix: prefix,\n\t\t\t\toptions,\n\t\t\t}),\n\t\t];\n\t}\n\treturn [{type: 'text', text: `[Resource: ${uri}]`}];\n}\n\ninterface McpToolCallResult {\n\treadonly content?: unknown;\n\treadonly structuredContent?: unknown;\n\treadonly toolResult?: unknown;\n\treadonly isError?: boolean;\n}\n\n// Map an MCP `tools/call` result to a ToolRunResult. Shape precedence mirrors\n// Claude Code: the pre-spec `toolResult` field, then `structuredContent`\n// (compact JSON — precise for the model), then the `content` block array, then\n// a JSON dump of the whole result so nothing is silently lost. A tool-level\n// error (`isError: true`) is a FAILED tool run even though the JSON-RPC call\n// itself succeeded — surfacing it as ok:true would hide real failures from the\n// model.\nexport function mcpResultToToolRunResult(\n\tresult: unknown,\n\toptions?: McpResultOptions,\n): ToolRunResult {\n\tconst typed = (result ?? {}) as McpToolCallResult;\n\tconst rawContent = typed.content;\n\tconst contentBlocks: readonly ToolResultContent[] | undefined =\n\t\tArray.isArray(rawContent)\n\t\t\t? rawContent.flatMap(block =>\n\t\t\t\t\tblockToContents(block as McpContentBlock, options),\n\t\t\t\t)\n\t\t\t: undefined;\n\n\tif (typed.isError === true) {\n\t\tconst errorText = (contentBlocks ?? [])\n\t\t\t.map(block => (block.type === 'text' ? block.text : '[non-text]'))\n\t\t\t.join('\\n');\n\t\treturn {ok: false, error: errorText || 'MCP tool reported an error'};\n\t}\n\n\t// Legacy pre-spec servers return a bare `toolResult` value.\n\tif ('toolResult' in typed) {\n\t\tconst value = typed.toolResult;\n\t\tconst text = typeof value === 'string' ? value : JSON.stringify(value);\n\t\treturn {ok: true, content: [{type: 'text', text}]};\n\t}\n\n\t// structuredContent wins over the content array (spec: content SHOULD\n\t// mirror it for backwards compatibility — the structured form is the\n\t// precise one) UNLESS the content array carries non-text blocks the JSON\n\t// form would lose (images).\n\tif (typed.structuredContent !== undefined) {\n\t\tconst hasNonText = (contentBlocks ?? []).some(\n\t\t\tblock => block.type !== 'text',\n\t\t);\n\t\tif (!hasNonText) {\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\ttext: JSON.stringify(typed.structuredContent),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t}\n\n\tif (contentBlocks) {\n\t\treturn {ok: true, content: contentBlocks};\n\t}\n\treturn {ok: true, content: [{type: 'text', text: JSON.stringify(result)}]};\n}\n\n// MCP tool/server names handed to the model must match ^[a-zA-Z0-9_-]+$ (the\n// schema constraint Anthropic enforces). Replace anything else with `_`.\nexport function sanitizeMcpToolName(name: string): string {\n\treturn name.replace(/[^a-zA-Z0-9_-]/g, '_');\n}\n\n// ── tool-name (mcp__<server>__<tool>) parsing ────────────────────────────────\n// The namespaced tool name the model sees (built in mcp.ts). Parsing it back lets\n// the tool catalog, mode gating, and feed rendering tell MCP tools from built-ins\n// and recover the originating server/tool.\nexport interface ParsedMcpToolName {\n\treadonly serverName: string;\n\treadonly toolName: string;\n}\n\n// True when a tool name uses the `mcp__server__tool` prefix convention.\nexport function isMcpTool(toolName: string): boolean {\n\treturn toolName.startsWith('mcp__');\n}\n\n// Split a prefixed MCP tool name into its server + tool parts. Returns null for\n// non-MCP names or malformed prefixes (fewer than 3 `__`-separated segments).\nexport function parseMcpToolName(\n\tprefixedName: string,\n): ParsedMcpToolName | null {\n\tif (!isMcpTool(prefixedName)) return null;\n\tconst parts = prefixedName.split('__');\n\tif (parts.length < 3) return null;\n\tconst serverName = parts[1];\n\tif (!serverName) return null;\n\treturn {\n\t\tserverName,\n\t\t// Tool names may themselves contain `__`, so rejoin everything after the server segment.\n\t\ttoolName: parts.slice(2).join('__'),\n\t};\n}\n","// MCP OAuth (PKCE) — everything needed to authenticate to an OAuth-protected MCP\n// server: metadata discovery (RFC 8414 / RFC 9728 / OIDC), a PKCE challenge, the\n// authorization URL, the code→token exchange + refresh, and the interactive\n// auth-code flow (loopback callback server + browser open + CSRF/state check).\n//\n// Zero-dep: node built-ins only (node:crypto, node:http, node:url, node:child_process).\n// fetch + the browser opener are injectable so every piece stays testable.\n\nimport {spawn} from 'node:child_process';\nimport {createHash, randomBytes} from 'node:crypto';\nimport {createServer, type Server} from 'node:http';\nimport {URL} from 'node:url';\nimport {MCP_CLIENT_INFO, MCP_PROTOCOL_VERSION} from './protocol.js';\n\nexport interface OAuthFetchResponse {\n\treadonly ok?: boolean;\n\treadonly status?: number;\n\treadonly statusText?: string;\n\treadonly headers?: {get(name: string): string | null};\n\tjson(): Promise<unknown>;\n\ttext?(): Promise<string>;\n}\n\nexport type OAuthFetchImpl = (\n\turl: string,\n\tinit?: {\n\t\treadonly method?: string;\n\t\treadonly headers?: Record<string, string>;\n\t\treadonly body?: string;\n\t\treadonly signal?: AbortSignal;\n\t},\n) => Promise<OAuthFetchResponse>;\n\nfunction defaultFetch(): OAuthFetchImpl {\n\treturn globalThis.fetch as unknown as OAuthFetchImpl;\n}\n\n// Token-endpoint + probe calls must not hang the agent forever. The interactive\n// auth path injects its own timed fetch, but the BACKGROUND refresh path (through\n// http-client's getValidAccessToken) hands us the raw, untimed globalThis.fetch —\n// so an unresponsive authorization server would otherwise stall a tool call\n// indefinitely. Mirrors command's oauth-flow.ts 80s FETCH_TIMEOUT_MS.\nconst OAUTH_REQUEST_TIMEOUT_MS = 80_000;\n\nasync function fetchWithTimeout(\n\tfetchImpl: OAuthFetchImpl,\n\turl: string,\n\tinit: {\n\t\treadonly method?: string;\n\t\treadonly headers?: Record<string, string>;\n\t\treadonly body?: string;\n\t},\n\ttimeoutMs = OAUTH_REQUEST_TIMEOUT_MS,\n): Promise<OAuthFetchResponse> {\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), timeoutMs);\n\ttry {\n\t\treturn await fetchImpl(url, {...init, signal: controller.signal});\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\nfunction queryString(params: Record<string, string>): string {\n\treturn Object.entries(params)\n\t\t.map(\n\t\t\t([key, value]) =>\n\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t)\n\t\t.join('&');\n}\n\n// How a token request body is encoded. Most servers (and every MCP caller) want the OAuth2\n// default form-urlencoded; some providers (e.g. Anthropic's token endpoint) require a JSON body.\nexport type TokenRequestEncoding = 'form' | 'json';\n\n// Build the headers + body for a token request in the requested encoding. Keeps form-encoded the\n// default so existing MCP callers are byte-for-byte unchanged.\nfunction encodeTokenRequest(\n\tfields: Record<string, string>,\n\tencoding: TokenRequestEncoding,\n): {readonly headers: Record<string, string>; readonly body: string} {\n\tif (encoding === 'json') {\n\t\treturn {\n\t\t\theaders: {\n\t\t\t\t'content-type': 'application/json',\n\t\t\t\taccept: 'application/json',\n\t\t\t},\n\t\t\tbody: JSON.stringify(fields),\n\t\t};\n\t}\n\treturn {\n\t\theaders: {'content-type': 'application/x-www-form-urlencoded'},\n\t\tbody: queryString(fields),\n\t};\n}\n\n// ── URL safety ───────────────────────────────────────────────────────────────\n// True for https:// URLs and for http:// URLs whose host is a loopback address.\n// RFC 8252 carves out loopback for native-app OAuth, so local-dev MCP servers\n// (http://localhost, http://127.0.0.1, http://[::1]) are allowed even with OAuth.\nexport function isSecureOrLoopback(url: string): boolean {\n\ttry {\n\t\tconst parsed = new URL(url);\n\t\tif (parsed.protocol === 'https:') return true;\n\t\tif (parsed.protocol !== 'http:') return false;\n\t\treturn (\n\t\t\tparsed.hostname === 'localhost' ||\n\t\t\tparsed.hostname === '127.0.0.1' ||\n\t\t\tparsed.hostname === '[::1]' ||\n\t\t\tparsed.hostname === '::1'\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// ── PKCE ─────────────────────────────────────────────────────────────────────\nexport interface Pkce {\n\treadonly verifier: string;\n\treadonly challenge: string; // base64url(sha256(verifier)) — the S256 method\n}\n\nexport function generatePkce(\n\tparams: {readonly randomBytesImpl?: (size: number) => Buffer} = {},\n): Pkce {\n\tconst verifier = (params.randomBytesImpl ?? randomBytes)(32).toString(\n\t\t'base64url',\n\t);\n\tconst challenge = createHash('sha256').update(verifier).digest('base64url');\n\treturn {verifier, challenge};\n}\n\n// ── OAuth config + token shapes ──────────────────────────────────────────────\nexport interface OAuthConfig {\n\treadonly authorizationUrl: string;\n\treadonly tokenUrl: string;\n\treadonly clientId: string;\n\treadonly clientSecret?: string;\n\treadonly scopes?: readonly string[];\n}\n\nexport interface TokenResult {\n\treadonly accessToken: string;\n\treadonly refreshToken?: string;\n\treadonly expiresAt?: number; // epoch ms\n\treadonly tokenType?: string;\n\treadonly scope?: string;\n\t// Origin (scheme://host[:port]) of the MCP server the token was issued for.\n\t// Bearer tokens are only attached to requests whose URL origin matches this.\n\treadonly issuerUrl?: string;\n}\n\ninterface RawTokenResponse {\n\treadonly access_token?: string;\n\treadonly refresh_token?: string;\n\treadonly expires_in?: number;\n\treadonly token_type?: string;\n\treadonly scope?: string;\n}\n\nfunction toTokenResult(\n\traw: RawTokenResponse,\n\tnow: () => number,\n\tfallbackRefreshToken?: string,\n): TokenResult {\n\tif (!raw.access_token) {\n\t\tthrow new Error('OAuth token response had no access_token');\n\t}\n\treturn {\n\t\taccessToken: raw.access_token,\n\t\trefreshToken: raw.refresh_token ?? fallbackRefreshToken,\n\t\texpiresAt:\n\t\t\ttypeof raw.expires_in === 'number'\n\t\t\t\t? now() + raw.expires_in * 1000\n\t\t\t\t: undefined,\n\t\ttokenType: raw.token_type,\n\t\tscope: raw.scope,\n\t};\n}\n\n// ── Authorization-server metadata discovery ──────────────────────────────────\nexport interface AuthServerMetadata {\n\treadonly authorizationEndpoint: string;\n\treadonly tokenEndpoint: string;\n\treadonly registrationEndpoint?: string;\n\treadonly scopes?: readonly string[];\n}\n\n// RFC 8414 §3: the well-known suffix is inserted BETWEEN host and issuer path.\n// https://ex.com -> https://ex.com/.well-known/oauth-authorization-server\n// https://ex.com/v1/oauth -> https://ex.com/.well-known/oauth-authorization-server/v1/oauth\nexport function buildOAuthMetadataUrl(issuerUrl: string): string {\n\tconst parsed = new URL(issuerUrl);\n\tconst issuerPath =\n\t\tparsed.pathname === '/' ? '' : parsed.pathname.replace(/\\/+$/, '');\n\tparsed.pathname = `/.well-known/oauth-authorization-server${issuerPath}`;\n\tparsed.search = '';\n\tparsed.hash = '';\n\treturn parsed.toString();\n}\n\n// OIDC Core 1.0 §4 APPENDS `/.well-known/openid-configuration` to the issuer.\nexport function buildOidcMetadataUrl(issuerUrl: string): string {\n\tconst parsed = new URL(issuerUrl);\n\tconst issuerPath = parsed.pathname.replace(/\\/+$/, '');\n\tparsed.pathname = `${issuerPath}/.well-known/openid-configuration`;\n\tparsed.search = '';\n\tparsed.hash = '';\n\treturn parsed.toString();\n}\n\nasync function tryFetchMetadata(\n\tmetadataUrl: string,\n\tfetchImpl: OAuthFetchImpl,\n): Promise<AuthServerMetadata | null> {\n\ttry {\n\t\tconst response = await fetchImpl(metadataUrl, {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {accept: 'application/json'},\n\t\t});\n\t\tif (response.ok === false) return null;\n\t\tconst meta = (await response.json()) as {\n\t\t\tauthorization_endpoint?: string;\n\t\t\ttoken_endpoint?: string;\n\t\t\tregistration_endpoint?: string;\n\t\t\tscopes_supported?: string[];\n\t\t};\n\t\tif (!meta.authorization_endpoint || !meta.token_endpoint) return null;\n\t\treturn {\n\t\t\tauthorizationEndpoint: meta.authorization_endpoint,\n\t\t\ttokenEndpoint: meta.token_endpoint,\n\t\t\tregistrationEndpoint: meta.registration_endpoint,\n\t\t\tscopes: meta.scopes_supported,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// RFC 8414 discovery from an issuer identifier, falling back to OIDC discovery.\nexport async function discoverAuthServer(params: {\n\treadonly issuerUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<AuthServerMetadata> {\n\tconst meta = await discoverOAuthMetadataFromIssuer({\n\t\tissuerUrl: params.issuerUrl,\n\t\tfetchImpl: params.fetchImpl,\n\t});\n\tif (!meta) {\n\t\tthrow new Error('discoverAuthServer: missing endpoints in metadata');\n\t}\n\treturn meta;\n}\n\nexport async function discoverOAuthMetadataFromIssuer(params: {\n\treadonly issuerUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<AuthServerMetadata | null> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst oauthMeta = await tryFetchMetadata(\n\t\tbuildOAuthMetadataUrl(params.issuerUrl),\n\t\tfetchImpl,\n\t);\n\tif (oauthMeta) return oauthMeta;\n\treturn tryFetchMetadata(buildOidcMetadataUrl(params.issuerUrl), fetchImpl);\n}\n\n// Probe a server's origin for well-known metadata when the issuer is unknown.\n// Prefer the issuer-aware variant whenever an issuer can be obtained.\nexport async function discoverOAuthMetadata(params: {\n\treadonly serverUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<AuthServerMetadata | null> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst origin = new URL(params.serverUrl).origin;\n\tconst oauthMeta = await tryFetchMetadata(\n\t\t`${origin}/.well-known/oauth-authorization-server`,\n\t\tfetchImpl,\n\t);\n\tif (oauthMeta) return oauthMeta;\n\treturn tryFetchMetadata(\n\t\t`${origin}/.well-known/openid-configuration`,\n\t\tfetchImpl,\n\t);\n}\n\n// Parse the `resource_metadata` param from a WWW-Authenticate header (RFC 9728 §5.1).\nexport function parseResourceMetadataUrl(\n\twwwAuthenticate: string | null | undefined,\n): string | null {\n\tif (!wwwAuthenticate) return null;\n\tconst match = wwwAuthenticate.match(\n\t\t/resource_metadata\\s*=\\s*\"([^\"]+)\"|resource_metadata\\s*=\\s*([^\\s,]+)/i,\n\t);\n\treturn match ? (match[1] ?? match[2] ?? null) : null;\n}\n\nasync function fetchProtectedResourceMetadata(\n\turl: string,\n\tfetchImpl: OAuthFetchImpl,\n): Promise<{\n\tauthorizationServers?: string[];\n\tscopesSupported?: string[];\n} | null> {\n\ttry {\n\t\tconst response = await fetchImpl(url, {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {accept: 'application/json'},\n\t\t});\n\t\tif (response.ok === false) return null;\n\t\tconst data = (await response.json()) as {\n\t\t\tauthorization_servers?: string[];\n\t\t\tscopes_supported?: string[];\n\t\t};\n\t\treturn {\n\t\t\tauthorizationServers: data.authorization_servers,\n\t\t\tscopesSupported: data.scopes_supported,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface ServerAuthRequirements {\n\treadonly requiresAuth: boolean;\n\treadonly metadata?: AuthServerMetadata;\n\treadonly error?: string;\n}\n\n// Probe an MCP server to learn whether it requires OAuth and, if so, where to\n// authenticate. Honors RFC 9728 (the WWW-Authenticate `resource_metadata`\n// pointer names the real authorization server, which often lives on a different\n// host than the MCP endpoint) before falling back to same-origin probing.\nexport async function checkServerAuthRequirements(params: {\n\treadonly serverUrl: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<ServerAuthRequirements> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\ttry {\n\t\tconst response = await fetchWithTimeout(fetchImpl, params.serverUrl, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {'content-type': 'application/json'},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tjsonrpc: '2.0',\n\t\t\t\tmethod: 'initialize',\n\t\t\t\tid: 0,\n\t\t\t\t// clientInfo is required by the MCP `initialize` spec; a server that\n\t\t\t\t// validates the body before auth would 400 a probe without it (and we\n\t\t\t\t// would then misread that as \"no auth required\").\n\t\t\t\tparams: {\n\t\t\t\t\tprotocolVersion: MCP_PROTOCOL_VERSION,\n\t\t\t\t\tcapabilities: {},\n\t\t\t\t\tclientInfo: MCP_CLIENT_INFO,\n\t\t\t\t},\n\t\t\t}),\n\t\t});\n\t\tconst status = response.status ?? 200;\n\t\tif (status === 401 || status === 403) {\n\t\t\tconst wwwAuth = response.headers?.get('www-authenticate') ?? null;\n\t\t\tconst resourceMetadataUrl = parseResourceMetadataUrl(wwwAuth);\n\t\t\tif (resourceMetadataUrl) {\n\t\t\t\tconst prm = await fetchProtectedResourceMetadata(\n\t\t\t\t\tresourceMetadataUrl,\n\t\t\t\t\tfetchImpl,\n\t\t\t\t);\n\t\t\t\tconst issuer = prm?.authorizationServers?.[0];\n\t\t\t\tif (issuer) {\n\t\t\t\t\tconst metadata = await discoverOAuthMetadataFromIssuer({\n\t\t\t\t\t\tissuerUrl: issuer,\n\t\t\t\t\t\tfetchImpl,\n\t\t\t\t\t});\n\t\t\t\t\tif (metadata) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\trequiresAuth: true,\n\t\t\t\t\t\t\tmetadata: prm?.scopesSupported\n\t\t\t\t\t\t\t\t? {...metadata, scopes: prm.scopesSupported}\n\t\t\t\t\t\t\t\t: metadata,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst metadata = await discoverOAuthMetadata({\n\t\t\t\tserverUrl: params.serverUrl,\n\t\t\t\tfetchImpl,\n\t\t\t});\n\t\t\treturn {requiresAuth: true, metadata: metadata ?? undefined};\n\t\t}\n\t\treturn {requiresAuth: false};\n\t} catch (error) {\n\t\treturn {\n\t\t\trequiresAuth: false,\n\t\t\terror: `Server unreachable: ${String(error)}`,\n\t\t};\n\t}\n}\n\n// RFC 7591 dynamic client registration — some servers mint a client on demand.\nexport async function registerOAuthClient(params: {\n\treadonly registrationEndpoint: string;\n\treadonly clientName: string;\n\treadonly redirectUris: readonly string[];\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<{clientId: string; clientSecret?: string} | null> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\ttry {\n\t\tconst response = await fetchImpl(params.registrationEndpoint, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {'content-type': 'application/json'},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tclient_name: params.clientName,\n\t\t\t\tredirect_uris: params.redirectUris,\n\t\t\t\ttoken_endpoint_auth_method: 'none', // public client (PKCE)\n\t\t\t\tgrant_types: ['authorization_code', 'refresh_token'],\n\t\t\t\tresponse_types: ['code'],\n\t\t\t}),\n\t\t});\n\t\tif (response.ok === false) return null;\n\t\tconst data = (await response.json()) as {\n\t\t\tclient_id?: string;\n\t\t\tclient_secret?: string;\n\t\t};\n\t\tif (!data.client_id) return null;\n\t\treturn {clientId: data.client_id, clientSecret: data.client_secret};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// ── Authorization URL ────────────────────────────────────────────────────────\nexport function buildAuthorizationUrl(params: {\n\treadonly authorizationEndpoint: string;\n\treadonly clientId: string;\n\treadonly redirectUri: string;\n\treadonly challenge: string;\n\treadonly scope?: string;\n\treadonly state?: string;\n}): string {\n\tconst query: Record<string, string> = {\n\t\tresponse_type: 'code',\n\t\tclient_id: params.clientId,\n\t\tredirect_uri: params.redirectUri,\n\t\tcode_challenge: params.challenge,\n\t\tcode_challenge_method: 'S256',\n\t};\n\tif (params.scope) query.scope = params.scope;\n\tif (params.state) query.state = params.state;\n\t// Merge into any existing query on the endpoint via the URL API. Raw\n\t// `?${queryString}` concatenation double-`?`s an authorization_endpoint that\n\t// already carries a query (e.g. multi-tenant `.../authorize?tenant=acme`),\n\t// which the authorization server then can't parse.\n\tconst url = new URL(params.authorizationEndpoint);\n\tfor (const [key, value] of Object.entries(query)) {\n\t\turl.searchParams.set(key, value);\n\t}\n\treturn url.toString();\n}\n\n// ── Token exchange + refresh ─────────────────────────────────────────────────\nexport async function exchangeCodeForToken(params: {\n\treadonly tokenEndpoint: string;\n\treadonly code: string;\n\treadonly verifier: string;\n\treadonly clientId: string;\n\treadonly redirectUri: string;\n\treadonly clientSecret?: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n\t// Request body encoding — default form-urlencoded (OAuth2 / every MCP caller); 'json' for\n\t// providers whose token endpoint requires a JSON body (e.g. Anthropic).\n\treadonly encoding?: TokenRequestEncoding;\n}): Promise<TokenResult> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst form: Record<string, string> = {\n\t\tgrant_type: 'authorization_code',\n\t\tcode: params.code,\n\t\tcode_verifier: params.verifier,\n\t\tclient_id: params.clientId,\n\t\tredirect_uri: params.redirectUri,\n\t};\n\tif (params.clientSecret) form.client_secret = params.clientSecret;\n\tconst {headers, body} = encodeTokenRequest(form, params.encoding ?? 'form');\n\tconst response = await fetchWithTimeout(fetchImpl, params.tokenEndpoint, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody,\n\t});\n\tif (response.ok === false) {\n\t\tconst body = response.text ? await response.text() : '';\n\t\tthrow new Error(\n\t\t\t`Token exchange failed: ${response.status ?? '?'} ${body}`.trim(),\n\t\t);\n\t}\n\treturn toTokenResult(\n\t\t(await response.json()) as RawTokenResponse,\n\t\tparams.now ?? (() => Date.now()),\n\t);\n}\n\nexport async function refreshAccessToken(params: {\n\treadonly tokenEndpoint: string;\n\treadonly refreshToken: string;\n\treadonly clientId: string;\n\treadonly clientSecret?: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n\t// Request body encoding — default form-urlencoded; 'json' for providers (e.g. Anthropic) whose\n\t// token endpoint requires a JSON body.\n\treadonly encoding?: TokenRequestEncoding;\n}): Promise<TokenResult> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst form: Record<string, string> = {\n\t\tgrant_type: 'refresh_token',\n\t\trefresh_token: params.refreshToken,\n\t\tclient_id: params.clientId,\n\t};\n\tif (params.clientSecret) form.client_secret = params.clientSecret;\n\tconst {headers, body} = encodeTokenRequest(form, params.encoding ?? 'form');\n\tconst response = await fetchWithTimeout(fetchImpl, params.tokenEndpoint, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody,\n\t});\n\tif (response.ok === false) {\n\t\tconst body = response.text ? await response.text() : '';\n\t\tthrow new Error(\n\t\t\t`Token refresh failed: ${response.status ?? '?'} ${body}`.trim(),\n\t\t);\n\t}\n\t// Keep the old refresh token if the server didn't rotate it.\n\treturn toTokenResult(\n\t\t(await response.json()) as RawTokenResponse,\n\t\tparams.now ?? (() => Date.now()),\n\t\tparams.refreshToken,\n\t);\n}\n\n// ── Interactive auth-code + PKCE flow ────────────────────────────────────────\nconst DEFAULT_CALLBACK_PORT = 8085;\nconst LOOPBACK_HOST = '127.0.0.1';\n\nexport interface OAuthResult {\n\treadonly success: boolean;\n\treadonly token?: TokenResult;\n\treadonly error?: string;\n}\n\n// Escape HTML so an attacker-influenced error_description can't inject script\n// into the page rendered back into the user's browser.\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/'/g, ''');\n}\n\nfunction htmlPage(title: string, body: string): string {\n\treturn `<!DOCTYPE html><html><head><title>${title}</title></head><body style=\"font-family: system-ui; padding: 40px; text-align: center;\"><h1>${title}</h1><p>${body}</p></body></html>`;\n}\n\ninterface CallbackServer {\n\treadonly server: Server;\n\treadonly waitForCode: () => Promise<string>;\n}\n\nfunction startCallbackServer(\n\tport: number,\n\texpectedState: string,\n): Promise<CallbackServer> {\n\treturn new Promise((resolveServer, rejectServer) => {\n\t\tlet resolveCode: ((code: string) => void) | null = null;\n\t\tlet rejectCode: ((error: Error) => void) | null = null;\n\t\tconst codePromise = new Promise<string>((resolve, reject) => {\n\t\t\tresolveCode = resolve;\n\t\t\trejectCode = reject;\n\t\t});\n\t\t// Mark as handled so an early callback (e.g. an injected opener that fires\n\t\t// before the caller attaches its consumer) can't trip an unhandled\n\t\t// rejection; the real consumer still receives the resolution/rejection.\n\t\tcodePromise.catch(() => {});\n\n\t\tconst server = createServer((request, response) => {\n\t\t\tconst requestUrl = new URL(\n\t\t\t\trequest.url ?? '/',\n\t\t\t\t`http://${LOOPBACK_HOST}:${port}`,\n\t\t\t);\n\t\t\tif (requestUrl.pathname !== '/callback') {\n\t\t\t\tresponse.writeHead(404, {Connection: 'close'});\n\t\t\t\tresponse.end('Not Found');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = requestUrl.searchParams.get('code');\n\t\t\tconst error = requestUrl.searchParams.get('error');\n\t\t\tconst errorDescription =\n\t\t\t\trequestUrl.searchParams.get('error_description');\n\t\t\tconst state = requestUrl.searchParams.get('state');\n\n\t\t\tconst respond = (statusCode: number, page: string): void => {\n\t\t\t\tresponse.writeHead(statusCode, {\n\t\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\t\tConnection: 'close',\n\t\t\t\t});\n\t\t\t\tresponse.end(page);\n\t\t\t};\n\n\t\t\t// CSRF defense: the state we sent must come back unchanged.\n\t\t\tif (state !== expectedState) {\n\t\t\t\trespond(\n\t\t\t\t\t400,\n\t\t\t\t\thtmlPage(\n\t\t\t\t\t\t'Authentication Failed',\n\t\t\t\t\t\t'Invalid state parameter. Please try again.',\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error('OAuth state parameter mismatch'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (error) {\n\t\t\t\tconst safe = escapeHtml(errorDescription || error);\n\t\t\t\trespond(400, htmlPage('Authentication Failed', safe));\n\t\t\t\trejectCode?.(new Error(errorDescription || error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!code) {\n\t\t\t\trespond(\n\t\t\t\t\t400,\n\t\t\t\t\thtmlPage(\n\t\t\t\t\t\t'Invalid Request',\n\t\t\t\t\t\t'No authorization code received.',\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error('No authorization code received'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\trespond(\n\t\t\t\t200,\n\t\t\t\thtmlPage(\n\t\t\t\t\t'Authentication Successful',\n\t\t\t\t\t'You can close this window and return to Command Code.',\n\t\t\t\t),\n\t\t\t);\n\t\t\tresolveCode?.(code);\n\t\t});\n\n\t\tserver.on('error', rejectServer);\n\t\t// Tight keep-alive so idle browser sockets don't pin the event loop after\n\t\t// close. 1ms (not 0 — Node reads 0 as \"never close\").\n\t\tserver.keepAliveTimeout = 1;\n\t\tserver.headersTimeout = 5000;\n\t\tserver.listen(port, LOOPBACK_HOST, () => {\n\t\t\tresolveServer({server, waitForCode: () => codePromise});\n\t\t});\n\t});\n}\n\nfunction defaultOpenBrowser(url: string): void {\n\ttry {\n\t\tif (process.platform === 'win32') {\n\t\t\t// cmd.exe's `start` treats its first quoted token as the window title,\n\t\t\t// so pass an empty \"\" title then the URL. The URL MUST stay quoted:\n\t\t\t// authorization URLs always carry several `&`-separated query params, and\n\t\t\t// an unquoted `&` is a cmd command separator that would truncate the URL\n\t\t\t// and kill the flow. windowsVerbatimArguments stops Node re-quoting (and\n\t\t\t// doubling) our escaping. (The old build shelled out with the URL\n\t\t\t// unquoted, breaking OAuth on Windows.)\n\t\t\tconst child = spawn('cmd', ['/c', 'start', '\"\"', `\"${url}\"`], {\n\t\t\t\tstdio: 'ignore',\n\t\t\t\tdetached: true,\n\t\t\t\twindowsVerbatimArguments: true,\n\t\t\t});\n\t\t\tchild.on('error', () => {});\n\t\t\tchild.unref();\n\t\t\treturn;\n\t\t}\n\t\tconst command = process.platform === 'darwin' ? 'open' : 'xdg-open';\n\t\tconst child = spawn(command, [url], {\n\t\t\tstdio: 'ignore',\n\t\t\tdetached: true,\n\t\t});\n\t\tchild.on('error', () => {});\n\t\tchild.unref();\n\t} catch {\n\t\t// Best-effort: if no opener exists, the user can paste the URL manually.\n\t}\n}\n\n// Run the OAuth2 authorization-code flow with PKCE: start a loopback callback\n// server, open the browser to the authorization URL, await the redirect (with a\n// CSRF/state check + timeout), exchange the code, and persist the token bound to\n// the server URL. The browser opener + fetch are injectable for tests.\nexport async function performOAuthFlow(params: {\n\treadonly serverUrl: string;\n\treadonly config: OAuthConfig;\n\treadonly vault: {\n\t\tset(input: {\n\t\t\treadonly serverUrl: string;\n\t\t\treadonly token: TokenResult;\n\t\t}): Promise<void>;\n\t};\n\treadonly port?: number;\n\treadonly timeoutMs?: number;\n\treadonly onStatus?: (message: string) => void;\n\treadonly openBrowser?: (url: string) => void | Promise<void>;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n}): Promise<OAuthResult> {\n\tif (!isSecureOrLoopback(params.serverUrl)) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: `MCP server url must use https:// when OAuth is configured (got \"${params.serverUrl}\"). http:// is only allowed for loopback hosts.`,\n\t\t};\n\t}\n\tconst port = params.port ?? DEFAULT_CALLBACK_PORT;\n\tconst timeoutMs = params.timeoutMs ?? 120_000;\n\tconst onStatus = params.onStatus ?? (() => {});\n\tconst openBrowser = params.openBrowser ?? defaultOpenBrowser;\n\tconst redirectUri = `http://${LOOPBACK_HOST}:${port}/callback`;\n\n\tlet server: Server | null = null;\n\tlet timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n\ttry {\n\t\tconst pkce = generatePkce();\n\t\tconst state = randomBytes(32).toString('base64url');\n\n\t\tonStatus('Starting authentication server...');\n\t\tconst callback = await startCallbackServer(port, state);\n\t\tserver = callback.server;\n\n\t\tconst authUrl = buildAuthorizationUrl({\n\t\t\tauthorizationEndpoint: params.config.authorizationUrl,\n\t\t\tclientId: params.config.clientId,\n\t\t\tredirectUri,\n\t\t\tchallenge: pkce.challenge,\n\t\t\tscope: params.config.scopes?.length\n\t\t\t\t? params.config.scopes.join(' ')\n\t\t\t\t: undefined,\n\t\t\tstate,\n\t\t});\n\n\t\tonStatus('Opening browser for authentication...');\n\t\tawait openBrowser(authUrl);\n\n\t\tonStatus('Waiting for authorization...');\n\t\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\t\ttimeoutTimer = setTimeout(\n\t\t\t\t() => reject(new Error('Authentication timed out')),\n\t\t\t\ttimeoutMs,\n\t\t\t);\n\t\t});\n\t\tconst code = await Promise.race([\n\t\t\tcallback.waitForCode(),\n\t\t\ttimeoutPromise,\n\t\t]);\n\n\t\tonStatus('Exchanging authorization code for tokens...');\n\t\tconst token = await exchangeCodeForToken({\n\t\t\ttokenEndpoint: params.config.tokenUrl,\n\t\t\tcode,\n\t\t\tverifier: pkce.verifier,\n\t\t\tclientId: params.config.clientId,\n\t\t\tclientSecret: params.config.clientSecret,\n\t\t\tredirectUri,\n\t\t\tfetchImpl: params.fetchImpl,\n\t\t\tnow: params.now,\n\t\t});\n\n\t\t// Bind the token to the server URL so it can never later be attached to a\n\t\t// request to a different origin (a malicious config swap).\n\t\tawait params.vault.set({\n\t\t\tserverUrl: params.serverUrl,\n\t\t\ttoken: {...token, issuerUrl: params.serverUrl},\n\t\t});\n\t\tonStatus('Authentication successful!');\n\t\treturn {success: true, token};\n\t} catch (error) {\n\t\treturn {success: false, error: String(error)};\n\t} finally {\n\t\tif (timeoutTimer) clearTimeout(timeoutTimer);\n\t\tif (server) {\n\t\t\t// close() alone only stops new connections — force idle/active sockets\n\t\t\t// shut so the CLI's event loop can exit.\n\t\t\tserver.closeIdleConnections?.();\n\t\t\tserver.closeAllConnections?.();\n\t\t\tserver.close();\n\t\t\tserver.unref();\n\t\t}\n\t}\n}\n","// Reusable zero-dep OAuth primitives a provider MODULE (built-in or external plugin) can use to\n// build its login flow without re-rolling the boring parts: PKCE, a loopback callback server, and\n// device-code request/poll. PKCE + the token exchange/refresh live in `../mcp/oauth.js` (the MCP\n// client already needed them) — we REUSE those here rather than duplicate, and add the two pieces\n// MCP didn't need: a general loopback server that returns its own redirect URI, and device-code.\n//\n// Node built-ins only (node:http, node:url) + the injected/global fetch — everything stays testable.\n\nimport {createServer, type Server} from 'node:http';\nimport {URL} from 'node:url';\n\nimport type {OAuthFetchImpl, TokenResult} from '../mcp/oauth.js';\n\n// Re-export the shared PKCE + token primitives so a plugin can pull the whole login toolkit from\n// one place. (Token exchange/refresh — exchangeCodeForToken / refreshAccessToken — are already\n// exported from the package root via mcp/oauth.)\nexport {generatePkce} from '../mcp/oauth.js';\nexport type {OAuthFetchImpl, Pkce, TokenResult} from '../mcp/oauth.js';\n\nconst LOOPBACK_HOST = '127.0.0.1';\n\nfunction defaultFetch(): OAuthFetchImpl {\n\treturn globalThis.fetch as unknown as OAuthFetchImpl;\n}\n\nfunction encodeForm(fields: Record<string, string>): string {\n\treturn Object.entries(fields)\n\t\t.map(\n\t\t\t([key, value]) =>\n\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t)\n\t\t.join('&');\n}\n\n// ── Loopback callback server (RFC 8252 native-app redirect) ──────────────────\nexport interface LoopbackCallback {\n\t// The http://127.0.0.1:<port><path> to use as the OAuth redirect_uri.\n\treadonly redirectUri: string;\n\t// Resolves with the authorization code (+ returned state) once the browser redirects back.\n\twaitForCode(): Promise<{\n\t\treadonly code: string;\n\t\treadonly state: string | null;\n\t}>;\n\t// Shut the server down — always call this once the flow settles (success or failure).\n\tclose(): void;\n}\n\n// Start a loopback HTTP server that captures the OAuth redirect. Pass port 0 (default) for an\n// ephemeral port so concurrent logins don't collide; read the real redirectUri off the result.\n// CSRF/state checking is the caller's job (it owns the state it sent) — this just surfaces it.\nexport function createLoopbackCallbackServer(\n\tparams: {\n\t\treadonly port?: number;\n\t\treadonly path?: string;\n\t\treadonly host?: string;\n\t\treadonly successHtml?: string;\n\t} = {},\n): Promise<LoopbackCallback> {\n\tconst host = params.host ?? LOOPBACK_HOST;\n\tconst path = params.path ?? '/callback';\n\tconst successHtml =\n\t\tparams.successHtml ??\n\t\t'<!DOCTYPE html><html><head><title>Authenticated</title></head><body style=\"font-family:system-ui;padding:40px;text-align:center;\"><h1>Authentication complete</h1><p>You can close this window and return to your terminal.</p></body></html>';\n\n\treturn new Promise((resolveServer, rejectServer) => {\n\t\tlet resolveCode:\n\t\t\t| ((value: {\n\t\t\t\t\treadonly code: string;\n\t\t\t\t\treadonly state: string | null;\n\t\t\t }) => void)\n\t\t\t| null = null;\n\t\tlet rejectCode: ((error: Error) => void) | null = null;\n\t\tconst codePromise = new Promise<{\n\t\t\treadonly code: string;\n\t\t\treadonly state: string | null;\n\t\t}>((resolve, reject) => {\n\t\t\tresolveCode = resolve;\n\t\t\trejectCode = reject;\n\t\t});\n\t\t// Swallow an early settle (e.g. a test opener firing before the caller awaits) so it can't\n\t\t// trip an unhandled rejection; the real consumer still receives the value.\n\t\tcodePromise.catch(() => {});\n\n\t\tconst server = createServer((request, response) => {\n\t\t\tconst requestUrl = new URL(request.url ?? '/', `http://${host}`);\n\t\t\tif (requestUrl.pathname !== path) {\n\t\t\t\tresponse.writeHead(404, {Connection: 'close'});\n\t\t\t\tresponse.end('Not Found');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = requestUrl.searchParams.get('code');\n\t\t\tconst error = requestUrl.searchParams.get('error');\n\t\t\tconst errorDescription =\n\t\t\t\trequestUrl.searchParams.get('error_description');\n\t\t\tconst state = requestUrl.searchParams.get('state');\n\t\t\tif (error) {\n\t\t\t\tresponse.writeHead(400, {\n\t\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\t\tConnection: 'close',\n\t\t\t\t});\n\t\t\t\tresponse.end(\n\t\t\t\t\t'<!DOCTYPE html><html><body><h1>Authentication failed</h1></body></html>',\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error(errorDescription || error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!code) {\n\t\t\t\tresponse.writeHead(400, {\n\t\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\t\tConnection: 'close',\n\t\t\t\t});\n\t\t\t\tresponse.end(\n\t\t\t\t\t'<!DOCTYPE html><html><body><h1>Missing authorization code</h1></body></html>',\n\t\t\t\t);\n\t\t\t\trejectCode?.(new Error('No authorization code received'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresponse.writeHead(200, {\n\t\t\t\t'Content-Type': 'text/html',\n\t\t\t\tConnection: 'close',\n\t\t\t});\n\t\t\tresponse.end(successHtml);\n\t\t\tresolveCode?.({code, state});\n\t\t});\n\n\t\tserver.on('error', rejectServer);\n\t\t// Tight keep-alive so an idle browser socket can't pin the event loop after close\n\t\t// (1ms, not 0 — Node reads 0 as \"never close\").\n\t\tserver.keepAliveTimeout = 1;\n\t\tserver.headersTimeout = 5000;\n\t\tserver.listen(params.port ?? 0, host, () => {\n\t\t\tconst address = server.address();\n\t\t\tconst port =\n\t\t\t\ttypeof address === 'object' && address !== null\n\t\t\t\t\t? address.port\n\t\t\t\t\t: (params.port ?? 0);\n\t\t\tresolveServer({\n\t\t\t\tredirectUri: `http://${host}:${port}${path}`,\n\t\t\t\twaitForCode: () => codePromise,\n\t\t\t\tclose: () => {\n\t\t\t\t\tserver.closeIdleConnections?.();\n\t\t\t\t\tserver.closeAllConnections?.();\n\t\t\t\t\tserver.close();\n\t\t\t\t\tserver.unref();\n\t\t\t\t},\n\t\t\t});\n\t\t});\n\t});\n}\n\n// ── Device-code flow (RFC 8628) ──────────────────────────────────────────────\nexport interface DeviceCodeGrant {\n\treadonly deviceCode: string;\n\treadonly userCode: string;\n\treadonly verificationUri: string;\n\treadonly verificationUriComplete?: string;\n\treadonly expiresIn?: number; // seconds\n\treadonly interval?: number; // seconds between polls\n}\n\n// Step 1: ask the device-authorization endpoint for a device + user code.\nexport async function requestDeviceCode(params: {\n\treadonly deviceAuthorizationEndpoint: string;\n\treadonly clientId: string;\n\treadonly scopes?: readonly string[];\n\treadonly fetchImpl?: OAuthFetchImpl;\n}): Promise<DeviceCodeGrant> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst fields: Record<string, string> = {client_id: params.clientId};\n\tif (params.scopes?.length) fields.scope = params.scopes.join(' ');\n\tconst response = await fetchImpl(params.deviceAuthorizationEndpoint, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'content-type': 'application/x-www-form-urlencoded',\n\t\t\taccept: 'application/json',\n\t\t},\n\t\tbody: encodeForm(fields),\n\t});\n\tif (response.ok === false) {\n\t\tconst body = response.text ? await response.text() : '';\n\t\tthrow new Error(\n\t\t\t`Device authorization failed: ${response.status ?? '?'} ${body}`.trim(),\n\t\t);\n\t}\n\tconst data = (await response.json()) as {\n\t\tdevice_code?: string;\n\t\tuser_code?: string;\n\t\tverification_uri?: string;\n\t\tverification_uri_complete?: string;\n\t\texpires_in?: number;\n\t\tinterval?: number;\n\t};\n\tif (!data.device_code || !data.user_code || !data.verification_uri) {\n\t\tthrow new Error(\n\t\t\t'Device authorization response missing required fields',\n\t\t);\n\t}\n\treturn {\n\t\tdeviceCode: data.device_code,\n\t\tuserCode: data.user_code,\n\t\tverificationUri: data.verification_uri,\n\t\tverificationUriComplete: data.verification_uri_complete,\n\t\texpiresIn: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\n// Step 2: poll the token endpoint until the user approves (or it times out / errors). Honors the\n// RFC's `authorization_pending` (keep waiting) and `slow_down` (back off) responses. `sleep`/`now`\n// are injectable so a test can drive the loop without real timers.\nexport async function pollDeviceToken(params: {\n\treadonly tokenEndpoint: string;\n\treadonly clientId: string;\n\treadonly deviceCode: string;\n\treadonly intervalMs?: number;\n\treadonly timeoutMs?: number;\n\treadonly clientSecret?: string;\n\treadonly fetchImpl?: OAuthFetchImpl;\n\treadonly now?: () => number;\n\treadonly sleep?: (ms: number) => Promise<void>;\n}): Promise<TokenResult> {\n\tconst fetchImpl = params.fetchImpl ?? defaultFetch();\n\tconst now = params.now ?? (() => Date.now());\n\tconst sleep =\n\t\tparams.sleep ??\n\t\t((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\tlet intervalMs = params.intervalMs ?? 5000;\n\tconst deadline = now() + (params.timeoutMs ?? 300_000);\n\n\tfor (;;) {\n\t\tif (now() >= deadline) {\n\t\t\tthrow new Error('Device authorization timed out');\n\t\t}\n\t\tawait sleep(intervalMs);\n\t\tconst fields: Record<string, string> = {\n\t\t\tgrant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n\t\t\tdevice_code: params.deviceCode,\n\t\t\tclient_id: params.clientId,\n\t\t};\n\t\tif (params.clientSecret) fields.client_secret = params.clientSecret;\n\t\tconst response = await fetchImpl(params.tokenEndpoint, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'content-type': 'application/x-www-form-urlencoded',\n\t\t\t\taccept: 'application/json',\n\t\t\t},\n\t\t\tbody: encodeForm(fields),\n\t\t});\n\t\tconst data = (await response.json()) as {\n\t\t\taccess_token?: string;\n\t\t\trefresh_token?: string;\n\t\t\texpires_in?: number;\n\t\t\ttoken_type?: string;\n\t\t\tscope?: string;\n\t\t\terror?: string;\n\t\t};\n\t\tif (data.access_token) {\n\t\t\treturn {\n\t\t\t\taccessToken: data.access_token,\n\t\t\t\trefreshToken: data.refresh_token,\n\t\t\t\texpiresAt:\n\t\t\t\t\ttypeof data.expires_in === 'number'\n\t\t\t\t\t\t? now() + data.expires_in * 1000\n\t\t\t\t\t\t: undefined,\n\t\t\t\ttokenType: data.token_type,\n\t\t\t\tscope: data.scope,\n\t\t\t};\n\t\t}\n\t\tif (data.error === 'authorization_pending') continue;\n\t\tif (data.error === 'slow_down') {\n\t\t\tintervalMs += 5000; // RFC 8628 §3.5: bump the interval by 5s and keep polling\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Device authorization failed: ${data.error ?? 'unknown error'}`,\n\t\t);\n\t}\n}\n","/** Direct-client wire adapter for Anthropic subscription OAuth. */\n\n// Exported so server/index.ts can alias it as ANTHROPIC_BETA_OAUTH: this fetch unconditionally\n// overwrites the anthropic-beta header with this string, so any advertised OAuth beta set must\n// be THIS value — a separate literal elsewhere would be silently ignored on the wire.\nexport const OAUTH_BETAS =\n\t'oauth-2025-04-20,interleaved-thinking-2025-05-14,web-search-2025-03-05,web-fetch-2025-09-10';\nconst TOOL_PREFIX = 'cc_';\nconst CLAUDE_CODE_VERSION = '2.1.76';\nconst CLAUDE_CODE_USER_AGENT = `claude-code/${CLAUDE_CODE_VERSION}`;\nconst BILLING_SALT = '59cf53e54c78';\n\nasync function sha256Hex(input: string): Promise<string> {\n\tconst data = new TextEncoder().encode(input);\n\tconst hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\treturn Array.from(new Uint8Array(hashBuffer))\n\t\t.map(b => b.toString(16).padStart(2, '0'))\n\t\t.join('');\n}\n\nfunction sampleJsCodeUnit(text: string, idx: number): string {\n\t// Encode as UTF-16 and get the nth code unit\n\tlet pos = 0;\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst code = text.charCodeAt(i);\n\t\tif (pos === idx) return String.fromCharCode(code);\n\t\tpos++;\n\t\t// Handle surrogate pairs\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tif (pos === idx) return String.fromCharCode(text.charCodeAt(i + 1));\n\t\t\tpos++;\n\t\t\ti++;\n\t\t}\n\t}\n\treturn '0';\n}\n\nfunction extractFirstUserMessage(\n\tmessages: Array<Record<string, unknown>>,\n): string {\n\tfor (const msg of messages) {\n\t\tif (msg.role !== 'user') continue;\n\t\tif (typeof msg.content === 'string') return msg.content;\n\t\tif (Array.isArray(msg.content)) {\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tconst b = block as Record<string, unknown>;\n\t\t\t\tif (b.type === 'text' && typeof b.text === 'string')\n\t\t\t\t\treturn b.text as string;\n\t\t\t}\n\t\t}\n\t}\n\treturn '';\n}\n\nasync function buildBillingBlock(\n\tmessages: Array<Record<string, unknown>>,\n): Promise<string> {\n\tconst firstMsg = extractFirstUserMessage(messages);\n\tconst sampled = [4, 7, 20]\n\t\t.map(idx => sampleJsCodeUnit(firstMsg, idx))\n\t\t.join('');\n\tconst versionHash = await sha256Hex(\n\t\t`${BILLING_SALT}${sampled}${CLAUDE_CODE_VERSION}`,\n\t);\n\treturn `x-anthropic-billing-header: cc_version=${CLAUDE_CODE_VERSION}.${versionHash.slice(0, 3)}; cc_entrypoint=cli; cch=00000;`;\n}\n\n// Brand-spoof rename for the OAuth path (OAuth tokens are provisioned for\n// Claude Code traffic, so the system prompt must not name a different\n// product). The rename must NEVER touch a match embedded in a path or\n// identifier: the blind replace corrupted real filesystem paths — a working\n// directory like ~/Sandbox/commandcode-aa1 reached the model as\n// ~/Sandbox/claude-aa1, so it wrote files into a directory that doesn't\n// exist, and every `.commandcode/` config path (taste/agents/skills) plus\n// commandcode.ai support URL was rewritten to something wrong. The\n// lookarounds skip any occurrence adjacent to path separators, dots,\n// dashes, underscores, `~`, or other word characters — only prose mentions\n// of the product name are renamed.\nconst BRAND_SPOOF_RULES: ReadonlyArray<{\n\treadonly pattern: RegExp;\n\treadonly replacement: string;\n}> = [\n\t{\n\t\tpattern: /(?<![\\w./\\\\~-])Command Code(?![\\w-])/g,\n\t\treplacement: 'Claude Code',\n\t},\n\t{\n\t\tpattern: /(?<![\\w./\\\\~-])commandcode(?![\\w-])/gi,\n\t\treplacement: 'claude',\n\t},\n];\n\nfunction spoofBrandText(text: string): string {\n\tlet result = text;\n\tfor (const rule of BRAND_SPOOF_RULES) {\n\t\tresult = result.replace(rule.pattern, rule.replacement);\n\t}\n\treturn result;\n}\n\nfunction prefixOAuthToolName(\n\ttool: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst name = tool.name as string | undefined;\n\tconst type = tool.type as string | undefined;\n\n\t// Don't prefix if no name or if it's a server-side web tool\n\tif (!name || type?.includes('web_')) {\n\t\treturn tool;\n\t}\n\n\treturn {\n\t\t...tool,\n\t\tname: `${TOOL_PREFIX}${name}`,\n\t};\n}\n\nfunction cleanOAuthMessageBlock(\n\tblock: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst cleaned = {...block};\n\n\tif (cleaned.type === 'tool_use') {\n\t\treturn prefixOAuthToolName(cleaned);\n\t}\n\n\treturn cleaned;\n}\n\nfunction cleanOAuthMessage(\n\tmessage: Record<string, unknown>,\n): Record<string, unknown> {\n\tif (!message.content || !Array.isArray(message.content)) {\n\t\treturn message;\n\t}\n\n\treturn {\n\t\t...message,\n\t\tcontent: message.content.map((block: Record<string, unknown>) =>\n\t\t\tcleanOAuthMessageBlock(block),\n\t\t),\n\t};\n}\n\nexport function createAnthropicOAuthFetch(\n\toauthToken: string,\n\tupstreamFetch: typeof globalThis.fetch = globalThis.fetch,\n): typeof globalThis.fetch {\n\treturn async (input, init) => {\n\t\tconst requestHeaders = new Headers(\n\t\t\tinit?.headers as ConstructorParameters<typeof Headers>[0],\n\t\t);\n\n\t\t// Set OAuth auth and strip API key\n\t\trequestHeaders.set('authorization', `Bearer ${oauthToken}`);\n\t\trequestHeaders.delete('x-api-key');\n\n\t\t// Replace SDK auto-added betas with OAuth betas\n\t\trequestHeaders.set('anthropic-beta', OAUTH_BETAS);\n\t\trequestHeaders.set('user-agent', CLAUDE_CODE_USER_AGENT);\n\n\t\t// Modify request body for OAuth compatibility\n\t\tlet body = init?.body;\n\t\tif (body && typeof body === 'string') {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(body);\n\t\t\t\t// Remove fields the OAuth API doesn't accept\n\t\t\t\tdelete parsed.tool_choice;\n\t\t\t\tdelete parsed.top_k;\n\t\t\t\tdelete parsed.top_p;\n\t\t\t\tdelete parsed.stop_sequences;\n\t\t\t\tfor (const key of Object.keys(parsed)) {\n\t\t\t\t\tif (parsed[key] === undefined || parsed[key] === null)\n\t\t\t\t\t\tdelete parsed[key];\n\t\t\t\t}\n\n\t\t\t\t// Build billing block and prepend to system\n\t\t\t\tconst billingText = await buildBillingBlock(\n\t\t\t\t\tparsed.messages || [],\n\t\t\t\t);\n\t\t\t\tconst billingBlock = {type: 'text', text: billingText};\n\t\t\t\tif (parsed.system && Array.isArray(parsed.system)) {\n\t\t\t\t\tparsed.system = [\n\t\t\t\t\t\tbillingBlock,\n\t\t\t\t\t\t...parsed.system.map(\n\t\t\t\t\t\t\t(item: Record<string, unknown>) => {\n\t\t\t\t\t\t\t\tconst cleaned = {...item};\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tcleaned.type === 'text' &&\n\t\t\t\t\t\t\t\t\ttypeof cleaned.text === 'string'\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tcleaned.text = spoofBrandText(\n\t\t\t\t\t\t\t\t\t\tcleaned.text as string,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn cleaned;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t];\n\t\t\t\t} else if (typeof parsed.system === 'string') {\n\t\t\t\t\tparsed.system = [\n\t\t\t\t\t\tbillingBlock,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\t\ttext: spoofBrandText(parsed.system),\n\t\t\t\t\t\t},\n\t\t\t\t\t];\n\t\t\t\t} else {\n\t\t\t\t\tparsed.system = [billingBlock];\n\t\t\t\t}\n\n\t\t\t\t// Prefix tool names (skip server-side web tools — they must keep original names)\n\t\t\t\tif (parsed.tools && Array.isArray(parsed.tools)) {\n\t\t\t\t\tparsed.tools = parsed.tools.map(prefixOAuthToolName);\n\t\t\t\t}\n\t\t\t\t// Prefix tool_use blocks in messages while preserving cache_control.\n\t\t\t\tif (parsed.messages && Array.isArray(parsed.messages)) {\n\t\t\t\t\tparsed.messages = parsed.messages.map(cleanOAuthMessage);\n\t\t\t\t}\n\t\t\t\tbody = JSON.stringify(parsed);\n\t\t\t} catch {\n\t\t\t\t// ignore parse errors\n\t\t\t}\n\t\t}\n\n\t\t// Add ?beta=true query parameter\n\t\tlet requestInput = input;\n\t\ttry {\n\t\t\tconst url = new URL(\n\t\t\t\ttypeof input === 'string'\n\t\t\t\t\t? input\n\t\t\t\t\t: input instanceof URL\n\t\t\t\t\t\t? input.toString()\n\t\t\t\t\t\t: (input as Request).url,\n\t\t\t);\n\t\t\tif (\n\t\t\t\turl.pathname === '/v1/messages' &&\n\t\t\t\t!url.searchParams.has('beta')\n\t\t\t) {\n\t\t\t\turl.searchParams.set('beta', 'true');\n\t\t\t\trequestInput =\n\t\t\t\t\tinput instanceof Request\n\t\t\t\t\t\t? new Request(url.toString(), input)\n\t\t\t\t\t\t: url;\n\t\t\t}\n\t\t} catch {}\n\n\t\tconst response = await upstreamFetch(requestInput, {\n\t\t\t...init,\n\t\t\tbody,\n\t\t\theaders: requestHeaders,\n\t\t});\n\n\t\t// Strip cc_ prefix from tool names in streaming response. Network chunks split at\n\t\t// arbitrary byte offsets, so the `\"name\": \"cc_…\"` fragment can span two reads — the\n\t\t// rewrite must only ever run on complete SSE lines. Decoded text accumulates in\n\t\t// `carry` and everything up to the last newline is rewritten and forwarded; the\n\t\t// remainder waits for the next chunk. SSE data lines are complete JSON documents,\n\t\t// so a line boundary guarantees the name field is whole.\n\t\tif (response.body) {\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tconst encoder = new TextEncoder();\n\t\t\tconst stripToolPrefix = (text: string): string =>\n\t\t\t\ttext.replace(/\"name\"\\s*:\\s*\"cc_([^\"]+)\"/g, '\"name\": \"$1\"');\n\t\t\tlet carry = '';\n\t\t\tconst stream = new ReadableStream({\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\tconst {done, value} = await reader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcarry += decoder.decode();\n\t\t\t\t\t\tif (carry) {\n\t\t\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\t\t\tencoder.encode(stripToolPrefix(carry)),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tcarry = '';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcarry += decoder.decode(value, {stream: true});\n\t\t\t\t\tconst boundary = carry.lastIndexOf('\\n');\n\t\t\t\t\t// No complete line yet — keep buffering; pull() is invoked again as\n\t\t\t\t\t// long as the consumer wants data.\n\t\t\t\t\tif (boundary === -1) return;\n\t\t\t\t\tconst complete = carry.slice(0, boundary + 1);\n\t\t\t\t\tcarry = carry.slice(boundary + 1);\n\t\t\t\t\tcontroller.enqueue(\n\t\t\t\t\t\tencoder.encode(stripToolPrefix(complete)),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn new Response(stream, {\n\t\t\t\tstatus: response.status,\n\t\t\t\tstatusText: response.statusText,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t}\n\t\treturn response;\n\t};\n}\n"],"mappings":";;;;;;AAWA,SAAQ,eAAAA,oBAAkB;AAC1B,SAAQ,uBAAsB;;;AEH9B,SAAQ,YAAY,mBAAkB;AAkH/B,SAAS,aACf,SAAgE,CAAC,GAC1D;AACP,QAAM,YAAY,OAAO,mBAAmB,aAAa,EAAE,EAAE;IAC5D;EACD;AACA,QAAM,YAAY,WAAW,QAAQ,EAAE,OAAO,QAAQ,EAAE,OAAO,WAAW;AAC1E,SAAO,EAAC,UAAU,UAAS;AAC5B;;;AE9HO,IAAM,cACZ;AACD,IAAM,cAAc;AACpB,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB,eAAe,mBAAmB;AACjE,IAAM,eAAe;AAErB,eAAe,UAAU,OAAgC;AACxD,QAAM,OAAO,IAAI,YAAY,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AC3B,eAAO;AAAA,UACN,SAAS;AAAA,YACR,eAAe,UAAU,OAAO,KAAK;AAAA,UACtC;AAAA,UACA,OAAO;AAAA,YACN,OAAO;AAAA,YACP;AAAA,UACD;AAAA,QACD;AAAA,MACD;AAAA,IACD;AAAA,EACD;AACD;AAIA,IAAM,oBAAoC,wBAAwB;AAClE,IAAO,gBAAQ;","names":["randomBytes","randomBytes"]}
|
package/dist/models.d.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
type AnthropicReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
2
|
+
interface AnthropicModelOption {
|
|
3
|
+
readonly id: string;
|
|
4
|
+
readonly provider: 'anthropic';
|
|
5
|
+
readonly spec: 'chatComplete';
|
|
6
|
+
readonly label: string;
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly description: string;
|
|
9
|
+
readonly reasoning?: boolean;
|
|
10
|
+
readonly reasoningEfforts?: readonly AnthropicReasoningEffort[];
|
|
11
|
+
readonly contextWindow?: number;
|
|
12
|
+
readonly inputModalities?: readonly ('text' | 'image')[];
|
|
13
|
+
}
|
|
14
|
+
declare const ANTHROPIC_MODEL_OPTIONS: {
|
|
15
|
+
readonly SONNET_5: {
|
|
16
|
+
readonly id: "claude-sonnet-5";
|
|
17
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
18
|
+
readonly provider: "anthropic";
|
|
19
|
+
readonly spec: "chatComplete";
|
|
20
|
+
readonly label: "Claude Sonnet 5";
|
|
21
|
+
readonly name: "Claude Sonnet 5";
|
|
22
|
+
readonly description: "best combo of speed & intelligence (recommended)";
|
|
23
|
+
readonly reasoning: true;
|
|
24
|
+
readonly reasoningEfforts: readonly AnthropicReasoningEffort[];
|
|
25
|
+
readonly contextWindow: 1000000;
|
|
26
|
+
};
|
|
27
|
+
readonly SONNET_4_6: {
|
|
28
|
+
readonly id: "claude-sonnet-4-6";
|
|
29
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
30
|
+
readonly provider: "anthropic";
|
|
31
|
+
readonly spec: "chatComplete";
|
|
32
|
+
readonly label: "Claude Sonnet 4.6";
|
|
33
|
+
readonly name: "Claude Sonnet 4.6";
|
|
34
|
+
readonly description: "prev Sonnet, still fast & capable";
|
|
35
|
+
readonly reasoningEfforts: readonly AnthropicReasoningEffort[];
|
|
36
|
+
readonly contextWindow: 1000000;
|
|
37
|
+
};
|
|
38
|
+
readonly FABLE_5: {
|
|
39
|
+
readonly id: "claude-fable-5";
|
|
40
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
41
|
+
readonly provider: "anthropic";
|
|
42
|
+
readonly spec: "chatComplete";
|
|
43
|
+
readonly label: "Claude Fable 5";
|
|
44
|
+
readonly name: "Claude Fable 5";
|
|
45
|
+
readonly description: "most capable for demanding reasoning & long-horizon agents";
|
|
46
|
+
readonly reasoning: true;
|
|
47
|
+
readonly reasoningEfforts: readonly AnthropicReasoningEffort[];
|
|
48
|
+
readonly contextWindow: 1000000;
|
|
49
|
+
};
|
|
50
|
+
readonly OPUS_5: {
|
|
51
|
+
readonly id: "claude-opus-5";
|
|
52
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
53
|
+
readonly provider: "anthropic";
|
|
54
|
+
readonly spec: "chatComplete";
|
|
55
|
+
readonly label: "Claude Opus 5";
|
|
56
|
+
readonly name: "Claude Opus 5";
|
|
57
|
+
readonly description: "most intelligent Opus for agents and coding";
|
|
58
|
+
readonly reasoning: true;
|
|
59
|
+
readonly reasoningEfforts: readonly AnthropicReasoningEffort[];
|
|
60
|
+
readonly contextWindow: 1000000;
|
|
61
|
+
};
|
|
62
|
+
readonly OPUS_4_8: {
|
|
63
|
+
readonly id: "claude-opus-4-8";
|
|
64
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
65
|
+
readonly provider: "anthropic";
|
|
66
|
+
readonly spec: "chatComplete";
|
|
67
|
+
readonly label: "Claude Opus 4.8";
|
|
68
|
+
readonly name: "Claude Opus 4.8";
|
|
69
|
+
readonly description: "prev flagship, still strong for agents and coding";
|
|
70
|
+
readonly reasoning: true;
|
|
71
|
+
readonly reasoningEfforts: readonly AnthropicReasoningEffort[];
|
|
72
|
+
readonly contextWindow: 1000000;
|
|
73
|
+
};
|
|
74
|
+
readonly OPUS_4_7: {
|
|
75
|
+
readonly id: "claude-opus-4-7";
|
|
76
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
77
|
+
readonly provider: "anthropic";
|
|
78
|
+
readonly spec: "chatComplete";
|
|
79
|
+
readonly label: "Claude Opus 4.7";
|
|
80
|
+
readonly name: "Claude Opus 4.7";
|
|
81
|
+
readonly description: "older Opus, still strong for agents and coding";
|
|
82
|
+
readonly reasoning: true;
|
|
83
|
+
readonly reasoningEfforts: readonly AnthropicReasoningEffort[];
|
|
84
|
+
readonly contextWindow: 1000000;
|
|
85
|
+
};
|
|
86
|
+
readonly HAIKU_4_5: {
|
|
87
|
+
readonly id: "claude-haiku-4-5-20251001";
|
|
88
|
+
readonly inputModalities: readonly ["text", "image"];
|
|
89
|
+
readonly provider: "anthropic";
|
|
90
|
+
readonly spec: "chatComplete";
|
|
91
|
+
readonly label: "Claude Haiku 4.5";
|
|
92
|
+
readonly name: "Claude Haiku 4.5";
|
|
93
|
+
readonly description: "fastest & most compact, great for quick tasks";
|
|
94
|
+
readonly contextWindow: 200000;
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
/** Canonical Anthropic model ids, in catalog order. */
|
|
98
|
+
declare const ANTHROPIC_MODEL_IDS: readonly string[];
|
|
99
|
+
declare const ANTHROPIC_DEPRECATED_MODEL_ALIASES: Readonly<Record<string, string>>;
|
|
100
|
+
/**
|
|
101
|
+
* Does an id look like an Anthropic model (including BYO/dated ids the catalog doesn't list)?
|
|
102
|
+
* This is the predicate that used to live inline in the harness model client
|
|
103
|
+
* (`model.includes('claude')`) to decide interleaved-thinking finalization — provider heuristics
|
|
104
|
+
* belong to the provider.
|
|
105
|
+
*/
|
|
106
|
+
declare function matchesAnthropicModel(modelId: string): boolean;
|
|
107
|
+
/**
|
|
108
|
+
* Harness ModelSpec-shaped catalog (structural — the harness validates on registration). Declares
|
|
109
|
+
* interleaved thinking for every Anthropic model so the core model client needs no 'claude'
|
|
110
|
+
* string of its own.
|
|
111
|
+
*/
|
|
112
|
+
declare const ANTHROPIC_MODEL_SPECS: {
|
|
113
|
+
id: "claude-sonnet-5" | "claude-sonnet-4-6" | "claude-fable-5" | "claude-opus-5" | "claude-opus-4-8" | "claude-opus-4-7" | "claude-haiku-4-5-20251001";
|
|
114
|
+
provider: "anthropic";
|
|
115
|
+
contextWindow: 1000000 | 200000;
|
|
116
|
+
reasoningEfforts: readonly AnthropicReasoningEffort[] | undefined;
|
|
117
|
+
inputModalities: readonly ["text", "image"];
|
|
118
|
+
interleavedThinking: boolean;
|
|
119
|
+
}[];
|
|
120
|
+
|
|
121
|
+
export { ANTHROPIC_DEPRECATED_MODEL_ALIASES, ANTHROPIC_MODEL_IDS, ANTHROPIC_MODEL_OPTIONS, ANTHROPIC_MODEL_SPECS, type AnthropicModelOption, type AnthropicReasoningEffort, matchesAnthropicModel };
|
package/dist/models.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ANTHROPIC_DEPRECATED_MODEL_ALIASES,
|
|
3
|
+
ANTHROPIC_MODEL_IDS,
|
|
4
|
+
ANTHROPIC_MODEL_OPTIONS,
|
|
5
|
+
ANTHROPIC_MODEL_SPECS,
|
|
6
|
+
matchesAnthropicModel
|
|
7
|
+
} from "./chunk-V3B4JGF6.js";
|
|
8
|
+
export {
|
|
9
|
+
ANTHROPIC_DEPRECATED_MODEL_ALIASES,
|
|
10
|
+
ANTHROPIC_MODEL_IDS,
|
|
11
|
+
ANTHROPIC_MODEL_OPTIONS,
|
|
12
|
+
ANTHROPIC_MODEL_SPECS,
|
|
13
|
+
matchesAnthropicModel
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=models.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
declare function createAnthropicOAuthFetch(oauthToken: string): typeof globalThis.fetch;
|
|
2
|
+
|
|
3
|
+
declare const ANTHROPIC_BETA_OAUTH = "oauth-2025-04-20,interleaved-thinking-2025-05-14,web-search-2025-03-05,web-fetch-2025-09-10";
|
|
4
|
+
declare const ANTHROPIC_BETA_API_KEY = "web-search-2025-03-05,web-fetch-2025-09-10";
|
|
5
|
+
interface AnthropicLanguageModelParams {
|
|
6
|
+
readonly modelId: string;
|
|
7
|
+
/** ChatGPT-style OAuth token (Claude Pro/Max). Wins over apiKey when set. */
|
|
8
|
+
readonly oAuthToken?: string | null;
|
|
9
|
+
/** ANTHROPIC_API_KEY fallback for the key-auth path. */
|
|
10
|
+
readonly apiKey?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Build the AI-SDK language model for an Anthropic request — OAuth (custom fetch: Bearer auth,
|
|
14
|
+
* ?beta=true, Claude Code spoof, cc_ tool prefixing, cache_control preservation) or plain API
|
|
15
|
+
* key. Returned as unknown; the api worker casts to its LanguageModelV3 like it always did.
|
|
16
|
+
*/
|
|
17
|
+
declare function getAnthropicLanguageModel(params: AnthropicLanguageModelParams): unknown;
|
|
18
|
+
|
|
19
|
+
export { ANTHROPIC_BETA_API_KEY, ANTHROPIC_BETA_OAUTH, type AnthropicLanguageModelParams, createAnthropicOAuthFetch, getAnthropicLanguageModel };
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// src/server/index.ts
|
|
2
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
3
|
+
|
|
4
|
+
// src/server/anthropic-oauth-fetch.ts
|
|
5
|
+
var OAUTH_BETAS = "oauth-2025-04-20,interleaved-thinking-2025-05-14,web-search-2025-03-05,web-fetch-2025-09-10";
|
|
6
|
+
var TOOL_PREFIX = "cc_";
|
|
7
|
+
var CLAUDE_CODE_VERSION = "2.1.76";
|
|
8
|
+
var CLAUDE_CODE_USER_AGENT = `claude-code/${CLAUDE_CODE_VERSION}`;
|
|
9
|
+
var BILLING_SALT = "59cf53e54c78";
|
|
10
|
+
async function sha256Hex(input) {
|
|
11
|
+
const data = new TextEncoder().encode(input);
|
|
12
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
13
|
+
return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
14
|
+
}
|
|
15
|
+
function sampleJsCodeUnit(text, idx) {
|
|
16
|
+
let pos = 0;
|
|
17
|
+
for (let i = 0; i < text.length; i++) {
|
|
18
|
+
const code = text.charCodeAt(i);
|
|
19
|
+
if (pos === idx) return String.fromCharCode(code);
|
|
20
|
+
pos++;
|
|
21
|
+
if (code >= 55296 && code <= 56319) {
|
|
22
|
+
if (pos === idx) return String.fromCharCode(text.charCodeAt(i + 1));
|
|
23
|
+
pos++;
|
|
24
|
+
i++;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return "0";
|
|
28
|
+
}
|
|
29
|
+
function extractFirstUserMessage(messages) {
|
|
30
|
+
for (const msg of messages) {
|
|
31
|
+
if (msg.role !== "user") continue;
|
|
32
|
+
if (typeof msg.content === "string") return msg.content;
|
|
33
|
+
if (Array.isArray(msg.content)) {
|
|
34
|
+
for (const block of msg.content) {
|
|
35
|
+
const b = block;
|
|
36
|
+
if (b.type === "text" && typeof b.text === "string")
|
|
37
|
+
return b.text;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return "";
|
|
42
|
+
}
|
|
43
|
+
async function buildBillingBlock(messages) {
|
|
44
|
+
const firstMsg = extractFirstUserMessage(messages);
|
|
45
|
+
const sampled = [4, 7, 20].map((idx) => sampleJsCodeUnit(firstMsg, idx)).join("");
|
|
46
|
+
const versionHash = await sha256Hex(
|
|
47
|
+
`${BILLING_SALT}${sampled}${CLAUDE_CODE_VERSION}`
|
|
48
|
+
);
|
|
49
|
+
return `x-anthropic-billing-header: cc_version=${CLAUDE_CODE_VERSION}.${versionHash.slice(0, 3)}; cc_entrypoint=cli; cch=00000;`;
|
|
50
|
+
}
|
|
51
|
+
var BRAND_SPOOF_RULES = [
|
|
52
|
+
{
|
|
53
|
+
pattern: /(?<![\w./\\~-])Command Code(?![\w-])/g,
|
|
54
|
+
replacement: "Claude Code"
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
pattern: /(?<![\w./\\~-])commandcode(?![\w-])/gi,
|
|
58
|
+
replacement: "claude"
|
|
59
|
+
}
|
|
60
|
+
];
|
|
61
|
+
function spoofBrandText(text) {
|
|
62
|
+
let result = text;
|
|
63
|
+
for (const rule of BRAND_SPOOF_RULES) {
|
|
64
|
+
result = result.replace(rule.pattern, rule.replacement);
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
function prefixOAuthToolName(tool) {
|
|
69
|
+
const name = tool.name;
|
|
70
|
+
const type = tool.type;
|
|
71
|
+
if (!name || type?.includes("web_")) {
|
|
72
|
+
return tool;
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
...tool,
|
|
76
|
+
name: `${TOOL_PREFIX}${name}`
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function cleanOAuthMessageBlock(block) {
|
|
80
|
+
const cleaned = { ...block };
|
|
81
|
+
if (cleaned.type === "tool_use") {
|
|
82
|
+
return prefixOAuthToolName(cleaned);
|
|
83
|
+
}
|
|
84
|
+
return cleaned;
|
|
85
|
+
}
|
|
86
|
+
function cleanOAuthMessage(message) {
|
|
87
|
+
if (!message.content || !Array.isArray(message.content)) {
|
|
88
|
+
return message;
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
...message,
|
|
92
|
+
content: message.content.map(
|
|
93
|
+
(block) => cleanOAuthMessageBlock(block)
|
|
94
|
+
)
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function createAnthropicOAuthFetch(oauthToken) {
|
|
98
|
+
return async (input, init) => {
|
|
99
|
+
const requestHeaders = new Headers(
|
|
100
|
+
init?.headers
|
|
101
|
+
);
|
|
102
|
+
requestHeaders.set("authorization", `Bearer ${oauthToken}`);
|
|
103
|
+
requestHeaders.delete("x-api-key");
|
|
104
|
+
requestHeaders.set("anthropic-beta", OAUTH_BETAS);
|
|
105
|
+
requestHeaders.set("user-agent", CLAUDE_CODE_USER_AGENT);
|
|
106
|
+
let body = init?.body;
|
|
107
|
+
if (body && typeof body === "string") {
|
|
108
|
+
try {
|
|
109
|
+
const parsed = JSON.parse(body);
|
|
110
|
+
delete parsed.tool_choice;
|
|
111
|
+
delete parsed.top_k;
|
|
112
|
+
delete parsed.top_p;
|
|
113
|
+
delete parsed.stop_sequences;
|
|
114
|
+
for (const key of Object.keys(parsed)) {
|
|
115
|
+
if (parsed[key] === void 0 || parsed[key] === null)
|
|
116
|
+
delete parsed[key];
|
|
117
|
+
}
|
|
118
|
+
const billingText = await buildBillingBlock(
|
|
119
|
+
parsed.messages || []
|
|
120
|
+
);
|
|
121
|
+
const billingBlock = { type: "text", text: billingText };
|
|
122
|
+
if (parsed.system && Array.isArray(parsed.system)) {
|
|
123
|
+
parsed.system = [
|
|
124
|
+
billingBlock,
|
|
125
|
+
...parsed.system.map(
|
|
126
|
+
(item) => {
|
|
127
|
+
const cleaned = { ...item };
|
|
128
|
+
if (cleaned.type === "text" && typeof cleaned.text === "string") {
|
|
129
|
+
cleaned.text = spoofBrandText(
|
|
130
|
+
cleaned.text
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
return cleaned;
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
];
|
|
137
|
+
} else if (typeof parsed.system === "string") {
|
|
138
|
+
parsed.system = [
|
|
139
|
+
billingBlock,
|
|
140
|
+
{
|
|
141
|
+
type: "text",
|
|
142
|
+
text: spoofBrandText(parsed.system)
|
|
143
|
+
}
|
|
144
|
+
];
|
|
145
|
+
} else {
|
|
146
|
+
parsed.system = [billingBlock];
|
|
147
|
+
}
|
|
148
|
+
if (parsed.tools && Array.isArray(parsed.tools)) {
|
|
149
|
+
parsed.tools = parsed.tools.map(prefixOAuthToolName);
|
|
150
|
+
}
|
|
151
|
+
if (parsed.messages && Array.isArray(parsed.messages)) {
|
|
152
|
+
parsed.messages = parsed.messages.map(cleanOAuthMessage);
|
|
153
|
+
}
|
|
154
|
+
body = JSON.stringify(parsed);
|
|
155
|
+
} catch {
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
let requestInput = input;
|
|
159
|
+
try {
|
|
160
|
+
const url = new URL(
|
|
161
|
+
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
|
|
162
|
+
);
|
|
163
|
+
if (url.pathname === "/v1/messages" && !url.searchParams.has("beta")) {
|
|
164
|
+
url.searchParams.set("beta", "true");
|
|
165
|
+
requestInput = input instanceof Request ? new Request(url.toString(), input) : url;
|
|
166
|
+
}
|
|
167
|
+
} catch {
|
|
168
|
+
}
|
|
169
|
+
const response = await globalThis.fetch(requestInput, {
|
|
170
|
+
...init,
|
|
171
|
+
body,
|
|
172
|
+
headers: requestHeaders
|
|
173
|
+
});
|
|
174
|
+
if (response.body) {
|
|
175
|
+
const reader = response.body.getReader();
|
|
176
|
+
const decoder = new TextDecoder();
|
|
177
|
+
const encoder = new TextEncoder();
|
|
178
|
+
const stripToolPrefix = (text) => text.replace(/"name"\s*:\s*"cc_([^"]+)"/g, '"name": "$1"');
|
|
179
|
+
let carry = "";
|
|
180
|
+
const stream = new ReadableStream({
|
|
181
|
+
async pull(controller) {
|
|
182
|
+
const { done, value } = await reader.read();
|
|
183
|
+
if (done) {
|
|
184
|
+
carry += decoder.decode();
|
|
185
|
+
if (carry) {
|
|
186
|
+
controller.enqueue(
|
|
187
|
+
encoder.encode(stripToolPrefix(carry))
|
|
188
|
+
);
|
|
189
|
+
carry = "";
|
|
190
|
+
}
|
|
191
|
+
controller.close();
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
carry += decoder.decode(value, { stream: true });
|
|
195
|
+
const boundary = carry.lastIndexOf("\n");
|
|
196
|
+
if (boundary === -1) return;
|
|
197
|
+
const complete = carry.slice(0, boundary + 1);
|
|
198
|
+
carry = carry.slice(boundary + 1);
|
|
199
|
+
controller.enqueue(
|
|
200
|
+
encoder.encode(stripToolPrefix(complete))
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
return new Response(stream, {
|
|
205
|
+
status: response.status,
|
|
206
|
+
statusText: response.statusText,
|
|
207
|
+
headers: response.headers
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return response;
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// src/server/index.ts
|
|
215
|
+
var ANTHROPIC_BETA_OAUTH = OAUTH_BETAS;
|
|
216
|
+
var ANTHROPIC_BETA_API_KEY = "web-search-2025-03-05,web-fetch-2025-09-10";
|
|
217
|
+
function getAnthropicLanguageModel(params) {
|
|
218
|
+
if (params.oAuthToken) {
|
|
219
|
+
const anthropic2 = createAnthropic({
|
|
220
|
+
apiKey: "placeholder",
|
|
221
|
+
headers: {
|
|
222
|
+
"anthropic-beta": ANTHROPIC_BETA_OAUTH
|
|
223
|
+
},
|
|
224
|
+
fetch: createAnthropicOAuthFetch(params.oAuthToken)
|
|
225
|
+
});
|
|
226
|
+
return anthropic2(params.modelId);
|
|
227
|
+
}
|
|
228
|
+
const anthropic = createAnthropic({
|
|
229
|
+
apiKey: params.apiKey,
|
|
230
|
+
headers: {
|
|
231
|
+
"anthropic-beta": ANTHROPIC_BETA_API_KEY
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
return anthropic(params.modelId);
|
|
235
|
+
}
|
|
236
|
+
export {
|
|
237
|
+
ANTHROPIC_BETA_API_KEY,
|
|
238
|
+
ANTHROPIC_BETA_OAUTH,
|
|
239
|
+
createAnthropicOAuthFetch,
|
|
240
|
+
getAnthropicLanguageModel
|
|
241
|
+
};
|
|
242
|
+
//# sourceMappingURL=index.js.map
|