@jecruz/merc-ai 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1453 -0
- package/dist/api-registry.d.ts +20 -0
- package/dist/api-registry.d.ts.map +1 -0
- package/dist/api-registry.js +44 -0
- package/dist/api-registry.js.map +1 -0
- package/dist/bedrock-provider.d.ts +5 -0
- package/dist/bedrock-provider.d.ts.map +1 -0
- package/dist/bedrock-provider.js +6 -0
- package/dist/bedrock-provider.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +116 -0
- package/dist/cli.js.map +1 -0
- package/dist/env-api-keys.d.ts +18 -0
- package/dist/env-api-keys.d.ts.map +1 -0
- package/dist/env-api-keys.js +134 -0
- package/dist/env-api-keys.js.map +1 -0
- package/dist/image-models.d.ts +10 -0
- package/dist/image-models.d.ts.map +1 -0
- package/dist/image-models.generated.d.ts +530 -0
- package/dist/image-models.generated.d.ts.map +1 -0
- package/dist/image-models.generated.js +532 -0
- package/dist/image-models.generated.js.map +1 -0
- package/dist/image-models.js +23 -0
- package/dist/image-models.js.map +1 -0
- package/dist/images-api-registry.d.ts +14 -0
- package/dist/images-api-registry.d.ts.map +1 -0
- package/dist/images-api-registry.js +22 -0
- package/dist/images-api-registry.js.map +1 -0
- package/dist/images.d.ts +5 -0
- package/dist/images.d.ts.map +1 -0
- package/dist/images.js +18 -0
- package/dist/images.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +22 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.generated.d.ts +20591 -0
- package/dist/models.generated.d.ts.map +1 -0
- package/dist/models.generated.js +19123 -0
- package/dist/models.generated.js.map +1 -0
- package/dist/models.js +80 -0
- package/dist/models.js.map +1 -0
- package/dist/oauth.d.ts +2 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +2 -0
- package/dist/oauth.js.map +1 -0
- package/dist/providers/amazon-bedrock.d.ts +38 -0
- package/dist/providers/amazon-bedrock.d.ts.map +1 -0
- package/dist/providers/amazon-bedrock.js +813 -0
- package/dist/providers/amazon-bedrock.js.map +1 -0
- package/dist/providers/anthropic.d.ts +54 -0
- package/dist/providers/anthropic.d.ts.map +1 -0
- package/dist/providers/anthropic.js +1035 -0
- package/dist/providers/anthropic.js.map +1 -0
- package/dist/providers/azure-openai-responses.d.ts +15 -0
- package/dist/providers/azure-openai-responses.d.ts.map +1 -0
- package/dist/providers/azure-openai-responses.js +219 -0
- package/dist/providers/azure-openai-responses.js.map +1 -0
- package/dist/providers/claude-cli.d.ts +4 -0
- package/dist/providers/claude-cli.d.ts.map +1 -0
- package/dist/providers/claude-cli.js +224 -0
- package/dist/providers/claude-cli.js.map +1 -0
- package/dist/providers/cloudflare.d.ts +13 -0
- package/dist/providers/cloudflare.d.ts.map +1 -0
- package/dist/providers/cloudflare.js +26 -0
- package/dist/providers/cloudflare.js.map +1 -0
- package/dist/providers/faux.d.ts +56 -0
- package/dist/providers/faux.d.ts.map +1 -0
- package/dist/providers/faux.js +377 -0
- package/dist/providers/faux.js.map +1 -0
- package/dist/providers/github-copilot-headers.d.ts +8 -0
- package/dist/providers/github-copilot-headers.d.ts.map +1 -0
- package/dist/providers/github-copilot-headers.js +29 -0
- package/dist/providers/github-copilot-headers.js.map +1 -0
- package/dist/providers/google-shared.d.ts +70 -0
- package/dist/providers/google-shared.d.ts.map +1 -0
- package/dist/providers/google-shared.js +329 -0
- package/dist/providers/google-shared.js.map +1 -0
- package/dist/providers/google-vertex.d.ts +15 -0
- package/dist/providers/google-vertex.d.ts.map +1 -0
- package/dist/providers/google-vertex.js +446 -0
- package/dist/providers/google-vertex.js.map +1 -0
- package/dist/providers/google.d.ts +13 -0
- package/dist/providers/google.d.ts.map +1 -0
- package/dist/providers/google.js +437 -0
- package/dist/providers/google.js.map +1 -0
- package/dist/providers/mistral.d.ts +25 -0
- package/dist/providers/mistral.d.ts.map +1 -0
- package/dist/providers/mistral.js +538 -0
- package/dist/providers/mistral.js.map +1 -0
- package/dist/providers/openai-codex-responses.d.ts +33 -0
- package/dist/providers/openai-codex-responses.d.ts.map +1 -0
- package/dist/providers/openai-codex-responses.js +1190 -0
- package/dist/providers/openai-codex-responses.js.map +1 -0
- package/dist/providers/openai-completions.d.ts +19 -0
- package/dist/providers/openai-completions.d.ts.map +1 -0
- package/dist/providers/openai-completions.js +1126 -0
- package/dist/providers/openai-completions.js.map +1 -0
- package/dist/providers/openai-responses-shared.d.ts +20 -0
- package/dist/providers/openai-responses-shared.d.ts.map +1 -0
- package/dist/providers/openai-responses-shared.js +543 -0
- package/dist/providers/openai-responses-shared.js.map +1 -0
- package/dist/providers/openai-responses.d.ts +14 -0
- package/dist/providers/openai-responses.d.ts.map +1 -0
- package/dist/providers/openai-responses.js +253 -0
- package/dist/providers/openai-responses.js.map +1 -0
- package/dist/providers/openrouter-images.d.ts +3 -0
- package/dist/providers/openrouter-images.d.ts.map +1 -0
- package/dist/providers/openrouter-images.js +139 -0
- package/dist/providers/openrouter-images.js.map +1 -0
- package/dist/providers/register-builtins.d.ts +37 -0
- package/dist/providers/register-builtins.d.ts.map +1 -0
- package/dist/providers/register-builtins.js +261 -0
- package/dist/providers/register-builtins.js.map +1 -0
- package/dist/providers/register-images-builtins.d.ts +4 -0
- package/dist/providers/register-images-builtins.d.ts.map +1 -0
- package/dist/providers/register-images-builtins.js +48 -0
- package/dist/providers/register-images-builtins.js.map +1 -0
- package/dist/providers/simple-options.d.ts +8 -0
- package/dist/providers/simple-options.d.ts.map +1 -0
- package/dist/providers/simple-options.js +47 -0
- package/dist/providers/simple-options.js.map +1 -0
- package/dist/providers/transform-messages.d.ts +8 -0
- package/dist/providers/transform-messages.d.ts.map +1 -0
- package/dist/providers/transform-messages.js +193 -0
- package/dist/providers/transform-messages.js.map +1 -0
- package/dist/session-resources.d.ts +4 -0
- package/dist/session-resources.d.ts.map +1 -0
- package/dist/session-resources.js +22 -0
- package/dist/session-resources.js.map +1 -0
- package/dist/stream.d.ts +8 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/stream.js +27 -0
- package/dist/stream.js.map +1 -0
- package/dist/types.d.ts +556 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/deferred-tools.d.ts +15 -0
- package/dist/utils/deferred-tools.d.ts.map +1 -0
- package/dist/utils/deferred-tools.js +48 -0
- package/dist/utils/deferred-tools.js.map +1 -0
- package/dist/utils/diagnostics.d.ts +19 -0
- package/dist/utils/diagnostics.d.ts.map +1 -0
- package/dist/utils/diagnostics.js +25 -0
- package/dist/utils/diagnostics.js.map +1 -0
- package/dist/utils/error-body.d.ts +20 -0
- package/dist/utils/error-body.d.ts.map +1 -0
- package/dist/utils/error-body.js +71 -0
- package/dist/utils/error-body.js.map +1 -0
- package/dist/utils/event-stream.d.ts +26 -0
- package/dist/utils/event-stream.d.ts.map +1 -0
- package/dist/utils/event-stream.js +98 -0
- package/dist/utils/event-stream.js.map +1 -0
- package/dist/utils/hash.d.ts +3 -0
- package/dist/utils/hash.d.ts.map +1 -0
- package/dist/utils/hash.js +14 -0
- package/dist/utils/hash.js.map +1 -0
- package/dist/utils/headers.d.ts +2 -0
- package/dist/utils/headers.d.ts.map +1 -0
- package/dist/utils/headers.js +8 -0
- package/dist/utils/headers.js.map +1 -0
- package/dist/utils/json-parse.d.ts +16 -0
- package/dist/utils/json-parse.d.ts.map +1 -0
- package/dist/utils/json-parse.js +113 -0
- package/dist/utils/json-parse.js.map +1 -0
- package/dist/utils/oauth/anthropic.d.ts +25 -0
- package/dist/utils/oauth/anthropic.d.ts.map +1 -0
- package/dist/utils/oauth/anthropic.js +335 -0
- package/dist/utils/oauth/anthropic.js.map +1 -0
- package/dist/utils/oauth/github-copilot.d.ts +30 -0
- package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
- package/dist/utils/oauth/github-copilot.js +351 -0
- package/dist/utils/oauth/github-copilot.js.map +1 -0
- package/dist/utils/oauth/index.d.ts +57 -0
- package/dist/utils/oauth/index.d.ts.map +1 -0
- package/dist/utils/oauth/index.js +121 -0
- package/dist/utils/oauth/index.js.map +1 -0
- package/dist/utils/oauth/oauth-page.d.ts +3 -0
- package/dist/utils/oauth/oauth-page.d.ts.map +1 -0
- package/dist/utils/oauth/oauth-page.js +105 -0
- package/dist/utils/oauth/oauth-page.js.map +1 -0
- package/dist/utils/oauth/openai-codex.d.ts +34 -0
- package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
- package/dist/utils/oauth/openai-codex.js +374 -0
- package/dist/utils/oauth/openai-codex.js.map +1 -0
- package/dist/utils/oauth/pkce.d.ts +13 -0
- package/dist/utils/oauth/pkce.d.ts.map +1 -0
- package/dist/utils/oauth/pkce.js +31 -0
- package/dist/utils/oauth/pkce.js.map +1 -0
- package/dist/utils/oauth/types.d.ts +57 -0
- package/dist/utils/oauth/types.d.ts.map +1 -0
- package/dist/utils/oauth/types.js +2 -0
- package/dist/utils/oauth/types.js.map +1 -0
- package/dist/utils/overflow.d.ts +56 -0
- package/dist/utils/overflow.d.ts.map +1 -0
- package/dist/utils/overflow.js +152 -0
- package/dist/utils/overflow.js.map +1 -0
- package/dist/utils/provider-env.d.ts +9 -0
- package/dist/utils/provider-env.d.ts.map +1 -0
- package/dist/utils/provider-env.js +82 -0
- package/dist/utils/provider-env.js.map +1 -0
- package/dist/utils/sanitize-unicode.d.ts +22 -0
- package/dist/utils/sanitize-unicode.d.ts.map +1 -0
- package/dist/utils/sanitize-unicode.js +26 -0
- package/dist/utils/sanitize-unicode.js.map +1 -0
- package/dist/utils/typebox-helpers.d.ts +17 -0
- package/dist/utils/typebox-helpers.d.ts.map +1 -0
- package/dist/utils/typebox-helpers.js +21 -0
- package/dist/utils/typebox-helpers.js.map +1 -0
- package/dist/utils/validation.d.ts +18 -0
- package/dist/utils/validation.d.ts.map +1 -0
- package/dist/utils/validation.js +281 -0
- package/dist/utils/validation.js.map +1 -0
- package/package.json +113 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AssistantMessageDiagnostic } from \"./utils/diagnostics.js\";\nimport type { AssistantImagesEventStream, AssistantMessageEventStream } from \"./utils/event-stream.js\";\n\nexport type {\n\tAssistantImagesEventStream,\n\tAssistantMessageEventStream,\n} from \"./utils/event-stream.js\";\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| \"claude-cli\";\n\nexport type Api = KnownApi | (string & {});\n\nexport type KnownImagesApi = \"openrouter-images\";\n\nexport type ImagesApi = KnownImagesApi | (string & {});\n\nexport type KnownProvider =\n\t| \"amazon-bedrock\"\n\t| \"anthropic\"\n\t| \"google\"\n\t| \"google-vertex\"\n\t| \"openai\"\n\t| \"azure-openai-responses\"\n\t| \"openai-codex\"\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| \"ant-ling\"\n\t| \"opencode\"\n\t| \"opencode-go\"\n\t| \"kimi-coding\"\n\t| \"cloudflare-workers-ai\"\n\t| \"cloudflare-ai-gateway\"\n\t| \"xiaomi\"\n\t| \"xiaomi-token-plan-cn\"\n\t| \"xiaomi-token-plan-ams\"\n\t| \"xiaomi-token-plan-sgp\";\nexport type Provider = KnownProvider | string;\n\nexport type KnownImagesProvider = \"openrouter\";\n\nexport type ImagesProvider = KnownImagesProvider | string;\n\nexport type ThinkingLevel = \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\nexport type ModelThinkingLevel = \"off\" | ThinkingLevel;\n/** Provider-specific reasoning map from Pi thinking levels to provider values. */\nexport type ThinkingLevelMap = Partial<Record<ModelThinkingLevel, string | null>>;\n\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 CacheRetention = \"none\" | \"short\" | \"long\";\n\nexport type Transport = \"sse\" | \"websocket\" | \"websocket-cached\" | \"auto\";\n\n/** Provider-scoped environment overrides. Explicit values take precedence over process.env. */\nexport type ProviderEnv = Readonly<Record<string, string | undefined>>;\n\nexport interface ProviderResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\nexport interface StreamOptions {\n\ttemperature?: number;\n\tmaxTokens?: number;\n\tsignal?: AbortSignal;\n\tapiKey?: string;\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 * 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: Model<Api>) => unknown | undefined | Promise<unknown | undefined>;\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 custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; can override default headers.\n\t * Not supported by all providers (e.g., AWS Bedrock uses SDK auth).\n\t */\n\theaders?: Record<string, string>;\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\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\t/**\n\t * Provider-scoped environment values. These take precedence over process.env\n\t * for provider configuration and credential discovery.\n\t */\n\tenv?: ProviderEnv;\n}\n\nexport type ProviderStreamOptions = StreamOptions & Record<string, unknown>;\n\nexport interface ImagesOptions {\n\tsignal?: AbortSignal;\n\tapiKey?: string;\n\t/** Provider-scoped environment values used for image-provider configuration. */\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: ImagesModel<ImagesApi>) => 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: ImagesModel<ImagesApi>) => void | Promise<void>;\n\t/**\n\t * Optional custom HTTP headers to include in API requests.\n\t * Merged with provider defaults; can override default headers.\n\t */\n\theaders?: Record<string, string>;\n\t/**\n\t * HTTP request timeout in milliseconds for providers/SDKs that support it.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum retry attempts for providers/SDKs that support client-side retries.\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\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// Unified options with reasoning passed to streamSimple() and completeSimple()\nexport interface SimpleStreamOptions extends StreamOptions {\n\treasoning?: ThinkingLevel;\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// - Must return an AssistantMessageEventStream.\n// - Once invoked, request/model/runtime failures should be encoded in the\n// returned 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: Context,\n\toptions?: TOptions,\n) => AssistantMessageEventStream;\n\nexport type ImagesFunction<TApi extends ImagesApi = ImagesApi, TOptions extends ImagesOptions = ImagesOptions> = (\n\tmodel: ImagesModel<TApi>,\n\tcontext: ImagesContext,\n\toptions?: TOptions,\n) => AssistantImagesEventStream;\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; // e.g., for OpenAI responses, the reasoning item ID\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\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string; // base64 encoded image data\n\tmimeType: string; // e.g., \"image/jpeg\", \"image/png\"\n}\n\nexport interface ToolCall {\n\ttype: \"toolCall\";\n\tid: string;\n\tname: string;\n\targuments: Record<string, any>;\n\tthoughtSignature?: string; // Google-specific: opaque signature for reusing thought context\n}\n\n/** Alternate per-million-token pricing for a higher input-token band. */\nexport interface CostTier {\n\tinputTokensAbove: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n}\n\nexport interface Usage {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\ttotalTokens: number;\n\tcost: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n}\n\nexport type StopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface UserMessage {\n\trole: \"user\";\n\tcontent: string | (TextContent | ImageContent)[];\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface AssistantMessage {\n\trole: \"assistant\";\n\tcontent: (TextContent | ThinkingContent | ImageContent | ToolCall)[];\n\tapi: Api;\n\tprovider: Provider;\n\tmodel: string;\n\tresponseModel?: string; // Concrete `chunk.model` when different from the requested `model` (e.g. OpenRouter `auto` -> `anthropic/...`)\n\tresponseId?: string; // Provider-specific response/message identifier when the upstream API exposes one\n\tdiagnostics?: AssistantMessageDiagnostic[]; // Redacted provider/runtime diagnostics for failures and recoveries.\n\tusage: Usage;\n\tstopReason: StopReason;\n\terrorMessage?: string;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport interface ToolResultMessage<TDetails = any> {\n\trole: \"toolResult\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tcontent: (TextContent | ImageContent)[]; // Supports text and images\n\tdetails?: TDetails;\n\t/**\n\t * Tool names that were activated by this tool result and should be loaded\n\t * lazily at this transcript position when supported by the provider.\n\t */\n\taddedToolNames?: string[];\n\tisError: boolean;\n\ttimestamp: number; // Unix timestamp in milliseconds\n}\n\nexport type Message = 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: ImagesApi;\n\tprovider: ImagesProvider;\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\nimport type { TSchema } from \"typebox\";\n\nexport interface Tool<TParameters extends TSchema = TSchema> {\n\tname: string;\n\tdescription: string;\n\tparameters: TParameters;\n}\n\nexport interface Context {\n\tsystemPrompt?: string;\n\tmessages: Message[];\n\ttools?: Tool[];\n}\n\n/**\n * Event protocol for AssistantMessageEventStream.\n *\n * Streams should emit `start` before partial updates, then terminate with either:\n * - `done` carrying the final successful AssistantMessage, or\n * - `error` carrying the final AssistantMessage with stopReason \"error\" or \"aborted\"\n * and errorMessage.\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: \"image_start\"; contentIndex: number; partial: AssistantMessage }\n\t| { type: \"image_end\"; contentIndex: number; image: ImageContent; 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| { type: \"done\"; reason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">; message: AssistantMessage }\n\t| { type: \"error\"; reason: Extract<StopReason, \"aborted\" | \"error\">; error: AssistantMessage };\n\nexport type AssistantImagesEvent =\n\t| { type: \"start\"; partial: AssistantImages }\n\t| { type: \"image_start\"; contentIndex: number; partial: AssistantImages }\n\t| { type: \"image_end\"; contentIndex: number; image: ImageContent; partial: AssistantImages }\n\t| { type: \"done\"; reason: Extract<ImagesStopReason, \"stop\">; images: AssistantImages }\n\t| { type: \"error\"; reason: Extract<ImagesStopReason, \"aborted\" | \"error\">; error: AssistantImages };\n\n/**\n * Compatibility settings for OpenAI-compatible completions APIs.\n * Use this to override URL-based auto-detection for custom providers.\n */\nexport interface OpenAICompletionsCompat {\n\t/** Whether the provider supports the `store` field. Default: auto-detected from URL. */\n\tsupportsStore?: boolean;\n\t/** Whether the provider supports the `developer` role (vs `system`). Default: auto-detected from URL. */\n\tsupportsDeveloperRole?: boolean;\n\t/** Whether the provider supports `reasoning_effort`. Default: auto-detected from URL. */\n\tsupportsReasoningEffort?: boolean;\n\t/** Whether the provider supports `stream_options: { include_usage: true }` for token usage in streaming responses. Default: true. */\n\tsupportsUsageInStreaming?: boolean;\n\t/** Which field to use for max tokens. Default: auto-detected from URL. */\n\tmaxTokensField?: \"max_completion_tokens\" | \"max_tokens\";\n\t/** Whether tool results require the `name` field. Default: auto-detected from URL. */\n\trequiresToolResultName?: boolean;\n\t/** Whether a user message after tool results requires an assistant message in between. Default: auto-detected from URL. */\n\trequiresAssistantAfterToolResult?: boolean;\n\t/** Whether thinking blocks must be converted to text blocks with <thinking> delimiters. Default: auto-detected from URL. */\n\trequiresThinkingAsText?: boolean;\n\t/** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. */\n\trequiresReasoningContentOnAssistantMessages?: boolean;\n\t/** Format for reasoning/thinking parameter. \"openai\" uses reasoning_effort, \"openrouter\" uses reasoning: { effort }, \"deepseek\" uses thinking: { type } plus reasoning_effort when supported, \"together\" uses reasoning: { enabled } plus reasoning_effort when supported, \"ant-ling\" uses reasoning: { effort }, \"zai\" uses thinking: { type }, \"qwen\" uses top-level enable_thinking: boolean, \"qwen-chat-template\" uses chat_template_kwargs.enable_thinking, \"minimax\" uses thinking: { type } plus reasoning_split, and \"string-thinking\" uses top-level thinking: string. Default: \"openai\". */\n\tthinkingFormat?:\n\t\t| \"openai\"\n\t\t| \"openrouter\"\n\t\t| \"deepseek\"\n\t\t| \"together\"\n\t\t| \"ant-ling\"\n\t\t| \"zai\"\n\t\t| \"qwen\"\n\t\t| \"qwen-chat-template\"\n\t\t| \"minimax\";\n\t/** OpenRouter-specific routing preferences. Only used when baseUrl points to OpenRouter. */\n\topenRouterRouting?: OpenRouterRouting;\n\t/** Whether the model uses OpenRouter's image-generation response shape with assistant `message.images`. */\n\topenRouterImageGeneration?: boolean;\n\t/** Vercel AI Gateway routing preferences. Only used when baseUrl points to Vercel AI Gateway. */\n\tvercelGatewayRouting?: VercelGatewayRouting;\n\t/** Whether z.ai supports top-level `tool_stream: true` for streaming tool call deltas. Default: false. */\n\tzaiToolStream?: boolean;\n\t/** Whether the provider supports the `strict` field in tool definitions. Default: true. */\n\tsupportsStrictMode?: boolean;\n\t/** Cache control convention for prompt caching. \"anthropic\" applies Anthropic-style `cache_control` markers to the system prompt, last tool definition, and last user/assistant text content. */\n\tcacheControlFormat?: \"anthropic\";\n\t/** Whether to send session-affinity data from `options.sessionId`. Default: false. */\n\tsendSessionAffinityHeaders?: boolean;\n\t/** Session-affinity header format. Default: auto-detected. */\n\tsessionAffinityFormat?: \"openai\" | \"openai-nosession\" | \"openrouter\";\n\t/** Whether the provider supports long prompt cache retention (`prompt_cache_retention: \"24h\"` or Anthropic-style `cache_control.ttl: \"1h\"`, depending on format). Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n}\n\n/** Compatibility settings for OpenAI Responses APIs. */\nexport interface OpenAIResponsesCompat {\n\t/** Whether the provider supports the `developer` role (vs `system`). Default: true. */\n\tsupportsDeveloperRole?: boolean;\n\t/** Session-affinity header format. Default: auto-detected. */\n\tsessionAffinityFormat?: \"openai\" | \"openai-nosession\" | \"openrouter\";\n\t/** Whether the provider supports `prompt_cache_retention: \"24h\"`. Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n\t/** Whether the provider supports client-side tool search / deferred tool loading. Default: false. */\n\tsupportsToolSearch?: boolean;\n}\n\n/** Compatibility settings for Anthropic Messages-compatible APIs. */\nexport interface AnthropicMessagesCompat {\n\t/** Whether the provider supports adaptive thinking payloads. */\n\tforceAdaptiveThinking?: boolean;\n\t/**\n\t * Whether the provider accepts per-tool `eager_input_streaming`.\n\t * When false, the Anthropic provider omits `tools[].eager_input_streaming`\n\t * and sends the legacy `fine-grained-tool-streaming-2025-05-14` beta header\n\t * for tool-enabled requests.\n\t * Default: true.\n\t */\n\tsupportsEagerToolInputStreaming?: boolean;\n\t/** Whether the provider supports Anthropic long cache retention (`cache_control.ttl: \"1h\"`). Default: true. */\n\tsupportsLongCacheRetention?: boolean;\n\t/**\n\t * Whether to send the `x-session-affinity` header from `options.sessionId`\n\t * when caching is enabled. Required for providers like Fireworks that use\n\t * session affinity for prompt cache routing (requests to the same replica\n\t * maximize cache hits).\n\t * Default: false.\n\t */\n\tsendSessionAffinityHeaders?: boolean;\n\t/**\n\t * Whether the provider supports Anthropic-style `cache_control` markers on\n\t * tool definitions. When false, `cache_control` is omitted from tool params.\n\t * Some Anthropic-compatible providers (e.g., Fireworks) do not support this\n\t * field on tools and may reject or ignore it.\n\t * Default: true.\n\t */\n\tsupportsCacheControlOnTools?: boolean;\n\t/** Whether the provider supports client-side `tool_reference` blocks. Default: false for unsupported models. */\n\tsupportsToolReferences?: boolean;\n}\n\n/**\n * OpenRouter provider routing preferences.\n * Controls which upstream providers OpenRouter routes requests to.\n * Sent as the `provider` field in the OpenRouter API request body.\n * @see https://openrouter.ai/docs/guides/routing/provider-selection\n */\nexport interface OpenRouterRouting {\n\t/** Whether to allow backup providers to serve requests. Default: true. */\n\tallow_fallbacks?: boolean;\n\t/** Whether to filter providers to only those that support all parameters in the request. Default: false. */\n\trequire_parameters?: boolean;\n\t/** Data collection setting. \"allow\" (default): allow providers that may store/train on data. \"deny\": only use providers that don't collect user data. */\n\tdata_collection?: \"deny\" | \"allow\";\n\t/** Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. */\n\tzdr?: boolean;\n\t/** Whether to restrict routing to only models that allow text distillation. */\n\tenforce_distillable_text?: boolean;\n\t/** An ordered list of provider names/slugs to try in sequence, falling back to the next if unavailable. */\n\torder?: string[];\n\t/** List of provider names/slugs to exclusively allow for this request. */\n\tonly?: string[];\n\t/** List of provider names/slugs to skip for this request. */\n\tignore?: string[];\n\t/** A list of quantization levels to filter providers by (e.g., [\"fp16\", \"bf16\", \"fp8\", \"fp6\", \"int8\", \"int4\", \"fp4\", \"fp32\"]). */\n\tquantizations?: string[];\n\t/** Sorting strategy. Can be a string (e.g., \"price\", \"throughput\", \"latency\") or an object with `by` and `partition`. */\n\tsort?:\n\t\t| string\n\t\t| {\n\t\t\t\t/** The sorting metric: \"price\", \"throughput\", \"latency\". */\n\t\t\t\tby?: string;\n\t\t\t\t/** Partitioning strategy: \"model\" (default) or \"none\". */\n\t\t\t\tpartition?: string | null;\n\t\t };\n\t/** Maximum price per million tokens (USD). */\n\tmax_price?: {\n\t\t/** Price per million prompt tokens. */\n\t\tprompt?: number | string;\n\t\t/** Price per million completion tokens. */\n\t\tcompletion?: number | string;\n\t\t/** Price per image. */\n\t\timage?: number | string;\n\t\t/** Price per audio unit. */\n\t\taudio?: number | string;\n\t\t/** Price per request. */\n\t\trequest?: number | string;\n\t};\n\t/** Preferred minimum throughput (tokens/second). Can be a number (applies to p50) or an object with percentile-specific cutoffs. */\n\tpreferred_min_throughput?:\n\t\t| number\n\t\t| {\n\t\t\t\t/** Minimum tokens/second at the 50th percentile. */\n\t\t\t\tp50?: number;\n\t\t\t\t/** Minimum tokens/second at the 75th percentile. */\n\t\t\t\tp75?: number;\n\t\t\t\t/** Minimum tokens/second at the 90th percentile. */\n\t\t\t\tp90?: number;\n\t\t\t\t/** Minimum tokens/second at the 99th percentile. */\n\t\t\t\tp99?: number;\n\t\t };\n\t/** Preferred maximum latency (seconds). Can be a number (applies to p50) or an object with percentile-specific cutoffs. */\n\tpreferred_max_latency?:\n\t\t| number\n\t\t| {\n\t\t\t\t/** Maximum latency in seconds at the 50th percentile. */\n\t\t\t\tp50?: number;\n\t\t\t\t/** Maximum latency in seconds at the 75th percentile. */\n\t\t\t\tp75?: number;\n\t\t\t\t/** Maximum latency in seconds at the 90th percentile. */\n\t\t\t\tp90?: number;\n\t\t\t\t/** Maximum latency in seconds at the 99th percentile. */\n\t\t\t\tp99?: number;\n\t\t };\n}\n\n/**\n * Vercel AI Gateway routing preferences.\n * Controls which upstream providers the gateway routes requests to.\n * @see https://vercel.com/docs/ai-gateway/models-and-providers/provider-options\n */\nexport interface VercelGatewayRouting {\n\t/** List of provider slugs to exclusively use for this request (e.g., [\"bedrock\", \"anthropic\"]). */\n\tonly?: string[];\n\t/** List of provider slugs to try in order (e.g., [\"anthropic\", \"openai\"]). */\n\torder?: string[];\n}\n\n// Model interface for the unified model system\nexport interface Model<TApi extends Api> {\n\tid: string;\n\tname: string;\n\tapi: TApi;\n\tprovider: Provider;\n\tbaseUrl: string;\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\tinput: (\"text\" | \"image\")[];\n\tcost: {\n\t\tinput: number; // $/million tokens\n\t\toutput: number; // $/million tokens\n\t\tcacheRead: number; // $/million tokens\n\t\tcacheWrite: number; // $/million tokens\n\t\ttiers?: CostTier[];\n\t};\n\tcontextWindow: number;\n\tmaxTokens: number;\n\theaders?: Record<string, string>;\n\t/** Disable provider authentication headers for trusted local-compatible endpoints. */\n\tauthHeader?: boolean;\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\" | \"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: never;\n}\n\nexport interface ImagesModel<TApi extends ImagesApi>\n\textends Omit<Model<Api>, \"api\" | \"provider\" | \"reasoning\" | \"contextWindow\" | \"maxTokens\" | \"compat\"> {\n\tapi: TApi;\n\tprovider: ImagesProvider;\n\toutput: (\"text\" | \"image\")[];\n}\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Context, Tool } from "../types.js";
|
|
2
|
+
type ToolNameNormalizer = (name: string) => string;
|
|
3
|
+
/**
|
|
4
|
+
* Split the current tool registry into immediately cached tools and deferred tools.
|
|
5
|
+
*
|
|
6
|
+
* Deferred tools are activated by a prior tool result's `addedToolNames` marker.
|
|
7
|
+
* When deferred loading is disabled, all current tools are returned in the
|
|
8
|
+
* immediate set and the deferred map is empty.
|
|
9
|
+
*/
|
|
10
|
+
export declare function splitDeferredTools(context: Context, enabled: boolean, normalizeName?: ToolNameNormalizer): {
|
|
11
|
+
immediate: Tool[];
|
|
12
|
+
deferred: ReadonlyMap<string, Tool>;
|
|
13
|
+
};
|
|
14
|
+
export {};
|
|
15
|
+
//# sourceMappingURL=deferred-tools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deferred-tools.d.ts","sourceRoot":"","sources":["../../src/utils/deferred-tools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAEjD,KAAK,kBAAkB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;AAInD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CACjC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,EAChB,aAAa,GAAE,kBAAqC,GAClD;IAAE,SAAS,EAAE,IAAI,EAAE,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;CAAE,CA0C5D","sourcesContent":["import type { Context, Tool } from \"../types.js\";\n\ntype ToolNameNormalizer = (name: string) => string;\n\nconst identityToolName: ToolNameNormalizer = (name) => name;\n\n/**\n * Split the current tool registry into immediately cached tools and deferred tools.\n *\n * Deferred tools are activated by a prior tool result's `addedToolNames` marker.\n * When deferred loading is disabled, all current tools are returned in the\n * immediate set and the deferred map is empty.\n */\nexport function splitDeferredTools(\n\tcontext: Context,\n\tenabled: boolean,\n\tnormalizeName: ToolNameNormalizer = identityToolName,\n): { immediate: Tool[]; deferred: ReadonlyMap<string, Tool> } {\n\tconst uniqueTools = new Map<string, Tool>();\n\tfor (const tool of context.tools ?? []) {\n\t\tuniqueTools.set(normalizeName(tool.name), tool);\n\t}\n\n\tif (!enabled) {\n\t\treturn { immediate: [...uniqueTools.values()], deferred: new Map() };\n\t}\n\n\tconst deferredNames = new Set<string>();\n\tconst usedNames = new Set<string>();\n\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tusedNames.add(normalizeName(block.name));\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\") {\n\t\t\tfor (const name of message.addedToolNames ?? []) {\n\t\t\t\tconst normalizedName = normalizeName(name);\n\t\t\t\tif (!usedNames.has(normalizedName)) {\n\t\t\t\t\tdeferredNames.add(normalizedName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tconst immediate: Tool[] = [];\n\tconst deferred = new Map<string, Tool>();\n\n\tfor (const [name, tool] of uniqueTools) {\n\t\tif (deferredNames.has(name)) {\n\t\t\tdeferred.set(name, tool);\n\t\t} else {\n\t\t\timmediate.push(tool);\n\t\t}\n\t}\n\n\treturn { immediate, deferred };\n}\n"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const identityToolName = (name) => name;
|
|
2
|
+
/**
|
|
3
|
+
* Split the current tool registry into immediately cached tools and deferred tools.
|
|
4
|
+
*
|
|
5
|
+
* Deferred tools are activated by a prior tool result's `addedToolNames` marker.
|
|
6
|
+
* When deferred loading is disabled, all current tools are returned in the
|
|
7
|
+
* immediate set and the deferred map is empty.
|
|
8
|
+
*/
|
|
9
|
+
export function splitDeferredTools(context, enabled, normalizeName = identityToolName) {
|
|
10
|
+
const uniqueTools = new Map();
|
|
11
|
+
for (const tool of context.tools ?? []) {
|
|
12
|
+
uniqueTools.set(normalizeName(tool.name), tool);
|
|
13
|
+
}
|
|
14
|
+
if (!enabled) {
|
|
15
|
+
return { immediate: [...uniqueTools.values()], deferred: new Map() };
|
|
16
|
+
}
|
|
17
|
+
const deferredNames = new Set();
|
|
18
|
+
const usedNames = new Set();
|
|
19
|
+
for (const message of context.messages) {
|
|
20
|
+
if (message.role === "assistant") {
|
|
21
|
+
for (const block of message.content) {
|
|
22
|
+
if (block.type === "toolCall") {
|
|
23
|
+
usedNames.add(normalizeName(block.name));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else if (message.role === "toolResult") {
|
|
28
|
+
for (const name of message.addedToolNames ?? []) {
|
|
29
|
+
const normalizedName = normalizeName(name);
|
|
30
|
+
if (!usedNames.has(normalizedName)) {
|
|
31
|
+
deferredNames.add(normalizedName);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const immediate = [];
|
|
37
|
+
const deferred = new Map();
|
|
38
|
+
for (const [name, tool] of uniqueTools) {
|
|
39
|
+
if (deferredNames.has(name)) {
|
|
40
|
+
deferred.set(name, tool);
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
immediate.push(tool);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return { immediate, deferred };
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=deferred-tools.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deferred-tools.js","sourceRoot":"","sources":["../../src/utils/deferred-tools.ts"],"names":[],"mappings":"AAIA,MAAM,gBAAgB,GAAuB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC;AAE5D;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CACjC,OAAgB,EAChB,OAAgB,EAChB,aAAa,GAAuB,gBAAgB,EACS;IAC7D,MAAM,WAAW,GAAG,IAAI,GAAG,EAAgB,CAAC;IAC5C,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,IAAI,EAAE,EAAE,CAAC;QACxC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC;IACtE,CAAC;IAED,MAAM,aAAa,GAAG,IAAI,GAAG,EAAU,CAAC;IACxC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IAEpC,KAAK,MAAM,OAAO,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;QACxC,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YAClC,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;gBACrC,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;oBAC/B,SAAS,CAAC,GAAG,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;gBAC1C,CAAC;YACF,CAAC;QACF,CAAC;aAAM,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YAC1C,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,cAAc,IAAI,EAAE,EAAE,CAAC;gBACjD,MAAM,cAAc,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;gBAC3C,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;oBACpC,aAAa,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;gBACnC,CAAC;YACF,CAAC;QACF,CAAC;IACF,CAAC;IAED,MAAM,SAAS,GAAW,EAAE,CAAC;IAC7B,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAgB,CAAC;IAEzC,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,WAAW,EAAE,CAAC;QACxC,IAAI,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC7B,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC1B,CAAC;aAAM,CAAC;YACP,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;IACF,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;AAAA,CAC/B","sourcesContent":["import type { Context, Tool } from \"../types.js\";\n\ntype ToolNameNormalizer = (name: string) => string;\n\nconst identityToolName: ToolNameNormalizer = (name) => name;\n\n/**\n * Split the current tool registry into immediately cached tools and deferred tools.\n *\n * Deferred tools are activated by a prior tool result's `addedToolNames` marker.\n * When deferred loading is disabled, all current tools are returned in the\n * immediate set and the deferred map is empty.\n */\nexport function splitDeferredTools(\n\tcontext: Context,\n\tenabled: boolean,\n\tnormalizeName: ToolNameNormalizer = identityToolName,\n): { immediate: Tool[]; deferred: ReadonlyMap<string, Tool> } {\n\tconst uniqueTools = new Map<string, Tool>();\n\tfor (const tool of context.tools ?? []) {\n\t\tuniqueTools.set(normalizeName(tool.name), tool);\n\t}\n\n\tif (!enabled) {\n\t\treturn { immediate: [...uniqueTools.values()], deferred: new Map() };\n\t}\n\n\tconst deferredNames = new Set<string>();\n\tconst usedNames = new Set<string>();\n\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tusedNames.add(normalizeName(block.name));\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\") {\n\t\t\tfor (const name of message.addedToolNames ?? []) {\n\t\t\t\tconst normalizedName = normalizeName(name);\n\t\t\t\tif (!usedNames.has(normalizedName)) {\n\t\t\t\t\tdeferredNames.add(normalizedName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tconst immediate: Tool[] = [];\n\tconst deferred = new Map<string, Tool>();\n\n\tfor (const [name, tool] of uniqueTools) {\n\t\tif (deferredNames.has(name)) {\n\t\t\tdeferred.set(name, tool);\n\t\t} else {\n\t\t\timmediate.push(tool);\n\t\t}\n\t}\n\n\treturn { immediate, deferred };\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface DiagnosticErrorInfo {
|
|
2
|
+
name?: string;
|
|
3
|
+
message: string;
|
|
4
|
+
stack?: string;
|
|
5
|
+
code?: string | number;
|
|
6
|
+
}
|
|
7
|
+
export interface AssistantMessageDiagnostic {
|
|
8
|
+
type: string;
|
|
9
|
+
timestamp: number;
|
|
10
|
+
error?: DiagnosticErrorInfo;
|
|
11
|
+
details?: Record<string, unknown>;
|
|
12
|
+
}
|
|
13
|
+
export declare function formatThrownValue(value: unknown): string;
|
|
14
|
+
export declare function extractDiagnosticError(error: unknown): DiagnosticErrorInfo;
|
|
15
|
+
export declare function createAssistantMessageDiagnostic(type: string, error: unknown, details?: Record<string, unknown>): AssistantMessageDiagnostic;
|
|
16
|
+
export declare function appendAssistantMessageDiagnostic<T extends {
|
|
17
|
+
diagnostics?: AssistantMessageDiagnostic[];
|
|
18
|
+
}>(message: T, diagnostic: AssistantMessageDiagnostic): void;
|
|
19
|
+
//# sourceMappingURL=diagnostics.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../../src/utils/diagnostics.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,mBAAmB;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,0BAA0B;IAC1C,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAIxD;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,mBAAmB,CAS1E;AAED,wBAAgB,gCAAgC,CAC/C,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,OAAO,EACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,0BAA0B,CAE5B;AAED,wBAAgB,gCAAgC,CAAC,CAAC,SAAS;IAAE,WAAW,CAAC,EAAE,0BAA0B,EAAE,CAAA;CAAE,EACxG,OAAO,EAAE,CAAC,EACV,UAAU,EAAE,0BAA0B,GACpC,IAAI,CAEN","sourcesContent":["export interface DiagnosticErrorInfo {\n\tname?: string;\n\tmessage: string;\n\tstack?: string;\n\tcode?: string | number;\n}\n\nexport interface AssistantMessageDiagnostic {\n\ttype: string;\n\ttimestamp: number;\n\terror?: DiagnosticErrorInfo;\n\tdetails?: Record<string, unknown>;\n}\n\nexport function formatThrownValue(value: unknown): string {\n\tif (value instanceof Error) return value.message || value.name;\n\tif (typeof value === \"string\") return value;\n\treturn String(value);\n}\n\nexport function extractDiagnosticError(error: unknown): DiagnosticErrorInfo {\n\tif (!(error instanceof Error)) return { name: \"ThrownValue\", message: formatThrownValue(error) };\n\tconst code = (error as Error & { code?: unknown }).code;\n\treturn {\n\t\tname: error.name || undefined,\n\t\tmessage: error.message || error.name,\n\t\tstack: error.stack,\n\t\tcode: typeof code === \"string\" || typeof code === \"number\" ? code : undefined,\n\t};\n}\n\nexport function createAssistantMessageDiagnostic(\n\ttype: string,\n\terror: unknown,\n\tdetails?: Record<string, unknown>,\n): AssistantMessageDiagnostic {\n\treturn { type, timestamp: Date.now(), error: extractDiagnosticError(error), details };\n}\n\nexport function appendAssistantMessageDiagnostic<T extends { diagnostics?: AssistantMessageDiagnostic[] }>(\n\tmessage: T,\n\tdiagnostic: AssistantMessageDiagnostic,\n): void {\n\tmessage.diagnostics = [...(message.diagnostics ?? []), diagnostic];\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export function formatThrownValue(value) {
|
|
2
|
+
if (value instanceof Error)
|
|
3
|
+
return value.message || value.name;
|
|
4
|
+
if (typeof value === "string")
|
|
5
|
+
return value;
|
|
6
|
+
return String(value);
|
|
7
|
+
}
|
|
8
|
+
export function extractDiagnosticError(error) {
|
|
9
|
+
if (!(error instanceof Error))
|
|
10
|
+
return { name: "ThrownValue", message: formatThrownValue(error) };
|
|
11
|
+
const code = error.code;
|
|
12
|
+
return {
|
|
13
|
+
name: error.name || undefined,
|
|
14
|
+
message: error.message || error.name,
|
|
15
|
+
stack: error.stack,
|
|
16
|
+
code: typeof code === "string" || typeof code === "number" ? code : undefined,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function createAssistantMessageDiagnostic(type, error, details) {
|
|
20
|
+
return { type, timestamp: Date.now(), error: extractDiagnosticError(error), details };
|
|
21
|
+
}
|
|
22
|
+
export function appendAssistantMessageDiagnostic(message, diagnostic) {
|
|
23
|
+
message.diagnostics = [...(message.diagnostics ?? []), diagnostic];
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../../src/utils/diagnostics.ts"],"names":[],"mappings":"AAcA,MAAM,UAAU,iBAAiB,CAAC,KAAc,EAAU;IACzD,IAAI,KAAK,YAAY,KAAK;QAAE,OAAO,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC;IAC/D,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AAAA,CACrB;AAED,MAAM,UAAU,sBAAsB,CAAC,KAAc,EAAuB;IAC3E,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC;IACjG,MAAM,IAAI,GAAI,KAAoC,CAAC,IAAI,CAAC;IACxD,OAAO;QACN,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,SAAS;QAC7B,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,IAAI;QACpC,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;KAC7E,CAAC;AAAA,CACF;AAED,MAAM,UAAU,gCAAgC,CAC/C,IAAY,EACZ,KAAc,EACd,OAAiC,EACJ;IAC7B,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,sBAAsB,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC;AAAA,CACtF;AAED,MAAM,UAAU,gCAAgC,CAC/C,OAAU,EACV,UAAsC,EAC/B;IACP,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC,EAAE,UAAU,CAAC,CAAC;AAAA,CACnE","sourcesContent":["export interface DiagnosticErrorInfo {\n\tname?: string;\n\tmessage: string;\n\tstack?: string;\n\tcode?: string | number;\n}\n\nexport interface AssistantMessageDiagnostic {\n\ttype: string;\n\ttimestamp: number;\n\terror?: DiagnosticErrorInfo;\n\tdetails?: Record<string, unknown>;\n}\n\nexport function formatThrownValue(value: unknown): string {\n\tif (value instanceof Error) return value.message || value.name;\n\tif (typeof value === \"string\") return value;\n\treturn String(value);\n}\n\nexport function extractDiagnosticError(error: unknown): DiagnosticErrorInfo {\n\tif (!(error instanceof Error)) return { name: \"ThrownValue\", message: formatThrownValue(error) };\n\tconst code = (error as Error & { code?: unknown }).code;\n\treturn {\n\t\tname: error.name || undefined,\n\t\tmessage: error.message || error.name,\n\t\tstack: error.stack,\n\t\tcode: typeof code === \"string\" || typeof code === \"number\" ? code : undefined,\n\t};\n}\n\nexport function createAssistantMessageDiagnostic(\n\ttype: string,\n\terror: unknown,\n\tdetails?: Record<string, unknown>,\n): AssistantMessageDiagnostic {\n\treturn { type, timestamp: Date.now(), error: extractDiagnosticError(error), details };\n}\n\nexport function appendAssistantMessageDiagnostic<T extends { diagnostics?: AssistantMessageDiagnostic[] }>(\n\tmessage: T,\n\tdiagnostic: AssistantMessageDiagnostic,\n): void {\n\tmessage.diagnostics = [...(message.diagnostics ?? []), diagnostic];\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;
|
|
2
|
+
export interface NormalizedProviderError {
|
|
3
|
+
/** HTTP status code, when one could be extracted from the SDK error object. */
|
|
4
|
+
status?: number;
|
|
5
|
+
/** Raw HTTP body reason, bounded to avoid untrusted error amplification. */
|
|
6
|
+
body?: string;
|
|
7
|
+
/** Error message or a safe serialization of a non-Error throw. */
|
|
8
|
+
message: string;
|
|
9
|
+
/** Whether the message already contains the extracted body. */
|
|
10
|
+
messageCarriesBody: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** Normalize SDK-specific status, body, and message fields for display. */
|
|
13
|
+
export declare function normalizeProviderError(error: unknown): NormalizedProviderError;
|
|
14
|
+
/** Format a normalized provider error while preserving the provider prefix. */
|
|
15
|
+
export declare function formatProviderError(norm: NormalizedProviderError, prefix?: string): string;
|
|
16
|
+
/** Bound provider-controlled error text before exposing it in the transcript. */
|
|
17
|
+
export declare function truncateErrorText(text: string, maxChars: number): string;
|
|
18
|
+
/** Serialize unknown thrown values without allowing serialization to throw again. */
|
|
19
|
+
export declare function safeJsonStringify(value: unknown): string;
|
|
20
|
+
//# sourceMappingURL=error-body.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-body.d.ts","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD,MAAM,WAAW,uBAAuB;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4EAA4E;IAC5E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,kEAAkE;IAClE,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,kBAAkB,EAAE,OAAO,CAAC;CAC5B;AAWD,2EAA2E;AAC3E,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAY9E;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAO1F;AAED,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGxE;AAED,qFAAqF;AACrF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAOxD","sourcesContent":["// Shared normalization for provider HTTP error objects.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, bounded to avoid untrusted error amplification. */\n\tbody?: string;\n\t/** Error message or a safe serialization of a non-Error throw. */\n\tmessage: string;\n\t/** Whether the message already contains the extracted body. */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\n/** Normalize SDK-specific status, body, and message fields for display. */\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) return { message: safeJsonStringify(error), messageCarriesBody: false };\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody: body === undefined || error.message.includes(body),\n\t};\n}\n\n/** Format a normalized provider error while preserving the provider prefix. */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\n/** Bound provider-controlled error text before exposing it in the transcript. */\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\n/** Serialize unknown thrown values without allowing serialization to throw again. */\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst responseBody = error.$response?.body;\n\tconst body =\n\t\ttypeof error.body === \"string\"\n\t\t\t? error.body\n\t\t\t: isNonEmptyObject(error.error)\n\t\t\t\t? safeJsonStringify(error.error)\n\t\t\t\t: typeof responseBody === \"string\"\n\t\t\t\t\t? responseBody\n\t\t\t\t\t: isNonEmptyObject(responseBody)\n\t\t\t\t\t\t? safeJsonStringify(responseBody)\n\t\t\t\t\t\t: undefined;\n\tif (body === undefined || body.trim().length === 0) return undefined;\n\treturn truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction isNonEmptyObject(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && Object.keys(value).length > 0;\n}\n"]}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Shared normalization for provider HTTP error objects.
|
|
2
|
+
export const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;
|
|
3
|
+
/** Normalize SDK-specific status, body, and message fields for display. */
|
|
4
|
+
export function normalizeProviderError(error) {
|
|
5
|
+
if (!(error instanceof Error))
|
|
6
|
+
return { message: safeJsonStringify(error), messageCarriesBody: false };
|
|
7
|
+
const sdkError = error;
|
|
8
|
+
const status = extractStatus(sdkError);
|
|
9
|
+
const body = extractBody(sdkError);
|
|
10
|
+
return {
|
|
11
|
+
status,
|
|
12
|
+
body,
|
|
13
|
+
message: error.message,
|
|
14
|
+
messageCarriesBody: body === undefined || error.message.includes(body),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** Format a normalized provider error while preserving the provider prefix. */
|
|
18
|
+
export function formatProviderError(norm, prefix) {
|
|
19
|
+
if (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {
|
|
20
|
+
return prefix !== undefined && norm.status !== undefined
|
|
21
|
+
? `${prefix} (${norm.status}): ${norm.message}`
|
|
22
|
+
: norm.message;
|
|
23
|
+
}
|
|
24
|
+
return prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;
|
|
25
|
+
}
|
|
26
|
+
/** Bound provider-controlled error text before exposing it in the transcript. */
|
|
27
|
+
export function truncateErrorText(text, maxChars) {
|
|
28
|
+
if (text.length <= maxChars)
|
|
29
|
+
return text;
|
|
30
|
+
return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;
|
|
31
|
+
}
|
|
32
|
+
/** Serialize unknown thrown values without allowing serialization to throw again. */
|
|
33
|
+
export function safeJsonStringify(value) {
|
|
34
|
+
try {
|
|
35
|
+
const serialized = JSON.stringify(value);
|
|
36
|
+
return serialized === undefined ? String(value) : serialized;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return String(value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function extractStatus(error) {
|
|
43
|
+
if (typeof error.statusCode === "number")
|
|
44
|
+
return error.statusCode;
|
|
45
|
+
if (typeof error.status === "number")
|
|
46
|
+
return error.status;
|
|
47
|
+
if (typeof error.$metadata?.httpStatusCode === "number")
|
|
48
|
+
return error.$metadata.httpStatusCode;
|
|
49
|
+
if (typeof error.$response?.statusCode === "number")
|
|
50
|
+
return error.$response.statusCode;
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
function extractBody(error) {
|
|
54
|
+
const responseBody = error.$response?.body;
|
|
55
|
+
const body = typeof error.body === "string"
|
|
56
|
+
? error.body
|
|
57
|
+
: isNonEmptyObject(error.error)
|
|
58
|
+
? safeJsonStringify(error.error)
|
|
59
|
+
: typeof responseBody === "string"
|
|
60
|
+
? responseBody
|
|
61
|
+
: isNonEmptyObject(responseBody)
|
|
62
|
+
? safeJsonStringify(responseBody)
|
|
63
|
+
: undefined;
|
|
64
|
+
if (body === undefined || body.trim().length === 0)
|
|
65
|
+
return undefined;
|
|
66
|
+
return truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);
|
|
67
|
+
}
|
|
68
|
+
function isNonEmptyObject(value) {
|
|
69
|
+
return typeof value === "object" && value !== null && Object.keys(value).length > 0;
|
|
70
|
+
}
|
|
71
|
+
//# sourceMappingURL=error-body.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-body.js","sourceRoot":"","sources":["../../src/utils/error-body.ts"],"names":[],"mappings":"AAAA,wDAAwD;AAExD,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAsBlD,2EAA2E;AAC3E,MAAM,UAAU,sBAAsB,CAAC,KAAc,EAA2B;IAC/E,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,KAAK,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC;IAEvG,MAAM,QAAQ,GAAG,KAAsB,CAAC;IACxC,MAAM,MAAM,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC;IACnC,OAAO;QACN,MAAM;QACN,IAAI;QACJ,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,kBAAkB,EAAE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;KACtE,CAAC;AAAA,CACF;AAED,+EAA+E;AAC/E,MAAM,UAAU,mBAAmB,CAAC,IAA6B,EAAE,MAAe,EAAU;IAC3F,IAAI,IAAI,CAAC,kBAAkB,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QACrF,OAAO,MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YACvD,CAAC,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,OAAO,EAAE;YAC/C,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC;AAAA,CAC1G;AAED,iFAAiF;AACjF,MAAM,UAAU,iBAAiB,CAAC,IAAY,EAAE,QAAgB,EAAU;IACzE,IAAI,IAAI,CAAC,MAAM,IAAI,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,kBAAkB,IAAI,CAAC,MAAM,GAAG,QAAQ,SAAS,CAAC;AAAA,CACnF;AAED,qFAAqF;AACrF,MAAM,UAAU,iBAAiB,CAAC,KAAc,EAAU;IACzD,IAAI,CAAC;QACJ,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACzC,OAAO,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;IAC9D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AAAA,CACD;AAED,SAAS,aAAa,CAAC,KAAoB,EAAsB;IAChE,IAAI,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC,UAAU,CAAC;IAClE,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC,MAAM,CAAC;IAC1D,IAAI,OAAO,KAAK,CAAC,SAAS,EAAE,cAAc,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC,SAAS,CAAC,cAAc,CAAC;IAC/F,IAAI,OAAO,KAAK,CAAC,SAAS,EAAE,UAAU,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC;IACvF,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,SAAS,WAAW,CAAC,KAAoB,EAAsB;IAC9D,MAAM,YAAY,GAAG,KAAK,CAAC,SAAS,EAAE,IAAI,CAAC;IAC3C,MAAM,IAAI,GACT,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC7B,CAAC,CAAC,KAAK,CAAC,IAAI;QACZ,CAAC,CAAC,gBAAgB,CAAC,KAAK,CAAC,KAAK,CAAC;YAC9B,CAAC,CAAC,iBAAiB,CAAC,KAAK,CAAC,KAAK,CAAC;YAChC,CAAC,CAAC,OAAO,YAAY,KAAK,QAAQ;gBACjC,CAAC,CAAC,YAAY;gBACd,CAAC,CAAC,gBAAgB,CAAC,YAAY,CAAC;oBAC/B,CAAC,CAAC,iBAAiB,CAAC,YAAY,CAAC;oBACjC,CAAC,CAAC,SAAS,CAAC;IACjB,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACrE,OAAO,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,6BAA6B,CAAC,CAAC;AAAA,CACrE;AAED,SAAS,gBAAgB,CAAC,KAAc,EAAW;IAClD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AAAA,CACpF","sourcesContent":["// Shared normalization for provider HTTP error objects.\n\nexport const MAX_PROVIDER_ERROR_BODY_CHARS = 4000;\n\nexport interface NormalizedProviderError {\n\t/** HTTP status code, when one could be extracted from the SDK error object. */\n\tstatus?: number;\n\t/** Raw HTTP body reason, bounded to avoid untrusted error amplification. */\n\tbody?: string;\n\t/** Error message or a safe serialization of a non-Error throw. */\n\tmessage: string;\n\t/** Whether the message already contains the extracted body. */\n\tmessageCarriesBody: boolean;\n}\n\ntype SdkErrorShape = Error & {\n\tstatusCode?: unknown;\n\tstatus?: unknown;\n\tbody?: unknown;\n\terror?: unknown;\n\t$metadata?: { httpStatusCode?: unknown };\n\t$response?: { statusCode?: unknown; body?: unknown };\n};\n\n/** Normalize SDK-specific status, body, and message fields for display. */\nexport function normalizeProviderError(error: unknown): NormalizedProviderError {\n\tif (!(error instanceof Error)) return { message: safeJsonStringify(error), messageCarriesBody: false };\n\n\tconst sdkError = error as SdkErrorShape;\n\tconst status = extractStatus(sdkError);\n\tconst body = extractBody(sdkError);\n\treturn {\n\t\tstatus,\n\t\tbody,\n\t\tmessage: error.message,\n\t\tmessageCarriesBody: body === undefined || error.message.includes(body),\n\t};\n}\n\n/** Format a normalized provider error while preserving the provider prefix. */\nexport function formatProviderError(norm: NormalizedProviderError, prefix?: string): string {\n\tif (norm.messageCarriesBody || norm.status === undefined || norm.body === undefined) {\n\t\treturn prefix !== undefined && norm.status !== undefined\n\t\t\t? `${prefix} (${norm.status}): ${norm.message}`\n\t\t\t: norm.message;\n\t}\n\treturn prefix !== undefined ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;\n}\n\n/** Bound provider-controlled error text before exposing it in the transcript. */\nexport function truncateErrorText(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\treturn `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;\n}\n\n/** Serialize unknown thrown values without allowing serialization to throw again. */\nexport function safeJsonStringify(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\treturn serialized === undefined ? String(value) : serialized;\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction extractStatus(error: SdkErrorShape): number | undefined {\n\tif (typeof error.statusCode === \"number\") return error.statusCode;\n\tif (typeof error.status === \"number\") return error.status;\n\tif (typeof error.$metadata?.httpStatusCode === \"number\") return error.$metadata.httpStatusCode;\n\tif (typeof error.$response?.statusCode === \"number\") return error.$response.statusCode;\n\treturn undefined;\n}\n\nfunction extractBody(error: SdkErrorShape): string | undefined {\n\tconst responseBody = error.$response?.body;\n\tconst body =\n\t\ttypeof error.body === \"string\"\n\t\t\t? error.body\n\t\t\t: isNonEmptyObject(error.error)\n\t\t\t\t? safeJsonStringify(error.error)\n\t\t\t\t: typeof responseBody === \"string\"\n\t\t\t\t\t? responseBody\n\t\t\t\t\t: isNonEmptyObject(responseBody)\n\t\t\t\t\t\t? safeJsonStringify(responseBody)\n\t\t\t\t\t\t: undefined;\n\tif (body === undefined || body.trim().length === 0) return undefined;\n\treturn truncateErrorText(body.trim(), MAX_PROVIDER_ERROR_BODY_CHARS);\n}\n\nfunction isNonEmptyObject(value: unknown): boolean {\n\treturn typeof value === \"object\" && value !== null && Object.keys(value).length > 0;\n}\n"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AssistantImages, AssistantImagesEvent, AssistantMessage, AssistantMessageEvent } from "../types.js";
|
|
2
|
+
export declare class EventStream<T, R = T> implements AsyncIterable<T> {
|
|
3
|
+
private isComplete;
|
|
4
|
+
private extractResult;
|
|
5
|
+
private queue;
|
|
6
|
+
private waiting;
|
|
7
|
+
private done;
|
|
8
|
+
private finalResultPromise;
|
|
9
|
+
private resolveFinalResult;
|
|
10
|
+
constructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R);
|
|
11
|
+
push(event: T): void;
|
|
12
|
+
end(result?: R): void;
|
|
13
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
14
|
+
result(): Promise<R>;
|
|
15
|
+
}
|
|
16
|
+
export declare class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
|
|
17
|
+
constructor();
|
|
18
|
+
}
|
|
19
|
+
export declare class AssistantImagesEventStream extends EventStream<AssistantImagesEvent, AssistantImages> {
|
|
20
|
+
constructor();
|
|
21
|
+
}
|
|
22
|
+
/** Factory function for AssistantMessageEventStream (for use in extensions) */
|
|
23
|
+
export declare function createAssistantMessageEventStream(): AssistantMessageEventStream;
|
|
24
|
+
/** Factory function for AssistantImagesEventStream (for use in extensions) */
|
|
25
|
+
export declare function createAssistantImagesEventStream(): AssistantImagesEventStream;
|
|
26
|
+
//# sourceMappingURL=event-stream.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-stream.d.ts","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAGlH,qBAAa,WAAW,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;IAQ5D,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,aAAa;IARtB,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,OAAO,CAA8C;IAC7D,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,kBAAkB,CAAa;IACvC,OAAO,CAAC,kBAAkB,CAAuB;IAEjD,YACS,UAAU,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,EACjC,aAAa,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,EAKtC;IAED,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAenB;IAED,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAUpB;IAEM,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC,CAYhD;IAED,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,CAEnB;CACD;AAED,qBAAa,2BAA4B,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACpG,cAYC;CACD;AAED,qBAAa,0BAA2B,SAAQ,WAAW,CAAC,oBAAoB,EAAE,eAAe,CAAC;IACjG,cAYC;CACD;AAED,+EAA+E;AAC/E,wBAAgB,iCAAiC,IAAI,2BAA2B,CAE/E;AAED,8EAA8E;AAC9E,wBAAgB,gCAAgC,IAAI,0BAA0B,CAE7E","sourcesContent":["import type { AssistantImages, AssistantImagesEvent, AssistantMessage, AssistantMessageEvent } from \"../types.js\";\n\n// Generic event stream class for async iteration\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nexport class AssistantImagesEventStream extends EventStream<AssistantImagesEvent, AssistantImages> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.images;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n\n/** Factory function for AssistantImagesEventStream (for use in extensions) */\nexport function createAssistantImagesEventStream(): AssistantImagesEventStream {\n\treturn new AssistantImagesEventStream();\n}\n"]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Generic event stream class for async iteration
|
|
2
|
+
export class EventStream {
|
|
3
|
+
isComplete;
|
|
4
|
+
extractResult;
|
|
5
|
+
queue = [];
|
|
6
|
+
waiting = [];
|
|
7
|
+
done = false;
|
|
8
|
+
finalResultPromise;
|
|
9
|
+
resolveFinalResult;
|
|
10
|
+
constructor(isComplete, extractResult) {
|
|
11
|
+
this.isComplete = isComplete;
|
|
12
|
+
this.extractResult = extractResult;
|
|
13
|
+
this.finalResultPromise = new Promise((resolve) => {
|
|
14
|
+
this.resolveFinalResult = resolve;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
push(event) {
|
|
18
|
+
if (this.done)
|
|
19
|
+
return;
|
|
20
|
+
if (this.isComplete(event)) {
|
|
21
|
+
this.done = true;
|
|
22
|
+
this.resolveFinalResult(this.extractResult(event));
|
|
23
|
+
}
|
|
24
|
+
// Deliver to waiting consumer or queue it
|
|
25
|
+
const waiter = this.waiting.shift();
|
|
26
|
+
if (waiter) {
|
|
27
|
+
waiter({ value: event, done: false });
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
this.queue.push(event);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
end(result) {
|
|
34
|
+
this.done = true;
|
|
35
|
+
if (result !== undefined) {
|
|
36
|
+
this.resolveFinalResult(result);
|
|
37
|
+
}
|
|
38
|
+
// Notify all waiting consumers that we're done
|
|
39
|
+
while (this.waiting.length > 0) {
|
|
40
|
+
const waiter = this.waiting.shift();
|
|
41
|
+
waiter({ value: undefined, done: true });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async *[Symbol.asyncIterator]() {
|
|
45
|
+
while (true) {
|
|
46
|
+
if (this.queue.length > 0) {
|
|
47
|
+
yield this.queue.shift();
|
|
48
|
+
}
|
|
49
|
+
else if (this.done) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
const result = await new Promise((resolve) => this.waiting.push(resolve));
|
|
54
|
+
if (result.done)
|
|
55
|
+
return;
|
|
56
|
+
yield result.value;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
result() {
|
|
61
|
+
return this.finalResultPromise;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export class AssistantMessageEventStream extends EventStream {
|
|
65
|
+
constructor() {
|
|
66
|
+
super((event) => event.type === "done" || event.type === "error", (event) => {
|
|
67
|
+
if (event.type === "done") {
|
|
68
|
+
return event.message;
|
|
69
|
+
}
|
|
70
|
+
else if (event.type === "error") {
|
|
71
|
+
return event.error;
|
|
72
|
+
}
|
|
73
|
+
throw new Error("Unexpected event type for final result");
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
export class AssistantImagesEventStream extends EventStream {
|
|
78
|
+
constructor() {
|
|
79
|
+
super((event) => event.type === "done" || event.type === "error", (event) => {
|
|
80
|
+
if (event.type === "done") {
|
|
81
|
+
return event.images;
|
|
82
|
+
}
|
|
83
|
+
else if (event.type === "error") {
|
|
84
|
+
return event.error;
|
|
85
|
+
}
|
|
86
|
+
throw new Error("Unexpected event type for final result");
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Factory function for AssistantMessageEventStream (for use in extensions) */
|
|
91
|
+
export function createAssistantMessageEventStream() {
|
|
92
|
+
return new AssistantMessageEventStream();
|
|
93
|
+
}
|
|
94
|
+
/** Factory function for AssistantImagesEventStream (for use in extensions) */
|
|
95
|
+
export function createAssistantImagesEventStream() {
|
|
96
|
+
return new AssistantImagesEventStream();
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=event-stream.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-stream.js","sourceRoot":"","sources":["../../src/utils/event-stream.ts"],"names":[],"mappings":"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","sourcesContent":["import type { AssistantImages, AssistantImagesEvent, AssistantMessage, AssistantMessageEvent } from \"../types.js\";\n\n// Generic event stream class for async iteration\nexport class EventStream<T, R = T> implements AsyncIterable<T> {\n\tprivate queue: T[] = [];\n\tprivate waiting: ((value: IteratorResult<T>) => void)[] = [];\n\tprivate done = false;\n\tprivate finalResultPromise: Promise<R>;\n\tprivate resolveFinalResult!: (result: R) => void;\n\n\tconstructor(\n\t\tprivate isComplete: (event: T) => boolean,\n\t\tprivate extractResult: (event: T) => R,\n\t) {\n\t\tthis.finalResultPromise = new Promise((resolve) => {\n\t\t\tthis.resolveFinalResult = resolve;\n\t\t});\n\t}\n\n\tpush(event: T): void {\n\t\tif (this.done) return;\n\n\t\tif (this.isComplete(event)) {\n\t\t\tthis.done = true;\n\t\t\tthis.resolveFinalResult(this.extractResult(event));\n\t\t}\n\n\t\t// Deliver to waiting consumer or queue it\n\t\tconst waiter = this.waiting.shift();\n\t\tif (waiter) {\n\t\t\twaiter({ value: event, done: false });\n\t\t} else {\n\t\t\tthis.queue.push(event);\n\t\t}\n\t}\n\n\tend(result?: R): void {\n\t\tthis.done = true;\n\t\tif (result !== undefined) {\n\t\t\tthis.resolveFinalResult(result);\n\t\t}\n\t\t// Notify all waiting consumers that we're done\n\t\twhile (this.waiting.length > 0) {\n\t\t\tconst waiter = this.waiting.shift()!;\n\t\t\twaiter({ value: undefined as any, done: true });\n\t\t}\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\twhile (true) {\n\t\t\tif (this.queue.length > 0) {\n\t\t\t\tyield this.queue.shift()!;\n\t\t\t} else if (this.done) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tconst result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));\n\t\t\t\tif (result.done) return;\n\t\t\t\tyield result.value;\n\t\t\t}\n\t\t}\n\t}\n\n\tresult(): Promise<R> {\n\t\treturn this.finalResultPromise;\n\t}\n}\n\nexport class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.message;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\nexport class AssistantImagesEventStream extends EventStream<AssistantImagesEvent, AssistantImages> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") {\n\t\t\t\t\treturn event.images;\n\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\treturn event.error;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"Unexpected event type for final result\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** Factory function for AssistantMessageEventStream (for use in extensions) */\nexport function createAssistantMessageEventStream(): AssistantMessageEventStream {\n\treturn new AssistantMessageEventStream();\n}\n\n/** Factory function for AssistantImagesEventStream (for use in extensions) */\nexport function createAssistantImagesEventStream(): AssistantImagesEventStream {\n\treturn new AssistantImagesEventStream();\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../../src/utils/hash.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAW7C","sourcesContent":["/** Fast deterministic hash to shorten long strings */\nexport function shortHash(str: string): string {\n\tlet h1 = 0xdeadbeef;\n\tlet h2 = 0x41c6ce57;\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst ch = str.charCodeAt(i);\n\t\th1 = Math.imul(h1 ^ ch, 2654435761);\n\t\th2 = Math.imul(h2 ^ ch, 1597334677);\n\t}\n\th1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n\th2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n\treturn (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Fast deterministic hash to shorten long strings */
|
|
2
|
+
export function shortHash(str) {
|
|
3
|
+
let h1 = 0xdeadbeef;
|
|
4
|
+
let h2 = 0x41c6ce57;
|
|
5
|
+
for (let i = 0; i < str.length; i++) {
|
|
6
|
+
const ch = str.charCodeAt(i);
|
|
7
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
8
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
9
|
+
}
|
|
10
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
11
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
12
|
+
return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=hash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hash.js","sourceRoot":"","sources":["../../src/utils/hash.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,MAAM,UAAU,SAAS,CAAC,GAAW,EAAU;IAC9C,IAAI,EAAE,GAAG,UAAU,CAAC;IACpB,IAAI,EAAE,GAAG,UAAU,CAAC;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,EAAE,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC7B,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,EAAE,UAAU,CAAC,CAAC;QACpC,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,EAAE,UAAU,CAAC,CAAC;IACrC,CAAC;IACD,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,CAAC,CAAC;IACvF,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,CAAC,CAAC;IACvF,OAAO,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AAAA,CACzD","sourcesContent":["/** Fast deterministic hash to shorten long strings */\nexport function shortHash(str: string): string {\n\tlet h1 = 0xdeadbeef;\n\tlet h2 = 0x41c6ce57;\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst ch = str.charCodeAt(i);\n\t\th1 = Math.imul(h1 ^ ch, 2654435761);\n\t\th2 = Math.imul(h2 ^ ch, 1597334677);\n\t}\n\th1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n\th2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n\treturn (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"headers.d.ts","sourceRoot":"","sources":["../../src/utils/headers.ts"],"names":[],"mappings":"AAAA,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAMxE","sourcesContent":["export function headersToRecord(headers: Headers): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\theaders.forEach((value, key) => {\n\t\tresult[key] = value;\n\t});\n\treturn result;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"headers.js","sourceRoot":"","sources":["../../src/utils/headers.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,eAAe,CAAC,OAAgB,EAA0B;IACzE,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC;QAC/B,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IAAA,CACpB,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["export function headersToRecord(headers: Headers): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\theaders.forEach((value, key) => {\n\t\tresult[key] = value;\n\t});\n\treturn result;\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Repairs malformed JSON string literals by:
|
|
3
|
+
* - escaping raw control characters inside strings
|
|
4
|
+
* - doubling backslashes before invalid escape characters
|
|
5
|
+
*/
|
|
6
|
+
export declare function repairJson(json: string): string;
|
|
7
|
+
export declare function parseJsonWithRepair<T>(json: string): T;
|
|
8
|
+
/**
|
|
9
|
+
* Attempts to parse potentially incomplete JSON during streaming.
|
|
10
|
+
* Always returns a valid object, even if the JSON is incomplete.
|
|
11
|
+
*
|
|
12
|
+
* @param partialJson The partial JSON string from streaming
|
|
13
|
+
* @returns Parsed object or empty object if parsing fails
|
|
14
|
+
*/
|
|
15
|
+
export declare function parseStreamingJson<T = Record<string, unknown>>(partialJson: string | undefined): T;
|
|
16
|
+
//# sourceMappingURL=json-parse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-parse.d.ts","sourceRoot":"","sources":["../../src/utils/json-parse.ts"],"names":[],"mappings":"AA0BA;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAmD/C;AAED,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,CAUtD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,SAAS,GAAG,CAAC,CAoBlG","sourcesContent":["import { parse as partialParse } from \"partial-json\";\n\nconst VALID_JSON_ESCAPES = new Set(['\"', \"\\\\\", \"/\", \"b\", \"f\", \"n\", \"r\", \"t\", \"u\"]);\n\nfunction isControlCharacter(char: string): boolean {\n\tconst codePoint = char.codePointAt(0);\n\treturn codePoint !== undefined && codePoint >= 0x00 && codePoint <= 0x1f;\n}\n\nfunction escapeControlCharacter(char: string): string {\n\tswitch (char) {\n\t\tcase \"\\b\":\n\t\t\treturn \"\\\\b\";\n\t\tcase \"\\f\":\n\t\t\treturn \"\\\\f\";\n\t\tcase \"\\n\":\n\t\t\treturn \"\\\\n\";\n\t\tcase \"\\r\":\n\t\t\treturn \"\\\\r\";\n\t\tcase \"\\t\":\n\t\t\treturn \"\\\\t\";\n\t\tdefault:\n\t\t\treturn `\\\\u${char.codePointAt(0)?.toString(16).padStart(4, \"0\") ?? \"0000\"}`;\n\t}\n}\n\n/**\n * Repairs malformed JSON string literals by:\n * - escaping raw control characters inside strings\n * - doubling backslashes before invalid escape characters\n */\nexport function repairJson(json: string): string {\n\tlet repaired = \"\";\n\tlet inString = false;\n\n\tfor (let index = 0; index < json.length; index++) {\n\t\tconst char = json[index];\n\n\t\tif (!inString) {\n\t\t\trepaired += char;\n\t\t\tif (char === '\"') {\n\t\t\t\tinString = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\trepaired += char;\n\t\t\tinString = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === \"\\\\\") {\n\t\t\tconst nextChar = json[index + 1];\n\t\t\tif (nextChar === undefined) {\n\t\t\t\trepaired += \"\\\\\\\\\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (nextChar === \"u\") {\n\t\t\t\tconst unicodeDigits = json.slice(index + 2, index + 6);\n\t\t\t\tif (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {\n\t\t\t\t\trepaired += `\\\\u${unicodeDigits}`;\n\t\t\t\t\tindex += 5;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (VALID_JSON_ESCAPES.has(nextChar)) {\n\t\t\t\trepaired += `\\\\${nextChar}`;\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\trepaired += \"\\\\\\\\\";\n\t\t\tcontinue;\n\t\t}\n\n\t\trepaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;\n\t}\n\n\treturn repaired;\n}\n\nexport function parseJsonWithRepair<T>(json: string): T {\n\ttry {\n\t\treturn JSON.parse(json) as T;\n\t} catch (error) {\n\t\tconst repairedJson = repairJson(json);\n\t\tif (repairedJson !== json) {\n\t\t\treturn JSON.parse(repairedJson) as T;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Attempts to parse potentially incomplete JSON during streaming.\n * Always returns a valid object, even if the JSON is incomplete.\n *\n * @param partialJson The partial JSON string from streaming\n * @returns Parsed object or empty object if parsing fails\n */\nexport function parseStreamingJson<T = Record<string, unknown>>(partialJson: string | undefined): T {\n\tif (!partialJson || partialJson.trim() === \"\") {\n\t\treturn {} as T;\n\t}\n\n\ttry {\n\t\treturn parseJsonWithRepair<T>(partialJson);\n\t} catch {\n\t\ttry {\n\t\t\tconst result = partialParse(partialJson);\n\t\t\treturn (result ?? {}) as T;\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tconst result = partialParse(repairJson(partialJson));\n\t\t\t\treturn (result ?? {}) as T;\n\t\t\t} catch {\n\t\t\t\treturn {} as T;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|