@kenkaiiii/gg-ai 4.2.12 → 4.2.14
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 +23 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +23 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -312,8 +312,17 @@ function toAnthropicThinking(level, maxTokens, model) {
|
|
|
312
312
|
maxTokens: maxTokens + budget
|
|
313
313
|
};
|
|
314
314
|
}
|
|
315
|
+
function remapToolCallId(id, idMap) {
|
|
316
|
+
if (id.startsWith("call_")) return id;
|
|
317
|
+
const existing = idMap.get(id);
|
|
318
|
+
if (existing) return existing;
|
|
319
|
+
const mapped = `call_${id.replace(/^toolu_/, "")}`;
|
|
320
|
+
idMap.set(id, mapped);
|
|
321
|
+
return mapped;
|
|
322
|
+
}
|
|
315
323
|
function toOpenAIMessages(messages) {
|
|
316
324
|
const out = [];
|
|
325
|
+
const idMap = /* @__PURE__ */ new Map();
|
|
317
326
|
for (const msg of messages) {
|
|
318
327
|
if (msg.role === "system") {
|
|
319
328
|
out.push({ role: "system", content: msg.content });
|
|
@@ -346,7 +355,7 @@ function toOpenAIMessages(messages) {
|
|
|
346
355
|
(p) => p.type === "tool_call"
|
|
347
356
|
).map(
|
|
348
357
|
(tc) => ({
|
|
349
|
-
id: tc.id,
|
|
358
|
+
id: remapToolCallId(tc.id, idMap),
|
|
350
359
|
type: "function",
|
|
351
360
|
function: { name: tc.name, arguments: JSON.stringify(tc.args) }
|
|
352
361
|
})
|
|
@@ -368,7 +377,7 @@ function toOpenAIMessages(messages) {
|
|
|
368
377
|
for (const result of msg.content) {
|
|
369
378
|
out.push({
|
|
370
379
|
role: "tool",
|
|
371
|
-
tool_call_id: result.toolCallId,
|
|
380
|
+
tool_call_id: remapToolCallId(result.toolCallId, idMap),
|
|
372
381
|
content: result.content
|
|
373
382
|
});
|
|
374
383
|
}
|
|
@@ -975,9 +984,18 @@ async function* parseSSE(body) {
|
|
|
975
984
|
reader.releaseLock();
|
|
976
985
|
}
|
|
977
986
|
}
|
|
987
|
+
function remapCodexId(id, idMap) {
|
|
988
|
+
if (id.startsWith("fc_") || id.startsWith("fc-")) return id;
|
|
989
|
+
const existing = idMap.get(id);
|
|
990
|
+
if (existing) return existing;
|
|
991
|
+
const mapped = `fc_${id.replace(/^toolu_/, "")}`;
|
|
992
|
+
idMap.set(id, mapped);
|
|
993
|
+
return mapped;
|
|
994
|
+
}
|
|
978
995
|
function toCodexInput(messages) {
|
|
979
996
|
let system;
|
|
980
997
|
const input = [];
|
|
998
|
+
const idMap = /* @__PURE__ */ new Map();
|
|
981
999
|
for (const msg of messages) {
|
|
982
1000
|
if (msg.role === "system") {
|
|
983
1001
|
system = msg.content;
|
|
@@ -1017,8 +1035,8 @@ function toCodexInput(messages) {
|
|
|
1017
1035
|
const [callId, itemId] = part.id.includes("|") ? part.id.split("|", 2) : [part.id, part.id];
|
|
1018
1036
|
input.push({
|
|
1019
1037
|
type: "function_call",
|
|
1020
|
-
id: itemId,
|
|
1021
|
-
call_id: callId,
|
|
1038
|
+
id: remapCodexId(itemId, idMap),
|
|
1039
|
+
call_id: remapCodexId(callId, idMap),
|
|
1022
1040
|
name: part.name,
|
|
1023
1041
|
arguments: JSON.stringify(part.args)
|
|
1024
1042
|
});
|
|
@@ -1031,7 +1049,7 @@ function toCodexInput(messages) {
|
|
|
1031
1049
|
const [callId] = result.toolCallId.includes("|") ? result.toolCallId.split("|", 2) : [result.toolCallId];
|
|
1032
1050
|
input.push({
|
|
1033
1051
|
type: "function_call_output",
|
|
1034
|
-
call_id: callId,
|
|
1052
|
+
call_id: remapCodexId(callId, idMap),
|
|
1035
1053
|
output: result.content
|
|
1036
1054
|
});
|
|
1037
1055
|
}
|
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 50k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 50_000) {\n this.queue.splice(0, this.queue.length - 25_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\nexport function toOpenAIMessages(messages: Message[]): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\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 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: tc.id,\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: result.toolCallId,\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 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 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);\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(options.temperature != null && !options.thinking\n ? { temperature: options.temperature }\n : {}),\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): 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(\"openai\", msg, {\n statusCode: err.status,\n cause: err,\n });\n }\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 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\nfunction toCodexInput(messages: Message[]): { system: string | undefined; input: unknown[] } {\n let system: string | undefined;\n const input: unknown[] = [];\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: itemId,\n call_id: callId,\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: callId,\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/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: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,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 });\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 50k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 50_000) {\n this.queue.splice(0, this.queue.length - 25_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(messages: Message[]): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\n const idMap = new Map<string, string>();\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 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 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 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);\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(options.temperature != null && !options.thinking\n ? { temperature: options.temperature }\n : {}),\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): 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(\"openai\", msg, {\n statusCode: err.status,\n cause: err,\n });\n }\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 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/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,IA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KAAK,UAAU;AAAA,IAClE,QAAQ;AAAA,EACV,EAAE;AACJ;AAIA,SAASD,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":["Anthropic","stream","runStream","toError","OpenAI","stream","runStream","toError","os"]}
|
package/dist/index.js
CHANGED
|
@@ -272,8 +272,17 @@ function toAnthropicThinking(level, maxTokens, model) {
|
|
|
272
272
|
maxTokens: maxTokens + budget
|
|
273
273
|
};
|
|
274
274
|
}
|
|
275
|
+
function remapToolCallId(id, idMap) {
|
|
276
|
+
if (id.startsWith("call_")) return id;
|
|
277
|
+
const existing = idMap.get(id);
|
|
278
|
+
if (existing) return existing;
|
|
279
|
+
const mapped = `call_${id.replace(/^toolu_/, "")}`;
|
|
280
|
+
idMap.set(id, mapped);
|
|
281
|
+
return mapped;
|
|
282
|
+
}
|
|
275
283
|
function toOpenAIMessages(messages) {
|
|
276
284
|
const out = [];
|
|
285
|
+
const idMap = /* @__PURE__ */ new Map();
|
|
277
286
|
for (const msg of messages) {
|
|
278
287
|
if (msg.role === "system") {
|
|
279
288
|
out.push({ role: "system", content: msg.content });
|
|
@@ -306,7 +315,7 @@ function toOpenAIMessages(messages) {
|
|
|
306
315
|
(p) => p.type === "tool_call"
|
|
307
316
|
).map(
|
|
308
317
|
(tc) => ({
|
|
309
|
-
id: tc.id,
|
|
318
|
+
id: remapToolCallId(tc.id, idMap),
|
|
310
319
|
type: "function",
|
|
311
320
|
function: { name: tc.name, arguments: JSON.stringify(tc.args) }
|
|
312
321
|
})
|
|
@@ -328,7 +337,7 @@ function toOpenAIMessages(messages) {
|
|
|
328
337
|
for (const result of msg.content) {
|
|
329
338
|
out.push({
|
|
330
339
|
role: "tool",
|
|
331
|
-
tool_call_id: result.toolCallId,
|
|
340
|
+
tool_call_id: remapToolCallId(result.toolCallId, idMap),
|
|
332
341
|
content: result.content
|
|
333
342
|
});
|
|
334
343
|
}
|
|
@@ -935,9 +944,18 @@ async function* parseSSE(body) {
|
|
|
935
944
|
reader.releaseLock();
|
|
936
945
|
}
|
|
937
946
|
}
|
|
947
|
+
function remapCodexId(id, idMap) {
|
|
948
|
+
if (id.startsWith("fc_") || id.startsWith("fc-")) return id;
|
|
949
|
+
const existing = idMap.get(id);
|
|
950
|
+
if (existing) return existing;
|
|
951
|
+
const mapped = `fc_${id.replace(/^toolu_/, "")}`;
|
|
952
|
+
idMap.set(id, mapped);
|
|
953
|
+
return mapped;
|
|
954
|
+
}
|
|
938
955
|
function toCodexInput(messages) {
|
|
939
956
|
let system;
|
|
940
957
|
const input = [];
|
|
958
|
+
const idMap = /* @__PURE__ */ new Map();
|
|
941
959
|
for (const msg of messages) {
|
|
942
960
|
if (msg.role === "system") {
|
|
943
961
|
system = msg.content;
|
|
@@ -977,8 +995,8 @@ function toCodexInput(messages) {
|
|
|
977
995
|
const [callId, itemId] = part.id.includes("|") ? part.id.split("|", 2) : [part.id, part.id];
|
|
978
996
|
input.push({
|
|
979
997
|
type: "function_call",
|
|
980
|
-
id: itemId,
|
|
981
|
-
call_id: callId,
|
|
998
|
+
id: remapCodexId(itemId, idMap),
|
|
999
|
+
call_id: remapCodexId(callId, idMap),
|
|
982
1000
|
name: part.name,
|
|
983
1001
|
arguments: JSON.stringify(part.args)
|
|
984
1002
|
});
|
|
@@ -991,7 +1009,7 @@ function toCodexInput(messages) {
|
|
|
991
1009
|
const [callId] = result.toolCallId.includes("|") ? result.toolCallId.split("|", 2) : [result.toolCallId];
|
|
992
1010
|
input.push({
|
|
993
1011
|
type: "function_call_output",
|
|
994
|
-
call_id: callId,
|
|
1012
|
+
call_id: remapCodexId(callId, idMap),
|
|
995
1013
|
output: result.content
|
|
996
1014
|
});
|
|
997
1015
|
}
|
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 50k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 50_000) {\n this.queue.splice(0, this.queue.length - 25_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\nexport function toOpenAIMessages(messages: Message[]): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\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 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: tc.id,\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: result.toolCallId,\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 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 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);\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(options.temperature != null && !options.thinking\n ? { temperature: options.temperature }\n : {}),\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): 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(\"openai\", msg, {\n statusCode: err.status,\n cause: err,\n });\n }\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 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\nfunction toCodexInput(messages: Message[]): { system: string | undefined; input: unknown[] } {\n let system: string | undefined;\n const input: unknown[] = [];\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: itemId,\n call_id: callId,\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: callId,\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/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,QAAQ,KAAK,OAAO,IAAI,EAAE,OAAO,SAAS,MAAM,CAAC;AAC3D,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,aAAa,SAAS;AAAA,EAC7B;AACF;;;ACrBA,OAAO,eAAe;;;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,IAAM;AAAA,IACjD;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,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,QAAQ,OAAO,aAAa,IAAsB;AAChD,QAAI,QAAQ;AACZ,WAAO,MAAM;AACX,aAAO,QAAQ,KAAK,MAAM,QAAQ;AAChC,cAAM,KAAK,MAAM,OAAO;AAAA,MAC1B;AAEA,WAAK,MAAM,OAAO,GAAG,KAAK;AAC1B,cAAQ;AACR,UAAI,KAAK,MAA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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 });\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 50k unconsumed events, drop oldest\n // to prevent OOM when consumer is blocked/slow\n if (this.queue.length > 50_000) {\n this.queue.splice(0, this.queue.length - 25_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(messages: Message[]): OpenAI.ChatCompletionMessageParam[] {\n const out: OpenAI.ChatCompletionMessageParam[] = [];\n const idMap = new Map<string, string>();\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 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 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 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);\n\n const params: OpenAI.ChatCompletionCreateParams = {\n model: options.model,\n messages,\n stream: true,\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(options.temperature != null && !options.thinking\n ? { temperature: options.temperature }\n : {}),\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): 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(\"openai\", msg, {\n statusCode: err.status,\n cause: err,\n });\n }\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 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/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,QAAQ,KAAK,OAAO,IAAI,EAAE,OAAO,SAAS,MAAM,CAAC;AAC3D,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,aAAa,SAAS;AAAA,EAC7B;AACF;;;ACrBA,OAAO,eAAe;;;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,IAAM;AAAA,IACjD;AACA,SAAK,MAAM,KAAK,KAAK;AACrB,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,QAAc;AACZ,SAAK,OAA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