@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.
Files changed (184) hide show
  1. package/CAPABILITIES.md +96 -0
  2. package/dist/packlets/ai-assist/cacheRequest.js +118 -0
  3. package/dist/packlets/ai-assist/cacheRequest.js.map +1 -0
  4. package/dist/packlets/ai-assist/chatRequestBuilders.js +72 -7
  5. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  6. package/dist/packlets/ai-assist/completionClient.js +195 -58
  7. package/dist/packlets/ai-assist/completionClient.js.map +1 -1
  8. package/dist/packlets/ai-assist/converters.js +54 -0
  9. package/dist/packlets/ai-assist/converters.js.map +1 -1
  10. package/dist/packlets/ai-assist/embeddingClient.js +16 -1
  11. package/dist/packlets/ai-assist/embeddingClient.js.map +1 -1
  12. package/dist/packlets/ai-assist/imageGenerationClient.js +17 -2
  13. package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  14. package/dist/packlets/ai-assist/index.js +3 -1
  15. package/dist/packlets/ai-assist/index.js.map +1 -1
  16. package/dist/packlets/ai-assist/listModelsClient.js +19 -1
  17. package/dist/packlets/ai-assist/listModelsClient.js.map +1 -1
  18. package/dist/packlets/ai-assist/model.js.map +1 -1
  19. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +200 -0
  20. package/dist/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  21. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js +137 -0
  22. package/dist/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  23. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js +156 -0
  24. package/dist/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  25. package/dist/packlets/ai-assist/promptCacheUsageMath.js +124 -0
  26. package/dist/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  27. package/dist/packlets/ai-assist/registry.js +9 -11
  28. package/dist/packlets/ai-assist/registry.js.map +1 -1
  29. package/dist/packlets/ai-assist/streamUsageCapability.js +134 -0
  30. package/dist/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  31. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +32 -9
  32. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  33. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +81 -35
  34. package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  35. package/dist/packlets/ai-assist/streamingAdapters/common.js +25 -1
  36. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  37. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  38. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  39. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +45 -11
  40. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  41. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +33 -22
  42. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  43. package/dist/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
  44. package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
  45. package/dist/packlets/ai-assist/streamingClient.js +20 -5
  46. package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
  47. package/dist/packlets/ai-assist/thinkingOptionsResolver.js +23 -5
  48. package/dist/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  49. package/dist/packlets/ai-assist/toolFormats.js +80 -0
  50. package/dist/packlets/ai-assist/toolFormats.js.map +1 -1
  51. package/dist/packlets/ai-assist/toolTypes.js +21 -0
  52. package/dist/packlets/ai-assist/toolTypes.js.map +1 -0
  53. package/dist/packlets/ai-assist/usageNormalization.js +178 -0
  54. package/dist/packlets/ai-assist/usageNormalization.js.map +1 -0
  55. package/dist/packlets/ai-assist/usageTypes.js +21 -0
  56. package/dist/packlets/ai-assist/usageTypes.js.map +1 -0
  57. package/dist/packlets/mustache/index.js.map +1 -1
  58. package/dist/packlets/mustache/interfaces.js.map +1 -1
  59. package/dist/packlets/mustache/mustacheTemplate.js +91 -0
  60. package/dist/packlets/mustache/mustacheTemplate.js.map +1 -1
  61. package/dist/ts-extras.d.ts +764 -48
  62. package/lib/packlets/ai-assist/cacheRequest.d.ts +100 -0
  63. package/lib/packlets/ai-assist/cacheRequest.d.ts.map +1 -0
  64. package/lib/packlets/ai-assist/cacheRequest.js +123 -0
  65. package/lib/packlets/ai-assist/cacheRequest.js.map +1 -0
  66. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +36 -6
  67. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -1
  68. package/lib/packlets/ai-assist/chatRequestBuilders.js +75 -7
  69. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
  70. package/lib/packlets/ai-assist/completionClient.d.ts +19 -0
  71. package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -1
  72. package/lib/packlets/ai-assist/completionClient.js +194 -57
  73. package/lib/packlets/ai-assist/completionClient.js.map +1 -1
  74. package/lib/packlets/ai-assist/converters.d.ts +46 -0
  75. package/lib/packlets/ai-assist/converters.d.ts.map +1 -1
  76. package/lib/packlets/ai-assist/converters.js +55 -1
  77. package/lib/packlets/ai-assist/converters.js.map +1 -1
  78. package/lib/packlets/ai-assist/embeddingClient.d.ts +9 -0
  79. package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -1
  80. package/lib/packlets/ai-assist/embeddingClient.js +16 -1
  81. package/lib/packlets/ai-assist/embeddingClient.js.map +1 -1
  82. package/lib/packlets/ai-assist/imageGenerationClient.d.ts +9 -0
  83. package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -1
  84. package/lib/packlets/ai-assist/imageGenerationClient.js +17 -2
  85. package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -1
  86. package/lib/packlets/ai-assist/index.d.ts +7 -2
  87. package/lib/packlets/ai-assist/index.d.ts.map +1 -1
  88. package/lib/packlets/ai-assist/index.js +11 -1
  89. package/lib/packlets/ai-assist/index.js.map +1 -1
  90. package/lib/packlets/ai-assist/listModelsClient.d.ts +12 -0
  91. package/lib/packlets/ai-assist/listModelsClient.d.ts.map +1 -1
  92. package/lib/packlets/ai-assist/listModelsClient.js +19 -1
  93. package/lib/packlets/ai-assist/listModelsClient.js.map +1 -1
  94. package/lib/packlets/ai-assist/model.d.ts +81 -295
  95. package/lib/packlets/ai-assist/model.d.ts.map +1 -1
  96. package/lib/packlets/ai-assist/model.js.map +1 -1
  97. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts +124 -0
  98. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.d.ts.map +1 -0
  99. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js +208 -0
  100. package/lib/packlets/ai-assist/promptCacheAnthropicBreakpointHarness.js.map +1 -0
  101. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts +77 -0
  102. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.d.ts.map +1 -0
  103. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js +143 -0
  104. package/lib/packlets/ai-assist/promptCacheObservabilityHarness.js.map +1 -0
  105. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts +84 -0
  106. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.d.ts.map +1 -0
  107. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js +163 -0
  108. package/lib/packlets/ai-assist/promptCacheRoutingAbHarness.js.map +1 -0
  109. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts +105 -0
  110. package/lib/packlets/ai-assist/promptCacheUsageMath.d.ts.map +1 -0
  111. package/lib/packlets/ai-assist/promptCacheUsageMath.js +130 -0
  112. package/lib/packlets/ai-assist/promptCacheUsageMath.js.map +1 -0
  113. package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
  114. package/lib/packlets/ai-assist/registry.js +9 -11
  115. package/lib/packlets/ai-assist/registry.js.map +1 -1
  116. package/lib/packlets/ai-assist/streamUsageCapability.d.ts +129 -0
  117. package/lib/packlets/ai-assist/streamUsageCapability.d.ts.map +1 -0
  118. package/lib/packlets/ai-assist/streamUsageCapability.js +140 -0
  119. package/lib/packlets/ai-assist/streamUsageCapability.js.map +1 -0
  120. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +2 -1
  121. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
  122. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +29 -6
  123. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
  124. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +58 -14
  125. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -1
  126. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +81 -36
  127. package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
  128. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +38 -3
  129. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
  130. package/lib/packlets/ai-assist/streamingAdapters/common.js +25 -1
  131. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
  132. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
  133. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +12 -5
  134. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
  135. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +2 -1
  136. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -1
  137. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +42 -8
  138. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -1
  139. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +2 -1
  140. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -1
  141. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +30 -19
  142. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -1
  143. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +22 -0
  144. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -1
  145. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +62 -4
  146. package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
  147. package/lib/packlets/ai-assist/streamingClient.d.ts +5 -0
  148. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
  149. package/lib/packlets/ai-assist/streamingClient.js +20 -5
  150. package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
  151. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts +11 -3
  152. package/lib/packlets/ai-assist/thinkingOptionsResolver.d.ts.map +1 -1
  153. package/lib/packlets/ai-assist/thinkingOptionsResolver.js +23 -5
  154. package/lib/packlets/ai-assist/thinkingOptionsResolver.js.map +1 -1
  155. package/lib/packlets/ai-assist/toolFormats.d.ts +55 -1
  156. package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -1
  157. package/lib/packlets/ai-assist/toolFormats.js +82 -0
  158. package/lib/packlets/ai-assist/toolFormats.js.map +1 -1
  159. package/lib/packlets/ai-assist/toolTypes.d.ts +386 -0
  160. package/lib/packlets/ai-assist/toolTypes.d.ts.map +1 -0
  161. package/lib/packlets/ai-assist/toolTypes.js +22 -0
  162. package/lib/packlets/ai-assist/toolTypes.js.map +1 -0
  163. package/lib/packlets/ai-assist/usageNormalization.d.ts +58 -0
  164. package/lib/packlets/ai-assist/usageNormalization.d.ts.map +1 -0
  165. package/lib/packlets/ai-assist/usageNormalization.js +184 -0
  166. package/lib/packlets/ai-assist/usageNormalization.js.map +1 -0
  167. package/lib/packlets/ai-assist/usageTypes.d.ts +84 -0
  168. package/lib/packlets/ai-assist/usageTypes.d.ts.map +1 -0
  169. package/lib/packlets/ai-assist/usageTypes.js +22 -0
  170. package/lib/packlets/ai-assist/usageTypes.js.map +1 -0
  171. package/lib/packlets/mustache/index.d.ts +1 -1
  172. package/lib/packlets/mustache/index.d.ts.map +1 -1
  173. package/lib/packlets/mustache/index.js.map +1 -1
  174. package/lib/packlets/mustache/interfaces.d.ts +30 -0
  175. package/lib/packlets/mustache/interfaces.d.ts.map +1 -1
  176. package/lib/packlets/mustache/interfaces.js.map +1 -1
  177. package/lib/packlets/mustache/mustacheTemplate.d.ts +56 -1
  178. package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -1
  179. package/lib/packlets/mustache/mustacheTemplate.js +91 -0
  180. package/lib/packlets/mustache/mustacheTemplate.js.map +1 -1
  181. package/package.json +16 -16
  182. package/perf/promptCacheAnthropicBreakpoint.js +135 -0
  183. package/perf/promptCacheObservability.js +107 -0
  184. package/perf/promptCacheRoutingAb.js +105 -0
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Tool types for AI assist: server-side tool configs, client-defined ("function")
3
+ * tools, the streaming events a tool call produces, the provider-exclusion vocabulary,
4
+ * and the client-tool round-trip result types.
5
+ *
6
+ * @remarks
7
+ * Split out of `model.ts` when the provider-exclusion types pushed that file past the
8
+ * 2000-line lint ceiling. The cut is along a real seam rather than an arbitrary one:
9
+ * everything here is about tools and nothing here depends on the rest of `model.ts`,
10
+ * so the module is a leaf. `model.ts` re-exports all of it, which is why no consumer
11
+ * import changed.
12
+ * @packageDocumentation
13
+ */
14
+ import { type Result } from '@fgv/ts-utils';
15
+ import { type JsonObject, type JsonSchema } from '@fgv/ts-json-base';
16
+ import type { IAiCompletionUsage } from './usageTypes';
17
+ /**
18
+ * Built-in server-side tool types supported across providers.
19
+ * @public
20
+ */
21
+ export type AiServerToolType = 'web_search';
22
+ /**
23
+ * Configuration specific to web search tools.
24
+ * @public
25
+ */
26
+ export interface IAiWebSearchToolConfig {
27
+ readonly type: 'web_search';
28
+ /**
29
+ * Optional: restrict search to these domains.
30
+ * Reaches Anthropic and the OpenAI/xAI Responses API; ignored on Gemini,
31
+ * whose `google_search` tool takes no configuration at all.
32
+ */
33
+ readonly allowedDomains?: ReadonlyArray<string>;
34
+ /**
35
+ * Optional: exclude these domains from search.
36
+ * Same reach as {@link AiAssist.IAiWebSearchToolConfig.allowedDomains}:
37
+ * Anthropic and OpenAI/xAI, ignored on Gemini.
38
+ */
39
+ readonly blockedDomains?: ReadonlyArray<string>;
40
+ /**
41
+ * Optional: max number of searches per request.
42
+ * **Anthropic only** — emitted as `max_uses` by the Anthropic formatter and
43
+ * read nowhere else, so it is silently ignored on OpenAI/xAI and Gemini.
44
+ */
45
+ readonly maxUses?: number;
46
+ /**
47
+ * Optional: enable image understanding during web search.
48
+ * When true, the model can view and analyze images found during search.
49
+ * Currently supported by xAI only; ignored by other providers.
50
+ */
51
+ readonly enableImageUnderstanding?: boolean;
52
+ }
53
+ /**
54
+ * Union of all server-side tool configurations. Discriminated on `type`.
55
+ * @public
56
+ */
57
+ export type AiServerToolConfig = IAiWebSearchToolConfig;
58
+ /**
59
+ * Declares a tool as enabled/disabled in provider settings.
60
+ * Tools are disabled by default — consuming apps must opt in explicitly.
61
+ * @public
62
+ */
63
+ export interface IAiToolEnablement {
64
+ /** Which tool type. */
65
+ readonly type: AiServerToolType;
66
+ /** Whether this tool is enabled by default for this provider. */
67
+ readonly enabled: boolean;
68
+ /** Optional tool-specific configuration. */
69
+ readonly config?: AiServerToolConfig;
70
+ }
71
+ /**
72
+ * Behavior annotations for a client-defined tool.
73
+ *
74
+ * @remarks
75
+ * These are **host-advisory-only hints** describing a tool's side-effect profile.
76
+ * They are consumed by the host's tool loop (e.g. a before-execute gate) and are
77
+ * **never serialized to the model** — the provider wire tool-schemas whitelist
78
+ * `{name, description, parameters}` and ignore this field.
79
+ *
80
+ * Field names mirror MCP's `ToolAnnotations` (`@modelcontextprotocol/sdk`) 1:1 so
81
+ * an MCP tool's annotations pass through unchanged. Per the MCP spec, all fields
82
+ * are hints — a host should never make tool-use decisions based on annotations
83
+ * received from an untrusted server without its own validation.
84
+ *
85
+ * @public
86
+ */
87
+ export interface IAiToolAnnotations {
88
+ /** Optional human-readable display title for the tool. */
89
+ readonly title?: string;
90
+ /** Hint: the tool does not modify its environment (read-only). */
91
+ readonly readOnlyHint?: boolean;
92
+ /** Hint: the tool may perform destructive updates (only meaningful when not read-only). */
93
+ readonly destructiveHint?: boolean;
94
+ /** Hint: repeated calls with the same arguments have no additional effect. */
95
+ readonly idempotentHint?: boolean;
96
+ /** Hint: the tool interacts with an open world of external entities. */
97
+ readonly openWorldHint?: boolean;
98
+ }
99
+ /**
100
+ * Configuration for a client-defined (harness-supplied) tool.
101
+ *
102
+ * @remarks
103
+ * The `parametersSchema` is the single source of truth for both the wire-format
104
+ * JSON Schema sent to the provider (via `.toJson()`) and the runtime argument
105
+ * validation (via `.validate(rawArgs)`). Use `JsonSchema.object(...)` from
106
+ * `@fgv/ts-json-base` to author the schema as a const (e.g. `const mySchema = JsonSchema.object({...})`);
107
+ * the static type `TParams` is then derived via `JsonSchema.Static<typeof mySchema>` —
108
+ * no drift between wire schema and runtime validation.
109
+ *
110
+ * @public
111
+ */
112
+ export interface IAiClientToolConfig<TParams = unknown> {
113
+ /** Discriminator — always `'client_tool'`. */
114
+ readonly type: 'client_tool';
115
+ /** Tool name sent to the model (must be unique within a call). */
116
+ readonly name: string;
117
+ /** Human-readable description of what the tool does, shown to the model. */
118
+ readonly description: string;
119
+ /**
120
+ * JSON Schema validator for the tool's parameters. Emits wire format via
121
+ * `.toJson()` and validates model-returned args via `.validate(rawArgs)`.
122
+ */
123
+ readonly parametersSchema: JsonSchema.ISchemaValidator<TParams>;
124
+ /**
125
+ * Optional host-advisory behavior annotations (read-only / destructive /
126
+ * idempotent / open-world hints + display title). Consumed by the host's
127
+ * tool loop; never serialized to the model. See {@link AiAssist.IAiToolAnnotations}.
128
+ */
129
+ readonly annotations?: IAiToolAnnotations;
130
+ }
131
+ /**
132
+ * A client-defined tool: configuration + execution callback pair.
133
+ *
134
+ * @remarks
135
+ * The `execute` callback receives typed `TParams` (already validated by
136
+ * `config.parametersSchema.validate()`) and returns a `Promise<Result<unknown>>`.
137
+ * Thrown errors are caught via `captureAsyncResult` in the round-trip helper.
138
+ *
139
+ * @public
140
+ */
141
+ export interface IAiClientTool<TParams = unknown> {
142
+ /** The tool's configuration (name, description, parameters schema). */
143
+ readonly config: IAiClientToolConfig<TParams>;
144
+ /**
145
+ * Execute the tool with validated parameters.
146
+ * @param args - Typed arguments, already validated against `config.parametersSchema`.
147
+ * @returns A `Promise<Result<unknown>>` — the result is stringified and sent back to the model.
148
+ */
149
+ readonly execute: (args: TParams) => Promise<Result<unknown>>;
150
+ }
151
+ /**
152
+ * Union of all tool configurations: server-side or client-defined.
153
+ * Discriminated on `type`.
154
+ * @public
155
+ */
156
+ export type AiToolConfig = AiServerToolConfig | IAiClientToolConfig;
157
+ /**
158
+ * Emitted when a client-defined tool call begins streaming. Carries the tool name
159
+ * and optional provider-assigned call ID (Anthropic / OpenAI Responses API; absent
160
+ * for Gemini which does not assign call IDs).
161
+ * @public
162
+ */
163
+ export interface IAiStreamToolUseStart {
164
+ readonly type: 'client-tool-call-start';
165
+ /** The name of the client tool being called. */
166
+ readonly toolName: string;
167
+ /**
168
+ * Provider-assigned call identifier (Anthropic: `toolu_*`; OpenAI: `call_*`).
169
+ * Absent for Gemini (correlation by name).
170
+ */
171
+ readonly callId?: string;
172
+ }
173
+ /**
174
+ * Emitted when a client-defined tool call is complete and its arguments are fully
175
+ * accumulated. The `args` object is the fully parsed JSON object — no further
176
+ * streaming deltas follow for this call.
177
+ * @public
178
+ */
179
+ export interface IAiStreamToolUseDelta {
180
+ readonly type: 'client-tool-call-done';
181
+ /** The name of the client tool being called. */
182
+ readonly toolName: string;
183
+ /**
184
+ * Provider-assigned call identifier. Absent for Gemini.
185
+ */
186
+ readonly callId?: string;
187
+ /** The fully accumulated and parsed tool arguments. */
188
+ readonly args: JsonObject;
189
+ }
190
+ /**
191
+ * Emitted after a client-defined tool has been executed and the result is ready
192
+ * to be fed back to the model in the round-trip continuation.
193
+ * @public
194
+ */
195
+ export interface IAiStreamToolUseComplete {
196
+ readonly type: 'client-tool-result';
197
+ /** The name of the client tool that was executed. */
198
+ readonly toolName: string;
199
+ /**
200
+ * Provider-assigned call identifier. Absent for Gemini.
201
+ */
202
+ readonly callId?: string;
203
+ /** The stringified result returned by the tool's execute callback. */
204
+ readonly result: string;
205
+ /** Whether the tool execution failed (schema validation failure, execute error, or unknown tool). */
206
+ readonly isError: boolean;
207
+ }
208
+ /**
209
+ * What to do when a request would combine a server tool with client (function)
210
+ * tools on a provider that declares the two mutually exclusive (see
211
+ * `IAiProviderDescriptor.serverToolsExclusiveWithClientTools`).
212
+ *
213
+ * @remarks
214
+ * - `'drop-server-tools'` (the default) removes the offending server tools and
215
+ * keeps every client tool. Client tools are what the host registered
216
+ * explicitly for this turn; a built-in like grounding is a per-provider
217
+ * nicety, and dropping it degrades the turn rather than losing it.
218
+ * - `'prefer-server-tools'` is the mirror image: keep the server tools and drop
219
+ * every client tool. For hosts whose turn is *about* the grounded answer.
220
+ * - `'fail'` refuses the request up front with a message naming the conflict —
221
+ * the behavior before this policy existed. For hosts that would rather
222
+ * choose themselves than have either half silently disappear.
223
+ *
224
+ * Whichever is chosen, what actually happened is reported, never inferred: see
225
+ * {@link AiAssist.IAiToolConflictReport}.
226
+ * @public
227
+ */
228
+ export type AiToolConflictPolicy = 'drop-server-tools' | 'prefer-server-tools' | 'fail';
229
+ /**
230
+ * What the conflict resolution did to a turn's tools.
231
+ *
232
+ * @remarks
233
+ * Required on {@link AiAssist.IAiClientToolTurnResult}, not optional, for the same reason
234
+ * `structuredOutput` is required on a completion response: an absent report is
235
+ * three-ways ambiguous — nothing conflicted / this build predates the feature /
236
+ * the resolution ran and said nothing — and disambiguating exactly that is what
237
+ * it is for. A turn where nothing conflicted reports the policy that was in
238
+ * force and two empty arrays.
239
+ * @public
240
+ */
241
+ export interface IAiToolConflictReport {
242
+ /** The policy that was in force for this turn (the default when none was passed). */
243
+ readonly policy: AiToolConflictPolicy;
244
+ /** Server tool types removed from the request. Empty when nothing was dropped. */
245
+ readonly droppedServerTools: ReadonlyArray<AiServerToolType>;
246
+ /** Names of client tools removed from the request. Empty when nothing was dropped. */
247
+ readonly droppedClientTools: ReadonlyArray<string>;
248
+ }
249
+ /**
250
+ * Summary of a single client tool call within a turn: the tool name, call ID,
251
+ * raw arguments, execution result, and whether the execution was an error.
252
+ * @public
253
+ */
254
+ export interface IAiClientToolCallSummary {
255
+ /** The name of the tool that was called. */
256
+ readonly toolName: string;
257
+ /** Provider-assigned call identifier (absent for Gemini). */
258
+ readonly callId?: string;
259
+ /** The fully accumulated raw arguments object as parsed JSON. */
260
+ readonly args: JsonObject;
261
+ /** The stringified result (success value or error message). */
262
+ readonly result: string;
263
+ /** Whether execution failed (schema validation failure, execute error, or unknown tool). */
264
+ readonly isError: boolean;
265
+ }
266
+ /**
267
+ * The provider-specific continuation data needed to build the follow-up request
268
+ * for the next round of the conversation.
269
+ *
270
+ * @remarks
271
+ * `messages` are provider-native request objects (Anthropic: content-block arrays,
272
+ * OpenAI Responses API: input items, Gemini: content parts). The continuation
273
+ * builder in `clientToolContinuationBuilder.ts` populates this.
274
+ *
275
+ * @public
276
+ */
277
+ export interface IAiClientToolContinuation {
278
+ /**
279
+ * **Cumulative** provider-native wire-format message objects covering all
280
+ * tool rounds so far. On each turn, `executeClientToolTurn` prepends the
281
+ * inbound `continuationMessages` so that this array always contains the
282
+ * complete wire tail from round 1 through the current round.
283
+ *
284
+ * To drive a multi-round loop, simply **replace** `continuationMessages`
285
+ * with this value — do not manually concatenate:
286
+ *
287
+ * ```ts
288
+ * let tail: JsonObject[] | undefined;
289
+ * while (true) {
290
+ * const { events, nextTurn } = executeClientToolTurn({
291
+ * ..., continuationMessages: tail
292
+ * }).orThrow();
293
+ * for await (const e of events) { /* observe *\/ }
294
+ * const outcome = (await nextTurn).orThrow();
295
+ * if (!outcome.continuation) break;
296
+ * tail = [...outcome.continuation.messages]; // replace — already cumulative
297
+ * }
298
+ * ```
299
+ *
300
+ * The exact shape is provider-native and may include provider-specific
301
+ * blocks (e.g. Anthropic thinking/redacted_thinking/tool_use, OpenAI
302
+ * function_call/function_call_output items, Gemini functionCall/functionResponse
303
+ * parts). These are NOT `IChatMessage[]` and must NOT be placed in the
304
+ * `messages` parameter — the normalized-message path strips provider-native
305
+ * fields (thinking signatures, redacted_thinking data) that the server
306
+ * requires for continuation validation.
307
+ *
308
+ * `toolCallsSummary` is per-round only (the calls executed in the current
309
+ * turn). Only `messages` is cumulative.
310
+ */
311
+ readonly messages: ReadonlyArray<JsonObject>;
312
+ /** Summary of each tool call executed in this turn (per-round, not cumulative). */
313
+ readonly toolCallsSummary: ReadonlyArray<IAiClientToolCallSummary>;
314
+ }
315
+ /**
316
+ * The result of a single client-tool turn: the optional continuation for the next
317
+ * call (absent when no tool calls occurred) and whether the stream was truncated.
318
+ * @public
319
+ */
320
+ export interface IAiClientToolTurnResult {
321
+ /**
322
+ * The continuation data for the next round-trip. `undefined` when the model
323
+ * completed without invoking any client tools.
324
+ */
325
+ readonly continuation: IAiClientToolContinuation | undefined;
326
+ /** Whether the stream was truncated (token limit or stop reason). */
327
+ readonly truncated: boolean;
328
+ /** The full concatenated text from all `text-delta` events in this turn. */
329
+ readonly fullText: string;
330
+ /**
331
+ * What the provider tool-conflict resolution did to this turn's tools.
332
+ * Always present; empty arrays mean nothing conflicted.
333
+ *
334
+ * @remarks
335
+ * Read this to tell the person (or the model, on a later turn) that a
336
+ * capability they expected was unavailable — e.g. that web search was dropped
337
+ * because the pinned model cannot ground and call functions in one request.
338
+ */
339
+ readonly toolConflicts: IAiToolConflictReport;
340
+ /**
341
+ * Token usage for this turn's provider call, when the provider reports it.
342
+ *
343
+ * @remarks
344
+ * The same `IAiCompletionUsage` the plain completion paths carry — normalized
345
+ * cache reads/writes, output and total input tokens, and a `reports` level
346
+ * saying which of those the provider is able to tell you. Sourced from the
347
+ * terminal `done` event of the underlying stream, so it is exactly what a
348
+ * caller watching `events` would see.
349
+ *
350
+ * Reading it here spares you *inspecting* the event stream, not *driving* it:
351
+ * `nextTurn` only resolves once `events` has been iterated to completion, the
352
+ * same as every other field on this interface.
353
+ *
354
+ * **One call, one usage.** `executeClientToolTurn` makes a single provider
355
+ * call per invocation; the multi-round loop is driven by the caller
356
+ * re-invoking with `continuationMessages`. So each result's `usage` already
357
+ * *is* one round's usage, and a host accumulating a per-turn total sums the
358
+ * results of its own loop. There is deliberately no `perRound` array here —
359
+ * it could only ever have one entry.
360
+ *
361
+ * **Optional on purpose, unlike `toolConflicts`.** The library always knows
362
+ * what it did to your tools, so a silent `toolConflicts` would be a defect
363
+ * and it is required. It cannot always know what a turn cost, so a required
364
+ * `usage` could only be satisfied by inventing one — the exact failure
365
+ * {@link AiAssist.IAiCompletionUsage.reports} exists to prevent.
366
+ *
367
+ * Absent means **no normalized usage is being exposed**, which covers two
368
+ * cases, the same as on {@link AiAssist.IAiCompletionResponse.usage} and
369
+ * {@link AiAssist.IAiStreamDone.usage}:
370
+ *
371
+ * - the provider reported nothing; or
372
+ * - the provider reported something the library declines to normalize,
373
+ * because this descriptor is outside
374
+ * {@link AiAssist.supportsCacheUsageReporting}. Groq, Mistral, Ollama and
375
+ * self-hosted `openai-compat` share the OpenAI-format adapter but have
376
+ * unverified usage shapes, so a raw `usage` block from one of them is
377
+ * dropped rather than stamped with a cache-reporting level it may not
378
+ * have earned.
379
+ *
380
+ * Either way it is never a fabricated zero. If you need to tell the two
381
+ * apart, the descriptor answers it: the second case is a property of the
382
+ * provider you picked, not of the turn.
383
+ */
384
+ readonly usage?: IAiCompletionUsage;
385
+ }
386
+ //# sourceMappingURL=toolTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolTypes.d.ts","sourceRoot":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AC;CAC3B;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACH,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IAC7C,mFAAmF;IACnF,QAAQ,CAAC,gBAAgB,EAAE,aAAa,CAAC,wBAAwB,CAAC,CAAC;CACpE;AAED;;;;GAIG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,yBAAyB,GAAG,SAAS,CAAC;IAC7D,qEAAqE;IACrE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,4EAA4E;IAC5E,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B;;;;;;;;OAQG;IACH,QAAQ,CAAC,aAAa,EAAE,qBAAqB,CAAC;IAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2CG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,kBAAkB,CAAC;CACrC"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ // Copyright (c) 2026 Erik Fortune
3
+ //
4
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ // of this software and associated documentation files (the "Software"), to deal
6
+ // in the Software without restriction, including without limitation the rights
7
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ // copies of the Software, and to permit persons to whom the Software is
9
+ // furnished to do so, subject to the following conditions:
10
+ //
11
+ // The above copyright notice and this permission notice shall be included in all
12
+ // copies or substantial portions of the Software.
13
+ //
14
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ // SOFTWARE.
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ //# 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,58 @@
1
+ /**
2
+ * Per-wire-shape `usage` block normalization, shared by the non-streaming
3
+ * adapters (`completionClient.ts`) and the streaming adapters
4
+ * (`streamingAdapters/*.ts`) so the same JSON layout is parsed once.
5
+ *
6
+ * @remarks
7
+ * Every function here follows one rule throughout: a field that is absent
8
+ * from the wire response stays absent on {@link AiAssist.IAiCompletionUsage} —
9
+ * never defaulted to `0`, and never derived from a sibling field unless the
10
+ * value that sibling would need is itself known. See `IAiCompletionUsage`
11
+ * for why.
12
+ * @packageDocumentation
13
+ */
14
+ import { type JsonObject } from '@fgv/ts-json-base';
15
+ import { type IAiCompletionUsage } from './usageTypes';
16
+ /**
17
+ * Normalizes an Anthropic Messages API `usage` block. Anthropic always
18
+ * reports both reads and writes, so `reports` is unconditionally
19
+ * `'reads-and-writes'` — an absent `cache_creation_input_tokens` genuinely
20
+ * means zero tokens were written this request.
21
+ * @internal
22
+ */
23
+ export declare function normalizeAnthropicUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined;
24
+ /**
25
+ * Normalizes an OpenAI/xAI Chat Completions `usage` block. `reports` is
26
+ * unconditionally `'reads'`: `cache_write_tokens` does not exist on this API
27
+ * for any provider reached through it, so `cacheWriteTokens` is never set —
28
+ * not even to `0`.
29
+ * @internal
30
+ */
31
+ export declare function normalizeOpenAiChatUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined;
32
+ /**
33
+ * Normalizes an OpenAI/xAI Responses API `usage` block. This route is shared
34
+ * by two providers that disagree about write reporting — OpenAI always sends
35
+ * `cache_write_tokens` (even when `0`), xAI never does — so `reports` is
36
+ * derived from field **presence**, not from provider identity: a wire that
37
+ * sends the field, however small its value, is `'reads-and-writes'`; a wire
38
+ * that omits it entirely is `'reads'`.
39
+ * @internal
40
+ */
41
+ export declare function normalizeOpenAiResponsesUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined;
42
+ /**
43
+ * Normalizes a Gemini `usageMetadata` block. `reports` is unconditionally
44
+ * `'reads'` — Gemini has no cache-write concept in a `generateContent` call;
45
+ * writes happen out-of-band via the explicit `cachedContents` resource,
46
+ * out of scope per the design (§10).
47
+ *
48
+ * @remarks
49
+ * The Gemini-specific footgun: `promptTokenCount` already **includes**
50
+ * `cachedContentTokenCount` (it is the total effective prompt size), unlike
51
+ * OpenAI where the cached figure sits in a sub-object alongside a separate
52
+ * total. `uncachedInputTokens` subtracts to correct for it — but only when
53
+ * `cachedContentTokenCount` is itself present, per the module's absent-means-
54
+ * absent rule.
55
+ * @internal
56
+ */
57
+ export declare function normalizeGeminiUsage(raw: JsonObject | undefined): IAiCompletionUsage | undefined;
58
+ //# sourceMappingURL=usageNormalization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usageNormalization.d.ts","sourceRoot":"","sources":["../../../src/packlets/ai-assist/usageNormalization.ts"],"names":[],"mappings":"AAoBA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAGpD,OAAO,EAA8B,KAAK,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAqBnF;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,UAAU,GAAG,SAAS,GAAG,kBAAkB,GAAG,SAAS,CAuBnG;AA2BD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,UAAU,GAAG,SAAS,GAAG,kBAAkB,GAAG,SAAS,CA6BpG;AAgCD;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,UAAU,GAAG,SAAS,GAAG,kBAAkB,GAAG,SAAS,CA4BzG;AAmBD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,UAAU,GAAG,SAAS,GAAG,kBAAkB,GAAG,SAAS,CA4BhG"}