@bastani/pi-ai 0.9.43 → 0.9.44-alpha.2
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 +23 -0
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +45 -58
- 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 +0 -6
- 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 +71 -78
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/constrained-sampling.d.ts +11 -1
- package/dist/api/constrained-sampling.d.ts.map +1 -1
- package/dist/api/constrained-sampling.js +33 -18
- package/dist/api/constrained-sampling.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +0 -6
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-shared.d.ts +2 -1
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +57 -2
- 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 +0 -6
- 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 +17 -44
- 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 +0 -5
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +34 -53
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +58 -57
- 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 +0 -6
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/pi-messages.d.ts +2 -0
- package/dist/api/pi-messages.d.ts.map +1 -1
- package/dist/api/pi-messages.js +15 -9
- package/dist/api/pi-messages.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/kimi-coding.json +1 -1
- package/dist/providers/data/moonshotai-cn.json +1 -1
- package/dist/providers/data/moonshotai.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +7 -2
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/radius-config.d.ts.map +1 -1
- package/dist/providers/radius-config.js +2 -1
- package/dist/providers/radius-config.js.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/error-body.d.ts.map +1 -1
- package/dist/utils/error-body.js +2 -1
- package/dist/utils/error-body.js.map +1 -1
- package/dist/utils/streaming-json.d.ts +84 -0
- package/dist/utils/streaming-json.d.ts.map +1 -0
- package/dist/utils/streaming-json.js +513 -0
- package/dist/utils/streaming-json.js.map +1 -0
- package/dist/utils/text.d.ts +7 -0
- package/dist/utils/text.d.ts.map +1 -1
- package/dist/utils/text.js +9 -0
- package/dist/utils/text.js.map +1 -1
- package/dist/utils/version.d.ts +1 -1
- package/dist/utils/version.d.ts.map +1 -1
- package/dist/utils/version.js +1 -1
- package/dist/utils/version.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"faux.d.ts","sourceRoot":"","sources":["../../src/providers/faux.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,KAAK,EAC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MAAM,CAAC,UACnB,cAAc,iBACP,oBAAoB,KACjC,2BAA2B;mCA+Df,KAAK,CAAC,MAAM,CAAC,UACnB,cAAc,kBACN,qBAAqB,KACnC,OAAO,CAAC,IAAI,CAAC;;YAOK,KAAK,CAAC,MAAM,CAAC;2BACE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,GAAG,SAAS;;;4BAkB7C,gBAAgB,EAAE;+BAGf,gBAAgB,EAAE;;EAO9C;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,2BAAgC,GAAG,kBAAkB,CAuB1F"}
|
package/dist/providers/faux.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createProvider } from "../models.js";
|
|
2
2
|
import { createAssistantMessageEventStream } from "../utils/event-stream.js";
|
|
3
|
+
import { ToolCallArgumentsStream } from "../utils/streaming-json.js";
|
|
3
4
|
import { getSystemMessageText } from "../utils/text.js";
|
|
4
5
|
const DEFAULT_API = "faux";
|
|
5
6
|
const DEFAULT_PROVIDER = "faux";
|
|
@@ -146,12 +147,13 @@ function withUsageEstimate(message, context, options, promptCache) {
|
|
|
146
147
|
if (previousPrompt) {
|
|
147
148
|
const cachedChars = commonPromptPrefixLength(previousPrompt, prompt);
|
|
148
149
|
cacheRead = Math.ceil(cachedChars / 4);
|
|
149
|
-
cacheWrite = Math.
|
|
150
|
-
input = Math.max(0, promptTokens - cacheRead);
|
|
150
|
+
cacheWrite = Math.max(0, promptTokens - cacheRead);
|
|
151
151
|
}
|
|
152
152
|
else {
|
|
153
153
|
cacheWrite = promptTokens;
|
|
154
154
|
}
|
|
155
|
+
// Every prompt token is either read from or written to the simulated cache.
|
|
156
|
+
input = 0;
|
|
155
157
|
promptCache.set(sessionId, prompt);
|
|
156
158
|
}
|
|
157
159
|
return {
|
|
@@ -296,6 +298,8 @@ async function streamWithDeltas(stream, message, minTokenSize, maxTokenSize, tok
|
|
|
296
298
|
}
|
|
297
299
|
partial.content = [...partial.content, { type: "toolCall", id: block.id, name: block.name, arguments: {} }];
|
|
298
300
|
stream.push({ type: "toolcall_start", contentIndex: index, partial: { ...partial } });
|
|
301
|
+
// Partial arguments come from the same parser real providers use, so consumers see them grow.
|
|
302
|
+
const toolArguments = new ToolCallArgumentsStream();
|
|
299
303
|
for (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {
|
|
300
304
|
await scheduleChunk(chunk, tokensPerSecond);
|
|
301
305
|
if (signal?.aborted) {
|
|
@@ -304,6 +308,7 @@ async function streamWithDeltas(stream, message, minTokenSize, maxTokenSize, tok
|
|
|
304
308
|
stream.end(aborted);
|
|
305
309
|
return;
|
|
306
310
|
}
|
|
311
|
+
partial.content[index].arguments = toolArguments.append(chunk);
|
|
307
312
|
stream.push({ type: "toolcall_delta", contentIndex: index, delta: chunk, partial: { ...partial } });
|
|
308
313
|
}
|
|
309
314
|
partial.content[index].arguments = block.arguments;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"faux.js","sourceRoot":"","sources":["../../src/providers/faux.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAiB,MAAM,cAAc,CAAC;AAqB7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAClC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,gBAAgB,GAAG,oBAAoB,CAAC;AAC9C,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,sBAAsB,GAAG,CAAC,CAAC;AAEjC,MAAM,aAAa,GAAU;IAC5B,KAAK,EAAE,CAAC;IACR,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,C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AAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE;QACvE,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,GAAG,EAAE;YACJ,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,cAAc,EAAE,IAAI,CAAC,cAAc;SACnC;KACD,CAAC,CAAC;IACH,OAAO;QACN,QAAQ;QACR,GAAG,EAAE,IAAI,CAAC,GAAG;QACb,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;KACrD,CAAC;AACH,CAAC","sourcesContent":["import { createProvider, type Provider } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tDeferredCancelOptions,\n\tDeferredFetchOptions,\n\tDeferredHandle,\n\tDocumentContent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tToolCall,\n\tToolResultMessage,\n\tTranscriptContext,\n\tUsage,\n} from \"../types.ts\";\nimport { createAssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { getSystemMessageText } from \"../utils/text.ts\";\n\nconst DEFAULT_API = \"faux\";\nconst DEFAULT_PROVIDER = \"faux\";\nconst DEFAULT_MODEL_ID = \"faux-1\";\nconst DEFAULT_MODEL_NAME = \"Faux Model\";\nconst DEFAULT_BASE_URL = \"http://localhost:0\";\nconst DEFAULT_MIN_TOKEN_SIZE = 3;\nconst DEFAULT_MAX_TOKEN_SIZE = 5;\n\nconst DEFAULT_USAGE: Usage = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FauxModelDefinition {\n\tid: string;\n\tname?: string;\n\treasoning?: boolean;\n\tinput?: (\"text\" | \"image\")[];\n\tinputLimits?: Model<string>[\"inputLimits\"];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n}\n\nexport type FauxContentBlock = TextContent | ThinkingContent | ToolCall;\n\nexport function fauxText(text: string): TextContent {\n\treturn { type: \"text\", text };\n}\n\nexport function fauxThinking(thinking: string): ThinkingContent {\n\treturn { type: \"thinking\", thinking };\n}\n\nexport function fauxToolCall(name: string, arguments_: ToolCall[\"arguments\"], options: { id?: string } = {}): ToolCall {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: options.id ?? randomId(\"tool\"),\n\t\tname,\n\t\targuments: arguments_,\n\t};\n}\n\nfunction normalizeFauxAssistantContent(content: string | FauxContentBlock | FauxContentBlock[]): FauxContentBlock[] {\n\tif (typeof content === \"string\") {\n\t\treturn [fauxText(content)];\n\t}\n\treturn Array.isArray(content) ? content : [content];\n}\n\nexport function fauxAssistantMessage(\n\tcontent: string | FauxContentBlock | FauxContentBlock[],\n\toptions: {\n\t\tstopReason?: AssistantMessage[\"stopReason\"];\n\t\tdeferred?: DeferredHandle;\n\t\terrorMessage?: string;\n\t\tresponseId?: string;\n\t\ttimestamp?: number;\n\t} = {},\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: normalizeFauxAssistantContent(content),\n\t\tapi: DEFAULT_API,\n\t\tprovider: DEFAULT_PROVIDER,\n\t\tmodel: DEFAULT_MODEL_ID,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: options.stopReason ?? \"stop\",\n\t\tdeferred: options.deferred,\n\t\terrorMessage: options.errorMessage,\n\t\tresponseId: options.responseId,\n\t\ttimestamp: options.timestamp ?? Date.now(),\n\t};\n}\n\nexport interface FauxProviderState {\n\tcallCount: number;\n\tdeferredFetchCount: number;\n\tcancelledDeferred: DeferredHandle[];\n}\n\nexport type FauxResponseFactory = (\n\tcontext: TranscriptContext,\n\toptions: SimpleStreamOptions | undefined,\n\tstate: FauxProviderState,\n\tmodel: Model<string>,\n) => AssistantMessage | Promise<AssistantMessage>;\n\nexport type FauxResponseStep = AssistantMessage | FauxResponseFactory;\n\nexport interface RegisterFauxProviderOptions {\n\tapi?: string;\n\tprovider?: string;\n\tmodels?: FauxModelDefinition[];\n\tdeferred?: {\n\t\t/** Number of fetches that return the original handle before the scripted response becomes ready. */\n\t\tpendingFetches?: number;\n\t\tpollAfterMs?: number;\n\t};\n\ttokensPerSecond?: number;\n\ttokenSize?: {\n\t\tmin?: number;\n\t\tmax?: number;\n\t};\n}\n\nexport interface FauxProviderRegistration {\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: FauxProviderState;\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n\tunregister: () => void;\n}\n\nexport interface FauxProviderHandle {\n\tprovider: Provider;\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: FauxProviderState;\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n}\n\nfunction estimateTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction randomId(prefix: string): string {\n\treturn `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction contentToText(content: string | Array<TextContent | ImageContent | DocumentContent>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"document\") {\n\t\t\t\treturn `[document:${block.mimeType}:${block.data.length}]`;\n\t\t\t}\n\t\t\treturn `[image:${block.mimeType}:${block.data.length}]`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction assistantContentToText(content: AssistantMessage[\"content\"]): string {\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\treturn block.thinking;\n\t\t\t}\n\t\t\t// Fallback boundary markers carry no text.\n\t\t\tif (block.type !== \"toolCall\") {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\treturn `${block.name}:${JSON.stringify(block.arguments)}`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction toolResultToText(message: ToolResultMessage): string {\n\treturn [message.toolName, ...message.content.map((block) => contentToText([block]))].join(\"\\n\");\n}\n\nfunction messageToText(message: Message): string {\n\tif (message.role === \"system\") {\n\t\treturn [\n\t\t\tgetSystemMessageText(message),\n\t\t\t...(message.toolsRemoved?.map((tool) => `tool-:${JSON.stringify(tool)}`) ?? []),\n\t\t\t...(message.toolsAdded?.map((tool) => `tool+:${JSON.stringify(tool)}`) ?? []),\n\t\t]\n\t\t\t.filter((part) => part.length > 0)\n\t\t\t.join(\"\\n\");\n\t}\n\tif (message.role === \"user\") {\n\t\treturn contentToText(message.content);\n\t}\n\tif (message.role === \"assistant\") {\n\t\treturn assistantContentToText(message.content);\n\t}\n\treturn toolResultToText(message);\n}\n\nfunction joinedLength(messages: readonly string[], count = messages.length): number {\n\tlet length = count > 0 ? (count - 1) * 2 : 0;\n\tfor (let index = 0; index < count; index++) length += messages[index]!.length;\n\treturn length;\n}\n\nfunction commonPromptPrefixLength(previous: readonly string[], current: readonly string[]): number {\n\tlet index = 0;\n\twhile (index < previous.length && index < current.length && previous[index] === current[index]) index++;\n\tconst rest = (messages: readonly string[]) =>\n\t\tindex === messages.length ? \"\" : (index > 0 ? \"\\n\\n\" : \"\") + messages.slice(index).join(\"\\n\\n\");\n\treturn joinedLength(previous, index) + commonPrefixLength(rest(previous), rest(current));\n}\n\nfunction commonPrefixLength(a: string, b: string): number {\n\tconst length = Math.min(a.length, b.length);\n\tlet index = 0;\n\twhile (index < length && a[index] === b[index]) {\n\t\tindex++;\n\t}\n\treturn index;\n}\n\nfunction withUsageEstimate(\n\tmessage: AssistantMessage,\n\tcontext: TranscriptContext,\n\toptions: StreamOptions | undefined,\n\tpromptCache: Map<string, readonly string[]>,\n): AssistantMessage {\n\tconst prompt = context.messages.map((message) => `${message.role}:${messageToText(message)}`);\n\tconst promptLength = joinedLength(prompt);\n\tconst promptTokens = Math.ceil(promptLength / 4);\n\tconst outputTokens = estimateTokens(assistantContentToText(message.content));\n\tlet input = promptTokens;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tconst sessionId = options?.sessionId;\n\n\tif (sessionId && options?.cacheRetention !== \"none\") {\n\t\tconst previousPrompt = promptCache.get(sessionId);\n\t\tif (previousPrompt) {\n\t\t\tconst cachedChars = commonPromptPrefixLength(previousPrompt, prompt);\n\t\t\tcacheRead = Math.ceil(cachedChars / 4);\n\t\t\tcacheWrite = Math.ceil((promptLength - cachedChars) / 4);\n\t\t\tinput = Math.max(0, promptTokens - cacheRead);\n\t\t} else {\n\t\t\tcacheWrite = promptTokens;\n\t\t}\n\t\tpromptCache.set(sessionId, prompt);\n\t}\n\n\treturn {\n\t\t...message,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput: outputTokens,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens: input + outputTokens + cacheRead + cacheWrite,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t};\n}\n\nfunction splitStringByTokenSize(text: string, minTokenSize: number, maxTokenSize: number): string[] {\n\tconst chunks: string[] = [];\n\tlet index = 0;\n\twhile (index < text.length) {\n\t\tconst tokenSize = minTokenSize + Math.floor(Math.random() * (maxTokenSize - minTokenSize + 1));\n\t\tconst charSize = Math.max(1, tokenSize * 4);\n\t\tchunks.push(text.slice(index, index + charSize));\n\t\tindex += charSize;\n\t}\n\treturn chunks.length > 0 ? chunks : [\"\"];\n}\n\nfunction cloneMessage(message: AssistantMessage, api: string, provider: string, modelId: string): AssistantMessage {\n\tconst cloned = structuredClone(message);\n\treturn {\n\t\t...cloned,\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\ttimestamp: cloned.timestamp ?? Date.now(),\n\t\tusage: cloned.usage ?? DEFAULT_USAGE,\n\t};\n}\n\nfunction createDeferredMessage(model: Model<string>, handle: DeferredHandle): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"deferred\",\n\t\tdeferred: handle,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createErrorMessage(error: unknown, api: string, provider: string, modelId: string): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAbortedMessage(partial: AssistantMessage): AssistantMessage {\n\treturn {\n\t\t...partial,\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: \"Request was aborted\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction scheduleChunk(chunk: string, tokensPerSecond: number | undefined): Promise<void> {\n\tif (!tokensPerSecond || tokensPerSecond <= 0) {\n\t\treturn new Promise((resolve) => queueMicrotask(resolve));\n\t}\n\tconst delayMs = (estimateTokens(chunk) / tokensPerSecond) * 1000;\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\nasync function streamWithDeltas(\n\tstream: AssistantMessageEventStream,\n\tmessage: AssistantMessage,\n\tminTokenSize: number,\n\tmaxTokenSize: number,\n\ttokensPerSecond: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tconst partial: AssistantMessage = { ...message, content: [], stopReason: \"pending\" };\n\tif (signal?.aborted) {\n\t\tconst aborted = createAbortedMessage(partial);\n\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\tstream.end(aborted);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"start\", partial: { ...partial } });\n\n\tfor (let index = 0; index < message.content.length; index++) {\n\t\tif (signal?.aborted) {\n\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\tstream.end(aborted);\n\t\t\treturn;\n\t\t}\n\n\t\tconst block = message.content[index];\n\n\t\tif (block.type === \"thinking\") {\n\t\t\tpartial.content = [...partial.content, { type: \"thinking\", thinking: \"\" }];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as ThinkingContent).thinking += chunk;\n\t\t\t\tstream.push({ type: \"thinking_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: index,\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: { ...partial },\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (block.type === \"text\") {\n\t\t\tpartial.content = [...partial.content, { type: \"text\", text: \"\" }];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as TextContent).text += chunk;\n\t\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } });\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Fallback boundary markers are replay metadata with nothing to stream, but they still\n\t\t// occupy a slot in `partial.content` so later blocks keep their source `contentIndex`.\n\t\t// This matches the real Anthropic provider, which pushes the wire `fallback` block into\n\t\t// `output.content` and emits no event for it; every `contentIndex` consumer indexes\n\t\t// `partial.content` directly, so skipping the slot would shift every later block by one.\n\t\tif (block.type !== \"toolCall\") {\n\t\t\tpartial.content = [...partial.content, block];\n\t\t\tcontinue;\n\t\t}\n\n\t\tpartial.content = [...partial.content, { type: \"toolCall\", id: block.id, name: block.name, arguments: {} }];\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } });\n\t\tfor (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {\n\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\tstream.end(aborted);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t}\n\t\t(partial.content[index] as ToolCall).arguments = block.arguments;\n\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } });\n\t}\n\n\tif (message.stopReason === \"pending\") {\n\t\tthrow new Error(\"Faux response ended without a stop reason\");\n\t}\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\tstream.push({ type: \"error\", reason: message.stopReason, error: message });\n\t\tstream.end(message);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"done\", reason: message.stopReason, message });\n\tstream.end(message);\n}\n\nexport function createFauxCore(options: RegisterFauxProviderOptions) {\n\tconst api = options.api ?? randomId(DEFAULT_API);\n\tconst provider = options.provider ?? DEFAULT_PROVIDER;\n\tconst minTokenSize = Math.max(\n\t\t1,\n\t\tMath.min(options.tokenSize?.min ?? DEFAULT_MIN_TOKEN_SIZE, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE),\n\t);\n\tconst maxTokenSize = Math.max(minTokenSize, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE);\n\tlet pendingResponses: FauxResponseStep[] = [];\n\tconst tokensPerSecond = options.tokensPerSecond;\n\tconst state: FauxProviderState = { callCount: 0, deferredFetchCount: 0, cancelledDeferred: [] };\n\tconst promptCache = new Map<string, readonly string[]>();\n\tconst deferredResponses = new Map<\n\t\tstring,\n\t\t{\n\t\t\thandle: DeferredHandle;\n\t\t\tstep: FauxResponseStep;\n\t\t\tcontext: TranscriptContext;\n\t\t\toptions: SimpleStreamOptions | undefined;\n\t\t\tmodel: Model<string>;\n\t\t\tpendingFetches: number;\n\t\t\tcancelled: boolean;\n\t\t\tfinal?: AssistantMessage;\n\t\t}\n\t>();\n\n\tconst modelDefinitions = options.models?.length\n\t\t? options.models\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tid: DEFAULT_MODEL_ID,\n\t\t\t\t\tname: DEFAULT_MODEL_NAME,\n\t\t\t\t\treasoning: false,\n\t\t\t\t\tinput: [\"text\", \"image\"] as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: 128000,\n\t\t\t\t\tmaxTokens: 16384,\n\t\t\t\t},\n\t\t\t];\n\tconst models = modelDefinitions.map((definition) => ({\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi,\n\t\tprovider,\n\t\tbaseUrl: DEFAULT_BASE_URL,\n\t\treasoning: definition.reasoning ?? false,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tinputLimits: definition.inputLimits,\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t})) as [Model<string>, ...Model<string>[]];\n\n\tconst resolveResponse = async (\n\t\tstep: FauxResponseStep,\n\t\tcontext: TranscriptContext,\n\t\tstreamOptions: SimpleStreamOptions | undefined,\n\t\trequestModel: Model<string>,\n\t): Promise<AssistantMessage> => {\n\t\tconst resolved = typeof step === \"function\" ? await step(context, streamOptions, state, requestModel) : step;\n\t\treturn withUsageEstimate(\n\t\t\tcloneMessage(resolved, api, provider, requestModel.id),\n\t\t\tcontext,\n\t\t\tstreamOptions,\n\t\t\tpromptCache,\n\t\t);\n\t};\n\n\tconst stream: StreamFunction<string, SimpleStreamOptions> = (requestModel, context, streamOptions) => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst step = pendingResponses.shift();\n\t\tstate.callCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tawait streamOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t\t\t\tif (!step) {\n\t\t\t\t\tlet message = createErrorMessage(\n\t\t\t\t\t\tnew Error(\"No more faux responses queued\"),\n\t\t\t\t\t\tapi,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\trequestModel.id,\n\t\t\t\t\t);\n\t\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\t\touter.end(message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (streamOptions?.deferred) {\n\t\t\t\t\tconst handle: DeferredHandle = {\n\t\t\t\t\t\tprovider: requestModel.provider,\n\t\t\t\t\t\tmodelId: requestModel.id,\n\t\t\t\t\t\tapi: requestModel.api,\n\t\t\t\t\t\tid: randomId(\"deferred\"),\n\t\t\t\t\t\t...(options.deferred?.pollAfterMs !== undefined ? { pollAfterMs: options.deferred.pollAfterMs } : {}),\n\t\t\t\t\t};\n\t\t\t\t\tdeferredResponses.set(handle.id, {\n\t\t\t\t\t\thandle,\n\t\t\t\t\t\tstep,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\toptions: streamOptions,\n\t\t\t\t\t\tmodel: requestModel,\n\t\t\t\t\t\tpendingFetches: Math.max(0, Math.floor(options.deferred?.pendingFetches ?? 0)),\n\t\t\t\t\t\tcancelled: false,\n\t\t\t\t\t});\n\t\t\t\t\tawait streamWithDeltas(\n\t\t\t\t\t\touter,\n\t\t\t\t\t\tcreateDeferredMessage(requestModel, handle),\n\t\t\t\t\t\tminTokenSize,\n\t\t\t\t\t\tmaxTokenSize,\n\t\t\t\t\t\ttokensPerSecond,\n\t\t\t\t\t\tstreamOptions.signal,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst message = await resolveResponse(step, context, streamOptions, requestModel);\n\t\t\t\tawait streamWithDeltas(outer, message, minTokenSize, maxTokenSize, tokensPerSecond, streamOptions?.signal);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst streamSimple: StreamFunction<string, SimpleStreamOptions> = (streamModel, context, streamOptions) =>\n\t\tstream(streamModel, context, streamOptions);\n\n\tconst fetchDeferred = (\n\t\trequestModel: Model<string>,\n\t\thandle: DeferredHandle,\n\t\tfetchOptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tstate.deferredFetchCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tawait fetchOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t\t\t\tconst entry = deferredResponses.get(handle.id);\n\t\t\t\tif (\n\t\t\t\t\t!entry ||\n\t\t\t\t\tentry.handle.provider !== handle.provider ||\n\t\t\t\t\tentry.handle.modelId !== handle.modelId ||\n\t\t\t\t\tentry.handle.api !== handle.api\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Unknown faux deferred response: ${handle.id}`);\n\t\t\t\t}\n\t\t\t\tif (entry.cancelled) throw new Error(`Faux deferred response was cancelled: ${handle.id}`);\n\n\t\t\t\tif (entry.pendingFetches > 0) {\n\t\t\t\t\tentry.pendingFetches--;\n\t\t\t\t\tawait streamWithDeltas(\n\t\t\t\t\t\touter,\n\t\t\t\t\t\tcreateDeferredMessage(requestModel, entry.handle),\n\t\t\t\t\t\tminTokenSize,\n\t\t\t\t\t\tmaxTokenSize,\n\t\t\t\t\t\ttokensPerSecond,\n\t\t\t\t\t\tfetchOptions?.signal,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!entry.final) {\n\t\t\t\t\tconst {\n\t\t\t\t\t\tdeferred: _deferred,\n\t\t\t\t\t\tsignal: _submissionSignal,\n\t\t\t\t\t\tonResponse: _submissionOnResponse,\n\t\t\t\t\t\t...submissionOptions\n\t\t\t\t\t} = entry.options ?? {};\n\t\t\t\t\ttry {\n\t\t\t\t\t\tentry.final = await resolveResponse(entry.step, entry.context, submissionOptions, entry.model);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tentry.final = createErrorMessage(error, api, provider, entry.model.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait streamWithDeltas(\n\t\t\t\t\touter,\n\t\t\t\t\tentry.final,\n\t\t\t\t\tminTokenSize,\n\t\t\t\t\tmaxTokenSize,\n\t\t\t\t\ttokensPerSecond,\n\t\t\t\t\tfetchOptions?.signal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst cancelDeferred = async (\n\t\trequestModel: Model<string>,\n\t\thandle: DeferredHandle,\n\t\tcancelOptions?: DeferredCancelOptions,\n\t): Promise<void> => {\n\t\tstate.cancelledDeferred.push(structuredClone(handle));\n\t\tconst entry = deferredResponses.get(handle.id);\n\t\tif (entry) entry.cancelled = true;\n\t\tawait cancelOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t};\n\n\tfunction getModel(): Model<string>;\n\tfunction getModel(requestedModelId: string): Model<string> | undefined;\n\tfunction getModel(requestedModelId?: string): Model<string> | undefined {\n\t\tif (!requestedModelId) {\n\t\t\treturn models[0];\n\t\t}\n\t\treturn models.find((candidate) => candidate.id === requestedModelId);\n\t}\n\n\treturn {\n\t\tapi,\n\t\tprovider,\n\t\tmodels,\n\t\tstream,\n\t\tstreamSimple,\n\t\tfetchDeferred,\n\t\tcancelDeferred,\n\t\tgetModel,\n\t\tstate,\n\t\tsetResponses(responses: FauxResponseStep[]) {\n\t\t\tpendingResponses = [...responses];\n\t\t},\n\t\tappendResponses(responses: FauxResponseStep[]) {\n\t\t\tpendingResponses.push(...responses);\n\t\t},\n\t\tgetPendingResponseCount() {\n\t\t\treturn pendingResponses.length;\n\t\t},\n\t};\n}\n\n/**\n * Faux provider for tests built on explicit `Models` collections:\n *\n * ```ts\n * const faux = fauxProvider();\n * const models = createModels();\n * models.setProvider(faux.provider);\n * faux.setResponses([fauxAssistantMessage(\"hi\")]);\n * ```\n */\nexport function fauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderHandle {\n\tconst core = createFauxCore(options);\n\tconst provider = createProvider({\n\t\tid: core.provider,\n\t\tauth: { apiKey: { name: \"Faux\", resolve: async () => ({ auth: {} }) } },\n\t\tmodels: core.models,\n\t\tapi: {\n\t\t\tstream: core.stream,\n\t\t\tstreamSimple: core.streamSimple,\n\t\t\tfetchDeferred: core.fetchDeferred,\n\t\t\tcancelDeferred: core.cancelDeferred,\n\t\t},\n\t});\n\treturn {\n\t\tprovider,\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};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"faux.js","sourceRoot":"","sources":["../../src/providers/faux.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAiB,MAAM,cAAc,CAAC;AAqB7D,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAClC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AACxC,MAAM,gBAAgB,GAAG,oBAAoB,CAAC;AAC9C,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,sBAAsB,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AC,OAAO,GAAgC,EAAE;IACrE,MAAM,IAAI,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,QAAQ,GAAG,cAAc,CAAC;QAC/B,EAAE,EAAE,IAAI,CAAC,QAAQ;QACjB,IAAI,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE;QACvE,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,GAAG,EAAE;YACJ,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,cAAc,EAAE,IAAI,CAAC,cAAc;SACnC;KACD,CAAC,CAAC;IACH,OAAO;QACN,QAAQ;QACR,GAAG,EAAE,IAAI,CAAC,GAAG;QACb,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;KACrD,CAAC;AACH,CAAC","sourcesContent":["import { createProvider, type Provider } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tDeferredCancelOptions,\n\tDeferredFetchOptions,\n\tDeferredHandle,\n\tDocumentContent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingContent,\n\tToolCall,\n\tToolResultMessage,\n\tTranscriptContext,\n\tUsage,\n} from \"../types.ts\";\nimport { createAssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { ToolCallArgumentsStream } from \"../utils/streaming-json.ts\";\nimport { getSystemMessageText } from \"../utils/text.ts\";\n\nconst DEFAULT_API = \"faux\";\nconst DEFAULT_PROVIDER = \"faux\";\nconst DEFAULT_MODEL_ID = \"faux-1\";\nconst DEFAULT_MODEL_NAME = \"Faux Model\";\nconst DEFAULT_BASE_URL = \"http://localhost:0\";\nconst DEFAULT_MIN_TOKEN_SIZE = 3;\nconst DEFAULT_MAX_TOKEN_SIZE = 5;\n\nconst DEFAULT_USAGE: Usage = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nexport interface FauxModelDefinition {\n\tid: string;\n\tname?: string;\n\treasoning?: boolean;\n\tinput?: (\"text\" | \"image\")[];\n\tinputLimits?: Model<string>[\"inputLimits\"];\n\tcost?: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\tcontextWindow?: number;\n\tmaxTokens?: number;\n}\n\nexport type FauxContentBlock = TextContent | ThinkingContent | ToolCall;\n\nexport function fauxText(text: string): TextContent {\n\treturn { type: \"text\", text };\n}\n\nexport function fauxThinking(thinking: string): ThinkingContent {\n\treturn { type: \"thinking\", thinking };\n}\n\nexport function fauxToolCall(name: string, arguments_: ToolCall[\"arguments\"], options: { id?: string } = {}): ToolCall {\n\treturn {\n\t\ttype: \"toolCall\",\n\t\tid: options.id ?? randomId(\"tool\"),\n\t\tname,\n\t\targuments: arguments_,\n\t};\n}\n\nfunction normalizeFauxAssistantContent(content: string | FauxContentBlock | FauxContentBlock[]): FauxContentBlock[] {\n\tif (typeof content === \"string\") {\n\t\treturn [fauxText(content)];\n\t}\n\treturn Array.isArray(content) ? content : [content];\n}\n\nexport function fauxAssistantMessage(\n\tcontent: string | FauxContentBlock | FauxContentBlock[],\n\toptions: {\n\t\tstopReason?: AssistantMessage[\"stopReason\"];\n\t\tdeferred?: DeferredHandle;\n\t\terrorMessage?: string;\n\t\tresponseId?: string;\n\t\ttimestamp?: number;\n\t} = {},\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: normalizeFauxAssistantContent(content),\n\t\tapi: DEFAULT_API,\n\t\tprovider: DEFAULT_PROVIDER,\n\t\tmodel: DEFAULT_MODEL_ID,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: options.stopReason ?? \"stop\",\n\t\tdeferred: options.deferred,\n\t\terrorMessage: options.errorMessage,\n\t\tresponseId: options.responseId,\n\t\ttimestamp: options.timestamp ?? Date.now(),\n\t};\n}\n\nexport interface FauxProviderState {\n\tcallCount: number;\n\tdeferredFetchCount: number;\n\tcancelledDeferred: DeferredHandle[];\n}\n\nexport type FauxResponseFactory = (\n\tcontext: TranscriptContext,\n\toptions: SimpleStreamOptions | undefined,\n\tstate: FauxProviderState,\n\tmodel: Model<string>,\n) => AssistantMessage | Promise<AssistantMessage>;\n\nexport type FauxResponseStep = AssistantMessage | FauxResponseFactory;\n\nexport interface RegisterFauxProviderOptions {\n\tapi?: string;\n\tprovider?: string;\n\tmodels?: FauxModelDefinition[];\n\tdeferred?: {\n\t\t/** Number of fetches that return the original handle before the scripted response becomes ready. */\n\t\tpendingFetches?: number;\n\t\tpollAfterMs?: number;\n\t};\n\ttokensPerSecond?: number;\n\ttokenSize?: {\n\t\tmin?: number;\n\t\tmax?: number;\n\t};\n}\n\nexport interface FauxProviderRegistration {\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: FauxProviderState;\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n\tunregister: () => void;\n}\n\nexport interface FauxProviderHandle {\n\tprovider: Provider;\n\tapi: string;\n\tmodels: [Model<string>, ...Model<string>[]];\n\tgetModel(): Model<string>;\n\tgetModel(modelId: string): Model<string> | undefined;\n\tstate: FauxProviderState;\n\tsetResponses: (responses: FauxResponseStep[]) => void;\n\tappendResponses: (responses: FauxResponseStep[]) => void;\n\tgetPendingResponseCount: () => number;\n}\n\nfunction estimateTokens(text: string): number {\n\treturn Math.ceil(text.length / 4);\n}\n\nfunction randomId(prefix: string): string {\n\treturn `${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction contentToText(content: string | Array<TextContent | ImageContent | DocumentContent>): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"document\") {\n\t\t\t\treturn `[document:${block.mimeType}:${block.data.length}]`;\n\t\t\t}\n\t\t\treturn `[image:${block.mimeType}:${block.data.length}]`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction assistantContentToText(content: AssistantMessage[\"content\"]): string {\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (block.type === \"text\") {\n\t\t\t\treturn block.text;\n\t\t\t}\n\t\t\tif (block.type === \"thinking\") {\n\t\t\t\treturn block.thinking;\n\t\t\t}\n\t\t\t// Fallback boundary markers carry no text.\n\t\t\tif (block.type !== \"toolCall\") {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\treturn `${block.name}:${JSON.stringify(block.arguments)}`;\n\t\t})\n\t\t.join(\"\\n\");\n}\n\nfunction toolResultToText(message: ToolResultMessage): string {\n\treturn [message.toolName, ...message.content.map((block) => contentToText([block]))].join(\"\\n\");\n}\n\nfunction messageToText(message: Message): string {\n\tif (message.role === \"system\") {\n\t\treturn [\n\t\t\tgetSystemMessageText(message),\n\t\t\t...(message.toolsRemoved?.map((tool) => `tool-:${JSON.stringify(tool)}`) ?? []),\n\t\t\t...(message.toolsAdded?.map((tool) => `tool+:${JSON.stringify(tool)}`) ?? []),\n\t\t]\n\t\t\t.filter((part) => part.length > 0)\n\t\t\t.join(\"\\n\");\n\t}\n\tif (message.role === \"user\") {\n\t\treturn contentToText(message.content);\n\t}\n\tif (message.role === \"assistant\") {\n\t\treturn assistantContentToText(message.content);\n\t}\n\treturn toolResultToText(message);\n}\n\nfunction joinedLength(messages: readonly string[], count = messages.length): number {\n\tlet length = count > 0 ? (count - 1) * 2 : 0;\n\tfor (let index = 0; index < count; index++) length += messages[index]!.length;\n\treturn length;\n}\n\nfunction commonPromptPrefixLength(previous: readonly string[], current: readonly string[]): number {\n\tlet index = 0;\n\twhile (index < previous.length && index < current.length && previous[index] === current[index]) index++;\n\tconst rest = (messages: readonly string[]) =>\n\t\tindex === messages.length ? \"\" : (index > 0 ? \"\\n\\n\" : \"\") + messages.slice(index).join(\"\\n\\n\");\n\treturn joinedLength(previous, index) + commonPrefixLength(rest(previous), rest(current));\n}\n\nfunction commonPrefixLength(a: string, b: string): number {\n\tconst length = Math.min(a.length, b.length);\n\tlet index = 0;\n\twhile (index < length && a[index] === b[index]) {\n\t\tindex++;\n\t}\n\treturn index;\n}\n\nfunction withUsageEstimate(\n\tmessage: AssistantMessage,\n\tcontext: TranscriptContext,\n\toptions: StreamOptions | undefined,\n\tpromptCache: Map<string, readonly string[]>,\n): AssistantMessage {\n\tconst prompt = context.messages.map((message) => `${message.role}:${messageToText(message)}`);\n\tconst promptLength = joinedLength(prompt);\n\tconst promptTokens = Math.ceil(promptLength / 4);\n\tconst outputTokens = estimateTokens(assistantContentToText(message.content));\n\tlet input = promptTokens;\n\tlet cacheRead = 0;\n\tlet cacheWrite = 0;\n\tconst sessionId = options?.sessionId;\n\n\tif (sessionId && options?.cacheRetention !== \"none\") {\n\t\tconst previousPrompt = promptCache.get(sessionId);\n\t\tif (previousPrompt) {\n\t\t\tconst cachedChars = commonPromptPrefixLength(previousPrompt, prompt);\n\t\t\tcacheRead = Math.ceil(cachedChars / 4);\n\t\t\tcacheWrite = Math.max(0, promptTokens - cacheRead);\n\t\t} else {\n\t\t\tcacheWrite = promptTokens;\n\t\t}\n\t\t// Every prompt token is either read from or written to the simulated cache.\n\t\tinput = 0;\n\t\tpromptCache.set(sessionId, prompt);\n\t}\n\n\treturn {\n\t\t...message,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput: outputTokens,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens: input + outputTokens + cacheRead + cacheWrite,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t};\n}\n\nfunction splitStringByTokenSize(text: string, minTokenSize: number, maxTokenSize: number): string[] {\n\tconst chunks: string[] = [];\n\tlet index = 0;\n\twhile (index < text.length) {\n\t\tconst tokenSize = minTokenSize + Math.floor(Math.random() * (maxTokenSize - minTokenSize + 1));\n\t\tconst charSize = Math.max(1, tokenSize * 4);\n\t\tchunks.push(text.slice(index, index + charSize));\n\t\tindex += charSize;\n\t}\n\treturn chunks.length > 0 ? chunks : [\"\"];\n}\n\nfunction cloneMessage(message: AssistantMessage, api: string, provider: string, modelId: string): AssistantMessage {\n\tconst cloned = structuredClone(message);\n\treturn {\n\t\t...cloned,\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\ttimestamp: cloned.timestamp ?? Date.now(),\n\t\tusage: cloned.usage ?? DEFAULT_USAGE,\n\t};\n}\n\nfunction createDeferredMessage(model: Model<string>, handle: DeferredHandle): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"deferred\",\n\t\tdeferred: handle,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createErrorMessage(error: unknown, api: string, provider: string, modelId: string): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi,\n\t\tprovider,\n\t\tmodel: modelId,\n\t\tusage: DEFAULT_USAGE,\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createAbortedMessage(partial: AssistantMessage): AssistantMessage {\n\treturn {\n\t\t...partial,\n\t\tstopReason: \"aborted\",\n\t\terrorMessage: \"Request was aborted\",\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction scheduleChunk(chunk: string, tokensPerSecond: number | undefined): Promise<void> {\n\tif (!tokensPerSecond || tokensPerSecond <= 0) {\n\t\treturn new Promise((resolve) => queueMicrotask(resolve));\n\t}\n\tconst delayMs = (estimateTokens(chunk) / tokensPerSecond) * 1000;\n\treturn new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\nasync function streamWithDeltas(\n\tstream: AssistantMessageEventStream,\n\tmessage: AssistantMessage,\n\tminTokenSize: number,\n\tmaxTokenSize: number,\n\ttokensPerSecond: number | undefined,\n\tsignal: AbortSignal | undefined,\n): Promise<void> {\n\tconst partial: AssistantMessage = { ...message, content: [], stopReason: \"pending\" };\n\tif (signal?.aborted) {\n\t\tconst aborted = createAbortedMessage(partial);\n\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\tstream.end(aborted);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"start\", partial: { ...partial } });\n\n\tfor (let index = 0; index < message.content.length; index++) {\n\t\tif (signal?.aborted) {\n\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\tstream.end(aborted);\n\t\t\treturn;\n\t\t}\n\n\t\tconst block = message.content[index];\n\n\t\tif (block.type === \"thinking\") {\n\t\t\tpartial.content = [...partial.content, { type: \"thinking\", thinking: \"\" }];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.thinking, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as ThinkingContent).thinking += chunk;\n\t\t\t\tstream.push({ type: \"thinking_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_end\",\n\t\t\t\tcontentIndex: index,\n\t\t\t\tcontent: block.thinking,\n\t\t\t\tpartial: { ...partial },\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (block.type === \"text\") {\n\t\t\tpartial.content = [...partial.content, { type: \"text\", text: \"\" }];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: { ...partial } });\n\t\t\tfor (const chunk of splitStringByTokenSize(block.text, minTokenSize, maxTokenSize)) {\n\t\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\t\tstream.end(aborted);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t(partial.content[index] as TextContent).text += chunk;\n\t\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t\t}\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: { ...partial } });\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Fallback boundary markers are replay metadata with nothing to stream, but they still\n\t\t// occupy a slot in `partial.content` so later blocks keep their source `contentIndex`.\n\t\t// This matches the real Anthropic provider, which pushes the wire `fallback` block into\n\t\t// `output.content` and emits no event for it; every `contentIndex` consumer indexes\n\t\t// `partial.content` directly, so skipping the slot would shift every later block by one.\n\t\tif (block.type !== \"toolCall\") {\n\t\t\tpartial.content = [...partial.content, block];\n\t\t\tcontinue;\n\t\t}\n\n\t\tpartial.content = [...partial.content, { type: \"toolCall\", id: block.id, name: block.name, arguments: {} }];\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: index, partial: { ...partial } });\n\t\t// Partial arguments come from the same parser real providers use, so consumers see them grow.\n\t\tconst toolArguments = new ToolCallArgumentsStream();\n\t\tfor (const chunk of splitStringByTokenSize(JSON.stringify(block.arguments), minTokenSize, maxTokenSize)) {\n\t\t\tawait scheduleChunk(chunk, tokensPerSecond);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tconst aborted = createAbortedMessage(partial);\n\t\t\t\tstream.push({ type: \"error\", reason: \"aborted\", error: aborted });\n\t\t\t\tstream.end(aborted);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t(partial.content[index] as ToolCall).arguments = toolArguments.append(chunk);\n\t\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: chunk, partial: { ...partial } });\n\t\t}\n\t\t(partial.content[index] as ToolCall).arguments = block.arguments;\n\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: { ...partial } });\n\t}\n\n\tif (message.stopReason === \"pending\") {\n\t\tthrow new Error(\"Faux response ended without a stop reason\");\n\t}\n\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\tstream.push({ type: \"error\", reason: message.stopReason, error: message });\n\t\tstream.end(message);\n\t\treturn;\n\t}\n\n\tstream.push({ type: \"done\", reason: message.stopReason, message });\n\tstream.end(message);\n}\n\nexport function createFauxCore(options: RegisterFauxProviderOptions) {\n\tconst api = options.api ?? randomId(DEFAULT_API);\n\tconst provider = options.provider ?? DEFAULT_PROVIDER;\n\tconst minTokenSize = Math.max(\n\t\t1,\n\t\tMath.min(options.tokenSize?.min ?? DEFAULT_MIN_TOKEN_SIZE, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE),\n\t);\n\tconst maxTokenSize = Math.max(minTokenSize, options.tokenSize?.max ?? DEFAULT_MAX_TOKEN_SIZE);\n\tlet pendingResponses: FauxResponseStep[] = [];\n\tconst tokensPerSecond = options.tokensPerSecond;\n\tconst state: FauxProviderState = { callCount: 0, deferredFetchCount: 0, cancelledDeferred: [] };\n\tconst promptCache = new Map<string, readonly string[]>();\n\tconst deferredResponses = new Map<\n\t\tstring,\n\t\t{\n\t\t\thandle: DeferredHandle;\n\t\t\tstep: FauxResponseStep;\n\t\t\tcontext: TranscriptContext;\n\t\t\toptions: SimpleStreamOptions | undefined;\n\t\t\tmodel: Model<string>;\n\t\t\tpendingFetches: number;\n\t\t\tcancelled: boolean;\n\t\t\tfinal?: AssistantMessage;\n\t\t}\n\t>();\n\n\tconst modelDefinitions = options.models?.length\n\t\t? options.models\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tid: DEFAULT_MODEL_ID,\n\t\t\t\t\tname: DEFAULT_MODEL_NAME,\n\t\t\t\t\treasoning: false,\n\t\t\t\t\tinput: [\"text\", \"image\"] as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\t\t\t\tcontextWindow: 128000,\n\t\t\t\t\tmaxTokens: 16384,\n\t\t\t\t},\n\t\t\t];\n\tconst models = modelDefinitions.map((definition) => ({\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi,\n\t\tprovider,\n\t\tbaseUrl: DEFAULT_BASE_URL,\n\t\treasoning: definition.reasoning ?? false,\n\t\tinput: definition.input ?? [\"text\", \"image\"],\n\t\tinputLimits: definition.inputLimits,\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t})) as [Model<string>, ...Model<string>[]];\n\n\tconst resolveResponse = async (\n\t\tstep: FauxResponseStep,\n\t\tcontext: TranscriptContext,\n\t\tstreamOptions: SimpleStreamOptions | undefined,\n\t\trequestModel: Model<string>,\n\t): Promise<AssistantMessage> => {\n\t\tconst resolved = typeof step === \"function\" ? await step(context, streamOptions, state, requestModel) : step;\n\t\treturn withUsageEstimate(\n\t\t\tcloneMessage(resolved, api, provider, requestModel.id),\n\t\t\tcontext,\n\t\t\tstreamOptions,\n\t\t\tpromptCache,\n\t\t);\n\t};\n\n\tconst stream: StreamFunction<string, SimpleStreamOptions> = (requestModel, context, streamOptions) => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst step = pendingResponses.shift();\n\t\tstate.callCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tawait streamOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t\t\t\tif (!step) {\n\t\t\t\t\tlet message = createErrorMessage(\n\t\t\t\t\t\tnew Error(\"No more faux responses queued\"),\n\t\t\t\t\t\tapi,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\trequestModel.id,\n\t\t\t\t\t);\n\t\t\t\t\tmessage = withUsageEstimate(message, context, streamOptions, promptCache);\n\t\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\t\touter.end(message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (streamOptions?.deferred) {\n\t\t\t\t\tconst handle: DeferredHandle = {\n\t\t\t\t\t\tprovider: requestModel.provider,\n\t\t\t\t\t\tmodelId: requestModel.id,\n\t\t\t\t\t\tapi: requestModel.api,\n\t\t\t\t\t\tid: randomId(\"deferred\"),\n\t\t\t\t\t\t...(options.deferred?.pollAfterMs !== undefined ? { pollAfterMs: options.deferred.pollAfterMs } : {}),\n\t\t\t\t\t};\n\t\t\t\t\tdeferredResponses.set(handle.id, {\n\t\t\t\t\t\thandle,\n\t\t\t\t\t\tstep,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\toptions: streamOptions,\n\t\t\t\t\t\tmodel: requestModel,\n\t\t\t\t\t\tpendingFetches: Math.max(0, Math.floor(options.deferred?.pendingFetches ?? 0)),\n\t\t\t\t\t\tcancelled: false,\n\t\t\t\t\t});\n\t\t\t\t\tawait streamWithDeltas(\n\t\t\t\t\t\touter,\n\t\t\t\t\t\tcreateDeferredMessage(requestModel, handle),\n\t\t\t\t\t\tminTokenSize,\n\t\t\t\t\t\tmaxTokenSize,\n\t\t\t\t\t\ttokensPerSecond,\n\t\t\t\t\t\tstreamOptions.signal,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst message = await resolveResponse(step, context, streamOptions, requestModel);\n\t\t\t\tawait streamWithDeltas(outer, message, minTokenSize, maxTokenSize, tokensPerSecond, streamOptions?.signal);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst streamSimple: StreamFunction<string, SimpleStreamOptions> = (streamModel, context, streamOptions) =>\n\t\tstream(streamModel, context, streamOptions);\n\n\tconst fetchDeferred = (\n\t\trequestModel: Model<string>,\n\t\thandle: DeferredHandle,\n\t\tfetchOptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream => {\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tstate.deferredFetchCount++;\n\n\t\tqueueMicrotask(async () => {\n\t\t\ttry {\n\t\t\t\tawait fetchOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t\t\t\tconst entry = deferredResponses.get(handle.id);\n\t\t\t\tif (\n\t\t\t\t\t!entry ||\n\t\t\t\t\tentry.handle.provider !== handle.provider ||\n\t\t\t\t\tentry.handle.modelId !== handle.modelId ||\n\t\t\t\t\tentry.handle.api !== handle.api\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Unknown faux deferred response: ${handle.id}`);\n\t\t\t\t}\n\t\t\t\tif (entry.cancelled) throw new Error(`Faux deferred response was cancelled: ${handle.id}`);\n\n\t\t\t\tif (entry.pendingFetches > 0) {\n\t\t\t\t\tentry.pendingFetches--;\n\t\t\t\t\tawait streamWithDeltas(\n\t\t\t\t\t\touter,\n\t\t\t\t\t\tcreateDeferredMessage(requestModel, entry.handle),\n\t\t\t\t\t\tminTokenSize,\n\t\t\t\t\t\tmaxTokenSize,\n\t\t\t\t\t\ttokensPerSecond,\n\t\t\t\t\t\tfetchOptions?.signal,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!entry.final) {\n\t\t\t\t\tconst {\n\t\t\t\t\t\tdeferred: _deferred,\n\t\t\t\t\t\tsignal: _submissionSignal,\n\t\t\t\t\t\tonResponse: _submissionOnResponse,\n\t\t\t\t\t\t...submissionOptions\n\t\t\t\t\t} = entry.options ?? {};\n\t\t\t\t\ttry {\n\t\t\t\t\t\tentry.final = await resolveResponse(entry.step, entry.context, submissionOptions, entry.model);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tentry.final = createErrorMessage(error, api, provider, entry.model.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait streamWithDeltas(\n\t\t\t\t\touter,\n\t\t\t\t\tentry.final,\n\t\t\t\t\tminTokenSize,\n\t\t\t\t\tmaxTokenSize,\n\t\t\t\t\ttokensPerSecond,\n\t\t\t\t\tfetchOptions?.signal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = createErrorMessage(error, api, provider, requestModel.id);\n\t\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\t\touter.end(message);\n\t\t\t}\n\t\t});\n\n\t\treturn outer;\n\t};\n\n\tconst cancelDeferred = async (\n\t\trequestModel: Model<string>,\n\t\thandle: DeferredHandle,\n\t\tcancelOptions?: DeferredCancelOptions,\n\t): Promise<void> => {\n\t\tstate.cancelledDeferred.push(structuredClone(handle));\n\t\tconst entry = deferredResponses.get(handle.id);\n\t\tif (entry) entry.cancelled = true;\n\t\tawait cancelOptions?.onResponse?.({ status: 200, headers: {} }, requestModel);\n\t};\n\n\tfunction getModel(): Model<string>;\n\tfunction getModel(requestedModelId: string): Model<string> | undefined;\n\tfunction getModel(requestedModelId?: string): Model<string> | undefined {\n\t\tif (!requestedModelId) {\n\t\t\treturn models[0];\n\t\t}\n\t\treturn models.find((candidate) => candidate.id === requestedModelId);\n\t}\n\n\treturn {\n\t\tapi,\n\t\tprovider,\n\t\tmodels,\n\t\tstream,\n\t\tstreamSimple,\n\t\tfetchDeferred,\n\t\tcancelDeferred,\n\t\tgetModel,\n\t\tstate,\n\t\tsetResponses(responses: FauxResponseStep[]) {\n\t\t\tpendingResponses = [...responses];\n\t\t},\n\t\tappendResponses(responses: FauxResponseStep[]) {\n\t\t\tpendingResponses.push(...responses);\n\t\t},\n\t\tgetPendingResponseCount() {\n\t\t\treturn pendingResponses.length;\n\t\t},\n\t};\n}\n\n/**\n * Faux provider for tests built on explicit `Models` collections:\n *\n * ```ts\n * const faux = fauxProvider();\n * const models = createModels();\n * models.setProvider(faux.provider);\n * faux.setResponses([fauxAssistantMessage(\"hi\")]);\n * ```\n */\nexport function fauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderHandle {\n\tconst core = createFauxCore(options);\n\tconst provider = createProvider({\n\t\tid: core.provider,\n\t\tauth: { apiKey: { name: \"Faux\", resolve: async () => ({ auth: {} }) } },\n\t\tmodels: core.models,\n\t\tapi: {\n\t\t\tstream: core.stream,\n\t\t\tstreamSimple: core.streamSimple,\n\t\t\tfetchDeferred: core.fetchDeferred,\n\t\t\tcancelDeferred: core.cancelDeferred,\n\t\t},\n\t});\n\treturn {\n\t\tprovider,\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};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"radius-config.d.ts","sourceRoot":"","sources":["../../src/providers/radius-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK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AAU,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe,GAAG,SAAS,GAAG,KAAK,CAAC,aAAa,CAAC,EAAE,CAGnH;AAOD,wBAAsB,uBAAuB,CAC5C,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,mBAAmB,CAAC,CAY9B"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ownedSlice } from "../utils/text.js";
|
|
1
2
|
export const DEFAULT_RADIUS_GATEWAY = "https://radius.pi.dev";
|
|
2
3
|
function isRadiusGatewayModel(value) {
|
|
3
4
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
@@ -45,7 +46,7 @@ export function getRadiusModels(providerId, credential) {
|
|
|
45
46
|
}
|
|
46
47
|
function truncateHttpBody(body) {
|
|
47
48
|
const trimmed = body.trim();
|
|
48
|
-
return trimmed.length > 512 ? `${trimmed
|
|
49
|
+
return trimmed.length > 512 ? `${ownedSlice(trimmed, 0, 512)}…` : trimmed;
|
|
49
50
|
}
|
|
50
51
|
export async function loadRadiusGatewayConfig(gateway, apiKey, signal) {
|
|
51
52
|
const headers = { accept: "application/json" };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"radius-config.js","sourceRoot":"","sources":["../../src/providers/radius-config.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"radius-config.js","sourceRoot":"","sources":["../../src/providers/radius-config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,MAAM,CAAC,MAAM,sBAAsB,GAAG,uBAAuB,CAAC;AAsB9D,SAAS,oBAAoB,CAAC,KAAc;IAC3C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtF,MAAM,KAAK,GAAG,KAAoC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AAE,CAAC;QAClB,MAAM,IAAI,KAAK,CACd,qCAAqC,OAAO,KAAK,QAAQ,CAAC,MAAM,KAAK,gBAAgB,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,CAC9G,CAAC;IACH,CAAC;IACD,MAAM,MAAM,GAAG,2BAA2B,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;IAClE,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,OAAO,EAAE,CAAC,CAAC;IACtE,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import type { OAuthCredential } from \"../auth/types.ts\";\nimport type { Model, ThinkingLevelMap } from \"../types.ts\";\nimport { ownedSlice } from \"../utils/text.ts\";\n\nexport const DEFAULT_RADIUS_GATEWAY = \"https://radius.pi.dev\";\n\nexport type RadiusGatewayModel = {\n\tid: string;\n\tname: string;\n\treasoning: boolean;\n\tthinkingLevelMap?: ThinkingLevelMap;\n\tinput: (\"text\" | \"image\")[];\n\tcost: Model<\"pi-messages\">[\"cost\"];\n\tcontextWindow: number;\n\tmaxTokens: number;\n};\n\nexport type RadiusGatewayConfig = {\n\tbaseUrl: string;\n\tmodels: RadiusGatewayModel[];\n};\n\nexport type RadiusOAuthCredential = OAuthCredential & {\n\tgatewayConfig?: RadiusGatewayConfig;\n};\n\nfunction isRadiusGatewayModel(value: unknown): value is RadiusGatewayModel {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst model = value as Partial<RadiusGatewayModel>;\n\treturn (\n\t\ttypeof model.id === \"string\" &&\n\t\ttypeof model.name === \"string\" &&\n\t\ttypeof model.reasoning === \"boolean\" &&\n\t\tArray.isArray(model.input) &&\n\t\ttypeof model.cost === \"object\" &&\n\t\tmodel.cost !== null &&\n\t\t!Array.isArray(model.cost) &&\n\t\ttypeof model.contextWindow === \"number\" &&\n\t\ttypeof model.maxTokens === \"number\"\n\t);\n}\n\nfunction sanitizeRadiusGatewayConfig(config: unknown): RadiusGatewayConfig | undefined {\n\tif (typeof config !== \"object\" || config === null || Array.isArray(config)) return undefined;\n\tconst { baseUrl, models } = config as Partial<RadiusGatewayConfig>;\n\tif (typeof baseUrl !== \"string\" || !Array.isArray(models)) return undefined;\n\treturn {\n\t\tbaseUrl,\n\t\tmodels: models.filter(isRadiusGatewayModel).map((model) => ({ ...model })),\n\t};\n}\n\nexport function normalizeRadiusGatewayUrl(value: string): string {\n\tconst withScheme = /^https?:\\/\\//iu.test(value) ? value : `https://${value}`;\n\treturn withScheme.replace(/\\/+$/u, \"\");\n}\n\nexport function getRadiusCredentialConfig(credential: OAuthCredential | undefined): RadiusGatewayConfig | undefined {\n\treturn sanitizeRadiusGatewayConfig((credential as RadiusOAuthCredential | undefined)?.gatewayConfig);\n}\n\nexport function getRadiusModelsFromConfig(providerId: string, config: RadiusGatewayConfig): Model<\"pi-messages\">[] {\n\treturn config.models.map((model) => ({\n\t\t...model,\n\t\tapi: \"pi-messages\",\n\t\tprovider: providerId,\n\t\tbaseUrl: config.baseUrl,\n\t}));\n}\n\nexport function getRadiusModels(providerId: string, credential: OAuthCredential | undefined): Model<\"pi-messages\">[] {\n\tconst config = getRadiusCredentialConfig(credential);\n\treturn config ? getRadiusModelsFromConfig(providerId, config) : [];\n}\n\nfunction truncateHttpBody(body: string): string {\n\tconst trimmed = body.trim();\n\treturn trimmed.length > 512 ? `${ownedSlice(trimmed, 0, 512)}…` : trimmed;\n}\n\nexport async function loadRadiusGatewayConfig(\n\tgateway: string,\n\tapiKey?: string,\n\tsignal?: AbortSignal,\n): Promise<RadiusGatewayConfig> {\n\tconst headers: Record<string, string> = { accept: \"application/json\" };\n\tif (apiKey) headers.authorization = `Bearer ${apiKey}`;\n\tconst response = await fetch(new URL(\"/v1/config\", gateway), { headers, signal });\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius config from ${gateway}: ${response.status}: ${truncateHttpBody(await response.text())}`,\n\t\t);\n\t}\n\tconst config = sanitizeRadiusGatewayConfig(await response.json());\n\tif (!config) throw new Error(`Invalid Radius config from ${gateway}`);\n\treturn config;\n}\n"]}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TelemetryContext } from \"@earendil-works/pi-telemetry\";\nimport type { AnthropicOptions } from \"./api/anthropic-messages.ts\";\nimport type { AzureOpenAIResponsesOptions } from \"./api/azure-openai-responses.ts\";\nimport type { BedrockOptions } from \"./api/bedrock-converse-stream.ts\";\nimport type { GoogleOptions } from \"./api/google-generative-ai.ts\";\nimport type { GoogleVertexOptions } from \"./api/google-vertex.ts\";\nimport type { MistralOptions } from \"./api/mistral-conversations.ts\";\nimport type { OpenAICodexResponsesOptions } from \"./api/openai-codex-responses.ts\";\nimport type { OpenAICompletionsOptions } from \"./api/openai-completions.ts\";\nimport type { OpenAIImagesOptions } from \"./api/openai-images.ts\";\nimport type { OpenAIResponsesOptions } from \"./api/openai-responses.ts\";\nimport type { PiMessagesOptions } from \"./api/pi-messages.ts\";\nimport type {\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tSystemOneCompat,\n} from \"./providers/compat-schema.ts\";\nimport type {\n\tCacheRetention,\n\tModelCost,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nimport type { AssistantMessageDiagnostic } from \"./utils/diagnostics.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\nimport type { ClientIdentity } from \"./utils/identity.ts\";\n\nexport type {\n\tAnthropicAllowedFallbackModel,\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tChatTemplateKwargValue,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tOpenRouterRouting,\n\tSessionAffinityFormat,\n\tSystemOneCompat,\n\tThinkingTokenBudgetField,\n\tVercelGatewayRouting,\n} from \"./providers/compat-schema.ts\";\nexport type {\n\tCacheRetention,\n\tModelCost,\n\tModelCostRates,\n\tModelCostTier,\n\tModelImageInputLimits,\n\tModelImageResizeOptions,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nexport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\n\nexport type KnownApi =\n\t| \"openai-completions\"\n\t| \"mistral-conversations\"\n\t| \"openai-responses\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex-responses\"\n\t| \"anthropic-messages\"\n\t| \"bedrock-converse-stream\"\n\t| \"google-generative-ai\"\n\t| \"google-vertex\"\n\t| \"pi-messages\";\n\nexport type Api = KnownApi | (string & {});\n\nexport type KnownImageApi = \"openrouter-images\" | \"openai-images\";\n\nexport type ImageApi = KnownImageApi | (string & {});\n\nexport type KnownClassifierApi =\n\t| \"typesafe-system-one\"\n\t| \"cloudflare-workers-ai-system-one\"\n\t| \"llama-cpp-classify\"\n\t| \"openai-decisions\";\n\nexport type ClassifierApi = KnownClassifierApi | (string & {});\n\nexport type CompactorApi = \"morph-compact\";\n\nexport type KnownProvider =\n\t| \"amazon-bedrock\"\n\t| \"ant-ling\"\n\t| \"anthropic\"\n\t| \"anthropic-api\"\n\t| \"google\"\n\t| \"google-vertex\"\n\t| \"openai\"\n\t| \"openai-api\"\n\t| \"azure\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex\"\n\t| \"openai-decisions\"\n\t| \"openai-images\"\n\t| \"radius\"\n\t| \"typesafe\"\n\t| \"morph\"\n\t| \"nvidia\"\n\t| \"deepseek\"\n\t| \"github-copilot\"\n\t| \"xai\"\n\t| \"groq\"\n\t| \"cerebras\"\n\t| \"openrouter\"\n\t| \"vercel-ai-gateway\"\n\t| \"zai\"\n\t| \"zai-coding-cn\"\n\t| \"mistral\"\n\t| \"minimax\"\n\t| \"minimax-cn\"\n\t| \"moonshotai\"\n\t| \"moonshotai-cn\"\n\t| \"huggingface\"\n\t| \"fireworks\"\n\t| \"together\"\n\t| \"baseten\"\n\t| \"opencode\"\n\t| \"opencode-go\"\n\t| \"kimi-coding\"\n\t| \"meta\"\n\t| \"cloudflare-workers-ai\"\n\t| \"cloudflare-ai-gateway\"\n\t| \"qwen-token-plan\"\n\t| \"qwen-token-plan-cn\"\n\t| \"qwen-token-plan-individual\"\n\t| \"xiaomi\"\n\t| \"xiaomi-token-plan-cn\"\n\t| \"xiaomi-token-plan-ams\"\n\t| \"xiaomi-token-plan-sgp\";\nexport type ProviderId = KnownProvider | string;\n\nexport type ToolChoice = \"auto\" | \"none\";\nexport type SamplingParams = Record<string, unknown>;\nexport type SamplingParamsByThinkingLevel = Partial<Record<ModelThinkingLevel, SamplingParams>>;\n/** Token budgets for each thinking level (token-based providers only) */\nexport interface ThinkingBudgets {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\n// Base options all providers share\nexport type Transport = \"sse\" | \"websocket\" | \"websocket-cached\" | \"auto\";\n\n/** Provider-scoped environment overrides. Values take precedence over process.env. */\nexport type ProviderEnv = Record<string, string>;\nexport type ProviderHeaders = Record<string, string | null>;\nexport type FetchFunction = typeof globalThis.fetch;\n\nexport interface ProviderResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Authentication, HTTP transport, and lifecycle callbacks shared by provider requests. */\nexport interface ProviderRequestOptions<TModel = Model<Api>> {\n\tsignal?: AbortSignal;\n\t/** Explicit parent context for telemetry produced by this logical request. */\n\ttelemetryContext?: TelemetryContext;\n\tapiKey?: string;\n\t/**\n\t * Optional fetch implementation for provider HTTP requests.\n\t * Defaults to `globalThis.fetch`. Provider adapters that cannot inject a custom implementation may reject it.\n\t * This does not affect WebSocket transports.\n\t */\n\tfetch?: FetchFunction;\n\t/**\n\t * Provider-scoped environment values. These take precedence over process.env for\n\t * provider configuration such as regional settings, endpoint placeholders, and\n\t * proxy variables.\n\t */\n\tenv?: ProviderEnv;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: TModel) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received.\n\t */\n\tonResponse?: (response: ProviderResponse, model: TModel) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; caller values override default headers.\n\t * On AWS Bedrock these are injected via a Smithy `build`-step middleware so\n\t * they are covered by SigV4 signing; reserved headers (`x-amz-*`,\n\t * `authorization`, `host`) are silently ignored to preserve SigV4 / bearer auth.\n\t * A null value suppresses a provider/API default header with the same name.\n\t */\n\theaders?: ProviderHeaders;\n\t/**\n\t * How the request identifies the calling app: `User-Agent` and provider attribution headers.\n\t * Absent fields use pi-ai's defaults: a detailed `User-Agent` and no attribution.\n\t */\n\tidentity?: ClientIdentity;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t * For example, OpenAI and Anthropic SDK clients default to 10 minutes.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t * For example, OpenAI and Anthropic SDK clients default to 2.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport interface StreamOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Optional callback invoked after an HTTP response is received and before\n\t * its body stream is consumed.\n\t */\n\tonResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;\n\t/**\n\t * Optional observer for each parsed provider stream event before Pi normalization.\n\t * Event data is adapter-owned and must be treated as read-only.\n\t * Adapter support is explicit; unsupported adapters do not invoke it.\n\t */\n\tonProviderStreamEvent?: (data: unknown, model: Model<Api>) => void | Promise<void>;\n\ttemperature?: number;\n\t/**\n\t * Arbitrary sampling parameters merged into the request body as-is, after the named request\n\t * fields, so keys here override them. Lets custom OpenAI-compatible servers (llama.cpp, vLLM,\n\t * SGLang, ...) receive parameters pi does not model, e.g. `top_p`, `top_k`, `min_p`,\n\t * `repetition_penalty`. Merged over `Model.samplingParams` per key. Only applied by\n\t * OpenAI-compatible adapters (completions, responses, Azure responses); other APIs ignore it.\n\t */\n\tsamplingParams?: SamplingParams;\n\tmaxTokens?: number;\n\t/**\n\t * Preferred transport for providers that support multiple transports.\n\t * Providers that do not support this option ignore it.\n\t */\n\ttransport?: Transport;\n\t/**\n\t * Prompt cache retention preference. Providers map this to their supported values.\n\t * Default: \"short\".\n\t */\n\tcacheRetention?: CacheRetention;\n\t/**\n\t * Optional session identifier for providers that support session-based caching.\n\t * Providers can use this to enable prompt caching, request routing, or other\n\t * session-aware features. Ignored by providers that don't support it.\n\t */\n\tsessionId?: string;\n\t/**\n\t * WebSocket connect timeout in milliseconds for providers that support\n\t * WebSocket transports. This covers the connection/open handshake only;\n\t * HTTP/SDK idleness uses `timeoutMs`, while gaps between decoded provider\n\t * stream events use `streamDeadlineMs`.\n\t */\n\twebsocketConnectTimeoutMs?: number;\n\t/**\n\t * Maximum idle gap in milliseconds between two provider stream events.\n\t *\n\t * Enforced below the HTTP layer, so a response body that stalls without ever\n\t * rejecting the adapter's async iterator (for example a decompression failure\n\t * that destroys the stream silently, #2553) still settles the attempt as a\n\t * retryable transport error instead of hanging forever. The timer restarts on\n\t * every event, so it never caps total stream duration.\n\t *\n\t * Defaults to 300000 ms. `0` (or any non-positive value) disables it.\n\t */\n\tstreamDeadlineMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderStreamOptions = StreamOptions & Record<string, unknown>;\n\nexport interface DeferredFetchOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Maximum provider long-poll duration in milliseconds.\n\t * Defaults to 0, which performs one status check.\n\t */\n\twait?: number;\n}\n\n/** Request options for best-effort deferred-response cancellation. */\nexport type DeferredCancelOptions = ProviderRequestOptions<Model<Api>>;\n\n/**\n * Maps known APIs to their full provider-specific stream option types.\n * Type-only imports from API implementation modules are erased at emit, so\n * this is tree-shake safe.\n */\nexport interface ApiOptionsMap {\n\t\"anthropic-messages\": AnthropicOptions;\n\t\"openai-completions\": OpenAICompletionsOptions;\n\t\"openai-responses\": OpenAIResponsesOptions;\n\t\"openai-codex-responses\": OpenAICodexResponsesOptions;\n\t\"azure-openai-responses\": AzureOpenAIResponsesOptions;\n\t\"google-generative-ai\": GoogleOptions;\n\t\"google-vertex\": GoogleVertexOptions;\n\t\"mistral-conversations\": MistralOptions;\n\t\"bedrock-converse-stream\": BedrockOptions;\n\t\"pi-messages\": PiMessagesOptions;\n}\n\n/**\n * Full stream options for an API. Known APIs resolve to their concrete option\n * type; custom API strings fall back to the generic shape.\n */\nexport type ApiStreamOptions<TApi extends Api> = TApi extends keyof ApiOptionsMap\n\t? ApiOptionsMap[TApi]\n\t: StreamOptions & Record<string, unknown>;\n\n/**\n * The uniform stream contract of an API implementation module: every module\n * under `src/api/` exports `stream` and `streamSimple`; capable modules may also\n * export deferred-response methods. Lazy wrappers (`lazyApi()`) and provider\n * factories pass these around as values. This is the untyped dispatch shape;\n * per-API option typing lives on the implementation modules themselves and on\n * `Provider.stream()` via `ApiStreamOptions`.\n */\nexport interface ProviderStreams {\n\tstream(model: Model<Api>, context: TranscriptContext, options?: StreamOptions): AssistantMessageEventStream;\n\tstreamSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred?(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tcancelDeferred?(model: Model<Api>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;\n}\n\n/**\n * The uniform contract of an image-generation API implementation module:\n * every image API module under `src/api/` exports exactly `generateImages`,\n * so the module itself satisfies this interface. Lazy wrappers and\n * `createProvider({ images })` pass these around as values.\n */\nexport interface ProviderImages {\n\tgenerateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ImagesOptions,\n\t): Promise<AssistantImages>;\n}\n\n/** The uniform contract implemented by classifier API modules. */\nexport interface ProviderClassifier {\n\tclassify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\nexport interface ClassifierOptions extends ProviderRequestOptions<ClassifierModel<ClassifierApi>> {\n\t/**\n\t * Divides the answer logits by this value before they are normalized into probabilities.\n\t * Values above 1 soften the distribution; values below 1 sharpen it. Must be positive.\n\t * APIs that cannot apply it ignore it.\n\t */\n\ttemperature?: number;\n}\n\nexport interface ImagesOptions extends ProviderRequestOptions<ImageModel<ImageApi>> {\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;\n\n/**\n * Maps known image APIs to their request option types, like `ApiOptionsMap`\n * does for chat APIs.\n */\nexport interface ImageApiOptionsMap {\n\t\"openrouter-images\": ImagesOptions;\n\t\"openai-images\": OpenAIImagesOptions;\n}\n\n/**\n * Request options for an image API. Known APIs resolve to their concrete option\n * type; custom API strings fall back to the generic shape.\n */\nexport type ImageApiOptions<TApi extends ImageApi> = TApi extends keyof ImageApiOptionsMap\n\t? ImageApiOptionsMap[TApi]\n\t: ProviderImagesOptions;\n\n// Unified options with reasoning passed to streamSimple() and completeSimple()\nexport interface SimpleStreamOptions extends StreamOptions {\n\t/** Provider-neutral tool selection for simple requests. When omitted, adapters use provider-specific behavior. */\n\ttoolChoice?: ToolChoice;\n\treasoning?: ThinkingLevel;\n\t/** Ask a capable provider to return a durable handle and continue the request asynchronously. */\n\tdeferred?: boolean | { window?: \"15m\" | \"1h\" | \"24h\" };\n\t/** Custom token budgets for thinking levels (token-based providers only) */\n\tthinkingBudgets?: ThinkingBudgets;\n}\n\n// Generic StreamFunction with typed options.\n//\n// Contract:\n// - Receives a normalized transcript: the system prompt and tools live in the\n// leading system message, never on the context itself.\n// - Must return an AssistantMessageEventStream.\n// - Direct streamSimple() calls may throw synchronously when request auth is\n// missing. Once a stream is returned, request/model/runtime failures should\n// be encoded in the stream, not thrown.\n// - Error termination must produce an AssistantMessage with stopReason\n// \"error\" or \"aborted\" and errorMessage, emitted via the stream protocol.\nexport type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (\n\tmodel: Model<TApi>,\n\tcontext: TranscriptContext,\n\toptions?: TOptions,\n) => AssistantMessageEventStream;\n\nexport type ImagesFunction<TOptions extends ImagesOptions = ImagesOptions> = (\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions?: TOptions,\n) => Promise<AssistantImages>;\n\nexport type ClassifierFunction<TOptions extends ClassifierOptions = ClassifierOptions> = (\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions?: TOptions,\n) => Promise<ClassifierResult>;\n\nexport interface TextSignatureV1 {\n\tv: 1;\n\tid: string;\n\tphase?: \"commentary\" | \"final_answer\";\n}\n\nexport interface TextContent {\n\ttype: \"text\";\n\ttext: string;\n\ttextSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)\n}\n\nexport interface ThinkingContent {\n\ttype: \"thinking\";\n\tthinking: string;\n\tthinkingSignature?: string; // Provider-specific opaque or serialized reasoning replay data\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted?: boolean;\n}\n\n/**\n * Boundary marker emitted by Anthropic server-side fallback, where one model's output gives way\n * to the next after a classifier refusal.\n *\n * This is public content rather than a stream-only event because it must survive the round trip:\n * \"Keep it exactly where it appeared. The API uses its position to validate the thinking blocks\n * around it, so a request that echoes thinking blocks from both sides of the boundary is rejected\n * if the block is omitted or moved.\"\n * https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n */\nexport interface FallbackContent {\n\ttype: \"fallback\";\n\t/** The model that declined. Echoes the model string sent when the declining hop is the request's own model. */\n\tfromModel: string;\n\t/** Resolved id of the model that continues. Always present. */\n\ttoModel: string;\n}\n\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string; // base64 encoded image data\n\tmimeType: string; // e.g., \"image/jpeg\", \"image/png\"\n}\n\n/**\n * A document sent as model input, currently PDF only.\n *\n * Anthropic documents PDF as a platform capability — \"All active models support PDF processing\" —\n * routed through the same vision path as images, so it is not a per-model modality. A model\n * advertises it through `Model.input` containing `\"pdf\"`, which generated metadata sets only for\n * the runtimes that can actually serialize a document block. Providers that cannot are sent a\n * visible placeholder instead, exactly as they are for images they cannot accept.\n * https://platform.claude.com/docs/en/build-with-claude/pdf-support\n */\nexport interface DocumentContent {\n\ttype: \"document\";\n\t/** Base64-encoded document bytes. Amazon Bedrock takes raw bytes and decodes this itself. */\n\tdata: string;\n\t/**\n\t * The only media type either serializer implements. It is a literal rather than `string`\n\t * because both paths hardcode PDF — the Anthropic block emits `BetaBase64PDFSource`, whose\n\t * `media_type` is itself a fixed literal, and Bedrock emits `DocumentFormat.PDF` — so a wider\n\t * type would let a caller label arbitrary bytes as a PDF. Widening this union later is\n\t * non-breaking; narrowing it after release would not be. Note that adding a format is not a\n\t * media-type swap on the Anthropic side: plain text needs a structurally different source\n\t * variant (`BetaPlainTextSource`, `type: \"text\"`), and Bedrock's `doc`/`docx`/`xls`/`xlsx`/\n\t * `csv`/`html`/`md` formats have no Anthropic source variant at all.\n\t */\n\tmimeType: \"application/pdf\";\n\t/**\n\t * Optional caller-supplied label. Amazon Bedrock requires a name and warns that it \"is\n\t * vulnerable to prompt injections\", so the Bedrock path sanitizes this to the characters AWS\n\t * permits and falls back to a neutral generated name.\n\t */\n\tname?: string;\n}\n\nexport interface ToolCall {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: JsonObject;\n\tthoughtSignature?: string; // Google-specific: opaque signature for reusing thought context\n\t/** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */\n\tnamespace?: string;\n\targumentsError?: string;\n}\n\nexport interface Usage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\t/** Subset of `cacheWrite` written with 1h retention. Anthropic and Bedrock report this split. */\n\tcacheWrite1h?: number;\n\t/**\n\t * Reasoning/thinking tokens, when the provider reports them. This is a subset of\n\t * `output`: `output` already includes these tokens. Set to a number (possibly 0) by\n\t * providers that expose a reasoning breakdown; left undefined by providers that don't.\n\t */\n\treasoning?: number;\n\ttotalTokens: number;\n\tcost: {\n\t\t/** Catalog-derived input cost. */\n\t\tinput: number;\n\t\t/** Catalog-derived output cost. */\n\t\toutput: number;\n\t\t/** Catalog-derived cache-read cost. */\n\t\tcacheRead: number;\n\t\t/** Catalog-derived cache-write cost. */\n\t\tcacheWrite: number;\n\t\t/** Best available total: provider-reported billed cost when supported, otherwise the catalog estimate. */\n\t\ttotal: number;\n\t\t/** True when `total` is the billed cost reported by the provider. False when it is a catalog estimate; absent also means false. */\n\t\ttotalFromProvider?: boolean;\n\t};\n}\n\nexport type StopReason = \"pending\" | \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\" | \"deferred\";\n\nexport type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;\nexport type JsonObject = { [key: string]: JsonValue };\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype IsExactlyJsonValue<T> = [T] extends [JsonValue] ? ([JsonValue] extends [T] ? true : false) : false;\ntype IsJsonProperty<T> =\n\tIsAny<T> extends true\n\t\t? false\n\t\t: unknown extends T\n\t\t\t? false\n\t\t\t: [Exclude<T, undefined>] extends [never]\n\t\t\t\t? true\n\t\t\t\t: IsJsonCompatible<Exclude<T, undefined>>;\ntype InvalidJsonKeys<T extends object> = {\n\t[TKey in keyof T]-?: TKey extends string | number ? (IsJsonProperty<T[TKey]> extends true ? never : TKey) : TKey;\n}[keyof T];\ntype IsJsonCompatible<T> =\n\tIsAny<T> extends true\n\t\t? false\n\t\t: unknown extends T\n\t\t\t? false\n\t\t\t: IsExactlyJsonValue<T> extends true\n\t\t\t\t? true\n\t\t\t\t: T extends null | boolean | number | string\n\t\t\t\t\t? true\n\t\t\t\t\t: T extends undefined\n\t\t\t\t\t\t? false\n\t\t\t\t\t\t: T extends readonly (infer TItem)[]\n\t\t\t\t\t\t\t? IsJsonCompatible<TItem>\n\t\t\t\t\t\t\t: T extends (...args: never[]) => unknown\n\t\t\t\t\t\t\t\t? false\n\t\t\t\t\t\t\t\t: T extends object\n\t\t\t\t\t\t\t\t\t? [InvalidJsonKeys<T>] extends [never]\n\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t: false\n\t\t\t\t\t\t\t\t\t: false;\n\n/** The JSON representation of a typed in-memory value. Optional object properties remain optional. */\nexport type JsonRepresentation<T> =\n\tIsAny<T> extends true\n\t\t? JsonValue\n\t\t: unknown extends T\n\t\t\t? JsonValue\n\t\t\t: [T] extends [JsonValue]\n\t\t\t\t? T\n\t\t\t\t: T extends readonly unknown[]\n\t\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t\t: T extends object\n\t\t\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t\t\t: never;\n\nexport interface DeferredHandle {\n\tprovider: string;\n\tmodelId: string;\n\tapi: string;\n\t/** Provider token, such as a response id or batch id plus row id. */\n\tid: string;\n\texpiresAt?: number;\n\tpollAfterMs?: number;\n\t/** Provider conversion data required to reconstruct the final assistant message. */\n\tdata?: JsonValue;\n}\n\n/**\n * System instructions and tool declarations at one point in the transcript.\n *\n * The leading system message is the system prompt. Later system messages change it:\n * `content` adds instructions from that point on, `sections` replace or remove named\n * prompt sections, and `toolsAdded`/`toolsRemoved` change the tool set. Replaying\n * every system message in order yields the current prompt and tools. Providers that\n * accept system messages mid-conversation send each one in place; other providers\n * rebuild the leading system message from the replayed state.\n */\nexport interface SystemMessage {\n\trole: \"system\";\n\t/** Instruction text. On the leading message this is the base prompt; later, additional instructions. */\n\tcontent: string | TextContent[];\n\t/**\n\t * Named, ordered prompt sections rendered verbatim after `content`. The leading message\n\t * declares them; later messages replace sections by name, and `null` removes one. Keep\n\t * each section self-delimiting (a tag, a heading) so the model can relate an update to\n\t * the original. Avoid integer-like names; JSON objects reorder those.\n\t */\n\tsections?: Record<string, string | null>;\n\t/** Complete definitions of tools that become available at this point. */\n\ttoolsAdded?: Tool[];\n\t/** Tools that stop being available at this point. */\n\ttoolsRemoved?: ToolReference[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface UserMessage {\n\trole: \"user\";\n\tcontent: string | (TextContent | ImageContent | DocumentContent)[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface AssistantMessage {\n\trole: \"assistant\";\n\tcontent: (TextContent | ThinkingContent | ToolCall | FallbackContent)[];\n\tapi: Api;\n\tprovider: ProviderId;\n\tmodel: string;\n\tresponseModel?: string; // Concrete model reported by the provider when different from the requested `model`\n\tresponseId?: string; // Provider-specific response/message identifier when the upstream API exposes one\n\t/** Exact provider-native effort level used for this response. Absent for legacy or unmanaged responses. */\n\tproviderThinkingLevel?: string;\n\tdiagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.\n\tusage: Usage;\n\tstopReason: StopReason;\n\tdeferred?: DeferredHandle;\n\terrorMessage?: string;\n\t/** Server-requested retry delay in ms (`Retry-After` or a body `retry_after`), when the provider sent one. */\n\tretryAfterMs?: number;\n\trawStopReason?: string;\n\t/**\n\t * Provider indication of whether the model explicitly ended its turn.\n\t * Preserved for debugging and does not currently affect agent control flow.\n\t */\n\tendTurn?: boolean;\n\ttimestamp: number; // Unix timestamp in milliseconds\n\tdurationMs?: number;\n}\n\n/** A tool call made by another tool, such as a codemode script. */\nexport interface NestedToolCallRecord {\n\tid: string;\n\tname: string;\n\t/** Omitted when over the size limits. */\n\targuments?: JsonObject;\n\t/** UTF-8 JSON size when arguments are omitted. */\n\targumentsBytes?: number;\n\tstatus: \"ok\" | \"error\" | \"unfinished\";\n\tdurationMs?: number;\n\terror?: string;\n}\n\n/** Bounded nested-call record. Results are not recorded. */\nexport interface NestedToolCalls {\n\tcalls: NestedToolCallRecord[];\n\tcomplete: boolean;\n}\n\nexport type ToolResultMessage<TDetails = JsonValue> =\n\tIsJsonCompatible<TDetails> extends true\n\t\t? {\n\t\t\t\trole: \"toolResult\";\n\t\t\t\ttoolCallId: string;\n\t\t\t\ttoolName: string;\n\t\t\t\tcontent: (TextContent | ImageContent)[]; // Supports text and images\n\t\t\t\tdetails?: JsonRepresentation<TDetails>;\n\t\t\t\t/** Usage from the tool execution itself, if available. Not part of main LLM context accounting. */\n\t\t\t\tusage?: Usage;\n\t\t\t\t/** Nested calls retained in the session, not sent to the model. */\n\t\t\t\tnestedCalls?: NestedToolCalls;\n\t\t\t\tisError: boolean;\n\t\t\t\ttimestamp: number; // Unix timestamp in milliseconds\n\t\t\t\tdurationMs?: number;\n\t\t\t}\n\t\t: never;\n\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;\n\nexport type ImagesInputContent = TextContent | ImageContent;\nexport type ImagesOutputContent = TextContent | ImageContent;\n\nexport interface ImagesContext {\n\tinput: ImagesInputContent[];\n}\n\nexport type ImagesStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface AssistantImages {\n\tapi: ImageApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\toutput: ImagesOutputContent[];\n\tresponseId?: string;\n\tusage?: Usage;\n\tstopReason: ImagesStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface ClassifierChoiceQuestion {\n\ttype: \"choice\";\n\tinstructions: string;\n\tcriteria: Record<string, string>;\n}\n\nexport interface ClassifierScoreQuestion {\n\ttype: \"score\";\n\tinstructions: string;\n\tcriteria: string[];\n}\n\nexport interface ClassifierBoolQuestion {\n\ttype: \"bool\";\n\tinstructions: string;\n\tcriteria: { true: string; false: string };\n}\n\nexport type ClassifierQuestion = ClassifierChoiceQuestion | ClassifierScoreQuestion | ClassifierBoolQuestion;\n\nexport interface ClassifierContext {\n\tstate: JsonObject;\n\t/**\n\t * Images judged together with `state`. Only models whose `input` includes `\"image\"` accept them;\n\t * other models return an error result.\n\t */\n\timages?: ImageContent[];\n\tquestions: Record<string, ClassifierQuestion>;\n}\n\nexport interface ClassifierChoiceAnswer {\n\ttype: \"choice\";\n\tchoice: string;\n\tprobabilities: Record<string, number>;\n\tconfidence: number;\n}\n\nexport interface ClassifierScoreAnswer {\n\ttype: \"score\";\n\tscore: number;\n\tconfidence: number;\n}\n\nexport interface ClassifierBoolAnswer {\n\ttype: \"bool\";\n\tprobability: number;\n}\n\nexport type ClassifierAnswer = ClassifierChoiceAnswer | ClassifierScoreAnswer | ClassifierBoolAnswer;\nexport type ClassifierStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface ClassifierResult {\n\tapi: ClassifierApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\tanswers: Record<string, ClassifierAnswer>;\n\t/** Token usage and cost at the model's catalog price, when reported. */\n\tusage?: Usage;\n\tstopReason: ClassifierStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nimport type { TSchema } from \"typebox\";\n\n/** OpenAI grammar variants for constrained sampling. */\nexport type GrammarFormat = \"openai_lark\" | \"openai_regex\";\n\nexport type GrammarVariants = Partial<Record<GrammarFormat, string>>;\n\n/**\n * Optional provider-side constrained sampling configs for a tool.\n *\n * The `json_schema` value roughly maps to the concept of `strict` in APIs which is\n * implemented as json-schema constrained sampling by APIs. Grammar variants let\n * callers provide provider-specific encodings of the same intended language.\n */\nexport type ConstrainedSamplingConfig =\n\t| {\n\t\t\ttype: \"json_schema\";\n\t\t\tstrict: \"prefer\" | \"require\";\n\t }\n\t| {\n\t\t\ttype: \"grammar\";\n\t\t\tvariants: GrammarVariants;\n\t };\n\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n}\n\nexport interface ToolReference {\n\tname: string;\n}\n\n/**\n * Request input accepted by the public stream entry points (`Models.stream()`,\n * `streamSimple()`, ...). `systemPrompt` and `tools` are shorthand for a leading\n * system message; `normalizeContext()` folds them into one before the request\n * reaches a provider.\n */\nexport interface Context {\n\tsystemPrompt?: string;\n\tmessages: Message[];\n\ttools?: Tool[];\n}\n\ndeclare const transcriptContextBrand: unique symbol;\n\n/**\n * Normalized request context passed to providers and API implementations. The\n * prompt and tool declarations are carried by the transcript's system messages.\n * Only `normalizeContext()` produces this type, so a raw `Context` cannot reach\n * provider code by accident.\n */\nexport type TranscriptContext = {\n\tmessages: Message[];\n\treadonly [transcriptContextBrand]: true;\n};\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Successful streams emit `start` before partial updates and terminate with\n * `done`. A stream may terminate directly with `error` when request setup fails\n * before generation starts; after `start`, failures also terminate with `error`.\n * Direct `streamSimple()` calls throw synchronously when request auth is missing.\n * Updates and `done` must never appear before `start`.\n *\n * Tool-call arguments at `toolcall_start` are provider-specific;\n * `toolcall_delta` carries subsequent JSON updates.\n */\nexport type AssistantMessageEvent =\n\t| { type: \"start\"; partial: AssistantMessage }\n\t| { type: \"text_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"text_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"thinking_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"thinking_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"toolcall_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\" | \"deferred\">;\n\t\t\tmessage: AssistantMessage;\n\t }\n\t| { type: \"error\"; reason: Extract<StopReason, \"aborted\" | \"error\">; error: AssistantMessage };\n\n/** Service tiers a model can advertise beyond standard processing. */\nexport type ModelServiceTierId = \"priority\" | \"ultrafast\";\n\n/**\n * A service tier a model advertises, following Codex's `ModelInfo.service_tiers`, with the provider's\n * published per-million-token rates for that tier.\n *\n * Adapters send a tier only when the model advertises it. `flex` is an API request option and needs\n * no advertisement.\n */\nexport interface ModelServiceTier {\n\tid: ModelServiceTierId;\n\tcost: ModelCost;\n}\n\n/**\n * Explicit routing metadata that marks a model as the fast-inference variant of another model.\n *\n * Presence of this field — never a `-fast` name suffix — is what gives a model fast semantics.\n * A provider, `models.json` custom model, or extension may own an exact `<base>-fast` ID without\n * this metadata, in which case it is an ordinary model and routes exactly as it is declared.\n */\nexport interface ModelFastRoute {\n\t/** Canonical ID of the normal-speed model this variant pairs with, in the same provider. */\n\tbaseModelId: string;\n\t/** Model ID to send upstream. OpenAI-style routing keeps the base ID; a provider with real fast siblings sends its own ID. */\n\tupstreamModelId: string;\n\t/** Service tier to send with the request. Set only for providers that route fast traffic through an OpenAI-style tier. */\n\tserviceTier?: ModelServiceTierId;\n\t/** Anthropic inference speed to send with the request. Set only for Claude models that support fast mode. */\n\tspeed?: \"fast\";\n}\n\n/** Fields shared by every catalog entry, regardless of what you can do with it. */\nexport interface BaseModel<TApi extends string> {\n\tid: string;\n\tname: string;\n\tapi: TApi;\n\tprovider: ProviderId;\n\tbaseUrl: string;\n\tinput: ModelInputModality[];\n\t/** Provider input limits and cache-safe preprocessing metadata. */\n\tinputLimits?: ModelInputLimits;\n\tcost: ModelCost;\n\theaders?: Record<string, string>;\n}\n\n/** Chat model: usable with `stream()` and friends. */\nexport interface Model<TApi extends Api> extends BaseModel<TApi> {\n\t/**\n\t * Optional: chat is the default model type, so models without `type` are chat\n\t * models. Narrow mixed model lists with `isModelType()` instead of comparing\n\t * `type` directly.\n\t */\n\ttype?: \"chat\";\n\treasoning: boolean;\n\t/**\n\t * Maps pi thinking levels to provider/model-specific values.\n\t * Missing keys use provider defaults. null marks a level as unsupported.\n\t */\n\tthinkingLevelMap?: ThinkingLevelMap;\n\t/** Prompt cache lifetimes per retention tier. Unset when the provider's cache behavior is unknown. */\n\tpromptCache?: ModelPromptCache;\n\tcontextWindow: number;\n\tmaxTokens: number;\n\t/** Default sampling parameters for this model. See {@link StreamOptions.samplingParams}; per-request keys override these. */\n\tsamplingParams?: SamplingParams;\n\t/** Sampling parameter overrides selected by the effective pi thinking level. */\n\tsamplingParamsByThinkingLevel?: SamplingParamsByThinkingLevel;\n\t/**\n\t * Marks this model as the fast-inference variant of {@link ModelFastRoute.baseModelId} and carries the\n\t * upstream routing it needs. Absent on every normal model.\n\t */\n\tfastRoute?: ModelFastRoute;\n\t/**\n\t * Service tiers this model advertises. When set, the Codex adapter sends only advertised tiers.\n\t * When unset, the model carries no tier metadata and only Ultrafast is withheld.\n\t */\n\tserviceTiers?: ModelServiceTier[];\n\t/** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */\n\tcompat?: TApi extends \"openai-completions\"\n\t\t? OpenAICompletionsCompat\n\t\t: TApi extends \"openai-responses\" | \"azure-openai-responses\" | \"openai-codex-responses\"\n\t\t\t? OpenAIResponsesCompat\n\t\t\t: TApi extends \"anthropic-messages\"\n\t\t\t\t? AnthropicMessagesCompat\n\t\t\t\t: TApi extends \"bedrock-converse-stream\"\n\t\t\t\t\t? BedrockCompat\n\t\t\t\t\t: TApi extends \"mistral-conversations\"\n\t\t\t\t\t\t? MistralConversationsCompat\n\t\t\t\t\t\t: never;\n}\n\n/** Image-generation model: usable with `generateImages()` only. */\nexport interface ImageModel<TApi extends ImageApi> extends BaseModel<TApi> {\n\ttype: \"image\";\n\t/** Output modalities. Always includes `\"image\"`; `\"text\"` means the model can also return text blocks. */\n\toutput: (\"text\" | \"image\")[];\n}\n\n/** Structured classifier model: usable with `classify()` only. */\nexport interface ClassifierModel<TApi extends ClassifierApi> extends BaseModel<TApi> {\n\ttype: \"classifier\";\n\tcontextWindow: number;\n\t/** Compatibility overrides for System One APIs. If not set, auto-detected from provider, baseUrl, and id. */\n\tcompat?: TApi extends \"typesafe-system-one\" | \"cloudflare-workers-ai-system-one\" ? SystemOneCompat : never;\n}\n\n/** Dedicated compaction model, excluded from chat model selection. */\nexport interface CompactorModel<TApi extends CompactorApi = CompactorApi> extends BaseModel<TApi> {\n\ttype: \"compactor\";\n}\n\n/** Model shape for each model type. */\nexport interface ModelTypeMap {\n\tchat: Model<Api>;\n\timage: ImageModel<ImageApi>;\n\tclassifier: ClassifierModel<ClassifierApi>;\n\tcompactor: CompactorModel;\n}\n\n/** What a catalog entry is for. Decides which `Models` operation accepts it. */\nexport type ModelType = keyof ModelTypeMap;\n\n/** Anything a provider can list. Narrow with `isModelType()`. */\nexport type AnyModel = ModelTypeMap[ModelType];\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TelemetryContext } from \"@earendil-works/pi-telemetry\";\nimport type { AnthropicOptions } from \"./api/anthropic-messages.ts\";\nimport type { AzureOpenAIResponsesOptions } from \"./api/azure-openai-responses.ts\";\nimport type { BedrockOptions } from \"./api/bedrock-converse-stream.ts\";\nimport type { GoogleOptions } from \"./api/google-generative-ai.ts\";\nimport type { GoogleVertexOptions } from \"./api/google-vertex.ts\";\nimport type { MistralOptions } from \"./api/mistral-conversations.ts\";\nimport type { OpenAICodexResponsesOptions } from \"./api/openai-codex-responses.ts\";\nimport type { OpenAICompletionsOptions } from \"./api/openai-completions.ts\";\nimport type { OpenAIImagesOptions } from \"./api/openai-images.ts\";\nimport type { OpenAIResponsesOptions } from \"./api/openai-responses.ts\";\nimport type { PiMessagesOptions } from \"./api/pi-messages.ts\";\nimport type {\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tSystemOneCompat,\n} from \"./providers/compat-schema.ts\";\nimport type {\n\tCacheRetention,\n\tModelCost,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nimport type { AssistantMessageDiagnostic } from \"./utils/diagnostics.ts\";\nimport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\nimport type { ClientIdentity } from \"./utils/identity.ts\";\n\nexport type {\n\tAnthropicAllowedFallbackModel,\n\tAnthropicMessagesCompat,\n\tBedrockCompat,\n\tChatTemplateKwargValue,\n\tMistralConversationsCompat,\n\tOpenAICompletionsCompat,\n\tOpenAIResponsesCompat,\n\tOpenRouterRouting,\n\tSessionAffinityFormat,\n\tSystemOneCompat,\n\tThinkingTokenBudgetField,\n\tVercelGatewayRouting,\n} from \"./providers/compat-schema.ts\";\nexport type {\n\tCacheRetention,\n\tModelCost,\n\tModelCostRates,\n\tModelCostTier,\n\tModelImageInputLimits,\n\tModelImageResizeOptions,\n\tModelInputLimits,\n\tModelInputModality,\n\tModelPromptCache,\n\tModelThinkingLevel,\n\tThinkingLevel,\n\tThinkingLevelMap,\n} from \"./providers/model-schema.ts\";\nexport type { AssistantMessageEventStream } from \"./utils/event-stream.ts\";\n\nexport type KnownApi =\n\t| \"openai-completions\"\n\t| \"mistral-conversations\"\n\t| \"openai-responses\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex-responses\"\n\t| \"anthropic-messages\"\n\t| \"bedrock-converse-stream\"\n\t| \"google-generative-ai\"\n\t| \"google-vertex\"\n\t| \"pi-messages\";\n\nexport type Api = KnownApi | (string & {});\n\nexport type KnownImageApi = \"openrouter-images\" | \"openai-images\";\n\nexport type ImageApi = KnownImageApi | (string & {});\n\nexport type KnownClassifierApi =\n\t| \"typesafe-system-one\"\n\t| \"cloudflare-workers-ai-system-one\"\n\t| \"llama-cpp-classify\"\n\t| \"openai-decisions\";\n\nexport type ClassifierApi = KnownClassifierApi | (string & {});\n\nexport type CompactorApi = \"morph-compact\";\n\nexport type KnownProvider =\n\t| \"amazon-bedrock\"\n\t| \"ant-ling\"\n\t| \"anthropic\"\n\t| \"anthropic-api\"\n\t| \"google\"\n\t| \"google-vertex\"\n\t| \"openai\"\n\t| \"openai-api\"\n\t| \"azure\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex\"\n\t| \"openai-decisions\"\n\t| \"openai-images\"\n\t| \"radius\"\n\t| \"typesafe\"\n\t| \"morph\"\n\t| \"nvidia\"\n\t| \"deepseek\"\n\t| \"github-copilot\"\n\t| \"xai\"\n\t| \"groq\"\n\t| \"cerebras\"\n\t| \"openrouter\"\n\t| \"vercel-ai-gateway\"\n\t| \"zai\"\n\t| \"zai-coding-cn\"\n\t| \"mistral\"\n\t| \"minimax\"\n\t| \"minimax-cn\"\n\t| \"moonshotai\"\n\t| \"moonshotai-cn\"\n\t| \"huggingface\"\n\t| \"fireworks\"\n\t| \"together\"\n\t| \"baseten\"\n\t| \"opencode\"\n\t| \"opencode-go\"\n\t| \"kimi-coding\"\n\t| \"meta\"\n\t| \"cloudflare-workers-ai\"\n\t| \"cloudflare-ai-gateway\"\n\t| \"qwen-token-plan\"\n\t| \"qwen-token-plan-cn\"\n\t| \"qwen-token-plan-individual\"\n\t| \"xiaomi\"\n\t| \"xiaomi-token-plan-cn\"\n\t| \"xiaomi-token-plan-ams\"\n\t| \"xiaomi-token-plan-sgp\";\nexport type ProviderId = KnownProvider | string;\n\nexport type ToolChoice = \"auto\" | \"none\";\nexport type SamplingParams = Record<string, unknown>;\nexport type SamplingParamsByThinkingLevel = Partial<Record<ModelThinkingLevel, SamplingParams>>;\n/** Token budgets for each thinking level (token-based providers only) */\nexport interface ThinkingBudgets {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\n// Base options all providers share\nexport type Transport = \"sse\" | \"websocket\" | \"websocket-cached\" | \"auto\";\n\n/** Provider-scoped environment overrides. Values take precedence over process.env. */\nexport type ProviderEnv = Record<string, string>;\nexport type ProviderHeaders = Record<string, string | null>;\nexport type FetchFunction = typeof globalThis.fetch;\n\nexport interface ProviderResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Authentication, HTTP transport, and lifecycle callbacks shared by provider requests. */\nexport interface ProviderRequestOptions<TModel = Model<Api>> {\n\tsignal?: AbortSignal;\n\t/** Explicit parent context for telemetry produced by this logical request. */\n\ttelemetryContext?: TelemetryContext;\n\tapiKey?: string;\n\t/**\n\t * Optional fetch implementation for provider HTTP requests.\n\t * Defaults to `globalThis.fetch`. Provider adapters that cannot inject a custom implementation may reject it.\n\t * This does not affect WebSocket transports.\n\t */\n\tfetch?: FetchFunction;\n\t/**\n\t * Provider-scoped environment values. These take precedence over process.env for\n\t * provider configuration such as regional settings, endpoint placeholders, and\n\t * proxy variables.\n\t */\n\tenv?: ProviderEnv;\n\t/**\n\t * Optional callback for inspecting or replacing provider payloads before sending.\n\t * Return undefined to keep the payload unchanged.\n\t */\n\tonPayload?: (payload: unknown, model: TModel) => unknown | undefined | Promise<unknown | undefined>;\n\t/**\n\t * Optional callback invoked after an HTTP response is received.\n\t */\n\tonResponse?: (response: ProviderResponse, model: TModel) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; caller values override default headers.\n\t * On AWS Bedrock these are injected via a Smithy `build`-step middleware so\n\t * they are covered by SigV4 signing; reserved headers (`x-amz-*`,\n\t * `authorization`, `host`) are silently ignored to preserve SigV4 / bearer auth.\n\t * A null value suppresses a provider/API default header with the same name.\n\t */\n\theaders?: ProviderHeaders;\n\t/**\n\t * How the request identifies the calling app: `User-Agent` and provider attribution headers.\n\t * Absent fields use pi-ai's defaults: a detailed `User-Agent` and no attribution.\n\t */\n\tidentity?: ClientIdentity;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t * For example, OpenAI and Anthropic SDK clients default to 10 minutes.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\n\t * For example, OpenAI and Anthropic SDK clients default to 2.\n\t */\n\tmaxRetries?: number;\n\t/**\n\t * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.\n\t * If the server's requested delay exceeds this value, the request fails immediately\n\t * with an error containing the requested delay, allowing higher-level retry logic\n\t * to handle it with user visibility.\n\t * Default: 60000 (60 seconds). Set to 0 to disable the cap.\n\t */\n\tmaxRetryDelayMs?: number;\n}\n\nexport interface StreamOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Optional callback invoked after an HTTP response is received and before\n\t * its body stream is consumed.\n\t */\n\tonResponse?: (response: ProviderResponse, model: Model<Api>) => void | Promise<void>;\n\t/**\n\t * Optional observer for each parsed provider stream event before Pi normalization.\n\t * Event data is adapter-owned and must be treated as read-only.\n\t * Adapter support is explicit; unsupported adapters do not invoke it.\n\t */\n\tonProviderStreamEvent?: (data: unknown, model: Model<Api>) => void | Promise<void>;\n\ttemperature?: number;\n\t/**\n\t * Arbitrary sampling parameters merged into the request body as-is, after the named request\n\t * fields, so keys here override them. Lets custom OpenAI-compatible servers (llama.cpp, vLLM,\n\t * SGLang, ...) receive parameters pi does not model, e.g. `top_p`, `top_k`, `min_p`,\n\t * `repetition_penalty`. Merged over `Model.samplingParams` per key. Only applied by\n\t * OpenAI-compatible adapters (completions, responses, Azure responses); other APIs ignore it.\n\t */\n\tsamplingParams?: SamplingParams;\n\tmaxTokens?: number;\n\t/**\n\t * Preferred transport for providers that support multiple transports.\n\t * Providers that do not support this option ignore it.\n\t */\n\ttransport?: Transport;\n\t/**\n\t * Prompt cache retention preference. Providers map this to their supported values.\n\t * Default: \"short\".\n\t */\n\tcacheRetention?: CacheRetention;\n\t/**\n\t * Optional session identifier for providers that support session-based caching.\n\t * Providers can use this to enable prompt caching, request routing, or other\n\t * session-aware features. Ignored by providers that don't support it.\n\t */\n\tsessionId?: string;\n\t/**\n\t * WebSocket connect timeout in milliseconds for providers that support\n\t * WebSocket transports. This covers the connection/open handshake only;\n\t * HTTP/SDK idleness uses `timeoutMs`, while gaps between decoded provider\n\t * stream events use `streamDeadlineMs`.\n\t */\n\twebsocketConnectTimeoutMs?: number;\n\t/**\n\t * Maximum idle gap in milliseconds between two provider stream events.\n\t *\n\t * Enforced below the HTTP layer, so a response body that stalls without ever\n\t * rejecting the adapter's async iterator (for example a decompression failure\n\t * that destroys the stream silently, #2553) still settles the attempt as a\n\t * retryable transport error instead of hanging forever. The timer restarts on\n\t * every event, so it never caps total stream duration.\n\t *\n\t * Defaults to 300000 ms. `0` (or any non-positive value) disables it.\n\t */\n\tstreamDeadlineMs?: number;\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t * For example, Anthropic uses `user_id` for abuse tracking and rate limiting.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderStreamOptions = StreamOptions & Record<string, unknown>;\n\nexport interface DeferredFetchOptions extends ProviderRequestOptions<Model<Api>> {\n\t/**\n\t * Maximum provider long-poll duration in milliseconds.\n\t * Defaults to 0, which performs one status check.\n\t */\n\twait?: number;\n}\n\n/** Request options for best-effort deferred-response cancellation. */\nexport type DeferredCancelOptions = ProviderRequestOptions<Model<Api>>;\n\n/**\n * Maps known APIs to their full provider-specific stream option types.\n * Type-only imports from API implementation modules are erased at emit, so\n * this is tree-shake safe.\n */\nexport interface ApiOptionsMap {\n\t\"anthropic-messages\": AnthropicOptions;\n\t\"openai-completions\": OpenAICompletionsOptions;\n\t\"openai-responses\": OpenAIResponsesOptions;\n\t\"openai-codex-responses\": OpenAICodexResponsesOptions;\n\t\"azure-openai-responses\": AzureOpenAIResponsesOptions;\n\t\"google-generative-ai\": GoogleOptions;\n\t\"google-vertex\": GoogleVertexOptions;\n\t\"mistral-conversations\": MistralOptions;\n\t\"bedrock-converse-stream\": BedrockOptions;\n\t\"pi-messages\": PiMessagesOptions;\n}\n\n/**\n * Full stream options for an API. Known APIs resolve to their concrete option\n * type; custom API strings fall back to the generic shape.\n */\nexport type ApiStreamOptions<TApi extends Api> = TApi extends keyof ApiOptionsMap\n\t? ApiOptionsMap[TApi]\n\t: StreamOptions & Record<string, unknown>;\n\n/**\n * The uniform stream contract of an API implementation module: every module\n * under `src/api/` exports `stream` and `streamSimple`; capable modules may also\n * export deferred-response methods. Lazy wrappers (`lazyApi()`) and provider\n * factories pass these around as values. This is the untyped dispatch shape;\n * per-API option typing lives on the implementation modules themselves and on\n * `Provider.stream()` via `ApiStreamOptions`.\n */\nexport interface ProviderStreams {\n\tstream(model: Model<Api>, context: TranscriptContext, options?: StreamOptions): AssistantMessageEventStream;\n\tstreamSimple(\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t): AssistantMessageEventStream;\n\tfetchDeferred?(\n\t\tmodel: Model<Api>,\n\t\thandle: DeferredHandle,\n\t\toptions?: DeferredFetchOptions,\n\t): AssistantMessageEventStream;\n\tcancelDeferred?(model: Model<Api>, handle: DeferredHandle, options?: DeferredCancelOptions): Promise<void>;\n}\n\n/**\n * The uniform contract of an image-generation API implementation module:\n * every image API module under `src/api/` exports exactly `generateImages`,\n * so the module itself satisfies this interface. Lazy wrappers and\n * `createProvider({ images })` pass these around as values.\n */\nexport interface ProviderImages {\n\tgenerateImages(\n\t\tmodel: ImageModel<ImageApi>,\n\t\tcontext: ImagesContext,\n\t\toptions?: ImagesOptions,\n\t): Promise<AssistantImages>;\n}\n\n/** The uniform contract implemented by classifier API modules. */\nexport interface ProviderClassifier {\n\tclassify(\n\t\tmodel: ClassifierModel<ClassifierApi>,\n\t\tcontext: ClassifierContext,\n\t\toptions?: ClassifierOptions,\n\t): Promise<ClassifierResult>;\n}\n\nexport interface ClassifierOptions extends ProviderRequestOptions<ClassifierModel<ClassifierApi>> {\n\t/**\n\t * Divides the answer logits by this value before they are normalized into probabilities.\n\t * Values above 1 soften the distribution; values below 1 sharpen it. Must be positive.\n\t * APIs that cannot apply it ignore it.\n\t */\n\ttemperature?: number;\n}\n\nexport interface ImagesOptions extends ProviderRequestOptions<ImageModel<ImageApi>> {\n\t/**\n\t * Optional metadata to include in API requests.\n\t * Providers extract the fields they understand and ignore the rest.\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\nexport type ProviderImagesOptions = ImagesOptions & Record<string, unknown>;\n\n/**\n * Maps known image APIs to their request option types, like `ApiOptionsMap`\n * does for chat APIs.\n */\nexport interface ImageApiOptionsMap {\n\t\"openrouter-images\": ImagesOptions;\n\t\"openai-images\": OpenAIImagesOptions;\n}\n\n/**\n * Request options for an image API. Known APIs resolve to their concrete option\n * type; custom API strings fall back to the generic shape.\n */\nexport type ImageApiOptions<TApi extends ImageApi> = TApi extends keyof ImageApiOptionsMap\n\t? ImageApiOptionsMap[TApi]\n\t: ProviderImagesOptions;\n\n// Unified options with reasoning passed to streamSimple() and completeSimple()\nexport interface SimpleStreamOptions extends StreamOptions {\n\t/** Provider-neutral tool selection for simple requests. When omitted, adapters use provider-specific behavior. */\n\ttoolChoice?: ToolChoice;\n\treasoning?: ThinkingLevel;\n\t/** Ask a capable provider to return a durable handle and continue the request asynchronously. */\n\tdeferred?: boolean | { window?: \"15m\" | \"1h\" | \"24h\" };\n\t/** Custom token budgets for thinking levels (token-based providers only) */\n\tthinkingBudgets?: ThinkingBudgets;\n}\n\n// Generic StreamFunction with typed options.\n//\n// Contract:\n// - Receives a normalized transcript: the system prompt and tools live in the\n// leading system message, never on the context itself.\n// - Must return an AssistantMessageEventStream.\n// - Direct streamSimple() calls may throw synchronously when request auth is\n// missing. Once a stream is returned, request/model/runtime failures should\n// be encoded in the stream, not thrown.\n// - Error termination must produce an AssistantMessage with stopReason\n// \"error\" or \"aborted\" and errorMessage, emitted via the stream protocol.\nexport type StreamFunction<TApi extends Api = Api, TOptions extends StreamOptions = StreamOptions> = (\n\tmodel: Model<TApi>,\n\tcontext: TranscriptContext,\n\toptions?: TOptions,\n) => AssistantMessageEventStream;\n\nexport type ImagesFunction<TOptions extends ImagesOptions = ImagesOptions> = (\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions?: TOptions,\n) => Promise<AssistantImages>;\n\nexport type ClassifierFunction<TOptions extends ClassifierOptions = ClassifierOptions> = (\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions?: TOptions,\n) => Promise<ClassifierResult>;\n\nexport interface TextSignatureV1 {\n\tv: 1;\n\tid: string;\n\tphase?: \"commentary\" | \"final_answer\";\n}\n\nexport interface TextContent {\n\ttype: \"text\";\n\ttext: string;\n\ttextSignature?: string; // e.g., for OpenAI responses, message metadata (legacy id string or TextSignatureV1 JSON)\n}\n\nexport interface ThinkingContent {\n\ttype: \"thinking\";\n\tthinking: string;\n\tthinkingSignature?: string; // Provider-specific opaque or serialized reasoning replay data\n\t/** When true, the thinking content was redacted by safety filters. The opaque\n\t * encrypted payload is stored in `thinkingSignature` so it can be passed back\n\t * to the API for multi-turn continuity. */\n\tredacted?: boolean;\n}\n\n/**\n * Boundary marker emitted by Anthropic server-side fallback, where one model's output gives way\n * to the next after a classifier refusal.\n *\n * This is public content rather than a stream-only event because it must survive the round trip:\n * \"Keep it exactly where it appeared. The API uses its position to validate the thinking blocks\n * around it, so a request that echoes thinking blocks from both sides of the boundary is rejected\n * if the block is omitted or moved.\"\n * https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback\n */\nexport interface FallbackContent {\n\ttype: \"fallback\";\n\t/** The model that declined. Echoes the model string sent when the declining hop is the request's own model. */\n\tfromModel: string;\n\t/** Resolved id of the model that continues. Always present. */\n\ttoModel: string;\n}\n\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string; // base64 encoded image data\n\tmimeType: string; // e.g., \"image/jpeg\", \"image/png\"\n}\n\n/**\n * A document sent as model input, currently PDF only.\n *\n * Anthropic documents PDF as a platform capability — \"All active models support PDF processing\" —\n * routed through the same vision path as images, so it is not a per-model modality. A model\n * advertises it through `Model.input` containing `\"pdf\"`, which generated metadata sets only for\n * the runtimes that can actually serialize a document block. Providers that cannot are sent a\n * visible placeholder instead, exactly as they are for images they cannot accept.\n * https://platform.claude.com/docs/en/build-with-claude/pdf-support\n */\nexport interface DocumentContent {\n\ttype: \"document\";\n\t/** Base64-encoded document bytes. Amazon Bedrock takes raw bytes and decodes this itself. */\n\tdata: string;\n\t/**\n\t * The only media type either serializer implements. It is a literal rather than `string`\n\t * because both paths hardcode PDF — the Anthropic block emits `BetaBase64PDFSource`, whose\n\t * `media_type` is itself a fixed literal, and Bedrock emits `DocumentFormat.PDF` — so a wider\n\t * type would let a caller label arbitrary bytes as a PDF. Widening this union later is\n\t * non-breaking; narrowing it after release would not be. Note that adding a format is not a\n\t * media-type swap on the Anthropic side: plain text needs a structurally different source\n\t * variant (`BetaPlainTextSource`, `type: \"text\"`), and Bedrock's `doc`/`docx`/`xls`/`xlsx`/\n\t * `csv`/`html`/`md` formats have no Anthropic source variant at all.\n\t */\n\tmimeType: \"application/pdf\";\n\t/**\n\t * Optional caller-supplied label. Amazon Bedrock requires a name and warns that it \"is\n\t * vulnerable to prompt injections\", so the Bedrock path sanitizes this to the characters AWS\n\t * permits and falls back to a neutral generated name.\n\t */\n\tname?: string;\n}\n\nexport interface ToolCall {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: JsonObject;\n\tthoughtSignature?: string; // Google-specific: opaque signature for reusing thought context\n\t/** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */\n\tnamespace?: string;\n\targumentsError?: string;\n}\n\nexport interface Usage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\t/** Subset of `cacheWrite` written with 1h retention. Anthropic and Bedrock report this split. */\n\tcacheWrite1h?: number;\n\t/**\n\t * Reasoning/thinking tokens, when the provider reports them. This is a subset of\n\t * `output`: `output` already includes these tokens. Set to a number (possibly 0) by\n\t * providers that expose a reasoning breakdown; left undefined by providers that don't.\n\t */\n\treasoning?: number;\n\ttotalTokens: number;\n\tcost: {\n\t\t/** Catalog-derived input cost. */\n\t\tinput: number;\n\t\t/** Catalog-derived output cost. */\n\t\toutput: number;\n\t\t/** Catalog-derived cache-read cost. */\n\t\tcacheRead: number;\n\t\t/** Catalog-derived cache-write cost. */\n\t\tcacheWrite: number;\n\t\t/** Best available total: provider-reported billed cost when supported, otherwise the catalog estimate. */\n\t\ttotal: number;\n\t\t/** True when `total` is the billed cost reported by the provider. False when it is a catalog estimate; absent also means false. */\n\t\ttotalFromProvider?: boolean;\n\t};\n}\n\nexport type StopReason = \"pending\" | \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\" | \"deferred\";\n\nexport type JsonValue = null | boolean | number | string | readonly JsonValue[] | JsonObject;\nexport type JsonObject = { [key: string]: JsonValue };\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype IsExactlyJsonValue<T> = [T] extends [JsonValue] ? ([JsonValue] extends [T] ? true : false) : false;\ntype IsJsonProperty<T> =\n\tIsAny<T> extends true\n\t\t? false\n\t\t: unknown extends T\n\t\t\t? false\n\t\t\t: [Exclude<T, undefined>] extends [never]\n\t\t\t\t? true\n\t\t\t\t: IsJsonCompatible<Exclude<T, undefined>>;\ntype InvalidJsonKeys<T extends object> = {\n\t[TKey in keyof T]-?: TKey extends string | number ? (IsJsonProperty<T[TKey]> extends true ? never : TKey) : TKey;\n}[keyof T];\ntype IsJsonCompatible<T> =\n\tIsAny<T> extends true\n\t\t? false\n\t\t: unknown extends T\n\t\t\t? false\n\t\t\t: IsExactlyJsonValue<T> extends true\n\t\t\t\t? true\n\t\t\t\t: T extends null | boolean | number | string\n\t\t\t\t\t? true\n\t\t\t\t\t: T extends undefined\n\t\t\t\t\t\t? false\n\t\t\t\t\t\t: T extends readonly (infer TItem)[]\n\t\t\t\t\t\t\t? IsJsonCompatible<TItem>\n\t\t\t\t\t\t\t: T extends (...args: never[]) => unknown\n\t\t\t\t\t\t\t\t? false\n\t\t\t\t\t\t\t\t: T extends object\n\t\t\t\t\t\t\t\t\t? [InvalidJsonKeys<T>] extends [never]\n\t\t\t\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t\t\t\t: false\n\t\t\t\t\t\t\t\t\t: false;\n\n/** The JSON representation of a typed in-memory value. Optional object properties remain optional. */\nexport type JsonRepresentation<T> =\n\tIsAny<T> extends true\n\t\t? JsonValue\n\t\t: unknown extends T\n\t\t\t? JsonValue\n\t\t\t: [T] extends [JsonValue]\n\t\t\t\t? T\n\t\t\t\t: T extends readonly unknown[]\n\t\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t\t: T extends object\n\t\t\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<Exclude<T[TKey], undefined>> }\n\t\t\t\t\t\t: never;\n\nexport interface DeferredHandle {\n\tprovider: string;\n\tmodelId: string;\n\tapi: string;\n\t/** Provider token, such as a response id or batch id plus row id. */\n\tid: string;\n\texpiresAt?: number;\n\tpollAfterMs?: number;\n\t/** Provider conversion data required to reconstruct the final assistant message. */\n\tdata?: JsonValue;\n}\n\n/**\n * System instructions and tool declarations at one point in the transcript.\n *\n * The leading system message is the system prompt. Later system messages change it:\n * `content` adds instructions from that point on, `sections` replace or remove named\n * prompt sections, and `toolsAdded`/`toolsRemoved` change the tool set. Replaying\n * every system message in order yields the current prompt and tools. Providers that\n * accept system messages mid-conversation send each one in place; other providers\n * rebuild the leading system message from the replayed state.\n */\nexport interface SystemMessage {\n\trole: \"system\";\n\t/** Instruction text. On the leading message this is the base prompt; later, additional instructions. */\n\tcontent: string | TextContent[];\n\t/**\n\t * Named, ordered prompt sections rendered verbatim after `content`. The leading message\n\t * declares them; later messages replace sections by name, and `null` removes one. Keep\n\t * each section self-delimiting (a tag, a heading) so the model can relate an update to\n\t * the original. Avoid integer-like names; JSON objects reorder those.\n\t */\n\tsections?: Record<string, string | null>;\n\t/** Complete definitions of tools that become available at this point. */\n\ttoolsAdded?: Tool[];\n\t/** Tools that stop being available at this point. */\n\ttoolsRemoved?: ToolReference[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface UserMessage {\n\trole: \"user\";\n\tcontent: string | (TextContent | ImageContent | DocumentContent)[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface AssistantMessage {\n\trole: \"assistant\";\n\tcontent: (TextContent | ThinkingContent | ToolCall | FallbackContent)[];\n\tapi: Api;\n\tprovider: ProviderId;\n\tmodel: string;\n\tresponseModel?: string; // Concrete model reported by the provider, when reported. May equal the requested `model`\n\tresponseId?: string; // Provider-specific response/message identifier when the upstream API exposes one\n\t/** Exact provider-native effort level used for this response. Absent for legacy or unmanaged responses. */\n\tproviderThinkingLevel?: string;\n\tdiagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.\n\tusage: Usage;\n\tstopReason: StopReason;\n\tdeferred?: DeferredHandle;\n\terrorMessage?: string;\n\t/** Server-requested retry delay in ms (`Retry-After` or a body `retry_after`), when the provider sent one. */\n\tretryAfterMs?: number;\n\trawStopReason?: string;\n\t/**\n\t * Provider indication of whether the model explicitly ended its turn.\n\t * Preserved for debugging and does not currently affect agent control flow.\n\t */\n\tendTurn?: boolean;\n\ttimestamp: number; // Unix timestamp in milliseconds\n\tdurationMs?: number;\n}\n\n/** A tool call made by another tool, such as a codemode script. */\nexport interface NestedToolCallRecord {\n\tid: string;\n\tname: string;\n\t/** Omitted when over the size limits. */\n\targuments?: JsonObject;\n\t/** UTF-8 JSON size when arguments are omitted. */\n\targumentsBytes?: number;\n\tstatus: \"ok\" | \"error\" | \"unfinished\";\n\tdurationMs?: number;\n\terror?: string;\n}\n\n/** Bounded nested-call record. Results are not recorded. */\nexport interface NestedToolCalls {\n\tcalls: NestedToolCallRecord[];\n\tcomplete: boolean;\n}\n\nexport type ToolResultMessage<TDetails = JsonValue> =\n\tIsJsonCompatible<TDetails> extends true\n\t\t? {\n\t\t\t\trole: \"toolResult\";\n\t\t\t\ttoolCallId: string;\n\t\t\t\ttoolName: string;\n\t\t\t\tcontent: (TextContent | ImageContent)[]; // Supports text and images\n\t\t\t\tdetails?: JsonRepresentation<TDetails>;\n\t\t\t\t/** Usage from the tool execution itself, if available. Not part of main LLM context accounting. */\n\t\t\t\tusage?: Usage;\n\t\t\t\t/** Nested calls retained in the session, not sent to the model. */\n\t\t\t\tnestedCalls?: NestedToolCalls;\n\t\t\t\tisError: boolean;\n\t\t\t\ttimestamp: number; // Unix timestamp in milliseconds\n\t\t\t\tdurationMs?: number;\n\t\t\t}\n\t\t: never;\n\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;\n\nexport type ImagesInputContent = TextContent | ImageContent;\nexport type ImagesOutputContent = TextContent | ImageContent;\n\nexport interface ImagesContext {\n\tinput: ImagesInputContent[];\n}\n\nexport type ImagesStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface AssistantImages {\n\tapi: ImageApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\toutput: ImagesOutputContent[];\n\tresponseId?: string;\n\tusage?: Usage;\n\tstopReason: ImagesStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface ClassifierChoiceQuestion {\n\ttype: \"choice\";\n\tinstructions: string;\n\tcriteria: Record<string, string>;\n}\n\nexport interface ClassifierScoreQuestion {\n\ttype: \"score\";\n\tinstructions: string;\n\tcriteria: string[];\n}\n\nexport interface ClassifierBoolQuestion {\n\ttype: \"bool\";\n\tinstructions: string;\n\tcriteria: { true: string; false: string };\n}\n\nexport type ClassifierQuestion = ClassifierChoiceQuestion | ClassifierScoreQuestion | ClassifierBoolQuestion;\n\nexport interface ClassifierContext {\n\tstate: JsonObject;\n\t/**\n\t * Images judged together with `state`. Only models whose `input` includes `\"image\"` accept them;\n\t * other models return an error result.\n\t */\n\timages?: ImageContent[];\n\tquestions: Record<string, ClassifierQuestion>;\n}\n\nexport interface ClassifierChoiceAnswer {\n\ttype: \"choice\";\n\tchoice: string;\n\tprobabilities: Record<string, number>;\n\tconfidence: number;\n}\n\nexport interface ClassifierScoreAnswer {\n\ttype: \"score\";\n\tscore: number;\n\tconfidence: number;\n}\n\nexport interface ClassifierBoolAnswer {\n\ttype: \"bool\";\n\tprobability: number;\n}\n\nexport type ClassifierAnswer = ClassifierChoiceAnswer | ClassifierScoreAnswer | ClassifierBoolAnswer;\nexport type ClassifierStopReason = \"stop\" | \"error\" | \"aborted\";\n\nexport interface ClassifierResult {\n\tapi: ClassifierApi;\n\tprovider: ProviderId;\n\tmodel: string;\n\tanswers: Record<string, ClassifierAnswer>;\n\t/** Token usage and cost at the model's catalog price, when reported. */\n\tusage?: Usage;\n\tstopReason: ClassifierStopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nimport type { TSchema } from \"typebox\";\n\n/** OpenAI grammar variants for constrained sampling. */\nexport type GrammarFormat = \"openai_lark\" | \"openai_regex\";\n\nexport type GrammarVariants = Partial<Record<GrammarFormat, string>>;\n\n/**\n * Optional provider-side constrained sampling configs for a tool.\n *\n * The `json_schema` value roughly maps to the concept of `strict` in APIs which is\n * implemented as json-schema constrained sampling by APIs. Grammar variants let\n * callers provide provider-specific encodings of the same intended language.\n */\nexport type ConstrainedSamplingConfig =\n\t| {\n\t\t\ttype: \"json_schema\";\n\t\t\tstrict: \"prefer\" | \"require\";\n\t }\n\t| {\n\t\t\ttype: \"grammar\";\n\t\t\tvariants: GrammarVariants;\n\t };\n\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n}\n\nexport interface ToolReference {\n\tname: string;\n}\n\n/**\n * Request input accepted by the public stream entry points (`Models.stream()`,\n * `streamSimple()`, ...). `systemPrompt` and `tools` are shorthand for a leading\n * system message; `normalizeContext()` folds them into one before the request\n * reaches a provider.\n */\nexport interface Context {\n\tsystemPrompt?: string;\n\tmessages: Message[];\n\ttools?: Tool[];\n}\n\ndeclare const transcriptContextBrand: unique symbol;\n\n/**\n * Normalized request context passed to providers and API implementations. The\n * prompt and tool declarations are carried by the transcript's system messages.\n * Only `normalizeContext()` produces this type, so a raw `Context` cannot reach\n * provider code by accident.\n */\nexport type TranscriptContext = {\n\tmessages: Message[];\n\treadonly [transcriptContextBrand]: true;\n};\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Successful streams emit `start` before partial updates and terminate with\n * `done`. A stream may terminate directly with `error` when request setup fails\n * before generation starts; after `start`, failures also terminate with `error`.\n * Direct `streamSimple()` calls throw synchronously when request auth is missing.\n * Updates and `done` must never appear before `start`.\n *\n * Tool-call arguments at `toolcall_start` are provider-specific;\n * `toolcall_delta` carries subsequent JSON updates.\n */\nexport type AssistantMessageEvent =\n\t| { type: \"start\"; partial: AssistantMessage }\n\t| { type: \"text_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"text_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"thinking_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"thinking_end\"; contentIndex: number; content: string; partial: AssistantMessage }\n\t| { type: \"toolcall_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string; partial: AssistantMessage }\n\t| { type: \"toolcall_end\"; contentIndex: number; toolCall: ToolCall; partial: AssistantMessage }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\" | \"deferred\">;\n\t\t\tmessage: AssistantMessage;\n\t }\n\t| { type: \"error\"; reason: Extract<StopReason, \"aborted\" | \"error\">; error: AssistantMessage };\n\n/** Service tiers a model can advertise beyond standard processing. */\nexport type ModelServiceTierId = \"priority\" | \"ultrafast\";\n\n/**\n * A service tier a model advertises, following Codex's `ModelInfo.service_tiers`, with the provider's\n * published per-million-token rates for that tier.\n *\n * Adapters send a tier only when the model advertises it. `flex` is an API request option and needs\n * no advertisement.\n */\nexport interface ModelServiceTier {\n\tid: ModelServiceTierId;\n\tcost: ModelCost;\n}\n\n/**\n * Explicit routing metadata that marks a model as the fast-inference variant of another model.\n *\n * Presence of this field — never a `-fast` name suffix — is what gives a model fast semantics.\n * A provider, `models.json` custom model, or extension may own an exact `<base>-fast` ID without\n * this metadata, in which case it is an ordinary model and routes exactly as it is declared.\n */\nexport interface ModelFastRoute {\n\t/** Canonical ID of the normal-speed model this variant pairs with, in the same provider. */\n\tbaseModelId: string;\n\t/** Model ID to send upstream. OpenAI-style routing keeps the base ID; a provider with real fast siblings sends its own ID. */\n\tupstreamModelId: string;\n\t/** Service tier to send with the request. Set only for providers that route fast traffic through an OpenAI-style tier. */\n\tserviceTier?: ModelServiceTierId;\n\t/** Anthropic inference speed to send with the request. Set only for Claude models that support fast mode. */\n\tspeed?: \"fast\";\n}\n\n/** Fields shared by every catalog entry, regardless of what you can do with it. */\nexport interface BaseModel<TApi extends string> {\n\tid: string;\n\tname: string;\n\tapi: TApi;\n\tprovider: ProviderId;\n\tbaseUrl: string;\n\tinput: ModelInputModality[];\n\t/** Provider input limits and cache-safe preprocessing metadata. */\n\tinputLimits?: ModelInputLimits;\n\tcost: ModelCost;\n\theaders?: Record<string, string>;\n}\n\n/** Chat model: usable with `stream()` and friends. */\nexport interface Model<TApi extends Api> extends BaseModel<TApi> {\n\t/**\n\t * Optional: chat is the default model type, so models without `type` are chat\n\t * models. Narrow mixed model lists with `isModelType()` instead of comparing\n\t * `type` directly.\n\t */\n\ttype?: \"chat\";\n\treasoning: boolean;\n\t/**\n\t * Maps pi thinking levels to provider/model-specific values.\n\t * Missing keys use provider defaults. null marks a level as unsupported.\n\t */\n\tthinkingLevelMap?: ThinkingLevelMap;\n\t/** Prompt cache lifetimes per retention tier. Unset when the provider's cache behavior is unknown. */\n\tpromptCache?: ModelPromptCache;\n\tcontextWindow: number;\n\tmaxTokens: number;\n\t/** Default sampling parameters for this model. See {@link StreamOptions.samplingParams}; per-request keys override these. */\n\tsamplingParams?: SamplingParams;\n\t/** Sampling parameter overrides selected by the effective pi thinking level. */\n\tsamplingParamsByThinkingLevel?: SamplingParamsByThinkingLevel;\n\t/**\n\t * Marks this model as the fast-inference variant of {@link ModelFastRoute.baseModelId} and carries the\n\t * upstream routing it needs. Absent on every normal model.\n\t */\n\tfastRoute?: ModelFastRoute;\n\t/**\n\t * Service tiers this model advertises. When set, the Codex adapter sends only advertised tiers.\n\t * When unset, the model carries no tier metadata and only Ultrafast is withheld.\n\t */\n\tserviceTiers?: ModelServiceTier[];\n\t/** Compatibility overrides for OpenAI-compatible APIs. If not set, auto-detected from baseUrl. */\n\tcompat?: TApi extends \"openai-completions\"\n\t\t? OpenAICompletionsCompat\n\t\t: TApi extends \"openai-responses\" | \"azure-openai-responses\" | \"openai-codex-responses\"\n\t\t\t? OpenAIResponsesCompat\n\t\t\t: TApi extends \"anthropic-messages\"\n\t\t\t\t? AnthropicMessagesCompat\n\t\t\t\t: TApi extends \"bedrock-converse-stream\"\n\t\t\t\t\t? BedrockCompat\n\t\t\t\t\t: TApi extends \"mistral-conversations\"\n\t\t\t\t\t\t? MistralConversationsCompat\n\t\t\t\t\t\t: never;\n}\n\n/** Image-generation model: usable with `generateImages()` only. */\nexport interface ImageModel<TApi extends ImageApi> extends BaseModel<TApi> {\n\ttype: \"image\";\n\t/** Output modalities. Always includes `\"image\"`; `\"text\"` means the model can also return text blocks. */\n\toutput: (\"text\" | \"image\")[];\n}\n\n/** Structured classifier model: usable with `classify()` only. */\nexport interface ClassifierModel<TApi extends ClassifierApi> extends BaseModel<TApi> {\n\ttype: \"classifier\";\n\tcontextWindow: number;\n\t/** Compatibility overrides for System One APIs. If not set, auto-detected from provider, baseUrl, and id. */\n\tcompat?: TApi extends \"typesafe-system-one\" | \"cloudflare-workers-ai-system-one\" ? SystemOneCompat : never;\n}\n\n/** Dedicated compaction model, excluded from chat model selection. */\nexport interface CompactorModel<TApi extends CompactorApi = CompactorApi> extends BaseModel<TApi> {\n\ttype: \"compactor\";\n}\n\n/** Model shape for each model type. */\nexport interface ModelTypeMap {\n\tchat: Model<Api>;\n\timage: ImageModel<ImageApi>;\n\tclassifier: ClassifierModel<ClassifierApi>;\n\tcompactor: CompactorModel;\n}\n\n/** What a catalog entry is for. Decides which `Models` operation accepts it. */\nexport type ModelType = keyof ModelTypeMap;\n\n/** Anything a provider can list. Narrow with `isModelType()`. */\nexport type AnyModel = ModelTypeMap[ModelType];\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,OAAO,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAWD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAgB9E;AAiED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAO1F;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD"}
|
package/dist/utils/error-body.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
// composes into its display string. The `messageCarriesBody` flag captures the
|
|
13
13
|
// Anthropic / `@google/genai` happy path where the SDK already folded the body
|
|
14
14
|
// into the message, so providers can preserve it without double-printing.
|
|
15
|
+
import { ownedSlice } from "./text.js";
|
|
15
16
|
export const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;
|
|
16
17
|
export function normalizeProviderError(error) {
|
|
17
18
|
if (!(error instanceof Error)) {
|
|
@@ -119,7 +120,7 @@ export function formatProviderError(norm, prefix) {
|
|
|
119
120
|
export function truncateErrorText(text, maxChars) {
|
|
120
121
|
if (text.length <= maxChars)
|
|
121
122
|
return text;
|
|
122
|
-
return `${text
|
|
123
|
+
return `${ownedSlice(text, 0, maxChars)}... [truncated ${text.length - maxChars} chars]`;
|
|
123
124
|
}
|
|
124
125
|
export function safeJsonStringify(value) {
|
|
125
126
|
try {
|