@bastani/pi-ai 0.9.20-alpha.2 → 0.9.20-alpha.4
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/CHANGELOG.md +34 -1
- package/NOTICE.md +1 -1
- package/README.md +28 -5
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +167 -85
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.d.ts.map +1 -1
- package/dist/api/azure-openai-responses.js +17 -5
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +15 -12
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +22 -80
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-shared.d.ts +13 -4
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +54 -4
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/google-vertex.d.ts.map +1 -1
- package/dist/api/google-vertex.js +25 -65
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/mistral-conversations.d.ts.map +1 -1
- package/dist/api/mistral-conversations.js +15 -11
- package/dist/api/mistral-conversations.js.map +1 -1
- package/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/dist/api/openai-codex-responses.js +20 -22
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts +6 -4
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +39 -57
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts +7 -5
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +56 -56
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +14 -19
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/pi-messages.d.ts +3 -3
- package/dist/api/pi-messages.d.ts.map +1 -1
- package/dist/api/pi-messages.js +2 -2
- package/dist/api/pi-messages.js.map +1 -1
- package/dist/api/simple-options.d.ts +3 -3
- package/dist/api/simple-options.d.ts.map +1 -1
- package/dist/api/simple-options.js.map +1 -1
- package/dist/api/transform-messages.d.ts.map +1 -1
- package/dist/api/transform-messages.js +21 -7
- package/dist/api/transform-messages.js.map +1 -1
- package/dist/auth/credential-store.d.ts.map +1 -1
- package/dist/auth/credential-store.js +3 -2
- package/dist/auth/credential-store.js.map +1 -1
- package/dist/auth/resolve.d.ts +4 -0
- package/dist/auth/resolve.d.ts.map +1 -1
- package/dist/auth/resolve.js +27 -8
- package/dist/auth/resolve.js.map +1 -1
- package/dist/compat.d.ts +3 -3
- package/dist/compat.d.ts.map +1 -1
- package/dist/compat.js +9 -6
- package/dist/compat.js.map +1 -1
- package/dist/env-api-keys.d.ts +2 -0
- package/dist/env-api-keys.d.ts.map +1 -1
- package/dist/env-api-keys.js +59 -43
- package/dist/env-api-keys.js.map +1 -1
- package/dist/image-models.generated.d.ts +30 -0
- package/dist/image-models.generated.d.ts.map +1 -1
- package/dist/image-models.generated.js +34 -4
- package/dist/image-models.generated.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +5 -4
- package/dist/models.d.ts.map +1 -1
- package/dist/models.generated.d.ts +2 -0
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.generated.js +2 -0
- package/dist/models.generated.js.map +1 -1
- package/dist/models.js +6 -3
- package/dist/models.js.map +1 -1
- package/dist/providers/amazon-bedrock.models.d.ts +1 -2
- package/dist/providers/amazon-bedrock.models.d.ts.map +1 -1
- package/dist/providers/amazon-bedrock.models.js.map +1 -1
- package/dist/providers/ant-ling.models.d.ts +1 -2
- package/dist/providers/ant-ling.models.d.ts.map +1 -1
- package/dist/providers/ant-ling.models.js.map +1 -1
- package/dist/providers/anthropic.models.d.ts +1 -2
- package/dist/providers/anthropic.models.d.ts.map +1 -1
- package/dist/providers/anthropic.models.js.map +1 -1
- package/dist/providers/azure-openai-responses.models.d.ts +1 -2
- package/dist/providers/azure-openai-responses.models.d.ts.map +1 -1
- package/dist/providers/azure-openai-responses.models.js.map +1 -1
- package/dist/providers/baseten.models.d.ts +1 -2
- package/dist/providers/baseten.models.d.ts.map +1 -1
- package/dist/providers/baseten.models.js.map +1 -1
- package/dist/providers/cerebras.models.d.ts +1 -2
- package/dist/providers/cerebras.models.d.ts.map +1 -1
- package/dist/providers/cerebras.models.js.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.models.d.ts +1 -2
- package/dist/providers/cloudflare-ai-gateway.models.d.ts.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.models.js.map +1 -1
- package/dist/providers/cloudflare-workers-ai.models.d.ts +1 -2
- package/dist/providers/cloudflare-workers-ai.models.d.ts.map +1 -1
- package/dist/providers/cloudflare-workers-ai.models.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/providers/data/anthropic.json +1 -1
- package/dist/providers/data/baseten.json +1 -1
- package/dist/providers/data/cerebras.json +1 -1
- package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/providers/data/deepseek.json +1 -1
- package/dist/providers/data/fireworks.json +1 -1
- package/dist/providers/data/github-copilot.json +1 -1
- package/dist/providers/data/google-vertex.json +1 -1
- package/dist/providers/data/google.json +1 -1
- package/dist/providers/data/mistral.json +1 -1
- package/dist/providers/data/moonshotai-cn.json +1 -1
- package/dist/providers/data/moonshotai.json +1 -1
- package/dist/providers/data/nvidia.json +1 -1
- package/dist/providers/data/openai-codex.json +1 -1
- package/dist/providers/data/openai.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/providers/data/radius.json +1 -0
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/zai-coding-cn.json +1 -1
- package/dist/providers/data/zai.json +1 -1
- package/dist/providers/deepseek.models.d.ts +1 -2
- package/dist/providers/deepseek.models.d.ts.map +1 -1
- package/dist/providers/deepseek.models.js.map +1 -1
- package/dist/providers/faux.d.ts +2 -2
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +11 -11
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/fireworks.models.d.ts +1 -2
- package/dist/providers/fireworks.models.d.ts.map +1 -1
- package/dist/providers/fireworks.models.js.map +1 -1
- package/dist/providers/github-copilot.models.d.ts +1 -2
- package/dist/providers/github-copilot.models.d.ts.map +1 -1
- package/dist/providers/github-copilot.models.js.map +1 -1
- package/dist/providers/google-vertex.models.d.ts +1 -2
- package/dist/providers/google-vertex.models.d.ts.map +1 -1
- package/dist/providers/google-vertex.models.js.map +1 -1
- package/dist/providers/google.models.d.ts +1 -2
- package/dist/providers/google.models.d.ts.map +1 -1
- package/dist/providers/google.models.js.map +1 -1
- package/dist/providers/groq.models.d.ts +1 -2
- package/dist/providers/groq.models.d.ts.map +1 -1
- package/dist/providers/groq.models.js.map +1 -1
- package/dist/providers/huggingface.models.d.ts +1 -2
- package/dist/providers/huggingface.models.d.ts.map +1 -1
- package/dist/providers/huggingface.models.js.map +1 -1
- package/dist/providers/kimi-coding.models.d.ts +1 -2
- package/dist/providers/kimi-coding.models.d.ts.map +1 -1
- package/dist/providers/kimi-coding.models.js.map +1 -1
- package/dist/providers/minimax-cn.models.d.ts +1 -2
- package/dist/providers/minimax-cn.models.d.ts.map +1 -1
- package/dist/providers/minimax-cn.models.js.map +1 -1
- package/dist/providers/minimax.models.d.ts +1 -2
- package/dist/providers/minimax.models.d.ts.map +1 -1
- package/dist/providers/minimax.models.js.map +1 -1
- package/dist/providers/mistral.models.d.ts +1 -2
- package/dist/providers/mistral.models.d.ts.map +1 -1
- package/dist/providers/mistral.models.js.map +1 -1
- package/dist/providers/moonshotai-cn.models.d.ts +1 -2
- package/dist/providers/moonshotai-cn.models.d.ts.map +1 -1
- package/dist/providers/moonshotai-cn.models.js.map +1 -1
- package/dist/providers/moonshotai.models.d.ts +1 -2
- package/dist/providers/moonshotai.models.d.ts.map +1 -1
- package/dist/providers/moonshotai.models.js.map +1 -1
- package/dist/providers/nvidia.models.d.ts +1 -2
- package/dist/providers/nvidia.models.d.ts.map +1 -1
- package/dist/providers/nvidia.models.js.map +1 -1
- package/dist/providers/openai-codex.models.d.ts +1 -2
- package/dist/providers/openai-codex.models.d.ts.map +1 -1
- package/dist/providers/openai-codex.models.js.map +1 -1
- package/dist/providers/openai.models.d.ts +1 -2
- package/dist/providers/openai.models.d.ts.map +1 -1
- package/dist/providers/openai.models.js.map +1 -1
- package/dist/providers/opencode-go.models.d.ts +1 -2
- package/dist/providers/opencode-go.models.d.ts.map +1 -1
- package/dist/providers/opencode-go.models.js.map +1 -1
- package/dist/providers/opencode.models.d.ts +1 -2
- package/dist/providers/opencode.models.d.ts.map +1 -1
- package/dist/providers/opencode.models.js.map +1 -1
- package/dist/providers/openrouter.models.d.ts +1 -2
- package/dist/providers/openrouter.models.d.ts.map +1 -1
- package/dist/providers/openrouter.models.js.map +1 -1
- package/dist/providers/qwen-token-plan-cn.models.d.ts +1 -2
- package/dist/providers/qwen-token-plan-cn.models.d.ts.map +1 -1
- package/dist/providers/qwen-token-plan-cn.models.js.map +1 -1
- package/dist/providers/qwen-token-plan-individual.models.d.ts +1 -2
- package/dist/providers/qwen-token-plan-individual.models.d.ts.map +1 -1
- package/dist/providers/qwen-token-plan-individual.models.js.map +1 -1
- package/dist/providers/qwen-token-plan.models.d.ts +1 -2
- package/dist/providers/qwen-token-plan.models.d.ts.map +1 -1
- package/dist/providers/qwen-token-plan.models.js.map +1 -1
- package/dist/providers/radius.d.ts.map +1 -1
- package/dist/providers/radius.js +19 -5
- package/dist/providers/radius.js.map +1 -1
- package/dist/providers/radius.models.d.ts +3 -0
- package/dist/providers/radius.models.d.ts.map +1 -0
- package/dist/providers/radius.models.js +6 -0
- package/dist/providers/radius.models.js.map +1 -0
- package/dist/providers/together.models.d.ts +1 -2
- package/dist/providers/together.models.d.ts.map +1 -1
- package/dist/providers/together.models.js.map +1 -1
- package/dist/providers/vercel-ai-gateway.models.d.ts +1 -2
- package/dist/providers/vercel-ai-gateway.models.d.ts.map +1 -1
- package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
- package/dist/providers/xai.models.d.ts +1 -2
- package/dist/providers/xai.models.d.ts.map +1 -1
- package/dist/providers/xai.models.js.map +1 -1
- package/dist/providers/xiaomi-token-plan-ams.models.d.ts +1 -2
- package/dist/providers/xiaomi-token-plan-ams.models.d.ts.map +1 -1
- package/dist/providers/xiaomi-token-plan-ams.models.js.map +1 -1
- package/dist/providers/xiaomi-token-plan-cn.models.d.ts +1 -2
- package/dist/providers/xiaomi-token-plan-cn.models.d.ts.map +1 -1
- package/dist/providers/xiaomi-token-plan-cn.models.js.map +1 -1
- package/dist/providers/xiaomi-token-plan-sgp.models.d.ts +1 -2
- package/dist/providers/xiaomi-token-plan-sgp.models.d.ts.map +1 -1
- package/dist/providers/xiaomi-token-plan-sgp.models.js.map +1 -1
- package/dist/providers/xiaomi.models.d.ts +1 -2
- package/dist/providers/xiaomi.models.d.ts.map +1 -1
- package/dist/providers/xiaomi.models.js.map +1 -1
- package/dist/providers/zai-coding-cn.models.d.ts +1 -2
- package/dist/providers/zai-coding-cn.models.d.ts.map +1 -1
- package/dist/providers/zai-coding-cn.models.js.map +1 -1
- package/dist/providers/zai.models.d.ts +1 -2
- package/dist/providers/zai.models.d.ts.map +1 -1
- package/dist/providers/zai.models.js.map +1 -1
- package/dist/types.d.ts +95 -26
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/diagnostics.d.ts +3 -2
- package/dist/utils/diagnostics.d.ts.map +1 -1
- package/dist/utils/diagnostics.js.map +1 -1
- package/dist/utils/estimate.d.ts +2 -2
- package/dist/utils/estimate.d.ts.map +1 -1
- package/dist/utils/estimate.js +8 -29
- package/dist/utils/estimate.js.map +1 -1
- package/dist/utils/overflow.d.ts +1 -0
- package/dist/utils/overflow.d.ts.map +1 -1
- package/dist/utils/overflow.js +17 -5
- package/dist/utils/overflow.js.map +1 -1
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +2 -0
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/text.d.ts +9 -1
- package/dist/utils/text.d.ts.map +1 -1
- package/dist/utils/text.js +26 -0
- package/dist/utils/text.js.map +1 -1
- package/dist/utils/transcript.d.ts +84 -0
- package/dist/utils/transcript.d.ts.map +1 -0
- package/dist/utils/transcript.js +204 -0
- package/dist/utils/transcript.js.map +1 -0
- package/package.json +3 -3
- package/dist/utils/deferred-tools.d.ts +0 -9
- package/dist/utils/deferred-tools.d.ts.map +0 -1
- package/dist/utils/deferred-tools.js +0 -36
- package/dist/utils/deferred-tools.js.map +0 -1
|
@@ -111,8 +111,8 @@ export function transformMessages(messages, model, normalizeToolCallId) {
|
|
|
111
111
|
const imageAwareMessages = downgradeUnsupportedDocuments(downgradeUnsupportedImages(normalizedMessages, model), model);
|
|
112
112
|
// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)
|
|
113
113
|
const transformed = imageAwareMessages.map((msg) => {
|
|
114
|
-
//
|
|
115
|
-
if (msg.role === "user") {
|
|
114
|
+
// System and user messages pass through unchanged
|
|
115
|
+
if (msg.role === "system" || msg.role === "user") {
|
|
116
116
|
return msg;
|
|
117
117
|
}
|
|
118
118
|
// Handle toolResult messages - normalize toolCallId if we have a mapping
|
|
@@ -233,7 +233,11 @@ export function transformMessages(messages, model, normalizeToolCallId) {
|
|
|
233
233
|
const result = [];
|
|
234
234
|
let pendingToolCalls = [];
|
|
235
235
|
let existingToolResultIds = new Set();
|
|
236
|
-
|
|
236
|
+
// System messages are transparent to tool-call accounting: one that lands between a tool
|
|
237
|
+
// call and its results is held back and emitted after the results (synthetic ones
|
|
238
|
+
// included), so it never causes a duplicate result for a call that is answered later.
|
|
239
|
+
const heldSystemMessages = [];
|
|
240
|
+
const closePendingToolCalls = () => {
|
|
237
241
|
if (pendingToolCalls.length > 0) {
|
|
238
242
|
for (const tc of pendingToolCalls) {
|
|
239
243
|
if (!existingToolResultIds.has(tc.id)) {
|
|
@@ -250,12 +254,14 @@ export function transformMessages(messages, model, normalizeToolCallId) {
|
|
|
250
254
|
pendingToolCalls = [];
|
|
251
255
|
existingToolResultIds = new Set();
|
|
252
256
|
}
|
|
257
|
+
result.push(...heldSystemMessages);
|
|
258
|
+
heldSystemMessages.length = 0;
|
|
253
259
|
};
|
|
254
260
|
for (let i = 0; i < boundaryFiltered.length; i++) {
|
|
255
261
|
const msg = boundaryFiltered[i];
|
|
256
262
|
if (msg.role === "assistant") {
|
|
257
263
|
// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now
|
|
258
|
-
|
|
264
|
+
closePendingToolCalls();
|
|
259
265
|
// Skip errored/aborted assistant messages entirely.
|
|
260
266
|
// These are incomplete turns that shouldn't be replayed:
|
|
261
267
|
// - May have partial content (reasoning without message, incomplete tool calls)
|
|
@@ -277,9 +283,17 @@ export function transformMessages(messages, model, normalizeToolCallId) {
|
|
|
277
283
|
existingToolResultIds.add(msg.toolCallId);
|
|
278
284
|
result.push(msg);
|
|
279
285
|
}
|
|
286
|
+
else if (msg.role === "system") {
|
|
287
|
+
if (pendingToolCalls.length > 0) {
|
|
288
|
+
heldSystemMessages.push(msg);
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
result.push(msg);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
280
294
|
else if (msg.role === "user") {
|
|
281
|
-
//
|
|
282
|
-
|
|
295
|
+
// A new user turn interrupts tool flow - insert synthetic results for orphaned calls
|
|
296
|
+
closePendingToolCalls();
|
|
283
297
|
result.push(msg);
|
|
284
298
|
}
|
|
285
299
|
else {
|
|
@@ -287,7 +301,7 @@ export function transformMessages(messages, model, normalizeToolCallId) {
|
|
|
287
301
|
}
|
|
288
302
|
}
|
|
289
303
|
// If the conversation ends with unresolved tool calls, synthesize results now.
|
|
290
|
-
|
|
304
|
+
closePendingToolCalls();
|
|
291
305
|
return result;
|
|
292
306
|
}
|
|
293
307
|
//# sourceMappingURL=transform-messages.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAYA,MAAM,iCAAiC,GAAG,gDAAgD,CAAC;AAC3F,MAAM,iCAAiC,GAAG,qDAAqD,CAAC;AAChG,MAAM,6BAA6B,GAAG,2DAA2D,CAAC;AAElG;;;;;;;;;;;;;;GAcG;AACH,SAAS,6BAA6B,CAAmB,KAAkB,EAAW;IACrF,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB;QAAE,OAAO,KAAK,CAAC;IACrD,MAAM,MAAM,GAAG,KAAK,CAAC,MAA6C,CAAC;IACnE,OAAO,MAAM,EAAE,6BAA6B,KAAK,IAAI,CAAC;AAAA,CACtD;AAED,+FAA+F;AAC/F,8EAA0E;AAC1E,SAAS,4BAA4B,CACpC,OAAiB,EACjB,WAAmB,EAC+B;IAClD,MAAM,MAAM,GAAoD,EAAE,CAAC;IACnE,IAAI,sBAAsB,GAAG,KAAK,CAAC;IAEnC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,sBAAsB,EAAE,CAAC;gBAC7B,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;YAClD,CAA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,CAAC,CAAC;YAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAChC,kFAAkF;YAClF,0BAA0B,EAAE,CAAC;YAC7B,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAED,+EAA+E;IAC/E,0BAA0B,EAAE,CAAC;IAE7B,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\n\nconst NON_VISION_USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst NON_VISION_TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\nconst NON_DOCUMENT_USER_PLACEHOLDER = \"(document omitted: model does not support document input)\";\n\n/**\n * Whether the target model's API adjudicates thinking-block model binding itself.\n *\n * Anthropic's preserved-thinking rules make the API, not the client, the authority on which\n * thinking blocks a model may read: \"Pass blocks back unchanged. Send every assistant turn\n * exactly as you received it, thinking blocks included, and let the API decide which blocks the\n * model can use\", and \"A block that fails the model check is always dropped\" before the prompt\n * reaches the model, unbilled.\n * https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking\n *\n * Flattening those blocks into visible text client-side is both lossy (a newer model that is\n * allowed to read them loses the reasoning) and destabilizing (it rewrites the conversation\n * prefix that later thinking-block signatures are bound to). Models whose generated metadata\n * sets this flag replay foreign signed blocks unchanged instead.\n */\nfunction delegatesThinkingModelBinding<TApi extends Api>(model: Model<TApi>): boolean {\n\tif (model.api !== \"anthropic-messages\") return false;\n\tconst compat = model.compat as AnthropicMessagesCompat | undefined;\n\treturn compat?.delegatesThinkingModelBinding === true;\n}\n\n// Preserves the caller's block union minus images, so a user message keeps its document blocks\n// while a tool result — which cannot carry one — keeps its narrower type.\nfunction replaceImagesWithPlaceholder<TBlock extends { type: string }>(\n\tcontent: TBlock[],\n\tplaceholder: string,\n): (Exclude<TBlock, ImageContent> | TextContent)[] {\n\tconst result: (Exclude<TBlock, ImageContent> | TextContent)[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\") {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst kept = block as Exclude<TBlock, ImageContent>;\n\t\tresult.push(kept);\n\t\tpreviousWasPlaceholder = kept.type === \"text\" && (kept as unknown as TextContent).text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tif (model.input.includes(\"image\")) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg): Message => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\treturn msg;\n\t});\n}\n\n/**\n * Replace document blocks with a visible placeholder for models that cannot receive one.\n *\n * Mirrors the image downgrade: only the Anthropic Messages and Amazon Bedrock Converse paths can\n * serialize a document, so every other provider — and any Claude mirror whose generated `input`\n * omits `\"pdf\"` — gets a marker rather than a silently missing attachment or a rejected request.\n * Documents only ever appear in user messages; tool results stay text/image-only.\n */\nfunction downgradeUnsupportedDocuments<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tif (model.input.includes(\"pdf\")) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg) => {\n\t\tif (msg.role !== \"user\" || !Array.isArray(msg.content)) return msg;\n\t\tif (!msg.content.some((block) => block.type === \"document\")) return msg;\n\n\t\tconst content: (TextContent | ImageContent)[] = [];\n\t\tlet previousWasPlaceholder = false;\n\t\tfor (const block of msg.content) {\n\t\t\tif (block.type === \"document\") {\n\t\t\t\tif (!previousWasPlaceholder) content.push({ type: \"text\", text: NON_DOCUMENT_USER_PLACEHOLDER });\n\t\t\t\tpreviousWasPlaceholder = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcontent.push(block);\n\t\t\tpreviousWasPlaceholder = block.type === \"text\" && block.text === NON_DOCUMENT_USER_PLACEHOLDER;\n\t\t}\n\t\treturn { ...msg, content };\n\t});\n}\n\n/**\n * Normalize tool call ID for cross-provider compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).\n */\nexport function transformMessages<TApi extends Api>(\n\tmessages: Message[],\n\tmodel: Model<TApi>,\n\tnormalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,\n): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs\n\tconst toolCallIdMap = new Map<string, string>();\n\t// Tool calls dropped for preceding a fallback boundary. Their results must go too: a\n\t// `tool_result` whose `tool_use` is absent is rejected, and `ToolResultMessage` is a separate\n\t// top-level message so removing the call alone would orphan it.\n\tconst droppedToolCallIds = new Set<string>();\n\t// Normalize null/undefined content from untyped callers (custom tools, hand-built\n\t// histories, old session files) so downstream code can rely on the type contract.\n\tconst normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));\n\tconst imageAwareMessages = downgradeUnsupportedDocuments(\n\t\tdowngradeUnsupportedImages(normalizedMessages, model),\n\t\tmodel,\n\t);\n\n\t// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)\n\tconst transformed = imageAwareMessages.map((msg) => {\n\t\t// User messages pass through unchanged\n\t\tif (msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tassistantMsg.model === model.id;\n\t\t\t// A different model on the same provider and API whose API adjudicates model binding\n\t\t\t// itself. Its signed blocks replay unchanged; the API keeps the ones the target model\n\t\t\t// may read and silently drops the rest.\n\t\t\tconst canReplayForeignThinking =\n\t\t\t\t!isSameModel &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tdelegatesThinkingModelBinding(model);\n\t\t\tconst preservesThinking = isSameModel || canReplayForeignThinking;\n\n\t\t\t// After a mid-output server-side fallback the turn holds output from two models either\n\t\t\t// side of a `fallback` marker. Anthropic's replay rules: keep the marker \"exactly where\n\t\t\t// it appeared\", keep `text` and everything after it, and drop `thinking`,\n\t\t\t// `redacted_thinking`, and client-side `tool_use` that precede the final marker. A\n\t\t\t// request that echoes thinking from both sides is rejected outright, so this is a\n\t\t\t// correctness requirement rather than a token saving — and it applies even when the\n\t\t\t// blocks would otherwise be replayable.\n\t\t\t// https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n\t\t\t// `findLastIndex` needs ES2023; this package targets ES2022.\n\t\t\tlet finalFallbackIndex = -1;\n\t\t\tfor (let i = assistantMsg.content.length - 1; i >= 0; i--) {\n\t\t\t\tif (assistantMsg.content[i].type === \"fallback\") {\n\t\t\t\t\tfinalFallbackIndex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst transformedContent = assistantMsg.content.flatMap((block, blockIndex) => {\n\t\t\t\tconst precedesFallbackBoundary = finalFallbackIndex >= 0 && blockIndex < finalFallbackIndex;\n\n\t\t\t\tif (block.type === \"fallback\") {\n\t\t\t\t\t// Only the final marker is load-bearing for validation, but earlier ones are\n\t\t\t\t\t// equally \"where they appeared\", so every marker is preserved in place.\n\t\t\t\t\treturn block;\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (precedesFallbackBoundary) return [];\n\t\t\t\t\t// Redacted thinking is opaque encrypted content the client cannot rewrite.\n\t\t\t\t\t// Replay it where the API adjudicates it; otherwise drop it to avoid API errors.\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\treturn preservesThinking ? block : [];\n\t\t\t\t\t}\n\t\t\t\t\t// Keep signed thinking blocks for replay even when the thinking text is empty\n\t\t\t\t\t// (OpenAI encrypted reasoning, or Anthropic `display: \"omitted\"`).\n\t\t\t\t\tif (preservesThinking && block.thinkingSignature) return block;\n\t\t\t\t\t// Skip empty thinking blocks, convert others to plain text\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (preservesThinking) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\t// Client-side `tool_use` before the final fallback marker must be dropped: the\n\t\t\t\t\t// declining model's tool call was never executed by the model that continued.\n\t\t\t\t\t// Record the id so its `toolResult` message is dropped alongside it.\n\t\t\t\t\tif (precedesFallbackBoundary) {\n\t\t\t\t\t\tdroppedToolCallIds.add(block.id);\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Drop the tool results whose calls were removed at a fallback boundary. Anthropic rejects a\n\t// `tool_result` with no matching `tool_use`, so removing the call without its result would\n\t// trade one rejection for another.\n\tconst boundaryFiltered =\n\t\tdroppedToolCallIds.size === 0\n\t\t\t? transformed\n\t\t\t: transformed.filter((msg) => msg.role !== \"toolResult\" || !droppedToolCallIds.has(msg.toolCallId));\n\n\t// Second pass: insert synthetic empty tool results for orphaned tool calls\n\t// This preserves thinking signatures and satisfies API requirements\n\tconst result: Message[] = [];\n\tlet pendingToolCalls: ToolCall[] = [];\n\tlet existingToolResultIds = new Set<string>();\n\tconst insertSyntheticToolResults = () => {\n\t\tif (pendingToolCalls.length > 0) {\n\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\tresult.push({\n\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpendingToolCalls = [];\n\t\t\texistingToolResultIds = new Set();\n\t\t}\n\t};\n\n\tfor (let i = 0; i < boundaryFiltered.length; i++) {\n\t\tconst msg = boundaryFiltered[i];\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\t// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now\n\t\t\tinsertSyntheticToolResults();\n\n\t\t\t// Skip errored/aborted assistant messages entirely.\n\t\t\t// These are incomplete turns that shouldn't be replayed:\n\t\t\t// - May have partial content (reasoning without message, incomplete tool calls)\n\t\t\t// - Replaying them can cause API errors (e.g., OpenAI \"reasoning without following item\")\n\t\t\t// - The model should retry from the last valid state\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tif (assistantMsg.stopReason === \"error\" || assistantMsg.stopReason === \"aborted\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Track tool calls from this assistant message\n\t\t\tconst toolCalls = assistantMsg.content.filter((b) => b.type === \"toolCall\") as ToolCall[];\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tpendingToolCalls = toolCalls;\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\texistingToolResultIds.add(msg.toolCallId);\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"user\") {\n\t\t\t// User message interrupts tool flow - insert synthetic results for orphaned calls\n\t\t\tinsertSyntheticToolResults();\n\t\t\tresult.push(msg);\n\t\t} else {\n\t\t\tresult.push(msg);\n\t\t}\n\t}\n\n\t// If the conversation ends with unresolved tool calls, synthesize results now.\n\tinsertSyntheticToolResults();\n\n\treturn result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAYA,MAAM,iCAAiC,GAAG,gDAAgD,CAAC;AAC3F,MAAM,iCAAiC,GAAG,qDAAqD,CAAC;AAChG,MAAM,6BAA6B,GAAG,2DAA2D,CAAC;AAElG;;;;;;;;;;;;;;GAcG;AACH,SAAS,6BAA6B,CAAmB,KAAkB,EAAW;IACrF,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB;QAAE,OAAO,KAAK,CAAC;IACrD,MAAM,MAAM,GAAG,KAAK,CAAC,MAA6C,CAAC;IACnE,OAAO,MAAM,EAAE,6BAA6B,KAAK,IAAI,CAAC;AAAA,CACtD;AAED,+FAA+F;AAC/F,8EAA0E;AAC1E,SAAS,4BAA4B,CACpC,OAAiB,EACjB,WAAmB,EAC+B;IAClD,MAAM,MAAM,GAAoD,EAAE,CAAC;IACnE,IAAI,sBAAsB,GAAG,KAAK,CAAC;IAEnC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,sBAAsB,EAAE,CAAC;gBAC7B,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;YAClD,CAAC;YACD,sBAAsB,GAAG,IAAI,CAAC;YAC9B,SAAS;QACV,CAAC;QAED,MAAM,IAAI,GAAG,KAAsC,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AAG,CAAC,CAAC;QAClB,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YACtC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAClC,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACjC,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAC9B,CAAC;iBAAM,CAAC;gBACP,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAClB,CAAC;QACF,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAChC,qFAAqF;YACrF,qBAAqB,EAAE,CAAC;YACxB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAED,+EAA+E;IAC/E,qBAAqB,EAAE,CAAC;IAExB,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import type {\n\tAnthropicMessagesCompat,\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\n\nconst NON_VISION_USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst NON_VISION_TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\nconst NON_DOCUMENT_USER_PLACEHOLDER = \"(document omitted: model does not support document input)\";\n\n/**\n * Whether the target model's API adjudicates thinking-block model binding itself.\n *\n * Anthropic's preserved-thinking rules make the API, not the client, the authority on which\n * thinking blocks a model may read: \"Pass blocks back unchanged. Send every assistant turn\n * exactly as you received it, thinking blocks included, and let the API decide which blocks the\n * model can use\", and \"A block that fails the model check is always dropped\" before the prompt\n * reaches the model, unbilled.\n * https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking\n *\n * Flattening those blocks into visible text client-side is both lossy (a newer model that is\n * allowed to read them loses the reasoning) and destabilizing (it rewrites the conversation\n * prefix that later thinking-block signatures are bound to). Models whose generated metadata\n * sets this flag replay foreign signed blocks unchanged instead.\n */\nfunction delegatesThinkingModelBinding<TApi extends Api>(model: Model<TApi>): boolean {\n\tif (model.api !== \"anthropic-messages\") return false;\n\tconst compat = model.compat as AnthropicMessagesCompat | undefined;\n\treturn compat?.delegatesThinkingModelBinding === true;\n}\n\n// Preserves the caller's block union minus images, so a user message keeps its document blocks\n// while a tool result — which cannot carry one — keeps its narrower type.\nfunction replaceImagesWithPlaceholder<TBlock extends { type: string }>(\n\tcontent: TBlock[],\n\tplaceholder: string,\n): (Exclude<TBlock, ImageContent> | TextContent)[] {\n\tconst result: (Exclude<TBlock, ImageContent> | TextContent)[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\") {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst kept = block as Exclude<TBlock, ImageContent>;\n\t\tresult.push(kept);\n\t\tpreviousWasPlaceholder = kept.type === \"text\" && (kept as unknown as TextContent).text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tif (model.input.includes(\"image\")) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg): Message => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\treturn msg;\n\t});\n}\n\n/**\n * Replace document blocks with a visible placeholder for models that cannot receive one.\n *\n * Mirrors the image downgrade: only the Anthropic Messages and Amazon Bedrock Converse paths can\n * serialize a document, so every other provider — and any Claude mirror whose generated `input`\n * omits `\"pdf\"` — gets a marker rather than a silently missing attachment or a rejected request.\n * Documents only ever appear in user messages; tool results stay text/image-only.\n */\nfunction downgradeUnsupportedDocuments<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tif (model.input.includes(\"pdf\")) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg) => {\n\t\tif (msg.role !== \"user\" || !Array.isArray(msg.content)) return msg;\n\t\tif (!msg.content.some((block) => block.type === \"document\")) return msg;\n\n\t\tconst content: (TextContent | ImageContent)[] = [];\n\t\tlet previousWasPlaceholder = false;\n\t\tfor (const block of msg.content) {\n\t\t\tif (block.type === \"document\") {\n\t\t\t\tif (!previousWasPlaceholder) content.push({ type: \"text\", text: NON_DOCUMENT_USER_PLACEHOLDER });\n\t\t\t\tpreviousWasPlaceholder = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcontent.push(block);\n\t\t\tpreviousWasPlaceholder = block.type === \"text\" && block.text === NON_DOCUMENT_USER_PLACEHOLDER;\n\t\t}\n\t\treturn { ...msg, content };\n\t});\n}\n\n/**\n * Normalize tool call ID for cross-provider compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).\n */\nexport function transformMessages<TApi extends Api>(\n\tmessages: Message[],\n\tmodel: Model<TApi>,\n\tnormalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,\n): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs\n\tconst toolCallIdMap = new Map<string, string>();\n\t// Tool calls dropped for preceding a fallback boundary. Their results must go too: a\n\t// `tool_result` whose `tool_use` is absent is rejected, and `ToolResultMessage` is a separate\n\t// top-level message so removing the call alone would orphan it.\n\tconst droppedToolCallIds = new Set<string>();\n\t// Normalize null/undefined content from untyped callers (custom tools, hand-built\n\t// histories, old session files) so downstream code can rely on the type contract.\n\tconst normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));\n\tconst imageAwareMessages = downgradeUnsupportedDocuments(\n\t\tdowngradeUnsupportedImages(normalizedMessages, model),\n\t\tmodel,\n\t);\n\n\t// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)\n\tconst transformed = imageAwareMessages.map((msg) => {\n\t\t// System and user messages pass through unchanged\n\t\tif (msg.role === \"system\" || msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tassistantMsg.model === model.id;\n\t\t\t// A different model on the same provider and API whose API adjudicates model binding\n\t\t\t// itself. Its signed blocks replay unchanged; the API keeps the ones the target model\n\t\t\t// may read and silently drops the rest.\n\t\t\tconst canReplayForeignThinking =\n\t\t\t\t!isSameModel &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tdelegatesThinkingModelBinding(model);\n\t\t\tconst preservesThinking = isSameModel || canReplayForeignThinking;\n\n\t\t\t// After a mid-output server-side fallback the turn holds output from two models either\n\t\t\t// side of a `fallback` marker. Anthropic's replay rules: keep the marker \"exactly where\n\t\t\t// it appeared\", keep `text` and everything after it, and drop `thinking`,\n\t\t\t// `redacted_thinking`, and client-side `tool_use` that precede the final marker. A\n\t\t\t// request that echoes thinking from both sides is rejected outright, so this is a\n\t\t\t// correctness requirement rather than a token saving — and it applies even when the\n\t\t\t// blocks would otherwise be replayable.\n\t\t\t// https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n\t\t\t// `findLastIndex` needs ES2023; this package targets ES2022.\n\t\t\tlet finalFallbackIndex = -1;\n\t\t\tfor (let i = assistantMsg.content.length - 1; i >= 0; i--) {\n\t\t\t\tif (assistantMsg.content[i].type === \"fallback\") {\n\t\t\t\t\tfinalFallbackIndex = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst transformedContent = assistantMsg.content.flatMap((block, blockIndex) => {\n\t\t\t\tconst precedesFallbackBoundary = finalFallbackIndex >= 0 && blockIndex < finalFallbackIndex;\n\n\t\t\t\tif (block.type === \"fallback\") {\n\t\t\t\t\t// Only the final marker is load-bearing for validation, but earlier ones are\n\t\t\t\t\t// equally \"where they appeared\", so every marker is preserved in place.\n\t\t\t\t\treturn block;\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (precedesFallbackBoundary) return [];\n\t\t\t\t\t// Redacted thinking is opaque encrypted content the client cannot rewrite.\n\t\t\t\t\t// Replay it where the API adjudicates it; otherwise drop it to avoid API errors.\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\treturn preservesThinking ? block : [];\n\t\t\t\t\t}\n\t\t\t\t\t// Keep signed thinking blocks for replay even when the thinking text is empty\n\t\t\t\t\t// (OpenAI encrypted reasoning, or Anthropic `display: \"omitted\"`).\n\t\t\t\t\tif (preservesThinking && block.thinkingSignature) return block;\n\t\t\t\t\t// Skip empty thinking blocks, convert others to plain text\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (preservesThinking) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\t// Client-side `tool_use` before the final fallback marker must be dropped: the\n\t\t\t\t\t// declining model's tool call was never executed by the model that continued.\n\t\t\t\t\t// Record the id so its `toolResult` message is dropped alongside it.\n\t\t\t\t\tif (precedesFallbackBoundary) {\n\t\t\t\t\t\tdroppedToolCallIds.add(block.id);\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Drop the tool results whose calls were removed at a fallback boundary. Anthropic rejects a\n\t// `tool_result` with no matching `tool_use`, so removing the call without its result would\n\t// trade one rejection for another.\n\tconst boundaryFiltered =\n\t\tdroppedToolCallIds.size === 0\n\t\t\t? transformed\n\t\t\t: transformed.filter((msg) => msg.role !== \"toolResult\" || !droppedToolCallIds.has(msg.toolCallId));\n\n\t// Second pass: insert synthetic empty tool results for orphaned tool calls\n\t// This preserves thinking signatures and satisfies API requirements\n\tconst result: Message[] = [];\n\tlet pendingToolCalls: ToolCall[] = [];\n\tlet existingToolResultIds = new Set<string>();\n\t// System messages are transparent to tool-call accounting: one that lands between a tool\n\t// call and its results is held back and emitted after the results (synthetic ones\n\t// included), so it never causes a duplicate result for a call that is answered later.\n\tconst heldSystemMessages: Message[] = [];\n\tconst closePendingToolCalls = () => {\n\t\tif (pendingToolCalls.length > 0) {\n\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\tresult.push({\n\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpendingToolCalls = [];\n\t\t\texistingToolResultIds = new Set();\n\t\t}\n\t\tresult.push(...heldSystemMessages);\n\t\theldSystemMessages.length = 0;\n\t};\n\n\tfor (let i = 0; i < boundaryFiltered.length; i++) {\n\t\tconst msg = boundaryFiltered[i];\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\t// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now\n\t\t\tclosePendingToolCalls();\n\n\t\t\t// Skip errored/aborted assistant messages entirely.\n\t\t\t// These are incomplete turns that shouldn't be replayed:\n\t\t\t// - May have partial content (reasoning without message, incomplete tool calls)\n\t\t\t// - Replaying them can cause API errors (e.g., OpenAI \"reasoning without following item\")\n\t\t\t// - The model should retry from the last valid state\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tif (assistantMsg.stopReason === \"error\" || assistantMsg.stopReason === \"aborted\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Track tool calls from this assistant message\n\t\t\tconst toolCalls = assistantMsg.content.filter((b) => b.type === \"toolCall\") as ToolCall[];\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tpendingToolCalls = toolCalls;\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\texistingToolResultIds.add(msg.toolCallId);\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"system\") {\n\t\t\tif (pendingToolCalls.length > 0) {\n\t\t\t\theldSystemMessages.push(msg);\n\t\t\t} else {\n\t\t\t\tresult.push(msg);\n\t\t\t}\n\t\t} else if (msg.role === \"user\") {\n\t\t\t// A new user turn interrupts tool flow - insert synthetic results for orphaned calls\n\t\t\tclosePendingToolCalls();\n\t\t\tresult.push(msg);\n\t\t} else {\n\t\t\tresult.push(msg);\n\t\t}\n\t}\n\n\t// If the conversation ends with unresolved tool calls, synthesize results now.\n\tclosePendingToolCalls();\n\n\treturn result;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-store.d.ts","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,UAAU,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEpG;;;;GAIG;AACH,qBAAa,uBAAwB,YAAW,eAAe;IAC9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AO,CAAC,UAAU,GAAG,SAAS,CAAC,CAajC;IAED,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAQxE;CACD","sourcesContent":["import { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"./types.ts\";\n\n/**\n * Default in-memory credential store. Apps inject persistent stores.\n * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.\n * Writes are serialized per provider through a promise chain.\n */\nexport class InMemoryCredentialStore implements CredentialStore {\n\tprivate credentials = new Map<string, Credential>();\n\tprivate chains = new Map<string, Promise<unknown>>();\n\n\t/** Serialize tasks per provider id without releasing the chain before active work settles. */\n\tprivate enqueue<T>(providerId: string, task: () => Promise<T>, options?: AuthOperationOptions): Promise<T> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst previous = this.chains.get(providerId) ?? Promise.resolve();\n\t\tconst queued = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = queued.catch(() => {});\n\t\tthis.chains.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.chains.get(providerId) === tail) this.chains.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(queued, signal);\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn this.credentials.get(providerId);\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tconst signal = operationSignal(options?.signal);\n\t\t\t\tconst current = this.credentials.get(providerId);\n\t\t\t\tconst next = await raceWithAbortSignal(fn(current), signal);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (next !== undefined) this.credentials.set(providerId, next);\n\t\t\t\treturn next ?? current;\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tthis.credentials.delete(providerId);\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n}\n"]}
|
|
@@ -34,9 +34,10 @@ export class InMemoryCredentialStore {
|
|
|
34
34
|
}
|
|
35
35
|
modify(providerId, fn, options) {
|
|
36
36
|
return this.enqueue(providerId, async () => {
|
|
37
|
+
const signal = operationSignal(options?.signal);
|
|
37
38
|
const current = this.credentials.get(providerId);
|
|
38
|
-
const next = await fn(current);
|
|
39
|
-
|
|
39
|
+
const next = await raceWithAbortSignal(fn(current), signal);
|
|
40
|
+
signal.throwIfAborted();
|
|
40
41
|
if (next !== undefined)
|
|
41
42
|
this.credentials.set(providerId, next);
|
|
42
43
|
return next ?? current;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-store.js","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAGzE;;;;GAIG;AACH,MAAM,OAAO,uBAAuB;IAC3B,WAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;IAC5C,MAAM,GAAG,IAAI,GAAG,EAA4B,CAAC;IAErD,8FAA8F;IACtF,OAAO,CAAI,UAAkB,EAAE,IAAsB,EAAE,OAA8B,EAAc;QAC1G,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,EAAE,MAAM,CAA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C,UAAU,EAAE,IAAI,CAAC,CAAC;YAC/D,OAAO,IAAI,IAAI,OAAO,CAAC;QAAA,CACvB,EACD,OAAO,CACP,CAAC;IAAA,CACF;IAED,MAAM,CAAC,UAAkB,EAAE,OAA8B,EAAiB;QACzE,OAAO,IAAI,CAAC,OAAO,CAClB,UAAU,EACV,KAAK,IAAI,EAAE,CAAC;YACX,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAAA,CACpC,EACD,OAAO,CACP,CAAC;IAAA,CACF;CACD","sourcesContent":["import { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"./types.ts\";\n\n/**\n * Default in-memory credential store. Apps inject persistent stores.\n * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.\n * Writes are serialized per provider through a promise chain.\n */\nexport class InMemoryCredentialStore implements CredentialStore {\n\tprivate credentials = new Map<string, Credential>();\n\tprivate chains = new Map<string, Promise<unknown>>();\n\n\t/** Serialize tasks per provider id without releasing the chain before active work settles. */\n\tprivate enqueue<T>(providerId: string, task: () => Promise<T>, options?: AuthOperationOptions): Promise<T> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst previous = this.chains.get(providerId) ?? Promise.resolve();\n\t\tconst queued = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = queued.catch(() => {});\n\t\tthis.chains.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.chains.get(providerId) === tail) this.chains.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(queued, signal);\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn this.credentials.get(providerId);\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tconst signal = operationSignal(options?.signal);\n\t\t\t\tconst current = this.credentials.get(providerId);\n\t\t\t\tconst next = await raceWithAbortSignal(fn(current), signal);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (next !== undefined) this.credentials.set(providerId, next);\n\t\t\t\treturn next ?? current;\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tthis.credentials.delete(providerId);\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n}\n"]}
|
package/dist/auth/resolve.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { ProviderEnv } from "../types.ts";
|
|
2
2
|
import type { AuthContext, AuthResult, CredentialStore, ProviderAuth } from "./types.ts";
|
|
3
3
|
export type ModelsErrorCode = "model_source" | "model_validation" | "provider" | "stream" | "auth" | "oauth";
|
|
4
|
+
/** Bound for pre-transport request-auth work: credential read, OAuth refresh, and toAuth. */
|
|
5
|
+
export declare const REQUEST_AUTH_PREPARATION_TIMEOUT_MS = 15000;
|
|
6
|
+
/** Source-neutral diagnostic when pre-transport request auth exceeds {@link REQUEST_AUTH_PREPARATION_TIMEOUT_MS}. */
|
|
7
|
+
export declare function requestAuthTimeoutMessage(providerId: string): string;
|
|
4
8
|
export interface AuthResolutionOverrides {
|
|
5
9
|
apiKey?: string;
|
|
6
10
|
env?: ProviderEnv;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.d.ts","sourceRo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AAU,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;AAE7G,6FAA6F;AAC7F,eAAO,MAAM,mCAAmC,QAAS,CAAC;AAE1D,qHAAqH;AACrH,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAEpE;AAED,MAAM,WAAW,uBAAuB;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,WAAW,CAAC;IAClB,kFAAkF;IAClF,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,qBAAa,WAAY,SAAQ,KAAK;IACrC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAE/B,YAAY,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAIhF;CACD;AAUD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAClC,QAAQ,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,YAAY,CAAA;CAAE,EAC5C,WAAW,EAAE,eAAe,EAC5B,WAAW,EAAE,WAAW,EACxB,SAAS,CAAC,EAAE,uBAAuB,GACjC,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAwBjC","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { formatThrownValue } from \"../utils/diagnostics.ts\";\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\n/** Bound for pre-transport request-auth work: credential read, OAuth refresh, and toAuth. */\nexport const REQUEST_AUTH_PREPARATION_TIMEOUT_MS = 15_000;\n\n/** Source-neutral diagnostic when pre-transport request auth exceeds {@link REQUEST_AUTH_PREPARATION_TIMEOUT_MS}. */\nexport function requestAuthTimeoutMessage(providerId: string): string {\n\treturn `Request authentication timed out for ${providerId}. Check the provider's credential source and try again.`;\n}\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n\tsignal?: AbortSignal;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(withCauseDetail(message, options?.cause), options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Callers surface `error.message` only, so keep the underlying reason in it. */\nfunction withCauseDetail(message: string, cause: unknown): string {\n\tif (cause === undefined || cause === null) return message;\n\tconst detail = formatThrownValue(cause).trim();\n\tif (!detail || message.includes(detail)) return message;\n\treturn `${message}: ${detail}`;\n}\n\n/**\n * Auth resolution shared by the `Models` and `ImagesModels` collections.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst caller = operationSignal(overrides?.signal);\n\tconst timeout = new AbortController();\n\tconst timer = setTimeout(() => {\n\t\ttimeout.abort();\n\t}, REQUEST_AUTH_PREPARATION_TIMEOUT_MS);\n\tconst signal = AbortSignal.any([caller, timeout.signal]);\n\tconst operation = resolveProviderAuthWithSignal(\n\t\tprovider,\n\t\tcredentials,\n\t\tauthContext,\n\t\t{ ...overrides, signal },\n\t\tsignal,\n\t);\n\treturn raceWithAbortSignal(operation, signal)\n\t\t.catch((error: unknown) => {\n\t\t\tif (timeout.signal.aborted && !caller.aborted) {\n\t\t\t\tthrow new ModelsError(\"auth\", requestAuthTimeoutMessage(provider.id));\n\t\t\t}\n\t\t\tthrow error;\n\t\t})\n\t\t.finally(() => {\n\t\t\tclearTimeout(timer);\n\t\t});\n}\n\nasync function resolveProviderAuthWithSignal(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides: AuthResolutionOverrides | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\tsignal.throwIfAborted();\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(\n\t\t\trequestAuthContext,\n\t\t\tprovider.auth.apiKey,\n\t\t\tprovider.id,\n\t\t\t{\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: overrides.apiKey,\n\t\t\t\tenv: overrides.env,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id, signal);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(\n\t\t\t\tcredentials,\n\t\t\t\tprovider.id,\n\t\t\t\tprovider.auth.oauth,\n\t\t\t\tstored,\n\t\t\t\tsignal,\n\t\t\t\toverrides?.minOAuthValidityMs,\n\t\t\t);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey\n\t\t? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined, signal)\n\t\t: undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\nconst DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;\n\n/**\n * OAuth resolution with double-checked locking: tokens with less than five\n * minutes remaining lock, re-check expiry under the lock, refresh once\n * globally, and persist the rotated credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n\tsignal: AbortSignal,\n\tminOAuthValidityMs?: number,\n): Promise<AuthResult | undefined> {\n\tconst minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);\n\tconst expiresSoon = (credential: OAuthCredential) => Date.now() + minimumValidityMs >= credential.expires;\n\tlet credential = stored;\n\n\tif (expiresSoon(credential)) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tlet post: Credential | undefined;\n\t\ttry {\n\t\t\tpost = await credentials.modify(\n\t\t\t\tproviderId,\n\t\t\t\tasync (current) => {\n\t\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\t\tif (!expiresSoon(current)) return undefined; // another process/request refreshed\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await raceWithAbortSignal(oauth.refresh(current, signal), signal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (signal.aborted) throw error;\n\t\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelsError) throw error;\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\tif (post?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t\t// The normal five-minute window triggers a refresh but does not impose a\n\t\t// provider contract. Explicit callers (such as bearer-token export) do\n\t\t// require the requested minimum after the refresh.\n\t\tif (minOAuthValidityMs !== undefined && expiresSoon(credential)) {\n\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh returned a token that expires too soon for ${providerId}`);\n\t\t}\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tproviderId: string,\n\tcredential: ApiKeyCredential | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ ctx: authContext, credential, signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${providerId}`, { cause: error });\n\t}\n}\n\nasync function readCredential(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\tsignal: AbortSignal,\n): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId, { signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n"]}
|
package/dist/auth/resolve.js
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { operationSignal, raceWithAbortSignal } from "../utils/abort.js";
|
|
2
2
|
import { formatThrownValue } from "../utils/diagnostics.js";
|
|
3
|
+
/** Bound for pre-transport request-auth work: credential read, OAuth refresh, and toAuth. */
|
|
4
|
+
export const REQUEST_AUTH_PREPARATION_TIMEOUT_MS = 15_000;
|
|
5
|
+
/** Source-neutral diagnostic when pre-transport request auth exceeds {@link REQUEST_AUTH_PREPARATION_TIMEOUT_MS}. */
|
|
6
|
+
export function requestAuthTimeoutMessage(providerId) {
|
|
7
|
+
return `Request authentication timed out for ${providerId}. Check the provider's credential source and try again.`;
|
|
8
|
+
}
|
|
3
9
|
export class ModelsError extends Error {
|
|
4
10
|
code;
|
|
5
11
|
constructor(code, message, options) {
|
|
@@ -24,8 +30,23 @@ function withCauseDetail(message, cause) {
|
|
|
24
30
|
* credential type without a matching handler.
|
|
25
31
|
*/
|
|
26
32
|
export function resolveProviderAuth(provider, credentials, authContext, overrides) {
|
|
27
|
-
const
|
|
28
|
-
|
|
33
|
+
const caller = operationSignal(overrides?.signal);
|
|
34
|
+
const timeout = new AbortController();
|
|
35
|
+
const timer = setTimeout(() => {
|
|
36
|
+
timeout.abort();
|
|
37
|
+
}, REQUEST_AUTH_PREPARATION_TIMEOUT_MS);
|
|
38
|
+
const signal = AbortSignal.any([caller, timeout.signal]);
|
|
39
|
+
const operation = resolveProviderAuthWithSignal(provider, credentials, authContext, { ...overrides, signal }, signal);
|
|
40
|
+
return raceWithAbortSignal(operation, signal)
|
|
41
|
+
.catch((error) => {
|
|
42
|
+
if (timeout.signal.aborted && !caller.aborted) {
|
|
43
|
+
throw new ModelsError("auth", requestAuthTimeoutMessage(provider.id));
|
|
44
|
+
}
|
|
45
|
+
throw error;
|
|
46
|
+
})
|
|
47
|
+
.finally(() => {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
});
|
|
29
50
|
}
|
|
30
51
|
async function resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal) {
|
|
31
52
|
signal.throwIfAborted();
|
|
@@ -60,7 +81,6 @@ function overlayEnvAuthContext(base, env) {
|
|
|
60
81
|
};
|
|
61
82
|
}
|
|
62
83
|
const DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;
|
|
63
|
-
const DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15_000;
|
|
64
84
|
/**
|
|
65
85
|
* OAuth resolution with double-checked locking: tokens with less than five
|
|
66
86
|
* minutes remaining lock, re-check expiry under the lock, refresh once
|
|
@@ -80,13 +100,11 @@ async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal
|
|
|
80
100
|
if (!expiresSoon(current))
|
|
81
101
|
return undefined; // another process/request refreshed
|
|
82
102
|
try {
|
|
83
|
-
|
|
84
|
-
signal,
|
|
85
|
-
AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS),
|
|
86
|
-
]);
|
|
87
|
-
return await oauth.refresh(current, refreshSignal);
|
|
103
|
+
return await raceWithAbortSignal(oauth.refresh(current, signal), signal);
|
|
88
104
|
}
|
|
89
105
|
catch (error) {
|
|
106
|
+
if (signal.aborted)
|
|
107
|
+
throw error;
|
|
90
108
|
throw new ModelsError("oauth", `OAuth refresh failed for ${providerId}`, { cause: error });
|
|
91
109
|
}
|
|
92
110
|
}, { signal });
|
|
@@ -94,6 +112,7 @@ async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal
|
|
|
94
112
|
catch (error) {
|
|
95
113
|
if (error instanceof ModelsError)
|
|
96
114
|
throw error;
|
|
115
|
+
signal.throwIfAborted();
|
|
97
116
|
throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
|
|
98
117
|
}
|
|
99
118
|
if (post?.type !== "oauth")
|
package/dist/auth/resolve.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAuB5D,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC5B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B,EAAE;QAClF,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;Q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Aa,CAC3B,WAAwB,EACxB,MAAkB,EAClB,UAAkB,EAClB,UAAwC,EACxC,MAAmB,EACe;IAClC,IAAI,CAAC;QACJ,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;IACvE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;AAAA,CACD;AAED,KAAK,UAAU,cAAc,CAC5B,WAA4B,EAC5B,UAAkB,EAClB,MAAmB,EACe;IAClC,IAAI,CAAC;QACJ,OAAO,MAAM,WAAW,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IACvD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;AAAA,CACD","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { formatThrownValue } from \"../utils/diagnostics.ts\";\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n\tsignal?: AbortSignal;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(withCauseDetail(message, options?.cause), options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Callers surface `error.message` only, so keep the underlying reason in it. */\nfunction withCauseDetail(message: string, cause: unknown): string {\n\tif (cause === undefined || cause === null) return message;\n\tconst detail = formatThrownValue(cause).trim();\n\tif (!detail || message.includes(detail)) return message;\n\treturn `${message}: ${detail}`;\n}\n\n/**\n * Auth resolution shared by the `Models` and `ImagesModels` collections.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst signal = operationSignal(overrides?.signal);\n\treturn raceWithAbortSignal(\n\t\tresolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal),\n\t\tsignal,\n\t);\n}\n\nasync function resolveProviderAuthWithSignal(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides: AuthResolutionOverrides | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\tsignal.throwIfAborted();\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(\n\t\t\trequestAuthContext,\n\t\t\tprovider.auth.apiKey,\n\t\t\tprovider.id,\n\t\t\t{\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: overrides.apiKey,\n\t\t\t\tenv: overrides.env,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id, signal);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(\n\t\t\t\tcredentials,\n\t\t\t\tprovider.id,\n\t\t\t\tprovider.auth.oauth,\n\t\t\t\tstored,\n\t\t\t\tsignal,\n\t\t\t\toverrides?.minOAuthValidityMs,\n\t\t\t);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey\n\t\t? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined, signal)\n\t\t: undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\nconst DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;\nconst DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15_000;\n\n/**\n * OAuth resolution with double-checked locking: tokens with less than five\n * minutes remaining lock, re-check expiry under the lock, refresh once\n * globally, and persist the rotated credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n\tsignal: AbortSignal,\n\tminOAuthValidityMs?: number,\n): Promise<AuthResult | undefined> {\n\tconst minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);\n\tconst expiresSoon = (credential: OAuthCredential) => Date.now() + minimumValidityMs >= credential.expires;\n\tlet credential = stored;\n\n\tif (expiresSoon(credential)) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tlet post: Credential | undefined;\n\t\ttry {\n\t\t\tpost = await credentials.modify(\n\t\t\t\tproviderId,\n\t\t\t\tasync (current) => {\n\t\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\t\tif (!expiresSoon(current)) return undefined; // another process/request refreshed\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst refreshSignal = AbortSignal.any([\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tAbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn await oauth.refresh(current, refreshSignal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelsError) throw error;\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\tif (post?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t\t// The normal five-minute window triggers a refresh but does not impose a\n\t\t// provider contract. Explicit callers (such as bearer-token export) do\n\t\t// require the requested minimum after the refresh.\n\t\tif (minOAuthValidityMs !== undefined && expiresSoon(credential)) {\n\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh returned a token that expires too soon for ${providerId}`);\n\t\t}\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tproviderId: string,\n\tcredential: ApiKeyCredential | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ ctx: authContext, credential, signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${providerId}`, { cause: error });\n\t}\n}\n\nasync function readCredential(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\tsignal: AbortSignal,\n): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId, { signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAe5D,6FAA6F;AAC7F,MAAM,CAAC,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAE1D,qHAAqH;AACrH,MAAM,UAAU,yBAAyB,CAAC,UAAkB,EAAU;IACrE,OAAO,wCAAwC,UAAU,yDAAyD,CAAC;AAAA,CACnH;AAUD,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC5B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B,EAAE;QAClF,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;QACzD,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD;AAED,iFAAiF;AACjF,SAAS,eAAe,CAAC,OAAe,EAAE,KAAc,EAAU;IACjE,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,OAAO,CAAC;IAC1D,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/C,IAAI,CAAC,MAAM,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA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O,EAAE,IAAI,EAAE,MAAM,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;IAClE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,OAAO,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACpG,CAAC;AAAA,CACD;AAED,KAAK,UAAU,aAAa,CAC3B,WAAwB,EACxB,MAAkB,EAClB,UAAkB,EAClB,UAAwC,EACxC,MAAmB,EACe;IAClC,IAAI,CAAC;QACJ,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;IACvE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;AAAA,CACD;AAED,KAAK,UAAU,cAAc,CAC5B,WAA4B,EAC5B,UAAkB,EAClB,MAAmB,EACe;IAClC,IAAI,CAAC;QACJ,OAAO,MAAM,WAAW,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IACvD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;AAAA,CACD","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { formatThrownValue } from \"../utils/diagnostics.ts\";\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\n/** Bound for pre-transport request-auth work: credential read, OAuth refresh, and toAuth. */\nexport const REQUEST_AUTH_PREPARATION_TIMEOUT_MS = 15_000;\n\n/** Source-neutral diagnostic when pre-transport request auth exceeds {@link REQUEST_AUTH_PREPARATION_TIMEOUT_MS}. */\nexport function requestAuthTimeoutMessage(providerId: string): string {\n\treturn `Request authentication timed out for ${providerId}. Check the provider's credential source and try again.`;\n}\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n\tsignal?: AbortSignal;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(withCauseDetail(message, options?.cause), options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Callers surface `error.message` only, so keep the underlying reason in it. */\nfunction withCauseDetail(message: string, cause: unknown): string {\n\tif (cause === undefined || cause === null) return message;\n\tconst detail = formatThrownValue(cause).trim();\n\tif (!detail || message.includes(detail)) return message;\n\treturn `${message}: ${detail}`;\n}\n\n/**\n * Auth resolution shared by the `Models` and `ImagesModels` collections.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst caller = operationSignal(overrides?.signal);\n\tconst timeout = new AbortController();\n\tconst timer = setTimeout(() => {\n\t\ttimeout.abort();\n\t}, REQUEST_AUTH_PREPARATION_TIMEOUT_MS);\n\tconst signal = AbortSignal.any([caller, timeout.signal]);\n\tconst operation = resolveProviderAuthWithSignal(\n\t\tprovider,\n\t\tcredentials,\n\t\tauthContext,\n\t\t{ ...overrides, signal },\n\t\tsignal,\n\t);\n\treturn raceWithAbortSignal(operation, signal)\n\t\t.catch((error: unknown) => {\n\t\t\tif (timeout.signal.aborted && !caller.aborted) {\n\t\t\t\tthrow new ModelsError(\"auth\", requestAuthTimeoutMessage(provider.id));\n\t\t\t}\n\t\t\tthrow error;\n\t\t})\n\t\t.finally(() => {\n\t\t\tclearTimeout(timer);\n\t\t});\n}\n\nasync function resolveProviderAuthWithSignal(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides: AuthResolutionOverrides | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\tsignal.throwIfAborted();\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(\n\t\t\trequestAuthContext,\n\t\t\tprovider.auth.apiKey,\n\t\t\tprovider.id,\n\t\t\t{\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: overrides.apiKey,\n\t\t\t\tenv: overrides.env,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id, signal);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(\n\t\t\t\tcredentials,\n\t\t\t\tprovider.id,\n\t\t\t\tprovider.auth.oauth,\n\t\t\t\tstored,\n\t\t\t\tsignal,\n\t\t\t\toverrides?.minOAuthValidityMs,\n\t\t\t);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey\n\t\t? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined, signal)\n\t\t: undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\nconst DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;\n\n/**\n * OAuth resolution with double-checked locking: tokens with less than five\n * minutes remaining lock, re-check expiry under the lock, refresh once\n * globally, and persist the rotated credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n\tsignal: AbortSignal,\n\tminOAuthValidityMs?: number,\n): Promise<AuthResult | undefined> {\n\tconst minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);\n\tconst expiresSoon = (credential: OAuthCredential) => Date.now() + minimumValidityMs >= credential.expires;\n\tlet credential = stored;\n\n\tif (expiresSoon(credential)) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tlet post: Credential | undefined;\n\t\ttry {\n\t\t\tpost = await credentials.modify(\n\t\t\t\tproviderId,\n\t\t\t\tasync (current) => {\n\t\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\t\tif (!expiresSoon(current)) return undefined; // another process/request refreshed\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await raceWithAbortSignal(oauth.refresh(current, signal), signal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (signal.aborted) throw error;\n\t\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelsError) throw error;\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\tif (post?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t\t// The normal five-minute window triggers a refresh but does not impose a\n\t\t// provider contract. Explicit callers (such as bearer-token export) do\n\t\t// require the requested minimum after the refresh.\n\t\tif (minOAuthValidityMs !== undefined && expiresSoon(credential)) {\n\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh returned a token that expires too soon for ${providerId}`);\n\t\t}\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tproviderId: string,\n\tcredential: ApiKeyCredential | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ ctx: authContext, credential, signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${providerId}`, { cause: error });\n\t}\n}\n\nasync function readCredential(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\tsignal: AbortSignal,\n): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId, { signal });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n"]}
|
package/dist/compat.d.ts
CHANGED
|
@@ -29,15 +29,15 @@ export * from "./providers/images/register-builtins.ts";
|
|
|
29
29
|
import { getBuiltinModel, getBuiltinModels, getBuiltinProviders } from "./providers/all.ts";
|
|
30
30
|
export type { BuiltinProvider } from "./providers/all.ts";
|
|
31
31
|
import { type FauxProviderRegistration, type RegisterFauxProviderOptions } from "./providers/faux.ts";
|
|
32
|
-
import type { Api, AssistantMessage, AssistantMessageEventStream, Context, Model, ProviderStreamOptions, SimpleStreamOptions, StreamFunction, StreamOptions } from "./types.ts";
|
|
32
|
+
import type { Api, AssistantMessage, AssistantMessageEventStream, Context, Model, ProviderStreamOptions, SimpleStreamOptions, StreamFunction, StreamOptions, TranscriptContext } from "./types.ts";
|
|
33
33
|
/** @deprecated Static catalog read. Use `getBuiltinModel` from "@bastani/pi-ai/providers/all" or `Models.getModel()`. */
|
|
34
34
|
export declare const getModel: typeof getBuiltinModel;
|
|
35
35
|
/** @deprecated Static catalog read. Use `getBuiltinModels` from "@bastani/pi-ai/providers/all" or `Models.getModels()`. */
|
|
36
36
|
export declare const getModels: typeof getBuiltinModels;
|
|
37
37
|
/** @deprecated Static catalog read. Use `getBuiltinProviders` from "@bastani/pi-ai/providers/all" or `Models.getProviders()`. */
|
|
38
38
|
export declare const getProviders: typeof getBuiltinProviders;
|
|
39
|
-
export type ApiStreamFunction = (model: Model<Api>, context:
|
|
40
|
-
export type ApiStreamSimpleFunction = (model: Model<Api>, context:
|
|
39
|
+
export type ApiStreamFunction = (model: Model<Api>, context: TranscriptContext, options?: StreamOptions) => AssistantMessageEventStream;
|
|
40
|
+
export type ApiStreamSimpleFunction = (model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) => AssistantMessageEventStream;
|
|
41
41
|
export interface ApiProvider<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> {
|
|
42
42
|
api: TApi;
|
|
43
43
|
stream: StreamFunction<TApi, TOptions>;
|
package/dist/compat.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kCAAkC,CAAC;AACjD,cAAc,sCAAsC,CAAC;AACrD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B,OAAO,CAAC,gBAAgB,CAAC,CAG3B;AAED,wBAAgB,YAAY,CAAC,IAAI,SAAS,GAAG,EAC5C,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,2BAA2B,CAU7B;AAED,wBAAsB,cAAc,CAAC,IAAI,SAAS,GAAG,EACpD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAG3B","sourcesContent":["/**\n * Temporary compatibility entrypoint preserving the old global pi-ai API\n * surface: api-dispatch `stream()`/`complete()` with env API key injection,\n * the api-registry, generated catalog reads (`getModel`/`getModels`/\n * `getProviders`), per-API lazy stream wrappers, and image generation.\n *\n * Existing apps switch imports from \"@bastani/pi-ai\" to\n * \"@bastani/pi-ai/compat\" unchanged; new code uses `createModels()`\n * and the provider factories. This module is deleted with the coding-agent\n * ModelManager migration.\n */\n\nexport * from \"./api/anthropic-messages.lazy.ts\";\nexport * from \"./api/azure-openai-responses.lazy.ts\";\nexport * from \"./api/bedrock-converse-stream.lazy.ts\";\nexport * from \"./api/google-generative-ai.lazy.ts\";\nexport * from \"./api/google-vertex.lazy.ts\";\nexport * from \"./api/mistral-conversations.lazy.ts\";\nexport * from \"./api/openai-codex-responses.lazy.ts\";\nexport * from \"./api/openai-completions.lazy.ts\";\nexport * from \"./api/openai-responses.lazy.ts\";\nexport * from \"./api/pi-messages.lazy.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./image-models.ts\";\nexport * from \"./images.ts\";\nexport * from \"./images-api-registry.ts\";\nexport * from \"./index.ts\";\nexport * from \"./legacy-api-aliases.ts\";\nexport * from \"./providers/images/register-builtins.ts\";\n\nimport { anthropicMessagesApi } from \"./api/anthropic-messages.lazy.ts\";\nimport { azureOpenAIResponsesApi } from \"./api/azure-openai-responses.lazy.ts\";\nimport { bedrockConverseStreamApi } from \"./api/bedrock-converse-stream.lazy.ts\";\nimport { googleGenerativeAIApi } from \"./api/google-generative-ai.lazy.ts\";\nimport { googleVertexApi } from \"./api/google-vertex.lazy.ts\";\nimport { mistralConversationsApi } from \"./api/mistral-conversations.lazy.ts\";\nimport { openAICodexResponsesApi } from \"./api/openai-codex-responses.lazy.ts\";\nimport { openAICompletionsApi } from \"./api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"./api/openai-responses.lazy.ts\";\nimport { piMessagesApi } from \"./api/pi-messages.lazy.ts\";\nimport { getEnvApiKey } from \"./env-api-keys.ts\";\nimport type { ModelsApiStreamOptions } from \"./models.ts\";\nimport { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from \"./providers/all.ts\";\n\nexport type { BuiltinProvider } from \"./providers/all.ts\";\n\nimport { createFauxCore, type FauxProviderRegistration, type RegisterFauxProviderOptions } from \"./providers/faux.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n} from \"./types.ts\";\n\n/** @deprecated Static catalog read. Use `getBuiltinModel` from \"@bastani/pi-ai/providers/all\" or `Models.getModel()`. */\nexport const getModel = getBuiltinModel;\n\n/** @deprecated Static catalog read. Use `getBuiltinModels` from \"@bastani/pi-ai/providers/all\" or `Models.getModels()`. */\nexport const getModels = getBuiltinModels;\n\n/** @deprecated Static catalog read. Use `getBuiltinProviders` from \"@bastani/pi-ai/providers/all\" or `Models.getProviders()`. */\nexport const getProviders = getBuiltinProviders;\n\nexport type ApiStreamFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: StreamOptions,\n) => AssistantMessageEventStream;\n\nexport type ApiStreamSimpleFunction = (\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream;\n\nexport interface ApiProvider<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> {\n\tapi: TApi;\n\tstream: StreamFunction<TApi, TOptions>;\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>;\n}\n\ninterface ApiProviderInternal {\n\tapi: Api;\n\tstream: ApiStreamFunction;\n\tstreamSimple: ApiStreamSimpleFunction;\n}\n\ntype RegisteredApiProvider = {\n\tprovider: ApiProviderInternal;\n\tsourceId?: string;\n};\n\nconst apiProviderRegistry = new Map<string, RegisteredApiProvider>();\n\nfunction wrapStream<TApi extends Api, TOptions extends StreamOptions>(\n\tapi: TApi,\n\tstream: StreamFunction<TApi, TOptions>,\n): ApiStreamFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn stream(model as Model<TApi>, context, options as TOptions);\n\t};\n}\n\nfunction wrapStreamSimple<TApi extends Api>(\n\tapi: TApi,\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>,\n): ApiStreamSimpleFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn streamSimple(model as Model<TApi>, context, options);\n\t};\n}\n\nexport function registerApiProvider<TApi extends Api, TOptions extends StreamOptions>(\n\tprovider: ApiProvider<TApi, TOptions>,\n\tsourceId?: string,\n): void {\n\tapiProviderRegistry.set(provider.api, {\n\t\tprovider: {\n\t\t\tapi: provider.api,\n\t\t\tstream: wrapStream(provider.api, provider.stream),\n\t\t\tstreamSimple: wrapStreamSimple(provider.api, provider.streamSimple),\n\t\t},\n\t\tsourceId,\n\t});\n}\n\nexport function getApiProvider(api: Api): ApiProviderInternal | undefined {\n\treturn apiProviderRegistry.get(api)?.provider;\n}\n\nexport function getApiProviders(): ApiProviderInternal[] {\n\treturn Array.from(apiProviderRegistry.values(), (entry) => entry.provider);\n}\n\nexport function unregisterApiProviders(sourceId: string): void {\n\tfor (const [api, entry] of apiProviderRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tapiProviderRegistry.delete(api);\n\t\t}\n\t}\n}\n\nfunction clearApiProviders(): void {\n\tapiProviderRegistry.clear();\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst core = createFauxCore(options);\n\tconst sourceId = `faux-provider-${Math.random().toString(36).slice(2, 10)}`;\n\tregisterApiProvider({ api: core.api, stream: core.stream, streamSimple: core.streamSimple }, sourceId);\n\treturn {\n\t\tapi: core.api,\n\t\tmodels: core.models,\n\t\tgetModel: core.getModel,\n\t\tstate: core.state,\n\t\tsetResponses: core.setResponses,\n\t\tappendResponses: core.appendResponses,\n\t\tgetPendingResponseCount: core.getPendingResponseCount,\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n\nconst BUILTIN_APIS: [Api, ProviderStreams][] = [\n\t[\"anthropic-messages\", anthropicMessagesApi()],\n\t[\"openai-completions\", openAICompletionsApi()],\n\t[\"openai-responses\", openAIResponsesApi()],\n\t[\"openai-codex-responses\", openAICodexResponsesApi()],\n\t[\"azure-openai-responses\", azureOpenAIResponsesApi()],\n\t[\"google-generative-ai\", googleGenerativeAIApi()],\n\t[\"google-vertex\", googleVertexApi()],\n\t[\"mistral-conversations\", mistralConversationsApi()],\n\t[\"bedrock-converse-stream\", bedrockConverseStreamApi()],\n\t[\"pi-messages\", piMessagesApi()],\n];\n\nconst builtinApiProviderInstances = new Map<Api, ReturnType<typeof getApiProvider>>();\n\n/**\n * Registers the builtin API implementations into the api-registry without\n * clobbering existing entries: compat may load after a test or extension has\n * already registered an override for a builtin api id.\n */\nexport function registerBuiltInApiProviders(): void {\n\tfor (const [api, streams] of BUILTIN_APIS) {\n\t\tif (!getApiProvider(api)) {\n\t\t\tregisterApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\t}\n\t\tbuiltinApiProviderInstances.set(api, getApiProvider(api));\n\t}\n}\n\nexport function resetApiProviders(): void {\n\tclearApiProviders();\n\tbuiltinApiProviderInstances.clear();\n\tregisterBuiltInApiProviders();\n}\n\nregisterBuiltInApiProviders();\n\nconst compatModels = builtinModels();\nconst AMBIENT_AUTH_MARKER = \"<authenticated>\";\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction withEnvApiKey<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tconst apiKey = getEnvApiKey(model.provider, options?.env);\n\tif (!apiKey || apiKey === AMBIENT_AUTH_MARKER) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction hasResolvedCloudflareAuth(options: StreamOptions | undefined): boolean {\n\treturn hasExplicitApiKey(options?.apiKey) || typeof options?.headers?.[\"cf-aig-authorization\"] === \"string\";\n}\n\nfunction getBuiltinProviderForModel(model: Model<Api>) {\n\tif (getApiProvider(model.api) !== builtinApiProviderInstances.get(model.api)) return undefined;\n\tconst provider = compatModels.getProvider(model.provider);\n\treturn provider?.getModels().some((candidate) => candidate.api === model.api) ? provider : undefined;\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.stream(model, context, options as ModelsApiStreamOptions<TApi> | undefined);\n\t\t}\n\t\treturn builtinProvider.stream(model, context, withEnvApiKey(model, options) as ApiStreamOptions<TApi>);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.stream(model, context, withEnvApiKey(model, options) as StreamOptions);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.streamSimple(model, context, options);\n\t\t}\n\t\treturn builtinProvider.streamSimple(model, context, withEnvApiKey(model, options));\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.streamSimple(model, context, withEnvApiKey(model, options));\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kCAAkC,CAAC;AACjD,cAAc,sCAAsC,CAAC;AACrD,cAAc,uCAAuC,CAAC;AACtD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qCAAqC,CAAC;AACpD,cAAc,sCAAsC,CAAC;AACrD,cAAc,kCAAkC,CAAC;AACjD,cAAc,gCAAgC,CAAC;AAC/C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,aAAa,C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E,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAG3B","sourcesContent":["/**\n * Temporary compatibility entrypoint preserving the old global pi-ai API\n * surface: api-dispatch `stream()`/`complete()` with env API key injection,\n * the api-registry, generated catalog reads (`getModel`/`getModels`/\n * `getProviders`), per-API lazy stream wrappers, and image generation.\n *\n * Existing apps switch imports from \"@bastani/pi-ai\" to\n * \"@bastani/pi-ai/compat\" unchanged; new code uses `createModels()`\n * and the provider factories. This module is deleted with the coding-agent\n * ModelManager migration.\n */\n\nexport * from \"./api/anthropic-messages.lazy.ts\";\nexport * from \"./api/azure-openai-responses.lazy.ts\";\nexport * from \"./api/bedrock-converse-stream.lazy.ts\";\nexport * from \"./api/google-generative-ai.lazy.ts\";\nexport * from \"./api/google-vertex.lazy.ts\";\nexport * from \"./api/mistral-conversations.lazy.ts\";\nexport * from \"./api/openai-codex-responses.lazy.ts\";\nexport * from \"./api/openai-completions.lazy.ts\";\nexport * from \"./api/openai-responses.lazy.ts\";\nexport * from \"./api/pi-messages.lazy.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./image-models.ts\";\nexport * from \"./images.ts\";\nexport * from \"./images-api-registry.ts\";\nexport * from \"./index.ts\";\nexport * from \"./legacy-api-aliases.ts\";\nexport * from \"./providers/images/register-builtins.ts\";\n\nimport { anthropicMessagesApi } from \"./api/anthropic-messages.lazy.ts\";\nimport { azureOpenAIResponsesApi } from \"./api/azure-openai-responses.lazy.ts\";\nimport { bedrockConverseStreamApi } from \"./api/bedrock-converse-stream.lazy.ts\";\nimport { googleGenerativeAIApi } from \"./api/google-generative-ai.lazy.ts\";\nimport { googleVertexApi } from \"./api/google-vertex.lazy.ts\";\nimport { mistralConversationsApi } from \"./api/mistral-conversations.lazy.ts\";\nimport { openAICodexResponsesApi } from \"./api/openai-codex-responses.lazy.ts\";\nimport { openAICompletionsApi } from \"./api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"./api/openai-responses.lazy.ts\";\nimport { piMessagesApi } from \"./api/pi-messages.lazy.ts\";\nimport { getEnvApiKey } from \"./env-api-keys.ts\";\nimport type { ModelsApiStreamOptions } from \"./models.ts\";\nimport { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from \"./providers/all.ts\";\n\nexport type { BuiltinProvider } from \"./providers/all.ts\";\n\nimport { createFauxCore, type FauxProviderRegistration, type RegisterFauxProviderOptions } from \"./providers/faux.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTranscriptContext,\n} from \"./types.ts\";\nimport { normalizeContext } from \"./utils/transcript.ts\";\n\n/** @deprecated Static catalog read. Use `getBuiltinModel` from \"@bastani/pi-ai/providers/all\" or `Models.getModel()`. */\nexport const getModel = getBuiltinModel;\n\n/** @deprecated Static catalog read. Use `getBuiltinModels` from \"@bastani/pi-ai/providers/all\" or `Models.getModels()`. */\nexport const getModels = getBuiltinModels;\n\n/** @deprecated Static catalog read. Use `getBuiltinProviders` from \"@bastani/pi-ai/providers/all\" or `Models.getProviders()`. */\nexport const getProviders = getBuiltinProviders;\n\nexport type ApiStreamFunction = (\n\tmodel: Model<Api>,\n\tcontext: TranscriptContext,\n\toptions?: StreamOptions,\n) => AssistantMessageEventStream;\n\nexport type ApiStreamSimpleFunction = (\n\tmodel: Model<Api>,\n\tcontext: TranscriptContext,\n\toptions?: SimpleStreamOptions,\n) => AssistantMessageEventStream;\n\nexport interface ApiProvider<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> {\n\tapi: TApi;\n\tstream: StreamFunction<TApi, TOptions>;\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>;\n}\n\ninterface ApiProviderInternal {\n\tapi: Api;\n\tstream: ApiStreamFunction;\n\tstreamSimple: ApiStreamSimpleFunction;\n}\n\ntype RegisteredApiProvider = {\n\tprovider: ApiProviderInternal;\n\tsourceId?: string;\n};\n\nconst apiProviderRegistry = new Map<string, RegisteredApiProvider>();\n\nfunction wrapStream<TApi extends Api, TOptions extends StreamOptions>(\n\tapi: TApi,\n\tstream: StreamFunction<TApi, TOptions>,\n): ApiStreamFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn stream(model as Model<TApi>, context, options as TOptions);\n\t};\n}\n\nfunction wrapStreamSimple<TApi extends Api>(\n\tapi: TApi,\n\tstreamSimple: StreamFunction<TApi, SimpleStreamOptions>,\n): ApiStreamSimpleFunction {\n\treturn (model, context, options) => {\n\t\tif (model.api !== api) {\n\t\t\tthrow new Error(`Mismatched api: ${model.api} expected ${api}`);\n\t\t}\n\t\treturn streamSimple(model as Model<TApi>, context, options);\n\t};\n}\n\nexport function registerApiProvider<TApi extends Api, TOptions extends StreamOptions>(\n\tprovider: ApiProvider<TApi, TOptions>,\n\tsourceId?: string,\n): void {\n\tapiProviderRegistry.set(provider.api, {\n\t\tprovider: {\n\t\t\tapi: provider.api,\n\t\t\tstream: wrapStream(provider.api, provider.stream),\n\t\t\tstreamSimple: wrapStreamSimple(provider.api, provider.streamSimple),\n\t\t},\n\t\tsourceId,\n\t});\n}\n\nexport function getApiProvider(api: Api): ApiProviderInternal | undefined {\n\treturn apiProviderRegistry.get(api)?.provider;\n}\n\nexport function getApiProviders(): ApiProviderInternal[] {\n\treturn Array.from(apiProviderRegistry.values(), (entry) => entry.provider);\n}\n\nexport function unregisterApiProviders(sourceId: string): void {\n\tfor (const [api, entry] of apiProviderRegistry.entries()) {\n\t\tif (entry.sourceId === sourceId) {\n\t\t\tapiProviderRegistry.delete(api);\n\t\t}\n\t}\n}\n\nfunction clearApiProviders(): void {\n\tapiProviderRegistry.clear();\n}\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst core = createFauxCore(options);\n\tconst sourceId = `faux-provider-${Math.random().toString(36).slice(2, 10)}`;\n\tregisterApiProvider({ api: core.api, stream: core.stream, streamSimple: core.streamSimple }, sourceId);\n\treturn {\n\t\tapi: core.api,\n\t\tmodels: core.models,\n\t\tgetModel: core.getModel,\n\t\tstate: core.state,\n\t\tsetResponses: core.setResponses,\n\t\tappendResponses: core.appendResponses,\n\t\tgetPendingResponseCount: core.getPendingResponseCount,\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n\nconst BUILTIN_APIS: [Api, ProviderStreams][] = [\n\t[\"anthropic-messages\", anthropicMessagesApi()],\n\t[\"openai-completions\", openAICompletionsApi()],\n\t[\"openai-responses\", openAIResponsesApi()],\n\t[\"openai-codex-responses\", openAICodexResponsesApi()],\n\t[\"azure-openai-responses\", azureOpenAIResponsesApi()],\n\t[\"google-generative-ai\", googleGenerativeAIApi()],\n\t[\"google-vertex\", googleVertexApi()],\n\t[\"mistral-conversations\", mistralConversationsApi()],\n\t[\"bedrock-converse-stream\", bedrockConverseStreamApi()],\n\t[\"pi-messages\", piMessagesApi()],\n];\n\nconst builtinApiProviderInstances = new Map<Api, ReturnType<typeof getApiProvider>>();\n\n/**\n * Registers the builtin API implementations into the api-registry without\n * clobbering existing entries: compat may load after a test or extension has\n * already registered an override for a builtin api id.\n */\nexport function registerBuiltInApiProviders(): void {\n\tfor (const [api, streams] of BUILTIN_APIS) {\n\t\tif (!getApiProvider(api)) {\n\t\t\tregisterApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\t}\n\t\tbuiltinApiProviderInstances.set(api, getApiProvider(api));\n\t}\n}\n\nexport function resetApiProviders(): void {\n\tclearApiProviders();\n\tbuiltinApiProviderInstances.clear();\n\tregisterBuiltInApiProviders();\n}\n\nregisterBuiltInApiProviders();\n\nconst compatModels = builtinModels();\nconst AMBIENT_AUTH_MARKER = \"<authenticated>\";\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction withEnvApiKey<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tconst apiKey = getEnvApiKey(model.provider, options?.env);\n\tif (!apiKey || apiKey === AMBIENT_AUTH_MARKER) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction hasResolvedCloudflareAuth(options: StreamOptions | undefined): boolean {\n\treturn hasExplicitApiKey(options?.apiKey) || typeof options?.headers?.[\"cf-aig-authorization\"] === \"string\";\n}\n\nfunction getBuiltinProviderForModel(model: Model<Api>) {\n\tif (getApiProvider(model.api) !== builtinApiProviderInstances.get(model.api)) return undefined;\n\tconst provider = compatModels.getProvider(model.provider);\n\treturn provider?.getModels().some((candidate) => candidate.api === model.api) ? provider : undefined;\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tconst transcript = normalizeContext(context);\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.stream(model, transcript, options as ModelsApiStreamOptions<TApi> | undefined);\n\t\t}\n\t\treturn builtinProvider.stream(model, transcript, withEnvApiKey(model, options) as ApiStreamOptions<TApi>);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.stream(model, transcript, withEnvApiKey(model, options) as StreamOptions);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst transcript = normalizeContext(context);\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.streamSimple(model, transcript, options);\n\t\t}\n\t\treturn builtinProvider.streamSimple(model, transcript, withEnvApiKey(model, options));\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.streamSimple(model, transcript, withEnvApiKey(model, options));\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
|
package/dist/compat.js
CHANGED
|
@@ -39,6 +39,7 @@ import { piMessagesApi } from "./api/pi-messages.lazy.js";
|
|
|
39
39
|
import { getEnvApiKey } from "./env-api-keys.js";
|
|
40
40
|
import { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from "./providers/all.js";
|
|
41
41
|
import { createFauxCore } from "./providers/faux.js";
|
|
42
|
+
import { normalizeContext } from "./utils/transcript.js";
|
|
42
43
|
/** @deprecated Static catalog read. Use `getBuiltinModel` from "@bastani/pi-ai/providers/all" or `Models.getModel()`. */
|
|
43
44
|
export const getModel = getBuiltinModel;
|
|
44
45
|
/** @deprecated Static catalog read. Use `getBuiltinModels` from "@bastani/pi-ai/providers/all" or `Models.getModels()`. */
|
|
@@ -167,30 +168,32 @@ function resolveApiProvider(api) {
|
|
|
167
168
|
return provider;
|
|
168
169
|
}
|
|
169
170
|
export function stream(model, context, options) {
|
|
171
|
+
const transcript = normalizeContext(context);
|
|
170
172
|
const builtinProvider = getBuiltinProviderForModel(model);
|
|
171
173
|
if (builtinProvider) {
|
|
172
174
|
if (model.provider.startsWith("cloudflare-") && !hasResolvedCloudflareAuth(options)) {
|
|
173
|
-
return compatModels.stream(model,
|
|
175
|
+
return compatModels.stream(model, transcript, options);
|
|
174
176
|
}
|
|
175
|
-
return builtinProvider.stream(model,
|
|
177
|
+
return builtinProvider.stream(model, transcript, withEnvApiKey(model, options));
|
|
176
178
|
}
|
|
177
179
|
const provider = resolveApiProvider(model.api);
|
|
178
|
-
return provider.stream(model,
|
|
180
|
+
return provider.stream(model, transcript, withEnvApiKey(model, options));
|
|
179
181
|
}
|
|
180
182
|
export async function complete(model, context, options) {
|
|
181
183
|
const s = stream(model, context, options);
|
|
182
184
|
return s.result();
|
|
183
185
|
}
|
|
184
186
|
export function streamSimple(model, context, options) {
|
|
187
|
+
const transcript = normalizeContext(context);
|
|
185
188
|
const builtinProvider = getBuiltinProviderForModel(model);
|
|
186
189
|
if (builtinProvider) {
|
|
187
190
|
if (model.provider.startsWith("cloudflare-") && !hasResolvedCloudflareAuth(options)) {
|
|
188
|
-
return compatModels.streamSimple(model,
|
|
191
|
+
return compatModels.streamSimple(model, transcript, options);
|
|
189
192
|
}
|
|
190
|
-
return builtinProvider.streamSimple(model,
|
|
193
|
+
return builtinProvider.streamSimple(model, transcript, withEnvApiKey(model, options));
|
|
191
194
|
}
|
|
192
195
|
const provider = resolveApiProvider(model.api);
|
|
193
|
-
return provider.streamSimple(model,
|
|
196
|
+
return provider.streamSimple(model, transcript, withEnvApiKey(model, options));
|
|
194
197
|
}
|
|
195
198
|
export async function completeSimple(model, context, options) {
|
|
196
199
|
const s = streamSimple(model, context, options);
|