@fgv/ts-extras 5.1.0-55 → 5.1.0-57
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/CAPABILITIES.md +96 -0
- package/dist/packlets/ai-assist/cacheRequest.js +118 -0
- package/dist/packlets/ai-assist/cacheRequest.js.map +1 -0
- package/dist/packlets/ai-assist/chatRequestBuilders.js +72 -7
- package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
- package/dist/packlets/ai-assist/completionClient.js +195 -58
- package/dist/packlets/ai-assist/completionClient.js.map +1 -1
- package/dist/packlets/ai-assist/converters.js +54 -0
- package/dist/packlets/ai-assist/converters.js.map +1 -1
- package/dist/packlets/ai-assist/embeddingClient.js +16 -1
- package/dist/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/dist/packlets/ai-assist/imageGenerationClient.js +17 -2
- package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -1
- package/dist/packlets/ai-assist/index.js +3 -1
- package/dist/packlets/ai-assist/index.js.map +1 -1
- package/dist/packlets/ai-assist/listModelsClient.js +19 -1
- package/dist/packlets/ai-assist/listModelsClient.js.map +1 -1
- package/dist/packlets/ai-assist/model.js.map +1 -1
- package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +200 -0
- package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
- package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js +137 -0
- package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
- package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js +156 -0
- package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
- package/dist/packlets/ai-assist/promptCacheUsageMath.js +124 -0
- package/dist/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
- package/dist/packlets/ai-assist/registry.js +9 -11
- package/dist/packlets/ai-assist/registry.js.map +1 -1
- package/dist/packlets/ai-assist/streamUsageCapability.js +134 -0
- package/dist/packlets/ai-assist/streamUsageCapability.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +32 -9
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +81 -35
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/common.js +25 -1
- package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +45 -11
- package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +33 -22
- package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
- package/dist/packlets/ai-assist/streamingClient.js +20 -5
- package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
- package/dist/packlets/ai-assist/thinkingOptionsResolver.js +23 -5
- package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
- package/dist/packlets/ai-assist/toolFormats.js +80 -0
- package/dist/packlets/ai-assist/toolFormats.js.map +1 -1
- package/dist/packlets/ai-assist/toolTypes.js +21 -0
- package/dist/packlets/ai-assist/toolTypes.js.map +1 -0
- package/dist/packlets/ai-assist/usageNormalization.js +178 -0
- package/dist/packlets/ai-assist/usageNormalization.js.map +1 -0
- package/dist/packlets/ai-assist/usageTypes.js +21 -0
- package/dist/packlets/ai-assist/usageTypes.js.map +1 -0
- package/dist/packlets/mustache/index.js.map +1 -1
- package/dist/packlets/mustache/interfaces.js.map +1 -1
- package/dist/packlets/mustache/mustacheTemplate.js +91 -0
- package/dist/packlets/mustache/mustacheTemplate.js.map +1 -1
- package/dist/ts-extras.d.ts +764 -48
- package/lib/packlets/ai-assist/cacheRequest.d.ts +100 -0
- package/lib/packlets/ai-assist/cacheRequest.d.ts.map +1 -0
- package/lib/packlets/ai-assist/cacheRequest.js +123 -0
- package/lib/packlets/ai-assist/cacheRequest.js.map +1 -0
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +36 -6
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -1
- package/lib/packlets/ai-assist/chatRequestBuilders.js +75 -7
- package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
- package/lib/packlets/ai-assist/completionClient.d.ts +19 -0
- package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/completionClient.js +194 -57
- package/lib/packlets/ai-assist/completionClient.js.map +1 -1
- package/lib/packlets/ai-assist/converters.d.ts +46 -0
- package/lib/packlets/ai-assist/converters.d.ts.map +1 -1
- package/lib/packlets/ai-assist/converters.js +55 -1
- package/lib/packlets/ai-assist/converters.js.map +1 -1
- package/lib/packlets/ai-assist/embeddingClient.d.ts +9 -0
- package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/embeddingClient.js +16 -1
- package/lib/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts +9 -0
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/imageGenerationClient.js +17 -2
- package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -1
- package/lib/packlets/ai-assist/index.d.ts +7 -2
- package/lib/packlets/ai-assist/index.d.ts.map +1 -1
- package/lib/packlets/ai-assist/index.js +11 -1
- package/lib/packlets/ai-assist/index.js.map +1 -1
- package/lib/packlets/ai-assist/listModelsClient.d.ts +12 -0
- package/lib/packlets/ai-assist/listModelsClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/listModelsClient.js +19 -1
- package/lib/packlets/ai-assist/listModelsClient.js.map +1 -1
- package/lib/packlets/ai-assist/model.d.ts +81 -295
- package/lib/packlets/ai-assist/model.d.ts.map +1 -1
- package/lib/packlets/ai-assist/model.js.map +1 -1
- package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts +124 -0
- package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts.map +1 -0
- package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +208 -0
- package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
- package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts +77 -0
- package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts.map +1 -0
- package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js +143 -0
- package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
- package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts +84 -0
- package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts.map +1 -0
- package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js +163 -0
- package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
- package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts +105 -0
- package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts.map +1 -0
- package/lib/packlets/ai-assist/promptCacheUsageMath.js +130 -0
- package/lib/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
- package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
- package/lib/packlets/ai-assist/registry.js +9 -11
- package/lib/packlets/ai-assist/registry.js.map +1 -1
- package/lib/packlets/ai-assist/streamUsageCapability.d.ts +129 -0
- package/lib/packlets/ai-assist/streamUsageCapability.d.ts.map +1 -0
- package/lib/packlets/ai-assist/streamUsageCapability.js +140 -0
- package/lib/packlets/ai-assist/streamUsageCapability.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +29 -6
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +58 -14
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +81 -36
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +38 -3
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.js +25 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +42 -8
- package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +30 -19
- package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +22 -0
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.d.ts +5 -0
- package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.js +20 -5
- package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
- package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +11 -3
- package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -1
- package/lib/packlets/ai-assist/thinkingOptionsResolver.js +23 -5
- package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
- package/lib/packlets/ai-assist/toolFormats.d.ts +55 -1
- package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -1
- package/lib/packlets/ai-assist/toolFormats.js +82 -0
- package/lib/packlets/ai-assist/toolFormats.js.map +1 -1
- package/lib/packlets/ai-assist/toolTypes.d.ts +386 -0
- package/lib/packlets/ai-assist/toolTypes.d.ts.map +1 -0
- package/lib/packlets/ai-assist/toolTypes.js +22 -0
- package/lib/packlets/ai-assist/toolTypes.js.map +1 -0
- package/lib/packlets/ai-assist/usageNormalization.d.ts +58 -0
- package/lib/packlets/ai-assist/usageNormalization.d.ts.map +1 -0
- package/lib/packlets/ai-assist/usageNormalization.js +184 -0
- package/lib/packlets/ai-assist/usageNormalization.js.map +1 -0
- package/lib/packlets/ai-assist/usageTypes.d.ts +84 -0
- package/lib/packlets/ai-assist/usageTypes.d.ts.map +1 -0
- package/lib/packlets/ai-assist/usageTypes.js +22 -0
- package/lib/packlets/ai-assist/usageTypes.js.map +1 -0
- package/lib/packlets/mustache/index.d.ts +1 -1
- package/lib/packlets/mustache/index.d.ts.map +1 -1
- package/lib/packlets/mustache/index.js.map +1 -1
- package/lib/packlets/mustache/interfaces.d.ts +30 -0
- package/lib/packlets/mustache/interfaces.d.ts.map +1 -1
- package/lib/packlets/mustache/interfaces.js.map +1 -1
- package/lib/packlets/mustache/mustacheTemplate.d.ts +56 -1
- package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -1
- package/lib/packlets/mustache/mustacheTemplate.js +91 -0
- package/lib/packlets/mustache/mustacheTemplate.js.map +1 -1
- package/package.json +16 -16
- package/perf/promptCacheAnthropicBreakpoint.js +135 -0
- package/perf/promptCacheObservability.js +107 -0
- package/perf/promptCacheRoutingAb.js +105 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toolFormats.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolFormats.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAkBZ,+EAA+E;AAC/E,kBAAkB;AAClB,+EAA+E;AAE/E;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,qBAAqB,CACnC,UAAiC,EACjC,aAAgD,EAChD,YAAgD;IAEhD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;IAErD,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAC/B,OAAO,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;QAChC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,aAAa;SACjB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;SACjD,GAAG,CAAC,CAAC,CAAC,EAAsB,EAAE,WA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right (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Provider-specific tool format translation and tool resolution logic.\n * @packageDocumentation\n */\n\nimport { type JsonObject, type JsonValue } from '@fgv/ts-json-base';\n\nimport {\n type AiServerToolConfig,\n type AiToolConfig,\n type IAiClientToolConfig,\n type IAiProviderDescriptor,\n type IAiToolEnablement,\n type IAiWebSearchToolConfig\n} from './model';\n\n// ============================================================================\n// Tool resolution\n// ============================================================================\n\n/**\n * Resolves the effective tools for a completion call.\n *\n * - If per-call tools are provided, they override settings-level tools entirely.\n * - Otherwise, settings-level enabled tools are used.\n * - Only tools supported by the provider are included.\n * - Returns an empty array if no tools are enabled (= no tools sent).\n *\n * @param descriptor - The provider descriptor (used to filter by supported tools)\n * @param settingsTools - Tool enablement from provider settings (optional)\n * @param perCallTools - Per-call tool override (optional)\n * @returns The resolved list of tool configs to include in the request\n * @public\n */\nexport function resolveEffectiveTools(\n descriptor: IAiProviderDescriptor,\n settingsTools?: ReadonlyArray<IAiToolEnablement>,\n perCallTools?: ReadonlyArray<AiServerToolConfig>\n): ReadonlyArray<AiServerToolConfig> {\n const supported = new Set(descriptor.supportedTools);\n\n if (perCallTools !== undefined) {\n return perCallTools.filter((t) => supported.has(t.type));\n }\n\n if (settingsTools === undefined) {\n return [];\n }\n\n return settingsTools\n .filter((e) => e.enabled && supported.has(e.type))\n .map((e): AiServerToolConfig => e.config ?? { type: e.type });\n}\n\n// ============================================================================\n// OpenAI / xAI Responses API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction webSearchToResponsesApi(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = { type: 'web_search' };\n\n if (config.allowedDomains || config.blockedDomains) {\n const filters: Record<string, unknown> = {};\n if (config.allowedDomains) {\n filters.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n filters.excluded_domains = [...config.blockedDomains];\n }\n tool.filters = filters;\n }\n\n if (config.enableImageUnderstanding) {\n tool.enable_image_understanding = true;\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction clientToolToResponsesApi(config: IAiClientToolConfig): JsonObject {\n return {\n type: 'function',\n name: config.name,\n description: config.description,\n parameters: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the xAI/OpenAI Responses API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toResponsesApiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToResponsesApi(t);\n case 'client_tool':\n return clientToolToResponsesApi(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Anthropic Messages API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the Anthropic Messages API.\n * @internal\n */\nfunction webSearchToAnthropic(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = {\n type: 'web_search_20250305',\n name: 'web_search'\n };\n\n if (config.maxUses !== undefined) {\n tool.max_uses = config.maxUses;\n }\n if (config.allowedDomains) {\n tool.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n tool.blocked_domains = [...config.blockedDomains];\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the Anthropic Messages API.\n * Note: Anthropic client tools have no `type` field (unlike server tools).\n * @internal\n */\nfunction clientToolToAnthropic(config: IAiClientToolConfig): JsonObject {\n return {\n name: config.name,\n description: config.description,\n input_schema: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the Anthropic Messages API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toAnthropicTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToAnthropic(t);\n case 'client_tool':\n return clientToolToAnthropic(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Gemini generateContent API format\n// ============================================================================\n\n/**\n * Sanitizes a draft-07 JSON Schema (as emitted by `JsonSchema.object(...).toJson()`)\n * into the OpenAPI 3.0 Schema Object subset that Gemini's `function_declarations[].parameters`\n * accepts.\n *\n * @remarks\n * Gemini's function-declaration schema is **not** full JSON Schema — it is a subset of\n * the OpenAPI 3.0 Schema Object and **rejects** (rather than ignores) draft-07-only\n * keywords. `JsonSchema` objects are strict-by-default, so `.toJson()` emits\n * `additionalProperties: false` on every object node, which 400s the whole request on\n * Gemini. This helper recursively strips the unsupported keywords so any\n * `JsonSchema`-authored client tool works on Gemini without consumer awareness of the\n * dialect difference. Stripping is infallible, so it returns a plain value rather than a\n * `Result`.\n *\n * `additionalProperties` and `$schema` are stripped only where they appear as schema\n * *keywords* (siblings of `type`/`properties`/etc.). Inside a `properties` map the keys\n * are user-defined parameter names, not keywords, so they are preserved verbatim while\n * each property's subschema value is still recursively sanitized — a tool parameter\n * legitimately named `additionalProperties` survives.\n *\n * @internal\n */\n/**\n * The non-`null` member of a draft-07 nullable `type` union, or `undefined` when `type` is\n * not one.\n *\n * @remarks\n * Deliberately narrow: only the two-member `[<type>, 'null']` shape `JsonSchema` emits is\n * recognised. A general union has no OpenAPI equivalent, so translating one would be\n * inventing a meaning — it is passed through unchanged and Gemini refuses it, which is the\n * honest outcome.\n * @internal\n */\nfunction _nullableUnionMember(type: JsonValue | undefined): string | undefined {\n if (!Array.isArray(type) || type.length !== 2 || !type.includes('null')) {\n return undefined;\n }\n const other: JsonValue | undefined = type.find((member) => member !== 'null');\n return typeof other === 'string' ? other : undefined;\n}\n\nexport function toGeminiParameterSchema(schema: JsonValue): JsonValue {\n if (Array.isArray(schema)) {\n return schema.map(toGeminiParameterSchema);\n }\n if (schema !== null && typeof schema === 'object') {\n const out: JsonObject = {};\n // Nullability is spelled differently in the two dialects and they are mutually\n // exclusive: draft-07 (and OpenAI strict mode) wants `type: ['string', 'null']`,\n // OpenAPI 3.0 (and Gemini) wants `type: 'string'` + `nullable: true` and rejects the\n // union array. This is the same class of translation as the `additionalProperties`\n // strip above — a dialect difference the consumer should not have to know about.\n const nullableType: string | undefined = _nullableUnionMember(schema.type);\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'additionalProperties' || key === '$schema') {\n continue;\n }\n if (nullableType !== undefined && key === 'type') {\n out.type = nullableType;\n out.nullable = true;\n continue;\n }\n if (nullableType !== undefined && key === 'enum' && Array.isArray(value)) {\n // A nullable enum carries `null` among its values in draft-07. OpenAPI expresses\n // that with `nullable` alone, so the member is dropped rather than sent as a value\n // Gemini would reject.\n out.enum = value.filter((member) => member !== null);\n continue;\n }\n if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {\n // `properties` maps user-defined parameter names to subschemas: recurse each\n // subschema value but never treat a parameter name as a strippable keyword.\n const properties: JsonObject = {};\n for (const [name, propSchema] of Object.entries(value)) {\n properties[name] = toGeminiParameterSchema(propSchema);\n }\n out[key] = properties;\n } else {\n out[key] = toGeminiParameterSchema(value);\n }\n }\n return out;\n }\n return schema;\n}\n\n/**\n * Formats tool configs for the Gemini generateContent API.\n *\n * @remarks\n * Gemini uses `google_search` for search grounding (no per-tool config).\n * Client-defined tools are accumulated into a single `function_declarations` entry.\n * Each client tool's parameters schema is sanitized to Gemini's OpenAPI-subset\n * dialect via {@link toGeminiParameterSchema} (the raw draft-07 `.toJson()` output\n * carries `additionalProperties`, which Gemini rejects).\n *\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toGeminiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n const result: JsonObject[] = [];\n const functionDeclarations: JsonObject[] = [];\n\n for (const t of tools) {\n switch (t.type) {\n case 'web_search':\n result.push({ google_search: {} } as JsonObject);\n break;\n case 'client_tool':\n functionDeclarations.push({\n name: t.name,\n description: t.description,\n parameters: toGeminiParameterSchema(t.parametersSchema.toJson())\n } as JsonObject);\n break;\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n result.push({ type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject);\n }\n }\n }\n\n if (functionDeclarations.length > 0) {\n result.push({ function_declarations: functionDeclarations } as JsonObject);\n }\n\n return result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"toolFormats.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolFormats.ts"],"names":[],"mappings":"A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R,qFAAqF;YACrF,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,WAAW,GAAU,CAAC,CAAC;gBAC7B,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,EAAE,EAAgB,CAAC,CAAC;YAChF,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,oBAAoB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpC,MAAM,CAAC,IAAI,CAAC,EAAE,qBAAqB,EAAE,oBAAoB,EAAgB,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Provider-specific tool format translation and tool resolution logic.\n * @packageDocumentation\n */\n\nimport { type JsonObject, type JsonValue } from '@fgv/ts-json-base';\nimport { type Result, fail, succeed } from '@fgv/ts-utils';\n\nimport { type IAiProviderDescriptor } from './model';\nimport {\n type AiServerToolConfig,\n type AiServerToolType,\n type AiToolConfig,\n type AiToolConflictPolicy,\n type IAiClientTool,\n type IAiClientToolConfig,\n type IAiToolConflictReport,\n type IAiToolEnablement,\n type IAiWebSearchToolConfig\n} from './toolTypes';\n\n// ============================================================================\n// Tool resolution\n// ============================================================================\n\n/**\n * Resolves the effective tools for a completion call.\n *\n * - If per-call tools are provided, they override settings-level tools entirely.\n * - Otherwise, settings-level enabled tools are used.\n * - Only tools supported by the provider are included.\n * - Returns an empty array if no tools are enabled (= no tools sent).\n *\n * @param descriptor - The provider descriptor (used to filter by supported tools)\n * @param settingsTools - Tool enablement from provider settings (optional)\n * @param perCallTools - Per-call tool override (optional)\n * @returns The resolved list of tool configs to include in the request\n * @public\n */\nexport function resolveEffectiveTools(\n descriptor: IAiProviderDescriptor,\n settingsTools?: ReadonlyArray<IAiToolEnablement>,\n perCallTools?: ReadonlyArray<AiServerToolConfig>\n): ReadonlyArray<AiServerToolConfig> {\n const supported = new Set(descriptor.supportedTools);\n\n if (perCallTools !== undefined) {\n return perCallTools.filter((t) => supported.has(t.type));\n }\n\n if (settingsTools === undefined) {\n return [];\n }\n\n return settingsTools\n .filter((e) => e.enabled && supported.has(e.type))\n .map((e): AiServerToolConfig => e.config ?? { type: e.type });\n}\n\n/**\n * The default {@link AiAssist.AiToolConflictPolicy} applied when a caller passes none.\n *\n * @remarks\n * Keeping the client tools is the right default because they are what the host\n * registered explicitly for *this* turn, while a built-in server tool is a\n * per-provider nicety the same host would get on some providers and not others.\n * Dropping the nicety degrades a turn; dropping the client tools changes what the\n * turn can do.\n * @public\n */\nexport const defaultToolConflictPolicy: AiToolConflictPolicy = 'drop-server-tools';\n\n/**\n * The outcome of {@link AiAssist.resolveToolConflicts}: the tools that survived,\n * plus the report of what did not.\n * @public\n */\nexport interface IAiResolvedToolConflicts {\n /** Server tools to send, after the policy was applied. */\n readonly serverTools: ReadonlyArray<AiServerToolConfig>;\n /** Client tools to send, after the policy was applied. */\n readonly clientTools: ReadonlyArray<IAiClientTool>;\n /** What the resolution did. Always populated; empty arrays mean nothing conflicted. */\n readonly report: IAiToolConflictReport;\n}\n\n/**\n * Applies a provider's declared server-tool/client-tool exclusions to one request's\n * tools.\n *\n * @remarks\n * The generic half of a rule that used to be a provider-identity branch. The\n * constraint is declared on the descriptor\n * (`IAiProviderDescriptor.serverToolsExclusiveWithClientTools`); this reads it\n * and applies `policy`, so no consumer needs to know *which* provider has the limit\n * or *what* the limit is. A descriptor that declares nothing, or a request with no\n * client tools, or one with no server tools, passes through untouched with an empty\n * report — the exclusion is about the *combination*, and either half alone is legal.\n *\n * Sibling to {@link AiAssist.resolveEffectiveTools} rather than an extension of it:\n * that function filters server tools against what the provider supports at all and\n * is used by every completion path, most of which have no client tools to weigh.\n *\n * @param descriptor - The provider descriptor carrying the declared exclusions.\n * @param serverTools - The server tools the caller wants to send, if any.\n * @param clientTools - The client tools the caller wants to send.\n * @param policy - What to do about a conflict. Defaults to\n * {@link AiAssist.defaultToolConflictPolicy}.\n * @returns `Success` with the surviving tools and a report, or `Failure` naming the\n * conflict when `policy` is `'fail'`.\n * @public\n */\nexport function resolveToolConflicts(\n descriptor: IAiProviderDescriptor,\n serverTools: ReadonlyArray<AiServerToolConfig> | undefined,\n clientTools: ReadonlyArray<IAiClientTool>,\n policy: AiToolConflictPolicy = defaultToolConflictPolicy\n): Result<IAiResolvedToolConflicts> {\n const present = serverTools ?? [];\n const exclusive = new Set(descriptor.serverToolsExclusiveWithClientTools ?? []);\n const conflicting: ReadonlyArray<AiServerToolType> =\n clientTools.length > 0 ? present.filter((t) => exclusive.has(t.type)).map((t) => t.type) : [];\n\n if (conflicting.length === 0) {\n return succeed({\n serverTools: present,\n clientTools,\n report: { policy, droppedServerTools: [], droppedClientTools: [] }\n });\n }\n\n // Name every conflicting tool, not just the first: a host reading the message is\n // deciding what to send instead, and a partial list invites a second round.\n const named = conflicting.join(', ');\n switch (policy) {\n case 'fail':\n return fail(\n `provider \"${descriptor.id}\" cannot combine server tool(s) [${named}] with client (function) tools in the same request; send one or the other`\n );\n case 'prefer-server-tools':\n return succeed({\n serverTools: present,\n clientTools: [],\n report: {\n policy,\n droppedServerTools: [],\n droppedClientTools: clientTools.map((t) => t.config.name)\n }\n });\n case 'drop-server-tools':\n return succeed({\n serverTools: present.filter((t) => !exclusive.has(t.type)),\n clientTools,\n report: { policy, droppedServerTools: conflicting, droppedClientTools: [] }\n });\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = policy;\n return fail(`unknown tool conflict policy: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n// ============================================================================\n// OpenAI / xAI Responses API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction webSearchToResponsesApi(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = { type: 'web_search' };\n\n if (config.allowedDomains || config.blockedDomains) {\n const filters: Record<string, unknown> = {};\n if (config.allowedDomains) {\n filters.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n filters.excluded_domains = [...config.blockedDomains];\n }\n tool.filters = filters;\n }\n\n if (config.enableImageUnderstanding) {\n tool.enable_image_understanding = true;\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the xAI/OpenAI Responses API.\n * @internal\n */\nfunction clientToolToResponsesApi(config: IAiClientToolConfig): JsonObject {\n return {\n type: 'function',\n name: config.name,\n description: config.description,\n parameters: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the xAI/OpenAI Responses API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toResponsesApiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToResponsesApi(t);\n case 'client_tool':\n return clientToolToResponsesApi(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Anthropic Messages API format\n// ============================================================================\n\n/**\n * Formats a web search tool config for the Anthropic Messages API.\n * @internal\n */\nfunction webSearchToAnthropic(config: IAiWebSearchToolConfig): JsonObject {\n const tool: Record<string, unknown> = {\n type: 'web_search_20250305',\n name: 'web_search'\n };\n\n if (config.maxUses !== undefined) {\n tool.max_uses = config.maxUses;\n }\n if (config.allowedDomains) {\n tool.allowed_domains = [...config.allowedDomains];\n }\n if (config.blockedDomains) {\n tool.blocked_domains = [...config.blockedDomains];\n }\n\n return tool as JsonObject;\n}\n\n/**\n * Formats a client tool config for the Anthropic Messages API.\n * Note: Anthropic client tools have no `type` field (unlike server tools).\n * @internal\n */\nfunction clientToolToAnthropic(config: IAiClientToolConfig): JsonObject {\n return {\n name: config.name,\n description: config.description,\n input_schema: config.parametersSchema.toJson()\n } as JsonObject;\n}\n\n/**\n * Formats tool configs for the Anthropic Messages API.\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toAnthropicTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n return tools.map((t) => {\n switch (t.type) {\n case 'web_search':\n return webSearchToAnthropic(t);\n case 'client_tool':\n return clientToolToAnthropic(t);\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n return { type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject;\n }\n }\n });\n}\n\n// ============================================================================\n// Gemini generateContent API format\n// ============================================================================\n\n/**\n * Sanitizes a draft-07 JSON Schema (as emitted by `JsonSchema.object(...).toJson()`)\n * into the OpenAPI 3.0 Schema Object subset that Gemini's `function_declarations[].parameters`\n * accepts.\n *\n * @remarks\n * Gemini's function-declaration schema is **not** full JSON Schema — it is a subset of\n * the OpenAPI 3.0 Schema Object and **rejects** (rather than ignores) draft-07-only\n * keywords. `JsonSchema` objects are strict-by-default, so `.toJson()` emits\n * `additionalProperties: false` on every object node, which 400s the whole request on\n * Gemini. This helper recursively strips the unsupported keywords so any\n * `JsonSchema`-authored client tool works on Gemini without consumer awareness of the\n * dialect difference. Stripping is infallible, so it returns a plain value rather than a\n * `Result`.\n *\n * `additionalProperties` and `$schema` are stripped only where they appear as schema\n * *keywords* (siblings of `type`/`properties`/etc.). Inside a `properties` map the keys\n * are user-defined parameter names, not keywords, so they are preserved verbatim while\n * each property's subschema value is still recursively sanitized — a tool parameter\n * legitimately named `additionalProperties` survives.\n *\n * @internal\n */\n/**\n * The non-`null` member of a draft-07 nullable `type` union, or `undefined` when `type` is\n * not one.\n *\n * @remarks\n * Deliberately narrow: only the two-member `[<type>, 'null']` shape `JsonSchema` emits is\n * recognised. A general union has no OpenAPI equivalent, so translating one would be\n * inventing a meaning — it is passed through unchanged and Gemini refuses it, which is the\n * honest outcome.\n * @internal\n */\nfunction _nullableUnionMember(type: JsonValue | undefined): string | undefined {\n if (!Array.isArray(type) || type.length !== 2 || !type.includes('null')) {\n return undefined;\n }\n const other: JsonValue | undefined = type.find((member) => member !== 'null');\n return typeof other === 'string' ? other : undefined;\n}\n\nexport function toGeminiParameterSchema(schema: JsonValue): JsonValue {\n if (Array.isArray(schema)) {\n return schema.map(toGeminiParameterSchema);\n }\n if (schema !== null && typeof schema === 'object') {\n const out: JsonObject = {};\n // Nullability is spelled differently in the two dialects and they are mutually\n // exclusive: draft-07 (and OpenAI strict mode) wants `type: ['string', 'null']`,\n // OpenAPI 3.0 (and Gemini) wants `type: 'string'` + `nullable: true` and rejects the\n // union array. This is the same class of translation as the `additionalProperties`\n // strip above — a dialect difference the consumer should not have to know about.\n const nullableType: string | undefined = _nullableUnionMember(schema.type);\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'additionalProperties' || key === '$schema') {\n continue;\n }\n if (nullableType !== undefined && key === 'type') {\n out.type = nullableType;\n out.nullable = true;\n continue;\n }\n if (nullableType !== undefined && key === 'enum' && Array.isArray(value)) {\n // A nullable enum carries `null` among its values in draft-07. OpenAPI expresses\n // that with `nullable` alone, so the member is dropped rather than sent as a value\n // Gemini would reject.\n out.enum = value.filter((member) => member !== null);\n continue;\n }\n if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {\n // `properties` maps user-defined parameter names to subschemas: recurse each\n // subschema value but never treat a parameter name as a strippable keyword.\n const properties: JsonObject = {};\n for (const [name, propSchema] of Object.entries(value)) {\n properties[name] = toGeminiParameterSchema(propSchema);\n }\n out[key] = properties;\n } else {\n out[key] = toGeminiParameterSchema(value);\n }\n }\n return out;\n }\n return schema;\n}\n\n/**\n * Formats tool configs for the Gemini generateContent API.\n *\n * @remarks\n * Gemini uses `google_search` for search grounding (no per-tool config).\n * Client-defined tools are accumulated into a single `function_declarations` entry.\n * Each client tool's parameters schema is sanitized to Gemini's OpenAPI-subset\n * dialect via {@link toGeminiParameterSchema} (the raw draft-07 `.toJson()` output\n * carries `additionalProperties`, which Gemini rejects).\n *\n * @param tools - The resolved tool configs (server-side and/or client-defined)\n * @returns Provider-native tool objects for the `tools` request field\n * @public\n */\nexport function toGeminiTools(tools: ReadonlyArray<AiToolConfig>): ReadonlyArray<JsonObject> {\n const result: JsonObject[] = [];\n const functionDeclarations: JsonObject[] = [];\n\n for (const t of tools) {\n switch (t.type) {\n case 'web_search':\n result.push({ google_search: {} } as JsonObject);\n break;\n case 'client_tool':\n functionDeclarations.push({\n name: t.name,\n description: t.description,\n parameters: toGeminiParameterSchema(t.parametersSchema.toJson())\n } as JsonObject);\n break;\n /* c8 ignore next 4 - defensive coding: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = t;\n result.push({ type: `unknown:${JSON.stringify(_exhaustive)}` } as JsonObject);\n }\n }\n }\n\n if (functionDeclarations.length > 0) {\n result.push({ function_declarations: functionDeclarations } as JsonObject);\n }\n\n return result;\n}\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Copyright (c) 2026 Erik Fortune
|
|
2
|
+
//
|
|
3
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
// in the Software without restriction, including without limitation the rights
|
|
6
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
// furnished to do so, subject to the following conditions:
|
|
9
|
+
//
|
|
10
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
// copies or substantial portions of the Software.
|
|
12
|
+
//
|
|
13
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
// SOFTWARE.
|
|
20
|
+
export {};
|
|
21
|
+
//# sourceMappingURL=toolTypes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toolTypes.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/toolTypes.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Tool types for AI assist: server-side tool configs, client-defined (\"function\")\n * tools, the streaming events a tool call produces, the provider-exclusion vocabulary,\n * and the client-tool round-trip result types.\n *\n * @remarks\n * Split out of `model.ts` when the provider-exclusion types pushed that file past the\n * 2000-line lint ceiling. The cut is along a real seam rather than an arbitrary one:\n * everything here is about tools and nothing here depends on the rest of `model.ts`,\n * so the module is a leaf. `model.ts` re-exports all of it, which is why no consumer\n * import changed.\n * @packageDocumentation\n */\n\nimport { type Result } from '@fgv/ts-utils';\nimport { type JsonObject, type JsonSchema } from '@fgv/ts-json-base';\nimport type { IAiCompletionUsage } from './usageTypes';\n\n// ============================================================================\n// Server-Side Tools\n// ============================================================================\n\n/**\n * Built-in server-side tool types supported across providers.\n * @public\n */\nexport type AiServerToolType = 'web_search';\n\n/**\n * Configuration specific to web search tools.\n * @public\n */\nexport interface IAiWebSearchToolConfig {\n readonly type: 'web_search';\n /**\n * Optional: restrict search to these domains.\n * Reaches Anthropic and the OpenAI/xAI Responses API; ignored on Gemini,\n * whose `google_search` tool takes no configuration at all.\n */\n readonly allowedDomains?: ReadonlyArray<string>;\n /**\n * Optional: exclude these domains from search.\n * Same reach as {@link AiAssist.IAiWebSearchToolConfig.allowedDomains}:\n * Anthropic and OpenAI/xAI, ignored on Gemini.\n */\n readonly blockedDomains?: ReadonlyArray<string>;\n /**\n * Optional: max number of searches per request.\n * **Anthropic only** — emitted as `max_uses` by the Anthropic formatter and\n * read nowhere else, so it is silently ignored on OpenAI/xAI and Gemini.\n */\n readonly maxUses?: number;\n /**\n * Optional: enable image understanding during web search.\n * When true, the model can view and analyze images found during search.\n * Currently supported by xAI only; ignored by other providers.\n */\n readonly enableImageUnderstanding?: boolean;\n}\n\n/**\n * Union of all server-side tool configurations. Discriminated on `type`.\n * @public\n */\nexport type AiServerToolConfig = IAiWebSearchToolConfig;\n\n/**\n * Declares a tool as enabled/disabled in provider settings.\n * Tools are disabled by default — consuming apps must opt in explicitly.\n * @public\n */\nexport interface IAiToolEnablement {\n /** Which tool type. */\n readonly type: AiServerToolType;\n /** Whether this tool is enabled by default for this provider. */\n readonly enabled: boolean;\n /** Optional tool-specific configuration. */\n readonly config?: AiServerToolConfig;\n}\n\n// ============================================================================\n// Client-Defined Tools\n// ============================================================================\n\n/**\n * Behavior annotations for a client-defined tool.\n *\n * @remarks\n * These are **host-advisory-only hints** describing a tool's side-effect profile.\n * They are consumed by the host's tool loop (e.g. a before-execute gate) and are\n * **never serialized to the model** — the provider wire tool-schemas whitelist\n * `{name, description, parameters}` and ignore this field.\n *\n * Field names mirror MCP's `ToolAnnotations` (`@modelcontextprotocol/sdk`) 1:1 so\n * an MCP tool's annotations pass through unchanged. Per the MCP spec, all fields\n * are hints — a host should never make tool-use decisions based on annotations\n * received from an untrusted server without its own validation.\n *\n * @public\n */\nexport interface IAiToolAnnotations {\n /** Optional human-readable display title for the tool. */\n readonly title?: string;\n /** Hint: the tool does not modify its environment (read-only). */\n readonly readOnlyHint?: boolean;\n /** Hint: the tool may perform destructive updates (only meaningful when not read-only). */\n readonly destructiveHint?: boolean;\n /** Hint: repeated calls with the same arguments have no additional effect. */\n readonly idempotentHint?: boolean;\n /** Hint: the tool interacts with an open world of external entities. */\n readonly openWorldHint?: boolean;\n}\n\n/**\n * Configuration for a client-defined (harness-supplied) tool.\n *\n * @remarks\n * The `parametersSchema` is the single source of truth for both the wire-format\n * JSON Schema sent to the provider (via `.toJson()`) and the runtime argument\n * validation (via `.validate(rawArgs)`). Use `JsonSchema.object(...)` from\n * `@fgv/ts-json-base` to author the schema as a const (e.g. `const mySchema = JsonSchema.object({...})`);\n * the static type `TParams` is then derived via `JsonSchema.Static<typeof mySchema>` —\n * no drift between wire schema and runtime validation.\n *\n * @public\n */\nexport interface IAiClientToolConfig<TParams = unknown> {\n /** Discriminator — always `'client_tool'`. */\n readonly type: 'client_tool';\n /** Tool name sent to the model (must be unique within a call). */\n readonly name: string;\n /** Human-readable description of what the tool does, shown to the model. */\n readonly description: string;\n /**\n * JSON Schema validator for the tool's parameters. Emits wire format via\n * `.toJson()` and validates model-returned args via `.validate(rawArgs)`.\n */\n readonly parametersSchema: JsonSchema.ISchemaValidator<TParams>;\n /**\n * Optional host-advisory behavior annotations (read-only / destructive /\n * idempotent / open-world hints + display title). Consumed by the host's\n * tool loop; never serialized to the model. See {@link AiAssist.IAiToolAnnotations}.\n */\n readonly annotations?: IAiToolAnnotations;\n}\n\n/**\n * A client-defined tool: configuration + execution callback pair.\n *\n * @remarks\n * The `execute` callback receives typed `TParams` (already validated by\n * `config.parametersSchema.validate()`) and returns a `Promise<Result<unknown>>`.\n * Thrown errors are caught via `captureAsyncResult` in the round-trip helper.\n *\n * @public\n */\nexport interface IAiClientTool<TParams = unknown> {\n /** The tool's configuration (name, description, parameters schema). */\n readonly config: IAiClientToolConfig<TParams>;\n /**\n * Execute the tool with validated parameters.\n * @param args - Typed arguments, already validated against `config.parametersSchema`.\n * @returns A `Promise<Result<unknown>>` — the result is stringified and sent back to the model.\n */\n readonly execute: (args: TParams) => Promise<Result<unknown>>;\n}\n\n/**\n * Union of all tool configurations: server-side or client-defined.\n * Discriminated on `type`.\n * @public\n */\nexport type AiToolConfig = AiServerToolConfig | IAiClientToolConfig;\n\n// ============================================================================\n// Client Tool Streaming Events\n// ============================================================================\n\n/**\n * Emitted when a client-defined tool call begins streaming. Carries the tool name\n * and optional provider-assigned call ID (Anthropic / OpenAI Responses API; absent\n * for Gemini which does not assign call IDs).\n * @public\n */\nexport interface IAiStreamToolUseStart {\n readonly type: 'client-tool-call-start';\n /** The name of the client tool being called. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier (Anthropic: `toolu_*`; OpenAI: `call_*`).\n * Absent for Gemini (correlation by name).\n */\n readonly callId?: string;\n}\n\n/**\n * Emitted when a client-defined tool call is complete and its arguments are fully\n * accumulated. The `args` object is the fully parsed JSON object — no further\n * streaming deltas follow for this call.\n * @public\n */\nexport interface IAiStreamToolUseDelta {\n readonly type: 'client-tool-call-done';\n /** The name of the client tool being called. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier. Absent for Gemini.\n */\n readonly callId?: string;\n /** The fully accumulated and parsed tool arguments. */\n readonly args: JsonObject;\n}\n\n/**\n * Emitted after a client-defined tool has been executed and the result is ready\n * to be fed back to the model in the round-trip continuation.\n * @public\n */\nexport interface IAiStreamToolUseComplete {\n readonly type: 'client-tool-result';\n /** The name of the client tool that was executed. */\n readonly toolName: string;\n /**\n * Provider-assigned call identifier. Absent for Gemini.\n */\n readonly callId?: string;\n /** The stringified result returned by the tool's execute callback. */\n readonly result: string;\n /** Whether the tool execution failed (schema validation failure, execute error, or unknown tool). */\n readonly isError: boolean;\n}\n\n// ============================================================================\n// Server/Client Tool Conflicts\n// ============================================================================\n\n/**\n * What to do when a request would combine a server tool with client (function)\n * tools on a provider that declares the two mutually exclusive (see\n * `IAiProviderDescriptor.serverToolsExclusiveWithClientTools`).\n *\n * @remarks\n * - `'drop-server-tools'` (the default) removes the offending server tools and\n * keeps every client tool. Client tools are what the host registered\n * explicitly for this turn; a built-in like grounding is a per-provider\n * nicety, and dropping it degrades the turn rather than losing it.\n * - `'prefer-server-tools'` is the mirror image: keep the server tools and drop\n * every client tool. For hosts whose turn is *about* the grounded answer.\n * - `'fail'` refuses the request up front with a message naming the conflict —\n * the behavior before this policy existed. For hosts that would rather\n * choose themselves than have either half silently disappear.\n *\n * Whichever is chosen, what actually happened is reported, never inferred: see\n * {@link AiAssist.IAiToolConflictReport}.\n * @public\n */\nexport type AiToolConflictPolicy = 'drop-server-tools' | 'prefer-server-tools' | 'fail';\n\n/**\n * What the conflict resolution did to a turn's tools.\n *\n * @remarks\n * Required on {@link AiAssist.IAiClientToolTurnResult}, not optional, for the same reason\n * `structuredOutput` is required on a completion response: an absent report is\n * three-ways ambiguous — nothing conflicted / this build predates the feature /\n * the resolution ran and said nothing — and disambiguating exactly that is what\n * it is for. A turn where nothing conflicted reports the policy that was in\n * force and two empty arrays.\n * @public\n */\nexport interface IAiToolConflictReport {\n /** The policy that was in force for this turn (the default when none was passed). */\n readonly policy: AiToolConflictPolicy;\n /** Server tool types removed from the request. Empty when nothing was dropped. */\n readonly droppedServerTools: ReadonlyArray<AiServerToolType>;\n /** Names of client tools removed from the request. Empty when nothing was dropped. */\n readonly droppedClientTools: ReadonlyArray<string>;\n}\n\n// ============================================================================\n// Client Tool Round-Trip Types\n// ============================================================================\n\n/**\n * Summary of a single client tool call within a turn: the tool name, call ID,\n * raw arguments, execution result, and whether the execution was an error.\n * @public\n */\nexport interface IAiClientToolCallSummary {\n /** The name of the tool that was called. */\n readonly toolName: string;\n /** Provider-assigned call identifier (absent for Gemini). */\n readonly callId?: string;\n /** The fully accumulated raw arguments object as parsed JSON. */\n readonly args: JsonObject;\n /** The stringified result (success value or error message). */\n readonly result: string;\n /** Whether execution failed (schema validation failure, execute error, or unknown tool). */\n readonly isError: boolean;\n}\n\n/**\n * The provider-specific continuation data needed to build the follow-up request\n * for the next round of the conversation.\n *\n * @remarks\n * `messages` are provider-native request objects (Anthropic: content-block arrays,\n * OpenAI Responses API: input items, Gemini: content parts). The continuation\n * builder in `clientToolContinuationBuilder.ts` populates this.\n *\n * @public\n */\nexport interface IAiClientToolContinuation {\n /**\n * **Cumulative** provider-native wire-format message objects covering all\n * tool rounds so far. On each turn, `executeClientToolTurn` prepends the\n * inbound `continuationMessages` so that this array always contains the\n * complete wire tail from round 1 through the current round.\n *\n * To drive a multi-round loop, simply **replace** `continuationMessages`\n * with this value — do not manually concatenate:\n *\n * ```ts\n * let tail: JsonObject[] | undefined;\n * while (true) {\n * const { events, nextTurn } = executeClientToolTurn({\n * ..., continuationMessages: tail\n * }).orThrow();\n * for await (const e of events) { /* observe *\\/ }\n * const outcome = (await nextTurn).orThrow();\n * if (!outcome.continuation) break;\n * tail = [...outcome.continuation.messages]; // replace — already cumulative\n * }\n * ```\n *\n * The exact shape is provider-native and may include provider-specific\n * blocks (e.g. Anthropic thinking/redacted_thinking/tool_use, OpenAI\n * function_call/function_call_output items, Gemini functionCall/functionResponse\n * parts). These are NOT `IChatMessage[]` and must NOT be placed in the\n * `messages` parameter — the normalized-message path strips provider-native\n * fields (thinking signatures, redacted_thinking data) that the server\n * requires for continuation validation.\n *\n * `toolCallsSummary` is per-round only (the calls executed in the current\n * turn). Only `messages` is cumulative.\n */\n readonly messages: ReadonlyArray<JsonObject>;\n /** Summary of each tool call executed in this turn (per-round, not cumulative). */\n readonly toolCallsSummary: ReadonlyArray<IAiClientToolCallSummary>;\n}\n\n/**\n * The result of a single client-tool turn: the optional continuation for the next\n * call (absent when no tool calls occurred) and whether the stream was truncated.\n * @public\n */\nexport interface IAiClientToolTurnResult {\n /**\n * The continuation data for the next round-trip. `undefined` when the model\n * completed without invoking any client tools.\n */\n readonly continuation: IAiClientToolContinuation | undefined;\n /** Whether the stream was truncated (token limit or stop reason). */\n readonly truncated: boolean;\n /** The full concatenated text from all `text-delta` events in this turn. */\n readonly fullText: string;\n /**\n * What the provider tool-conflict resolution did to this turn's tools.\n * Always present; empty arrays mean nothing conflicted.\n *\n * @remarks\n * Read this to tell the person (or the model, on a later turn) that a\n * capability they expected was unavailable — e.g. that web search was dropped\n * because the pinned model cannot ground and call functions in one request.\n */\n readonly toolConflicts: IAiToolConflictReport;\n /**\n * Token usage for this turn's provider call, when the provider reports it.\n *\n * @remarks\n * The same `IAiCompletionUsage` the plain completion paths carry — normalized\n * cache reads/writes, output and total input tokens, and a `reports` level\n * saying which of those the provider is able to tell you. Sourced from the\n * terminal `done` event of the underlying stream, so it is exactly what a\n * caller watching `events` would see.\n *\n * Reading it here spares you *inspecting* the event stream, not *driving* it:\n * `nextTurn` only resolves once `events` has been iterated to completion, the\n * same as every other field on this interface.\n *\n * **One call, one usage.** `executeClientToolTurn` makes a single provider\n * call per invocation; the multi-round loop is driven by the caller\n * re-invoking with `continuationMessages`. So each result's `usage` already\n * *is* one round's usage, and a host accumulating a per-turn total sums the\n * results of its own loop. There is deliberately no `perRound` array here —\n * it could only ever have one entry.\n *\n * **Optional on purpose, unlike `toolConflicts`.** The library always knows\n * what it did to your tools, so a silent `toolConflicts` would be a defect\n * and it is required. It cannot always know what a turn cost, so a required\n * `usage` could only be satisfied by inventing one — the exact failure\n * {@link AiAssist.IAiCompletionUsage.reports} exists to prevent.\n *\n * Absent means **no normalized usage is being exposed**, which covers two\n * cases, the same as on {@link AiAssist.IAiCompletionResponse.usage} and\n * {@link AiAssist.IAiStreamDone.usage}:\n *\n * - the provider reported nothing; or\n * - the provider reported something the library declines to normalize,\n * because this descriptor is outside\n * {@link AiAssist.supportsCacheUsageReporting}. Groq, Mistral, Ollama and\n * self-hosted `openai-compat` share the OpenAI-format adapter but have\n * unverified usage shapes, so a raw `usage` block from one of them is\n * dropped rather than stamped with a cache-reporting level it may not\n * have earned.\n *\n * Either way it is never a fabricated zero. If you need to tell the two\n * apart, the descriptor answers it: the second case is a property of the\n * provider you picked, not of the turn.\n */\n readonly usage?: IAiCompletionUsage;\n}\n"]}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Copyright (c) 2026 Erik Fortune
|
|
2
|
+
//
|
|
3
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
// in the Software without restriction, including without limitation the rights
|
|
6
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
// furnished to do so, subject to the following conditions:
|
|
9
|
+
//
|
|
10
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
// copies or substantial portions of the Software.
|
|
12
|
+
//
|
|
13
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
// SOFTWARE.
|
|
20
|
+
import { Validators } from '@fgv/ts-utils';
|
|
21
|
+
const anthropicRawUsage = Validators.object({
|
|
22
|
+
input_tokens: Validators.number,
|
|
23
|
+
output_tokens: Validators.number.optional(),
|
|
24
|
+
cache_creation_input_tokens: Validators.number.optional(),
|
|
25
|
+
cache_read_input_tokens: Validators.number.optional()
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* Normalizes an Anthropic Messages API `usage` block. Anthropic always
|
|
29
|
+
* reports both reads and writes, so `reports` is unconditionally
|
|
30
|
+
* `'reads-and-writes'` — an absent `cache_creation_input_tokens` genuinely
|
|
31
|
+
* means zero tokens were written this request.
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
export function normalizeAnthropicUsage(raw) {
|
|
35
|
+
if (raw === undefined) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
const parsed = anthropicRawUsage.validate(raw);
|
|
39
|
+
if (parsed.isFailure()) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
const { input_tokens: uncachedInputTokens, output_tokens: outputTokens, cache_creation_input_tokens: cacheWriteTokens, cache_read_input_tokens: cachedInputTokens } = parsed.value;
|
|
43
|
+
return {
|
|
44
|
+
reports: 'reads-and-writes',
|
|
45
|
+
uncachedInputTokens,
|
|
46
|
+
cachedInputTokens,
|
|
47
|
+
cacheWriteTokens,
|
|
48
|
+
outputTokens,
|
|
49
|
+
totalInputTokens: cachedInputTokens !== undefined ? uncachedInputTokens + cachedInputTokens : undefined,
|
|
50
|
+
raw
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
const openAiChatPromptTokensDetails = Validators.object({ cached_tokens: Validators.number.optional() });
|
|
54
|
+
const openAiChatRawUsage = Validators.object({
|
|
55
|
+
prompt_tokens: Validators.number.optional(),
|
|
56
|
+
completion_tokens: Validators.number.optional(),
|
|
57
|
+
prompt_tokens_details: openAiChatPromptTokensDetails.optional()
|
|
58
|
+
});
|
|
59
|
+
/**
|
|
60
|
+
* Normalizes an OpenAI/xAI Chat Completions `usage` block. `reports` is
|
|
61
|
+
* unconditionally `'reads'`: `cache_write_tokens` does not exist on this API
|
|
62
|
+
* for any provider reached through it, so `cacheWriteTokens` is never set —
|
|
63
|
+
* not even to `0`.
|
|
64
|
+
* @internal
|
|
65
|
+
*/
|
|
66
|
+
export function normalizeOpenAiChatUsage(raw) {
|
|
67
|
+
if (raw === undefined) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
const parsed = openAiChatRawUsage.validate(raw);
|
|
71
|
+
if (parsed.isFailure()) {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
const { prompt_tokens: promptTokens, completion_tokens: outputTokens, prompt_tokens_details } = parsed.value;
|
|
75
|
+
const cachedInputTokens = prompt_tokens_details === null || prompt_tokens_details === void 0 ? void 0 : prompt_tokens_details.cached_tokens;
|
|
76
|
+
const uncachedInputTokens = cachedInputTokens !== undefined && promptTokens !== undefined
|
|
77
|
+
? promptTokens - cachedInputTokens
|
|
78
|
+
: undefined;
|
|
79
|
+
return {
|
|
80
|
+
reports: 'reads',
|
|
81
|
+
uncachedInputTokens,
|
|
82
|
+
cachedInputTokens,
|
|
83
|
+
outputTokens,
|
|
84
|
+
totalInputTokens: uncachedInputTokens !== undefined && cachedInputTokens !== undefined
|
|
85
|
+
? uncachedInputTokens + cachedInputTokens
|
|
86
|
+
: undefined,
|
|
87
|
+
raw
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
const openAiResponsesInputTokensDetails = Validators.object({
|
|
91
|
+
cached_tokens: Validators.number.optional(),
|
|
92
|
+
cache_write_tokens: Validators.number.optional()
|
|
93
|
+
});
|
|
94
|
+
const openAiResponsesRawUsage = Validators.object({
|
|
95
|
+
input_tokens: Validators.number.optional(),
|
|
96
|
+
output_tokens: Validators.number.optional(),
|
|
97
|
+
input_tokens_details: openAiResponsesInputTokensDetails.optional()
|
|
98
|
+
});
|
|
99
|
+
/**
|
|
100
|
+
* Normalizes an OpenAI/xAI Responses API `usage` block. This route is shared
|
|
101
|
+
* by two providers that disagree about write reporting — OpenAI always sends
|
|
102
|
+
* `cache_write_tokens` (even when `0`), xAI never does — so `reports` is
|
|
103
|
+
* derived from field **presence**, not from provider identity: a wire that
|
|
104
|
+
* sends the field, however small its value, is `'reads-and-writes'`; a wire
|
|
105
|
+
* that omits it entirely is `'reads'`.
|
|
106
|
+
* @internal
|
|
107
|
+
*/
|
|
108
|
+
export function normalizeOpenAiResponsesUsage(raw) {
|
|
109
|
+
if (raw === undefined) {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
const parsed = openAiResponsesRawUsage.validate(raw);
|
|
113
|
+
if (parsed.isFailure()) {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
const { input_tokens: inputTokens, output_tokens: outputTokens, input_tokens_details } = parsed.value;
|
|
117
|
+
const cachedInputTokens = input_tokens_details === null || input_tokens_details === void 0 ? void 0 : input_tokens_details.cached_tokens;
|
|
118
|
+
const cacheWriteTokens = input_tokens_details === null || input_tokens_details === void 0 ? void 0 : input_tokens_details.cache_write_tokens;
|
|
119
|
+
const reports = cacheWriteTokens !== undefined ? 'reads-and-writes' : 'reads';
|
|
120
|
+
const uncachedInputTokens = cachedInputTokens !== undefined && inputTokens !== undefined
|
|
121
|
+
? inputTokens - cachedInputTokens
|
|
122
|
+
: undefined;
|
|
123
|
+
return {
|
|
124
|
+
reports,
|
|
125
|
+
uncachedInputTokens,
|
|
126
|
+
cachedInputTokens,
|
|
127
|
+
cacheWriteTokens,
|
|
128
|
+
outputTokens,
|
|
129
|
+
totalInputTokens: uncachedInputTokens !== undefined && cachedInputTokens !== undefined
|
|
130
|
+
? uncachedInputTokens + cachedInputTokens
|
|
131
|
+
: undefined,
|
|
132
|
+
raw
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const geminiRawUsage = Validators.object({
|
|
136
|
+
promptTokenCount: Validators.number.optional(),
|
|
137
|
+
candidatesTokenCount: Validators.number.optional(),
|
|
138
|
+
cachedContentTokenCount: Validators.number.optional()
|
|
139
|
+
});
|
|
140
|
+
/**
|
|
141
|
+
* Normalizes a Gemini `usageMetadata` block. `reports` is unconditionally
|
|
142
|
+
* `'reads'` — Gemini has no cache-write concept in a `generateContent` call;
|
|
143
|
+
* writes happen out-of-band via the explicit `cachedContents` resource,
|
|
144
|
+
* out of scope per the design (§10).
|
|
145
|
+
*
|
|
146
|
+
* @remarks
|
|
147
|
+
* The Gemini-specific footgun: `promptTokenCount` already **includes**
|
|
148
|
+
* `cachedContentTokenCount` (it is the total effective prompt size), unlike
|
|
149
|
+
* OpenAI where the cached figure sits in a sub-object alongside a separate
|
|
150
|
+
* total. `uncachedInputTokens` subtracts to correct for it — but only when
|
|
151
|
+
* `cachedContentTokenCount` is itself present, per the module's absent-means-
|
|
152
|
+
* absent rule.
|
|
153
|
+
* @internal
|
|
154
|
+
*/
|
|
155
|
+
export function normalizeGeminiUsage(raw) {
|
|
156
|
+
if (raw === undefined) {
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
const parsed = geminiRawUsage.validate(raw);
|
|
160
|
+
if (parsed.isFailure()) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
const { promptTokenCount, candidatesTokenCount: outputTokens, cachedContentTokenCount: cachedInputTokens } = parsed.value;
|
|
164
|
+
const uncachedInputTokens = cachedInputTokens !== undefined && promptTokenCount !== undefined
|
|
165
|
+
? promptTokenCount - cachedInputTokens
|
|
166
|
+
: undefined;
|
|
167
|
+
return {
|
|
168
|
+
reports: 'reads',
|
|
169
|
+
uncachedInputTokens,
|
|
170
|
+
cachedInputTokens,
|
|
171
|
+
outputTokens,
|
|
172
|
+
totalInputTokens: uncachedInputTokens !== undefined && cachedInputTokens !== undefined
|
|
173
|
+
? uncachedInputTokens + cachedInputTokens
|
|
174
|
+
: undefined,
|
|
175
|
+
raw
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
//# sourceMappingURL=usageNormalization.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usageNormalization.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/usageNormalization.ts"],"names":[],"mappings":"AAAA,k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AClE,CAAC,CAAC,mBAAmB,GAAG,iBAAiB;YACzC,CAAC,CAAC,SAAS;QACf,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Per-wire-shape `usage` block normalization, shared by the non-streaming\n * adapters (`completionClient.ts`) and the streaming adapters\n * (`streamingAdapters/*.ts`) so the same JSON layout is parsed once.\n *\n * @remarks\n * Every function here follows one rule throughout: a field that is absent\n * from the wire response stays absent on {@link AiAssist.IAiCompletionUsage} —\n * never defaulted to `0`, and never derived from a sibling field unless the\n * value that sibling would need is itself known. See `IAiCompletionUsage`\n * for why.\n * @packageDocumentation\n */\n\n/* eslint-disable @typescript-eslint/naming-convention -- wire field names are snake_case */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\nimport { type Validator, Validators } from '@fgv/ts-utils';\n\nimport { type AiCacheReportingLevel, type IAiCompletionUsage } from './usageTypes';\n\n// ============================================================================\n// Anthropic Messages\n// ============================================================================\n\n/** @internal */\ninterface IAnthropicRawUsage {\n readonly input_tokens: number;\n readonly output_tokens?: number;\n readonly cache_creation_input_tokens?: number;\n readonly cache_read_input_tokens?: number;\n}\n\nconst anthropicRawUsage: Validator<IAnthropicRawUsage> = Validators.object<IAnthropicRawUsage>({\n input_tokens: Validators.number,\n output_tokens: Validators.number.optional(),\n cache_creation_input_tokens: Validators.number.optional(),\n cache_read_input_tokens: Validators.number.optional()\n});\n\n/**\n * Normalizes an Anthropic Messages API `usage` block. Anthropic always\n * reports both reads and writes, so `reports` is unconditionally\n * `'reads-and-writes'` — an absent `cache_creation_input_tokens` genuinely\n * means zero tokens were written this request.\n * @internal\n */\nexport function normalizeAnthropicUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = anthropicRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n input_tokens: uncachedInputTokens,\n output_tokens: outputTokens,\n cache_creation_input_tokens: cacheWriteTokens,\n cache_read_input_tokens: cachedInputTokens\n } = parsed.value;\n return {\n reports: 'reads-and-writes',\n uncachedInputTokens,\n cachedInputTokens,\n cacheWriteTokens,\n outputTokens,\n totalInputTokens: cachedInputTokens !== undefined ? uncachedInputTokens + cachedInputTokens : undefined,\n raw\n };\n}\n\n// ============================================================================\n// OpenAI / xAI Chat Completions\n// ============================================================================\n\n/** @internal */\ninterface IOpenAiChatPromptTokensDetails {\n readonly cached_tokens?: number;\n}\n\nconst openAiChatPromptTokensDetails: Validator<IOpenAiChatPromptTokensDetails> =\n Validators.object<IOpenAiChatPromptTokensDetails>({ cached_tokens: Validators.number.optional() });\n\n/** @internal */\ninterface IOpenAiChatRawUsage {\n readonly prompt_tokens?: number;\n readonly completion_tokens?: number;\n readonly prompt_tokens_details?: IOpenAiChatPromptTokensDetails;\n}\n\nconst openAiChatRawUsage: Validator<IOpenAiChatRawUsage> = Validators.object<IOpenAiChatRawUsage>({\n prompt_tokens: Validators.number.optional(),\n completion_tokens: Validators.number.optional(),\n prompt_tokens_details: openAiChatPromptTokensDetails.optional()\n});\n\n/**\n * Normalizes an OpenAI/xAI Chat Completions `usage` block. `reports` is\n * unconditionally `'reads'`: `cache_write_tokens` does not exist on this API\n * for any provider reached through it, so `cacheWriteTokens` is never set —\n * not even to `0`.\n * @internal\n */\nexport function normalizeOpenAiChatUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = openAiChatRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n prompt_tokens: promptTokens,\n completion_tokens: outputTokens,\n prompt_tokens_details\n } = parsed.value;\n const cachedInputTokens = prompt_tokens_details?.cached_tokens;\n const uncachedInputTokens =\n cachedInputTokens !== undefined && promptTokens !== undefined\n ? promptTokens - cachedInputTokens\n : undefined;\n return {\n reports: 'reads',\n uncachedInputTokens,\n cachedInputTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n\n// ============================================================================\n// OpenAI / xAI Responses\n// ============================================================================\n\n/** @internal */\ninterface IOpenAiResponsesInputTokensDetails {\n readonly cached_tokens?: number;\n readonly cache_write_tokens?: number;\n}\n\nconst openAiResponsesInputTokensDetails: Validator<IOpenAiResponsesInputTokensDetails> =\n Validators.object<IOpenAiResponsesInputTokensDetails>({\n cached_tokens: Validators.number.optional(),\n cache_write_tokens: Validators.number.optional()\n });\n\n/** @internal */\ninterface IOpenAiResponsesRawUsage {\n readonly input_tokens?: number;\n readonly output_tokens?: number;\n readonly input_tokens_details?: IOpenAiResponsesInputTokensDetails;\n}\n\nconst openAiResponsesRawUsage: Validator<IOpenAiResponsesRawUsage> =\n Validators.object<IOpenAiResponsesRawUsage>({\n input_tokens: Validators.number.optional(),\n output_tokens: Validators.number.optional(),\n input_tokens_details: openAiResponsesInputTokensDetails.optional()\n });\n\n/**\n * Normalizes an OpenAI/xAI Responses API `usage` block. This route is shared\n * by two providers that disagree about write reporting — OpenAI always sends\n * `cache_write_tokens` (even when `0`), xAI never does — so `reports` is\n * derived from field **presence**, not from provider identity: a wire that\n * sends the field, however small its value, is `'reads-and-writes'`; a wire\n * that omits it entirely is `'reads'`.\n * @internal\n */\nexport function normalizeOpenAiResponsesUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = openAiResponsesRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const { input_tokens: inputTokens, output_tokens: outputTokens, input_tokens_details } = parsed.value;\n const cachedInputTokens = input_tokens_details?.cached_tokens;\n const cacheWriteTokens = input_tokens_details?.cache_write_tokens;\n const reports: AiCacheReportingLevel = cacheWriteTokens !== undefined ? 'reads-and-writes' : 'reads';\n const uncachedInputTokens =\n cachedInputTokens !== undefined && inputTokens !== undefined\n ? inputTokens - cachedInputTokens\n : undefined;\n return {\n reports,\n uncachedInputTokens,\n cachedInputTokens,\n cacheWriteTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n\n// ============================================================================\n// Gemini generateContent / streamGenerateContent\n// ============================================================================\n\n/** @internal */\ninterface IGeminiRawUsage {\n readonly promptTokenCount?: number;\n readonly candidatesTokenCount?: number;\n readonly cachedContentTokenCount?: number;\n}\n\nconst geminiRawUsage: Validator<IGeminiRawUsage> = Validators.object<IGeminiRawUsage>({\n promptTokenCount: Validators.number.optional(),\n candidatesTokenCount: Validators.number.optional(),\n cachedContentTokenCount: Validators.number.optional()\n});\n\n/**\n * Normalizes a Gemini `usageMetadata` block. `reports` is unconditionally\n * `'reads'` — Gemini has no cache-write concept in a `generateContent` call;\n * writes happen out-of-band via the explicit `cachedContents` resource,\n * out of scope per the design (§10).\n *\n * @remarks\n * The Gemini-specific footgun: `promptTokenCount` already **includes**\n * `cachedContentTokenCount` (it is the total effective prompt size), unlike\n * OpenAI where the cached figure sits in a sub-object alongside a separate\n * total. `uncachedInputTokens` subtracts to correct for it — but only when\n * `cachedContentTokenCount` is itself present, per the module's absent-means-\n * absent rule.\n * @internal\n */\nexport function normalizeGeminiUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = geminiRawUsage.validate(raw);\n if (parsed.isFailure()) {\n return undefined;\n }\n const {\n promptTokenCount,\n candidatesTokenCount: outputTokens,\n cachedContentTokenCount: cachedInputTokens\n } = parsed.value;\n const uncachedInputTokens =\n cachedInputTokens !== undefined && promptTokenCount !== undefined\n ? promptTokenCount - cachedInputTokens\n : undefined;\n return {\n reports: 'reads',\n uncachedInputTokens,\n cachedInputTokens,\n outputTokens,\n totalInputTokens:\n uncachedInputTokens !== undefined && cachedInputTokens !== undefined\n ? uncachedInputTokens + cachedInputTokens\n : undefined,\n raw\n };\n}\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Copyright (c) 2026 Erik Fortune
|
|
2
|
+
//
|
|
3
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
// in the Software without restriction, including without limitation the rights
|
|
6
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
// furnished to do so, subject to the following conditions:
|
|
9
|
+
//
|
|
10
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
// copies or substantial portions of the Software.
|
|
12
|
+
//
|
|
13
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
// SOFTWARE.
|
|
20
|
+
export {};
|
|
21
|
+
//# sourceMappingURL=usageTypes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usageTypes.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/usageTypes.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Completion usage types: what a provider's wire shape can report about\n * prompt-cache reads/writes, and the normalized token accounting built from it.\n *\n * @remarks\n * Its own module rather than part of `model.ts` because it depends on nothing\n * there — `model.ts` imports it, not the reverse — and because `model.ts` was\n * at the `max-lines` cap. Same rationale as `structuredOutputTypes.ts`.\n * @packageDocumentation\n */\n\nimport { type JsonObject } from '@fgv/ts-json-base';\n\n/**\n * What a provider's wire shape is able to report about prompt-cache usage,\n * given that a usage block was present on the response at all.\n *\n * @remarks\n * `'reads'` — cache reads are reported; cache writes cannot be (either the API\n * has no write concept, or the field structurally does not exist on this route).\n * `'reads-and-writes'` — both reads and writes are reported.\n *\n * There is deliberately no `'none'` member: \"no usage was reported at all\" is\n * already expressed by {@link AiAssist.IAiCompletionResponse.usage} itself\n * being absent, and a third value here would be a second, reachable-only-via-\n * bug way to say the same thing — check `usage === undefined`, not a `reports`\n * value, to detect that case.\n *\n * See {@link AiAssist.IAiCompletionUsage.reports} for why this is required\n * rather than optional.\n * @public\n */\nexport type AiCacheReportingLevel = 'reads' | 'reads-and-writes';\n\n/**\n * Token accounting for a completion, normalized across providers.\n *\n * @remarks\n * Every field but `reports` is best-effort: a provider's wire shape reports\n * what it reports, and an absent field here means the corresponding wire\n * field was itself absent — never a guessed zero. See `reports` for the one\n * exception this rule has to be explicit about.\n * @public\n */\nexport interface IAiCompletionUsage {\n /**\n * What this response's wire shape *can* report about caching.\n *\n * @remarks\n * **Required, not optional.** An optional field would make an absent\n * `cacheWriteTokens` three-ways ambiguous — no write happened / this API\n * cannot report writes / a build predating the field — and disambiguating\n * exactly that is what this field exists for. Under `'reads-and-writes'`, an\n * absent `cacheWriteTokens` genuinely means zero tokens were written this\n * request — the actionable signal that a breakpoint did not take. Under\n * `'reads'` it means the API cannot say, and inferring \"zero writes\" from it\n * would be a fabricated fact. Same remedy as\n * `IAiCompletionResponse.structuredOutput`.\n */\n readonly reports: AiCacheReportingLevel;\n /** Input tokens **not** served from cache. Normalized — see `CAPABILITIES.md` for the per-provider table. */\n readonly uncachedInputTokens?: number;\n /** Input tokens served from cache. */\n readonly cachedInputTokens?: number;\n /**\n * Input tokens written to cache.\n *\n * @remarks\n * Two absence cases, disambiguated by `reports` — never by a `0` this field\n * itself carries:\n * - **`reports: 'reads-and-writes'` and this field absent** — the wire\n * genuinely reported zero tokens written. Treat absence as `0`, not as\n * unknown; this is the actionable \"the breakpoint did not take\" signal.\n * - **`reports: 'reads'` and this field absent** — the API cannot report\n * writes on this route at all (structurally unfillable, e.g. OpenAI/xAI\n * Chat Completions). Never defaulted to `0` here — that would fabricate a\n * fact the wire never stated.\n */\n readonly cacheWriteTokens?: number;\n /** Generated output tokens. */\n readonly outputTokens?: number;\n /** Total input = uncached + cached, when both are known. */\n readonly totalInputTokens?: number;\n /** The provider's own usage block, unnormalized, for anything this shape drops. */\n readonly raw?: JsonObject;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/mustache/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/mustache/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAaH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport {\n IContextValidationResult,\n IMissingVariableDetail,\n IMustacheTemplateOptions,\n IRenderedSegment,\n IRenderedTemplate,\n IVariableRef,\n MustacheEscapeStrategy,\n MustacheTokenType\n} from './interfaces';\n\nexport { MustacheTemplate } from './mustacheTemplate';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../src/packlets/mustache/interfaces.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D;;;;;;;;;;;;;;;;;;;;GAoBG;;
|
|
1
|
+
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../src/packlets/mustache/interfaces.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D;;;;;;;;;;;;;;;;;;;;GAoBG;;AA8LH,oBAAoB","sourcesContent":["/* c8 ignore start - Type definitions only, no runtime code */\n/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Type of a Mustache token as returned by Mustache.parse()\n * @public\n */\nexport type MustacheTokenType =\n | 'text' // Raw text\n | 'name' // {{ variable }} - escaped value\n | '&' // {{{ variable }}} or {{& variable }} - unescaped value\n | '#' // {{# section }} - section start\n | '^' // {{^ section }} - inverted section\n | '!' // {{! comment }} - comment\n | '>' // {{> partial }} - partial\n | '='; // {{= =}} - set delimiter\n\n/**\n * One contiguous run of the rendered output, attributed to what produced it.\n * @public\n */\nexport interface IRenderedSegment {\n /** `'literal'` for template text; `'substitution'` for an interpolated value. */\n readonly kind: 'literal' | 'substitution';\n /** Variable name, when `kind` is `'substitution'`. */\n readonly name?: string;\n /** Offset into `IRenderedTemplate.text`, in UTF-16 code units. */\n readonly start: number;\n /** Length in UTF-16 code units. May be `0` for a variable that rendered empty. */\n readonly length: number;\n /** `false` for a triple-stash / `{{&}}` interpolation, which bypasses escaping. */\n readonly escaped: boolean;\n}\n\n/**\n * A render plus the map of which part of the output came from where.\n * @public\n */\nexport interface IRenderedTemplate {\n /** The rendered output — identical to what `MustacheTemplate.render` returns. */\n readonly text: string;\n /**\n * Document-ordered, contiguous and gapless: every code unit of `text` belongs to exactly one\n * segment, so concatenating them reproduces `text` exactly. That identity is verified before\n * this is returned.\n */\n readonly segments: ReadonlyArray<IRenderedSegment>;\n}\n\n/**\n * Represents a variable reference extracted from a Mustache template.\n * @public\n */\nexport interface IVariableRef {\n /**\n * The raw variable name as it appears in the template (e.g., 'user.name')\n */\n readonly name: string;\n\n /**\n * The path segments parsed from the variable name (e.g., ['user', 'name'])\n */\n readonly path: readonly string[];\n\n /**\n * The type of token this variable was extracted from\n */\n readonly tokenType: MustacheTokenType;\n\n /**\n * Whether this variable is used in a section context (# or ^)\n * Section variables may reference arrays/objects for iteration\n */\n readonly isSection: boolean;\n}\n\n/**\n * Details about a missing variable in context validation.\n * @public\n */\nexport interface IMissingVariableDetail {\n /**\n * The variable reference that is missing\n */\n readonly variable: IVariableRef;\n\n /**\n * The path segment where the lookup failed\n * (e.g., for 'user.profile.name' if 'profile' is missing, this would be 'profile')\n */\n readonly failedAtSegment?: string;\n\n /**\n * The parent path that exists (e.g., ['user'] if 'user' exists but 'user.profile' does not)\n */\n readonly existingPath: readonly string[];\n}\n\n/**\n * Result of context validation, containing details about missing variables.\n * @public\n */\nexport interface IContextValidationResult {\n /**\n * Whether the context is valid (has all required variables)\n */\n readonly isValid: boolean;\n\n /**\n * Variables that are present in the context\n */\n readonly presentVariables: readonly string[];\n\n /**\n * Variables that are missing from the context\n */\n readonly missingVariables: readonly string[];\n\n /**\n * Detailed information about each missing variable\n */\n readonly missingDetails: readonly IMissingVariableDetail[];\n}\n\n/**\n * Strategy applied to double-brace `{{name}}` tokens at render time.\n *\n * - `'html'`: the standard mustache.js HTML escape (back-compat default).\n * - `'none'`: verbatim passthrough — values are interpolated as-is\n * (coerced to `String`). Suitable for LLM-prompt rendering and other\n * non-HTML targets where `& → &` corrupts the output.\n * - `(value) => string`: caller-supplied escape function.\n *\n * Note: triple-brace `{{{name}}}` (and `{{&name}}`) tokens are always\n * rendered unescaped regardless of this strategy — that is the standard\n * mustache.js semantics and is not affected by this option.\n *\n * @public\n */\nexport type MustacheEscapeStrategy = 'html' | 'none' | ((value: string) => string);\n\n/**\n * Options for template parsing and validation.\n * @public\n */\nexport interface IMustacheTemplateOptions {\n /**\n * Custom opening and closing tags (default: `['{{', '}}']`)\n */\n readonly tags?: readonly [string, string];\n\n /**\n * Whether to include comment tokens in variable extraction (default: false)\n */\n readonly includeComments?: boolean;\n\n /**\n * Whether to include partial references in variable extraction (default: false)\n */\n readonly includePartials?: boolean;\n\n /**\n * Escape strategy applied to double-brace `{{name}}` tokens at render\n * time. Default `'html'` preserves the existing mustache.js behavior\n * (back-compat).\n *\n * Pass `'none'` for LLM-prompt or other non-HTML targets where the\n * default `& → &` escape would corrupt the output. Pass a custom\n * function for any other escape policy.\n *\n * The strategy is applied per-template via a private `Mustache.Writer`\n * instance; no global state on the `mustache` module is mutated, so\n * concurrent templates with different strategies are safe.\n *\n * Note: triple-brace `{{{name}}}` tokens are always rendered unescaped\n * regardless of strategy (standard mustache.js semantics).\n */\n readonly escape?: MustacheEscapeStrategy;\n}\n\n/**\n * Required version of options with all fields populated.\n * @internal\n */\nexport interface IRequiredMustacheTemplateOptions {\n readonly tags: [string, string];\n readonly includeComments: boolean;\n readonly includePartials: boolean;\n readonly escape: MustacheEscapeStrategy;\n}\n\n/* c8 ignore stop */\n"]}
|
|
@@ -179,6 +179,97 @@ export class MustacheTemplate {
|
|
|
179
179
|
render(context) {
|
|
180
180
|
return captureResult(() => this._writer.render(this.template, context, undefined, { escape: this._escapeFn }));
|
|
181
181
|
}
|
|
182
|
+
/**
|
|
183
|
+
* Renders the template and reports which part of the output came from where.
|
|
184
|
+
*
|
|
185
|
+
* @remarks
|
|
186
|
+
* The rendered `text` is identical to `render`'s. What is added is
|
|
187
|
+
* `segments`: a document-ordered, contiguous, gapless attribution of every code unit to either
|
|
188
|
+
* template literal text or a named interpolation. It answers "what is in this output, in what
|
|
189
|
+
* order, and how much of it is each part" — a prompt's composition, a generated document's
|
|
190
|
+
* section sizes, a diff-free view of where a template's bulk actually goes.
|
|
191
|
+
*
|
|
192
|
+
* **Offsets are computed during the render, never recovered afterwards.** Recovering them by
|
|
193
|
+
* searching the output for each substituted value is the obvious shortcut and it is unsound: a
|
|
194
|
+
* value can occur more than once, can render empty, can be a substring of the surrounding
|
|
195
|
+
* literal text, and can be altered by escaping between input and output. That failure is silent
|
|
196
|
+
* and produces plausible offsets, which is the worst property a diagnostic can have.
|
|
197
|
+
*
|
|
198
|
+
* **Sections, inverted sections and partials are refused, not approximated.** Their rendered
|
|
199
|
+
* output is not a linear image of the token order — a section may repeat its body, or omit it —
|
|
200
|
+
* so a segment list walked from the template would mis-describe the result. Failing names the
|
|
201
|
+
* construct. Comments and set-delimiter tags emit nothing and are skipped; because each
|
|
202
|
+
* interpolation is rendered from its already-parsed token rather than from a re-parsed slice of
|
|
203
|
+
* the template, a set-delimiter tag has no effect on what this produces.
|
|
204
|
+
*
|
|
205
|
+
* **Every context value is evaluated exactly once, as `render()` evaluates it.** A lambda in the
|
|
206
|
+
* context is therefore invoked the same number of times either way, and a context whose lambda
|
|
207
|
+
* answers differently per call is rendered rather than rejected — the returned `segments` always
|
|
208
|
+
* describe the returned `text`, whatever that text was. (The concatenation identity is asserted
|
|
209
|
+
* across every shape in this package's test suite, not re-checked at runtime: re-checking means
|
|
210
|
+
* a second full render, which is precisely what would double those invocations.)
|
|
211
|
+
*
|
|
212
|
+
* @param context - The context object for template rendering.
|
|
213
|
+
* @returns Success with the rendered text and its segment map, or Failure if the
|
|
214
|
+
* template contains a construct this cannot describe
|
|
215
|
+
*/
|
|
216
|
+
renderWithSegments(context) {
|
|
217
|
+
return captureResult(() => {
|
|
218
|
+
const segments = [];
|
|
219
|
+
const lookup = new Mustache.Context(context);
|
|
220
|
+
let text = '';
|
|
221
|
+
for (const token of this._tokens) {
|
|
222
|
+
const type = token[0];
|
|
223
|
+
if (type === '!' || type === '=') {
|
|
224
|
+
continue; // emits nothing
|
|
225
|
+
}
|
|
226
|
+
if (type !== 'text' && type !== 'name' && type !== '&') {
|
|
227
|
+
throw new Error(`renderWithSegments does not support '${type}' tokens (sections, inverted sections ` +
|
|
228
|
+
`and partials render non-linearly, so a segment map walked from the template would ` +
|
|
229
|
+
`misdescribe the output). Use render() for this template.`);
|
|
230
|
+
}
|
|
231
|
+
const rendered = type === 'text' ? String(token[1]) : this._renderInterpolation(type, String(token[1]), lookup);
|
|
232
|
+
segments.push(Object.assign(Object.assign({ kind: type === 'text' ? 'literal' : 'substitution' }, (type === 'text' ? {} : { name: String(token[1]) })), { start: text.length, length: rendered.length, escaped: type === 'name' }));
|
|
233
|
+
text += rendered;
|
|
234
|
+
}
|
|
235
|
+
// Deliberately NOT re-rendered and compared against render() here. Such a check did once
|
|
236
|
+
// catch a real defect, but paying for it means a second full render — which invokes every
|
|
237
|
+
// lambda in the context a second time, so the check both doubles a caller's side effects
|
|
238
|
+
// and turns a context whose lambda answers differently per call into a failure on a
|
|
239
|
+
// template that renders fine. The identity is asserted in the test suite instead, where a
|
|
240
|
+
// second render costs nobody anything.
|
|
241
|
+
return { text, segments };
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Renders one interpolation token against a prepared lookup context.
|
|
246
|
+
*
|
|
247
|
+
* @remarks
|
|
248
|
+
* Delegates to the same `Writer` primitives `render()` reaches through `renderTokens`, so the
|
|
249
|
+
* value semantics — dotted paths, lambdas, `null` and `undefined` rendering empty, non-string
|
|
250
|
+
* coercion — are mustache.js's rather than a reimplementation of them.
|
|
251
|
+
*
|
|
252
|
+
* The token is passed as a freshly built `[type, name]` array rather than the parsed span. Both
|
|
253
|
+
* primitives read only the name, and `@types/mustache` declares the parameter as `string[]`
|
|
254
|
+
* while a parsed span carries its source offsets as numbers — so handing over the span would
|
|
255
|
+
* need a cast to work around the typings. Building the pair the primitives actually read needs
|
|
256
|
+
* none.
|
|
257
|
+
*
|
|
258
|
+
* @param type - `'name'` for an escaped interpolation, `'&'` for an unescaped one.
|
|
259
|
+
* @param name - The interpolation's name (may be a dotted path).
|
|
260
|
+
* @param lookup - The context to resolve the name against.
|
|
261
|
+
* @returns The rendered value; empty when the name resolves to `null` or `undefined`.
|
|
262
|
+
*/
|
|
263
|
+
_renderInterpolation(type, name, lookup) {
|
|
264
|
+
const token = [type, name];
|
|
265
|
+
const value = type === 'name'
|
|
266
|
+
? this._writer.escapedValue(token, lookup, { escape: this._escapeFn })
|
|
267
|
+
: this._writer.unescapedValue(token, lookup);
|
|
268
|
+
// Both primitives guard with `if (value != null)` and so return `undefined` — never `null` —
|
|
269
|
+
// for an absent value, which is why only `undefined` is tested here. `renderTokens` appends
|
|
270
|
+
// nothing in that case and string-coerces everything else.
|
|
271
|
+
return value === undefined ? '' : String(value);
|
|
272
|
+
}
|
|
182
273
|
/**
|
|
183
274
|
* Validates the context and renders the template if validation passes.
|
|
184
275
|
* @param context - The context object to validate and render with
|