@kenkaiiii/gg-ai 4.2.25 → 4.2.26
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/index.cjs +13 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +13 -3
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -452,10 +452,20 @@ async function runStream(options, result) {
|
|
|
452
452
|
const isOAuth = options.apiKey?.startsWith("sk-ant-oat");
|
|
453
453
|
const client = new import_sdk.default({
|
|
454
454
|
...isOAuth ? { apiKey: null, authToken: options.apiKey } : { apiKey: options.apiKey },
|
|
455
|
-
...options.baseUrl ? { baseURL: options.baseUrl } : {}
|
|
455
|
+
...options.baseUrl ? { baseURL: options.baseUrl } : {},
|
|
456
|
+
...isOAuth ? {
|
|
457
|
+
defaultHeaders: {
|
|
458
|
+
"user-agent": "claude-cli/2.1.75",
|
|
459
|
+
"x-app": "cli"
|
|
460
|
+
}
|
|
461
|
+
} : {}
|
|
456
462
|
});
|
|
457
463
|
const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);
|
|
458
|
-
const { system, messages } = toAnthropicMessages(options.messages, cacheControl);
|
|
464
|
+
const { system: rawSystem, messages } = toAnthropicMessages(options.messages, cacheControl);
|
|
465
|
+
const system = isOAuth ? [
|
|
466
|
+
{ type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude." },
|
|
467
|
+
...rawSystem ?? []
|
|
468
|
+
] : rawSystem;
|
|
459
469
|
let maxTokens = options.maxTokens ?? 4096;
|
|
460
470
|
let thinking;
|
|
461
471
|
let outputConfig;
|
|
@@ -489,7 +499,7 @@ async function runStream(options, result) {
|
|
|
489
499
|
stream: true
|
|
490
500
|
};
|
|
491
501
|
const betaHeaders = [
|
|
492
|
-
...isOAuth ? ["oauth-2025-04-20"] : [],
|
|
502
|
+
...isOAuth ? ["claude-code-20250219", "oauth-2025-04-20"] : [],
|
|
493
503
|
...options.compaction ? ["compact-2026-01-12"] : []
|
|
494
504
|
];
|
|
495
505
|
const stream2 = client.messages.stream(params, {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/providers/anthropic.ts","../src/utils/event-stream.ts","../src/utils/zod-to-json-schema.ts","../src/providers/transform.ts","../src/providers/openai.ts","../src/providers/openai-codex.ts","../src/stream.ts"],"sourcesContent":["// Core entry point\nexport { stream } from \"./stream.js\";\n\n// Types\nexport type {\n Provider,\n ThinkingLevel,\n CacheRetention,\n TextContent,\n ThinkingContent,\n ImageContent,\n ToolCall,\n ToolResult,\n ServerToolCall,\n ServerToolResult,\n ServerToolDefinition,\n RawContent,\n ContentPart,\n SystemMessage,\n UserMessage,\n AssistantMessage,\n ToolResultMessage,\n Message,\n Tool,\n ToolChoice,\n TextDeltaEvent,\n ThinkingDeltaEvent,\n ToolCallDeltaEvent,\n ToolCallDoneEvent,\n ServerToolCallEvent,\n ServerToolResultEvent,\n DoneEvent,\n ErrorEvent,\n StreamEvent,\n StopReason,\n StreamResponse,\n Usage,\n StreamOptions,\n} from \"./types.js\";\n\n// Classes\nexport { StreamResult, EventStream } from \"./utils/event-stream.js\";\nexport { GGAIError, ProviderError } from \"./errors.js\";\n","export class GGAIError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"GGAIError\";\n }\n}\n\nexport class ProviderError extends GGAIError {\n readonly provider: string;\n readonly statusCode?: number;\n\n constructor(\n provider: string,\n message: string,\n options?: { statusCode?: number; cause?: unknown },\n ) {\n super(`[${provider}] ${message}`, { cause: options?.cause });\n this.name = \"ProviderError\";\n this.provider = provider;\n this.statusCode = options?.statusCode;\n }\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ContentPart,\n ServerToolCall,\n ServerToolResult,\n StreamOptions,\n StreamResponse,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeAnthropicStopReason,\n toAnthropicCacheControl,\n toAnthropicMessages,\n toAnthropicThinking,\n toAnthropicToolChoice,\n toAnthropicTools,\n} from \"./transform.js\";\n\nexport function streamAnthropic(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const isOAuth = options.apiKey?.startsWith(\"sk-ant-oat\");\n\n const client = new Anthropic({\n ...(isOAuth\n ? { apiKey: null as unknown as string, authToken: options.apiKey }\n : { apiKey: options.apiKey }),\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n });\n\n const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);\n const { system, messages } = toAnthropicMessages(options.messages, cacheControl);\n\n let maxTokens = options.maxTokens ?? 4096;\n let thinking: Anthropic.ThinkingConfigParam | undefined;\n let outputConfig: Record<string, unknown> | undefined;\n\n if (options.thinking) {\n const t = toAnthropicThinking(options.thinking, maxTokens, options.model);\n thinking = t.thinking;\n maxTokens = t.maxTokens;\n if (t.outputConfig) {\n outputConfig = t.outputConfig;\n }\n }\n\n const params: Anthropic.MessageCreateParams = {\n model: options.model,\n max_tokens: maxTokens,\n messages,\n ...(system ? { system: system as Anthropic.MessageCreateParams[\"system\"] } : {}),\n ...(thinking ? { thinking } : {}),\n ...(outputConfig\n ? { output_config: outputConfig as unknown as Anthropic.MessageCreateParams[\"output_config\"] }\n : {}),\n ...(options.temperature != null && !thinking ? { temperature: options.temperature } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop_sequences: options.stop } : {}),\n ...(options.tools?.length || options.serverTools?.length || options.webSearch\n ? {\n tools: [\n ...(options.tools?.length ? toAnthropicTools(options.tools) : []),\n ...(options.serverTools ?? []),\n ...(options.webSearch ? [{ type: \"web_search_20250305\", name: \"web_search\" }] : []),\n ] as Anthropic.MessageCreateParams[\"tools\"],\n }\n : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toAnthropicToolChoice(options.toolChoice) }\n : {}),\n ...(options.compaction\n ? { context_management: { edits: [{ type: \"compact_20260112\" }] } }\n : {}),\n stream: true,\n } as Anthropic.MessageCreateParams;\n\n const betaHeaders = [\n ...(isOAuth ? [\"oauth-2025-04-20\"] : []),\n ...(options.compaction ? [\"compact-2026-01-12\"] : []),\n ];\n\n const stream = client.messages.stream(params, {\n signal: options.signal ?? undefined,\n ...(betaHeaders.length ? { headers: { \"anthropic-beta\": betaHeaders.join(\",\") } } : {}),\n });\n\n const contentParts: ContentPart[] = [];\n // Track the current tool call being streamed (by content block index)\n let currentToolId = \"\";\n let currentToolName = \"\";\n\n stream.on(\"text\", (text) => {\n result.push({ type: \"text_delta\", text });\n });\n\n stream.on(\"thinking\", (thinkingDelta) => {\n result.push({ type: \"thinking_delta\", text: thinkingDelta });\n });\n\n stream.on(\"streamEvent\", (event) => {\n if (event.type === \"content_block_start\") {\n // When a new tool_use content block starts, capture its id and name\n if (event.content_block.type === \"tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n // Track server_tool_use blocks\n if (event.content_block.type === \"server_tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n }\n });\n\n stream.on(\"inputJson\", (delta) => {\n result.push({\n type: \"toolcall_delta\",\n id: currentToolId,\n name: currentToolName,\n argsJson: delta,\n });\n });\n\n stream.on(\"contentBlock\", (block) => {\n if (block.type === \"text\") {\n contentParts.push({ type: \"text\", text: block.text });\n } else if (block.type === \"thinking\") {\n contentParts.push({ type: \"thinking\", text: block.thinking, signature: block.signature });\n } else if (block.type === \"tool_use\") {\n const tc: ToolCall = {\n type: \"tool_call\",\n id: block.id,\n name: block.name,\n args: block.input as Record<string, unknown>,\n };\n contentParts.push(tc);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args: tc.args,\n });\n } else if (block.type === \"server_tool_use\") {\n const stc: ServerToolCall = {\n type: \"server_tool_call\",\n id: block.id,\n name: block.name,\n input: block.input,\n };\n contentParts.push(stc);\n result.push({\n type: \"server_toolcall\",\n id: stc.id,\n name: stc.name,\n input: stc.input,\n });\n } else {\n const raw = block as unknown as Record<string, unknown>;\n const blockType = raw.type as string;\n if (blockType === \"web_search_tool_result\") {\n // Server tool result blocks\n const str: ServerToolResult = {\n type: \"server_tool_result\",\n toolUseId: raw.tool_use_id as string,\n resultType: blockType,\n data: raw,\n };\n contentParts.push(str);\n result.push({\n type: \"server_toolresult\",\n toolUseId: str.toolUseId,\n resultType: str.resultType,\n data: str.data,\n });\n } else {\n // Preserve unknown blocks (e.g. compaction) for round-tripping\n contentParts.push({ type: \"raw\", data: raw });\n }\n }\n });\n\n try {\n const finalMessage = await stream.finalMessage();\n const stopReason = normalizeAnthropicStopReason(finalMessage.stop_reason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : \"\",\n },\n stopReason,\n usage: {\n inputTokens: finalMessage.usage.input_tokens,\n outputTokens: finalMessage.usage.output_tokens,\n ...((finalMessage.usage as unknown as Record<string, unknown>).cache_read_input_tokens !=\n null && {\n cacheRead: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_read_input_tokens as number,\n }),\n ...((finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens != null && {\n cacheWrite: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens as number,\n }),\n },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n } catch (err) {\n const error = toError(err);\n result.push({ type: \"error\", error });\n result.abort(error);\n }\n}\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof Anthropic.APIError) {\n return new ProviderError(\"anthropic\", err.message, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(\"anthropic\", err.message, { cause: err });\n }\n return new ProviderError(\"anthropic\", String(err));\n}\n","import type { StreamEvent, StreamResponse } from \"../types.js\";\n\n/**\n * Push-based async iterable. Producers push events, consumers\n * iterate with `for await`. Also supports thenable so you can\n * `await stream(...)` directly to get the final response.\n */\nexport class EventStream<T = StreamEvent> implements AsyncIterable<T> {\n private queue: T[] = [];\n private resolve: (() => void) | null = null;\n private done = false;\n private error: Error | null = null;\n\n push(event: T): void {\n // Safety valve: if queue grows beyond 10k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 10_000) {\n this.queue.splice(0, this.queue.length - 5_000);\n }\n this.queue.push(event);\n this.resolve?.();\n this.resolve = null;\n }\n\n close(): void {\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n abort(error: Error): void {\n this.error = error;\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n let index = 0;\n while (true) {\n while (index < this.queue.length) {\n yield this.queue[index++]!;\n }\n // Reset to avoid holding references to already-yielded events\n this.queue.splice(0, index);\n index = 0;\n if (this.error) throw this.error;\n if (this.done) return;\n await new Promise<void>((r) => {\n this.resolve = r;\n });\n }\n }\n}\n\n/**\n * Wraps EventStream and adds a `.response` promise that resolves\n * to the final StreamResponse. Also implements thenable so:\n *\n * const msg = await stream({...}) // awaits response\n * for await (const e of stream({...})) {} // iterates events\n */\nexport class StreamResult implements AsyncIterable<StreamEvent> {\n readonly events: EventStream<StreamEvent>;\n readonly response: Promise<StreamResponse>;\n private resolveResponse!: (r: StreamResponse) => void;\n private rejectResponse!: (e: Error) => void;\n private hasConsumer = false;\n\n constructor() {\n this.events = new EventStream<StreamEvent>();\n this.response = new Promise<StreamResponse>((resolve, reject) => {\n this.resolveResponse = resolve;\n this.rejectResponse = reject;\n });\n }\n\n push(event: StreamEvent): void {\n this.events.push(event);\n }\n\n complete(response: StreamResponse): void {\n this.events.close();\n this.resolveResponse(response);\n }\n\n abort(error: Error): void {\n this.events.abort(error);\n this.rejectResponse(error);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n this.hasConsumer = true;\n return this.events[Symbol.asyncIterator]();\n }\n\n then<TResult1 = StreamResponse, TResult2 = never>(\n onfulfilled?: ((value: StreamResponse) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n // Drain events so the stream completes\n this.drainEvents().catch(() => {});\n return this.response.then(onfulfilled, onrejected);\n }\n\n private async drainEvents(): Promise<void> {\n if (this.hasConsumer) return;\n this.hasConsumer = true;\n for await (const _ of this.events) {\n // consume silently\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Converts a Zod schema to a JSON Schema object suitable for\n * provider tool parameter definitions.\n */\nexport function zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n const jsonSchema = z.toJSONSchema(schema);\n // Remove $schema and other meta keys providers don't want\n const { $schema: _schema, ...rest } = jsonSchema as Record<string, unknown>;\n return rest;\n}\n","import type Anthropic from \"@anthropic-ai/sdk\";\nimport type OpenAI from \"openai\";\nimport type {\n CacheRetention,\n ContentPart,\n Message,\n StopReason,\n TextContent,\n ThinkingContent,\n ThinkingLevel,\n Tool,\n ToolChoice,\n} from \"../types.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\n// ── Anthropic Transforms ───────────────────────────────────\n\nexport function toAnthropicCacheControl(\n retention: CacheRetention | undefined,\n baseUrl: string | undefined,\n): { type: \"ephemeral\"; ttl?: \"1h\" } | undefined {\n const resolved = retention ?? \"short\";\n if (resolved === \"none\") return undefined;\n const ttl =\n resolved === \"long\" && (!baseUrl || baseUrl.includes(\"api.anthropic.com\")) ? \"1h\" : undefined;\n return { type: \"ephemeral\", ...(ttl && { ttl }) } as { type: \"ephemeral\"; ttl?: \"1h\" };\n}\n\nexport function toAnthropicMessages(\n messages: Message[],\n cacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" },\n): {\n system: Anthropic.TextBlockParam[] | undefined;\n messages: Anthropic.MessageParam[];\n} {\n let systemText: string | undefined;\n const out: Anthropic.MessageParam[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n systemText = msg.content;\n continue;\n }\n if (msg.role === \"user\") {\n out.push({\n role: \"user\",\n content:\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"text\" as const, text: part.text };\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: part.mediaType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data: part.data,\n },\n };\n }),\n });\n continue;\n }\n if (msg.role === \"assistant\") {\n const content =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((part) => {\n // Strip thinking blocks without a valid signature (e.g. from GLM/OpenAI)\n // — Anthropic rejects empty signatures\n if (part.type === \"thinking\" && !part.signature) return false;\n return true;\n })\n .map((part): Anthropic.ContentBlockParam => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"thinking\")\n return { type: \"thinking\", thinking: part.text, signature: part.signature! };\n if (part.type === \"tool_call\")\n return {\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: part.args,\n };\n if (part.type === \"server_tool_call\")\n return {\n type: \"server_tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n } as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"server_tool_result\")\n return part.data as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"raw\") return part.data as unknown as Anthropic.ContentBlockParam;\n // image content shouldn't appear in assistant messages\n return { type: \"text\", text: \"\" };\n });\n out.push({ role: \"assistant\", content });\n continue;\n }\n if (msg.role === \"tool\") {\n out.push({\n role: \"user\",\n content: msg.content.map((result) => ({\n type: \"tool_result\" as const,\n tool_use_id: result.toolCallId,\n content: result.content,\n is_error: result.isError,\n })),\n });\n }\n }\n\n // Add cache_control to the last user message to cache conversation history\n if (cacheControl && out.length > 0) {\n for (let i = out.length - 1; i >= 0; i--) {\n if (out[i].role === \"user\") {\n const content = out[i].content;\n if (typeof content === \"string\") {\n out[i] = {\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: content,\n cache_control: cacheControl,\n } as Anthropic.TextBlockParam,\n ],\n };\n } else if (Array.isArray(content) && content.length > 0) {\n const last = content[content.length - 1];\n content[content.length - 1] = {\n ...last,\n cache_control: cacheControl,\n } as (typeof content)[number];\n }\n break;\n }\n }\n }\n\n // Build system as block array (supports cache_control).\n // Split on \"<!-- uncached -->\" marker: text before is cached, text after is not.\n let system: Anthropic.TextBlockParam[] | undefined;\n if (systemText) {\n const marker = \"<!-- uncached -->\";\n const markerIdx = systemText.indexOf(marker);\n if (markerIdx !== -1 && cacheControl) {\n const cachedPart = systemText.slice(0, markerIdx).trimEnd();\n const uncachedPart = systemText.slice(markerIdx + marker.length).trimStart();\n system = [\n { type: \"text\" as const, text: cachedPart, cache_control: cacheControl },\n ...(uncachedPart ? [{ type: \"text\" as const, text: uncachedPart }] : []),\n ];\n } else {\n system = [\n {\n type: \"text\" as const,\n text: systemText,\n ...(cacheControl && { cache_control: cacheControl }),\n },\n ];\n }\n }\n\n return { system, messages: out };\n}\n\nexport function toAnthropicTools(tools: Tool[]): Anthropic.Tool[] {\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: (tool.rawInputSchema ??\n zodToJsonSchema(tool.parameters)) as Anthropic.Tool[\"input_schema\"],\n }));\n}\n\nexport function toAnthropicToolChoice(choice: ToolChoice): Anthropic.ToolChoice {\n if (choice === \"auto\") return { type: \"auto\" };\n if (choice === \"none\") return { type: \"none\" };\n if (choice === \"required\") return { type: \"any\" };\n return { type: \"tool\", name: choice.name };\n}\n\nfunction supportsAdaptiveThinking(model: string): boolean {\n return /opus-4-6|sonnet-4-6/.test(model);\n}\n\nexport function toAnthropicThinking(\n level: ThinkingLevel,\n maxTokens: number,\n model: string,\n): {\n thinking: Anthropic.ThinkingConfigParam;\n maxTokens: number;\n outputConfig?: { effort: string };\n} {\n if (supportsAdaptiveThinking(model)) {\n // Adaptive thinking — model decides when/how much to think.\n // budget_tokens is deprecated on Opus 4.6 / Sonnet 4.6.\n // \"max\" effort is Opus-only; downgrade to \"high\" for Sonnet\n let effort: string = level;\n if (level === \"max\" && !model.includes(\"opus\")) {\n effort = \"high\";\n }\n return {\n thinking: { type: \"adaptive\" } as unknown as Anthropic.ThinkingConfigParam,\n maxTokens,\n outputConfig: { effort },\n };\n }\n\n // Legacy budget-based thinking for older models (\"max\" treated as \"high\")\n const effectiveLevel = level === \"max\" ? \"high\" : level;\n const budgetMap: Record<\"low\" | \"medium\" | \"high\", number> = {\n low: Math.max(1024, Math.floor(maxTokens * 0.25)),\n medium: Math.max(2048, Math.floor(maxTokens * 0.5)),\n high: Math.max(4096, maxTokens),\n };\n const budget = budgetMap[effectiveLevel];\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n maxTokens: maxTokens + budget,\n };\n}\n\n// ── OpenAI Transforms ──────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match OpenAI's expected prefix.\n * Anthropic uses `toolu_*` IDs which OpenAI rejects — we need `call_*` prefixed IDs.\n * The mapping is consistent within a single conversion so assistant tool_call IDs\n * match their corresponding tool result references.\n */\nfunction remapToolCallId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"call_\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `call_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nexport function toOpenAIMessages(\n messages: Message[],\n options?: { provider?: string },\n): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\n const idMap = new Map<string, string>();\n // GLM drops reasoning_content when a user message follows tool results.\n // Merge user text into the last tool message to preserve thinking context.\n const mergeToolResultText = options?.provider === \"glm\";\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n out.push({ role: \"system\", content: msg.content });\n continue;\n }\n if (msg.role === \"user\") {\n // For GLM: if the previous message is a tool result, merge text into it\n // to avoid a standalone user message that causes reasoning_content to be dropped.\n if (mergeToolResultText && out.length > 0 && out[out.length - 1]!.role === \"tool\") {\n const userText =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\");\n if (userText) {\n // Append text to the last tool message's content\n const lastTool = out[out.length - 1] as OpenAI.ChatCompletionToolMessageParam;\n lastTool.content = (lastTool.content ?? \"\") + \"\\n\\n\" + userText;\n continue;\n }\n }\n if (typeof msg.content === \"string\") {\n out.push({ role: \"user\", content: msg.content });\n } else {\n out.push({\n role: \"user\",\n content: msg.content.map(\n (\n part,\n ): OpenAI.ChatCompletionContentPartImage | OpenAI.ChatCompletionContentPartText => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${part.mediaType};base64,${part.data}`,\n },\n };\n },\n ),\n });\n }\n continue;\n }\n if (msg.role === \"assistant\") {\n const parts = typeof msg.content === \"string\" ? msg.content : undefined;\n const toolCalls =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter(\n (p): p is Extract<ContentPart, { type: \"tool_call\" }> => p.type === \"tool_call\",\n )\n .map(\n (tc): OpenAI.ChatCompletionMessageToolCall => ({\n id: remapToolCallId(tc.id, idMap),\n type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.args) },\n }),\n )\n : undefined;\n const textParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n // Roundtrip thinking content as reasoning_content (GLM, Moonshot)\n const thinkingParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is ThinkingContent => p.type === \"thinking\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n\n const assistantMsg: OpenAI.ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content: parts || textParts || null,\n ...(toolCalls?.length ? { tool_calls: toolCalls } : {}),\n };\n // Attach reasoning_content for multi-turn coherence (non-standard field).\n // Moonshot requires reasoning_content on ALL assistant messages with tool_calls\n // when thinking is enabled — even if empty.\n if (thinkingParts || toolCalls?.length) {\n (assistantMsg as unknown as Record<string, unknown>).reasoning_content =\n thinkingParts || \" \";\n }\n out.push(assistantMsg);\n continue;\n }\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n out.push({\n role: \"tool\",\n tool_call_id: remapToolCallId(result.toolCallId, idMap),\n content: result.content,\n });\n }\n }\n }\n\n return out;\n}\n\nexport function toOpenAITools(tools: Tool[]): OpenAI.ChatCompletionTool[] {\n return tools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n },\n }));\n}\n\nexport function toOpenAIToolChoice(choice: ToolChoice): OpenAI.ChatCompletionToolChoiceOption {\n if (choice === \"auto\") return \"auto\";\n if (choice === \"none\") return \"none\";\n if (choice === \"required\") return \"required\";\n return { type: \"function\", function: { name: choice.name } };\n}\n\nexport function toOpenAIReasoningEffort(level: ThinkingLevel): \"low\" | \"medium\" | \"high\" {\n return level === \"max\" ? \"high\" : level;\n}\n\n// ── Response Normalization ─────────────────────────────────\n\nexport function normalizeAnthropicStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"max_tokens\";\n case \"pause_turn\":\n return \"pause_turn\";\n case \"stop_sequence\":\n return \"stop_sequence\";\n case \"refusal\":\n return \"refusal\";\n default:\n return \"end_turn\";\n }\n}\n\nexport function normalizeOpenAIStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_calls\":\n return \"tool_use\";\n case \"length\":\n return \"max_tokens\";\n case \"stop\":\n return \"stop_sequence\";\n default:\n return \"end_turn\";\n }\n}\n","import OpenAI from \"openai\";\nimport type { ContentPart, StreamOptions, StreamResponse, ToolCall } from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeOpenAIStopReason,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAIToolChoice,\n toOpenAITools,\n} from \"./transform.js\";\n\nexport function streamOpenAI(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n const providerName = options.provider ?? \"openai\";\n runStream(options, result).catch((err) => result.abort(toError(err, providerName)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const client = new OpenAI({\n apiKey: options.apiKey,\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n });\n\n // GLM and Moonshot use a custom `thinking` body param instead of `reasoning_effort`\n const usesThinkingParam = options.provider === \"glm\" || options.provider === \"moonshot\";\n\n const messages = toOpenAIMessages(options.messages, { provider: options.provider });\n\n // GLM models default to 0.6 temperature when not in thinking mode\n const defaultTemp = options.provider === \"glm\" ? 0.6 : undefined;\n const effectiveTemp = options.temperature ?? defaultTemp;\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(effectiveTemp != null && !options.thinking ? { temperature: effectiveTemp } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop: options.stop } : {}),\n ...(options.thinking && !usesThinkingParam\n ? { reasoning_effort: toOpenAIReasoningEffort(options.thinking) }\n : {}),\n ...(options.tools?.length ? { tools: toOpenAITools(options.tools) } : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toOpenAIToolChoice(options.toolChoice) }\n : {}),\n stream_options: { include_usage: true },\n };\n\n // Inject provider-native web search tools (non-standard, bypass SDK types)\n if (options.webSearch) {\n if (options.provider === \"moonshot\") {\n const raw = params as unknown as Record<string, unknown>;\n const tools = ((raw.tools as unknown[]) ?? []).slice();\n tools.push({ type: \"builtin_function\", function: { name: \"$web_search\" } });\n raw.tools = tools;\n }\n // GLM (Z.AI): web search is provided via MCP servers, not inline tools\n // OpenAI: Chat Completions API does not support web search\n }\n\n // Inject custom thinking param for GLM/Moonshot (not part of OpenAI spec)\n if (usesThinkingParam) {\n (params as unknown as Record<string, unknown>).thinking = options.thinking\n ? { type: \"enabled\" }\n : { type: \"disabled\" };\n }\n\n const stream = await client.chat.completions.create(params, {\n signal: options.signal ?? undefined,\n });\n\n const contentParts: ContentPart[] = [];\n const toolCallAccum = new Map<number, { id: string; name: string; argsJson: string }>();\n let textAccum = \"\";\n let thinkingAccum = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n let cacheRead = 0;\n let finishReason: string | null = null;\n\n for await (const chunk of stream as AsyncIterable<OpenAI.ChatCompletionChunk>) {\n const choice = chunk.choices?.[0];\n\n if (chunk.usage) {\n inputTokens = chunk.usage.prompt_tokens;\n outputTokens = chunk.usage.completion_tokens;\n const details = chunk.usage.prompt_tokens_details;\n if (details?.cached_tokens) {\n cacheRead = details.cached_tokens;\n }\n }\n\n if (!choice) continue;\n\n if (choice.finish_reason) {\n finishReason = choice.finish_reason;\n }\n\n const delta = choice.delta;\n\n // Reasoning/thinking delta (GLM, Moonshot)\n const reasoningContent = (delta as Record<string, unknown>).reasoning_content;\n if (typeof reasoningContent === \"string\" && reasoningContent) {\n thinkingAccum += reasoningContent;\n result.push({ type: \"thinking_delta\", text: reasoningContent });\n }\n\n // Text delta\n if (delta.content) {\n textAccum += delta.content;\n result.push({ type: \"text_delta\", text: delta.content });\n }\n\n // Tool call deltas\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n let accum = toolCallAccum.get(tc.index);\n if (!accum) {\n accum = {\n id: tc.id ?? \"\",\n name: tc.function?.name ?? \"\",\n argsJson: \"\",\n };\n toolCallAccum.set(tc.index, accum);\n }\n if (tc.id) accum.id = tc.id;\n if (tc.function?.name) accum.name = tc.function.name;\n if (tc.function?.arguments) {\n accum.argsJson += tc.function.arguments;\n result.push({\n type: \"toolcall_delta\",\n id: accum.id,\n name: accum.name,\n argsJson: tc.function.arguments,\n });\n }\n }\n }\n }\n\n // Finalize thinking content (GLM, Moonshot reasoning_content)\n if (thinkingAccum) {\n contentParts.push({ type: \"thinking\", text: thinkingAccum });\n }\n\n // Finalize text content\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n // Finalize tool calls\n for (const [, tc] of toolCallAccum) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n // malformed JSON — keep empty\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n\n const stopReason = normalizeOpenAIStopReason(finishReason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens, ...(cacheRead > 0 && { cacheRead }) },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n}\n\nfunction toError(err: unknown, provider: string = \"openai\"): ProviderError {\n if (err instanceof OpenAI.APIError) {\n // Include full error body for debugging — GLM/Moonshot use non-standard error shapes\n let msg = err.message;\n const body = err.error as Record<string, unknown> | undefined;\n if (body) {\n // Append raw error body so debug logs capture the exact API response\n msg += ` | body: ${JSON.stringify(body)}`;\n }\n return new ProviderError(provider, msg, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(provider, err.message, { cause: err });\n }\n return new ProviderError(provider, String(err));\n}\n","import os from \"node:os\";\nimport type {\n ContentPart,\n Message,\n StreamOptions,\n StreamResponse,\n Tool,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\nconst DEFAULT_BASE_URL = \"https://chatgpt.com/backend-api\";\n\nexport function streamOpenAICodex(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const url = `${baseUrl}/codex/responses`;\n\n const { system, input } = toCodexInput(options.messages);\n\n const body: Record<string, unknown> = {\n model: options.model,\n store: false,\n stream: true,\n instructions: system,\n input,\n tool_choice: \"auto\",\n parallel_tool_calls: true,\n include: [\"reasoning.encrypted_content\"],\n };\n\n if (options.tools?.length) {\n body.tools = toCodexTools(options.tools);\n }\n if (options.temperature != null && !options.thinking) {\n body.temperature = options.temperature;\n }\n if (options.thinking) {\n body.reasoning = {\n effort: options.thinking,\n summary: \"auto\",\n };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n Authorization: `Bearer ${options.apiKey}`,\n \"OpenAI-Beta\": \"responses=experimental\",\n originator: \"ggcoder\",\n \"User-Agent\": `ggcoder (${os.platform()} ${os.release()}; ${os.arch()})`,\n };\n\n if (options.accountId) {\n headers[\"chatgpt-account-id\"] = options.accountId;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let message = `Codex API error (${response.status}): ${text}`;\n\n // Add helpful context for common errors\n if (response.status === 400 && text.includes(\"not supported\")) {\n message +=\n `\\n\\nHint: Codex models require a ChatGPT Plus ($20/mo) or Pro ($200/mo) subscription. ` +\n `The \"codex-spark\" variants require ChatGPT Pro. ` +\n `Ensure your account has an active subscription at https://chatgpt.com/settings`;\n }\n\n throw new ProviderError(\"openai\", message, {\n statusCode: response.status,\n });\n }\n\n if (!response.body) {\n throw new ProviderError(\"openai\", \"No response body from Codex API\");\n }\n\n const contentParts: ContentPart[] = [];\n let textAccum = \"\";\n const toolCalls = new Map<string, { id: string; name: string; argsJson: string }>();\n let inputTokens = 0;\n let outputTokens = 0;\n\n for await (const event of parseSSE(response.body)) {\n const type = event.type as string | undefined;\n if (!type) continue;\n\n if (type === \"error\") {\n const msg = (event.message as string) || JSON.stringify(event);\n throw new ProviderError(\"openai\", `Codex error: ${msg}`);\n }\n\n if (type === \"response.failed\") {\n const msg =\n ((event.error as Record<string, unknown>)?.message as string) || \"Codex response failed\";\n throw new ProviderError(\"openai\", msg);\n }\n\n // Text delta\n if (type === \"response.output_text.delta\") {\n const delta = event.delta as string;\n textAccum += delta;\n result.push({ type: \"text_delta\", text: delta });\n }\n\n // Thinking delta\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = event.delta as string;\n result.push({ type: \"thinking_delta\", text: delta });\n }\n\n // Tool call started\n if (type === \"response.output_item.added\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const name = item.name as string;\n toolCalls.set(id, { id, name, argsJson: (item.arguments as string) || \"\" });\n }\n }\n\n // Tool call arguments delta\n if (type === \"response.function_call_arguments.delta\") {\n const delta = event.delta as string;\n const itemId = event.item_id as string;\n // Find the matching tool call\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson += delta;\n result.push({\n type: \"toolcall_delta\",\n id: tc.id,\n name: tc.name,\n argsJson: delta,\n });\n break;\n }\n }\n }\n\n // Tool call arguments done\n if (type === \"response.function_call_arguments.done\") {\n const itemId = event.item_id as string;\n const argsStr = event.arguments as string;\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson = argsStr;\n break;\n }\n }\n }\n\n // Item done — finalize tool call\n if (type === \"response.output_item.done\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const tc = toolCalls.get(id);\n if (tc) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n }\n }\n\n // Response completed\n if (type === \"response.completed\" || type === \"response.done\") {\n const resp = event.response as Record<string, unknown> | undefined;\n const usage = resp?.usage as Record<string, number> | undefined;\n if (usage) {\n inputTokens = usage.input_tokens ?? 0;\n outputTokens = usage.output_tokens ?? 0;\n }\n }\n }\n\n // Finalize content parts\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n for (const [, tc] of toolCalls) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n }\n\n const hasToolCalls = contentParts.some((p) => p.type === \"tool_call\");\n const stopReason = hasToolCalls ? \"tool_use\" : \"end_turn\";\n\n const streamResponse: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(streamResponse);\n}\n\n// ── SSE Parser ─────────────────────────────────────────────\n\nasync function* parseSSE(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<Record<string, unknown>> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let idx = buffer.indexOf(\"\\n\\n\");\n while (idx !== -1) {\n const chunk = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n\n const dataLines = chunk\n .split(\"\\n\")\n .filter((l) => l.startsWith(\"data:\"))\n .map((l) => l.slice(5).trim());\n\n if (dataLines.length > 0) {\n const data = dataLines.join(\"\\n\").trim();\n if (data && data !== \"[DONE]\") {\n try {\n yield JSON.parse(data) as Record<string, unknown>;\n } catch {\n // skip malformed JSON\n }\n }\n }\n idx = buffer.indexOf(\"\\n\\n\");\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n// ── Message Conversion ─────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match Codex API's expected prefix.\n * Codex expects IDs starting with `fc_` — Anthropic uses `toolu_*` which gets rejected.\n */\nfunction remapCodexId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"fc_\") || id.startsWith(\"fc-\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `fc_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nfunction toCodexInput(messages: Message[]): { system: string | undefined; input: unknown[] } {\n let system: string | undefined;\n const input: unknown[] = [];\n const idMap = new Map<string, string>();\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n system = msg.content;\n continue;\n }\n\n if (msg.role === \"user\") {\n const content =\n typeof msg.content === \"string\"\n ? [{ type: \"input_text\", text: msg.content }]\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"input_text\", text: part.text };\n return {\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${part.mediaType};base64,${part.data}`,\n };\n });\n input.push({ role: \"user\", content });\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (typeof msg.content === \"string\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: msg.content, annotations: [] }],\n status: \"completed\",\n });\n continue;\n }\n\n for (const part of msg.content) {\n if (part.type === \"text\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: part.text, annotations: [] }],\n status: \"completed\",\n });\n } else if (part.type === \"tool_call\") {\n const [callId, itemId] = part.id.includes(\"|\")\n ? part.id.split(\"|\", 2)\n : [part.id, part.id];\n input.push({\n type: \"function_call\",\n id: remapCodexId(itemId, idMap),\n call_id: remapCodexId(callId, idMap),\n name: part.name,\n arguments: JSON.stringify(part.args),\n });\n }\n // thinking parts are skipped for codex input\n }\n continue;\n }\n\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n const [callId] = result.toolCallId.includes(\"|\")\n ? result.toolCallId.split(\"|\", 2)\n : [result.toolCallId];\n input.push({\n type: \"function_call_output\",\n call_id: remapCodexId(callId, idMap),\n output: result.content,\n });\n }\n }\n }\n\n return { system, input };\n}\n\n// ── Tool Conversion ────────────────────────────────────────\n\nfunction toCodexTools(tools: Tool[]): unknown[] {\n return tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n strict: null,\n }));\n}\n\n// ── Error Handling ─────────────────────────────────────────\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof ProviderError) return err;\n if (err instanceof Error) {\n return new ProviderError(\"openai\", err.message, { cause: err });\n }\n return new ProviderError(\"openai\", String(err));\n}\n","import type { StreamOptions } from \"./types.js\";\nimport { GGAIError } from \"./errors.js\";\nimport type { StreamResult } from \"./utils/event-stream.js\";\nimport { streamAnthropic } from \"./providers/anthropic.js\";\nimport { streamOpenAI } from \"./providers/openai.js\";\nimport { streamOpenAICodex } from \"./providers/openai-codex.js\";\n\n/**\n * Unified streaming entry point. Returns a StreamResult that is both\n * an async iterable (for streaming events) and thenable (await for\n * the final response).\n *\n * ```ts\n * // Stream events\n * for await (const event of stream({ provider: \"anthropic\", model: \"claude-sonnet-4-6\", messages })) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text);\n * }\n *\n * // Or just await the final message\n * const response = await stream({ provider: \"openai\", model: \"gpt-4.1\", messages });\n * ```\n */\nexport function stream(options: StreamOptions): StreamResult {\n switch (options.provider) {\n case \"anthropic\":\n return streamAnthropic(options);\n case \"openai\":\n // Use codex endpoint for OAuth tokens (have accountId)\n if (options.accountId) {\n return streamOpenAICodex(options);\n }\n return streamOpenAI(options);\n case \"glm\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.z.ai/api/coding/paas/v4\",\n });\n case \"moonshot\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.moonshot.ai/v1\",\n });\n default:\n throw new GGAIError(\n `Unknown provider: ${options.provider as string}. Supported: \"anthropic\", \"openai\", \"glm\", \"moonshot\"`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gBAAN,cAA4B,UAAU;AAAA,EAClC;AAAA,EACA;AAAA,EAET,YACE,UACA,SACA,SACA;AACA,UAAM,IAAI,QAAQ,KAAK,OAAO,IAAI,EAAE,OAAO,SAAS,MAAM,CAAC;AAC3D,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,aAAa,SAAS;AAAA,EAC7B;AACF;;;ACrBA,iBAAsB;;;ACOf,IAAM,cAAN,MAA+D;AAAA,EAC5D,QAAa,CAAC;AAAA,EACd,UAA+B;AAAA,EAC/B,OAAO;AAAA,EACP,QAAsB;AAAA,EAE9B,KAAK,OAAgB;AAGnB,QAAI,KAAK,MAAM,SAAS,KAAQ;AAC9B,WAAK,MAAM,OAAO,GAAG,KAAK,MAAM,SAAS,GAAK;AAAA,IAChD;AACA,SAAK,MAAM,KAAK,KAAK;AACrB,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,QAAc;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,OAAoB;AACxB,SAAK,QAAQ;AACb,SAAK,OAA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XO,SAAS,OAAO,SAAsC;AAC3D,UAAQ,QAAQ,UAAU;AAAA,IACxB,KAAK;AACH,aAAO,gBAAgB,OAAO;AAAA,IAChC,KAAK;AAEH,UAAI,QAAQ,WAAW;AACrB,eAAO,kBAAkB,OAAO;AAAA,MAClC;AACA,aAAO,aAAa,OAAO;AAAA,IAC7B,KAAK;AACH,aAAO,aAAa;AAAA,QAClB,GAAG;AAAA,QACH,SAAS,QAAQ,WAAW;AAAA,MAC9B,CAAC;AAAA,IACH,KAAK;AACH,aAAO,aAAa;AAAA,QAClB,GAAG;AAAA,QACH,SAAS,QAAQ,WAAW;AAAA,MAC9B,CAAC;AAAA,IACH;AACE,YAAM,IAAI;AAAA,QACR,qBAAqB,QAAQ,QAAkB;AAAA,MACjD;AAAA,EACJ;AACF;","names":["Anthropic","stream","runStream","toError","OpenAI","stream","runStream","toError","os"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/providers/anthropic.ts","../src/utils/event-stream.ts","../src/utils/zod-to-json-schema.ts","../src/providers/transform.ts","../src/providers/openai.ts","../src/providers/openai-codex.ts","../src/stream.ts"],"sourcesContent":["// Core entry point\nexport { stream } from \"./stream.js\";\n\n// Types\nexport type {\n Provider,\n ThinkingLevel,\n CacheRetention,\n TextContent,\n ThinkingContent,\n ImageContent,\n ToolCall,\n ToolResult,\n ServerToolCall,\n ServerToolResult,\n ServerToolDefinition,\n RawContent,\n ContentPart,\n SystemMessage,\n UserMessage,\n AssistantMessage,\n ToolResultMessage,\n Message,\n Tool,\n ToolChoice,\n TextDeltaEvent,\n ThinkingDeltaEvent,\n ToolCallDeltaEvent,\n ToolCallDoneEvent,\n ServerToolCallEvent,\n ServerToolResultEvent,\n DoneEvent,\n ErrorEvent,\n StreamEvent,\n StopReason,\n StreamResponse,\n Usage,\n StreamOptions,\n} from \"./types.js\";\n\n// Classes\nexport { StreamResult, EventStream } from \"./utils/event-stream.js\";\nexport { GGAIError, ProviderError } from \"./errors.js\";\n","export class GGAIError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"GGAIError\";\n }\n}\n\nexport class ProviderError extends GGAIError {\n readonly provider: string;\n readonly statusCode?: number;\n\n constructor(\n provider: string,\n message: string,\n options?: { statusCode?: number; cause?: unknown },\n ) {\n super(`[${provider}] ${message}`, { cause: options?.cause });\n this.name = \"ProviderError\";\n this.provider = provider;\n this.statusCode = options?.statusCode;\n }\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ContentPart,\n ServerToolCall,\n ServerToolResult,\n StreamOptions,\n StreamResponse,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeAnthropicStopReason,\n toAnthropicCacheControl,\n toAnthropicMessages,\n toAnthropicThinking,\n toAnthropicToolChoice,\n toAnthropicTools,\n} from \"./transform.js\";\n\nexport function streamAnthropic(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const isOAuth = options.apiKey?.startsWith(\"sk-ant-oat\");\n\n const client = new Anthropic({\n ...(isOAuth\n ? { apiKey: null as unknown as string, authToken: options.apiKey }\n : { apiKey: options.apiKey }),\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n ...(isOAuth\n ? {\n defaultHeaders: {\n \"user-agent\": \"claude-cli/2.1.75\",\n \"x-app\": \"cli\",\n },\n }\n : {}),\n });\n\n const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);\n const { system: rawSystem, messages } = toAnthropicMessages(options.messages, cacheControl);\n\n // OAuth tokens require Claude Code identity in the system prompt\n const system = isOAuth\n ? [\n { type: \"text\" as const, text: \"You are Claude Code, Anthropic's official CLI for Claude.\" },\n ...(rawSystem ?? []),\n ]\n : rawSystem;\n\n let maxTokens = options.maxTokens ?? 4096;\n let thinking: Anthropic.ThinkingConfigParam | undefined;\n let outputConfig: Record<string, unknown> | undefined;\n\n if (options.thinking) {\n const t = toAnthropicThinking(options.thinking, maxTokens, options.model);\n thinking = t.thinking;\n maxTokens = t.maxTokens;\n if (t.outputConfig) {\n outputConfig = t.outputConfig;\n }\n }\n\n const params: Anthropic.MessageCreateParams = {\n model: options.model,\n max_tokens: maxTokens,\n messages,\n ...(system ? { system: system as Anthropic.MessageCreateParams[\"system\"] } : {}),\n ...(thinking ? { thinking } : {}),\n ...(outputConfig\n ? { output_config: outputConfig as unknown as Anthropic.MessageCreateParams[\"output_config\"] }\n : {}),\n ...(options.temperature != null && !thinking ? { temperature: options.temperature } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop_sequences: options.stop } : {}),\n ...(options.tools?.length || options.serverTools?.length || options.webSearch\n ? {\n tools: [\n ...(options.tools?.length ? toAnthropicTools(options.tools) : []),\n ...(options.serverTools ?? []),\n ...(options.webSearch ? [{ type: \"web_search_20250305\", name: \"web_search\" }] : []),\n ] as Anthropic.MessageCreateParams[\"tools\"],\n }\n : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toAnthropicToolChoice(options.toolChoice) }\n : {}),\n ...(options.compaction\n ? { context_management: { edits: [{ type: \"compact_20260112\" }] } }\n : {}),\n stream: true,\n } as Anthropic.MessageCreateParams;\n\n const betaHeaders = [\n ...(isOAuth ? [\"claude-code-20250219\", \"oauth-2025-04-20\"] : []),\n ...(options.compaction ? [\"compact-2026-01-12\"] : []),\n ];\n\n const stream = client.messages.stream(params, {\n signal: options.signal ?? undefined,\n ...(betaHeaders.length ? { headers: { \"anthropic-beta\": betaHeaders.join(\",\") } } : {}),\n });\n\n const contentParts: ContentPart[] = [];\n // Track the current tool call being streamed (by content block index)\n let currentToolId = \"\";\n let currentToolName = \"\";\n\n stream.on(\"text\", (text) => {\n result.push({ type: \"text_delta\", text });\n });\n\n stream.on(\"thinking\", (thinkingDelta) => {\n result.push({ type: \"thinking_delta\", text: thinkingDelta });\n });\n\n stream.on(\"streamEvent\", (event) => {\n if (event.type === \"content_block_start\") {\n // When a new tool_use content block starts, capture its id and name\n if (event.content_block.type === \"tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n // Track server_tool_use blocks\n if (event.content_block.type === \"server_tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n }\n });\n\n stream.on(\"inputJson\", (delta) => {\n result.push({\n type: \"toolcall_delta\",\n id: currentToolId,\n name: currentToolName,\n argsJson: delta,\n });\n });\n\n stream.on(\"contentBlock\", (block) => {\n if (block.type === \"text\") {\n contentParts.push({ type: \"text\", text: block.text });\n } else if (block.type === \"thinking\") {\n contentParts.push({ type: \"thinking\", text: block.thinking, signature: block.signature });\n } else if (block.type === \"tool_use\") {\n const tc: ToolCall = {\n type: \"tool_call\",\n id: block.id,\n name: block.name,\n args: block.input as Record<string, unknown>,\n };\n contentParts.push(tc);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args: tc.args,\n });\n } else if (block.type === \"server_tool_use\") {\n const stc: ServerToolCall = {\n type: \"server_tool_call\",\n id: block.id,\n name: block.name,\n input: block.input,\n };\n contentParts.push(stc);\n result.push({\n type: \"server_toolcall\",\n id: stc.id,\n name: stc.name,\n input: stc.input,\n });\n } else {\n const raw = block as unknown as Record<string, unknown>;\n const blockType = raw.type as string;\n if (blockType === \"web_search_tool_result\") {\n // Server tool result blocks\n const str: ServerToolResult = {\n type: \"server_tool_result\",\n toolUseId: raw.tool_use_id as string,\n resultType: blockType,\n data: raw,\n };\n contentParts.push(str);\n result.push({\n type: \"server_toolresult\",\n toolUseId: str.toolUseId,\n resultType: str.resultType,\n data: str.data,\n });\n } else {\n // Preserve unknown blocks (e.g. compaction) for round-tripping\n contentParts.push({ type: \"raw\", data: raw });\n }\n }\n });\n\n try {\n const finalMessage = await stream.finalMessage();\n const stopReason = normalizeAnthropicStopReason(finalMessage.stop_reason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : \"\",\n },\n stopReason,\n usage: {\n inputTokens: finalMessage.usage.input_tokens,\n outputTokens: finalMessage.usage.output_tokens,\n ...((finalMessage.usage as unknown as Record<string, unknown>).cache_read_input_tokens !=\n null && {\n cacheRead: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_read_input_tokens as number,\n }),\n ...((finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens != null && {\n cacheWrite: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens as number,\n }),\n },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n } catch (err) {\n const error = toError(err);\n result.push({ type: \"error\", error });\n result.abort(error);\n }\n}\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof Anthropic.APIError) {\n return new ProviderError(\"anthropic\", err.message, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(\"anthropic\", err.message, { cause: err });\n }\n return new ProviderError(\"anthropic\", String(err));\n}\n","import type { StreamEvent, StreamResponse } from \"../types.js\";\n\n/**\n * Push-based async iterable. Producers push events, consumers\n * iterate with `for await`. Also supports thenable so you can\n * `await stream(...)` directly to get the final response.\n */\nexport class EventStream<T = StreamEvent> implements AsyncIterable<T> {\n private queue: T[] = [];\n private resolve: (() => void) | null = null;\n private done = false;\n private error: Error | null = null;\n\n push(event: T): void {\n // Safety valve: if queue grows beyond 10k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 10_000) {\n this.queue.splice(0, this.queue.length - 5_000);\n }\n this.queue.push(event);\n this.resolve?.();\n this.resolve = null;\n }\n\n close(): void {\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n abort(error: Error): void {\n this.error = error;\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n let index = 0;\n while (true) {\n while (index < this.queue.length) {\n yield this.queue[index++]!;\n }\n // Reset to avoid holding references to already-yielded events\n this.queue.splice(0, index);\n index = 0;\n if (this.error) throw this.error;\n if (this.done) return;\n await new Promise<void>((r) => {\n this.resolve = r;\n });\n }\n }\n}\n\n/**\n * Wraps EventStream and adds a `.response` promise that resolves\n * to the final StreamResponse. Also implements thenable so:\n *\n * const msg = await stream({...}) // awaits response\n * for await (const e of stream({...})) {} // iterates events\n */\nexport class StreamResult implements AsyncIterable<StreamEvent> {\n readonly events: EventStream<StreamEvent>;\n readonly response: Promise<StreamResponse>;\n private resolveResponse!: (r: StreamResponse) => void;\n private rejectResponse!: (e: Error) => void;\n private hasConsumer = false;\n\n constructor() {\n this.events = new EventStream<StreamEvent>();\n this.response = new Promise<StreamResponse>((resolve, reject) => {\n this.resolveResponse = resolve;\n this.rejectResponse = reject;\n });\n }\n\n push(event: StreamEvent): void {\n this.events.push(event);\n }\n\n complete(response: StreamResponse): void {\n this.events.close();\n this.resolveResponse(response);\n }\n\n abort(error: Error): void {\n this.events.abort(error);\n this.rejectResponse(error);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n this.hasConsumer = true;\n return this.events[Symbol.asyncIterator]();\n }\n\n then<TResult1 = StreamResponse, TResult2 = never>(\n onfulfilled?: ((value: StreamResponse) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n // Drain events so the stream completes\n this.drainEvents().catch(() => {});\n return this.response.then(onfulfilled, onrejected);\n }\n\n private async drainEvents(): Promise<void> {\n if (this.hasConsumer) return;\n this.hasConsumer = true;\n for await (const _ of this.events) {\n // consume silently\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Converts a Zod schema to a JSON Schema object suitable for\n * provider tool parameter definitions.\n */\nexport function zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n const jsonSchema = z.toJSONSchema(schema);\n // Remove $schema and other meta keys providers don't want\n const { $schema: _schema, ...rest } = jsonSchema as Record<string, unknown>;\n return rest;\n}\n","import type Anthropic from \"@anthropic-ai/sdk\";\nimport type OpenAI from \"openai\";\nimport type {\n CacheRetention,\n ContentPart,\n Message,\n StopReason,\n TextContent,\n ThinkingContent,\n ThinkingLevel,\n Tool,\n ToolChoice,\n} from \"../types.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\n// ── Anthropic Transforms ───────────────────────────────────\n\nexport function toAnthropicCacheControl(\n retention: CacheRetention | undefined,\n baseUrl: string | undefined,\n): { type: \"ephemeral\"; ttl?: \"1h\" } | undefined {\n const resolved = retention ?? \"short\";\n if (resolved === \"none\") return undefined;\n const ttl =\n resolved === \"long\" && (!baseUrl || baseUrl.includes(\"api.anthropic.com\")) ? \"1h\" : undefined;\n return { type: \"ephemeral\", ...(ttl && { ttl }) } as { type: \"ephemeral\"; ttl?: \"1h\" };\n}\n\nexport function toAnthropicMessages(\n messages: Message[],\n cacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" },\n): {\n system: Anthropic.TextBlockParam[] | undefined;\n messages: Anthropic.MessageParam[];\n} {\n let systemText: string | undefined;\n const out: Anthropic.MessageParam[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n systemText = msg.content;\n continue;\n }\n if (msg.role === \"user\") {\n out.push({\n role: \"user\",\n content:\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"text\" as const, text: part.text };\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: part.mediaType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data: part.data,\n },\n };\n }),\n });\n continue;\n }\n if (msg.role === \"assistant\") {\n const content =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((part) => {\n // Strip thinking blocks without a valid signature (e.g. from GLM/OpenAI)\n // — Anthropic rejects empty signatures\n if (part.type === \"thinking\" && !part.signature) return false;\n return true;\n })\n .map((part): Anthropic.ContentBlockParam => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"thinking\")\n return { type: \"thinking\", thinking: part.text, signature: part.signature! };\n if (part.type === \"tool_call\")\n return {\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: part.args,\n };\n if (part.type === \"server_tool_call\")\n return {\n type: \"server_tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n } as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"server_tool_result\")\n return part.data as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"raw\") return part.data as unknown as Anthropic.ContentBlockParam;\n // image content shouldn't appear in assistant messages\n return { type: \"text\", text: \"\" };\n });\n out.push({ role: \"assistant\", content });\n continue;\n }\n if (msg.role === \"tool\") {\n out.push({\n role: \"user\",\n content: msg.content.map((result) => ({\n type: \"tool_result\" as const,\n tool_use_id: result.toolCallId,\n content: result.content,\n is_error: result.isError,\n })),\n });\n }\n }\n\n // Add cache_control to the last user message to cache conversation history\n if (cacheControl && out.length > 0) {\n for (let i = out.length - 1; i >= 0; i--) {\n if (out[i].role === \"user\") {\n const content = out[i].content;\n if (typeof content === \"string\") {\n out[i] = {\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: content,\n cache_control: cacheControl,\n } as Anthropic.TextBlockParam,\n ],\n };\n } else if (Array.isArray(content) && content.length > 0) {\n const last = content[content.length - 1];\n content[content.length - 1] = {\n ...last,\n cache_control: cacheControl,\n } as (typeof content)[number];\n }\n break;\n }\n }\n }\n\n // Build system as block array (supports cache_control).\n // Split on \"<!-- uncached -->\" marker: text before is cached, text after is not.\n let system: Anthropic.TextBlockParam[] | undefined;\n if (systemText) {\n const marker = \"<!-- uncached -->\";\n const markerIdx = systemText.indexOf(marker);\n if (markerIdx !== -1 && cacheControl) {\n const cachedPart = systemText.slice(0, markerIdx).trimEnd();\n const uncachedPart = systemText.slice(markerIdx + marker.length).trimStart();\n system = [\n { type: \"text\" as const, text: cachedPart, cache_control: cacheControl },\n ...(uncachedPart ? [{ type: \"text\" as const, text: uncachedPart }] : []),\n ];\n } else {\n system = [\n {\n type: \"text\" as const,\n text: systemText,\n ...(cacheControl && { cache_control: cacheControl }),\n },\n ];\n }\n }\n\n return { system, messages: out };\n}\n\nexport function toAnthropicTools(tools: Tool[]): Anthropic.Tool[] {\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: (tool.rawInputSchema ??\n zodToJsonSchema(tool.parameters)) as Anthropic.Tool[\"input_schema\"],\n }));\n}\n\nexport function toAnthropicToolChoice(choice: ToolChoice): Anthropic.ToolChoice {\n if (choice === \"auto\") return { type: \"auto\" };\n if (choice === \"none\") return { type: \"none\" };\n if (choice === \"required\") return { type: \"any\" };\n return { type: \"tool\", name: choice.name };\n}\n\nfunction supportsAdaptiveThinking(model: string): boolean {\n return /opus-4-6|sonnet-4-6/.test(model);\n}\n\nexport function toAnthropicThinking(\n level: ThinkingLevel,\n maxTokens: number,\n model: string,\n): {\n thinking: Anthropic.ThinkingConfigParam;\n maxTokens: number;\n outputConfig?: { effort: string };\n} {\n if (supportsAdaptiveThinking(model)) {\n // Adaptive thinking — model decides when/how much to think.\n // budget_tokens is deprecated on Opus 4.6 / Sonnet 4.6.\n // \"max\" effort is Opus-only; downgrade to \"high\" for Sonnet\n let effort: string = level;\n if (level === \"max\" && !model.includes(\"opus\")) {\n effort = \"high\";\n }\n return {\n thinking: { type: \"adaptive\" } as unknown as Anthropic.ThinkingConfigParam,\n maxTokens,\n outputConfig: { effort },\n };\n }\n\n // Legacy budget-based thinking for older models (\"max\" treated as \"high\")\n const effectiveLevel = level === \"max\" ? \"high\" : level;\n const budgetMap: Record<\"low\" | \"medium\" | \"high\", number> = {\n low: Math.max(1024, Math.floor(maxTokens * 0.25)),\n medium: Math.max(2048, Math.floor(maxTokens * 0.5)),\n high: Math.max(4096, maxTokens),\n };\n const budget = budgetMap[effectiveLevel];\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n maxTokens: maxTokens + budget,\n };\n}\n\n// ── OpenAI Transforms ──────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match OpenAI's expected prefix.\n * Anthropic uses `toolu_*` IDs which OpenAI rejects — we need `call_*` prefixed IDs.\n * The mapping is consistent within a single conversion so assistant tool_call IDs\n * match their corresponding tool result references.\n */\nfunction remapToolCallId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"call_\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `call_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nexport function toOpenAIMessages(\n messages: Message[],\n options?: { provider?: string },\n): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\n const idMap = new Map<string, string>();\n // GLM drops reasoning_content when a user message follows tool results.\n // Merge user text into the last tool message to preserve thinking context.\n const mergeToolResultText = options?.provider === \"glm\";\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n out.push({ role: \"system\", content: msg.content });\n continue;\n }\n if (msg.role === \"user\") {\n // For GLM: if the previous message is a tool result, merge text into it\n // to avoid a standalone user message that causes reasoning_content to be dropped.\n if (mergeToolResultText && out.length > 0 && out[out.length - 1]!.role === \"tool\") {\n const userText =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\");\n if (userText) {\n // Append text to the last tool message's content\n const lastTool = out[out.length - 1] as OpenAI.ChatCompletionToolMessageParam;\n lastTool.content = (lastTool.content ?? \"\") + \"\\n\\n\" + userText;\n continue;\n }\n }\n if (typeof msg.content === \"string\") {\n out.push({ role: \"user\", content: msg.content });\n } else {\n out.push({\n role: \"user\",\n content: msg.content.map(\n (\n part,\n ): OpenAI.ChatCompletionContentPartImage | OpenAI.ChatCompletionContentPartText => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${part.mediaType};base64,${part.data}`,\n },\n };\n },\n ),\n });\n }\n continue;\n }\n if (msg.role === \"assistant\") {\n const parts = typeof msg.content === \"string\" ? msg.content : undefined;\n const toolCalls =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter(\n (p): p is Extract<ContentPart, { type: \"tool_call\" }> => p.type === \"tool_call\",\n )\n .map(\n (tc): OpenAI.ChatCompletionMessageToolCall => ({\n id: remapToolCallId(tc.id, idMap),\n type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.args) },\n }),\n )\n : undefined;\n const textParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n // Roundtrip thinking content as reasoning_content (GLM, Moonshot)\n const thinkingParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is ThinkingContent => p.type === \"thinking\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n\n const assistantMsg: OpenAI.ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content: parts || textParts || null,\n ...(toolCalls?.length ? { tool_calls: toolCalls } : {}),\n };\n // Attach reasoning_content for multi-turn coherence (non-standard field).\n // Moonshot requires reasoning_content on ALL assistant messages with tool_calls\n // when thinking is enabled — even if empty.\n if (thinkingParts || toolCalls?.length) {\n (assistantMsg as unknown as Record<string, unknown>).reasoning_content =\n thinkingParts || \" \";\n }\n out.push(assistantMsg);\n continue;\n }\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n out.push({\n role: \"tool\",\n tool_call_id: remapToolCallId(result.toolCallId, idMap),\n content: result.content,\n });\n }\n }\n }\n\n return out;\n}\n\nexport function toOpenAITools(tools: Tool[]): OpenAI.ChatCompletionTool[] {\n return tools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n },\n }));\n}\n\nexport function toOpenAIToolChoice(choice: ToolChoice): OpenAI.ChatCompletionToolChoiceOption {\n if (choice === \"auto\") return \"auto\";\n if (choice === \"none\") return \"none\";\n if (choice === \"required\") return \"required\";\n return { type: \"function\", function: { name: choice.name } };\n}\n\nexport function toOpenAIReasoningEffort(level: ThinkingLevel): \"low\" | \"medium\" | \"high\" {\n return level === \"max\" ? \"high\" : level;\n}\n\n// ── Response Normalization ─────────────────────────────────\n\nexport function normalizeAnthropicStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"max_tokens\";\n case \"pause_turn\":\n return \"pause_turn\";\n case \"stop_sequence\":\n return \"stop_sequence\";\n case \"refusal\":\n return \"refusal\";\n default:\n return \"end_turn\";\n }\n}\n\nexport function normalizeOpenAIStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_calls\":\n return \"tool_use\";\n case \"length\":\n return \"max_tokens\";\n case \"stop\":\n return \"stop_sequence\";\n default:\n return \"end_turn\";\n }\n}\n","import OpenAI from \"openai\";\nimport type { ContentPart, StreamOptions, StreamResponse, ToolCall } from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeOpenAIStopReason,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAIToolChoice,\n toOpenAITools,\n} from \"./transform.js\";\n\nexport function streamOpenAI(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n const providerName = options.provider ?? \"openai\";\n runStream(options, result).catch((err) => result.abort(toError(err, providerName)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const client = new OpenAI({\n apiKey: options.apiKey,\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n });\n\n // GLM and Moonshot use a custom `thinking` body param instead of `reasoning_effort`\n const usesThinkingParam = options.provider === \"glm\" || options.provider === \"moonshot\";\n\n const messages = toOpenAIMessages(options.messages, { provider: options.provider });\n\n // GLM models default to 0.6 temperature when not in thinking mode\n const defaultTemp = options.provider === \"glm\" ? 0.6 : undefined;\n const effectiveTemp = options.temperature ?? defaultTemp;\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(effectiveTemp != null && !options.thinking ? { temperature: effectiveTemp } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop: options.stop } : {}),\n ...(options.thinking && !usesThinkingParam\n ? { reasoning_effort: toOpenAIReasoningEffort(options.thinking) }\n : {}),\n ...(options.tools?.length ? { tools: toOpenAITools(options.tools) } : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toOpenAIToolChoice(options.toolChoice) }\n : {}),\n stream_options: { include_usage: true },\n };\n\n // Inject provider-native web search tools (non-standard, bypass SDK types)\n if (options.webSearch) {\n if (options.provider === \"moonshot\") {\n const raw = params as unknown as Record<string, unknown>;\n const tools = ((raw.tools as unknown[]) ?? []).slice();\n tools.push({ type: \"builtin_function\", function: { name: \"$web_search\" } });\n raw.tools = tools;\n }\n // GLM (Z.AI): web search is provided via MCP servers, not inline tools\n // OpenAI: Chat Completions API does not support web search\n }\n\n // Inject custom thinking param for GLM/Moonshot (not part of OpenAI spec)\n if (usesThinkingParam) {\n (params as unknown as Record<string, unknown>).thinking = options.thinking\n ? { type: \"enabled\" }\n : { type: \"disabled\" };\n }\n\n const stream = await client.chat.completions.create(params, {\n signal: options.signal ?? undefined,\n });\n\n const contentParts: ContentPart[] = [];\n const toolCallAccum = new Map<number, { id: string; name: string; argsJson: string }>();\n let textAccum = \"\";\n let thinkingAccum = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n let cacheRead = 0;\n let finishReason: string | null = null;\n\n for await (const chunk of stream as AsyncIterable<OpenAI.ChatCompletionChunk>) {\n const choice = chunk.choices?.[0];\n\n if (chunk.usage) {\n inputTokens = chunk.usage.prompt_tokens;\n outputTokens = chunk.usage.completion_tokens;\n const details = chunk.usage.prompt_tokens_details;\n if (details?.cached_tokens) {\n cacheRead = details.cached_tokens;\n }\n }\n\n if (!choice) continue;\n\n if (choice.finish_reason) {\n finishReason = choice.finish_reason;\n }\n\n const delta = choice.delta;\n\n // Reasoning/thinking delta (GLM, Moonshot)\n const reasoningContent = (delta as Record<string, unknown>).reasoning_content;\n if (typeof reasoningContent === \"string\" && reasoningContent) {\n thinkingAccum += reasoningContent;\n result.push({ type: \"thinking_delta\", text: reasoningContent });\n }\n\n // Text delta\n if (delta.content) {\n textAccum += delta.content;\n result.push({ type: \"text_delta\", text: delta.content });\n }\n\n // Tool call deltas\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n let accum = toolCallAccum.get(tc.index);\n if (!accum) {\n accum = {\n id: tc.id ?? \"\",\n name: tc.function?.name ?? \"\",\n argsJson: \"\",\n };\n toolCallAccum.set(tc.index, accum);\n }\n if (tc.id) accum.id = tc.id;\n if (tc.function?.name) accum.name = tc.function.name;\n if (tc.function?.arguments) {\n accum.argsJson += tc.function.arguments;\n result.push({\n type: \"toolcall_delta\",\n id: accum.id,\n name: accum.name,\n argsJson: tc.function.arguments,\n });\n }\n }\n }\n }\n\n // Finalize thinking content (GLM, Moonshot reasoning_content)\n if (thinkingAccum) {\n contentParts.push({ type: \"thinking\", text: thinkingAccum });\n }\n\n // Finalize text content\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n // Finalize tool calls\n for (const [, tc] of toolCallAccum) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n // malformed JSON — keep empty\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n\n const stopReason = normalizeOpenAIStopReason(finishReason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens, ...(cacheRead > 0 && { cacheRead }) },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n}\n\nfunction toError(err: unknown, provider: string = \"openai\"): ProviderError {\n if (err instanceof OpenAI.APIError) {\n // Include full error body for debugging — GLM/Moonshot use non-standard error shapes\n let msg = err.message;\n const body = err.error as Record<string, unknown> | undefined;\n if (body) {\n // Append raw error body so debug logs capture the exact API response\n msg += ` | body: ${JSON.stringify(body)}`;\n }\n return new ProviderError(provider, msg, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(provider, err.message, { cause: err });\n }\n return new ProviderError(provider, String(err));\n}\n","import os from \"node:os\";\nimport type {\n ContentPart,\n Message,\n StreamOptions,\n StreamResponse,\n Tool,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\nconst DEFAULT_BASE_URL = \"https://chatgpt.com/backend-api\";\n\nexport function streamOpenAICodex(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const url = `${baseUrl}/codex/responses`;\n\n const { system, input } = toCodexInput(options.messages);\n\n const body: Record<string, unknown> = {\n model: options.model,\n store: false,\n stream: true,\n instructions: system,\n input,\n tool_choice: \"auto\",\n parallel_tool_calls: true,\n include: [\"reasoning.encrypted_content\"],\n };\n\n if (options.tools?.length) {\n body.tools = toCodexTools(options.tools);\n }\n if (options.temperature != null && !options.thinking) {\n body.temperature = options.temperature;\n }\n if (options.thinking) {\n body.reasoning = {\n effort: options.thinking,\n summary: \"auto\",\n };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n Authorization: `Bearer ${options.apiKey}`,\n \"OpenAI-Beta\": \"responses=experimental\",\n originator: \"ggcoder\",\n \"User-Agent\": `ggcoder (${os.platform()} ${os.release()}; ${os.arch()})`,\n };\n\n if (options.accountId) {\n headers[\"chatgpt-account-id\"] = options.accountId;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let message = `Codex API error (${response.status}): ${text}`;\n\n // Add helpful context for common errors\n if (response.status === 400 && text.includes(\"not supported\")) {\n message +=\n `\\n\\nHint: Codex models require a ChatGPT Plus ($20/mo) or Pro ($200/mo) subscription. ` +\n `The \"codex-spark\" variants require ChatGPT Pro. ` +\n `Ensure your account has an active subscription at https://chatgpt.com/settings`;\n }\n\n throw new ProviderError(\"openai\", message, {\n statusCode: response.status,\n });\n }\n\n if (!response.body) {\n throw new ProviderError(\"openai\", \"No response body from Codex API\");\n }\n\n const contentParts: ContentPart[] = [];\n let textAccum = \"\";\n const toolCalls = new Map<string, { id: string; name: string; argsJson: string }>();\n let inputTokens = 0;\n let outputTokens = 0;\n\n for await (const event of parseSSE(response.body)) {\n const type = event.type as string | undefined;\n if (!type) continue;\n\n if (type === \"error\") {\n const msg = (event.message as string) || JSON.stringify(event);\n throw new ProviderError(\"openai\", `Codex error: ${msg}`);\n }\n\n if (type === \"response.failed\") {\n const msg =\n ((event.error as Record<string, unknown>)?.message as string) || \"Codex response failed\";\n throw new ProviderError(\"openai\", msg);\n }\n\n // Text delta\n if (type === \"response.output_text.delta\") {\n const delta = event.delta as string;\n textAccum += delta;\n result.push({ type: \"text_delta\", text: delta });\n }\n\n // Thinking delta\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = event.delta as string;\n result.push({ type: \"thinking_delta\", text: delta });\n }\n\n // Tool call started\n if (type === \"response.output_item.added\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const name = item.name as string;\n toolCalls.set(id, { id, name, argsJson: (item.arguments as string) || \"\" });\n }\n }\n\n // Tool call arguments delta\n if (type === \"response.function_call_arguments.delta\") {\n const delta = event.delta as string;\n const itemId = event.item_id as string;\n // Find the matching tool call\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson += delta;\n result.push({\n type: \"toolcall_delta\",\n id: tc.id,\n name: tc.name,\n argsJson: delta,\n });\n break;\n }\n }\n }\n\n // Tool call arguments done\n if (type === \"response.function_call_arguments.done\") {\n const itemId = event.item_id as string;\n const argsStr = event.arguments as string;\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson = argsStr;\n break;\n }\n }\n }\n\n // Item done — finalize tool call\n if (type === \"response.output_item.done\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const tc = toolCalls.get(id);\n if (tc) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n }\n }\n\n // Response completed\n if (type === \"response.completed\" || type === \"response.done\") {\n const resp = event.response as Record<string, unknown> | undefined;\n const usage = resp?.usage as Record<string, number> | undefined;\n if (usage) {\n inputTokens = usage.input_tokens ?? 0;\n outputTokens = usage.output_tokens ?? 0;\n }\n }\n }\n\n // Finalize content parts\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n for (const [, tc] of toolCalls) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n }\n\n const hasToolCalls = contentParts.some((p) => p.type === \"tool_call\");\n const stopReason = hasToolCalls ? \"tool_use\" : \"end_turn\";\n\n const streamResponse: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(streamResponse);\n}\n\n// ── SSE Parser ─────────────────────────────────────────────\n\nasync function* parseSSE(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<Record<string, unknown>> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let idx = buffer.indexOf(\"\\n\\n\");\n while (idx !== -1) {\n const chunk = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n\n const dataLines = chunk\n .split(\"\\n\")\n .filter((l) => l.startsWith(\"data:\"))\n .map((l) => l.slice(5).trim());\n\n if (dataLines.length > 0) {\n const data = dataLines.join(\"\\n\").trim();\n if (data && data !== \"[DONE]\") {\n try {\n yield JSON.parse(data) as Record<string, unknown>;\n } catch {\n // skip malformed JSON\n }\n }\n }\n idx = buffer.indexOf(\"\\n\\n\");\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n// ── Message Conversion ─────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match Codex API's expected prefix.\n * Codex expects IDs starting with `fc_` — Anthropic uses `toolu_*` which gets rejected.\n */\nfunction remapCodexId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"fc_\") || id.startsWith(\"fc-\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `fc_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nfunction toCodexInput(messages: Message[]): { system: string | undefined; input: unknown[] } {\n let system: string | undefined;\n const input: unknown[] = [];\n const idMap = new Map<string, string>();\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n system = msg.content;\n continue;\n }\n\n if (msg.role === \"user\") {\n const content =\n typeof msg.content === \"string\"\n ? [{ type: \"input_text\", text: msg.content }]\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"input_text\", text: part.text };\n return {\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${part.mediaType};base64,${part.data}`,\n };\n });\n input.push({ role: \"user\", content });\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (typeof msg.content === \"string\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: msg.content, annotations: [] }],\n status: \"completed\",\n });\n continue;\n }\n\n for (const part of msg.content) {\n if (part.type === \"text\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: part.text, annotations: [] }],\n status: \"completed\",\n });\n } else if (part.type === \"tool_call\") {\n const [callId, itemId] = part.id.includes(\"|\")\n ? part.id.split(\"|\", 2)\n : [part.id, part.id];\n input.push({\n type: \"function_call\",\n id: remapCodexId(itemId, idMap),\n call_id: remapCodexId(callId, idMap),\n name: part.name,\n arguments: JSON.stringify(part.args),\n });\n }\n // thinking parts are skipped for codex input\n }\n continue;\n }\n\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n const [callId] = result.toolCallId.includes(\"|\")\n ? result.toolCallId.split(\"|\", 2)\n : [result.toolCallId];\n input.push({\n type: \"function_call_output\",\n call_id: remapCodexId(callId, idMap),\n output: result.content,\n });\n }\n }\n }\n\n return { system, input };\n}\n\n// ── Tool Conversion ────────────────────────────────────────\n\nfunction toCodexTools(tools: Tool[]): unknown[] {\n return tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n strict: null,\n }));\n}\n\n// ── Error Handling ─────────────────────────────────────────\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof ProviderError) return err;\n if (err instanceof Error) {\n return new ProviderError(\"openai\", err.message, { cause: err });\n }\n return new ProviderError(\"openai\", String(err));\n}\n","import type { StreamOptions } from \"./types.js\";\nimport { GGAIError } from \"./errors.js\";\nimport type { StreamResult } from \"./utils/event-stream.js\";\nimport { streamAnthropic } from \"./providers/anthropic.js\";\nimport { streamOpenAI } from \"./providers/openai.js\";\nimport { streamOpenAICodex } from \"./providers/openai-codex.js\";\n\n/**\n * Unified streaming entry point. Returns a StreamResult that is both\n * an async iterable (for streaming events) and thenable (await for\n * the final response).\n *\n * ```ts\n * // Stream events\n * for await (const event of stream({ provider: \"anthropic\", model: \"claude-sonnet-4-6\", messages })) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text);\n * }\n *\n * // Or just await the final message\n * const response = await stream({ provider: \"openai\", model: \"gpt-4.1\", messages });\n * ```\n */\nexport function stream(options: StreamOptions): StreamResult {\n switch (options.provider) {\n case \"anthropic\":\n return streamAnthropic(options);\n case \"openai\":\n // Use codex endpoint for OAuth tokens (have accountId)\n if (options.accountId) {\n return streamOpenAICodex(options);\n }\n return streamOpenAI(options);\n case \"glm\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.z.ai/api/coding/paas/v4\",\n });\n case \"moonshot\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.moonshot.ai/v1\",\n });\n default:\n throw new GGAIError(\n `Unknown provider: ${options.provider as string}. Supported: \"anthropic\", \"openai\", \"glm\", \"moonshot\"`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gBAAN,cAA4B,UAAU;AAAA,EAClC;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aAAO,aAAa;AAAA,QAClB,GAAG;AAAA,QACH,SAAS,QAAQ,WAAW;AAAA,MAC9B,CAAC;AAAA,IACH;AACE,YAAM,IAAI;AAAA,QACR,qBAAqB,QAAQ,QAAkB;AAAA,MACjD;AAAA,EACJ;AACF;","names":["Anthropic","stream","runStream","toError","OpenAI","stream","runStream","toError","os"]}
|
package/dist/index.js
CHANGED
|
@@ -412,10 +412,20 @@ async function runStream(options, result) {
|
|
|
412
412
|
const isOAuth = options.apiKey?.startsWith("sk-ant-oat");
|
|
413
413
|
const client = new Anthropic({
|
|
414
414
|
...isOAuth ? { apiKey: null, authToken: options.apiKey } : { apiKey: options.apiKey },
|
|
415
|
-
...options.baseUrl ? { baseURL: options.baseUrl } : {}
|
|
415
|
+
...options.baseUrl ? { baseURL: options.baseUrl } : {},
|
|
416
|
+
...isOAuth ? {
|
|
417
|
+
defaultHeaders: {
|
|
418
|
+
"user-agent": "claude-cli/2.1.75",
|
|
419
|
+
"x-app": "cli"
|
|
420
|
+
}
|
|
421
|
+
} : {}
|
|
416
422
|
});
|
|
417
423
|
const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);
|
|
418
|
-
const { system, messages } = toAnthropicMessages(options.messages, cacheControl);
|
|
424
|
+
const { system: rawSystem, messages } = toAnthropicMessages(options.messages, cacheControl);
|
|
425
|
+
const system = isOAuth ? [
|
|
426
|
+
{ type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude." },
|
|
427
|
+
...rawSystem ?? []
|
|
428
|
+
] : rawSystem;
|
|
419
429
|
let maxTokens = options.maxTokens ?? 4096;
|
|
420
430
|
let thinking;
|
|
421
431
|
let outputConfig;
|
|
@@ -449,7 +459,7 @@ async function runStream(options, result) {
|
|
|
449
459
|
stream: true
|
|
450
460
|
};
|
|
451
461
|
const betaHeaders = [
|
|
452
|
-
...isOAuth ? ["oauth-2025-04-20"] : [],
|
|
462
|
+
...isOAuth ? ["claude-code-20250219", "oauth-2025-04-20"] : [],
|
|
453
463
|
...options.compaction ? ["compact-2026-01-12"] : []
|
|
454
464
|
];
|
|
455
465
|
const stream2 = client.messages.stream(params, {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/providers/anthropic.ts","../src/utils/event-stream.ts","../src/utils/zod-to-json-schema.ts","../src/providers/transform.ts","../src/providers/openai.ts","../src/providers/openai-codex.ts","../src/stream.ts"],"sourcesContent":["export class GGAIError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"GGAIError\";\n }\n}\n\nexport class ProviderError extends GGAIError {\n readonly provider: string;\n readonly statusCode?: number;\n\n constructor(\n provider: string,\n message: string,\n options?: { statusCode?: number; cause?: unknown },\n ) {\n super(`[${provider}] ${message}`, { cause: options?.cause });\n this.name = \"ProviderError\";\n this.provider = provider;\n this.statusCode = options?.statusCode;\n }\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ContentPart,\n ServerToolCall,\n ServerToolResult,\n StreamOptions,\n StreamResponse,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeAnthropicStopReason,\n toAnthropicCacheControl,\n toAnthropicMessages,\n toAnthropicThinking,\n toAnthropicToolChoice,\n toAnthropicTools,\n} from \"./transform.js\";\n\nexport function streamAnthropic(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const isOAuth = options.apiKey?.startsWith(\"sk-ant-oat\");\n\n const client = new Anthropic({\n ...(isOAuth\n ? { apiKey: null as unknown as string, authToken: options.apiKey }\n : { apiKey: options.apiKey }),\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n });\n\n const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);\n const { system, messages } = toAnthropicMessages(options.messages, cacheControl);\n\n let maxTokens = options.maxTokens ?? 4096;\n let thinking: Anthropic.ThinkingConfigParam | undefined;\n let outputConfig: Record<string, unknown> | undefined;\n\n if (options.thinking) {\n const t = toAnthropicThinking(options.thinking, maxTokens, options.model);\n thinking = t.thinking;\n maxTokens = t.maxTokens;\n if (t.outputConfig) {\n outputConfig = t.outputConfig;\n }\n }\n\n const params: Anthropic.MessageCreateParams = {\n model: options.model,\n max_tokens: maxTokens,\n messages,\n ...(system ? { system: system as Anthropic.MessageCreateParams[\"system\"] } : {}),\n ...(thinking ? { thinking } : {}),\n ...(outputConfig\n ? { output_config: outputConfig as unknown as Anthropic.MessageCreateParams[\"output_config\"] }\n : {}),\n ...(options.temperature != null && !thinking ? { temperature: options.temperature } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop_sequences: options.stop } : {}),\n ...(options.tools?.length || options.serverTools?.length || options.webSearch\n ? {\n tools: [\n ...(options.tools?.length ? toAnthropicTools(options.tools) : []),\n ...(options.serverTools ?? []),\n ...(options.webSearch ? [{ type: \"web_search_20250305\", name: \"web_search\" }] : []),\n ] as Anthropic.MessageCreateParams[\"tools\"],\n }\n : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toAnthropicToolChoice(options.toolChoice) }\n : {}),\n ...(options.compaction\n ? { context_management: { edits: [{ type: \"compact_20260112\" }] } }\n : {}),\n stream: true,\n } as Anthropic.MessageCreateParams;\n\n const betaHeaders = [\n ...(isOAuth ? [\"oauth-2025-04-20\"] : []),\n ...(options.compaction ? [\"compact-2026-01-12\"] : []),\n ];\n\n const stream = client.messages.stream(params, {\n signal: options.signal ?? undefined,\n ...(betaHeaders.length ? { headers: { \"anthropic-beta\": betaHeaders.join(\",\") } } : {}),\n });\n\n const contentParts: ContentPart[] = [];\n // Track the current tool call being streamed (by content block index)\n let currentToolId = \"\";\n let currentToolName = \"\";\n\n stream.on(\"text\", (text) => {\n result.push({ type: \"text_delta\", text });\n });\n\n stream.on(\"thinking\", (thinkingDelta) => {\n result.push({ type: \"thinking_delta\", text: thinkingDelta });\n });\n\n stream.on(\"streamEvent\", (event) => {\n if (event.type === \"content_block_start\") {\n // When a new tool_use content block starts, capture its id and name\n if (event.content_block.type === \"tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n // Track server_tool_use blocks\n if (event.content_block.type === \"server_tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n }\n });\n\n stream.on(\"inputJson\", (delta) => {\n result.push({\n type: \"toolcall_delta\",\n id: currentToolId,\n name: currentToolName,\n argsJson: delta,\n });\n });\n\n stream.on(\"contentBlock\", (block) => {\n if (block.type === \"text\") {\n contentParts.push({ type: \"text\", text: block.text });\n } else if (block.type === \"thinking\") {\n contentParts.push({ type: \"thinking\", text: block.thinking, signature: block.signature });\n } else if (block.type === \"tool_use\") {\n const tc: ToolCall = {\n type: \"tool_call\",\n id: block.id,\n name: block.name,\n args: block.input as Record<string, unknown>,\n };\n contentParts.push(tc);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args: tc.args,\n });\n } else if (block.type === \"server_tool_use\") {\n const stc: ServerToolCall = {\n type: \"server_tool_call\",\n id: block.id,\n name: block.name,\n input: block.input,\n };\n contentParts.push(stc);\n result.push({\n type: \"server_toolcall\",\n id: stc.id,\n name: stc.name,\n input: stc.input,\n });\n } else {\n const raw = block as unknown as Record<string, unknown>;\n const blockType = raw.type as string;\n if (blockType === \"web_search_tool_result\") {\n // Server tool result blocks\n const str: ServerToolResult = {\n type: \"server_tool_result\",\n toolUseId: raw.tool_use_id as string,\n resultType: blockType,\n data: raw,\n };\n contentParts.push(str);\n result.push({\n type: \"server_toolresult\",\n toolUseId: str.toolUseId,\n resultType: str.resultType,\n data: str.data,\n });\n } else {\n // Preserve unknown blocks (e.g. compaction) for round-tripping\n contentParts.push({ type: \"raw\", data: raw });\n }\n }\n });\n\n try {\n const finalMessage = await stream.finalMessage();\n const stopReason = normalizeAnthropicStopReason(finalMessage.stop_reason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : \"\",\n },\n stopReason,\n usage: {\n inputTokens: finalMessage.usage.input_tokens,\n outputTokens: finalMessage.usage.output_tokens,\n ...((finalMessage.usage as unknown as Record<string, unknown>).cache_read_input_tokens !=\n null && {\n cacheRead: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_read_input_tokens as number,\n }),\n ...((finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens != null && {\n cacheWrite: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens as number,\n }),\n },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n } catch (err) {\n const error = toError(err);\n result.push({ type: \"error\", error });\n result.abort(error);\n }\n}\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof Anthropic.APIError) {\n return new ProviderError(\"anthropic\", err.message, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(\"anthropic\", err.message, { cause: err });\n }\n return new ProviderError(\"anthropic\", String(err));\n}\n","import type { StreamEvent, StreamResponse } from \"../types.js\";\n\n/**\n * Push-based async iterable. Producers push events, consumers\n * iterate with `for await`. Also supports thenable so you can\n * `await stream(...)` directly to get the final response.\n */\nexport class EventStream<T = StreamEvent> implements AsyncIterable<T> {\n private queue: T[] = [];\n private resolve: (() => void) | null = null;\n private done = false;\n private error: Error | null = null;\n\n push(event: T): void {\n // Safety valve: if queue grows beyond 10k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 10_000) {\n this.queue.splice(0, this.queue.length - 5_000);\n }\n this.queue.push(event);\n this.resolve?.();\n this.resolve = null;\n }\n\n close(): void {\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n abort(error: Error): void {\n this.error = error;\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n let index = 0;\n while (true) {\n while (index < this.queue.length) {\n yield this.queue[index++]!;\n }\n // Reset to avoid holding references to already-yielded events\n this.queue.splice(0, index);\n index = 0;\n if (this.error) throw this.error;\n if (this.done) return;\n await new Promise<void>((r) => {\n this.resolve = r;\n });\n }\n }\n}\n\n/**\n * Wraps EventStream and adds a `.response` promise that resolves\n * to the final StreamResponse. Also implements thenable so:\n *\n * const msg = await stream({...}) // awaits response\n * for await (const e of stream({...})) {} // iterates events\n */\nexport class StreamResult implements AsyncIterable<StreamEvent> {\n readonly events: EventStream<StreamEvent>;\n readonly response: Promise<StreamResponse>;\n private resolveResponse!: (r: StreamResponse) => void;\n private rejectResponse!: (e: Error) => void;\n private hasConsumer = false;\n\n constructor() {\n this.events = new EventStream<StreamEvent>();\n this.response = new Promise<StreamResponse>((resolve, reject) => {\n this.resolveResponse = resolve;\n this.rejectResponse = reject;\n });\n }\n\n push(event: StreamEvent): void {\n this.events.push(event);\n }\n\n complete(response: StreamResponse): void {\n this.events.close();\n this.resolveResponse(response);\n }\n\n abort(error: Error): void {\n this.events.abort(error);\n this.rejectResponse(error);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n this.hasConsumer = true;\n return this.events[Symbol.asyncIterator]();\n }\n\n then<TResult1 = StreamResponse, TResult2 = never>(\n onfulfilled?: ((value: StreamResponse) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n // Drain events so the stream completes\n this.drainEvents().catch(() => {});\n return this.response.then(onfulfilled, onrejected);\n }\n\n private async drainEvents(): Promise<void> {\n if (this.hasConsumer) return;\n this.hasConsumer = true;\n for await (const _ of this.events) {\n // consume silently\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Converts a Zod schema to a JSON Schema object suitable for\n * provider tool parameter definitions.\n */\nexport function zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n const jsonSchema = z.toJSONSchema(schema);\n // Remove $schema and other meta keys providers don't want\n const { $schema: _schema, ...rest } = jsonSchema as Record<string, unknown>;\n return rest;\n}\n","import type Anthropic from \"@anthropic-ai/sdk\";\nimport type OpenAI from \"openai\";\nimport type {\n CacheRetention,\n ContentPart,\n Message,\n StopReason,\n TextContent,\n ThinkingContent,\n ThinkingLevel,\n Tool,\n ToolChoice,\n} from \"../types.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\n// ── Anthropic Transforms ───────────────────────────────────\n\nexport function toAnthropicCacheControl(\n retention: CacheRetention | undefined,\n baseUrl: string | undefined,\n): { type: \"ephemeral\"; ttl?: \"1h\" } | undefined {\n const resolved = retention ?? \"short\";\n if (resolved === \"none\") return undefined;\n const ttl =\n resolved === \"long\" && (!baseUrl || baseUrl.includes(\"api.anthropic.com\")) ? \"1h\" : undefined;\n return { type: \"ephemeral\", ...(ttl && { ttl }) } as { type: \"ephemeral\"; ttl?: \"1h\" };\n}\n\nexport function toAnthropicMessages(\n messages: Message[],\n cacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" },\n): {\n system: Anthropic.TextBlockParam[] | undefined;\n messages: Anthropic.MessageParam[];\n} {\n let systemText: string | undefined;\n const out: Anthropic.MessageParam[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n systemText = msg.content;\n continue;\n }\n if (msg.role === \"user\") {\n out.push({\n role: \"user\",\n content:\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"text\" as const, text: part.text };\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: part.mediaType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data: part.data,\n },\n };\n }),\n });\n continue;\n }\n if (msg.role === \"assistant\") {\n const content =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((part) => {\n // Strip thinking blocks without a valid signature (e.g. from GLM/OpenAI)\n // — Anthropic rejects empty signatures\n if (part.type === \"thinking\" && !part.signature) return false;\n return true;\n })\n .map((part): Anthropic.ContentBlockParam => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"thinking\")\n return { type: \"thinking\", thinking: part.text, signature: part.signature! };\n if (part.type === \"tool_call\")\n return {\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: part.args,\n };\n if (part.type === \"server_tool_call\")\n return {\n type: \"server_tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n } as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"server_tool_result\")\n return part.data as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"raw\") return part.data as unknown as Anthropic.ContentBlockParam;\n // image content shouldn't appear in assistant messages\n return { type: \"text\", text: \"\" };\n });\n out.push({ role: \"assistant\", content });\n continue;\n }\n if (msg.role === \"tool\") {\n out.push({\n role: \"user\",\n content: msg.content.map((result) => ({\n type: \"tool_result\" as const,\n tool_use_id: result.toolCallId,\n content: result.content,\n is_error: result.isError,\n })),\n });\n }\n }\n\n // Add cache_control to the last user message to cache conversation history\n if (cacheControl && out.length > 0) {\n for (let i = out.length - 1; i >= 0; i--) {\n if (out[i].role === \"user\") {\n const content = out[i].content;\n if (typeof content === \"string\") {\n out[i] = {\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: content,\n cache_control: cacheControl,\n } as Anthropic.TextBlockParam,\n ],\n };\n } else if (Array.isArray(content) && content.length > 0) {\n const last = content[content.length - 1];\n content[content.length - 1] = {\n ...last,\n cache_control: cacheControl,\n } as (typeof content)[number];\n }\n break;\n }\n }\n }\n\n // Build system as block array (supports cache_control).\n // Split on \"<!-- uncached -->\" marker: text before is cached, text after is not.\n let system: Anthropic.TextBlockParam[] | undefined;\n if (systemText) {\n const marker = \"<!-- uncached -->\";\n const markerIdx = systemText.indexOf(marker);\n if (markerIdx !== -1 && cacheControl) {\n const cachedPart = systemText.slice(0, markerIdx).trimEnd();\n const uncachedPart = systemText.slice(markerIdx + marker.length).trimStart();\n system = [\n { type: \"text\" as const, text: cachedPart, cache_control: cacheControl },\n ...(uncachedPart ? [{ type: \"text\" as const, text: uncachedPart }] : []),\n ];\n } else {\n system = [\n {\n type: \"text\" as const,\n text: systemText,\n ...(cacheControl && { cache_control: cacheControl }),\n },\n ];\n }\n }\n\n return { system, messages: out };\n}\n\nexport function toAnthropicTools(tools: Tool[]): Anthropic.Tool[] {\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: (tool.rawInputSchema ??\n zodToJsonSchema(tool.parameters)) as Anthropic.Tool[\"input_schema\"],\n }));\n}\n\nexport function toAnthropicToolChoice(choice: ToolChoice): Anthropic.ToolChoice {\n if (choice === \"auto\") return { type: \"auto\" };\n if (choice === \"none\") return { type: \"none\" };\n if (choice === \"required\") return { type: \"any\" };\n return { type: \"tool\", name: choice.name };\n}\n\nfunction supportsAdaptiveThinking(model: string): boolean {\n return /opus-4-6|sonnet-4-6/.test(model);\n}\n\nexport function toAnthropicThinking(\n level: ThinkingLevel,\n maxTokens: number,\n model: string,\n): {\n thinking: Anthropic.ThinkingConfigParam;\n maxTokens: number;\n outputConfig?: { effort: string };\n} {\n if (supportsAdaptiveThinking(model)) {\n // Adaptive thinking — model decides when/how much to think.\n // budget_tokens is deprecated on Opus 4.6 / Sonnet 4.6.\n // \"max\" effort is Opus-only; downgrade to \"high\" for Sonnet\n let effort: string = level;\n if (level === \"max\" && !model.includes(\"opus\")) {\n effort = \"high\";\n }\n return {\n thinking: { type: \"adaptive\" } as unknown as Anthropic.ThinkingConfigParam,\n maxTokens,\n outputConfig: { effort },\n };\n }\n\n // Legacy budget-based thinking for older models (\"max\" treated as \"high\")\n const effectiveLevel = level === \"max\" ? \"high\" : level;\n const budgetMap: Record<\"low\" | \"medium\" | \"high\", number> = {\n low: Math.max(1024, Math.floor(maxTokens * 0.25)),\n medium: Math.max(2048, Math.floor(maxTokens * 0.5)),\n high: Math.max(4096, maxTokens),\n };\n const budget = budgetMap[effectiveLevel];\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n maxTokens: maxTokens + budget,\n };\n}\n\n// ── OpenAI Transforms ──────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match OpenAI's expected prefix.\n * Anthropic uses `toolu_*` IDs which OpenAI rejects — we need `call_*` prefixed IDs.\n * The mapping is consistent within a single conversion so assistant tool_call IDs\n * match their corresponding tool result references.\n */\nfunction remapToolCallId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"call_\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `call_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nexport function toOpenAIMessages(\n messages: Message[],\n options?: { provider?: string },\n): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\n const idMap = new Map<string, string>();\n // GLM drops reasoning_content when a user message follows tool results.\n // Merge user text into the last tool message to preserve thinking context.\n const mergeToolResultText = options?.provider === \"glm\";\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n out.push({ role: \"system\", content: msg.content });\n continue;\n }\n if (msg.role === \"user\") {\n // For GLM: if the previous message is a tool result, merge text into it\n // to avoid a standalone user message that causes reasoning_content to be dropped.\n if (mergeToolResultText && out.length > 0 && out[out.length - 1]!.role === \"tool\") {\n const userText =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\");\n if (userText) {\n // Append text to the last tool message's content\n const lastTool = out[out.length - 1] as OpenAI.ChatCompletionToolMessageParam;\n lastTool.content = (lastTool.content ?? \"\") + \"\\n\\n\" + userText;\n continue;\n }\n }\n if (typeof msg.content === \"string\") {\n out.push({ role: \"user\", content: msg.content });\n } else {\n out.push({\n role: \"user\",\n content: msg.content.map(\n (\n part,\n ): OpenAI.ChatCompletionContentPartImage | OpenAI.ChatCompletionContentPartText => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${part.mediaType};base64,${part.data}`,\n },\n };\n },\n ),\n });\n }\n continue;\n }\n if (msg.role === \"assistant\") {\n const parts = typeof msg.content === \"string\" ? msg.content : undefined;\n const toolCalls =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter(\n (p): p is Extract<ContentPart, { type: \"tool_call\" }> => p.type === \"tool_call\",\n )\n .map(\n (tc): OpenAI.ChatCompletionMessageToolCall => ({\n id: remapToolCallId(tc.id, idMap),\n type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.args) },\n }),\n )\n : undefined;\n const textParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n // Roundtrip thinking content as reasoning_content (GLM, Moonshot)\n const thinkingParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is ThinkingContent => p.type === \"thinking\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n\n const assistantMsg: OpenAI.ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content: parts || textParts || null,\n ...(toolCalls?.length ? { tool_calls: toolCalls } : {}),\n };\n // Attach reasoning_content for multi-turn coherence (non-standard field).\n // Moonshot requires reasoning_content on ALL assistant messages with tool_calls\n // when thinking is enabled — even if empty.\n if (thinkingParts || toolCalls?.length) {\n (assistantMsg as unknown as Record<string, unknown>).reasoning_content =\n thinkingParts || \" \";\n }\n out.push(assistantMsg);\n continue;\n }\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n out.push({\n role: \"tool\",\n tool_call_id: remapToolCallId(result.toolCallId, idMap),\n content: result.content,\n });\n }\n }\n }\n\n return out;\n}\n\nexport function toOpenAITools(tools: Tool[]): OpenAI.ChatCompletionTool[] {\n return tools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n },\n }));\n}\n\nexport function toOpenAIToolChoice(choice: ToolChoice): OpenAI.ChatCompletionToolChoiceOption {\n if (choice === \"auto\") return \"auto\";\n if (choice === \"none\") return \"none\";\n if (choice === \"required\") return \"required\";\n return { type: \"function\", function: { name: choice.name } };\n}\n\nexport function toOpenAIReasoningEffort(level: ThinkingLevel): \"low\" | \"medium\" | \"high\" {\n return level === \"max\" ? \"high\" : level;\n}\n\n// ── Response Normalization ─────────────────────────────────\n\nexport function normalizeAnthropicStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"max_tokens\";\n case \"pause_turn\":\n return \"pause_turn\";\n case \"stop_sequence\":\n return \"stop_sequence\";\n case \"refusal\":\n return \"refusal\";\n default:\n return \"end_turn\";\n }\n}\n\nexport function normalizeOpenAIStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_calls\":\n return \"tool_use\";\n case \"length\":\n return \"max_tokens\";\n case \"stop\":\n return \"stop_sequence\";\n default:\n return \"end_turn\";\n }\n}\n","import OpenAI from \"openai\";\nimport type { ContentPart, StreamOptions, StreamResponse, ToolCall } from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeOpenAIStopReason,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAIToolChoice,\n toOpenAITools,\n} from \"./transform.js\";\n\nexport function streamOpenAI(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n const providerName = options.provider ?? \"openai\";\n runStream(options, result).catch((err) => result.abort(toError(err, providerName)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const client = new OpenAI({\n apiKey: options.apiKey,\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n });\n\n // GLM and Moonshot use a custom `thinking` body param instead of `reasoning_effort`\n const usesThinkingParam = options.provider === \"glm\" || options.provider === \"moonshot\";\n\n const messages = toOpenAIMessages(options.messages, { provider: options.provider });\n\n // GLM models default to 0.6 temperature when not in thinking mode\n const defaultTemp = options.provider === \"glm\" ? 0.6 : undefined;\n const effectiveTemp = options.temperature ?? defaultTemp;\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(effectiveTemp != null && !options.thinking ? { temperature: effectiveTemp } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop: options.stop } : {}),\n ...(options.thinking && !usesThinkingParam\n ? { reasoning_effort: toOpenAIReasoningEffort(options.thinking) }\n : {}),\n ...(options.tools?.length ? { tools: toOpenAITools(options.tools) } : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toOpenAIToolChoice(options.toolChoice) }\n : {}),\n stream_options: { include_usage: true },\n };\n\n // Inject provider-native web search tools (non-standard, bypass SDK types)\n if (options.webSearch) {\n if (options.provider === \"moonshot\") {\n const raw = params as unknown as Record<string, unknown>;\n const tools = ((raw.tools as unknown[]) ?? []).slice();\n tools.push({ type: \"builtin_function\", function: { name: \"$web_search\" } });\n raw.tools = tools;\n }\n // GLM (Z.AI): web search is provided via MCP servers, not inline tools\n // OpenAI: Chat Completions API does not support web search\n }\n\n // Inject custom thinking param for GLM/Moonshot (not part of OpenAI spec)\n if (usesThinkingParam) {\n (params as unknown as Record<string, unknown>).thinking = options.thinking\n ? { type: \"enabled\" }\n : { type: \"disabled\" };\n }\n\n const stream = await client.chat.completions.create(params, {\n signal: options.signal ?? undefined,\n });\n\n const contentParts: ContentPart[] = [];\n const toolCallAccum = new Map<number, { id: string; name: string; argsJson: string }>();\n let textAccum = \"\";\n let thinkingAccum = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n let cacheRead = 0;\n let finishReason: string | null = null;\n\n for await (const chunk of stream as AsyncIterable<OpenAI.ChatCompletionChunk>) {\n const choice = chunk.choices?.[0];\n\n if (chunk.usage) {\n inputTokens = chunk.usage.prompt_tokens;\n outputTokens = chunk.usage.completion_tokens;\n const details = chunk.usage.prompt_tokens_details;\n if (details?.cached_tokens) {\n cacheRead = details.cached_tokens;\n }\n }\n\n if (!choice) continue;\n\n if (choice.finish_reason) {\n finishReason = choice.finish_reason;\n }\n\n const delta = choice.delta;\n\n // Reasoning/thinking delta (GLM, Moonshot)\n const reasoningContent = (delta as Record<string, unknown>).reasoning_content;\n if (typeof reasoningContent === \"string\" && reasoningContent) {\n thinkingAccum += reasoningContent;\n result.push({ type: \"thinking_delta\", text: reasoningContent });\n }\n\n // Text delta\n if (delta.content) {\n textAccum += delta.content;\n result.push({ type: \"text_delta\", text: delta.content });\n }\n\n // Tool call deltas\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n let accum = toolCallAccum.get(tc.index);\n if (!accum) {\n accum = {\n id: tc.id ?? \"\",\n name: tc.function?.name ?? \"\",\n argsJson: \"\",\n };\n toolCallAccum.set(tc.index, accum);\n }\n if (tc.id) accum.id = tc.id;\n if (tc.function?.name) accum.name = tc.function.name;\n if (tc.function?.arguments) {\n accum.argsJson += tc.function.arguments;\n result.push({\n type: \"toolcall_delta\",\n id: accum.id,\n name: accum.name,\n argsJson: tc.function.arguments,\n });\n }\n }\n }\n }\n\n // Finalize thinking content (GLM, Moonshot reasoning_content)\n if (thinkingAccum) {\n contentParts.push({ type: \"thinking\", text: thinkingAccum });\n }\n\n // Finalize text content\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n // Finalize tool calls\n for (const [, tc] of toolCallAccum) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n // malformed JSON — keep empty\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n\n const stopReason = normalizeOpenAIStopReason(finishReason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens, ...(cacheRead > 0 && { cacheRead }) },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n}\n\nfunction toError(err: unknown, provider: string = \"openai\"): ProviderError {\n if (err instanceof OpenAI.APIError) {\n // Include full error body for debugging — GLM/Moonshot use non-standard error shapes\n let msg = err.message;\n const body = err.error as Record<string, unknown> | undefined;\n if (body) {\n // Append raw error body so debug logs capture the exact API response\n msg += ` | body: ${JSON.stringify(body)}`;\n }\n return new ProviderError(provider, msg, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(provider, err.message, { cause: err });\n }\n return new ProviderError(provider, String(err));\n}\n","import os from \"node:os\";\nimport type {\n ContentPart,\n Message,\n StreamOptions,\n StreamResponse,\n Tool,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\nconst DEFAULT_BASE_URL = \"https://chatgpt.com/backend-api\";\n\nexport function streamOpenAICodex(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const url = `${baseUrl}/codex/responses`;\n\n const { system, input } = toCodexInput(options.messages);\n\n const body: Record<string, unknown> = {\n model: options.model,\n store: false,\n stream: true,\n instructions: system,\n input,\n tool_choice: \"auto\",\n parallel_tool_calls: true,\n include: [\"reasoning.encrypted_content\"],\n };\n\n if (options.tools?.length) {\n body.tools = toCodexTools(options.tools);\n }\n if (options.temperature != null && !options.thinking) {\n body.temperature = options.temperature;\n }\n if (options.thinking) {\n body.reasoning = {\n effort: options.thinking,\n summary: \"auto\",\n };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n Authorization: `Bearer ${options.apiKey}`,\n \"OpenAI-Beta\": \"responses=experimental\",\n originator: \"ggcoder\",\n \"User-Agent\": `ggcoder (${os.platform()} ${os.release()}; ${os.arch()})`,\n };\n\n if (options.accountId) {\n headers[\"chatgpt-account-id\"] = options.accountId;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let message = `Codex API error (${response.status}): ${text}`;\n\n // Add helpful context for common errors\n if (response.status === 400 && text.includes(\"not supported\")) {\n message +=\n `\\n\\nHint: Codex models require a ChatGPT Plus ($20/mo) or Pro ($200/mo) subscription. ` +\n `The \"codex-spark\" variants require ChatGPT Pro. ` +\n `Ensure your account has an active subscription at https://chatgpt.com/settings`;\n }\n\n throw new ProviderError(\"openai\", message, {\n statusCode: response.status,\n });\n }\n\n if (!response.body) {\n throw new ProviderError(\"openai\", \"No response body from Codex API\");\n }\n\n const contentParts: ContentPart[] = [];\n let textAccum = \"\";\n const toolCalls = new Map<string, { id: string; name: string; argsJson: string }>();\n let inputTokens = 0;\n let outputTokens = 0;\n\n for await (const event of parseSSE(response.body)) {\n const type = event.type as string | undefined;\n if (!type) continue;\n\n if (type === \"error\") {\n const msg = (event.message as string) || JSON.stringify(event);\n throw new ProviderError(\"openai\", `Codex error: ${msg}`);\n }\n\n if (type === \"response.failed\") {\n const msg =\n ((event.error as Record<string, unknown>)?.message as string) || \"Codex response failed\";\n throw new ProviderError(\"openai\", msg);\n }\n\n // Text delta\n if (type === \"response.output_text.delta\") {\n const delta = event.delta as string;\n textAccum += delta;\n result.push({ type: \"text_delta\", text: delta });\n }\n\n // Thinking delta\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = event.delta as string;\n result.push({ type: \"thinking_delta\", text: delta });\n }\n\n // Tool call started\n if (type === \"response.output_item.added\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const name = item.name as string;\n toolCalls.set(id, { id, name, argsJson: (item.arguments as string) || \"\" });\n }\n }\n\n // Tool call arguments delta\n if (type === \"response.function_call_arguments.delta\") {\n const delta = event.delta as string;\n const itemId = event.item_id as string;\n // Find the matching tool call\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson += delta;\n result.push({\n type: \"toolcall_delta\",\n id: tc.id,\n name: tc.name,\n argsJson: delta,\n });\n break;\n }\n }\n }\n\n // Tool call arguments done\n if (type === \"response.function_call_arguments.done\") {\n const itemId = event.item_id as string;\n const argsStr = event.arguments as string;\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson = argsStr;\n break;\n }\n }\n }\n\n // Item done — finalize tool call\n if (type === \"response.output_item.done\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const tc = toolCalls.get(id);\n if (tc) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n }\n }\n\n // Response completed\n if (type === \"response.completed\" || type === \"response.done\") {\n const resp = event.response as Record<string, unknown> | undefined;\n const usage = resp?.usage as Record<string, number> | undefined;\n if (usage) {\n inputTokens = usage.input_tokens ?? 0;\n outputTokens = usage.output_tokens ?? 0;\n }\n }\n }\n\n // Finalize content parts\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n for (const [, tc] of toolCalls) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n }\n\n const hasToolCalls = contentParts.some((p) => p.type === \"tool_call\");\n const stopReason = hasToolCalls ? \"tool_use\" : \"end_turn\";\n\n const streamResponse: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(streamResponse);\n}\n\n// ── SSE Parser ─────────────────────────────────────────────\n\nasync function* parseSSE(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<Record<string, unknown>> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let idx = buffer.indexOf(\"\\n\\n\");\n while (idx !== -1) {\n const chunk = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n\n const dataLines = chunk\n .split(\"\\n\")\n .filter((l) => l.startsWith(\"data:\"))\n .map((l) => l.slice(5).trim());\n\n if (dataLines.length > 0) {\n const data = dataLines.join(\"\\n\").trim();\n if (data && data !== \"[DONE]\") {\n try {\n yield JSON.parse(data) as Record<string, unknown>;\n } catch {\n // skip malformed JSON\n }\n }\n }\n idx = buffer.indexOf(\"\\n\\n\");\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n// ── Message Conversion ─────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match Codex API's expected prefix.\n * Codex expects IDs starting with `fc_` — Anthropic uses `toolu_*` which gets rejected.\n */\nfunction remapCodexId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"fc_\") || id.startsWith(\"fc-\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `fc_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nfunction toCodexInput(messages: Message[]): { system: string | undefined; input: unknown[] } {\n let system: string | undefined;\n const input: unknown[] = [];\n const idMap = new Map<string, string>();\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n system = msg.content;\n continue;\n }\n\n if (msg.role === \"user\") {\n const content =\n typeof msg.content === \"string\"\n ? [{ type: \"input_text\", text: msg.content }]\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"input_text\", text: part.text };\n return {\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${part.mediaType};base64,${part.data}`,\n };\n });\n input.push({ role: \"user\", content });\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (typeof msg.content === \"string\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: msg.content, annotations: [] }],\n status: \"completed\",\n });\n continue;\n }\n\n for (const part of msg.content) {\n if (part.type === \"text\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: part.text, annotations: [] }],\n status: \"completed\",\n });\n } else if (part.type === \"tool_call\") {\n const [callId, itemId] = part.id.includes(\"|\")\n ? part.id.split(\"|\", 2)\n : [part.id, part.id];\n input.push({\n type: \"function_call\",\n id: remapCodexId(itemId, idMap),\n call_id: remapCodexId(callId, idMap),\n name: part.name,\n arguments: JSON.stringify(part.args),\n });\n }\n // thinking parts are skipped for codex input\n }\n continue;\n }\n\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n const [callId] = result.toolCallId.includes(\"|\")\n ? result.toolCallId.split(\"|\", 2)\n : [result.toolCallId];\n input.push({\n type: \"function_call_output\",\n call_id: remapCodexId(callId, idMap),\n output: result.content,\n });\n }\n }\n }\n\n return { system, input };\n}\n\n// ── Tool Conversion ────────────────────────────────────────\n\nfunction toCodexTools(tools: Tool[]): unknown[] {\n return tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n strict: null,\n }));\n}\n\n// ── Error Handling ─────────────────────────────────────────\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof ProviderError) return err;\n if (err instanceof Error) {\n return new ProviderError(\"openai\", err.message, { cause: err });\n }\n return new ProviderError(\"openai\", String(err));\n}\n","import type { StreamOptions } from \"./types.js\";\nimport { GGAIError } from \"./errors.js\";\nimport type { StreamResult } from \"./utils/event-stream.js\";\nimport { streamAnthropic } from \"./providers/anthropic.js\";\nimport { streamOpenAI } from \"./providers/openai.js\";\nimport { streamOpenAICodex } from \"./providers/openai-codex.js\";\n\n/**\n * Unified streaming entry point. Returns a StreamResult that is both\n * an async iterable (for streaming events) and thenable (await for\n * the final response).\n *\n * ```ts\n * // Stream events\n * for await (const event of stream({ provider: \"anthropic\", model: \"claude-sonnet-4-6\", messages })) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text);\n * }\n *\n * // Or just await the final message\n * const response = await stream({ provider: \"openai\", model: \"gpt-4.1\", messages });\n * ```\n */\nexport function stream(options: StreamOptions): StreamResult {\n switch (options.provider) {\n case \"anthropic\":\n return streamAnthropic(options);\n case \"openai\":\n // Use codex endpoint for OAuth tokens (have accountId)\n if (options.accountId) {\n return streamOpenAICodex(options);\n }\n return streamOpenAI(options);\n case \"glm\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.z.ai/api/coding/paas/v4\",\n });\n case \"moonshot\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.moonshot.ai/v1\",\n });\n default:\n throw new GGAIError(\n `Unknown provider: ${options.provider as string}. Supported: \"anthropic\", \"openai\", \"glm\", \"moonshot\"`,\n );\n }\n}\n"],"mappings":";AAAO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gBAAN,cAA4B,UAAU;AAAA,EAClC;AAAA,EACA;AAAA,EAET,YACE,UACA,SACA,SACA;AACA,UAAM,IAAI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AS,aAAa,QAAQ,KAAK;AAAA,UACnC,QAAQ,OAAO;AAAA,QACjB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,QAAQ,MAAM;AACzB;AAIA,SAAS,aAAa,OAA0B;AAC9C,SAAO,MAAM,IAAI,CAAC,UAAU;AAAA,IAC1B,MAAM;AAAA,IACN,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB,YAAY,KAAK,kBAAkB,gBAAgB,KAAK,UAAU;AAAA,IAClE,QAAQ;AAAA,EACV,EAAE;AACJ;AAIA,SAASC,SAAQ,KAA6B;AAC5C,MAAI,eAAe,cAAe,QAAO;AACzC,MAAI,eAAe,OAAO;AACxB,WAAO,IAAI,cAAc,UAAU,IAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,EAChE;AACA,SAAO,IAAI,cAAc,UAAU,OAAO,GAAG,CAAC;AAChD;;;AC1XO,SAAS,OAAO,SAAsC;AAC3D,UAAQ,QAAQ,UAAU;AAAA,IACxB,KAAK;AACH,aAAO,gBAAgB,OAAO;AAAA,IAChC,KAAK;AAEH,UAAI,QAAQ,WAAW;AACrB,eAAO,kBAAkB,OAAO;AAAA,MAClC;AACA,aAAO,aAAa,OAAO;AAAA,IAC7B,KAAK;AACH,aAAO,aAAa;AAAA,QAClB,GAAG;AAAA,QACH,SAAS,QAAQ,WAAW;AAAA,MAC9B,CAAC;AAAA,IACH,KAAK;AACH,aAAO,aAAa;AAAA,QAClB,GAAG;AAAA,QACH,SAAS,QAAQ,WAAW;AAAA,MAC9B,CAAC;AAAA,IACH;AACE,YAAM,IAAI;AAAA,QACR,qBAAqB,QAAQ,QAAkB;AAAA,MACjD;AAAA,EACJ;AACF;","names":["stream","runStream","toError","stream","runStream","toError"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/providers/anthropic.ts","../src/utils/event-stream.ts","../src/utils/zod-to-json-schema.ts","../src/providers/transform.ts","../src/providers/openai.ts","../src/providers/openai-codex.ts","../src/stream.ts"],"sourcesContent":["export class GGAIError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"GGAIError\";\n }\n}\n\nexport class ProviderError extends GGAIError {\n readonly provider: string;\n readonly statusCode?: number;\n\n constructor(\n provider: string,\n message: string,\n options?: { statusCode?: number; cause?: unknown },\n ) {\n super(`[${provider}] ${message}`, { cause: options?.cause });\n this.name = \"ProviderError\";\n this.provider = provider;\n this.statusCode = options?.statusCode;\n }\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n ContentPart,\n ServerToolCall,\n ServerToolResult,\n StreamOptions,\n StreamResponse,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeAnthropicStopReason,\n toAnthropicCacheControl,\n toAnthropicMessages,\n toAnthropicThinking,\n toAnthropicToolChoice,\n toAnthropicTools,\n} from \"./transform.js\";\n\nexport function streamAnthropic(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const isOAuth = options.apiKey?.startsWith(\"sk-ant-oat\");\n\n const client = new Anthropic({\n ...(isOAuth\n ? { apiKey: null as unknown as string, authToken: options.apiKey }\n : { apiKey: options.apiKey }),\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n ...(isOAuth\n ? {\n defaultHeaders: {\n \"user-agent\": \"claude-cli/2.1.75\",\n \"x-app\": \"cli\",\n },\n }\n : {}),\n });\n\n const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);\n const { system: rawSystem, messages } = toAnthropicMessages(options.messages, cacheControl);\n\n // OAuth tokens require Claude Code identity in the system prompt\n const system = isOAuth\n ? [\n { type: \"text\" as const, text: \"You are Claude Code, Anthropic's official CLI for Claude.\" },\n ...(rawSystem ?? []),\n ]\n : rawSystem;\n\n let maxTokens = options.maxTokens ?? 4096;\n let thinking: Anthropic.ThinkingConfigParam | undefined;\n let outputConfig: Record<string, unknown> | undefined;\n\n if (options.thinking) {\n const t = toAnthropicThinking(options.thinking, maxTokens, options.model);\n thinking = t.thinking;\n maxTokens = t.maxTokens;\n if (t.outputConfig) {\n outputConfig = t.outputConfig;\n }\n }\n\n const params: Anthropic.MessageCreateParams = {\n model: options.model,\n max_tokens: maxTokens,\n messages,\n ...(system ? { system: system as Anthropic.MessageCreateParams[\"system\"] } : {}),\n ...(thinking ? { thinking } : {}),\n ...(outputConfig\n ? { output_config: outputConfig as unknown as Anthropic.MessageCreateParams[\"output_config\"] }\n : {}),\n ...(options.temperature != null && !thinking ? { temperature: options.temperature } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop_sequences: options.stop } : {}),\n ...(options.tools?.length || options.serverTools?.length || options.webSearch\n ? {\n tools: [\n ...(options.tools?.length ? toAnthropicTools(options.tools) : []),\n ...(options.serverTools ?? []),\n ...(options.webSearch ? [{ type: \"web_search_20250305\", name: \"web_search\" }] : []),\n ] as Anthropic.MessageCreateParams[\"tools\"],\n }\n : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toAnthropicToolChoice(options.toolChoice) }\n : {}),\n ...(options.compaction\n ? { context_management: { edits: [{ type: \"compact_20260112\" }] } }\n : {}),\n stream: true,\n } as Anthropic.MessageCreateParams;\n\n const betaHeaders = [\n ...(isOAuth ? [\"claude-code-20250219\", \"oauth-2025-04-20\"] : []),\n ...(options.compaction ? [\"compact-2026-01-12\"] : []),\n ];\n\n const stream = client.messages.stream(params, {\n signal: options.signal ?? undefined,\n ...(betaHeaders.length ? { headers: { \"anthropic-beta\": betaHeaders.join(\",\") } } : {}),\n });\n\n const contentParts: ContentPart[] = [];\n // Track the current tool call being streamed (by content block index)\n let currentToolId = \"\";\n let currentToolName = \"\";\n\n stream.on(\"text\", (text) => {\n result.push({ type: \"text_delta\", text });\n });\n\n stream.on(\"thinking\", (thinkingDelta) => {\n result.push({ type: \"thinking_delta\", text: thinkingDelta });\n });\n\n stream.on(\"streamEvent\", (event) => {\n if (event.type === \"content_block_start\") {\n // When a new tool_use content block starts, capture its id and name\n if (event.content_block.type === \"tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n // Track server_tool_use blocks\n if (event.content_block.type === \"server_tool_use\") {\n currentToolId = event.content_block.id;\n currentToolName = event.content_block.name;\n }\n }\n });\n\n stream.on(\"inputJson\", (delta) => {\n result.push({\n type: \"toolcall_delta\",\n id: currentToolId,\n name: currentToolName,\n argsJson: delta,\n });\n });\n\n stream.on(\"contentBlock\", (block) => {\n if (block.type === \"text\") {\n contentParts.push({ type: \"text\", text: block.text });\n } else if (block.type === \"thinking\") {\n contentParts.push({ type: \"thinking\", text: block.thinking, signature: block.signature });\n } else if (block.type === \"tool_use\") {\n const tc: ToolCall = {\n type: \"tool_call\",\n id: block.id,\n name: block.name,\n args: block.input as Record<string, unknown>,\n };\n contentParts.push(tc);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args: tc.args,\n });\n } else if (block.type === \"server_tool_use\") {\n const stc: ServerToolCall = {\n type: \"server_tool_call\",\n id: block.id,\n name: block.name,\n input: block.input,\n };\n contentParts.push(stc);\n result.push({\n type: \"server_toolcall\",\n id: stc.id,\n name: stc.name,\n input: stc.input,\n });\n } else {\n const raw = block as unknown as Record<string, unknown>;\n const blockType = raw.type as string;\n if (blockType === \"web_search_tool_result\") {\n // Server tool result blocks\n const str: ServerToolResult = {\n type: \"server_tool_result\",\n toolUseId: raw.tool_use_id as string,\n resultType: blockType,\n data: raw,\n };\n contentParts.push(str);\n result.push({\n type: \"server_toolresult\",\n toolUseId: str.toolUseId,\n resultType: str.resultType,\n data: str.data,\n });\n } else {\n // Preserve unknown blocks (e.g. compaction) for round-tripping\n contentParts.push({ type: \"raw\", data: raw });\n }\n }\n });\n\n try {\n const finalMessage = await stream.finalMessage();\n const stopReason = normalizeAnthropicStopReason(finalMessage.stop_reason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : \"\",\n },\n stopReason,\n usage: {\n inputTokens: finalMessage.usage.input_tokens,\n outputTokens: finalMessage.usage.output_tokens,\n ...((finalMessage.usage as unknown as Record<string, unknown>).cache_read_input_tokens !=\n null && {\n cacheRead: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_read_input_tokens as number,\n }),\n ...((finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens != null && {\n cacheWrite: (finalMessage.usage as unknown as Record<string, unknown>)\n .cache_creation_input_tokens as number,\n }),\n },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n } catch (err) {\n const error = toError(err);\n result.push({ type: \"error\", error });\n result.abort(error);\n }\n}\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof Anthropic.APIError) {\n return new ProviderError(\"anthropic\", err.message, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(\"anthropic\", err.message, { cause: err });\n }\n return new ProviderError(\"anthropic\", String(err));\n}\n","import type { StreamEvent, StreamResponse } from \"../types.js\";\n\n/**\n * Push-based async iterable. Producers push events, consumers\n * iterate with `for await`. Also supports thenable so you can\n * `await stream(...)` directly to get the final response.\n */\nexport class EventStream<T = StreamEvent> implements AsyncIterable<T> {\n private queue: T[] = [];\n private resolve: (() => void) | null = null;\n private done = false;\n private error: Error | null = null;\n\n push(event: T): void {\n // Safety valve: if queue grows beyond 10k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 10_000) {\n this.queue.splice(0, this.queue.length - 5_000);\n }\n this.queue.push(event);\n this.resolve?.();\n this.resolve = null;\n }\n\n close(): void {\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n abort(error: Error): void {\n this.error = error;\n this.done = true;\n this.resolve?.();\n this.resolve = null;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n let index = 0;\n while (true) {\n while (index < this.queue.length) {\n yield this.queue[index++]!;\n }\n // Reset to avoid holding references to already-yielded events\n this.queue.splice(0, index);\n index = 0;\n if (this.error) throw this.error;\n if (this.done) return;\n await new Promise<void>((r) => {\n this.resolve = r;\n });\n }\n }\n}\n\n/**\n * Wraps EventStream and adds a `.response` promise that resolves\n * to the final StreamResponse. Also implements thenable so:\n *\n * const msg = await stream({...}) // awaits response\n * for await (const e of stream({...})) {} // iterates events\n */\nexport class StreamResult implements AsyncIterable<StreamEvent> {\n readonly events: EventStream<StreamEvent>;\n readonly response: Promise<StreamResponse>;\n private resolveResponse!: (r: StreamResponse) => void;\n private rejectResponse!: (e: Error) => void;\n private hasConsumer = false;\n\n constructor() {\n this.events = new EventStream<StreamEvent>();\n this.response = new Promise<StreamResponse>((resolve, reject) => {\n this.resolveResponse = resolve;\n this.rejectResponse = reject;\n });\n }\n\n push(event: StreamEvent): void {\n this.events.push(event);\n }\n\n complete(response: StreamResponse): void {\n this.events.close();\n this.resolveResponse(response);\n }\n\n abort(error: Error): void {\n this.events.abort(error);\n this.rejectResponse(error);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n this.hasConsumer = true;\n return this.events[Symbol.asyncIterator]();\n }\n\n then<TResult1 = StreamResponse, TResult2 = never>(\n onfulfilled?: ((value: StreamResponse) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n // Drain events so the stream completes\n this.drainEvents().catch(() => {});\n return this.response.then(onfulfilled, onrejected);\n }\n\n private async drainEvents(): Promise<void> {\n if (this.hasConsumer) return;\n this.hasConsumer = true;\n for await (const _ of this.events) {\n // consume silently\n }\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Converts a Zod schema to a JSON Schema object suitable for\n * provider tool parameter definitions.\n */\nexport function zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n const jsonSchema = z.toJSONSchema(schema);\n // Remove $schema and other meta keys providers don't want\n const { $schema: _schema, ...rest } = jsonSchema as Record<string, unknown>;\n return rest;\n}\n","import type Anthropic from \"@anthropic-ai/sdk\";\nimport type OpenAI from \"openai\";\nimport type {\n CacheRetention,\n ContentPart,\n Message,\n StopReason,\n TextContent,\n ThinkingContent,\n ThinkingLevel,\n Tool,\n ToolChoice,\n} from \"../types.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\n// ── Anthropic Transforms ───────────────────────────────────\n\nexport function toAnthropicCacheControl(\n retention: CacheRetention | undefined,\n baseUrl: string | undefined,\n): { type: \"ephemeral\"; ttl?: \"1h\" } | undefined {\n const resolved = retention ?? \"short\";\n if (resolved === \"none\") return undefined;\n const ttl =\n resolved === \"long\" && (!baseUrl || baseUrl.includes(\"api.anthropic.com\")) ? \"1h\" : undefined;\n return { type: \"ephemeral\", ...(ttl && { ttl }) } as { type: \"ephemeral\"; ttl?: \"1h\" };\n}\n\nexport function toAnthropicMessages(\n messages: Message[],\n cacheControl?: { type: \"ephemeral\"; ttl?: \"1h\" },\n): {\n system: Anthropic.TextBlockParam[] | undefined;\n messages: Anthropic.MessageParam[];\n} {\n let systemText: string | undefined;\n const out: Anthropic.MessageParam[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n systemText = msg.content;\n continue;\n }\n if (msg.role === \"user\") {\n out.push({\n role: \"user\",\n content:\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"text\" as const, text: part.text };\n return {\n type: \"image\" as const,\n source: {\n type: \"base64\" as const,\n media_type: part.mediaType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data: part.data,\n },\n };\n }),\n });\n continue;\n }\n if (msg.role === \"assistant\") {\n const content =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((part) => {\n // Strip thinking blocks without a valid signature (e.g. from GLM/OpenAI)\n // — Anthropic rejects empty signatures\n if (part.type === \"thinking\" && !part.signature) return false;\n return true;\n })\n .map((part): Anthropic.ContentBlockParam => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n if (part.type === \"thinking\")\n return { type: \"thinking\", thinking: part.text, signature: part.signature! };\n if (part.type === \"tool_call\")\n return {\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: part.args,\n };\n if (part.type === \"server_tool_call\")\n return {\n type: \"server_tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n } as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"server_tool_result\")\n return part.data as unknown as Anthropic.ContentBlockParam;\n if (part.type === \"raw\") return part.data as unknown as Anthropic.ContentBlockParam;\n // image content shouldn't appear in assistant messages\n return { type: \"text\", text: \"\" };\n });\n out.push({ role: \"assistant\", content });\n continue;\n }\n if (msg.role === \"tool\") {\n out.push({\n role: \"user\",\n content: msg.content.map((result) => ({\n type: \"tool_result\" as const,\n tool_use_id: result.toolCallId,\n content: result.content,\n is_error: result.isError,\n })),\n });\n }\n }\n\n // Add cache_control to the last user message to cache conversation history\n if (cacheControl && out.length > 0) {\n for (let i = out.length - 1; i >= 0; i--) {\n if (out[i].role === \"user\") {\n const content = out[i].content;\n if (typeof content === \"string\") {\n out[i] = {\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: content,\n cache_control: cacheControl,\n } as Anthropic.TextBlockParam,\n ],\n };\n } else if (Array.isArray(content) && content.length > 0) {\n const last = content[content.length - 1];\n content[content.length - 1] = {\n ...last,\n cache_control: cacheControl,\n } as (typeof content)[number];\n }\n break;\n }\n }\n }\n\n // Build system as block array (supports cache_control).\n // Split on \"<!-- uncached -->\" marker: text before is cached, text after is not.\n let system: Anthropic.TextBlockParam[] | undefined;\n if (systemText) {\n const marker = \"<!-- uncached -->\";\n const markerIdx = systemText.indexOf(marker);\n if (markerIdx !== -1 && cacheControl) {\n const cachedPart = systemText.slice(0, markerIdx).trimEnd();\n const uncachedPart = systemText.slice(markerIdx + marker.length).trimStart();\n system = [\n { type: \"text\" as const, text: cachedPart, cache_control: cacheControl },\n ...(uncachedPart ? [{ type: \"text\" as const, text: uncachedPart }] : []),\n ];\n } else {\n system = [\n {\n type: \"text\" as const,\n text: systemText,\n ...(cacheControl && { cache_control: cacheControl }),\n },\n ];\n }\n }\n\n return { system, messages: out };\n}\n\nexport function toAnthropicTools(tools: Tool[]): Anthropic.Tool[] {\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: (tool.rawInputSchema ??\n zodToJsonSchema(tool.parameters)) as Anthropic.Tool[\"input_schema\"],\n }));\n}\n\nexport function toAnthropicToolChoice(choice: ToolChoice): Anthropic.ToolChoice {\n if (choice === \"auto\") return { type: \"auto\" };\n if (choice === \"none\") return { type: \"none\" };\n if (choice === \"required\") return { type: \"any\" };\n return { type: \"tool\", name: choice.name };\n}\n\nfunction supportsAdaptiveThinking(model: string): boolean {\n return /opus-4-6|sonnet-4-6/.test(model);\n}\n\nexport function toAnthropicThinking(\n level: ThinkingLevel,\n maxTokens: number,\n model: string,\n): {\n thinking: Anthropic.ThinkingConfigParam;\n maxTokens: number;\n outputConfig?: { effort: string };\n} {\n if (supportsAdaptiveThinking(model)) {\n // Adaptive thinking — model decides when/how much to think.\n // budget_tokens is deprecated on Opus 4.6 / Sonnet 4.6.\n // \"max\" effort is Opus-only; downgrade to \"high\" for Sonnet\n let effort: string = level;\n if (level === \"max\" && !model.includes(\"opus\")) {\n effort = \"high\";\n }\n return {\n thinking: { type: \"adaptive\" } as unknown as Anthropic.ThinkingConfigParam,\n maxTokens,\n outputConfig: { effort },\n };\n }\n\n // Legacy budget-based thinking for older models (\"max\" treated as \"high\")\n const effectiveLevel = level === \"max\" ? \"high\" : level;\n const budgetMap: Record<\"low\" | \"medium\" | \"high\", number> = {\n low: Math.max(1024, Math.floor(maxTokens * 0.25)),\n medium: Math.max(2048, Math.floor(maxTokens * 0.5)),\n high: Math.max(4096, maxTokens),\n };\n const budget = budgetMap[effectiveLevel];\n return {\n thinking: { type: \"enabled\", budget_tokens: budget },\n maxTokens: maxTokens + budget,\n };\n}\n\n// ── OpenAI Transforms ──────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match OpenAI's expected prefix.\n * Anthropic uses `toolu_*` IDs which OpenAI rejects — we need `call_*` prefixed IDs.\n * The mapping is consistent within a single conversion so assistant tool_call IDs\n * match their corresponding tool result references.\n */\nfunction remapToolCallId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"call_\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `call_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nexport function toOpenAIMessages(\n messages: Message[],\n options?: { provider?: string },\n): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\n const idMap = new Map<string, string>();\n // GLM drops reasoning_content when a user message follows tool results.\n // Merge user text into the last tool message to preserve thinking context.\n const mergeToolResultText = options?.provider === \"glm\";\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n out.push({ role: \"system\", content: msg.content });\n continue;\n }\n if (msg.role === \"user\") {\n // For GLM: if the previous message is a tool result, merge text into it\n // to avoid a standalone user message that causes reasoning_content to be dropped.\n if (mergeToolResultText && out.length > 0 && out[out.length - 1]!.role === \"tool\") {\n const userText =\n typeof msg.content === \"string\"\n ? msg.content\n : msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\");\n if (userText) {\n // Append text to the last tool message's content\n const lastTool = out[out.length - 1] as OpenAI.ChatCompletionToolMessageParam;\n lastTool.content = (lastTool.content ?? \"\") + \"\\n\\n\" + userText;\n continue;\n }\n }\n if (typeof msg.content === \"string\") {\n out.push({ role: \"user\", content: msg.content });\n } else {\n out.push({\n role: \"user\",\n content: msg.content.map(\n (\n part,\n ): OpenAI.ChatCompletionContentPartImage | OpenAI.ChatCompletionContentPartText => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${part.mediaType};base64,${part.data}`,\n },\n };\n },\n ),\n });\n }\n continue;\n }\n if (msg.role === \"assistant\") {\n const parts = typeof msg.content === \"string\" ? msg.content : undefined;\n const toolCalls =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter(\n (p): p is Extract<ContentPart, { type: \"tool_call\" }> => p.type === \"tool_call\",\n )\n .map(\n (tc): OpenAI.ChatCompletionMessageToolCall => ({\n id: remapToolCallId(tc.id, idMap),\n type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.args) },\n }),\n )\n : undefined;\n const textParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is TextContent => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n // Roundtrip thinking content as reasoning_content (GLM, Moonshot)\n const thinkingParts =\n typeof msg.content !== \"string\"\n ? msg.content\n .filter((p): p is ThinkingContent => p.type === \"thinking\")\n .map((p) => p.text)\n .join(\"\")\n : undefined;\n\n const assistantMsg: OpenAI.ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content: parts || textParts || null,\n ...(toolCalls?.length ? { tool_calls: toolCalls } : {}),\n };\n // Attach reasoning_content for multi-turn coherence (non-standard field).\n // Moonshot requires reasoning_content on ALL assistant messages with tool_calls\n // when thinking is enabled — even if empty.\n if (thinkingParts || toolCalls?.length) {\n (assistantMsg as unknown as Record<string, unknown>).reasoning_content =\n thinkingParts || \" \";\n }\n out.push(assistantMsg);\n continue;\n }\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n out.push({\n role: \"tool\",\n tool_call_id: remapToolCallId(result.toolCallId, idMap),\n content: result.content,\n });\n }\n }\n }\n\n return out;\n}\n\nexport function toOpenAITools(tools: Tool[]): OpenAI.ChatCompletionTool[] {\n return tools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n },\n }));\n}\n\nexport function toOpenAIToolChoice(choice: ToolChoice): OpenAI.ChatCompletionToolChoiceOption {\n if (choice === \"auto\") return \"auto\";\n if (choice === \"none\") return \"none\";\n if (choice === \"required\") return \"required\";\n return { type: \"function\", function: { name: choice.name } };\n}\n\nexport function toOpenAIReasoningEffort(level: ThinkingLevel): \"low\" | \"medium\" | \"high\" {\n return level === \"max\" ? \"high\" : level;\n}\n\n// ── Response Normalization ─────────────────────────────────\n\nexport function normalizeAnthropicStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"max_tokens\";\n case \"pause_turn\":\n return \"pause_turn\";\n case \"stop_sequence\":\n return \"stop_sequence\";\n case \"refusal\":\n return \"refusal\";\n default:\n return \"end_turn\";\n }\n}\n\nexport function normalizeOpenAIStopReason(reason: string | null): StopReason {\n switch (reason) {\n case \"tool_calls\":\n return \"tool_use\";\n case \"length\":\n return \"max_tokens\";\n case \"stop\":\n return \"stop_sequence\";\n default:\n return \"end_turn\";\n }\n}\n","import OpenAI from \"openai\";\nimport type { ContentPart, StreamOptions, StreamResponse, ToolCall } from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport {\n normalizeOpenAIStopReason,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAIToolChoice,\n toOpenAITools,\n} from \"./transform.js\";\n\nexport function streamOpenAI(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n const providerName = options.provider ?? \"openai\";\n runStream(options, result).catch((err) => result.abort(toError(err, providerName)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const client = new OpenAI({\n apiKey: options.apiKey,\n ...(options.baseUrl ? { baseURL: options.baseUrl } : {}),\n });\n\n // GLM and Moonshot use a custom `thinking` body param instead of `reasoning_effort`\n const usesThinkingParam = options.provider === \"glm\" || options.provider === \"moonshot\";\n\n const messages = toOpenAIMessages(options.messages, { provider: options.provider });\n\n // GLM models default to 0.6 temperature when not in thinking mode\n const defaultTemp = options.provider === \"glm\" ? 0.6 : undefined;\n const effectiveTemp = options.temperature ?? defaultTemp;\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(effectiveTemp != null && !options.thinking ? { temperature: effectiveTemp } : {}),\n ...(options.topP != null ? { top_p: options.topP } : {}),\n ...(options.stop ? { stop: options.stop } : {}),\n ...(options.thinking && !usesThinkingParam\n ? { reasoning_effort: toOpenAIReasoningEffort(options.thinking) }\n : {}),\n ...(options.tools?.length ? { tools: toOpenAITools(options.tools) } : {}),\n ...(options.toolChoice && options.tools?.length\n ? { tool_choice: toOpenAIToolChoice(options.toolChoice) }\n : {}),\n stream_options: { include_usage: true },\n };\n\n // Inject provider-native web search tools (non-standard, bypass SDK types)\n if (options.webSearch) {\n if (options.provider === \"moonshot\") {\n const raw = params as unknown as Record<string, unknown>;\n const tools = ((raw.tools as unknown[]) ?? []).slice();\n tools.push({ type: \"builtin_function\", function: { name: \"$web_search\" } });\n raw.tools = tools;\n }\n // GLM (Z.AI): web search is provided via MCP servers, not inline tools\n // OpenAI: Chat Completions API does not support web search\n }\n\n // Inject custom thinking param for GLM/Moonshot (not part of OpenAI spec)\n if (usesThinkingParam) {\n (params as unknown as Record<string, unknown>).thinking = options.thinking\n ? { type: \"enabled\" }\n : { type: \"disabled\" };\n }\n\n const stream = await client.chat.completions.create(params, {\n signal: options.signal ?? undefined,\n });\n\n const contentParts: ContentPart[] = [];\n const toolCallAccum = new Map<number, { id: string; name: string; argsJson: string }>();\n let textAccum = \"\";\n let thinkingAccum = \"\";\n let inputTokens = 0;\n let outputTokens = 0;\n let cacheRead = 0;\n let finishReason: string | null = null;\n\n for await (const chunk of stream as AsyncIterable<OpenAI.ChatCompletionChunk>) {\n const choice = chunk.choices?.[0];\n\n if (chunk.usage) {\n inputTokens = chunk.usage.prompt_tokens;\n outputTokens = chunk.usage.completion_tokens;\n const details = chunk.usage.prompt_tokens_details;\n if (details?.cached_tokens) {\n cacheRead = details.cached_tokens;\n }\n }\n\n if (!choice) continue;\n\n if (choice.finish_reason) {\n finishReason = choice.finish_reason;\n }\n\n const delta = choice.delta;\n\n // Reasoning/thinking delta (GLM, Moonshot)\n const reasoningContent = (delta as Record<string, unknown>).reasoning_content;\n if (typeof reasoningContent === \"string\" && reasoningContent) {\n thinkingAccum += reasoningContent;\n result.push({ type: \"thinking_delta\", text: reasoningContent });\n }\n\n // Text delta\n if (delta.content) {\n textAccum += delta.content;\n result.push({ type: \"text_delta\", text: delta.content });\n }\n\n // Tool call deltas\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n let accum = toolCallAccum.get(tc.index);\n if (!accum) {\n accum = {\n id: tc.id ?? \"\",\n name: tc.function?.name ?? \"\",\n argsJson: \"\",\n };\n toolCallAccum.set(tc.index, accum);\n }\n if (tc.id) accum.id = tc.id;\n if (tc.function?.name) accum.name = tc.function.name;\n if (tc.function?.arguments) {\n accum.argsJson += tc.function.arguments;\n result.push({\n type: \"toolcall_delta\",\n id: accum.id,\n name: accum.name,\n argsJson: tc.function.arguments,\n });\n }\n }\n }\n }\n\n // Finalize thinking content (GLM, Moonshot reasoning_content)\n if (thinkingAccum) {\n contentParts.push({ type: \"thinking\", text: thinkingAccum });\n }\n\n // Finalize text content\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n // Finalize tool calls\n for (const [, tc] of toolCallAccum) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n // malformed JSON — keep empty\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n\n const stopReason = normalizeOpenAIStopReason(finishReason);\n\n const response: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens, ...(cacheRead > 0 && { cacheRead }) },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(response);\n}\n\nfunction toError(err: unknown, provider: string = \"openai\"): ProviderError {\n if (err instanceof OpenAI.APIError) {\n // Include full error body for debugging — GLM/Moonshot use non-standard error shapes\n let msg = err.message;\n const body = err.error as Record<string, unknown> | undefined;\n if (body) {\n // Append raw error body so debug logs capture the exact API response\n msg += ` | body: ${JSON.stringify(body)}`;\n }\n return new ProviderError(provider, msg, {\n statusCode: err.status,\n cause: err,\n });\n }\n if (err instanceof Error) {\n return new ProviderError(provider, err.message, { cause: err });\n }\n return new ProviderError(provider, String(err));\n}\n","import os from \"node:os\";\nimport type {\n ContentPart,\n Message,\n StreamOptions,\n StreamResponse,\n Tool,\n ToolCall,\n} from \"../types.js\";\nimport { ProviderError } from \"../errors.js\";\nimport { StreamResult } from \"../utils/event-stream.js\";\nimport { zodToJsonSchema } from \"../utils/zod-to-json-schema.js\";\n\nconst DEFAULT_BASE_URL = \"https://chatgpt.com/backend-api\";\n\nexport function streamOpenAICodex(options: StreamOptions): StreamResult {\n const result = new StreamResult();\n runStream(options, result).catch((err) => result.abort(toError(err)));\n return result;\n}\n\nasync function runStream(options: StreamOptions, result: StreamResult): Promise<void> {\n const baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const url = `${baseUrl}/codex/responses`;\n\n const { system, input } = toCodexInput(options.messages);\n\n const body: Record<string, unknown> = {\n model: options.model,\n store: false,\n stream: true,\n instructions: system,\n input,\n tool_choice: \"auto\",\n parallel_tool_calls: true,\n include: [\"reasoning.encrypted_content\"],\n };\n\n if (options.tools?.length) {\n body.tools = toCodexTools(options.tools);\n }\n if (options.temperature != null && !options.thinking) {\n body.temperature = options.temperature;\n }\n if (options.thinking) {\n body.reasoning = {\n effort: options.thinking,\n summary: \"auto\",\n };\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n Authorization: `Bearer ${options.apiKey}`,\n \"OpenAI-Beta\": \"responses=experimental\",\n originator: \"ggcoder\",\n \"User-Agent\": `ggcoder (${os.platform()} ${os.release()}; ${os.arch()})`,\n };\n\n if (options.accountId) {\n headers[\"chatgpt-account-id\"] = options.accountId;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n let message = `Codex API error (${response.status}): ${text}`;\n\n // Add helpful context for common errors\n if (response.status === 400 && text.includes(\"not supported\")) {\n message +=\n `\\n\\nHint: Codex models require a ChatGPT Plus ($20/mo) or Pro ($200/mo) subscription. ` +\n `The \"codex-spark\" variants require ChatGPT Pro. ` +\n `Ensure your account has an active subscription at https://chatgpt.com/settings`;\n }\n\n throw new ProviderError(\"openai\", message, {\n statusCode: response.status,\n });\n }\n\n if (!response.body) {\n throw new ProviderError(\"openai\", \"No response body from Codex API\");\n }\n\n const contentParts: ContentPart[] = [];\n let textAccum = \"\";\n const toolCalls = new Map<string, { id: string; name: string; argsJson: string }>();\n let inputTokens = 0;\n let outputTokens = 0;\n\n for await (const event of parseSSE(response.body)) {\n const type = event.type as string | undefined;\n if (!type) continue;\n\n if (type === \"error\") {\n const msg = (event.message as string) || JSON.stringify(event);\n throw new ProviderError(\"openai\", `Codex error: ${msg}`);\n }\n\n if (type === \"response.failed\") {\n const msg =\n ((event.error as Record<string, unknown>)?.message as string) || \"Codex response failed\";\n throw new ProviderError(\"openai\", msg);\n }\n\n // Text delta\n if (type === \"response.output_text.delta\") {\n const delta = event.delta as string;\n textAccum += delta;\n result.push({ type: \"text_delta\", text: delta });\n }\n\n // Thinking delta\n if (type === \"response.reasoning_summary_text.delta\") {\n const delta = event.delta as string;\n result.push({ type: \"thinking_delta\", text: delta });\n }\n\n // Tool call started\n if (type === \"response.output_item.added\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const name = item.name as string;\n toolCalls.set(id, { id, name, argsJson: (item.arguments as string) || \"\" });\n }\n }\n\n // Tool call arguments delta\n if (type === \"response.function_call_arguments.delta\") {\n const delta = event.delta as string;\n const itemId = event.item_id as string;\n // Find the matching tool call\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson += delta;\n result.push({\n type: \"toolcall_delta\",\n id: tc.id,\n name: tc.name,\n argsJson: delta,\n });\n break;\n }\n }\n }\n\n // Tool call arguments done\n if (type === \"response.function_call_arguments.done\") {\n const itemId = event.item_id as string;\n const argsStr = event.arguments as string;\n for (const [key, tc] of toolCalls) {\n if (key.endsWith(`|${itemId}`)) {\n tc.argsJson = argsStr;\n break;\n }\n }\n }\n\n // Item done — finalize tool call\n if (type === \"response.output_item.done\") {\n const item = event.item as Record<string, unknown>;\n if (item?.type === \"function_call\") {\n const callId = item.call_id as string;\n const itemId = item.id as string;\n const id = `${callId}|${itemId}`;\n const tc = toolCalls.get(id);\n if (tc) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n result.push({\n type: \"toolcall_done\",\n id: tc.id,\n name: tc.name,\n args,\n });\n }\n }\n }\n\n // Response completed\n if (type === \"response.completed\" || type === \"response.done\") {\n const resp = event.response as Record<string, unknown> | undefined;\n const usage = resp?.usage as Record<string, number> | undefined;\n if (usage) {\n inputTokens = usage.input_tokens ?? 0;\n outputTokens = usage.output_tokens ?? 0;\n }\n }\n }\n\n // Finalize content parts\n if (textAccum) {\n contentParts.push({ type: \"text\", text: textAccum });\n }\n\n for (const [, tc] of toolCalls) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.argsJson) as Record<string, unknown>;\n } catch {\n /* malformed JSON */\n }\n const toolCall: ToolCall = {\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n args,\n };\n contentParts.push(toolCall);\n }\n\n const hasToolCalls = contentParts.some((p) => p.type === \"tool_call\");\n const stopReason = hasToolCalls ? \"tool_use\" : \"end_turn\";\n\n const streamResponse: StreamResponse = {\n message: {\n role: \"assistant\",\n content: contentParts.length > 0 ? contentParts : textAccum || \"\",\n },\n stopReason,\n usage: { inputTokens, outputTokens },\n };\n\n result.push({ type: \"done\", stopReason });\n result.complete(streamResponse);\n}\n\n// ── SSE Parser ─────────────────────────────────────────────\n\nasync function* parseSSE(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<Record<string, unknown>> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let idx = buffer.indexOf(\"\\n\\n\");\n while (idx !== -1) {\n const chunk = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n\n const dataLines = chunk\n .split(\"\\n\")\n .filter((l) => l.startsWith(\"data:\"))\n .map((l) => l.slice(5).trim());\n\n if (dataLines.length > 0) {\n const data = dataLines.join(\"\\n\").trim();\n if (data && data !== \"[DONE]\") {\n try {\n yield JSON.parse(data) as Record<string, unknown>;\n } catch {\n // skip malformed JSON\n }\n }\n }\n idx = buffer.indexOf(\"\\n\\n\");\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n// ── Message Conversion ─────────────────────────────────────\n\n/**\n * Remap tool call IDs that don't match Codex API's expected prefix.\n * Codex expects IDs starting with `fc_` — Anthropic uses `toolu_*` which gets rejected.\n */\nfunction remapCodexId(id: string, idMap: Map<string, string>): string {\n if (id.startsWith(\"fc_\") || id.startsWith(\"fc-\")) return id;\n const existing = idMap.get(id);\n if (existing) return existing;\n const mapped = `fc_${id.replace(/^toolu_/, \"\")}`;\n idMap.set(id, mapped);\n return mapped;\n}\n\nfunction toCodexInput(messages: Message[]): { system: string | undefined; input: unknown[] } {\n let system: string | undefined;\n const input: unknown[] = [];\n const idMap = new Map<string, string>();\n\n for (const msg of messages) {\n if (msg.role === \"system\") {\n system = msg.content;\n continue;\n }\n\n if (msg.role === \"user\") {\n const content =\n typeof msg.content === \"string\"\n ? [{ type: \"input_text\", text: msg.content }]\n : msg.content.map((part) => {\n if (part.type === \"text\") return { type: \"input_text\", text: part.text };\n return {\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${part.mediaType};base64,${part.data}`,\n };\n });\n input.push({ role: \"user\", content });\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (typeof msg.content === \"string\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: msg.content, annotations: [] }],\n status: \"completed\",\n });\n continue;\n }\n\n for (const part of msg.content) {\n if (part.type === \"text\") {\n input.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: part.text, annotations: [] }],\n status: \"completed\",\n });\n } else if (part.type === \"tool_call\") {\n const [callId, itemId] = part.id.includes(\"|\")\n ? part.id.split(\"|\", 2)\n : [part.id, part.id];\n input.push({\n type: \"function_call\",\n id: remapCodexId(itemId, idMap),\n call_id: remapCodexId(callId, idMap),\n name: part.name,\n arguments: JSON.stringify(part.args),\n });\n }\n // thinking parts are skipped for codex input\n }\n continue;\n }\n\n if (msg.role === \"tool\") {\n for (const result of msg.content) {\n const [callId] = result.toolCallId.includes(\"|\")\n ? result.toolCallId.split(\"|\", 2)\n : [result.toolCallId];\n input.push({\n type: \"function_call_output\",\n call_id: remapCodexId(callId, idMap),\n output: result.content,\n });\n }\n }\n }\n\n return { system, input };\n}\n\n// ── Tool Conversion ────────────────────────────────────────\n\nfunction toCodexTools(tools: Tool[]): unknown[] {\n return tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.rawInputSchema ?? zodToJsonSchema(tool.parameters),\n strict: null,\n }));\n}\n\n// ── Error Handling ─────────────────────────────────────────\n\nfunction toError(err: unknown): ProviderError {\n if (err instanceof ProviderError) return err;\n if (err instanceof Error) {\n return new ProviderError(\"openai\", err.message, { cause: err });\n }\n return new ProviderError(\"openai\", String(err));\n}\n","import type { StreamOptions } from \"./types.js\";\nimport { GGAIError } from \"./errors.js\";\nimport type { StreamResult } from \"./utils/event-stream.js\";\nimport { streamAnthropic } from \"./providers/anthropic.js\";\nimport { streamOpenAI } from \"./providers/openai.js\";\nimport { streamOpenAICodex } from \"./providers/openai-codex.js\";\n\n/**\n * Unified streaming entry point. Returns a StreamResult that is both\n * an async iterable (for streaming events) and thenable (await for\n * the final response).\n *\n * ```ts\n * // Stream events\n * for await (const event of stream({ provider: \"anthropic\", model: \"claude-sonnet-4-6\", messages })) {\n * if (event.type === \"text_delta\") process.stdout.write(event.text);\n * }\n *\n * // Or just await the final message\n * const response = await stream({ provider: \"openai\", model: \"gpt-4.1\", messages });\n * ```\n */\nexport function stream(options: StreamOptions): StreamResult {\n switch (options.provider) {\n case \"anthropic\":\n return streamAnthropic(options);\n case \"openai\":\n // Use codex endpoint for OAuth tokens (have accountId)\n if (options.accountId) {\n return streamOpenAICodex(options);\n }\n return streamOpenAI(options);\n case \"glm\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.z.ai/api/coding/paas/v4\",\n });\n case \"moonshot\":\n return streamOpenAI({\n ...options,\n baseUrl: options.baseUrl ?? \"https://api.moonshot.ai/v1\",\n });\n default:\n throw new GGAIError(\n `Unknown provider: ${options.provider as string}. Supported: \"anthropic\", \"openai\", \"glm\", \"moonshot\"`,\n );\n }\n}\n"],"mappings":";AAAO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gBAAN,cAA4B,UAAU;AAAA,EAClC;AAAA,EACA;AAAA,EAET,YACE,UACA,SACA,SACA;AACA,UAAM,IAAI,Q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,YAAM,IAAI;AAAA,QACR,qBAAqB,QAAQ,QAAkB;AAAA,MACjD;AAAA,EACJ;AACF;","names":["stream","runStream","toError","stream","runStream","toError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kenkaiiii/gg-ai",
|
|
3
|
-
"version": "4.2.
|
|
3
|
+
"version": "4.2.26",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Unified LLM streaming API for Anthropic and OpenAI",
|
|
6
6
|
"license": "MIT",
|
|
@@ -24,12 +24,12 @@
|
|
|
24
24
|
],
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@anthropic-ai/sdk": "^0.78.0",
|
|
27
|
-
"openai": "^6.
|
|
27
|
+
"openai": "^6.29.0",
|
|
28
28
|
"zod": "^4.3.6"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"typescript": "^5.9.3",
|
|
32
|
-
"vitest": "^4.0
|
|
32
|
+
"vitest": "^4.1.0"
|
|
33
33
|
},
|
|
34
34
|
"publishConfig": {
|
|
35
35
|
"access": "public"
|