pagegraph 0.13.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -41
- package/dist/anthropic-messages-TqKpKmfW.js +1067 -0
- package/dist/anthropic-messages-TqKpKmfW.js.map +1 -0
- package/dist/audit.d.ts +2 -0
- package/dist/audit.js +1 -1
- package/dist/audit.js.map +1 -1
- package/dist/azure-openai-responses-DJjBLwoI.js +231 -0
- package/dist/azure-openai-responses-DJjBLwoI.js.map +1 -0
- package/dist/cli.js +10487 -38044
- package/dist/cli.js.map +1 -1
- package/dist/cloudflare-workers-ai-system-one-f3ZrvNYZ.js +41 -0
- package/dist/cloudflare-workers-ai-system-one-f3ZrvNYZ.js.map +1 -0
- package/dist/config.d.ts +6 -6
- package/dist/config.js.map +1 -1
- package/dist/diagnostics-Wt5faNDM.js +108 -0
- package/dist/diagnostics-Wt5faNDM.js.map +1 -0
- package/dist/dist-cFoAzruL.js +4794 -0
- package/dist/dist-cFoAzruL.js.map +1 -0
- package/dist/env-api-keys-C-OA0yM-.js +124 -0
- package/dist/env-api-keys-C-OA0yM-.js.map +1 -0
- package/dist/error-body-CyiejW4b.js +103 -0
- package/dist/error-body-CyiejW4b.js.map +1 -0
- package/dist/github-copilot-headers-CEpMOpQF.js +24 -0
- package/dist/github-copilot-headers-CEpMOpQF.js.map +1 -0
- package/dist/google-generative-ai-BxABKIKO.js +330 -0
- package/dist/google-generative-ai-BxABKIKO.js.map +1 -0
- package/dist/google-shared-0gpM2jFi.js +19471 -0
- package/dist/google-shared-0gpM2jFi.js.map +1 -0
- package/dist/google-vertex-D8Eb5cbu.js +376 -0
- package/dist/google-vertex-D8Eb5cbu.js.map +1 -0
- package/dist/hash-Dp7EzZUo.js +18 -0
- package/dist/hash-Dp7EzZUo.js.map +1 -0
- package/dist/headers-BRNMVpzu.js +19 -0
- package/dist/headers-BRNMVpzu.js.map +1 -0
- package/dist/json-parse-C10znB7l.js +383 -0
- package/dist/json-parse-C10znB7l.js.map +1 -0
- package/dist/mistral-conversations-CvaqBWjR.js +690 -0
- package/dist/mistral-conversations-CvaqBWjR.js.map +1 -0
- package/dist/models-DcT5qOEL.js +1203 -0
- package/dist/models-DcT5qOEL.js.map +1 -0
- package/dist/node-Ccvru9GE.js +26 -0
- package/dist/node-Ccvru9GE.js.map +1 -0
- package/dist/node-MEosBOF2.js +2403 -0
- package/dist/node-MEosBOF2.js.map +1 -0
- package/dist/openai-BCBEd2eO.js +17350 -0
- package/dist/openai-BCBEd2eO.js.map +1 -0
- package/dist/openai-codex-responses-vJqxeeRC.js +1268 -0
- package/dist/openai-codex-responses-vJqxeeRC.js.map +1 -0
- package/dist/openai-completions-Cb_fRAbI.js +989 -0
- package/dist/openai-completions-Cb_fRAbI.js.map +1 -0
- package/dist/openai-prompt-cache-Bc6qNWt0.js +10 -0
- package/dist/openai-prompt-cache-Bc6qNWt0.js.map +1 -0
- package/dist/openai-responses-sDuh82G5.js +268 -0
- package/dist/openai-responses-sDuh82G5.js.map +1 -0
- package/dist/openai-responses-shared-mhuo1Jov.js +599 -0
- package/dist/openai-responses-shared-mhuo1Jov.js.map +1 -0
- package/dist/openrouter-images-CRmBkzpX.js +127 -0
- package/dist/openrouter-images-CRmBkzpX.js.map +1 -0
- package/dist/pi-D3mMmYey.js +56805 -0
- package/dist/pi-D3mMmYey.js.map +1 -0
- package/dist/pi-messages-CejiVYvO.js +308 -0
- package/dist/pi-messages-CejiVYvO.js.map +1 -0
- package/dist/provider-env-t38GK5FF.js +39 -0
- package/dist/provider-env-t38GK5FF.js.map +1 -0
- package/dist/provider-retry-DzKoh1X7.js +80 -0
- package/dist/provider-retry-DzKoh1X7.js.map +1 -0
- package/dist/rolldown-runtime-B-lAHAz2.js +37 -0
- package/dist/sanitize-unicode-Ds14l9Om.js +28 -0
- package/dist/sanitize-unicode-Ds14l9Om.js.map +1 -0
- package/dist/sdk-C9_wiO6w.js +12503 -0
- package/dist/sdk-C9_wiO6w.js.map +1 -0
- package/dist/state-BuJP_3Lr.js +28102 -0
- package/dist/state-BuJP_3Lr.js.map +1 -0
- package/dist/system-one-shared-Dl10ZF7Z.js +167 -0
- package/dist/system-one-shared-Dl10ZF7Z.js.map +1 -0
- package/dist/transform-messages-BLJ8EfK6.js +468 -0
- package/dist/transform-messages-BLJ8EfK6.js.map +1 -0
- package/dist/typesafe-system-one-CwEWMV8P.js +25 -0
- package/dist/typesafe-system-one-CwEWMV8P.js.map +1 -0
- package/package.json +4 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-responses-shared-mhuo1Jov.js","names":["_exhaustive"],"sources":["../node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js"],"sourcesContent":["import { calculateCost } from \"../models.js\";\nimport { shortHash } from \"../utils/hash.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { getSystemMessageText, renderSystemMessageUpdate } from \"../utils/text.js\";\nimport { resolveTranscript, resolveTranscriptTools } from \"../utils/transcript.js\";\nimport { appendGrammarToolInputJsonDelta, getGrammarToolInput, getJsonSchemaToolParameters, resolveGrammarConstrainedSampling, resolveJsonSchemaStrictSampling, } from \"./constrained-sampling.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n// =============================================================================\n// Utilities\n// =============================================================================\nfunction encodeTextSignatureV1(id, phase) {\n const payload = { v: 1, id };\n if (phase)\n payload.phase = phase;\n return JSON.stringify(payload);\n}\nfunction parseTextSignature(signature) {\n if (!signature)\n return undefined;\n if (signature.startsWith(\"{\")) {\n try {\n const parsed = JSON.parse(signature);\n if (parsed.v === 1 && typeof parsed.id === \"string\") {\n if (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n return { id: parsed.id, phase: parsed.phase };\n }\n return { id: parsed.id };\n }\n }\n catch {\n // Fall through to legacy plain-string handling.\n }\n }\n return { id: signature };\n}\nfunction convertToolResultOutput(model, content) {\n const textResult = content\n .filter((c) => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n const images = content.filter((c) => c.type === \"image\");\n const hasText = textResult.length > 0;\n if (images.length === 0 || !model.input.includes(\"image\")) {\n return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? \"(see attached image)\" : \"(no tool output)\");\n }\n const output = [];\n if (hasText) {\n output.push({ type: \"input_text\", text: sanitizeSurrogates(textResult) });\n }\n for (const image of images) {\n output.push({\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${image.mimeType};base64,${image.data}`,\n });\n }\n return output;\n}\n// =============================================================================\n// Message conversion\n// =============================================================================\nexport function convertResponsesMessages(model, context, allowedToolCallProviders, options) {\n const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);\n const messages = [];\n const normalizeIdPart = (part) => {\n const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n return normalized.replace(/_+$/, \"\");\n };\n const buildForeignResponsesItemId = (itemId) => {\n const normalized = `fc_${shortHash(itemId)}`;\n return normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n };\n const normalizeToolCallId = (id, _targetModel, source) => {\n if (!allowedToolCallProviders.has(model.provider))\n return normalizeIdPart(id);\n if (!id.includes(\"|\"))\n return normalizeIdPart(id);\n const [callId, itemId] = id.split(\"|\");\n const normalizedCallId = normalizeIdPart(callId);\n const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n // OpenAI Responses API requires item id to start with \"fc\"\n if (!normalizedItemId.startsWith(\"fc_\")) {\n normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n }\n return `${normalizedCallId}|${normalizedItemId}`;\n };\n const transformedMessages = transformMessages(normalizedContext.messages, model, normalizeToolCallId);\n const transcriptTools = resolveTranscriptTools(normalizedContext.messages, (options?.supportsAdditionalTools ?? false) || (options?.supportsToolSearch ?? false));\n const appendSystemToolAdditions = (message, seed) => {\n const tools = transcriptTools.anchorsAdditions ? (message.toolsAdded ?? []) : [];\n if (tools.length === 0)\n return;\n if (options?.supportsAdditionalTools) {\n messages.push({\n type: \"additional_tools\",\n role: \"developer\",\n tools: convertResponsesTools(tools, options.toolOptions),\n });\n return;\n }\n if (!options?.supportsToolSearch)\n return;\n const names = tools.map((tool) => tool.name);\n const callId = `pi_tool_load_${shortHash(`${seed}:${names.join(\",\")}`)}`;\n messages.push({\n type: \"tool_search_call\",\n call_id: callId,\n execution: \"client\",\n status: \"completed\",\n arguments: { query: names.join(\" \"), limit: names.length },\n });\n messages.push({\n type: \"tool_search_output\",\n call_id: callId,\n execution: \"client\",\n status: \"completed\",\n tools: convertResponsesTools(tools, { ...options.toolOptions, toolSearchResult: true }),\n });\n };\n const includeInitialSystemMessage = options?.includeSystemPrompt ?? true;\n const compat = model.compat;\n const instructionRole = model.reasoning && compat?.supportsDeveloperRole !== false ? \"developer\" : \"system\";\n let msgIndex = 0;\n let sourceIndex = 0;\n for (const msg of transformedMessages) {\n const isLeadingSystemMessage = sourceIndex++ === 0 && msg.role === \"system\";\n if (msg.role === \"system\") {\n if (!isLeadingSystemMessage)\n appendSystemToolAdditions(msg, `system:${msgIndex}`);\n if (!isLeadingSystemMessage || includeInitialSystemMessage) {\n const text = isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg);\n if (text.length > 0) {\n messages.push({ role: instructionRole, content: sanitizeSurrogates(text) });\n }\n }\n }\n else if (msg.role === \"user\") {\n if (typeof msg.content === \"string\") {\n messages.push({\n role: \"user\",\n content: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n });\n }\n else {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"input_text\",\n text: sanitizeSurrogates(item.text),\n };\n }\n return {\n type: \"input_image\",\n detail: \"auto\",\n image_url: `data:${item.mimeType};base64,${item.data}`,\n };\n });\n if (content.length === 0)\n continue;\n messages.push({\n role: \"user\",\n content,\n });\n }\n }\n else if (msg.role === \"assistant\") {\n const output = [];\n const assistantMsg = msg;\n const isSameProviderAndApi = assistantMsg.provider === model.provider && assistantMsg.api === model.api;\n const isSameModel = isSameProviderAndApi && assistantMsg.model === model.id;\n const isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model.id;\n let textBlockIndex = 0;\n for (const block of msg.content) {\n if (block.type === \"thinking\") {\n if (block.thinkingSignature) {\n const reasoningItem = JSON.parse(block.thinkingSignature);\n output.push(reasoningItem);\n }\n }\n else if (block.type === \"text\") {\n const textBlock = block;\n const parsedSignature = parseTextSignature(textBlock.textSignature);\n const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;\n textBlockIndex++;\n // OpenAI requires id to be max 64 characters\n let msgId = parsedSignature?.id;\n if (!msgId) {\n msgId = fallbackMessageId;\n }\n else if (msgId.length > 64) {\n msgId = `msg_${shortHash(msgId)}`;\n }\n output.push({\n type: \"message\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n status: \"completed\",\n id: msgId,\n phase: parsedSignature?.phase,\n });\n }\n else if (block.type === \"toolCall\") {\n const toolCall = block;\n const [callId, itemIdRaw] = toolCall.id.split(\"|\");\n const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);\n let itemId = itemIdRaw;\n // For different-model messages, set id to undefined to avoid pairing validation.\n // OpenAI tracks which item IDs were paired with rs_xxx reasoning items.\n // By omitting the id, we avoid triggering that validation (like cross-provider does).\n // Also drop ids that do not match the replayed item type: function_call ids must be fc_*\n // and custom_tool_call ids must be ctc_*. Foreign tool call ids are normalized to fc_*, and\n // a call can switch between the two types when grammar tool support differs.\n const itemIdPrefix = customInputProperty === undefined ? \"fc_\" : \"ctc_\";\n if (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) {\n itemId = undefined;\n }\n if (customInputProperty !== undefined) {\n output.push({\n type: \"custom_tool_call\",\n id: itemId,\n call_id: callId,\n name: toolCall.name,\n input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty)),\n ...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\n });\n }\n else {\n output.push({\n type: \"function_call\",\n id: itemId,\n call_id: callId,\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n ...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\n });\n }\n }\n }\n if (output.length === 0)\n continue;\n messages.push(...output);\n }\n else if (msg.role === \"toolResult\") {\n const [callId] = msg.toolCallId.split(\"|\");\n const output = convertToolResultOutput(model, msg.content);\n if (options?.grammarToolInputProperties?.has(msg.toolName)) {\n messages.push({\n type: \"custom_tool_call_output\",\n call_id: callId,\n output,\n });\n }\n else {\n messages.push({\n type: \"function_call_output\",\n call_id: callId,\n output,\n });\n }\n }\n if (!isLeadingSystemMessage)\n msgIndex++;\n }\n return messages;\n}\n// =============================================================================\n// Tool conversion\n// =============================================================================\nexport function convertResponsesTools(tools, options) {\n const defaultStrict = options?.strict === undefined ? false : options.strict;\n const supportsStrictMode = options?.supportsStrictMode ?? true;\n const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;\n return tools.map((tool) => {\n const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);\n if (grammar) {\n return {\n type: \"custom\",\n name: tool.name,\n description: tool.description,\n format: {\n type: \"grammar\",\n syntax: grammar.format,\n definition: grammar.definition,\n },\n ...(options?.toolSearchResult ? { defer_loading: true } : {}),\n };\n }\n const constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n const strict = constrainedStrict ?? defaultStrict;\n const functionTool = {\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: getJsonSchemaToolParameters(tool, strict === true),\n ...(options?.toolSearchResult ? { defer_loading: true } : {}),\n };\n if (supportsStrictMode) {\n functionTool.strict = strict;\n }\n return functionTool;\n });\n}\nfunction getCustomToolCallInput(block) {\n const property = block.customInput?.property;\n if (property === undefined)\n return \"\";\n const value = block.arguments[property];\n return typeof value === \"string\" ? value : \"\";\n}\nfunction appendCustomToolCallInput(block, nextInput, close) {\n const customInput = block.customInput;\n if (!customInput)\n return undefined;\n const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);\n block.arguments = { [customInput.property]: nextInput };\n return delta;\n}\nexport async function processResponsesStream(openaiStream, output, stream, model, options) {\n let sawTerminalResponseEvent = false;\n const outputSlots = new Map();\n const reasoningBlocksById = new Map();\n const applyMessagePhaseStopReason = (item) => {\n if (item.type === \"message\" && item.phase === \"final_answer\") {\n output.stopReason = \"stop\";\n }\n };\n const getSlot = (outputIndex, type) => {\n const slot = outputSlots.get(outputIndex);\n return slot?.type === type ? slot : undefined;\n };\n const pushToolCallDelta = (slot, delta) => {\n if (delta === undefined)\n return;\n stream.push({\n type: \"toolcall_delta\",\n contentIndex: slot.contentIndex,\n delta,\n partial: output,\n });\n };\n const createSlot = (outputIndex, item) => {\n if (item.type === \"reasoning\") {\n const block = { type: \"thinking\", thinking: \"\" };\n output.content.push(block);\n const slot = {\n type: \"thinking\",\n block,\n contentIndex: output.content.length - 1,\n };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"thinking_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n if (item.type === \"message\") {\n applyMessagePhaseStopReason(item);\n const block = { type: \"text\", text: \"\" };\n output.content.push(block);\n const slot = { type: \"text\", block, contentIndex: output.content.length - 1 };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"text_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n if (item.type === \"function_call\") {\n const block = {\n type: \"toolCall\",\n id: `${item.call_id}|${item.id}`,\n name: item.name,\n arguments: {},\n ...(item.namespace !== undefined ? { namespace: item.namespace } : {}),\n partialJson: item.arguments || \"\",\n };\n output.content.push(block);\n const slot = {\n type: \"toolCall\",\n block,\n contentIndex: output.content.length - 1,\n };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n if (item.type === \"custom_tool_call\") {\n const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? \"input\";\n const input = item.input || \"\";\n const block = {\n type: \"toolCall\",\n id: `${item.call_id}|${item.id}`,\n name: item.name,\n arguments: { [inputProperty]: input },\n ...(item.namespace !== undefined ? { namespace: item.namespace } : {}),\n customInput: {\n property: inputProperty,\n jsonBuffer: { input: \"\", started: false, closed: false },\n },\n };\n output.content.push(block);\n const slot = {\n type: \"toolCall\",\n block,\n contentIndex: output.content.length - 1,\n };\n outputSlots.set(outputIndex, slot);\n stream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n return slot;\n }\n return undefined;\n };\n const getOrCreateSlot = (outputIndex, item) => {\n return outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);\n };\n // Azure OpenAI can omit reasoning.encrypted_content from response.output_item.done\n // and provide it only in response.completed.response.output. Backfill the\n // persisted reasoning signature from the terminal response to keep store:false\n // multi-turn replay stateless. See https://github.com/earendil-works/pi/issues/6409.\n const backfillReasoningSignatures = (responseOutput) => {\n for (const item of responseOutput) {\n if (item.type !== \"reasoning\" || !item.encrypted_content)\n continue;\n const block = reasoningBlocksById.get(item.id);\n if (!block?.thinkingSignature)\n continue;\n const storedItem = JSON.parse(block.thinkingSignature);\n if (storedItem.encrypted_content)\n continue;\n block.thinkingSignature = JSON.stringify({\n ...storedItem,\n encrypted_content: item.encrypted_content,\n });\n }\n };\n const finalizeResponse = (response) => {\n sawTerminalResponseEvent = true;\n backfillReasoningSignatures(response.output ?? []);\n if (response?.id) {\n output.responseId = response.id;\n }\n if (response?.usage) {\n const inputDetails = response.usage.input_tokens_details;\n const cachedTokens = inputDetails?.cached_tokens || 0;\n const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;\n output.usage = {\n // OpenAI includes cached and cache-write tokens in input_tokens, so subtract both.\n input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),\n output: response.usage.output_tokens || 0,\n cacheRead: cachedTokens,\n cacheWrite: cacheWriteTokens,\n reasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,\n totalTokens: response.usage.total_tokens || 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n }\n calculateCost(model, output.usage);\n if (options?.applyServiceTierPricing) {\n const serviceTier = options.resolveServiceTier\n ? options.resolveServiceTier(response?.service_tier, options.serviceTier)\n : (response?.service_tier ?? options.serviceTier);\n options.applyServiceTierPricing(output.usage, serviceTier);\n }\n // Map status to stop reason. For incomplete responses, retain the provider's\n // specific reason so max-output truncation and content filtering stay distinct.\n const status = response?.status;\n const incompleteDetails = response?.incomplete_details;\n const incompleteReason = typeof incompleteDetails?.reason === \"string\" ? incompleteDetails.reason : undefined;\n output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;\n const mappedStop = mapStopReason(status, incompleteReason);\n output.stopReason = mappedStop.stopReason;\n if (mappedStop.errorMessage === undefined)\n delete output.errorMessage;\n else\n output.errorMessage = mappedStop.errorMessage;\n if (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n output.stopReason = \"toolUse\";\n }\n };\n for await (const event of openaiStream) {\n await options?.onProviderStreamEvent?.(event, model);\n if (event.type === \"response.created\") {\n output.responseId = event.response.id;\n }\n else if (event.type === \"response.output_item.added\") {\n createSlot(event.output_index, event.item);\n }\n else if (event.type === \"response.reasoning_summary_text.delta\") {\n const slot = getSlot(event.output_index, \"thinking\");\n if (!slot)\n continue;\n slot.block.thinking += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.reasoning_summary_part.done\") {\n const slot = getSlot(event.output_index, \"thinking\");\n if (!slot)\n continue;\n slot.block.thinking += \"\\n\\n\";\n stream.push({\n type: \"thinking_delta\",\n contentIndex: slot.contentIndex,\n delta: \"\\n\\n\",\n partial: output,\n });\n }\n else if (event.type === \"response.reasoning_text.delta\") {\n const slot = getSlot(event.output_index, \"thinking\");\n if (!slot)\n continue;\n slot.block.thinking += event.delta;\n stream.push({\n type: \"thinking_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.output_text.delta\") {\n const slot = getSlot(event.output_index, \"text\");\n if (!slot)\n continue;\n slot.block.text += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.refusal.delta\") {\n const slot = getSlot(event.output_index, \"text\");\n if (!slot)\n continue;\n slot.block.text += event.delta;\n stream.push({\n type: \"text_delta\",\n contentIndex: slot.contentIndex,\n delta: event.delta,\n partial: output,\n });\n }\n else if (event.type === \"response.function_call_arguments.delta\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || slot.block.partialJson === undefined)\n continue;\n slot.block.partialJson += event.delta;\n slot.block.arguments = parseStreamingJson(slot.block.partialJson);\n pushToolCallDelta(slot, event.delta);\n }\n else if (event.type === \"response.function_call_arguments.done\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || slot.block.partialJson === undefined)\n continue;\n const previousPartialJson = slot.block.partialJson;\n slot.block.partialJson = event.arguments;\n slot.block.arguments = parseStreamingJson(slot.block.partialJson);\n if (event.arguments.startsWith(previousPartialJson)) {\n const delta = event.arguments.slice(previousPartialJson.length);\n if (delta.length > 0)\n pushToolCallDelta(slot, delta);\n }\n }\n else if (event.type === \"response.custom_tool_call_input.delta\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || !slot.block.customInput)\n continue;\n pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false));\n }\n else if (event.type === \"response.custom_tool_call_input.done\") {\n const slot = getSlot(event.output_index, \"toolCall\");\n if (!slot || !slot.block.customInput)\n continue;\n pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));\n }\n else if (event.type === \"response.output_item.done\") {\n const item = event.item;\n applyMessagePhaseStopReason(item);\n const slot = getOrCreateSlot(event.output_index, item);\n if (item.type === \"reasoning\" && slot?.type === \"thinking\") {\n const summaryText = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n const contentText = item.content?.map((c) => c.text).join(\"\\n\\n\") || \"\";\n slot.block.thinking = summaryText || contentText || slot.block.thinking;\n slot.block.thinkingSignature = JSON.stringify(item);\n reasoningBlocksById.set(item.id, slot.block);\n stream.push({\n type: \"thinking_end\",\n contentIndex: slot.contentIndex,\n content: slot.block.thinking,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n else if (item.type === \"message\" && slot?.type === \"text\") {\n slot.block.text = item.content?.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\") || \"\";\n slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n stream.push({\n type: \"text_end\",\n contentIndex: slot.contentIndex,\n content: slot.block.text,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n else if (item.type === \"function_call\" &&\n slot?.type === \"toolCall\" &&\n slot.block.partialJson !== undefined) {\n slot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n if (item.namespace !== undefined)\n slot.block.namespace = item.namespace;\n // Finalize in-place and strip the scratch buffer so replay only\n // carries parsed arguments.\n delete slot.block.partialJson;\n stream.push({\n type: \"toolcall_end\",\n contentIndex: slot.contentIndex,\n toolCall: slot.block,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n else if (item.type === \"custom_tool_call\" && slot?.type === \"toolCall\" && slot.block.customInput) {\n pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true));\n if (item.namespace !== undefined)\n slot.block.namespace = item.namespace;\n delete slot.block.customInput;\n stream.push({\n type: \"toolcall_end\",\n contentIndex: slot.contentIndex,\n toolCall: slot.block,\n partial: output,\n });\n outputSlots.delete(event.output_index);\n }\n }\n else if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n finalizeResponse(event.response);\n }\n else if (event.type === \"error\") {\n throw new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n }\n else if (event.type === \"response.failed\") {\n sawTerminalResponseEvent = true;\n output.rawStopReason = event.response?.status;\n const error = event.response?.error;\n const details = event.response?.incomplete_details;\n const msg = error\n ? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n : details?.reason\n ? `incomplete: ${details.reason}`\n : \"Unknown error (no error details in response)\";\n throw new Error(msg);\n }\n }\n if (!sawTerminalResponseEvent) {\n throw new Error(\"OpenAI Responses stream ended before a terminal response event\");\n }\n // The agent runs every tool call in the final message. Refuse to hand over calls whose\n // output_item.done never arrived: their arguments may be cut off or mixed up, e.g. when a\n // non-compliant server omits output_index. Finished calls have their scratch buffers removed.\n if (output.stopReason === \"toolUse\") {\n for (const block of output.content) {\n if (block.type !== \"toolCall\")\n continue;\n const toolCall = block;\n if (toolCall.partialJson !== undefined || toolCall.customInput !== undefined) {\n throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`);\n }\n }\n }\n}\nfunction mapStopReason(status, incompleteReason) {\n if (!status)\n return { stopReason: \"stop\" };\n switch (status) {\n case \"completed\":\n return { stopReason: \"stop\" };\n case \"incomplete\":\n if (incompleteReason === \"max_output_tokens\") {\n return { stopReason: \"length\" };\n }\n return {\n stopReason: \"error\",\n errorMessage: incompleteReason\n ? `Response incomplete: ${incompleteReason}`\n : \"Response incomplete without a provider reason\",\n };\n case \"failed\":\n case \"cancelled\":\n return { stopReason: \"error\" };\n // These two are wonky ...\n case \"in_progress\":\n case \"queued\":\n return { stopReason: \"stop\" };\n default: {\n const _exhaustive = status;\n throw new Error(`Unhandled stop reason: ${_exhaustive}`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OAAO,EAAE,YAAY,QAAQ;EAEjC,KAAK;EACL,KAAK,UACD,OAAO,EAAE,YAAY,OAAO;EAChC,SAEI,MAAM,IAAI,MAAM,0BAA0BA,QAAa;CAE/D;AACJ"}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { n as providerHeadersToRecord, t as headersToRecord } from "./headers-BRNMVpzu.js";
|
|
2
|
+
import { t as retryProviderRequest } from "./provider-retry-DzKoh1X7.js";
|
|
3
|
+
import { t as sanitizeSurrogates } from "./sanitize-unicode-Ds14l9Om.js";
|
|
4
|
+
import { n as OpenAI } from "./openai-BCBEd2eO.js";
|
|
5
|
+
import { n as normalizeProviderError, t as formatProviderError } from "./error-body-CyiejW4b.js";
|
|
6
|
+
//#region node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js
|
|
7
|
+
/** Image generation over OpenRouter's chat completions endpoint. */
|
|
8
|
+
const generateImages = async (model, context, options) => {
|
|
9
|
+
const output = {
|
|
10
|
+
api: model.api,
|
|
11
|
+
provider: model.provider,
|
|
12
|
+
model: model.id,
|
|
13
|
+
output: [],
|
|
14
|
+
stopReason: "stop",
|
|
15
|
+
timestamp: Date.now()
|
|
16
|
+
};
|
|
17
|
+
try {
|
|
18
|
+
const apiKey = options?.apiKey;
|
|
19
|
+
if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
|
|
20
|
+
const client = createClient(model, apiKey, options?.headers, options?.fetch);
|
|
21
|
+
let params = buildParams(model, context);
|
|
22
|
+
const nextParams = await options?.onPayload?.(params, model);
|
|
23
|
+
if (nextParams !== void 0) params = nextParams;
|
|
24
|
+
const requestOptions = {
|
|
25
|
+
...options?.signal ? { signal: options.signal } : {},
|
|
26
|
+
...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
|
|
27
|
+
maxRetries: 0
|
|
28
|
+
};
|
|
29
|
+
const { data: response, response: rawResponse } = await retryProviderRequest(() => client.chat.completions.create(params, requestOptions).withResponse(), {
|
|
30
|
+
maxRetries: options?.maxRetries,
|
|
31
|
+
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
32
|
+
signal: options?.signal
|
|
33
|
+
});
|
|
34
|
+
await options?.onResponse?.({
|
|
35
|
+
status: rawResponse.status,
|
|
36
|
+
headers: headersToRecord(rawResponse.headers)
|
|
37
|
+
}, model);
|
|
38
|
+
const imageResponse = response;
|
|
39
|
+
output.responseId = imageResponse.id;
|
|
40
|
+
if (imageResponse.usage) output.usage = parseUsage(imageResponse.usage, model);
|
|
41
|
+
const choice = imageResponse.choices[0];
|
|
42
|
+
if (choice) {
|
|
43
|
+
const content = choice.message.content;
|
|
44
|
+
if (typeof content === "string" && content.length > 0) output.output.push({
|
|
45
|
+
type: "text",
|
|
46
|
+
text: content
|
|
47
|
+
});
|
|
48
|
+
for (const image of choice.message.images ?? []) {
|
|
49
|
+
const imageUrl = typeof image.image_url === "string" ? image.image_url : image.image_url?.url;
|
|
50
|
+
if (!imageUrl?.startsWith("data:")) continue;
|
|
51
|
+
const matches = imageUrl.match(/^data:([^;]+);base64,(.+)$/);
|
|
52
|
+
if (!matches) continue;
|
|
53
|
+
output.output.push({
|
|
54
|
+
type: "image",
|
|
55
|
+
mimeType: matches[1],
|
|
56
|
+
data: matches[2]
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return output;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
63
|
+
output.errorMessage = formatProviderError(normalizeProviderError(error));
|
|
64
|
+
return output;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
function createClient(model, apiKey, optionsHeaders, fetch) {
|
|
68
|
+
return new OpenAI({
|
|
69
|
+
apiKey,
|
|
70
|
+
baseURL: model.baseUrl,
|
|
71
|
+
dangerouslyAllowBrowser: true,
|
|
72
|
+
fetch,
|
|
73
|
+
defaultHeaders: providerHeadersToRecord({
|
|
74
|
+
...model.headers,
|
|
75
|
+
...optionsHeaders
|
|
76
|
+
})
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
function buildParams(model, context) {
|
|
80
|
+
const content = context.input.map((item) => {
|
|
81
|
+
if (item.type === "text") return {
|
|
82
|
+
type: "text",
|
|
83
|
+
text: sanitizeSurrogates(item.text)
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
type: "image_url",
|
|
87
|
+
image_url: { url: `data:${item.mimeType};base64,${item.data}` }
|
|
88
|
+
};
|
|
89
|
+
});
|
|
90
|
+
return {
|
|
91
|
+
model: model.id,
|
|
92
|
+
messages: [{
|
|
93
|
+
role: "user",
|
|
94
|
+
content
|
|
95
|
+
}],
|
|
96
|
+
stream: false,
|
|
97
|
+
modalities: model.output.includes("text") ? ["image", "text"] : ["image"]
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function parseUsage(rawUsage, model) {
|
|
101
|
+
const promptTokens = rawUsage.prompt_tokens || 0;
|
|
102
|
+
const reportedCachedTokens = rawUsage.prompt_tokens_details?.cached_tokens || 0;
|
|
103
|
+
const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;
|
|
104
|
+
const cacheReadTokens = cacheWriteTokens > 0 ? Math.max(0, reportedCachedTokens - cacheWriteTokens) : reportedCachedTokens;
|
|
105
|
+
const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);
|
|
106
|
+
const output = rawUsage.completion_tokens || 0;
|
|
107
|
+
const usage = {
|
|
108
|
+
input,
|
|
109
|
+
output,
|
|
110
|
+
cacheRead: cacheReadTokens,
|
|
111
|
+
cacheWrite: cacheWriteTokens,
|
|
112
|
+
totalTokens: input + output + cacheReadTokens + cacheWriteTokens,
|
|
113
|
+
cost: {
|
|
114
|
+
input: model.cost.input / 1e6 * input,
|
|
115
|
+
output: model.cost.output / 1e6 * output,
|
|
116
|
+
cacheRead: model.cost.cacheRead / 1e6 * cacheReadTokens,
|
|
117
|
+
cacheWrite: model.cost.cacheWrite / 1e6 * cacheWriteTokens,
|
|
118
|
+
total: 0
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
122
|
+
return usage;
|
|
123
|
+
}
|
|
124
|
+
//#endregion
|
|
125
|
+
export { generateImages };
|
|
126
|
+
|
|
127
|
+
//# sourceMappingURL=openrouter-images-CRmBkzpX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openrouter-images-CRmBkzpX.js","names":[],"sources":["../node_modules/@earendil-works/pi-ai/dist/api/openrouter-images.js"],"sourcesContent":["import OpenAI from \"openai\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.js\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.js\";\nimport { retryProviderRequest } from \"../utils/provider-retry.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\n/** Image generation over OpenRouter's chat completions endpoint. */\nexport const generateImages = async (model, context, options) => {\n const output = {\n api: model.api,\n provider: model.provider,\n model: model.id,\n output: [],\n stopReason: \"stop\",\n timestamp: Date.now(),\n };\n try {\n const apiKey = options?.apiKey;\n if (!apiKey) {\n throw new Error(`No API key for provider: ${model.provider}`);\n }\n const client = createClient(model, apiKey, options?.headers, options?.fetch);\n let params = buildParams(model, context);\n const nextParams = await options?.onPayload?.(params, model);\n if (nextParams !== undefined) {\n params = nextParams;\n }\n const requestOptions = {\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n maxRetries: 0,\n };\n const { data: response, response: rawResponse } = await retryProviderRequest(() => client.chat.completions\n .create(params, requestOptions)\n .withResponse(), {\n maxRetries: options?.maxRetries,\n maxRetryDelayMs: options?.maxRetryDelayMs,\n signal: options?.signal,\n });\n await options?.onResponse?.({ status: rawResponse.status, headers: headersToRecord(rawResponse.headers) }, model);\n const imageResponse = response;\n output.responseId = imageResponse.id;\n if (imageResponse.usage) {\n output.usage = parseUsage(imageResponse.usage, model);\n }\n const choice = imageResponse.choices[0];\n if (choice) {\n const content = choice.message.content;\n if (typeof content === \"string\" && content.length > 0) {\n output.output.push({ type: \"text\", text: content });\n }\n for (const image of choice.message.images ?? []) {\n const imageUrl = typeof image.image_url === \"string\" ? image.image_url : image.image_url?.url;\n if (!imageUrl?.startsWith(\"data:\"))\n continue;\n const matches = imageUrl.match(/^data:([^;]+);base64,(.+)$/);\n if (!matches)\n continue;\n output.output.push({\n type: \"image\",\n mimeType: matches[1],\n data: matches[2],\n });\n }\n }\n return output;\n }\n catch (error) {\n output.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n output.errorMessage = formatProviderError(normalizeProviderError(error));\n return output;\n }\n};\nfunction createClient(model, apiKey, optionsHeaders, fetch) {\n return new OpenAI({\n apiKey,\n baseURL: model.baseUrl,\n dangerouslyAllowBrowser: true,\n fetch,\n defaultHeaders: providerHeadersToRecord({ ...model.headers, ...optionsHeaders }),\n });\n}\nfunction buildParams(model, context) {\n const content = context.input.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"text\",\n text: sanitizeSurrogates(item.text),\n };\n }\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${item.mimeType};base64,${item.data}`,\n },\n };\n });\n return {\n model: model.id,\n messages: [\n {\n role: \"user\",\n content,\n },\n ],\n stream: false,\n modalities: model.output.includes(\"text\") ? [\"image\", \"text\"] : [\"image\"],\n };\n}\nfunction parseUsage(rawUsage, model) {\n const promptTokens = rawUsage.prompt_tokens || 0;\n const reportedCachedTokens = rawUsage.prompt_tokens_details?.cached_tokens || 0;\n const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;\n const cacheReadTokens = cacheWriteTokens > 0 ? Math.max(0, reportedCachedTokens - cacheWriteTokens) : reportedCachedTokens;\n const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);\n const output = rawUsage.completion_tokens || 0;\n const usage = {\n input,\n output,\n cacheRead: cacheReadTokens,\n cacheWrite: cacheWriteTokens,\n totalTokens: input + output + cacheReadTokens + cacheWriteTokens,\n cost: {\n input: (model.cost.input / 1000000) * input,\n output: (model.cost.output / 1000000) * output,\n cacheRead: (model.cost.cacheRead / 1000000) * cacheReadTokens,\n cacheWrite: (model.cost.cacheWrite / 1000000) * cacheWriteTokens,\n total: 0,\n },\n };\n usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n return usage;\n}\n//# sourceMappingURL=openrouter-images.js.map"],"x_google_ignoreList":[0],"mappings":";;;;;;;AAMA,MAAa,iBAAiB,OAAO,OAAO,SAAS,YAAY;CAC7D,MAAM,SAAS;EACX,KAAK,MAAM;EACX,UAAU,MAAM;EAChB,OAAO,MAAM;EACb,QAAQ,CAAC;EACT,YAAY;EACZ,WAAW,KAAK,IAAI;CACxB;CACA,IAAI;EACA,MAAM,SAAS,SAAS;EACxB,IAAI,CAAC,QACD,MAAM,IAAI,MAAM,4BAA4B,MAAM,UAAU;EAEhE,MAAM,SAAS,aAAa,OAAO,QAAQ,SAAS,SAAS,SAAS,KAAK;EAC3E,IAAI,SAAS,YAAY,OAAO,OAAO;EACvC,MAAM,aAAa,MAAM,SAAS,YAAY,QAAQ,KAAK;EAC3D,IAAI,eAAe,KAAA,GACf,SAAS;EAEb,MAAM,iBAAiB;GACnB,GAAI,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;GACpD,GAAI,SAAS,cAAc,KAAA,IAAY,EAAE,SAAS,QAAQ,UAAU,IAAI,CAAC;GACzE,YAAY;EAChB;EACA,MAAM,EAAE,MAAM,UAAU,UAAU,gBAAgB,MAAM,2BAA2B,OAAO,KAAK,YAC1F,OAAO,QAAQ,cAAc,CAAC,CAC9B,aAAa,GAAG;GACjB,YAAY,SAAS;GACrB,iBAAiB,SAAS;GAC1B,QAAQ,SAAS;EACrB,CAAC;EACD,MAAM,SAAS,aAAa;GAAE,QAAQ,YAAY;GAA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