@ashx-j/lunr-ai 0.2.27 → 0.2.28
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/dist/api/anthropic-claude-code-bridge.d.ts.map +1 -1
- package/dist/api/anthropic-claude-code-bridge.js +21 -3
- package/dist/api/anthropic-claude-code-bridge.js.map +1 -1
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +3 -0
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.d.ts.map +1 -1
- package/dist/api/azure-openai-responses.js +1 -0
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +8 -1
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +7 -2
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-vertex.d.ts.map +1 -1
- package/dist/api/google-vertex.js +7 -2
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/lazy.d.ts.map +1 -1
- package/dist/api/lazy.js +1 -0
- package/dist/api/lazy.js.map +1 -1
- package/dist/api/mistral-conversations.d.ts.map +1 -1
- package/dist/api/mistral-conversations.js +2 -0
- package/dist/api/mistral-conversations.js.map +1 -1
- package/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/dist/api/openai-codex-responses.js +13 -3
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +9 -1
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +7 -4
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +1 -0
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/openrouter-images.d.ts.map +1 -1
- package/dist/api/openrouter-images.js +8 -2
- package/dist/api/openrouter-images.js.map +1 -1
- package/dist/api/pi-messages.d.ts.map +1 -1
- package/dist/api/pi-messages.js +19 -3
- package/dist/api/pi-messages.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +1 -1
- package/dist/models.d.ts.map +1 -1
- package/dist/models.generated.d.ts +42 -0
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.js +5 -2
- package/dist/models.js.map +1 -1
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +5 -1
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/google-vertex.models.d.ts +21 -0
- package/dist/providers/google-vertex.models.d.ts.map +1 -1
- package/dist/providers/google-vertex.models.js +3 -0
- package/dist/providers/google-vertex.models.js.map +1 -1
- package/dist/providers/google.models.d.ts +21 -0
- package/dist/providers/google.models.d.ts.map +1 -1
- package/dist/providers/google.models.js +3 -0
- package/dist/providers/google.models.js.map +1 -1
- package/dist/types.d.ts +10 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/estimate.d.ts +3 -0
- package/dist/utils/estimate.d.ts.map +1 -1
- package/dist/utils/estimate.js +35 -30
- package/dist/utils/estimate.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-claude-code-bridge.d.ts","sourceRoot":"","sources":["../../src/api/anthropic-claude-code-bridge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACX,GAAG,EAEH,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,aAAa,EAGb,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAwDvE,wBAAgB,qBAAqB,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,MAAM,UAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAoB/F;AA2JD,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyB3D;AAgGD,wBAAgB,gBAAgB,CAC/B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,aAAa,GAAG,mBAAwB,GAC/C,2BAA2B,CA8R7B","sourcesContent":["import { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport type { ExternalClaudeCodeCredential } from \"../auth/types.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tToolCall,\n\tUsage,\n} from \"../types.ts\";\nimport { getClaudeCodeWorkerPath } from \"../utils/claude-code-assets.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nconst SAFE_ERRORS = {\n\tcontext_overflow: \"Claude Code prompt is too long for the context window.\",\n\ttimeout: \"Claude Code request timed out.\",\n\trate_limit: \"Claude Code rate limit reached. Please retry your request.\",\n\toverloaded: \"Claude Code service overloaded. Please retry your request.\",\n\ttransient: \"Claude Code service unavailable. Please retry your request.\",\n\tincomplete: \"Claude Code stream ended before message_stop. Please retry your request.\",\n} as const;\n\nclass ClaudeCodeRequestError extends Error {\n\tconstructor(category: unknown) {\n\t\tsuper(\n\t\t\ttypeof category === \"string\" && Object.hasOwn(SAFE_ERRORS, category)\n\t\t\t\t? SAFE_ERRORS[category as keyof typeof SAFE_ERRORS]\n\t\t\t\t: \"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\",\n\t\t);\n\t}\n}\n\nconst MAX_RECORD = 64 * 1024 * 1024;\nconst CONFLICTS = [\n\t\"ANTHROPIC_API_KEY\",\n\t\"ANTHROPIC_AUTH_TOKEN\",\n\t\"ANTHROPIC_OAUTH_TOKEN\",\n\t\"ANTHROPIC_BASE_URL\",\n\t\"ANTHROPIC_FOUNDRY_API_KEY\",\n\t\"CLAUDE_CODE_USE_BEDROCK\",\n\t\"CLAUDE_CODE_USE_VERTEX\",\n\t\"CLAUDE_CODE_USE_FOUNDRY\",\n\t\"CLAUDE_CODE_EXTRA_BODY\",\n] as const;\nconst ENV_ALLOWLIST = [\n\t\"PATH\",\n\t\"HOME\",\n\t\"USERPROFILE\",\n\t\"APPDATA\",\n\t\"LOCALAPPDATA\",\n\t\"PROGRAMDATA\",\n\t\"SYSTEMROOT\",\n\t\"SYSTEMDRIVE\",\n\t\"COMSPEC\",\n\t\"PATHEXT\",\n\t\"TEMP\",\n\t\"TMP\",\n\t\"LANG\",\n\t\"LC_ALL\",\n\t\"HTTP_PROXY\",\n\t\"HTTPS_PROXY\",\n\t\"NO_PROXY\",\n\t\"http_proxy\",\n\t\"https_proxy\",\n\t\"no_proxy\",\n] as const;\n\nexport function claudeCodeEnvironment(configDir?: string, strict = true): Record<string, string> {\n\tconst conflicting = CONFLICTS.filter((name) => {\n\t\tconst value = process.env[name];\n\t\treturn (\n\t\t\tvalue &&\n\t\t\t((name !== \"CLAUDE_CODE_USE_BEDROCK\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_VERTEX\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_FOUNDRY\") ||\n\t\t\t\t![\"0\", \"false\", \"no\", \"off\"].includes(value.toLowerCase()))\n\t\t);\n\t});\n\tif (strict && conflicting.length)\n\t\tthrow new Error(`Claude Code subscription refuses conflicting environment variables: ${conflicting.join(\", \")}`);\n\tif (process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\")\n\t\tthrow new Error(\"Claude Code subscription requires TLS certificate verification\");\n\tconst env = Object.fromEntries(\n\t\tENV_ALLOWLIST.flatMap((name) => (process.env[name] ? [[name, process.env[name]]] : [])),\n\t);\n\tif (configDir) env.CLAUDE_SUBSCRIPTION_DIRECTSDK_CONFIG_DIR = configDir;\n\treturn env;\n}\n\nfunction contentHash(content: AssistantMessage[\"content\"]): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(content)).digest(\"hex\");\n}\n\nfunction history(\n\tcontext: Context,\n\tmodel: Model<Api>,\n\tconnection: ExternalClaudeCodeCredential,\n): { messages: unknown[]; tools: unknown[] } {\n\tconst messages: Record<string, unknown>[] = context.systemPrompt\n\t\t? [{ role: \"system\", content: context.systemPrompt }]\n\t\t: [];\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"user\") {\n\t\t\tmessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent:\n\t\t\t\t\ttypeof message.content === \"string\"\n\t\t\t\t\t\t? message.content\n\t\t\t\t\t\t: message.content.map((block) =>\n\t\t\t\t\t\t\t\tblock.type === \"text\"\n\t\t\t\t\t\t\t\t\t? { type: \"text\", text: block.text }\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\t\t\t\timage_url: { url: `data:${block.mimeType};base64,${block.data}` },\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t});\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst text = message.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst calls = message.content\n\t\t\t\t.filter((block): block is ToolCall => block.type === \"toolCall\")\n\t\t\t\t.map((block) => ({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments) },\n\t\t\t\t}));\n\t\t\tconst projection = {\n\t\t\t\tcontent: text.trim(),\n\t\t\t\ttool_calls: calls.map((call) => ({\n\t\t\t\t\tid: call.id,\n\t\t\t\t\tname: call.function.name,\n\t\t\t\t\tinput: JSON.parse(call.function.arguments),\n\t\t\t\t})),\n\t\t\t};\n\t\t\tconst carrier =\n\t\t\t\tmessage.provider === \"anthropic\" &&\n\t\t\t\tmessage.model === model.id &&\n\t\t\t\tmessage.claudeCodeCarrier?.version === 1 &&\n\t\t\t\tconnection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.accountFingerprint === connection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.contentHash === contentHash(message.content) &&\n\t\t\t\tJSON.stringify(message.claudeCodeCarrier.projection) === JSON.stringify(projection)\n\t\t\t\t\t? [{ type: \"claude-subscription-directsdk-experimental.native_assistant\", ...message.claudeCodeCarrier }]\n\t\t\t\t\t: [];\n\t\t\tmessages.push({ role: \"assistant\", content: text, tool_calls: calls, reasoning_details: carrier });\n\t\t} else {\n\t\t\tif (message.content.some((block) => block.type !== \"text\"))\n\t\t\t\tthrow new Error(\"Claude Code subscription supports text tool results only\");\n\t\t\tmessages.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\ttool_call_id: message.toolCallId,\n\t\t\t\tcontent: message.content.map((block) => (block.type === \"text\" ? block.text : \"\")).join(\"\"),\n\t\t\t\tis_error: message.isError,\n\t\t\t});\n\t\t}\n\t}\n\tconst tools = (context.tools ?? []).map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t},\n\t}));\n\treturn { messages, tools };\n}\n\nfunction validateOptions(model: Model<Api>, options: StreamOptions | SimpleStreamOptions): void {\n\tif (!options.externalClaudeCode)\n\t\tthrow new Error(\"Claude Code subscription setup is required. Run /login anthropic.\");\n\tif (\n\t\toptions.apiKey ||\n\t\tObject.keys(options.headers ?? {}).length ||\n\t\toptions.onPayload ||\n\t\toptions.onResponse ||\n\t\toptions.env ||\n\t\toptions.metadata ||\n\t\t(options.transport && options.transport !== \"auto\") ||\n\t\toptions.maxRetries ||\n\t\t(options.maxRetryDelayMs !== undefined && options.maxRetryDelayMs !== 60_000) ||\n\t\toptions.websocketConnectTimeoutMs ||\n\t\tmodel.baseUrl !== \"https://api.anthropic.com\"\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support API keys, alternate endpoints, or request mutations\");\n\t}\n\tconst anthro = options as StreamOptions & {\n\t\ttoolChoice?: unknown;\n\t\tclient?: unknown;\n\t\textraBody?: unknown;\n\t\tthinkingBudgetTokens?: unknown;\n\t\tstopSequences?: unknown;\n\t\tthinkingEnabled?: boolean;\n\t\teffort?: string;\n\t\tthinkingDisplay?: unknown;\n\t\tinterleavedThinking?: unknown;\n\t};\n\tif (\n\t\t(anthro.toolChoice && anthro.toolChoice !== \"auto\") ||\n\t\tanthro.client ||\n\t\tanthro.extraBody ||\n\t\tanthro.thinkingBudgetTokens ||\n\t\tanthro.stopSequences ||\n\t\tanthro.thinkingDisplay !== undefined ||\n\t\tanthro.interleavedThinking !== undefined\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support forced tools or native request overrides\");\n\t}\n\tif (options.temperature !== undefined)\n\t\tthrow new Error(\"Claude Code subscription does not support sampling overrides\");\n}\n\ntype WorkerEvent = {\n\tv: 1;\n\trequestId: string;\n\ttype: string;\n\ttext?: unknown;\n\tpid?: unknown;\n\tresponse?: unknown;\n\tcategory?: unknown;\n};\n\nfunction parseWorkerRecord(line: string, requestId: string): WorkerEvent {\n\tif (Buffer.byteLength(line) > MAX_RECORD) throw new Error(\"Claude Code bridge record exceeds size limit\");\n\tconst value: unknown = JSON.parse(line);\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"v\" in value) ||\n\t\tvalue.v !== 1 ||\n\t\t!(\"requestId\" in value) ||\n\t\tvalue.requestId !== requestId ||\n\t\t!(\"type\" in value) ||\n\t\ttypeof value.type !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid Claude Code bridge record\");\n\t}\n\treturn value as WorkerEvent;\n}\n\nexport async function stopNative(pid: number): Promise<void> {\n\tif (!Number.isSafeInteger(pid) || pid < 1) return;\n\tif (process.platform === \"win32\") {\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst killer = spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], { stdio: \"ignore\", windowsHide: true });\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tkiller.kill();\n\t\t\t\tresolve();\n\t\t\t}, 3000);\n\t\t\tkiller.once(\"error\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tkiller.once(\"close\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t} else {\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t/* Already exited. */\n\t\t}\n\t}\n}\n\nfunction validatedCompletion(\n\tvalue: unknown,\n\tmodel: Model<Api>,\n\ttext: string,\n\tthinking: string,\n): {\n\tcontent: AssistantMessage[\"content\"];\n\tcarrier: AssistantMessage[\"claudeCodeCarrier\"];\n\tusage: Usage;\n\tresponseId: string;\n\treason: \"stop\" | \"length\" | \"toolUse\";\n} {\n\tif (!value || typeof value !== \"object\" || !(\"choices\" in value) || !Array.isArray(value.choices))\n\t\tthrow new Error(\"Invalid native completion\");\n\tconst response = value as Record<string, unknown> & {\n\t\tchoices: { finish_reason: unknown; message: Record<string, unknown> }[];\n\t\tusage: Record<string, unknown>;\n\t};\n\tconst choice = response.choices[0];\n\tif (\n\t\t!choice ||\n\t\t![\"stop\", \"length\", \"tool_calls\"].includes(String(choice.finish_reason)) ||\n\t\t(typeof choice.message?.content !== \"string\" && choice.message?.content !== null) ||\n\t\t(choice.message.content ?? \"\") !== text ||\n\t\t(choice.message.reasoning_content ?? \"\") !== thinking\n\t)\n\t\tthrow new Error(\"Native completion differs from streamed content\");\n\tconst rawCalls = choice.message.tool_calls ?? [];\n\tif (!Array.isArray(rawCalls)) throw new Error(\"Invalid native tool calls\");\n\tconst calls: ToolCall[] = rawCalls.map((call) => {\n\t\tif (\n\t\t\t!call ||\n\t\t\ttypeof call !== \"object\" ||\n\t\t\ttypeof call.id !== \"string\" ||\n\t\t\ttypeof call.function?.name !== \"string\" ||\n\t\t\ttypeof call.function?.arguments !== \"string\"\n\t\t)\n\t\t\tthrow new Error(\"Invalid native tool call\");\n\t\tconst args: unknown = JSON.parse(call.function.arguments);\n\t\tif (!args || typeof args !== \"object\" || Array.isArray(args)) throw new Error(\"Invalid native tool arguments\");\n\t\treturn { type: \"toolCall\", id: call.id, name: call.function.name, arguments: args as Record<string, unknown> };\n\t});\n\tconst native = response.usage;\n\tif (\n\t\t!native ||\n\t\ttypeof native.native_admission !== \"object\" ||\n\t\tnative.native_admission === null ||\n\t\t(native.native_admission as { upstream_requests?: unknown }).upstream_requests !== 1\n\t)\n\t\tthrow new Error(\"Native one-request admission not verified\");\n\tif (\n\t\t!native ||\n\t\t!Number.isFinite(native.prompt_tokens) ||\n\t\t!Number.isFinite(native.completion_tokens) ||\n\t\t!Number.isFinite(native.cache_creation_input_tokens) ||\n\t\t!(\"prompt_tokens_details\" in native)\n\t)\n\t\tthrow new Error(\"Missing native usage\");\n\tconst cached = (native.prompt_tokens_details as { cached_tokens?: unknown }).cached_tokens;\n\tif (!Number.isFinite(cached)) throw new Error(\"Missing native cache usage\");\n\tconst usage: Usage = {\n\t\tinput: Number(native.prompt_tokens) - Number(cached) - Number(native.cache_creation_input_tokens),\n\t\toutput: Number(native.completion_tokens),\n\t\tcacheRead: Number(cached),\n\t\tcacheWrite: Number(native.cache_creation_input_tokens),\n\t\ttotalTokens: Number(native.total_tokens),\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tif (usage.input < 0 || usage.output < 0) throw new Error(\"Invalid native usage\");\n\tcalculateCost(model, usage);\n\tconst details = choice.message.reasoning_details;\n\tconst carrier = Array.isArray(details)\n\t\t? details.find((entry) => entry?.type === \"claude-subscription-directsdk-experimental.native_assistant\")\n\t\t: undefined;\n\tconst projection = {\n\t\tcontent: text.trim(),\n\t\ttool_calls: calls.map((call) => ({ id: call.id, name: call.name, input: call.arguments })),\n\t};\n\tif (\n\t\t!carrier ||\n\t\tcarrier.version !== 1 ||\n\t\t!Array.isArray(carrier.messages) ||\n\t\tJSON.stringify(carrier.projection) !== JSON.stringify(projection)\n\t)\n\t\tthrow new Error(\"Invalid native replay carrier\");\n\treturn {\n\t\tcontent: [...(text ? [{ type: \"text\" as const, text }] : []), ...calls],\n\t\tcarrier: { version: 1, messages: carrier.messages, projection },\n\t\tusage,\n\t\tresponseId: String(response.id ?? \"\"),\n\t\treason: choice.finish_reason === \"tool_calls\" ? \"toolUse\" : choice.finish_reason === \"length\" ? \"length\" : \"stop\",\n\t};\n}\n\nexport function streamClaudeCode(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: StreamOptions | SimpleStreamOptions = {},\n): AssistantMessageEventStream {\n\tconst stream = new AssistantMessageEventStream();\n\tconst output: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tcontent: [],\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\tvoid (async () => {\n\t\tlet child: ChildProcessWithoutNullStreams | undefined;\n\t\tlet nativePid: number | undefined;\n\t\tlet nativeCleanup: Promise<void> | undefined;\n\t\tconst stopNativeOnce = () => {\n\t\t\tif (nativePid === undefined) return Promise.resolve();\n\t\t\tnativeCleanup ??= stopNative(nativePid);\n\t\t\treturn nativeCleanup;\n\t\t};\n\t\tlet timedOut = false;\n\t\tlet timer: NodeJS.Timeout | undefined;\n\t\tlet abortTimer: NodeJS.Timeout | undefined;\n\t\tlet started = false;\n\t\tlet complete = false;\n\t\tlet buffer = \"\";\n\t\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\t\tlet text = \"\";\n\t\tlet thinking = \"\";\n\t\tlet activeIndex = -1;\n\t\tlet activeType: \"text\" | \"thinking\" | undefined;\n\t\ttry {\n\t\t\tvalidateOptions(model, options);\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tconst connection = options.externalClaudeCode!;\n\t\t\tconst env = claudeCodeEnvironment(connection.configDir);\n\t\t\tconst input = history(context, model, connection);\n\t\t\tconst anthropicOptions = options as StreamOptions & { thinkingEnabled?: boolean; effort?: string };\n\t\t\tconst reasoning =\n\t\t\t\t\"reasoning\" in options && options.reasoning\n\t\t\t\t\t? { enabled: true, effort: options.reasoning }\n\t\t\t\t\t: anthropicOptions.thinkingEnabled !== undefined || anthropicOptions.effort\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tenabled: anthropicOptions.thinkingEnabled ?? true,\n\t\t\t\t\t\t\t\t...(anthropicOptions.effort ? { effort: anthropicOptions.effort } : {}),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\t\t\tconst requestId = randomUUID();\n\t\t\tchild = spawn(connection.python, [\"-s\", \"-B\", \"-u\", getClaudeCodeWorkerPath(\"lunr_bridge.py\")], {\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv,\n\t\t\t});\n\t\t\tconst worker = child;\n\t\t\tworker.stderr.resume();\n\t\t\tworker.stdin.on(\"error\", () => {});\n\t\t\tconst idleMs = Math.min(300_000, Math.max(1000, options.timeoutMs ?? 180_000));\n\t\t\tconst record = {\n\t\t\t\tv: 1,\n\t\t\t\trequestId,\n\t\t\t\ttype: \"start\",\n\t\t\t\tcommand: connection.command,\n\t\t\t\tenv,\n\t\t\t\tmodel: model.id,\n\t\t\t\t...input,\n\t\t\t\textraBody: {\n\t\t\t\t\t...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n\t\t\t\t\t...(reasoning ? { reasoning } : {}),\n\t\t\t\t},\n\t\t\t\ttimeout: Math.round(idleMs / 1000),\n\t\t\t};\n\t\t\tconst payload = JSON.stringify(record);\n\t\t\tif (Buffer.byteLength(payload) > MAX_RECORD) throw new Error(\"Claude Code request exceeds size limit\");\n\t\t\tworker.stdin.write(`${payload}\\n`);\n\t\t\tlet cancelSent = false;\n\t\t\tconst abort = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tcancelSent = true;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\tworker.stdin.write(`${JSON.stringify({ v: 1, requestId, type: \"cancel\" })}\\n`);\n\t\t\t\tabortTimer = setTimeout(() => {\n\t\t\t\t\tvoid stopNativeOnce().then(() => worker.kill());\n\t\t\t\t}, 2500);\n\t\t\t};\n\t\t\tconst resetDeadline = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t}, idleMs);\n\t\t\t};\n\t\t\ttimer = setTimeout(\n\t\t\t\t() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t},\n\t\t\t\tMath.min(30_000, idleMs),\n\t\t\t);\n\t\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tif (options.signal?.aborted) abort();\n\t\t\ttry {\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tworker.on(\"error\", reject);\n\t\t\t\t\tworker.stdout.on(\"data\", (data: Buffer) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tbuffer += decoder.decode(data, { stream: true });\n\t\t\t\t\t\t\tif (Buffer.byteLength(buffer) > MAX_RECORD)\n\t\t\t\t\t\t\t\tthrow new Error(\"Claude Code bridge record exceeds size limit\");\n\t\t\t\t\t\t\tfor (let newline = buffer.indexOf(\"\\n\"); newline >= 0; newline = buffer.indexOf(\"\\n\")) {\n\t\t\t\t\t\t\t\tconst event = parseWorkerRecord(buffer.slice(0, newline), requestId);\n\t\t\t\t\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\t\t\t\t\tif (event.type === \"ready\" || event.type === \"replay_progress\") resetDeadline();\n\t\t\t\t\t\t\t\telse if (\n\t\t\t\t\t\t\t\t\tevent.type === \"native_started\" &&\n\t\t\t\t\t\t\t\t\tNumber.isSafeInteger(event.pid) &&\n\t\t\t\t\t\t\t\t\tNumber(event.pid) > 0\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tnativePid = Number(event.pid);\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\t\tcancelSent &&\n\t\t\t\t\t\t\t\t\t[\"start\", \"text_delta\", \"thinking_delta\", \"complete\"].includes(event.type)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\telse if (event.type === \"start\") {\n\t\t\t\t\t\t\t\t\tif (started) throw new Error(\"Duplicate Claude Code stream start\");\n\t\t\t\t\t\t\t\t\tstarted = true;\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\t\t\t\t} else if (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete || typeof event.text !== \"string\")\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Invalid Claude Code stream delta\");\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t\tconst kind = event.type === \"text_delta\" ? \"text\" : \"thinking\";\n\t\t\t\t\t\t\t\t\tif (activeType !== kind) {\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tactiveIndex = output.content.length;\n\t\t\t\t\t\t\t\t\t\tactiveType = kind;\n\t\t\t\t\t\t\t\t\t\tif (kind === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"text\", text: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"thinking\", thinking: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst block = output.content[activeIndex];\n\t\t\t\t\t\t\t\t\tif (kind === \"text\" && block?.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\ttext += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.text += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (kind === \"thinking\" && block?.type === \"thinking\") {\n\t\t\t\t\t\t\t\t\t\tthinking += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.thinking += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"complete\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete) throw new Error(\"Invalid Claude Code completion order\");\n\t\t\t\t\t\t\t\t\tconst result = validatedCompletion(event.response, model, text, thinking);\n\t\t\t\t\t\t\t\t\tcomplete = true;\n\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\toutput.content = [\n\t\t\t\t\t\t\t\t\t\t...output.content.filter((block) => block.type !== \"toolCall\"),\n\t\t\t\t\t\t\t\t\t\t...result.content.filter((block) => block.type === \"toolCall\"),\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t\toutput.claudeCodeCarrier = result.carrier && {\n\t\t\t\t\t\t\t\t\t\t...result.carrier,\n\t\t\t\t\t\t\t\t\t\tcontentHash: contentHash(output.content),\n\t\t\t\t\t\t\t\t\t\taccountFingerprint: connection.accountFingerprint,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\toutput.responseId = result.responseId;\n\t\t\t\t\t\t\t\t\toutput.usage = result.usage;\n\t\t\t\t\t\t\t\t\toutput.stopReason = result.reason;\n\t\t\t\t\t\t\t\t\tfor (let index = 0; index < output.content.length; index++) {\n\t\t\t\t\t\t\t\t\t\tconst block = output.content[index];\n\t\t\t\t\t\t\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: output });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"cancelled\" && cancelSent) {\n\t\t\t\t\t\t\t\t} else if (event.type === \"error\" || event.type === \"cancelled\")\n\t\t\t\t\t\t\t\t\tthrow new ClaudeCodeRequestError(event.type === \"error\" ? event.category : undefined);\n\t\t\t\t\t\t\t\telse throw new Error(\"Unknown Claude Code bridge event\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tworker.on(\"close\", () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tdecoder.decode();\n\t\t\t\t\t\t\tif (complete || cancelSent) resolve();\n\t\t\t\t\t\t\telse reject(new Error(\"Claude Code bridge exited without a validated completion\"));\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\t}\n\t\t\tif (timedOut) throw new ClaudeCodeRequestError(\"timeout\");\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason as \"stop\" | \"length\" | \"toolUse\", message: output });\n\t\t} catch (error) {\n\t\t\toutput.content = [];\n\t\t\toutput.claudeCodeCarrier = undefined;\n\t\t\toutput.stopReason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tconst detail =\n\t\t\t\terror instanceof Error &&\n\t\t\t\t(error.message.startsWith(\"Claude Code subscription setup is required\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription does not support\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription refuses conflicting\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription requires TLS\"))\n\t\t\t\t\t? error.message\n\t\t\t\t\t: undefined;\n\t\t\toutput.errorMessage = options.signal?.aborted\n\t\t\t\t? \"Claude Code request cancelled\"\n\t\t\t\t: timedOut\n\t\t\t\t\t? SAFE_ERRORS.timeout\n\t\t\t\t\t: error instanceof ClaudeCodeRequestError\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: (detail ??\n\t\t\t\t\t\t\t\"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\");\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t} finally {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (abortTimer) clearTimeout(abortTimer);\n\t\t\tif (child) {\n\t\t\t\tif (!complete || child.exitCode === null) await stopNativeOnce();\n\t\t\t\tif (child.exitCode === null) child.kill();\n\t\t\t}\n\t\t}\n\t})();\n\treturn stream;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"anthropic-claude-code-bridge.d.ts","sourceRoot":"","sources":["../../src/api/anthropic-claude-code-bridge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACX,GAAG,EAEH,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,aAAa,EAGb,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAwDvE,wBAAgB,qBAAqB,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,MAAM,UAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAoB/F;AA2JD,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyB3D;AAmHD,wBAAgB,gBAAgB,CAC/B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,aAAa,GAAG,mBAAwB,GAC/C,2BAA2B,CAiS7B","sourcesContent":["import { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport type { ExternalClaudeCodeCredential } from \"../auth/types.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tToolCall,\n\tUsage,\n} from \"../types.ts\";\nimport { getClaudeCodeWorkerPath } from \"../utils/claude-code-assets.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nconst SAFE_ERRORS = {\n\tcontext_overflow: \"Claude Code prompt is too long for the context window.\",\n\ttimeout: \"Claude Code request timed out.\",\n\trate_limit: \"Claude Code rate limit reached. Please retry your request.\",\n\toverloaded: \"Claude Code service overloaded. Please retry your request.\",\n\ttransient: \"Claude Code service unavailable. Please retry your request.\",\n\tincomplete: \"Claude Code stream ended before message_stop. Please retry your request.\",\n} as const;\n\nclass ClaudeCodeRequestError extends Error {\n\tconstructor(category: unknown) {\n\t\tsuper(\n\t\t\ttypeof category === \"string\" && Object.hasOwn(SAFE_ERRORS, category)\n\t\t\t\t? SAFE_ERRORS[category as keyof typeof SAFE_ERRORS]\n\t\t\t\t: \"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\",\n\t\t);\n\t}\n}\n\nconst MAX_RECORD = 64 * 1024 * 1024;\nconst CONFLICTS = [\n\t\"ANTHROPIC_API_KEY\",\n\t\"ANTHROPIC_AUTH_TOKEN\",\n\t\"ANTHROPIC_OAUTH_TOKEN\",\n\t\"ANTHROPIC_BASE_URL\",\n\t\"ANTHROPIC_FOUNDRY_API_KEY\",\n\t\"CLAUDE_CODE_USE_BEDROCK\",\n\t\"CLAUDE_CODE_USE_VERTEX\",\n\t\"CLAUDE_CODE_USE_FOUNDRY\",\n\t\"CLAUDE_CODE_EXTRA_BODY\",\n] as const;\nconst ENV_ALLOWLIST = [\n\t\"PATH\",\n\t\"HOME\",\n\t\"USERPROFILE\",\n\t\"APPDATA\",\n\t\"LOCALAPPDATA\",\n\t\"PROGRAMDATA\",\n\t\"SYSTEMROOT\",\n\t\"SYSTEMDRIVE\",\n\t\"COMSPEC\",\n\t\"PATHEXT\",\n\t\"TEMP\",\n\t\"TMP\",\n\t\"LANG\",\n\t\"LC_ALL\",\n\t\"HTTP_PROXY\",\n\t\"HTTPS_PROXY\",\n\t\"NO_PROXY\",\n\t\"http_proxy\",\n\t\"https_proxy\",\n\t\"no_proxy\",\n] as const;\n\nexport function claudeCodeEnvironment(configDir?: string, strict = true): Record<string, string> {\n\tconst conflicting = CONFLICTS.filter((name) => {\n\t\tconst value = process.env[name];\n\t\treturn (\n\t\t\tvalue &&\n\t\t\t((name !== \"CLAUDE_CODE_USE_BEDROCK\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_VERTEX\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_FOUNDRY\") ||\n\t\t\t\t![\"0\", \"false\", \"no\", \"off\"].includes(value.toLowerCase()))\n\t\t);\n\t});\n\tif (strict && conflicting.length)\n\t\tthrow new Error(`Claude Code subscription refuses conflicting environment variables: ${conflicting.join(\", \")}`);\n\tif (process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\")\n\t\tthrow new Error(\"Claude Code subscription requires TLS certificate verification\");\n\tconst env = Object.fromEntries(\n\t\tENV_ALLOWLIST.flatMap((name) => (process.env[name] ? [[name, process.env[name]]] : [])),\n\t);\n\tif (configDir) env.CLAUDE_SUBSCRIPTION_DIRECTSDK_CONFIG_DIR = configDir;\n\treturn env;\n}\n\nfunction contentHash(content: AssistantMessage[\"content\"]): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(content)).digest(\"hex\");\n}\n\nfunction history(\n\tcontext: Context,\n\tmodel: Model<Api>,\n\tconnection: ExternalClaudeCodeCredential,\n): { messages: unknown[]; tools: unknown[] } {\n\tconst messages: Record<string, unknown>[] = context.systemPrompt\n\t\t? [{ role: \"system\", content: context.systemPrompt }]\n\t\t: [];\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"user\") {\n\t\t\tmessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent:\n\t\t\t\t\ttypeof message.content === \"string\"\n\t\t\t\t\t\t? message.content\n\t\t\t\t\t\t: message.content.map((block) =>\n\t\t\t\t\t\t\t\tblock.type === \"text\"\n\t\t\t\t\t\t\t\t\t? { type: \"text\", text: block.text }\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\t\t\t\timage_url: { url: `data:${block.mimeType};base64,${block.data}` },\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t});\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst text = message.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst calls = message.content\n\t\t\t\t.filter((block): block is ToolCall => block.type === \"toolCall\")\n\t\t\t\t.map((block) => ({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments) },\n\t\t\t\t}));\n\t\t\tconst projection = {\n\t\t\t\tcontent: text.trim(),\n\t\t\t\ttool_calls: calls.map((call) => ({\n\t\t\t\t\tid: call.id,\n\t\t\t\t\tname: call.function.name,\n\t\t\t\t\tinput: JSON.parse(call.function.arguments),\n\t\t\t\t})),\n\t\t\t};\n\t\t\tconst carrier =\n\t\t\t\tmessage.provider === \"anthropic\" &&\n\t\t\t\tmessage.model === model.id &&\n\t\t\t\tmessage.claudeCodeCarrier?.version === 1 &&\n\t\t\t\tconnection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.accountFingerprint === connection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.contentHash === contentHash(message.content) &&\n\t\t\t\tJSON.stringify(message.claudeCodeCarrier.projection) === JSON.stringify(projection)\n\t\t\t\t\t? [{ type: \"claude-subscription-directsdk-experimental.native_assistant\", ...message.claudeCodeCarrier }]\n\t\t\t\t\t: [];\n\t\t\tmessages.push({ role: \"assistant\", content: text, tool_calls: calls, reasoning_details: carrier });\n\t\t} else {\n\t\t\tif (message.content.some((block) => block.type !== \"text\"))\n\t\t\t\tthrow new Error(\"Claude Code subscription supports text tool results only\");\n\t\t\tmessages.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\ttool_call_id: message.toolCallId,\n\t\t\t\tcontent: message.content.map((block) => (block.type === \"text\" ? block.text : \"\")).join(\"\"),\n\t\t\t\tis_error: message.isError,\n\t\t\t});\n\t\t}\n\t}\n\tconst tools = (context.tools ?? []).map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t},\n\t}));\n\treturn { messages, tools };\n}\n\nfunction validateOptions(model: Model<Api>, options: StreamOptions | SimpleStreamOptions): void {\n\tif (!options.externalClaudeCode)\n\t\tthrow new Error(\"Claude Code subscription setup is required. Run /login anthropic.\");\n\tif (\n\t\toptions.apiKey ||\n\t\tObject.keys(options.headers ?? {}).length ||\n\t\toptions.onPayload ||\n\t\toptions.onResponse ||\n\t\toptions.env ||\n\t\toptions.metadata ||\n\t\t(options.transport && options.transport !== \"auto\") ||\n\t\toptions.maxRetries ||\n\t\t(options.maxRetryDelayMs !== undefined && options.maxRetryDelayMs !== 60_000) ||\n\t\toptions.websocketConnectTimeoutMs ||\n\t\tmodel.baseUrl !== \"https://api.anthropic.com\"\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support API keys, alternate endpoints, or request mutations\");\n\t}\n\tconst anthro = options as StreamOptions & {\n\t\ttoolChoice?: unknown;\n\t\tclient?: unknown;\n\t\textraBody?: unknown;\n\t\tthinkingBudgetTokens?: unknown;\n\t\tstopSequences?: unknown;\n\t\tthinkingEnabled?: boolean;\n\t\teffort?: string;\n\t\tthinkingDisplay?: unknown;\n\t\tinterleavedThinking?: unknown;\n\t};\n\tif (\n\t\t(anthro.toolChoice && anthro.toolChoice !== \"auto\") ||\n\t\tanthro.client ||\n\t\tanthro.extraBody ||\n\t\tanthro.thinkingBudgetTokens ||\n\t\tanthro.stopSequences ||\n\t\tanthro.thinkingDisplay !== undefined ||\n\t\tanthro.interleavedThinking !== undefined\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support forced tools or native request overrides\");\n\t}\n\tif (options.temperature !== undefined)\n\t\tthrow new Error(\"Claude Code subscription does not support sampling overrides\");\n}\n\ntype WorkerEvent = {\n\tv: 1;\n\trequestId: string;\n\ttype: string;\n\ttext?: unknown;\n\tpid?: unknown;\n\tresponse?: unknown;\n\tcategory?: unknown;\n};\n\nfunction parseWorkerRecord(line: string, requestId: string): WorkerEvent {\n\tif (Buffer.byteLength(line) > MAX_RECORD) throw new Error(\"Claude Code bridge record exceeds size limit\");\n\tconst value: unknown = JSON.parse(line);\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"v\" in value) ||\n\t\tvalue.v !== 1 ||\n\t\t!(\"requestId\" in value) ||\n\t\tvalue.requestId !== requestId ||\n\t\t!(\"type\" in value) ||\n\t\ttypeof value.type !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid Claude Code bridge record\");\n\t}\n\treturn value as WorkerEvent;\n}\n\nexport async function stopNative(pid: number): Promise<void> {\n\tif (!Number.isSafeInteger(pid) || pid < 1) return;\n\tif (process.platform === \"win32\") {\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst killer = spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], { stdio: \"ignore\", windowsHide: true });\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tkiller.kill();\n\t\t\t\tresolve();\n\t\t\t}, 3000);\n\t\t\tkiller.once(\"error\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tkiller.once(\"close\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t} else {\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t/* Already exited. */\n\t\t}\n\t}\n}\n\nfunction validatedCompletion(\n\tvalue: unknown,\n\tmodel: Model<Api>,\n\ttext: string,\n\tthinking: string,\n\tonUsage?: (usage: Usage) => void,\n): {\n\tcontent: AssistantMessage[\"content\"];\n\tcarrier: AssistantMessage[\"claudeCodeCarrier\"];\n\tusage: Usage;\n\tresponseId: string;\n\treason: \"stop\" | \"length\" | \"toolUse\";\n} {\n\tif (!value || typeof value !== \"object\" || !(\"choices\" in value) || !Array.isArray(value.choices))\n\t\tthrow new Error(\"Invalid native completion\");\n\tconst response = value as Record<string, unknown> & {\n\t\tchoices: { finish_reason: unknown; message: Record<string, unknown> }[];\n\t\tusage: Record<string, unknown>;\n\t};\n\tconst choice = response.choices[0];\n\tif (\n\t\t!choice ||\n\t\t![\"stop\", \"length\", \"tool_calls\"].includes(String(choice.finish_reason)) ||\n\t\t(typeof choice.message?.content !== \"string\" && choice.message?.content !== null) ||\n\t\t(choice.message.content ?? \"\") !== text ||\n\t\t(choice.message.reasoning_content ?? \"\") !== thinking\n\t)\n\t\tthrow new Error(\"Native completion differs from streamed content\");\n\tconst rawCalls = choice.message.tool_calls ?? [];\n\tif (!Array.isArray(rawCalls)) throw new Error(\"Invalid native tool calls\");\n\tconst calls: ToolCall[] = rawCalls.map((call) => {\n\t\tif (\n\t\t\t!call ||\n\t\t\ttypeof call !== \"object\" ||\n\t\t\ttypeof call.id !== \"string\" ||\n\t\t\ttypeof call.function?.name !== \"string\" ||\n\t\t\ttypeof call.function?.arguments !== \"string\"\n\t\t)\n\t\t\tthrow new Error(\"Invalid native tool call\");\n\t\tconst args: unknown = JSON.parse(call.function.arguments);\n\t\tif (!args || typeof args !== \"object\" || Array.isArray(args)) throw new Error(\"Invalid native tool arguments\");\n\t\treturn { type: \"toolCall\", id: call.id, name: call.function.name, arguments: args as Record<string, unknown> };\n\t});\n\tconst native = response.usage;\n\tif (\n\t\t!native ||\n\t\ttypeof native.native_admission !== \"object\" ||\n\t\tnative.native_admission === null ||\n\t\t(native.native_admission as { upstream_requests?: unknown }).upstream_requests !== 1\n\t)\n\t\tthrow new Error(\"Native one-request admission not verified\");\n\tif (\n\t\t!native ||\n\t\t!Number.isFinite(native.prompt_tokens) ||\n\t\t!Number.isFinite(native.completion_tokens) ||\n\t\t!Number.isFinite(native.cache_creation_input_tokens) ||\n\t\t!(\"prompt_tokens_details\" in native)\n\t)\n\t\tthrow new Error(\"Missing native usage\");\n\tconst cached = (native.prompt_tokens_details as { cached_tokens?: unknown }).cached_tokens;\n\tif (!Number.isFinite(cached)) throw new Error(\"Missing native cache usage\");\n\tconst usage: Usage = {\n\t\tinput: Number(native.prompt_tokens) - Number(cached) - Number(native.cache_creation_input_tokens),\n\t\tmeasurement: \"reported\",\n\t\treasoning: (native.completion_tokens_details as { reasoning_tokens?: number } | undefined)?.reasoning_tokens,\n\t\tcacheWrite1h: (native.native_usage as { cache_creation?: { ephemeral_1h_input_tokens?: number } } | undefined)\n\t\t\t?.cache_creation?.ephemeral_1h_input_tokens,\n\t\toutput: Number(native.completion_tokens),\n\t\tcacheRead: Number(cached),\n\t\tcacheWrite: Number(native.cache_creation_input_tokens),\n\t\ttotalTokens: Number(native.total_tokens),\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tif (\n\t\t[\n\t\t\tusage.input,\n\t\t\tusage.output,\n\t\t\tusage.cacheRead,\n\t\t\tusage.cacheWrite,\n\t\t\tusage.totalTokens,\n\t\t\tusage.reasoning ?? 0,\n\t\t\tusage.cacheWrite1h ?? 0,\n\t\t].some((value) => !Number.isFinite(value) || value < 0) ||\n\t\t(usage.cacheWrite1h ?? 0) > usage.cacheWrite ||\n\t\t(usage.reasoning ?? 0) > usage.output\n\t)\n\t\tthrow new Error(\"Invalid native usage\");\n\tcalculateCost(model, usage);\n\tonUsage?.(usage);\n\tconst details = choice.message.reasoning_details;\n\tconst carrier = Array.isArray(details)\n\t\t? details.find((entry) => entry?.type === \"claude-subscription-directsdk-experimental.native_assistant\")\n\t\t: undefined;\n\tconst projection = {\n\t\tcontent: text.trim(),\n\t\ttool_calls: calls.map((call) => ({ id: call.id, name: call.name, input: call.arguments })),\n\t};\n\tif (\n\t\t!carrier ||\n\t\tcarrier.version !== 1 ||\n\t\t!Array.isArray(carrier.messages) ||\n\t\tJSON.stringify(carrier.projection) !== JSON.stringify(projection)\n\t)\n\t\tthrow new Error(\"Invalid native replay carrier\");\n\treturn {\n\t\tcontent: [...(text ? [{ type: \"text\" as const, text }] : []), ...calls],\n\t\tcarrier: { version: 1, messages: carrier.messages, projection },\n\t\tusage,\n\t\tresponseId: String(response.id ?? \"\"),\n\t\treason: choice.finish_reason === \"tool_calls\" ? \"toolUse\" : choice.finish_reason === \"length\" ? \"length\" : \"stop\",\n\t};\n}\n\nexport function streamClaudeCode(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: StreamOptions | SimpleStreamOptions = {},\n): AssistantMessageEventStream {\n\tconst stream = new AssistantMessageEventStream();\n\tconst output: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tcontent: [],\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tmeasurement: \"unknown\",\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\tvoid (async () => {\n\t\tlet child: ChildProcessWithoutNullStreams | undefined;\n\t\tlet nativePid: number | undefined;\n\t\tlet nativeCleanup: Promise<void> | undefined;\n\t\tconst stopNativeOnce = () => {\n\t\t\tif (nativePid === undefined) return Promise.resolve();\n\t\t\tnativeCleanup ??= stopNative(nativePid);\n\t\t\treturn nativeCleanup;\n\t\t};\n\t\tlet timedOut = false;\n\t\tlet timer: NodeJS.Timeout | undefined;\n\t\tlet abortTimer: NodeJS.Timeout | undefined;\n\t\tlet started = false;\n\t\tlet complete = false;\n\t\tlet buffer = \"\";\n\t\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\t\tlet text = \"\";\n\t\tlet thinking = \"\";\n\t\tlet activeIndex = -1;\n\t\tlet activeType: \"text\" | \"thinking\" | undefined;\n\t\ttry {\n\t\t\tvalidateOptions(model, options);\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tconst connection = options.externalClaudeCode!;\n\t\t\tconst env = claudeCodeEnvironment(connection.configDir);\n\t\t\tconst input = history(context, model, connection);\n\t\t\tconst anthropicOptions = options as StreamOptions & { thinkingEnabled?: boolean; effort?: string };\n\t\t\tconst reasoning =\n\t\t\t\t\"reasoning\" in options && options.reasoning\n\t\t\t\t\t? { enabled: true, effort: options.reasoning }\n\t\t\t\t\t: anthropicOptions.thinkingEnabled !== undefined || anthropicOptions.effort\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tenabled: anthropicOptions.thinkingEnabled ?? true,\n\t\t\t\t\t\t\t\t...(anthropicOptions.effort ? { effort: anthropicOptions.effort } : {}),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\t\t\tconst requestId = randomUUID();\n\t\t\tchild = spawn(connection.python, [\"-s\", \"-B\", \"-u\", getClaudeCodeWorkerPath(\"lunr_bridge.py\")], {\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv,\n\t\t\t});\n\t\t\tconst worker = child;\n\t\t\tworker.stderr.resume();\n\t\t\tworker.stdin.on(\"error\", () => {});\n\t\t\tconst idleMs = Math.min(300_000, Math.max(1000, options.timeoutMs ?? 180_000));\n\t\t\tconst record = {\n\t\t\t\tv: 1,\n\t\t\t\trequestId,\n\t\t\t\ttype: \"start\",\n\t\t\t\tcommand: connection.command,\n\t\t\t\tenv,\n\t\t\t\tmodel: model.id,\n\t\t\t\t...input,\n\t\t\t\textraBody: {\n\t\t\t\t\t...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n\t\t\t\t\t...(reasoning ? { reasoning } : {}),\n\t\t\t\t},\n\t\t\t\ttimeout: Math.round(idleMs / 1000),\n\t\t\t};\n\t\t\tconst payload = JSON.stringify(record);\n\t\t\tif (Buffer.byteLength(payload) > MAX_RECORD) throw new Error(\"Claude Code request exceeds size limit\");\n\t\t\tworker.stdin.write(`${payload}\\n`);\n\t\t\tlet cancelSent = false;\n\t\t\tconst abort = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tcancelSent = true;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\tworker.stdin.write(`${JSON.stringify({ v: 1, requestId, type: \"cancel\" })}\\n`);\n\t\t\t\tabortTimer = setTimeout(() => {\n\t\t\t\t\tvoid stopNativeOnce().then(() => worker.kill());\n\t\t\t\t}, 2500);\n\t\t\t};\n\t\t\tconst resetDeadline = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t}, idleMs);\n\t\t\t};\n\t\t\ttimer = setTimeout(\n\t\t\t\t() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t},\n\t\t\t\tMath.min(30_000, idleMs),\n\t\t\t);\n\t\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tif (options.signal?.aborted) abort();\n\t\t\ttry {\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tworker.on(\"error\", reject);\n\t\t\t\t\tworker.stdout.on(\"data\", (data: Buffer) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tbuffer += decoder.decode(data, { stream: true });\n\t\t\t\t\t\t\tif (Buffer.byteLength(buffer) > MAX_RECORD)\n\t\t\t\t\t\t\t\tthrow new Error(\"Claude Code bridge record exceeds size limit\");\n\t\t\t\t\t\t\tfor (let newline = buffer.indexOf(\"\\n\"); newline >= 0; newline = buffer.indexOf(\"\\n\")) {\n\t\t\t\t\t\t\t\tconst event = parseWorkerRecord(buffer.slice(0, newline), requestId);\n\t\t\t\t\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\t\t\t\t\tif (event.type === \"ready\" || event.type === \"replay_progress\") resetDeadline();\n\t\t\t\t\t\t\t\telse if (\n\t\t\t\t\t\t\t\t\tevent.type === \"native_started\" &&\n\t\t\t\t\t\t\t\t\tNumber.isSafeInteger(event.pid) &&\n\t\t\t\t\t\t\t\t\tNumber(event.pid) > 0\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tnativePid = Number(event.pid);\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\t\tcancelSent &&\n\t\t\t\t\t\t\t\t\t[\"start\", \"text_delta\", \"thinking_delta\", \"complete\"].includes(event.type)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\telse if (event.type === \"start\") {\n\t\t\t\t\t\t\t\t\tif (started) throw new Error(\"Duplicate Claude Code stream start\");\n\t\t\t\t\t\t\t\t\tstarted = true;\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\t\t\t\t} else if (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete || typeof event.text !== \"string\")\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Invalid Claude Code stream delta\");\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t\tconst kind = event.type === \"text_delta\" ? \"text\" : \"thinking\";\n\t\t\t\t\t\t\t\t\tif (activeType !== kind) {\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tactiveIndex = output.content.length;\n\t\t\t\t\t\t\t\t\t\tactiveType = kind;\n\t\t\t\t\t\t\t\t\t\tif (kind === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"text\", text: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"thinking\", thinking: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst block = output.content[activeIndex];\n\t\t\t\t\t\t\t\t\tif (kind === \"text\" && block?.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\ttext += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.text += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (kind === \"thinking\" && block?.type === \"thinking\") {\n\t\t\t\t\t\t\t\t\t\tthinking += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.thinking += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"complete\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete) throw new Error(\"Invalid Claude Code completion order\");\n\t\t\t\t\t\t\t\t\tconst result = validatedCompletion(event.response, model, text, thinking, (usage) => {\n\t\t\t\t\t\t\t\t\t\toutput.usage = usage;\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcomplete = true;\n\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\toutput.content = [\n\t\t\t\t\t\t\t\t\t\t...output.content.filter((block) => block.type !== \"toolCall\"),\n\t\t\t\t\t\t\t\t\t\t...result.content.filter((block) => block.type === \"toolCall\"),\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t\toutput.claudeCodeCarrier = result.carrier && {\n\t\t\t\t\t\t\t\t\t\t...result.carrier,\n\t\t\t\t\t\t\t\t\t\tcontentHash: contentHash(output.content),\n\t\t\t\t\t\t\t\t\t\taccountFingerprint: connection.accountFingerprint,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\toutput.responseId = result.responseId;\n\t\t\t\t\t\t\t\t\toutput.usage = result.usage;\n\t\t\t\t\t\t\t\t\toutput.stopReason = result.reason;\n\t\t\t\t\t\t\t\t\tfor (let index = 0; index < output.content.length; index++) {\n\t\t\t\t\t\t\t\t\t\tconst block = output.content[index];\n\t\t\t\t\t\t\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: output });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"cancelled\" && cancelSent) {\n\t\t\t\t\t\t\t\t} else if (event.type === \"error\" || event.type === \"cancelled\")\n\t\t\t\t\t\t\t\t\tthrow new ClaudeCodeRequestError(event.type === \"error\" ? event.category : undefined);\n\t\t\t\t\t\t\t\telse throw new Error(\"Unknown Claude Code bridge event\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tworker.on(\"close\", () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tdecoder.decode();\n\t\t\t\t\t\t\tif (complete || cancelSent) resolve();\n\t\t\t\t\t\t\telse reject(new Error(\"Claude Code bridge exited without a validated completion\"));\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\t}\n\t\t\tif (timedOut) throw new ClaudeCodeRequestError(\"timeout\");\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason as \"stop\" | \"length\" | \"toolUse\", message: output });\n\t\t} catch (error) {\n\t\t\toutput.content = [];\n\t\t\toutput.claudeCodeCarrier = undefined;\n\t\t\toutput.stopReason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tconst detail =\n\t\t\t\terror instanceof Error &&\n\t\t\t\t(error.message.startsWith(\"Claude Code subscription setup is required\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription does not support\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription refuses conflicting\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription requires TLS\"))\n\t\t\t\t\t? error.message\n\t\t\t\t\t: undefined;\n\t\t\toutput.errorMessage = options.signal?.aborted\n\t\t\t\t? \"Claude Code request cancelled\"\n\t\t\t\t: timedOut\n\t\t\t\t\t? SAFE_ERRORS.timeout\n\t\t\t\t\t: error instanceof ClaudeCodeRequestError\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: (detail ??\n\t\t\t\t\t\t\t\"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\");\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t} finally {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (abortTimer) clearTimeout(abortTimer);\n\t\t\tif (child) {\n\t\t\t\tif (!complete || child.exitCode === null) await stopNativeOnce();\n\t\t\t\tif (child.exitCode === null) child.kill();\n\t\t\t}\n\t\t}\n\t})();\n\treturn stream;\n}\n"]}
|
|
@@ -217,7 +217,7 @@ export async function stopNative(pid) {
|
|
|
217
217
|
}
|
|
218
218
|
}
|
|
219
219
|
}
|
|
220
|
-
function validatedCompletion(value, model, text, thinking) {
|
|
220
|
+
function validatedCompletion(value, model, text, thinking, onUsage) {
|
|
221
221
|
if (!value || typeof value !== "object" || !("choices" in value) || !Array.isArray(value.choices))
|
|
222
222
|
throw new Error("Invalid native completion");
|
|
223
223
|
const response = value;
|
|
@@ -260,15 +260,30 @@ function validatedCompletion(value, model, text, thinking) {
|
|
|
260
260
|
throw new Error("Missing native cache usage");
|
|
261
261
|
const usage = {
|
|
262
262
|
input: Number(native.prompt_tokens) - Number(cached) - Number(native.cache_creation_input_tokens),
|
|
263
|
+
measurement: "reported",
|
|
264
|
+
reasoning: native.completion_tokens_details?.reasoning_tokens,
|
|
265
|
+
cacheWrite1h: native.native_usage
|
|
266
|
+
?.cache_creation?.ephemeral_1h_input_tokens,
|
|
263
267
|
output: Number(native.completion_tokens),
|
|
264
268
|
cacheRead: Number(cached),
|
|
265
269
|
cacheWrite: Number(native.cache_creation_input_tokens),
|
|
266
270
|
totalTokens: Number(native.total_tokens),
|
|
267
271
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
268
272
|
};
|
|
269
|
-
if (
|
|
273
|
+
if ([
|
|
274
|
+
usage.input,
|
|
275
|
+
usage.output,
|
|
276
|
+
usage.cacheRead,
|
|
277
|
+
usage.cacheWrite,
|
|
278
|
+
usage.totalTokens,
|
|
279
|
+
usage.reasoning ?? 0,
|
|
280
|
+
usage.cacheWrite1h ?? 0,
|
|
281
|
+
].some((value) => !Number.isFinite(value) || value < 0) ||
|
|
282
|
+
(usage.cacheWrite1h ?? 0) > usage.cacheWrite ||
|
|
283
|
+
(usage.reasoning ?? 0) > usage.output)
|
|
270
284
|
throw new Error("Invalid native usage");
|
|
271
285
|
calculateCost(model, usage);
|
|
286
|
+
onUsage?.(usage);
|
|
272
287
|
const details = choice.message.reasoning_details;
|
|
273
288
|
const carrier = Array.isArray(details)
|
|
274
289
|
? details.find((entry) => entry?.type === "claude-subscription-directsdk-experimental.native_assistant")
|
|
@@ -304,6 +319,7 @@ export function streamClaudeCode(model, context, options = {}) {
|
|
|
304
319
|
cacheRead: 0,
|
|
305
320
|
cacheWrite: 0,
|
|
306
321
|
totalTokens: 0,
|
|
322
|
+
measurement: "unknown",
|
|
307
323
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
308
324
|
},
|
|
309
325
|
stopReason: "stop",
|
|
@@ -487,7 +503,9 @@ export function streamClaudeCode(model, context, options = {}) {
|
|
|
487
503
|
else if (event.type === "complete") {
|
|
488
504
|
if (!started || complete)
|
|
489
505
|
throw new Error("Invalid Claude Code completion order");
|
|
490
|
-
const result = validatedCompletion(event.response, model, text, thinking)
|
|
506
|
+
const result = validatedCompletion(event.response, model, text, thinking, (usage) => {
|
|
507
|
+
output.usage = usage;
|
|
508
|
+
});
|
|
491
509
|
complete = true;
|
|
492
510
|
if (activeType === "text")
|
|
493
511
|
stream.push({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-claude-code-bridge.js","sourceRoot":"","sources":["../../src/api/anthropic-claude-code-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuC,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAW7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0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AAK,CAAC,OAAO;gBACf,CAAC,CAAC,SAAS,CAAC;YACd,MAAM,CAAC,YAAY,GAAG,OAAO,CAAC,MAAM,EAAE,OAAO;gBAC5C,CAAC,CAAC,+BAA+B;gBACjC,CAAC,CAAC,QAAQ;oBACT,CAAC,CAAC,WAAW,CAAC,OAAO;oBACrB,CAAC,CAAC,KAAK,YAAY,sBAAsB;wBACxC,CAAC,CAAC,KAAK,CAAC,OAAO;wBACf,CAAC,CAAC,CAAC,MAAM;4BACR,kGAAkG,CAAC,CAAC;YACxG,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;QAC1E,CAAC;gBAAS,CAAC;YACV,IAAI,KAAK;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;YAC/B,IAAI,UAAU;gBAAE,YAAY,CAAC,UAAU,CAAC,CAAC;YACzC,IAAI,KAAK,EAAE,CAAC;gBACX,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI;oBAAE,MAAM,cAAc,EAAE,CAAC;gBACjE,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI;oBAAE,KAAK,CAAC,IAAI,EAAE,CAAC;YAC3C,CAAC;QACF,CAAC;IAAA,CACD,CAAC,EAAE,CAAC;IACL,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport type { ExternalClaudeCodeCredential } from \"../auth/types.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tToolCall,\n\tUsage,\n} from \"../types.ts\";\nimport { getClaudeCodeWorkerPath } from \"../utils/claude-code-assets.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nconst SAFE_ERRORS = {\n\tcontext_overflow: \"Claude Code prompt is too long for the context window.\",\n\ttimeout: \"Claude Code request timed out.\",\n\trate_limit: \"Claude Code rate limit reached. Please retry your request.\",\n\toverloaded: \"Claude Code service overloaded. Please retry your request.\",\n\ttransient: \"Claude Code service unavailable. Please retry your request.\",\n\tincomplete: \"Claude Code stream ended before message_stop. Please retry your request.\",\n} as const;\n\nclass ClaudeCodeRequestError extends Error {\n\tconstructor(category: unknown) {\n\t\tsuper(\n\t\t\ttypeof category === \"string\" && Object.hasOwn(SAFE_ERRORS, category)\n\t\t\t\t? SAFE_ERRORS[category as keyof typeof SAFE_ERRORS]\n\t\t\t\t: \"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\",\n\t\t);\n\t}\n}\n\nconst MAX_RECORD = 64 * 1024 * 1024;\nconst CONFLICTS = [\n\t\"ANTHROPIC_API_KEY\",\n\t\"ANTHROPIC_AUTH_TOKEN\",\n\t\"ANTHROPIC_OAUTH_TOKEN\",\n\t\"ANTHROPIC_BASE_URL\",\n\t\"ANTHROPIC_FOUNDRY_API_KEY\",\n\t\"CLAUDE_CODE_USE_BEDROCK\",\n\t\"CLAUDE_CODE_USE_VERTEX\",\n\t\"CLAUDE_CODE_USE_FOUNDRY\",\n\t\"CLAUDE_CODE_EXTRA_BODY\",\n] as const;\nconst ENV_ALLOWLIST = [\n\t\"PATH\",\n\t\"HOME\",\n\t\"USERPROFILE\",\n\t\"APPDATA\",\n\t\"LOCALAPPDATA\",\n\t\"PROGRAMDATA\",\n\t\"SYSTEMROOT\",\n\t\"SYSTEMDRIVE\",\n\t\"COMSPEC\",\n\t\"PATHEXT\",\n\t\"TEMP\",\n\t\"TMP\",\n\t\"LANG\",\n\t\"LC_ALL\",\n\t\"HTTP_PROXY\",\n\t\"HTTPS_PROXY\",\n\t\"NO_PROXY\",\n\t\"http_proxy\",\n\t\"https_proxy\",\n\t\"no_proxy\",\n] as const;\n\nexport function claudeCodeEnvironment(configDir?: string, strict = true): Record<string, string> {\n\tconst conflicting = CONFLICTS.filter((name) => {\n\t\tconst value = process.env[name];\n\t\treturn (\n\t\t\tvalue &&\n\t\t\t((name !== \"CLAUDE_CODE_USE_BEDROCK\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_VERTEX\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_FOUNDRY\") ||\n\t\t\t\t![\"0\", \"false\", \"no\", \"off\"].includes(value.toLowerCase()))\n\t\t);\n\t});\n\tif (strict && conflicting.length)\n\t\tthrow new Error(`Claude Code subscription refuses conflicting environment variables: ${conflicting.join(\", \")}`);\n\tif (process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\")\n\t\tthrow new Error(\"Claude Code subscription requires TLS certificate verification\");\n\tconst env = Object.fromEntries(\n\t\tENV_ALLOWLIST.flatMap((name) => (process.env[name] ? [[name, process.env[name]]] : [])),\n\t);\n\tif (configDir) env.CLAUDE_SUBSCRIPTION_DIRECTSDK_CONFIG_DIR = configDir;\n\treturn env;\n}\n\nfunction contentHash(content: AssistantMessage[\"content\"]): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(content)).digest(\"hex\");\n}\n\nfunction history(\n\tcontext: Context,\n\tmodel: Model<Api>,\n\tconnection: ExternalClaudeCodeCredential,\n): { messages: unknown[]; tools: unknown[] } {\n\tconst messages: Record<string, unknown>[] = context.systemPrompt\n\t\t? [{ role: \"system\", content: context.systemPrompt }]\n\t\t: [];\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"user\") {\n\t\t\tmessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent:\n\t\t\t\t\ttypeof message.content === \"string\"\n\t\t\t\t\t\t? message.content\n\t\t\t\t\t\t: message.content.map((block) =>\n\t\t\t\t\t\t\t\tblock.type === \"text\"\n\t\t\t\t\t\t\t\t\t? { type: \"text\", text: block.text }\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\t\t\t\timage_url: { url: `data:${block.mimeType};base64,${block.data}` },\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t});\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst text = message.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst calls = message.content\n\t\t\t\t.filter((block): block is ToolCall => block.type === \"toolCall\")\n\t\t\t\t.map((block) => ({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments) },\n\t\t\t\t}));\n\t\t\tconst projection = {\n\t\t\t\tcontent: text.trim(),\n\t\t\t\ttool_calls: calls.map((call) => ({\n\t\t\t\t\tid: call.id,\n\t\t\t\t\tname: call.function.name,\n\t\t\t\t\tinput: JSON.parse(call.function.arguments),\n\t\t\t\t})),\n\t\t\t};\n\t\t\tconst carrier =\n\t\t\t\tmessage.provider === \"anthropic\" &&\n\t\t\t\tmessage.model === model.id &&\n\t\t\t\tmessage.claudeCodeCarrier?.version === 1 &&\n\t\t\t\tconnection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.accountFingerprint === connection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.contentHash === contentHash(message.content) &&\n\t\t\t\tJSON.stringify(message.claudeCodeCarrier.projection) === JSON.stringify(projection)\n\t\t\t\t\t? [{ type: \"claude-subscription-directsdk-experimental.native_assistant\", ...message.claudeCodeCarrier }]\n\t\t\t\t\t: [];\n\t\t\tmessages.push({ role: \"assistant\", content: text, tool_calls: calls, reasoning_details: carrier });\n\t\t} else {\n\t\t\tif (message.content.some((block) => block.type !== \"text\"))\n\t\t\t\tthrow new Error(\"Claude Code subscription supports text tool results only\");\n\t\t\tmessages.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\ttool_call_id: message.toolCallId,\n\t\t\t\tcontent: message.content.map((block) => (block.type === \"text\" ? block.text : \"\")).join(\"\"),\n\t\t\t\tis_error: message.isError,\n\t\t\t});\n\t\t}\n\t}\n\tconst tools = (context.tools ?? []).map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t},\n\t}));\n\treturn { messages, tools };\n}\n\nfunction validateOptions(model: Model<Api>, options: StreamOptions | SimpleStreamOptions): void {\n\tif (!options.externalClaudeCode)\n\t\tthrow new Error(\"Claude Code subscription setup is required. Run /login anthropic.\");\n\tif (\n\t\toptions.apiKey ||\n\t\tObject.keys(options.headers ?? {}).length ||\n\t\toptions.onPayload ||\n\t\toptions.onResponse ||\n\t\toptions.env ||\n\t\toptions.metadata ||\n\t\t(options.transport && options.transport !== \"auto\") ||\n\t\toptions.maxRetries ||\n\t\t(options.maxRetryDelayMs !== undefined && options.maxRetryDelayMs !== 60_000) ||\n\t\toptions.websocketConnectTimeoutMs ||\n\t\tmodel.baseUrl !== \"https://api.anthropic.com\"\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support API keys, alternate endpoints, or request mutations\");\n\t}\n\tconst anthro = options as StreamOptions & {\n\t\ttoolChoice?: unknown;\n\t\tclient?: unknown;\n\t\textraBody?: unknown;\n\t\tthinkingBudgetTokens?: unknown;\n\t\tstopSequences?: unknown;\n\t\tthinkingEnabled?: boolean;\n\t\teffort?: string;\n\t\tthinkingDisplay?: unknown;\n\t\tinterleavedThinking?: unknown;\n\t};\n\tif (\n\t\t(anthro.toolChoice && anthro.toolChoice !== \"auto\") ||\n\t\tanthro.client ||\n\t\tanthro.extraBody ||\n\t\tanthro.thinkingBudgetTokens ||\n\t\tanthro.stopSequences ||\n\t\tanthro.thinkingDisplay !== undefined ||\n\t\tanthro.interleavedThinking !== undefined\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support forced tools or native request overrides\");\n\t}\n\tif (options.temperature !== undefined)\n\t\tthrow new Error(\"Claude Code subscription does not support sampling overrides\");\n}\n\ntype WorkerEvent = {\n\tv: 1;\n\trequestId: string;\n\ttype: string;\n\ttext?: unknown;\n\tpid?: unknown;\n\tresponse?: unknown;\n\tcategory?: unknown;\n};\n\nfunction parseWorkerRecord(line: string, requestId: string): WorkerEvent {\n\tif (Buffer.byteLength(line) > MAX_RECORD) throw new Error(\"Claude Code bridge record exceeds size limit\");\n\tconst value: unknown = JSON.parse(line);\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"v\" in value) ||\n\t\tvalue.v !== 1 ||\n\t\t!(\"requestId\" in value) ||\n\t\tvalue.requestId !== requestId ||\n\t\t!(\"type\" in value) ||\n\t\ttypeof value.type !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid Claude Code bridge record\");\n\t}\n\treturn value as WorkerEvent;\n}\n\nexport async function stopNative(pid: number): Promise<void> {\n\tif (!Number.isSafeInteger(pid) || pid < 1) return;\n\tif (process.platform === \"win32\") {\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst killer = spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], { stdio: \"ignore\", windowsHide: true });\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tkiller.kill();\n\t\t\t\tresolve();\n\t\t\t}, 3000);\n\t\t\tkiller.once(\"error\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tkiller.once(\"close\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t} else {\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t/* Already exited. */\n\t\t}\n\t}\n}\n\nfunction validatedCompletion(\n\tvalue: unknown,\n\tmodel: Model<Api>,\n\ttext: string,\n\tthinking: string,\n): {\n\tcontent: AssistantMessage[\"content\"];\n\tcarrier: AssistantMessage[\"claudeCodeCarrier\"];\n\tusage: Usage;\n\tresponseId: string;\n\treason: \"stop\" | \"length\" | \"toolUse\";\n} {\n\tif (!value || typeof value !== \"object\" || !(\"choices\" in value) || !Array.isArray(value.choices))\n\t\tthrow new Error(\"Invalid native completion\");\n\tconst response = value as Record<string, unknown> & {\n\t\tchoices: { finish_reason: unknown; message: Record<string, unknown> }[];\n\t\tusage: Record<string, unknown>;\n\t};\n\tconst choice = response.choices[0];\n\tif (\n\t\t!choice ||\n\t\t![\"stop\", \"length\", \"tool_calls\"].includes(String(choice.finish_reason)) ||\n\t\t(typeof choice.message?.content !== \"string\" && choice.message?.content !== null) ||\n\t\t(choice.message.content ?? \"\") !== text ||\n\t\t(choice.message.reasoning_content ?? \"\") !== thinking\n\t)\n\t\tthrow new Error(\"Native completion differs from streamed content\");\n\tconst rawCalls = choice.message.tool_calls ?? [];\n\tif (!Array.isArray(rawCalls)) throw new Error(\"Invalid native tool calls\");\n\tconst calls: ToolCall[] = rawCalls.map((call) => {\n\t\tif (\n\t\t\t!call ||\n\t\t\ttypeof call !== \"object\" ||\n\t\t\ttypeof call.id !== \"string\" ||\n\t\t\ttypeof call.function?.name !== \"string\" ||\n\t\t\ttypeof call.function?.arguments !== \"string\"\n\t\t)\n\t\t\tthrow new Error(\"Invalid native tool call\");\n\t\tconst args: unknown = JSON.parse(call.function.arguments);\n\t\tif (!args || typeof args !== \"object\" || Array.isArray(args)) throw new Error(\"Invalid native tool arguments\");\n\t\treturn { type: \"toolCall\", id: call.id, name: call.function.name, arguments: args as Record<string, unknown> };\n\t});\n\tconst native = response.usage;\n\tif (\n\t\t!native ||\n\t\ttypeof native.native_admission !== \"object\" ||\n\t\tnative.native_admission === null ||\n\t\t(native.native_admission as { upstream_requests?: unknown }).upstream_requests !== 1\n\t)\n\t\tthrow new Error(\"Native one-request admission not verified\");\n\tif (\n\t\t!native ||\n\t\t!Number.isFinite(native.prompt_tokens) ||\n\t\t!Number.isFinite(native.completion_tokens) ||\n\t\t!Number.isFinite(native.cache_creation_input_tokens) ||\n\t\t!(\"prompt_tokens_details\" in native)\n\t)\n\t\tthrow new Error(\"Missing native usage\");\n\tconst cached = (native.prompt_tokens_details as { cached_tokens?: unknown }).cached_tokens;\n\tif (!Number.isFinite(cached)) throw new Error(\"Missing native cache usage\");\n\tconst usage: Usage = {\n\t\tinput: Number(native.prompt_tokens) - Number(cached) - Number(native.cache_creation_input_tokens),\n\t\toutput: Number(native.completion_tokens),\n\t\tcacheRead: Number(cached),\n\t\tcacheWrite: Number(native.cache_creation_input_tokens),\n\t\ttotalTokens: Number(native.total_tokens),\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tif (usage.input < 0 || usage.output < 0) throw new Error(\"Invalid native usage\");\n\tcalculateCost(model, usage);\n\tconst details = choice.message.reasoning_details;\n\tconst carrier = Array.isArray(details)\n\t\t? details.find((entry) => entry?.type === \"claude-subscription-directsdk-experimental.native_assistant\")\n\t\t: undefined;\n\tconst projection = {\n\t\tcontent: text.trim(),\n\t\ttool_calls: calls.map((call) => ({ id: call.id, name: call.name, input: call.arguments })),\n\t};\n\tif (\n\t\t!carrier ||\n\t\tcarrier.version !== 1 ||\n\t\t!Array.isArray(carrier.messages) ||\n\t\tJSON.stringify(carrier.projection) !== JSON.stringify(projection)\n\t)\n\t\tthrow new Error(\"Invalid native replay carrier\");\n\treturn {\n\t\tcontent: [...(text ? [{ type: \"text\" as const, text }] : []), ...calls],\n\t\tcarrier: { version: 1, messages: carrier.messages, projection },\n\t\tusage,\n\t\tresponseId: String(response.id ?? \"\"),\n\t\treason: choice.finish_reason === \"tool_calls\" ? \"toolUse\" : choice.finish_reason === \"length\" ? \"length\" : \"stop\",\n\t};\n}\n\nexport function streamClaudeCode(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: StreamOptions | SimpleStreamOptions = {},\n): AssistantMessageEventStream {\n\tconst stream = new AssistantMessageEventStream();\n\tconst output: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tcontent: [],\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\tvoid (async () => {\n\t\tlet child: ChildProcessWithoutNullStreams | undefined;\n\t\tlet nativePid: number | undefined;\n\t\tlet nativeCleanup: Promise<void> | undefined;\n\t\tconst stopNativeOnce = () => {\n\t\t\tif (nativePid === undefined) return Promise.resolve();\n\t\t\tnativeCleanup ??= stopNative(nativePid);\n\t\t\treturn nativeCleanup;\n\t\t};\n\t\tlet timedOut = false;\n\t\tlet timer: NodeJS.Timeout | undefined;\n\t\tlet abortTimer: NodeJS.Timeout | undefined;\n\t\tlet started = false;\n\t\tlet complete = false;\n\t\tlet buffer = \"\";\n\t\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\t\tlet text = \"\";\n\t\tlet thinking = \"\";\n\t\tlet activeIndex = -1;\n\t\tlet activeType: \"text\" | \"thinking\" | undefined;\n\t\ttry {\n\t\t\tvalidateOptions(model, options);\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tconst connection = options.externalClaudeCode!;\n\t\t\tconst env = claudeCodeEnvironment(connection.configDir);\n\t\t\tconst input = history(context, model, connection);\n\t\t\tconst anthropicOptions = options as StreamOptions & { thinkingEnabled?: boolean; effort?: string };\n\t\t\tconst reasoning =\n\t\t\t\t\"reasoning\" in options && options.reasoning\n\t\t\t\t\t? { enabled: true, effort: options.reasoning }\n\t\t\t\t\t: anthropicOptions.thinkingEnabled !== undefined || anthropicOptions.effort\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tenabled: anthropicOptions.thinkingEnabled ?? true,\n\t\t\t\t\t\t\t\t...(anthropicOptions.effort ? { effort: anthropicOptions.effort } : {}),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\t\t\tconst requestId = randomUUID();\n\t\t\tchild = spawn(connection.python, [\"-s\", \"-B\", \"-u\", getClaudeCodeWorkerPath(\"lunr_bridge.py\")], {\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv,\n\t\t\t});\n\t\t\tconst worker = child;\n\t\t\tworker.stderr.resume();\n\t\t\tworker.stdin.on(\"error\", () => {});\n\t\t\tconst idleMs = Math.min(300_000, Math.max(1000, options.timeoutMs ?? 180_000));\n\t\t\tconst record = {\n\t\t\t\tv: 1,\n\t\t\t\trequestId,\n\t\t\t\ttype: \"start\",\n\t\t\t\tcommand: connection.command,\n\t\t\t\tenv,\n\t\t\t\tmodel: model.id,\n\t\t\t\t...input,\n\t\t\t\textraBody: {\n\t\t\t\t\t...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n\t\t\t\t\t...(reasoning ? { reasoning } : {}),\n\t\t\t\t},\n\t\t\t\ttimeout: Math.round(idleMs / 1000),\n\t\t\t};\n\t\t\tconst payload = JSON.stringify(record);\n\t\t\tif (Buffer.byteLength(payload) > MAX_RECORD) throw new Error(\"Claude Code request exceeds size limit\");\n\t\t\tworker.stdin.write(`${payload}\\n`);\n\t\t\tlet cancelSent = false;\n\t\t\tconst abort = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tcancelSent = true;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\tworker.stdin.write(`${JSON.stringify({ v: 1, requestId, type: \"cancel\" })}\\n`);\n\t\t\t\tabortTimer = setTimeout(() => {\n\t\t\t\t\tvoid stopNativeOnce().then(() => worker.kill());\n\t\t\t\t}, 2500);\n\t\t\t};\n\t\t\tconst resetDeadline = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t}, idleMs);\n\t\t\t};\n\t\t\ttimer = setTimeout(\n\t\t\t\t() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t},\n\t\t\t\tMath.min(30_000, idleMs),\n\t\t\t);\n\t\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tif (options.signal?.aborted) abort();\n\t\t\ttry {\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tworker.on(\"error\", reject);\n\t\t\t\t\tworker.stdout.on(\"data\", (data: Buffer) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tbuffer += decoder.decode(data, { stream: true });\n\t\t\t\t\t\t\tif (Buffer.byteLength(buffer) > MAX_RECORD)\n\t\t\t\t\t\t\t\tthrow new Error(\"Claude Code bridge record exceeds size limit\");\n\t\t\t\t\t\t\tfor (let newline = buffer.indexOf(\"\\n\"); newline >= 0; newline = buffer.indexOf(\"\\n\")) {\n\t\t\t\t\t\t\t\tconst event = parseWorkerRecord(buffer.slice(0, newline), requestId);\n\t\t\t\t\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\t\t\t\t\tif (event.type === \"ready\" || event.type === \"replay_progress\") resetDeadline();\n\t\t\t\t\t\t\t\telse if (\n\t\t\t\t\t\t\t\t\tevent.type === \"native_started\" &&\n\t\t\t\t\t\t\t\t\tNumber.isSafeInteger(event.pid) &&\n\t\t\t\t\t\t\t\t\tNumber(event.pid) > 0\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tnativePid = Number(event.pid);\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\t\tcancelSent &&\n\t\t\t\t\t\t\t\t\t[\"start\", \"text_delta\", \"thinking_delta\", \"complete\"].includes(event.type)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\telse if (event.type === \"start\") {\n\t\t\t\t\t\t\t\t\tif (started) throw new Error(\"Duplicate Claude Code stream start\");\n\t\t\t\t\t\t\t\t\tstarted = true;\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\t\t\t\t} else if (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete || typeof event.text !== \"string\")\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Invalid Claude Code stream delta\");\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t\tconst kind = event.type === \"text_delta\" ? \"text\" : \"thinking\";\n\t\t\t\t\t\t\t\t\tif (activeType !== kind) {\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tactiveIndex = output.content.length;\n\t\t\t\t\t\t\t\t\t\tactiveType = kind;\n\t\t\t\t\t\t\t\t\t\tif (kind === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"text\", text: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"thinking\", thinking: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst block = output.content[activeIndex];\n\t\t\t\t\t\t\t\t\tif (kind === \"text\" && block?.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\ttext += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.text += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (kind === \"thinking\" && block?.type === \"thinking\") {\n\t\t\t\t\t\t\t\t\t\tthinking += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.thinking += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"complete\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete) throw new Error(\"Invalid Claude Code completion order\");\n\t\t\t\t\t\t\t\t\tconst result = validatedCompletion(event.response, model, text, thinking);\n\t\t\t\t\t\t\t\t\tcomplete = true;\n\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\toutput.content = [\n\t\t\t\t\t\t\t\t\t\t...output.content.filter((block) => block.type !== \"toolCall\"),\n\t\t\t\t\t\t\t\t\t\t...result.content.filter((block) => block.type === \"toolCall\"),\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t\toutput.claudeCodeCarrier = result.carrier && {\n\t\t\t\t\t\t\t\t\t\t...result.carrier,\n\t\t\t\t\t\t\t\t\t\tcontentHash: contentHash(output.content),\n\t\t\t\t\t\t\t\t\t\taccountFingerprint: connection.accountFingerprint,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\toutput.responseId = result.responseId;\n\t\t\t\t\t\t\t\t\toutput.usage = result.usage;\n\t\t\t\t\t\t\t\t\toutput.stopReason = result.reason;\n\t\t\t\t\t\t\t\t\tfor (let index = 0; index < output.content.length; index++) {\n\t\t\t\t\t\t\t\t\t\tconst block = output.content[index];\n\t\t\t\t\t\t\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: output });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"cancelled\" && cancelSent) {\n\t\t\t\t\t\t\t\t} else if (event.type === \"error\" || event.type === \"cancelled\")\n\t\t\t\t\t\t\t\t\tthrow new ClaudeCodeRequestError(event.type === \"error\" ? event.category : undefined);\n\t\t\t\t\t\t\t\telse throw new Error(\"Unknown Claude Code bridge event\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tworker.on(\"close\", () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tdecoder.decode();\n\t\t\t\t\t\t\tif (complete || cancelSent) resolve();\n\t\t\t\t\t\t\telse reject(new Error(\"Claude Code bridge exited without a validated completion\"));\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\t}\n\t\t\tif (timedOut) throw new ClaudeCodeRequestError(\"timeout\");\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason as \"stop\" | \"length\" | \"toolUse\", message: output });\n\t\t} catch (error) {\n\t\t\toutput.content = [];\n\t\t\toutput.claudeCodeCarrier = undefined;\n\t\t\toutput.stopReason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tconst detail =\n\t\t\t\terror instanceof Error &&\n\t\t\t\t(error.message.startsWith(\"Claude Code subscription setup is required\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription does not support\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription refuses conflicting\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription requires TLS\"))\n\t\t\t\t\t? error.message\n\t\t\t\t\t: undefined;\n\t\t\toutput.errorMessage = options.signal?.aborted\n\t\t\t\t? \"Claude Code request cancelled\"\n\t\t\t\t: timedOut\n\t\t\t\t\t? SAFE_ERRORS.timeout\n\t\t\t\t\t: error instanceof ClaudeCodeRequestError\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: (detail ??\n\t\t\t\t\t\t\t\"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\");\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t} finally {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (abortTimer) clearTimeout(abortTimer);\n\t\t\tif (child) {\n\t\t\t\tif (!complete || child.exitCode === null) await stopNativeOnce();\n\t\t\t\tif (child.exitCode === null) child.kill();\n\t\t\t}\n\t\t}\n\t})();\n\treturn stream;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"anthropic-claude-code-bridge.js","sourceRoot":"","sources":["../../src/api/anthropic-claude-code-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuC,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAW7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAEvE,MAAM,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;YAC/B,IAAI,UAAU;gBAAE,YAAY,CAAC,UAAU,CAAC,CAAC;YACzC,IAAI,KAAK,EAAE,CAAC;gBACX,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI;oBAAE,MAAM,cAAc,EAAE,CAAC;gBACjE,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI;oBAAE,KAAK,CAAC,IAAI,EAAE,CAAC;YAC3C,CAAC;QACF,CAAC;IAAA,CACD,CAAC,EAAE,CAAC;IACL,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport type { ExternalClaudeCodeCredential } from \"../auth/types.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamOptions,\n\tToolCall,\n\tUsage,\n} from \"../types.ts\";\nimport { getClaudeCodeWorkerPath } from \"../utils/claude-code-assets.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nconst SAFE_ERRORS = {\n\tcontext_overflow: \"Claude Code prompt is too long for the context window.\",\n\ttimeout: \"Claude Code request timed out.\",\n\trate_limit: \"Claude Code rate limit reached. Please retry your request.\",\n\toverloaded: \"Claude Code service overloaded. Please retry your request.\",\n\ttransient: \"Claude Code service unavailable. Please retry your request.\",\n\tincomplete: \"Claude Code stream ended before message_stop. Please retry your request.\",\n} as const;\n\nclass ClaudeCodeRequestError extends Error {\n\tconstructor(category: unknown) {\n\t\tsuper(\n\t\t\ttypeof category === \"string\" && Object.hasOwn(SAFE_ERRORS, category)\n\t\t\t\t? SAFE_ERRORS[category as keyof typeof SAFE_ERRORS]\n\t\t\t\t: \"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\",\n\t\t);\n\t}\n}\n\nconst MAX_RECORD = 64 * 1024 * 1024;\nconst CONFLICTS = [\n\t\"ANTHROPIC_API_KEY\",\n\t\"ANTHROPIC_AUTH_TOKEN\",\n\t\"ANTHROPIC_OAUTH_TOKEN\",\n\t\"ANTHROPIC_BASE_URL\",\n\t\"ANTHROPIC_FOUNDRY_API_KEY\",\n\t\"CLAUDE_CODE_USE_BEDROCK\",\n\t\"CLAUDE_CODE_USE_VERTEX\",\n\t\"CLAUDE_CODE_USE_FOUNDRY\",\n\t\"CLAUDE_CODE_EXTRA_BODY\",\n] as const;\nconst ENV_ALLOWLIST = [\n\t\"PATH\",\n\t\"HOME\",\n\t\"USERPROFILE\",\n\t\"APPDATA\",\n\t\"LOCALAPPDATA\",\n\t\"PROGRAMDATA\",\n\t\"SYSTEMROOT\",\n\t\"SYSTEMDRIVE\",\n\t\"COMSPEC\",\n\t\"PATHEXT\",\n\t\"TEMP\",\n\t\"TMP\",\n\t\"LANG\",\n\t\"LC_ALL\",\n\t\"HTTP_PROXY\",\n\t\"HTTPS_PROXY\",\n\t\"NO_PROXY\",\n\t\"http_proxy\",\n\t\"https_proxy\",\n\t\"no_proxy\",\n] as const;\n\nexport function claudeCodeEnvironment(configDir?: string, strict = true): Record<string, string> {\n\tconst conflicting = CONFLICTS.filter((name) => {\n\t\tconst value = process.env[name];\n\t\treturn (\n\t\t\tvalue &&\n\t\t\t((name !== \"CLAUDE_CODE_USE_BEDROCK\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_VERTEX\" &&\n\t\t\t\tname !== \"CLAUDE_CODE_USE_FOUNDRY\") ||\n\t\t\t\t![\"0\", \"false\", \"no\", \"off\"].includes(value.toLowerCase()))\n\t\t);\n\t});\n\tif (strict && conflicting.length)\n\t\tthrow new Error(`Claude Code subscription refuses conflicting environment variables: ${conflicting.join(\", \")}`);\n\tif (process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\")\n\t\tthrow new Error(\"Claude Code subscription requires TLS certificate verification\");\n\tconst env = Object.fromEntries(\n\t\tENV_ALLOWLIST.flatMap((name) => (process.env[name] ? [[name, process.env[name]]] : [])),\n\t);\n\tif (configDir) env.CLAUDE_SUBSCRIPTION_DIRECTSDK_CONFIG_DIR = configDir;\n\treturn env;\n}\n\nfunction contentHash(content: AssistantMessage[\"content\"]): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(content)).digest(\"hex\");\n}\n\nfunction history(\n\tcontext: Context,\n\tmodel: Model<Api>,\n\tconnection: ExternalClaudeCodeCredential,\n): { messages: unknown[]; tools: unknown[] } {\n\tconst messages: Record<string, unknown>[] = context.systemPrompt\n\t\t? [{ role: \"system\", content: context.systemPrompt }]\n\t\t: [];\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"user\") {\n\t\t\tmessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent:\n\t\t\t\t\ttypeof message.content === \"string\"\n\t\t\t\t\t\t? message.content\n\t\t\t\t\t\t: message.content.map((block) =>\n\t\t\t\t\t\t\t\tblock.type === \"text\"\n\t\t\t\t\t\t\t\t\t? { type: \"text\", text: block.text }\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"image_url\",\n\t\t\t\t\t\t\t\t\t\t\timage_url: { url: `data:${block.mimeType};base64,${block.data}` },\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t});\n\t\t} else if (message.role === \"assistant\") {\n\t\t\tconst text = message.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\");\n\t\t\tconst calls = message.content\n\t\t\t\t.filter((block): block is ToolCall => block.type === \"toolCall\")\n\t\t\t\t.map((block) => ({\n\t\t\t\t\tid: block.id,\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tfunction: { name: block.name, arguments: JSON.stringify(block.arguments) },\n\t\t\t\t}));\n\t\t\tconst projection = {\n\t\t\t\tcontent: text.trim(),\n\t\t\t\ttool_calls: calls.map((call) => ({\n\t\t\t\t\tid: call.id,\n\t\t\t\t\tname: call.function.name,\n\t\t\t\t\tinput: JSON.parse(call.function.arguments),\n\t\t\t\t})),\n\t\t\t};\n\t\t\tconst carrier =\n\t\t\t\tmessage.provider === \"anthropic\" &&\n\t\t\t\tmessage.model === model.id &&\n\t\t\t\tmessage.claudeCodeCarrier?.version === 1 &&\n\t\t\t\tconnection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.accountFingerprint === connection.accountFingerprint &&\n\t\t\t\tmessage.claudeCodeCarrier.contentHash === contentHash(message.content) &&\n\t\t\t\tJSON.stringify(message.claudeCodeCarrier.projection) === JSON.stringify(projection)\n\t\t\t\t\t? [{ type: \"claude-subscription-directsdk-experimental.native_assistant\", ...message.claudeCodeCarrier }]\n\t\t\t\t\t: [];\n\t\t\tmessages.push({ role: \"assistant\", content: text, tool_calls: calls, reasoning_details: carrier });\n\t\t} else {\n\t\t\tif (message.content.some((block) => block.type !== \"text\"))\n\t\t\t\tthrow new Error(\"Claude Code subscription supports text tool results only\");\n\t\t\tmessages.push({\n\t\t\t\trole: \"tool\",\n\t\t\t\ttool_call_id: message.toolCallId,\n\t\t\t\tcontent: message.content.map((block) => (block.type === \"text\" ? block.text : \"\")).join(\"\"),\n\t\t\t\tis_error: message.isError,\n\t\t\t});\n\t\t}\n\t}\n\tconst tools = (context.tools ?? []).map((tool) => ({\n\t\ttype: \"function\",\n\t\tfunction: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters,\n\t\t},\n\t}));\n\treturn { messages, tools };\n}\n\nfunction validateOptions(model: Model<Api>, options: StreamOptions | SimpleStreamOptions): void {\n\tif (!options.externalClaudeCode)\n\t\tthrow new Error(\"Claude Code subscription setup is required. Run /login anthropic.\");\n\tif (\n\t\toptions.apiKey ||\n\t\tObject.keys(options.headers ?? {}).length ||\n\t\toptions.onPayload ||\n\t\toptions.onResponse ||\n\t\toptions.env ||\n\t\toptions.metadata ||\n\t\t(options.transport && options.transport !== \"auto\") ||\n\t\toptions.maxRetries ||\n\t\t(options.maxRetryDelayMs !== undefined && options.maxRetryDelayMs !== 60_000) ||\n\t\toptions.websocketConnectTimeoutMs ||\n\t\tmodel.baseUrl !== \"https://api.anthropic.com\"\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support API keys, alternate endpoints, or request mutations\");\n\t}\n\tconst anthro = options as StreamOptions & {\n\t\ttoolChoice?: unknown;\n\t\tclient?: unknown;\n\t\textraBody?: unknown;\n\t\tthinkingBudgetTokens?: unknown;\n\t\tstopSequences?: unknown;\n\t\tthinkingEnabled?: boolean;\n\t\teffort?: string;\n\t\tthinkingDisplay?: unknown;\n\t\tinterleavedThinking?: unknown;\n\t};\n\tif (\n\t\t(anthro.toolChoice && anthro.toolChoice !== \"auto\") ||\n\t\tanthro.client ||\n\t\tanthro.extraBody ||\n\t\tanthro.thinkingBudgetTokens ||\n\t\tanthro.stopSequences ||\n\t\tanthro.thinkingDisplay !== undefined ||\n\t\tanthro.interleavedThinking !== undefined\n\t) {\n\t\tthrow new Error(\"Claude Code subscription does not support forced tools or native request overrides\");\n\t}\n\tif (options.temperature !== undefined)\n\t\tthrow new Error(\"Claude Code subscription does not support sampling overrides\");\n}\n\ntype WorkerEvent = {\n\tv: 1;\n\trequestId: string;\n\ttype: string;\n\ttext?: unknown;\n\tpid?: unknown;\n\tresponse?: unknown;\n\tcategory?: unknown;\n};\n\nfunction parseWorkerRecord(line: string, requestId: string): WorkerEvent {\n\tif (Buffer.byteLength(line) > MAX_RECORD) throw new Error(\"Claude Code bridge record exceeds size limit\");\n\tconst value: unknown = JSON.parse(line);\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"v\" in value) ||\n\t\tvalue.v !== 1 ||\n\t\t!(\"requestId\" in value) ||\n\t\tvalue.requestId !== requestId ||\n\t\t!(\"type\" in value) ||\n\t\ttypeof value.type !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid Claude Code bridge record\");\n\t}\n\treturn value as WorkerEvent;\n}\n\nexport async function stopNative(pid: number): Promise<void> {\n\tif (!Number.isSafeInteger(pid) || pid < 1) return;\n\tif (process.platform === \"win32\") {\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst killer = spawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], { stdio: \"ignore\", windowsHide: true });\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tkiller.kill();\n\t\t\t\tresolve();\n\t\t\t}, 3000);\n\t\t\tkiller.once(\"error\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tkiller.once(\"close\", () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t} else {\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t/* Already exited. */\n\t\t}\n\t}\n}\n\nfunction validatedCompletion(\n\tvalue: unknown,\n\tmodel: Model<Api>,\n\ttext: string,\n\tthinking: string,\n\tonUsage?: (usage: Usage) => void,\n): {\n\tcontent: AssistantMessage[\"content\"];\n\tcarrier: AssistantMessage[\"claudeCodeCarrier\"];\n\tusage: Usage;\n\tresponseId: string;\n\treason: \"stop\" | \"length\" | \"toolUse\";\n} {\n\tif (!value || typeof value !== \"object\" || !(\"choices\" in value) || !Array.isArray(value.choices))\n\t\tthrow new Error(\"Invalid native completion\");\n\tconst response = value as Record<string, unknown> & {\n\t\tchoices: { finish_reason: unknown; message: Record<string, unknown> }[];\n\t\tusage: Record<string, unknown>;\n\t};\n\tconst choice = response.choices[0];\n\tif (\n\t\t!choice ||\n\t\t![\"stop\", \"length\", \"tool_calls\"].includes(String(choice.finish_reason)) ||\n\t\t(typeof choice.message?.content !== \"string\" && choice.message?.content !== null) ||\n\t\t(choice.message.content ?? \"\") !== text ||\n\t\t(choice.message.reasoning_content ?? \"\") !== thinking\n\t)\n\t\tthrow new Error(\"Native completion differs from streamed content\");\n\tconst rawCalls = choice.message.tool_calls ?? [];\n\tif (!Array.isArray(rawCalls)) throw new Error(\"Invalid native tool calls\");\n\tconst calls: ToolCall[] = rawCalls.map((call) => {\n\t\tif (\n\t\t\t!call ||\n\t\t\ttypeof call !== \"object\" ||\n\t\t\ttypeof call.id !== \"string\" ||\n\t\t\ttypeof call.function?.name !== \"string\" ||\n\t\t\ttypeof call.function?.arguments !== \"string\"\n\t\t)\n\t\t\tthrow new Error(\"Invalid native tool call\");\n\t\tconst args: unknown = JSON.parse(call.function.arguments);\n\t\tif (!args || typeof args !== \"object\" || Array.isArray(args)) throw new Error(\"Invalid native tool arguments\");\n\t\treturn { type: \"toolCall\", id: call.id, name: call.function.name, arguments: args as Record<string, unknown> };\n\t});\n\tconst native = response.usage;\n\tif (\n\t\t!native ||\n\t\ttypeof native.native_admission !== \"object\" ||\n\t\tnative.native_admission === null ||\n\t\t(native.native_admission as { upstream_requests?: unknown }).upstream_requests !== 1\n\t)\n\t\tthrow new Error(\"Native one-request admission not verified\");\n\tif (\n\t\t!native ||\n\t\t!Number.isFinite(native.prompt_tokens) ||\n\t\t!Number.isFinite(native.completion_tokens) ||\n\t\t!Number.isFinite(native.cache_creation_input_tokens) ||\n\t\t!(\"prompt_tokens_details\" in native)\n\t)\n\t\tthrow new Error(\"Missing native usage\");\n\tconst cached = (native.prompt_tokens_details as { cached_tokens?: unknown }).cached_tokens;\n\tif (!Number.isFinite(cached)) throw new Error(\"Missing native cache usage\");\n\tconst usage: Usage = {\n\t\tinput: Number(native.prompt_tokens) - Number(cached) - Number(native.cache_creation_input_tokens),\n\t\tmeasurement: \"reported\",\n\t\treasoning: (native.completion_tokens_details as { reasoning_tokens?: number } | undefined)?.reasoning_tokens,\n\t\tcacheWrite1h: (native.native_usage as { cache_creation?: { ephemeral_1h_input_tokens?: number } } | undefined)\n\t\t\t?.cache_creation?.ephemeral_1h_input_tokens,\n\t\toutput: Number(native.completion_tokens),\n\t\tcacheRead: Number(cached),\n\t\tcacheWrite: Number(native.cache_creation_input_tokens),\n\t\ttotalTokens: Number(native.total_tokens),\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tif (\n\t\t[\n\t\t\tusage.input,\n\t\t\tusage.output,\n\t\t\tusage.cacheRead,\n\t\t\tusage.cacheWrite,\n\t\t\tusage.totalTokens,\n\t\t\tusage.reasoning ?? 0,\n\t\t\tusage.cacheWrite1h ?? 0,\n\t\t].some((value) => !Number.isFinite(value) || value < 0) ||\n\t\t(usage.cacheWrite1h ?? 0) > usage.cacheWrite ||\n\t\t(usage.reasoning ?? 0) > usage.output\n\t)\n\t\tthrow new Error(\"Invalid native usage\");\n\tcalculateCost(model, usage);\n\tonUsage?.(usage);\n\tconst details = choice.message.reasoning_details;\n\tconst carrier = Array.isArray(details)\n\t\t? details.find((entry) => entry?.type === \"claude-subscription-directsdk-experimental.native_assistant\")\n\t\t: undefined;\n\tconst projection = {\n\t\tcontent: text.trim(),\n\t\ttool_calls: calls.map((call) => ({ id: call.id, name: call.name, input: call.arguments })),\n\t};\n\tif (\n\t\t!carrier ||\n\t\tcarrier.version !== 1 ||\n\t\t!Array.isArray(carrier.messages) ||\n\t\tJSON.stringify(carrier.projection) !== JSON.stringify(projection)\n\t)\n\t\tthrow new Error(\"Invalid native replay carrier\");\n\treturn {\n\t\tcontent: [...(text ? [{ type: \"text\" as const, text }] : []), ...calls],\n\t\tcarrier: { version: 1, messages: carrier.messages, projection },\n\t\tusage,\n\t\tresponseId: String(response.id ?? \"\"),\n\t\treason: choice.finish_reason === \"tool_calls\" ? \"toolUse\" : choice.finish_reason === \"length\" ? \"length\" : \"stop\",\n\t};\n}\n\nexport function streamClaudeCode(\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: StreamOptions | SimpleStreamOptions = {},\n): AssistantMessageEventStream {\n\tconst stream = new AssistantMessageEventStream();\n\tconst output: AssistantMessage = {\n\t\trole: \"assistant\",\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tcontent: [],\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tmeasurement: \"unknown\",\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\tvoid (async () => {\n\t\tlet child: ChildProcessWithoutNullStreams | undefined;\n\t\tlet nativePid: number | undefined;\n\t\tlet nativeCleanup: Promise<void> | undefined;\n\t\tconst stopNativeOnce = () => {\n\t\t\tif (nativePid === undefined) return Promise.resolve();\n\t\t\tnativeCleanup ??= stopNative(nativePid);\n\t\t\treturn nativeCleanup;\n\t\t};\n\t\tlet timedOut = false;\n\t\tlet timer: NodeJS.Timeout | undefined;\n\t\tlet abortTimer: NodeJS.Timeout | undefined;\n\t\tlet started = false;\n\t\tlet complete = false;\n\t\tlet buffer = \"\";\n\t\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\t\tlet text = \"\";\n\t\tlet thinking = \"\";\n\t\tlet activeIndex = -1;\n\t\tlet activeType: \"text\" | \"thinking\" | undefined;\n\t\ttry {\n\t\t\tvalidateOptions(model, options);\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tconst connection = options.externalClaudeCode!;\n\t\t\tconst env = claudeCodeEnvironment(connection.configDir);\n\t\t\tconst input = history(context, model, connection);\n\t\t\tconst anthropicOptions = options as StreamOptions & { thinkingEnabled?: boolean; effort?: string };\n\t\t\tconst reasoning =\n\t\t\t\t\"reasoning\" in options && options.reasoning\n\t\t\t\t\t? { enabled: true, effort: options.reasoning }\n\t\t\t\t\t: anthropicOptions.thinkingEnabled !== undefined || anthropicOptions.effort\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tenabled: anthropicOptions.thinkingEnabled ?? true,\n\t\t\t\t\t\t\t\t...(anthropicOptions.effort ? { effort: anthropicOptions.effort } : {}),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\t\t\tconst requestId = randomUUID();\n\t\t\tchild = spawn(connection.python, [\"-s\", \"-B\", \"-u\", getClaudeCodeWorkerPath(\"lunr_bridge.py\")], {\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv,\n\t\t\t});\n\t\t\tconst worker = child;\n\t\t\tworker.stderr.resume();\n\t\t\tworker.stdin.on(\"error\", () => {});\n\t\t\tconst idleMs = Math.min(300_000, Math.max(1000, options.timeoutMs ?? 180_000));\n\t\t\tconst record = {\n\t\t\t\tv: 1,\n\t\t\t\trequestId,\n\t\t\t\ttype: \"start\",\n\t\t\t\tcommand: connection.command,\n\t\t\t\tenv,\n\t\t\t\tmodel: model.id,\n\t\t\t\t...input,\n\t\t\t\textraBody: {\n\t\t\t\t\t...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n\t\t\t\t\t...(reasoning ? { reasoning } : {}),\n\t\t\t\t},\n\t\t\t\ttimeout: Math.round(idleMs / 1000),\n\t\t\t};\n\t\t\tconst payload = JSON.stringify(record);\n\t\t\tif (Buffer.byteLength(payload) > MAX_RECORD) throw new Error(\"Claude Code request exceeds size limit\");\n\t\t\tworker.stdin.write(`${payload}\\n`);\n\t\t\tlet cancelSent = false;\n\t\t\tconst abort = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tcancelSent = true;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\tworker.stdin.write(`${JSON.stringify({ v: 1, requestId, type: \"cancel\" })}\\n`);\n\t\t\t\tabortTimer = setTimeout(() => {\n\t\t\t\t\tvoid stopNativeOnce().then(() => worker.kill());\n\t\t\t\t}, 2500);\n\t\t\t};\n\t\t\tconst resetDeadline = () => {\n\t\t\t\tif (cancelSent) return;\n\t\t\t\tif (timer) clearTimeout(timer);\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t}, idleMs);\n\t\t\t};\n\t\t\ttimer = setTimeout(\n\t\t\t\t() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tabort();\n\t\t\t\t},\n\t\t\t\tMath.min(30_000, idleMs),\n\t\t\t);\n\t\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tif (options.signal?.aborted) abort();\n\t\t\ttry {\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tworker.on(\"error\", reject);\n\t\t\t\t\tworker.stdout.on(\"data\", (data: Buffer) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tbuffer += decoder.decode(data, { stream: true });\n\t\t\t\t\t\t\tif (Buffer.byteLength(buffer) > MAX_RECORD)\n\t\t\t\t\t\t\t\tthrow new Error(\"Claude Code bridge record exceeds size limit\");\n\t\t\t\t\t\t\tfor (let newline = buffer.indexOf(\"\\n\"); newline >= 0; newline = buffer.indexOf(\"\\n\")) {\n\t\t\t\t\t\t\t\tconst event = parseWorkerRecord(buffer.slice(0, newline), requestId);\n\t\t\t\t\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\t\t\t\t\tif (event.type === \"ready\" || event.type === \"replay_progress\") resetDeadline();\n\t\t\t\t\t\t\t\telse if (\n\t\t\t\t\t\t\t\t\tevent.type === \"native_started\" &&\n\t\t\t\t\t\t\t\t\tNumber.isSafeInteger(event.pid) &&\n\t\t\t\t\t\t\t\t\tNumber(event.pid) > 0\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tnativePid = Number(event.pid);\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t\t\tcancelSent &&\n\t\t\t\t\t\t\t\t\t[\"start\", \"text_delta\", \"thinking_delta\", \"complete\"].includes(event.type)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\telse if (event.type === \"start\") {\n\t\t\t\t\t\t\t\t\tif (started) throw new Error(\"Duplicate Claude Code stream start\");\n\t\t\t\t\t\t\t\t\tstarted = true;\n\t\t\t\t\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\t\t\t\t} else if (event.type === \"text_delta\" || event.type === \"thinking_delta\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete || typeof event.text !== \"string\")\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Invalid Claude Code stream delta\");\n\t\t\t\t\t\t\t\t\tresetDeadline();\n\t\t\t\t\t\t\t\t\tconst kind = event.type === \"text_delta\" ? \"text\" : \"thinking\";\n\t\t\t\t\t\t\t\t\tif (activeType !== kind) {\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tactiveIndex = output.content.length;\n\t\t\t\t\t\t\t\t\t\tactiveType = kind;\n\t\t\t\t\t\t\t\t\t\tif (kind === \"text\") {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"text\", text: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"text_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\toutput.content.push({ type: \"thinking\", thinking: \"\" });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: activeIndex, partial: output });\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst block = output.content[activeIndex];\n\t\t\t\t\t\t\t\t\tif (kind === \"text\" && block?.type === \"text\") {\n\t\t\t\t\t\t\t\t\t\ttext += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.text += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (kind === \"thinking\" && block?.type === \"thinking\") {\n\t\t\t\t\t\t\t\t\t\tthinking += event.text;\n\t\t\t\t\t\t\t\t\t\tblock.thinking += event.text;\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tdelta: event.text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"complete\") {\n\t\t\t\t\t\t\t\t\tif (!started || complete) throw new Error(\"Invalid Claude Code completion order\");\n\t\t\t\t\t\t\t\t\tconst result = validatedCompletion(event.response, model, text, thinking, (usage) => {\n\t\t\t\t\t\t\t\t\t\toutput.usage = usage;\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcomplete = true;\n\t\t\t\t\t\t\t\t\tif (activeType === \"text\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { text: string }).text,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (activeType === \"thinking\")\n\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\t\t\t\t\t\t\tcontentIndex: activeIndex,\n\t\t\t\t\t\t\t\t\t\t\tcontent: (output.content[activeIndex] as { thinking: string }).thinking,\n\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\toutput.content = [\n\t\t\t\t\t\t\t\t\t\t...output.content.filter((block) => block.type !== \"toolCall\"),\n\t\t\t\t\t\t\t\t\t\t...result.content.filter((block) => block.type === \"toolCall\"),\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t\toutput.claudeCodeCarrier = result.carrier && {\n\t\t\t\t\t\t\t\t\t\t...result.carrier,\n\t\t\t\t\t\t\t\t\t\tcontentHash: contentHash(output.content),\n\t\t\t\t\t\t\t\t\t\taccountFingerprint: connection.accountFingerprint,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\toutput.responseId = result.responseId;\n\t\t\t\t\t\t\t\t\toutput.usage = result.usage;\n\t\t\t\t\t\t\t\t\toutput.stopReason = result.reason;\n\t\t\t\t\t\t\t\t\tfor (let index = 0; index < output.content.length; index++) {\n\t\t\t\t\t\t\t\t\t\tconst block = output.content[index];\n\t\t\t\t\t\t\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\t\t\t\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: output });\n\t\t\t\t\t\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\t\t\t\t\t\t\t\tcontentIndex: index,\n\t\t\t\t\t\t\t\t\t\t\t\ttoolCall: block,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (event.type === \"cancelled\" && cancelSent) {\n\t\t\t\t\t\t\t\t} else if (event.type === \"error\" || event.type === \"cancelled\")\n\t\t\t\t\t\t\t\t\tthrow new ClaudeCodeRequestError(event.type === \"error\" ? event.category : undefined);\n\t\t\t\t\t\t\t\telse throw new Error(\"Unknown Claude Code bridge event\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tworker.on(\"close\", () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tdecoder.decode();\n\t\t\t\t\t\t\tif (complete || cancelSent) resolve();\n\t\t\t\t\t\t\telse reject(new Error(\"Claude Code bridge exited without a validated completion\"));\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", abort);\n\t\t\t}\n\t\t\tif (timedOut) throw new ClaudeCodeRequestError(\"timeout\");\n\t\t\tif (options.signal?.aborted) throw new Error(\"Claude Code request cancelled\");\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason as \"stop\" | \"length\" | \"toolUse\", message: output });\n\t\t} catch (error) {\n\t\t\toutput.content = [];\n\t\t\toutput.claudeCodeCarrier = undefined;\n\t\t\toutput.stopReason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tconst detail =\n\t\t\t\terror instanceof Error &&\n\t\t\t\t(error.message.startsWith(\"Claude Code subscription setup is required\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription does not support\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription refuses conflicting\") ||\n\t\t\t\t\terror.message.startsWith(\"Claude Code subscription requires TLS\"))\n\t\t\t\t\t? error.message\n\t\t\t\t\t: undefined;\n\t\t\toutput.errorMessage = options.signal?.aborted\n\t\t\t\t? \"Claude Code request cancelled\"\n\t\t\t\t: timedOut\n\t\t\t\t\t? SAFE_ERRORS.timeout\n\t\t\t\t\t: error instanceof ClaudeCodeRequestError\n\t\t\t\t\t\t? error.message\n\t\t\t\t\t\t: (detail ??\n\t\t\t\t\t\t\t\"Claude Code request failed. Run /login anthropic to check setup and Claude Code version 2.1.263.\");\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t} finally {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (abortTimer) clearTimeout(abortTimer);\n\t\t\tif (child) {\n\t\t\t\tif (!complete || child.exitCode === null) await stopNativeOnce();\n\t\t\t\tif (child.exitCode === null) child.kill();\n\t\t\t}\n\t\t}\n\t})();\n\treturn stream;\n}\n"]}
|