@anvia/core 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/agent/index.d.ts +11 -11
  2. package/dist/agent/index.js +11 -11
  3. package/dist/{agent-Q7FT1xmG.d.ts → agent-x3YTyv5i.d.ts} +8 -7
  4. package/dist/audio-generation/index.d.ts +1 -1
  5. package/dist/{chunk-6X2UTX3L.js → chunk-2NDQHV7V.js} +6 -6
  6. package/dist/{chunk-MELYDKWQ.js → chunk-4BGN6PYF.js} +4 -4
  7. package/dist/{chunk-WHAPIIEZ.js → chunk-4HWN7734.js} +5 -5
  8. package/dist/{chunk-PJDL5UT2.js → chunk-ADH7NNCS.js} +63 -1
  9. package/dist/chunk-ADH7NNCS.js.map +1 -0
  10. package/dist/{chunk-NCPN4SJR.js → chunk-BCA4VZ5W.js} +2 -2
  11. package/dist/{chunk-SWUH4G2I.js → chunk-I6XOQ4LK.js} +2 -2
  12. package/dist/{chunk-ZSTUMG7G.js → chunk-KYEBWN3E.js} +6 -6
  13. package/dist/{chunk-F56AMXMQ.js → chunk-MC3CCKEB.js} +2 -2
  14. package/dist/{chunk-TGLNXVII.js → chunk-MRQLEK2B.js} +3 -3
  15. package/dist/{chunk-MTGNA4OS.js → chunk-Q25IWLBT.js} +2 -2
  16. package/dist/{chunk-ZNTIUOKL.js → chunk-UQX6EXWG.js} +2 -2
  17. package/dist/{chunk-3IYTCGHS.js → chunk-VXONXP2G.js} +17 -10
  18. package/dist/{chunk-3IYTCGHS.js.map → chunk-VXONXP2G.js.map} +1 -1
  19. package/dist/{chunk-N3YV3WCO.js → chunk-YEBIVZM2.js} +22 -5
  20. package/dist/chunk-YEBIVZM2.js.map +1 -0
  21. package/dist/completion/index.d.ts +3 -3
  22. package/dist/completion/index.js +11 -5
  23. package/dist/{errors-Bf661V89.d.ts → errors-2moLDuuN.d.ts} +2 -2
  24. package/dist/evals/index.d.ts +8 -8
  25. package/dist/evals/index.js +12 -12
  26. package/dist/extractor/index.d.ts +8 -8
  27. package/dist/extractor/index.js +12 -12
  28. package/dist/guardrails/index.d.ts +1 -1
  29. package/dist/hooks/index.d.ts +3 -3
  30. package/dist/image-generation/index.d.ts +1 -1
  31. package/dist/{index-XTUEMWhU.d.ts → index-BxSbmOMr.d.ts} +4 -2
  32. package/dist/index.d.ts +13 -13
  33. package/dist/index.js +22 -16
  34. package/dist/internal/agent.d.ts +8 -8
  35. package/dist/internal/agent.js +9 -9
  36. package/dist/{json-D9IvOgx_.d.ts → json-BVPssigK.d.ts} +1 -1
  37. package/dist/loaders/index.d.ts +1 -1
  38. package/dist/mcp/index.d.ts +4 -4
  39. package/dist/memory/index.d.ts +4 -4
  40. package/dist/memory/index.js +4 -4
  41. package/dist/{middleware-DfMc30in.d.ts → middleware-Dp3d_pxi.d.ts} +3 -3
  42. package/dist/observability/index.d.ts +3 -3
  43. package/dist/pipeline/index.d.ts +8 -8
  44. package/dist/request/index.d.ts +8 -8
  45. package/dist/request/index.js +8 -8
  46. package/dist/skills/index.d.ts +4 -4
  47. package/dist/skills/index.js +5 -5
  48. package/dist/{think-tool-CpCKo8Q8.d.ts → think-tool-DfCMuO8e.d.ts} +1 -1
  49. package/dist/tool/index.d.ts +5 -5
  50. package/dist/tool/index.js +5 -5
  51. package/dist/{tool-Dhwg__1L.d.ts → tool-Cohdv5GC.d.ts} +1 -1
  52. package/dist/transcription/index.d.ts +1 -1
  53. package/dist/{types-fBv8mhvP.d.ts → types-04LqWrmy.d.ts} +1 -1
  54. package/dist/{types-DBHzPsbx.d.ts → types-BrLbKnEz.d.ts} +1 -1
  55. package/dist/{types-BCA8p0sb.d.ts → types-D9JpeAPF.d.ts} +1 -1
  56. package/dist/{types-XjIh933x.d.ts → types-G12i56s2.d.ts} +26 -1
  57. package/dist/{types-BBEf34DP.d.ts → types-JJCxRnaZ.d.ts} +2 -2
  58. package/dist/{types-BrxxAtcJ.d.ts → types-O-abTIin.d.ts} +1 -1
  59. package/dist/ui/index.d.ts +2 -1
  60. package/dist/ui/index.js +2 -2
  61. package/dist/vector-store/index.d.ts +4 -4
  62. package/dist/vector-store/index.js +2 -2
  63. package/package.json +1 -1
  64. package/dist/chunk-N3YV3WCO.js.map +0 -1
  65. package/dist/chunk-PJDL5UT2.js.map +0 -1
  66. /package/dist/{chunk-6X2UTX3L.js.map → chunk-2NDQHV7V.js.map} +0 -0
  67. /package/dist/{chunk-MELYDKWQ.js.map → chunk-4BGN6PYF.js.map} +0 -0
  68. /package/dist/{chunk-WHAPIIEZ.js.map → chunk-4HWN7734.js.map} +0 -0
  69. /package/dist/{chunk-NCPN4SJR.js.map → chunk-BCA4VZ5W.js.map} +0 -0
  70. /package/dist/{chunk-SWUH4G2I.js.map → chunk-I6XOQ4LK.js.map} +0 -0
  71. /package/dist/{chunk-ZSTUMG7G.js.map → chunk-KYEBWN3E.js.map} +0 -0
  72. /package/dist/{chunk-F56AMXMQ.js.map → chunk-MC3CCKEB.js.map} +0 -0
  73. /package/dist/{chunk-TGLNXVII.js.map → chunk-MRQLEK2B.js.map} +0 -0
  74. /package/dist/{chunk-MTGNA4OS.js.map → chunk-Q25IWLBT.js.map} +0 -0
  75. /package/dist/{chunk-ZNTIUOKL.js.map → chunk-UQX6EXWG.js.map} +0 -0
@@ -1,16 +1,16 @@
1
- import { D as DynamicContextOptions, b as DynamicToolOptions, c as AgentEventStore, d as AgentEventStoreOptions, A as Agent } from '../agent-Q7FT1xmG.js';
2
- export { e as AgentEventAppendInput, f as AgentEventRecord, g as AgentEventStoreInclude, h as AgentSession, i as AgentToolOptions } from '../agent-Q7FT1xmG.js';
1
+ import { D as DynamicContextOptions, b as DynamicToolOptions, c as AgentEventStore, d as AgentEventStoreOptions, A as Agent } from '../agent-x3YTyv5i.js';
2
+ export { e as AgentEventAppendInput, f as AgentEventRecord, g as AgentEventStoreInclude, h as AgentSession, i as AgentToolOptions } from '../agent-x3YTyv5i.js';
3
3
  import { Z as ZodSchema } from '../zod-schema-C7F4clpm.js';
4
- import { C as CompletionModel, P as ProviderTool, i as JsonValue, z as ToolChoice } from '../types-XjIh933x.js';
4
+ import { C as CompletionModel, P as ProviderTool, l as JsonValue, L as ToolChoice } from '../types-G12i56s2.js';
5
5
  import { GuardrailPolicyInput } from '../guardrails/index.js';
6
- import { P as PromptHook } from '../types-BCA8p0sb.js';
7
- import { a as McpServer } from '../types-BBEf34DP.js';
8
- import { m as MemoryStore, n as MemoryOptions } from '../types-DBHzPsbx.js';
9
- import { i as AgentObserver, O as ObserveOptions } from '../index-XTUEMWhU.js';
10
- import { a as SkillSet } from '../types-fBv8mhvP.js';
11
- import { i as ToolSearchDocument, j as ToolSet, A as AgentMiddleware } from '../middleware-DfMc30in.js';
12
- import { A as AnyTool, e as ToolApprovalsOptions } from '../tool-Dhwg__1L.js';
13
- import { a as VectorSearchIndex } from '../types-BrxxAtcJ.js';
6
+ import { P as PromptHook } from '../types-D9JpeAPF.js';
7
+ import { a as McpServer } from '../types-JJCxRnaZ.js';
8
+ import { m as MemoryStore, n as MemoryOptions } from '../types-BrLbKnEz.js';
9
+ import { i as AgentObserver, O as ObserveOptions } from '../index-BxSbmOMr.js';
10
+ import { a as SkillSet } from '../types-04LqWrmy.js';
11
+ import { i as ToolSearchDocument, j as ToolSet, A as AgentMiddleware } from '../middleware-Dp3d_pxi.js';
12
+ import { A as AnyTool, e as ToolApprovalsOptions } from '../tool-Cohdv5GC.js';
13
+ import { a as VectorSearchIndex } from '../types-O-abTIin.js';
14
14
  import 'zod';
15
15
  import '@modelcontextprotocol/sdk/client/sse.js';
16
16
  import '@modelcontextprotocol/sdk/client/stdio.js';
@@ -1,21 +1,21 @@
1
1
  import {
2
2
  AgentBuilder
3
- } from "../chunk-WHAPIIEZ.js";
4
- import "../chunk-N3YV3WCO.js";
5
- import "../chunk-3IYTCGHS.js";
3
+ } from "../chunk-4HWN7734.js";
4
+ import "../chunk-YEBIVZM2.js";
5
+ import "../chunk-VXONXP2G.js";
6
6
  import "../chunk-YK4WAAS4.js";
7
7
  import "../chunk-XUUY2L2D.js";
8
- import "../chunk-6X2UTX3L.js";
9
- import "../chunk-MELYDKWQ.js";
8
+ import "../chunk-2NDQHV7V.js";
9
+ import "../chunk-4BGN6PYF.js";
10
10
  import "../chunk-2ODTMRHP.js";
11
- import "../chunk-ZNTIUOKL.js";
12
- import "../chunk-TGLNXVII.js";
11
+ import "../chunk-UQX6EXWG.js";
12
+ import "../chunk-MRQLEK2B.js";
13
+ import "../chunk-Q25IWLBT.js";
14
+ import "../chunk-MC3CCKEB.js";
15
+ import "../chunk-ADH7NNCS.js";
16
+ import "../chunk-WQKHFADH.js";
13
17
  import "../chunk-MNWK2USR.js";
14
18
  import "../chunk-OIMLU4SF.js";
15
- import "../chunk-MTGNA4OS.js";
16
- import "../chunk-F56AMXMQ.js";
17
- import "../chunk-PJDL5UT2.js";
18
- import "../chunk-WQKHFADH.js";
19
19
  import "../chunk-CWUJUSOS.js";
20
20
  export {
21
21
  AgentBuilder
@@ -1,11 +1,11 @@
1
- import { C as CompletionModel, M as Message, D as Document, i as JsonValue, P as ProviderTool, z as ToolChoice, J as JsonObject } from './types-XjIh933x.js';
1
+ import { C as CompletionModel, M as Message, D as Document, l as JsonValue, P as ProviderTool, L as ToolChoice, J as JsonObject, j as ContextUsage } from './types-G12i56s2.js';
2
2
  import { GuardrailPolicyInput, GuardrailPolicy } from './guardrails/index.js';
3
- import { P as PromptHook } from './types-BCA8p0sb.js';
4
- import { q as MemoryContext, s as MemoryRegistration, u as SessionOptions } from './types-DBHzPsbx.js';
5
- import { j as AgentTraceOptions, P as PromptResponse, d as AgentStreamEvent, f as AgentStreamEventWithoutToolCallDeltas, g as AgentStreamOptions, k as AgentObserverRegistration } from './index-XTUEMWhU.js';
6
- import { e as ToolApprovalsOptions, T as Tool, A as AnyTool, f as ToolCallContext, N as NormalizedToolOutput } from './tool-Dhwg__1L.js';
7
- import { A as AgentMiddleware, i as ToolSearchDocument, j as ToolSet } from './middleware-DfMc30in.js';
8
- import { V as VectorFilter, c as VectorSearchResult, a as VectorSearchIndex } from './types-BrxxAtcJ.js';
3
+ import { P as PromptHook } from './types-D9JpeAPF.js';
4
+ import { q as MemoryContext, s as MemoryRegistration, u as SessionOptions } from './types-BrLbKnEz.js';
5
+ import { j as AgentTraceOptions, P as PromptResponse, d as AgentStreamEvent, f as AgentStreamEventWithoutToolCallDeltas, g as AgentStreamOptions, k as AgentObserverRegistration } from './index-BxSbmOMr.js';
6
+ import { e as ToolApprovalsOptions, T as Tool, A as AnyTool, f as ToolCallContext, N as NormalizedToolOutput } from './tool-Cohdv5GC.js';
7
+ import { A as AgentMiddleware, i as ToolSearchDocument, j as ToolSet } from './middleware-Dp3d_pxi.js';
8
+ import { V as VectorFilter, c as VectorSearchResult, a as VectorSearchIndex } from './types-O-abTIin.js';
9
9
 
10
10
  type CompletionRetryContext = {
11
11
  error: unknown;
@@ -215,6 +215,7 @@ declare class AgentSession<M extends CompletionModel = CompletionModel> {
215
215
  });
216
216
  prompt(prompt: string | Message): PromptRequest<M>;
217
217
  messages(): Promise<Message[]>;
218
+ contextUsage(): Promise<ContextUsage | undefined>;
218
219
  clear(): Promise<void>;
219
220
  }
220
221
 
@@ -1,4 +1,4 @@
1
- import { i as JsonValue } from '../types-XjIh933x.js';
1
+ import { l as JsonValue } from '../types-G12i56s2.js';
2
2
 
3
3
  type AudioGenerationRequest = {
4
4
  text: string;
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  InMemoryVectorStore,
3
3
  createTool
4
- } from "./chunk-MELYDKWQ.js";
5
- import {
6
- embedDocuments
7
- } from "./chunk-MNWK2USR.js";
4
+ } from "./chunk-4BGN6PYF.js";
8
5
  import {
9
6
  isToolResultContentArray,
10
7
  serializeToolResultOutput
11
- } from "./chunk-PJDL5UT2.js";
8
+ } from "./chunk-ADH7NNCS.js";
9
+ import {
10
+ embedDocuments
11
+ } from "./chunk-MNWK2USR.js";
12
12
 
13
13
  // src/tool/errors.ts
14
14
  var ToolCallError = class extends Error {
@@ -220,4 +220,4 @@ export {
220
220
  createMiddleware,
221
221
  createThinkTool
222
222
  };
223
- //# sourceMappingURL=chunk-6X2UTX3L.js.map
223
+ //# sourceMappingURL=chunk-2NDQHV7V.js.map
@@ -1,10 +1,10 @@
1
+ import {
2
+ toProviderJsonSchema
3
+ } from "./chunk-WQKHFADH.js";
1
4
  import {
2
5
  cosineSimilarity,
3
6
  embedText
4
7
  } from "./chunk-MNWK2USR.js";
5
- import {
6
- toProviderJsonSchema
7
- } from "./chunk-WQKHFADH.js";
8
8
 
9
9
  // src/vector-store/index.ts
10
10
  import { z } from "zod";
@@ -334,4 +334,4 @@ export {
334
334
  InMemoryVectorIndex,
335
335
  createVectorSearchTool
336
336
  };
337
- //# sourceMappingURL=chunk-MELYDKWQ.js.map
337
+ //# sourceMappingURL=chunk-4BGN6PYF.js.map
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  Agent,
3
3
  normalizeAgentId
4
- } from "./chunk-N3YV3WCO.js";
4
+ } from "./chunk-YEBIVZM2.js";
5
5
  import {
6
6
  ToolSet
7
- } from "./chunk-6X2UTX3L.js";
7
+ } from "./chunk-2NDQHV7V.js";
8
8
  import {
9
9
  resolveMemoryOptions
10
- } from "./chunk-ZNTIUOKL.js";
10
+ } from "./chunk-UQX6EXWG.js";
11
11
  import {
12
12
  isProviderTool
13
- } from "./chunk-PJDL5UT2.js";
13
+ } from "./chunk-ADH7NNCS.js";
14
14
  import {
15
15
  toProviderJsonSchema
16
16
  } from "./chunk-WQKHFADH.js";
@@ -217,4 +217,4 @@ var AgentBuilder = class {
217
217
  export {
218
218
  AgentBuilder
219
219
  };
220
- //# sourceMappingURL=chunk-WHAPIIEZ.js.map
220
+ //# sourceMappingURL=chunk-4HWN7734.js.map
@@ -266,6 +266,29 @@ function isProviderTool(value) {
266
266
  const candidate = value;
267
267
  return candidate.kind === "provider" && typeof candidate.provider === "string" && candidate.provider.trim().length > 0 && typeof candidate.name === "string" && candidate.name.trim().length > 0 && (candidate.configuration === void 0 || typeof candidate.configuration === "object" && candidate.configuration !== null && !Array.isArray(candidate.configuration) && isJsonValue(candidate.configuration));
268
268
  }
269
+ function calculateContextUsage(usage, model) {
270
+ if (model === void 0 || !Number.isFinite(usage.inputTokens) || usage.inputTokens <= 0 || !Number.isFinite(model.context.contextWindow) || model.context.contextWindow <= 0) {
271
+ return void 0;
272
+ }
273
+ const usedTokens = Math.max(0, usage.inputTokens);
274
+ const remainingTokens = Math.max(0, model.context.contextWindow - usedTokens);
275
+ const usedPercent = Math.min(100, usedTokens / model.context.contextWindow * 100);
276
+ return {
277
+ model,
278
+ usedTokens,
279
+ remainingTokens,
280
+ usedPercent,
281
+ remainingPercent: 100 - usedPercent
282
+ };
283
+ }
284
+ function withContextUsage(response, model) {
285
+ const contextUsage = calculateContextUsage(response.usage, model);
286
+ return contextUsage === void 0 ? response : { ...response, contextUsage };
287
+ }
288
+ function resolveCompletionModelInfo(model, catalog, overrides) {
289
+ const context = overrides?.[model] ?? catalog[model];
290
+ return context === void 0 ? void 0 : { id: model, context };
291
+ }
269
292
  var Usage = {
270
293
  empty() {
271
294
  return {
@@ -330,6 +353,15 @@ function getAssistantGenerationMetadata(message) {
330
353
  ...generation.usage.details === void 0 ? {} : { details: { ...generation.usage.details } }
331
354
  }
332
355
  };
356
+ if (isContextUsageValue(generation.contextUsage)) {
357
+ metadata.contextUsage = {
358
+ ...generation.contextUsage,
359
+ model: {
360
+ ...generation.contextUsage.model,
361
+ context: { ...generation.contextUsage.model.context }
362
+ }
363
+ };
364
+ }
333
365
  if (isCompletionSourceArray(generation.sources)) {
334
366
  metadata.sources = generation.sources.map((source) => ({ ...source }));
335
367
  }
@@ -344,6 +376,33 @@ function getAssistantGenerationMetadata(message) {
344
376
  function isJsonObjectValue(value) {
345
377
  return typeof value === "object" && value !== null && !Array.isArray(value);
346
378
  }
379
+ function isContextUsageValue(value) {
380
+ if (!isJsonObjectValue(value) || !isJsonObjectValue(value.model)) {
381
+ return false;
382
+ }
383
+ const context = value.model.context;
384
+ if (typeof value.model.id === "string" && isJsonObjectValue(context) && isPositiveFiniteNumber(context.contextWindow) && isOptionalPositiveFiniteNumber(context.maxInputTokens) && isOptionalPositiveFiniteNumber(context.maxOutputTokens) && isNonnegativeFiniteNumber(value.usedTokens) && isNonnegativeFiniteNumber(value.remainingTokens) && isPercentage(value.usedPercent) && isPercentage(value.remainingPercent)) {
385
+ const contextWindow = context.contextWindow;
386
+ const remainingTokens = Math.max(0, contextWindow - value.usedTokens);
387
+ const usedPercent = Math.min(100, value.usedTokens / contextWindow * 100);
388
+ const remainingPercent = remainingTokens / contextWindow * 100;
389
+ return value.remainingTokens === remainingTokens && approximatelyEqual(value.usedPercent, usedPercent) && approximatelyEqual(value.remainingPercent, remainingPercent);
390
+ }
391
+ return false;
392
+ }
393
+ function approximatelyEqual(left, right) {
394
+ const scale = Math.max(1, Math.abs(left), Math.abs(right));
395
+ return Math.abs(left - right) <= Number.EPSILON * scale * 8;
396
+ }
397
+ function isPositiveFiniteNumber(value) {
398
+ return isNonnegativeFiniteNumber(value) && value > 0;
399
+ }
400
+ function isOptionalPositiveFiniteNumber(value) {
401
+ return value === void 0 || isPositiveFiniteNumber(value);
402
+ }
403
+ function isPercentage(value) {
404
+ return isNonnegativeFiniteNumber(value) && value <= 100;
405
+ }
347
406
  function isUsageValue(value) {
348
407
  if (!isJsonObjectValue(value)) {
349
408
  return false;
@@ -441,10 +500,13 @@ export {
441
500
  reasoningDisplayText,
442
501
  Message,
443
502
  isProviderTool,
503
+ calculateContextUsage,
504
+ withContextUsage,
505
+ resolveCompletionModelInfo,
444
506
  Usage,
445
507
  getAssistantGenerationMetadata,
446
508
  CompletionCapabilityError,
447
509
  assertCompletionRequestSupported,
448
510
  textFromAssistantContent
449
511
  };
450
- //# sourceMappingURL=chunk-PJDL5UT2.js.map
512
+ //# sourceMappingURL=chunk-ADH7NNCS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/completion/json.ts","../src/completion/types.ts"],"sourcesContent":["import type { JsonValue } from \"./types\";\n\nexport function isJsonValue(value: unknown): value is JsonValue {\n return isJsonValueWithAncestors(value, new WeakSet<object>());\n}\n\nfunction isJsonValueWithAncestors(value: unknown, ancestors: WeakSet<object>): value is JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return true;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n if (typeof value !== \"object\" || ancestors.has(value)) {\n return false;\n }\n\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n if (!hasOnlyDenseArrayProperties(value)) {\n return false;\n }\n for (let index = 0; index < value.length; index += 1) {\n if (!isJsonValueWithAncestors(value[index], ancestors)) {\n return false;\n }\n }\n return true;\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return false;\n }\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== \"string\") {\n return false;\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n descriptor === undefined ||\n !descriptor.enumerable ||\n !(\"value\" in descriptor) ||\n !isJsonValueWithAncestors(descriptor.value, ancestors)\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction hasOnlyDenseArrayProperties(value: unknown[]): boolean {\n const keys = Reflect.ownKeys(value);\n if (keys.length !== value.length + 1 || keys.at(-1) !== \"length\") {\n return false;\n }\n for (let index = 0; index < value.length; index += 1) {\n const key = String(index);\n if (keys[index] !== key) {\n return false;\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !descriptor.enumerable || !(\"value\" in descriptor)) {\n return false;\n }\n }\n return true;\n}\n","import { isJsonValue } from \"./json\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\nexport type JsonObject = { [key: string]: JsonValue | undefined };\n\nexport type Document = {\n id: string;\n text: string;\n additionalProps?: Record<string, string>;\n};\n\nexport type Text = {\n type: \"text\";\n text: string;\n signature?: string;\n};\n\nexport type ImageDetail = \"auto\" | \"low\" | \"high\";\n\nexport type ImageContent = {\n type: \"image\";\n source:\n | {\n type: \"url\";\n url: string;\n }\n | {\n type: \"base64\";\n data: string;\n mediaType: string;\n };\n detail?: ImageDetail;\n};\n\nexport type DocumentContent = {\n type: \"document\";\n source:\n | {\n type: \"url\";\n url: string;\n mediaType: string;\n filename?: string;\n }\n | {\n type: \"base64\";\n data: string;\n mediaType: string;\n filename?: string;\n }\n | {\n type: \"text\";\n text: string;\n mediaType?: string;\n filename?: string;\n };\n};\n\nexport type Reasoning = {\n type: \"reasoning\";\n text: string;\n id?: string;\n content?: ReasoningContent[];\n};\n\nexport type ReasoningContent =\n | {\n type: \"text\";\n text: string;\n signature?: string;\n }\n | {\n type: \"summary\";\n text: string;\n }\n | {\n type: \"encrypted\";\n data: string;\n }\n | {\n type: \"redacted\";\n data: string;\n };\n\nexport type ReasoningContentType = ReasoningContent[\"type\"];\n\nexport type ToolFunction = {\n name: string;\n arguments: JsonValue;\n};\n\nexport type ToolCall = {\n type: \"tool_call\";\n id: string;\n callId?: string;\n function: ToolFunction;\n signature?: string;\n additionalParams?: JsonValue;\n};\n\nexport type ToolResultContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mediaType?: string };\n\nexport type ToolResult = {\n type: \"tool_result\";\n id: string;\n callId?: string;\n toolName?: string;\n content: ToolResultContent[];\n};\n\nexport type MessageOptions = {\n metadata?: JsonValue | undefined;\n};\n\nexport type AssistantMessageOptions = MessageOptions & {\n id?: string | undefined;\n};\n\nexport type ToolResultOptions = {\n callId?: string | undefined;\n toolName?: string | undefined;\n};\n\nexport type ToolResultMessageOptions = ToolResultOptions & MessageOptions;\n\nexport type UserContent = Text | ImageContent | DocumentContent;\nexport type AssistantContent = Text | ToolCall | Reasoning | ImageContent;\nexport type ToolContent = ToolResult;\n\nexport type SystemMessage = {\n role: \"system\";\n content: string;\n metadata?: JsonValue;\n};\n\nexport type UserMessage = {\n role: \"user\";\n content: UserContent[];\n metadata?: JsonValue;\n};\n\nexport type AssistantMessage = {\n role: \"assistant\";\n id?: string;\n content: AssistantContent[];\n metadata?: JsonValue;\n};\n\nexport type ToolMessage = {\n role: \"tool\";\n content: ToolContent[];\n metadata?: JsonValue;\n};\n\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage;\n\nexport const UserContent = {\n text(text: string): Text {\n return { type: \"text\", text };\n },\n imageUrl(url: string, options: { detail?: ImageDetail } = {}): ImageContent {\n const image: ImageContent = { type: \"image\", source: { type: \"url\", url } };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n imageBase64(\n data: string,\n mediaType: string,\n options: { detail?: ImageDetail } = {},\n ): ImageContent {\n const image: ImageContent = {\n type: \"image\",\n source: { type: \"base64\", data, mediaType },\n };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n documentUrl(\n url: string,\n mediaType: string,\n options: { filename?: string | undefined } = {},\n ): DocumentContent {\n return {\n type: \"document\",\n source:\n options.filename === undefined\n ? { type: \"url\", url, mediaType }\n : { type: \"url\", url, mediaType, filename: options.filename },\n };\n },\n documentBase64(\n data: string,\n mediaType: string,\n options: { filename?: string | undefined } = {},\n ): DocumentContent {\n return {\n type: \"document\",\n source:\n options.filename === undefined\n ? { type: \"base64\", data, mediaType }\n : { type: \"base64\", data, mediaType, filename: options.filename },\n };\n },\n documentText(text: string): Text {\n return { type: \"text\", text };\n },\n};\n\nexport const ToolContent = {\n toolResult(\n id: string,\n content: string | ToolResultContent[],\n callIdOrOptions?: string | ToolResultOptions,\n toolName?: string,\n ): ToolResult {\n const normalized =\n typeof content === \"string\" ? [{ type: \"text\" as const, text: content }] : content;\n const options = normalizeToolResultOptions(callIdOrOptions, toolName);\n const result: ToolResult = { type: \"tool_result\", id, content: normalized };\n if (options.callId !== undefined) {\n result.callId = options.callId;\n }\n if (options.toolName !== undefined) {\n result.toolName = options.toolName;\n }\n return result;\n },\n};\n\nfunction normalizeToolResultOptions(\n callIdOrOptions?: string | ToolResultOptions,\n toolName?: string,\n): ToolResultOptions {\n if (callIdOrOptions === undefined) {\n return toolName === undefined ? {} : { toolName };\n }\n if (typeof callIdOrOptions === \"string\") {\n return toolName === undefined\n ? { callId: callIdOrOptions }\n : { callId: callIdOrOptions, toolName };\n }\n return toolName === undefined ? callIdOrOptions : { ...callIdOrOptions, toolName };\n}\n\nexport function serializeToolResultOutput(output: unknown): string {\n if (typeof output === \"string\") {\n return output;\n }\n\n try {\n const serialized = JSON.stringify(output);\n return serialized === undefined ? String(output) : serialized;\n } catch {\n return String(output);\n }\n}\n\nexport function isToolResultContentArray(value: unknown): value is ToolResultContent[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((item) => {\n if (typeof item !== \"object\" || item === null || !(\"type\" in item)) {\n return false;\n }\n if (item.type === \"text\") {\n return \"text\" in item && typeof item.text === \"string\";\n }\n if (item.type === \"image\") {\n return (\n \"data\" in item &&\n typeof item.data === \"string\" &&\n (!(\"mediaType\" in item) ||\n item.mediaType === undefined ||\n typeof item.mediaType === \"string\")\n );\n }\n return false;\n })\n );\n}\n\nexport const AssistantContent = {\n text(text: string): Text {\n return { type: \"text\", text };\n },\n imageUrl(url: string, options: { detail?: ImageDetail } = {}): ImageContent {\n const image: ImageContent = { type: \"image\", source: { type: \"url\", url } };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n imageBase64(\n data: string,\n mediaType: string,\n options: { detail?: ImageDetail } = {},\n ): ImageContent {\n const image: ImageContent = {\n type: \"image\",\n source: { type: \"base64\", data, mediaType },\n };\n if (options.detail !== undefined) {\n image.detail = options.detail;\n }\n return image;\n },\n reasoning(text: string, id?: string): Reasoning {\n return id === undefined ? { type: \"reasoning\", text } : { type: \"reasoning\", text, id };\n },\n reasoningFromContent(content: ReasoningContent[], id?: string): Reasoning {\n const text = reasoningDisplayText(content);\n const reasoning: Reasoning = { type: \"reasoning\", text, content };\n return id === undefined ? reasoning : { ...reasoning, id };\n },\n reasoningSummary(text: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"summary\", text }], id);\n },\n reasoningEncrypted(data: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"encrypted\", data }], id);\n },\n reasoningRedacted(data: string, id?: string): Reasoning {\n return AssistantContent.reasoningFromContent([{ type: \"redacted\", data }], id);\n },\n toolCall(id: string, name: string, args: JsonValue, callId?: string): ToolCall {\n const base: ToolCall = {\n type: \"tool_call\",\n id,\n function: {\n name,\n arguments: args,\n },\n };\n return callId === undefined ? base : { ...base, callId };\n },\n};\n\nexport function reasoningDisplayText(reasoning: Reasoning | ReasoningContent[]): string {\n const content = Array.isArray(reasoning) ? reasoning : reasoning.content;\n if (content === undefined) {\n return Array.isArray(reasoning) ? \"\" : reasoning.text;\n }\n return content\n .flatMap((item) => {\n if (item.type === \"text\" || item.type === \"summary\") {\n return [item.text];\n }\n return [];\n })\n .join(\"\");\n}\n\nexport const Message = {\n system(content: string, options: MessageOptions = {}): Message {\n return { role: \"system\", content, ...messageMetadata(options) };\n },\n user(content: string | UserContent[], options: MessageOptions = {}): Message {\n return {\n role: \"user\",\n content: typeof content === \"string\" ? [UserContent.text(content)] : content,\n ...messageMetadata(options),\n };\n },\n assistant(\n content: string | AssistantContent[],\n idOrOptions?: string | AssistantMessageOptions,\n ): Message {\n const normalized = typeof content === \"string\" ? [AssistantContent.text(content)] : content;\n const options = typeof idOrOptions === \"string\" ? { id: idOrOptions } : (idOrOptions ?? {});\n const metadata = messageMetadata(options).metadata;\n const message: AssistantMessage =\n options.id === undefined\n ? { role: \"assistant\", content: normalized }\n : { role: \"assistant\", id: options.id, content: normalized };\n if (metadata !== undefined) {\n message.metadata = metadata;\n }\n return message;\n },\n tool(content: ToolContent | ToolContent[], options: MessageOptions = {}): Message {\n return {\n role: \"tool\",\n content: Array.isArray(content) ? content : [content],\n ...messageMetadata(options),\n };\n },\n toolResult(id: string, output: unknown, options: ToolResultMessageOptions = {}): Message {\n const content = isToolResultContentArray(output) ? output : serializeToolResultOutput(output);\n return Message.tool(\n ToolContent.toolResult(id, content, {\n callId: options.callId,\n toolName: options.toolName,\n }),\n { metadata: options.metadata },\n );\n },\n};\n\nfunction messageMetadata(options: MessageOptions): { metadata?: JsonValue } {\n if (options.metadata === undefined) {\n return {};\n }\n if (!isJsonValue(options.metadata)) {\n throw new TypeError(\"Message metadata must be a strict JSON value.\");\n }\n return { metadata: options.metadata };\n}\n\nexport type ToolChoice =\n | \"auto\"\n | \"required\"\n | \"none\"\n | {\n type: \"function\";\n name: string;\n };\n\nexport type ToolDefinition = {\n name: string;\n description: string;\n parameters: JsonObject;\n};\n\n/**\n * A tool executed by the model provider rather than by Anvia's local tool runtime.\n *\n * Provider packages expose typed factories for these values. Application code can\n * pass them through the same high-level `tools` APIs used for local tools.\n */\nexport type ProviderTool = {\n kind: \"provider\";\n provider: string;\n name: string;\n configuration?: JsonObject;\n};\n\nexport type CompletionTool = ToolDefinition | ProviderTool;\n\nexport function isProviderTool(value: unknown): value is ProviderTool {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const candidate = value as Partial<ProviderTool>;\n return (\n candidate.kind === \"provider\" &&\n typeof candidate.provider === \"string\" &&\n candidate.provider.trim().length > 0 &&\n typeof candidate.name === \"string\" &&\n candidate.name.trim().length > 0 &&\n (candidate.configuration === undefined ||\n (typeof candidate.configuration === \"object\" &&\n candidate.configuration !== null &&\n !Array.isArray(candidate.configuration) &&\n isJsonValue(candidate.configuration)))\n );\n}\n\nexport type CompletionSource = {\n type: \"url\";\n url: string;\n title?: string;\n id?: string;\n startIndex?: number;\n endIndex?: number;\n};\n\nexport type ProviderToolCall = {\n id: string;\n name: string;\n status?: string;\n details?: JsonObject;\n};\n\n/**\n * Provider-normalized, mutually exclusive usage buckets.\n *\n * Every token should appear in exactly one non-total bucket. `total` is the\n * only aggregate key and should equal the sum of the other buckets.\n */\nexport type UsageDetails = Record<string, number>;\n\nexport type Usage = {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cachedInputTokens: number;\n cacheCreationInputTokens: number;\n details?: UsageDetails;\n};\n\nexport type ModelContextLimits = {\n contextWindow: number;\n maxInputTokens?: number;\n maxOutputTokens?: number;\n};\n\nexport type CompletionModelInfo<ModelName extends string = string> = {\n id: ModelName;\n context: ModelContextLimits;\n};\n\nexport type CompletionModelMetadataOptions = {\n modelOverrides?: Readonly<Record<string, ModelContextLimits>>;\n};\n\nexport type ContextUsage<ModelName extends string = string> = {\n model: CompletionModelInfo<ModelName>;\n usedTokens: number;\n remainingTokens: number;\n usedPercent: number;\n remainingPercent: number;\n};\n\nexport function calculateContextUsage<ModelName extends string>(\n usage: Usage,\n model: CompletionModelInfo<ModelName> | undefined,\n): ContextUsage<ModelName> | undefined {\n if (\n model === undefined ||\n !Number.isFinite(usage.inputTokens) ||\n usage.inputTokens <= 0 ||\n !Number.isFinite(model.context.contextWindow) ||\n model.context.contextWindow <= 0\n ) {\n return undefined;\n }\n\n const usedTokens = Math.max(0, usage.inputTokens);\n const remainingTokens = Math.max(0, model.context.contextWindow - usedTokens);\n const usedPercent = Math.min(100, (usedTokens / model.context.contextWindow) * 100);\n return {\n model,\n usedTokens,\n remainingTokens,\n usedPercent,\n remainingPercent: 100 - usedPercent,\n };\n}\n\nexport function withContextUsage<RawResponse, ModelName extends string>(\n response: CompletionResponse<RawResponse>,\n model: CompletionModelInfo<ModelName> | undefined,\n): CompletionResponse<RawResponse> {\n const contextUsage = calculateContextUsage(response.usage, model);\n return contextUsage === undefined ? response : { ...response, contextUsage };\n}\n\nexport function resolveCompletionModelInfo<ModelName extends string>(\n model: ModelName,\n catalog: Readonly<Record<string, ModelContextLimits>>,\n overrides?: Readonly<Record<string, ModelContextLimits>>,\n): CompletionModelInfo<ModelName> | undefined {\n const context = overrides?.[model] ?? catalog[model];\n return context === undefined ? undefined : { id: model, context };\n}\n\nexport type AssistantGenerationMetadata = {\n provider: string;\n model: string;\n usage: Usage;\n contextUsage?: ContextUsage;\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n};\n\nexport const Usage = {\n empty(): Usage {\n return {\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n cachedInputTokens: 0,\n cacheCreationInputTokens: 0,\n };\n },\n add(left: Usage, right: Usage): Usage {\n const result: Usage = {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n totalTokens: left.totalTokens + right.totalTokens,\n cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,\n cacheCreationInputTokens: left.cacheCreationInputTokens + right.cacheCreationInputTokens,\n };\n const details = addUsageDetails(left, right);\n if (details !== undefined) {\n result.details = details;\n }\n return result;\n },\n};\n\nfunction addUsageDetails(left: Usage, right: Usage): UsageDetails | undefined {\n if (isEmptyUsage(left) && left.details === undefined) {\n return right.details === undefined ? undefined : { ...right.details };\n }\n if (isEmptyUsage(right) && right.details === undefined) {\n return left.details === undefined ? undefined : { ...left.details };\n }\n if (left.details === undefined || right.details === undefined) {\n return undefined;\n }\n const details: UsageDetails = { ...left.details };\n for (const [key, value] of Object.entries(right.details)) {\n details[key] = (details[key] ?? 0) + value;\n }\n return details;\n}\n\nfunction isEmptyUsage(usage: Usage): boolean {\n return (\n usage.inputTokens === 0 &&\n usage.outputTokens === 0 &&\n usage.totalTokens === 0 &&\n usage.cachedInputTokens === 0 &&\n usage.cacheCreationInputTokens === 0\n );\n}\n\nexport function getAssistantGenerationMetadata(\n message: Message,\n): AssistantGenerationMetadata | undefined {\n if (message.role !== \"assistant\" || !isJsonObjectValue(message.metadata)) {\n return undefined;\n }\n const frameworkMetadata = message.metadata.anvia;\n if (!isJsonObjectValue(frameworkMetadata)) {\n return undefined;\n }\n const generation = frameworkMetadata.generation;\n if (\n !isJsonObjectValue(generation) ||\n typeof generation.provider !== \"string\" ||\n typeof generation.model !== \"string\" ||\n !isUsageValue(generation.usage)\n ) {\n return undefined;\n }\n const metadata: AssistantGenerationMetadata = {\n provider: generation.provider,\n model: generation.model,\n usage: {\n ...generation.usage,\n ...(generation.usage.details === undefined\n ? {}\n : { details: { ...generation.usage.details } }),\n },\n };\n if (isContextUsageValue(generation.contextUsage)) {\n metadata.contextUsage = {\n ...generation.contextUsage,\n model: {\n ...generation.contextUsage.model,\n context: { ...generation.contextUsage.model.context },\n },\n };\n }\n if (isCompletionSourceArray(generation.sources)) {\n metadata.sources = generation.sources.map((source) => ({ ...source }));\n }\n if (isProviderToolCallArray(generation.providerToolCalls)) {\n metadata.providerToolCalls = generation.providerToolCalls.map((toolCall) => ({\n ...toolCall,\n ...(toolCall.details === undefined ? {} : { details: { ...toolCall.details } }),\n }));\n }\n return metadata;\n}\n\nfunction isJsonObjectValue(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isContextUsageValue(value: JsonValue | undefined): value is JsonObject & ContextUsage {\n if (!isJsonObjectValue(value) || !isJsonObjectValue(value.model)) {\n return false;\n }\n const context = value.model.context;\n if (\n typeof value.model.id === \"string\" &&\n isJsonObjectValue(context) &&\n isPositiveFiniteNumber(context.contextWindow) &&\n isOptionalPositiveFiniteNumber(context.maxInputTokens) &&\n isOptionalPositiveFiniteNumber(context.maxOutputTokens) &&\n isNonnegativeFiniteNumber(value.usedTokens) &&\n isNonnegativeFiniteNumber(value.remainingTokens) &&\n isPercentage(value.usedPercent) &&\n isPercentage(value.remainingPercent)\n ) {\n const contextWindow = context.contextWindow;\n const remainingTokens = Math.max(0, contextWindow - value.usedTokens);\n const usedPercent = Math.min(100, (value.usedTokens / contextWindow) * 100);\n const remainingPercent = (remainingTokens / contextWindow) * 100;\n return (\n value.remainingTokens === remainingTokens &&\n approximatelyEqual(value.usedPercent, usedPercent) &&\n approximatelyEqual(value.remainingPercent, remainingPercent)\n );\n }\n return false;\n}\n\nfunction approximatelyEqual(left: number, right: number): boolean {\n const scale = Math.max(1, Math.abs(left), Math.abs(right));\n return Math.abs(left - right) <= Number.EPSILON * scale * 8;\n}\n\nfunction isPositiveFiniteNumber(value: JsonValue | undefined): value is number {\n return isNonnegativeFiniteNumber(value) && value > 0;\n}\n\nfunction isOptionalPositiveFiniteNumber(value: JsonValue | undefined): boolean {\n return value === undefined || isPositiveFiniteNumber(value);\n}\n\nfunction isPercentage(value: JsonValue | undefined): value is number {\n return isNonnegativeFiniteNumber(value) && value <= 100;\n}\n\nfunction isUsageValue(value: JsonValue | undefined): value is JsonObject & Usage {\n if (!isJsonObjectValue(value)) {\n return false;\n }\n return (\n isNonnegativeFiniteNumber(value.inputTokens) &&\n isNonnegativeFiniteNumber(value.outputTokens) &&\n isNonnegativeFiniteNumber(value.totalTokens) &&\n isNonnegativeFiniteNumber(value.cachedInputTokens) &&\n isNonnegativeFiniteNumber(value.cacheCreationInputTokens) &&\n isUsageDetailsValue(value.details)\n );\n}\n\nfunction isNonnegativeFiniteNumber(value: JsonValue | undefined): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\nfunction isUsageDetailsValue(value: JsonValue | undefined): value is JsonObject | undefined {\n if (value === undefined) {\n return true;\n }\n if (!isJsonObjectValue(value)) {\n return false;\n }\n let total: number | undefined;\n let bucketSum = 0;\n for (const [key, detail] of Object.entries(value)) {\n if (detail === undefined || !isNonnegativeFiniteNumber(detail)) {\n return false;\n }\n if (key === \"total\") {\n total = detail;\n } else {\n bucketSum += detail;\n }\n }\n return total !== undefined && total === bucketSum;\n}\n\nfunction isCompletionSourceArray(value: JsonValue | undefined): value is CompletionSource[] {\n return (\n Array.isArray(value) &&\n value.every(\n (source) =>\n isJsonObjectValue(source) &&\n source.type === \"url\" &&\n typeof source.url === \"string\" &&\n (source.title === undefined || typeof source.title === \"string\") &&\n (source.id === undefined || typeof source.id === \"string\") &&\n (source.startIndex === undefined || typeof source.startIndex === \"number\") &&\n (source.endIndex === undefined || typeof source.endIndex === \"number\"),\n )\n );\n}\n\nfunction isProviderToolCallArray(value: JsonValue | undefined): value is ProviderToolCall[] {\n return (\n Array.isArray(value) &&\n value.every(\n (toolCall) =>\n isJsonObjectValue(toolCall) &&\n typeof toolCall.id === \"string\" &&\n typeof toolCall.name === \"string\" &&\n (toolCall.status === undefined || typeof toolCall.status === \"string\") &&\n (toolCall.details === undefined || isJsonObjectValue(toolCall.details)),\n )\n );\n}\n\nexport type CompletionRequest<ModelName extends string = string> = {\n model?: ModelName;\n instructions?: string;\n chatHistory: Message[];\n documents: Document[];\n tools: ToolDefinition[];\n providerTools?: ProviderTool[];\n temperature?: number;\n maxTokens?: number;\n toolChoice?: ToolChoice;\n additionalParams?: JsonValue;\n outputSchema?: JsonObject;\n};\n\nexport type CompletionResponse<RawResponse = unknown> = {\n choice: AssistantContent[];\n usage: Usage;\n contextUsage?: ContextUsage;\n rawResponse: RawResponse;\n messageId?: string;\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n};\n\nexport type CompletionModelCapabilities = {\n streaming: boolean;\n tools: boolean;\n toolChoice: boolean;\n imageInput: boolean;\n documentInput: boolean;\n outputSchema: boolean;\n reasoning: boolean;\n providerTools?: boolean;\n};\n\nexport interface CompletionModel<RawResponse = unknown, ModelName extends string = string> {\n readonly provider: string;\n readonly defaultModel: ModelName;\n readonly capabilities: CompletionModelCapabilities;\n getModelInfo?(model?: ModelName): CompletionModelInfo<ModelName> | undefined;\n traceRequest?(\n request: CompletionRequest<ModelName>,\n options?: { stream?: boolean | undefined },\n ): JsonObject | undefined;\n completion(request: CompletionRequest<ModelName>): Promise<CompletionResponse<RawResponse>>;\n}\n\nexport type ToolCallArgumentsMode = \"append\" | \"replace\";\n\nexport type CompletionStreamEvent<RawResponse = unknown> =\n | {\n type: \"text_delta\";\n delta: string;\n }\n | {\n type: \"reasoning_delta\";\n delta: string;\n id?: string;\n contentType?: ReasoningContentType;\n signature?: string;\n }\n | {\n type: \"tool_call_delta\";\n id: string;\n callId?: string;\n name?: string;\n argumentsDelta?: string;\n argumentsMode?: ToolCallArgumentsMode;\n signature?: string;\n }\n | {\n type: \"tool_call\";\n toolCall: ToolCall;\n }\n | {\n type: \"source\";\n source: CompletionSource;\n }\n | {\n type: \"provider_tool_call\";\n toolCall: ProviderToolCall;\n }\n | {\n type: \"message_id\";\n id: string;\n }\n | {\n type: \"final\";\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n usage?: Usage;\n };\n\nexport interface StreamingCompletionModel<RawResponse = unknown, ModelName extends string = string>\n extends CompletionModel<RawResponse, ModelName> {\n streamCompletion(\n request: CompletionRequest<ModelName>,\n ): AsyncIterable<CompletionStreamEvent<RawResponse>>;\n}\n\nexport class CompletionCapabilityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CompletionCapabilityError\";\n }\n}\n\nexport function assertCompletionRequestSupported(\n model: CompletionModel,\n request: CompletionRequest,\n options: { streaming?: boolean | undefined } = {},\n): void {\n const modelLabel = `${model.provider}:${request.model ?? model.defaultModel}`;\n const capabilities = model.capabilities;\n\n if (options.streaming === true && !capabilities.streaming) {\n throw new CompletionCapabilityError(`${modelLabel} does not support streaming completions.`);\n }\n\n if (request.tools.length > 0 && !capabilities.tools) {\n throw new CompletionCapabilityError(`${modelLabel} does not support tool definitions.`);\n }\n\n if ((request.providerTools?.length ?? 0) > 0 && capabilities.providerTools !== true) {\n throw new CompletionCapabilityError(`${modelLabel} does not support provider-executed tools.`);\n }\n\n if (request.toolChoice !== undefined && !capabilities.toolChoice) {\n throw new CompletionCapabilityError(`${modelLabel} does not support tool choice.`);\n }\n\n if (request.outputSchema !== undefined && !capabilities.outputSchema) {\n throw new CompletionCapabilityError(`${modelLabel} does not support output schemas.`);\n }\n\n if (!capabilities.imageInput && requestHasImageInput(request)) {\n throw new CompletionCapabilityError(`${modelLabel} does not support image input.`);\n }\n\n if (!capabilities.documentInput && requestHasFileDocumentInput(request)) {\n throw new CompletionCapabilityError(`${modelLabel} does not support document file input.`);\n }\n}\n\nexport function textFromAssistantContent(content: AssistantContent[]): string {\n return content.flatMap((item) => (item.type === \"text\" ? [item.text] : [])).join(\"\\n\");\n}\n\nfunction requestHasImageInput(request: CompletionRequest): boolean {\n return request.chatHistory.some((message) =>\n message.role === \"system\" ? false : message.content.some((content) => content.type === \"image\"),\n );\n}\n\nfunction requestHasFileDocumentInput(request: CompletionRequest): boolean {\n return request.chatHistory.some((message) =>\n message.role === \"user\"\n ? message.content.some(\n (content) => content.type === \"document\" && content.source.type !== \"text\",\n )\n : false,\n );\n}\n"],"mappings":";AAEO,SAAS,YAAY,OAAoC;AAC9D,SAAO,yBAAyB,OAAO,oBAAI,QAAgB,CAAC;AAC9D;AAEA,SAAS,yBAAyB,OAAgB,WAAgD;AAChG,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW;AAC7E,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,OAAO,SAAS,KAAK;AAAA,EAC9B;AACA,MAAI,OAAO,UAAU,YAAY,UAAU,IAAI,KAAK,GAAG;AACrD,WAAO;AAAA,EACT;AAEA,YAAU,IAAI,KAAK;AACnB,MAAI;AACF,QAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,UAAI,CAAC,4BAA4B,KAAK,GAAG;AACvC,eAAO;AAAA,MACT;AACA,eAAS,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;AACpD,YAAI,CAAC,yBAAyB,MAAM,KAAK,GAAG,SAAS,GAAG;AACtD,iBAAO;AAAA,QACT;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAEA,UAAM,YAAY,OAAO,eAAe,KAAK;AAC7C,QAAI,cAAc,OAAO,aAAa,cAAc,MAAM;AACxD,aAAO;AAAA,IACT;AACA,eAAW,OAAO,QAAQ,QAAQ,KAAK,GAAG;AACxC,UAAI,OAAO,QAAQ,UAAU;AAC3B,eAAO;AAAA,MACT;AACA,YAA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GAAG,UAAU,gCAAgC;AAAA,EACnF;AAEA,MAAI,CAAC,aAAa,iBAAiB,4BAA4B,OAAO,GAAG;AACvE,UAAM,IAAI,0BAA0B,GAAG,UAAU,wCAAwC;AAAA,EAC3F;AACF;AAEO,SAAS,yBAAyB,SAAqC;AAC5E,SAAO,QAAQ,QAAQ,CAAC,SAAU,KAAK,SAAS,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,CAAE,EAAE,KAAK,IAAI;AACvF;AAEA,SAAS,qBAAqB,SAAqC;AACjE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,WAAW,QAAQ,QAAQ,QAAQ,KAAK,CAAC,YAAY,QAAQ,SAAS,OAAO;AAAA,EAChG;AACF;AAEA,SAAS,4BAA4B,SAAqC;AACxE,SAAO,QAAQ,YAAY;AAAA,IAAK,CAAC,YAC/B,QAAQ,SAAS,SACb,QAAQ,QAAQ;AAAA,MACd,CAAC,YAAY,QAAQ,SAAS,cAAc,QAAQ,OAAO,SAAS;AAAA,IACtE,IACA;AAAA,EACN;AACF;","names":[]}
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-YK4WAAS4.js";
7
7
  import {
8
8
  createTool
9
- } from "./chunk-MELYDKWQ.js";
9
+ } from "./chunk-4BGN6PYF.js";
10
10
 
11
11
  // src/skills/instructions.ts
12
12
  function skillInstructions(skills) {
@@ -395,4 +395,4 @@ export {
395
395
  SkillValidationError,
396
396
  skill
397
397
  };
398
- //# sourceMappingURL=chunk-NCPN4SJR.js.map
398
+ //# sourceMappingURL=chunk-BCA4VZ5W.js.map
@@ -6,7 +6,7 @@ import {
6
6
  isJsonValue,
7
7
  reasoningDisplayText,
8
8
  serializeToolResultOutput
9
- } from "./chunk-PJDL5UT2.js";
9
+ } from "./chunk-ADH7NNCS.js";
10
10
 
11
11
  // src/ui/messages.ts
12
12
  function uiMessagesToCoreMessages(messages) {
@@ -463,4 +463,4 @@ export {
463
463
  uiMessagesToCoreMessages,
464
464
  coreMessagesToUIMessages
465
465
  };
466
- //# sourceMappingURL=chunk-SWUH4G2I.js.map
466
+ //# sourceMappingURL=chunk-I6XOQ4LK.js.map
@@ -1,20 +1,20 @@
1
1
  import {
2
2
  AgentBuilder
3
- } from "./chunk-WHAPIIEZ.js";
3
+ } from "./chunk-4HWN7734.js";
4
4
  import {
5
5
  extractRagText
6
- } from "./chunk-3IYTCGHS.js";
6
+ } from "./chunk-VXONXP2G.js";
7
7
  import {
8
8
  createTool
9
- } from "./chunk-MELYDKWQ.js";
9
+ } from "./chunk-4BGN6PYF.js";
10
10
  import {
11
11
  CompletionRequestBuilder
12
- } from "./chunk-MTGNA4OS.js";
12
+ } from "./chunk-Q25IWLBT.js";
13
13
  import {
14
14
  CompletionCapabilityError,
15
15
  Message,
16
16
  Usage
17
- } from "./chunk-PJDL5UT2.js";
17
+ } from "./chunk-ADH7NNCS.js";
18
18
 
19
19
  // src/extractor/extractor.ts
20
20
  var SUBMIT_TOOL_NAME = "submit";
@@ -138,4 +138,4 @@ export {
138
138
  Extractor,
139
139
  ExtractorBuilder
140
140
  };
141
- //# sourceMappingURL=chunk-ZSTUMG7G.js.map
141
+ //# sourceMappingURL=chunk-KYEBWN3E.js.map
@@ -3,7 +3,7 @@ import {
3
3
  assertCompletionRequestSupported,
4
4
  isProviderTool,
5
5
  textFromAssistantContent
6
- } from "./chunk-PJDL5UT2.js";
6
+ } from "./chunk-ADH7NNCS.js";
7
7
  import {
8
8
  toProviderJsonSchema
9
9
  } from "./chunk-WQKHFADH.js";
@@ -218,4 +218,4 @@ export {
218
218
  createParsedCompletion,
219
219
  isStreamingCompletionModel
220
220
  };
221
- //# sourceMappingURL=chunk-F56AMXMQ.js.map
221
+ //# sourceMappingURL=chunk-MC3CCKEB.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  createCompletion
3
- } from "./chunk-F56AMXMQ.js";
3
+ } from "./chunk-MC3CCKEB.js";
4
4
  import {
5
5
  Message
6
- } from "./chunk-PJDL5UT2.js";
6
+ } from "./chunk-ADH7NNCS.js";
7
7
 
8
8
  // src/memory/errors.ts
9
9
  var MemoryCompactionError = class extends Error {
@@ -217,4 +217,4 @@ export {
217
217
  createMemoryCompactionSummary,
218
218
  cumulativeCompactedMessageCount
219
219
  };
220
- //# sourceMappingURL=chunk-TGLNXVII.js.map
220
+ //# sourceMappingURL=chunk-MRQLEK2B.js.map
@@ -2,7 +2,7 @@ import {
2
2
  Message,
3
3
  assertCompletionRequestSupported,
4
4
  isProviderTool
5
- } from "./chunk-PJDL5UT2.js";
5
+ } from "./chunk-ADH7NNCS.js";
6
6
 
7
7
  // src/completion/documents.ts
8
8
  function normalizeDocuments(documents) {
@@ -135,4 +135,4 @@ export {
135
135
  formatDocument,
136
136
  CompletionRequestBuilder
137
137
  };
138
- //# sourceMappingURL=chunk-MTGNA4OS.js.map
138
+ //# sourceMappingURL=chunk-Q25IWLBT.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  assertNonnegativeInteger,
3
3
  assertPositiveInteger
4
- } from "./chunk-TGLNXVII.js";
4
+ } from "./chunk-MRQLEK2B.js";
5
5
 
6
6
  // src/memory/options.ts
7
7
  function resolveMemoryOptions(options = {}) {
@@ -30,4 +30,4 @@ function resolveMemoryOptions(options = {}) {
30
30
  export {
31
31
  resolveMemoryOptions
32
32
  };
33
- //# sourceMappingURL=chunk-ZNTIUOKL.js.map
33
+ //# sourceMappingURL=chunk-UQX6EXWG.js.map
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  parseToolArgs,
6
6
  toolResultContentToText
7
- } from "./chunk-6X2UTX3L.js";
7
+ } from "./chunk-2NDQHV7V.js";
8
8
  import {
9
9
  runControl,
10
10
  toolCallControl
@@ -14,16 +14,13 @@ import {
14
14
  MemoryCompactionError,
15
15
  createMemoryCompactionSummary,
16
16
  cumulativeCompactedMessageCount
17
- } from "./chunk-TGLNXVII.js";
18
- import {
19
- mapWithConcurrency
20
- } from "./chunk-OIMLU4SF.js";
17
+ } from "./chunk-MRQLEK2B.js";
21
18
  import {
22
19
  CompletionRequestBuilder
23
- } from "./chunk-MTGNA4OS.js";
20
+ } from "./chunk-Q25IWLBT.js";
24
21
  import {
25
22
  isStreamingCompletionModel
26
- } from "./chunk-F56AMXMQ.js";
23
+ } from "./chunk-MC3CCKEB.js";
27
24
  import {
28
25
  AssistantContent,
29
26
  Message,
@@ -32,7 +29,10 @@ import {
32
29
  assertCompletionRequestSupported,
33
30
  getAssistantGenerationMetadata,
34
31
  textFromAssistantContent
35
- } from "./chunk-PJDL5UT2.js";
32
+ } from "./chunk-ADH7NNCS.js";
33
+ import {
34
+ mapWithConcurrency
35
+ } from "./chunk-OIMLU4SF.js";
36
36
  import {
37
37
  appendGuardrailPolicies,
38
38
  hasEnforcedOutputGuardrails,
@@ -2111,6 +2111,7 @@ var PromptRequest = class _PromptRequest {
2111
2111
  runId,
2112
2112
  output: result.output,
2113
2113
  usage: result.usage,
2114
+ contextUsage: result.contextUsage,
2114
2115
  messages: result.messages,
2115
2116
  trace: result.trace,
2116
2117
  guardrails: result.guardrails,
@@ -2241,6 +2242,7 @@ var PromptRequest = class _PromptRequest {
2241
2242
  provider: this.agent.model.provider,
2242
2243
  model: request.model ?? this.agent.model.defaultModel,
2243
2244
  usage: { ...response.usage },
2245
+ ...response.contextUsage === void 0 ? {} : { contextUsage: response.contextUsage },
2244
2246
  ...response.sources === void 0 ? {} : { sources: response.sources },
2245
2247
  ...response.providerToolCalls === void 0 ? {} : { providerToolCalls: response.providerToolCalls }
2246
2248
  }
@@ -2650,8 +2652,12 @@ function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
2650
2652
  function generationArtifacts(messages) {
2651
2653
  const sources = /* @__PURE__ */ new Map();
2652
2654
  const providerToolCalls = /* @__PURE__ */ new Map();
2655
+ let contextUsage;
2653
2656
  for (const message of messages) {
2654
2657
  const metadata = getAssistantGenerationMetadata(message);
2658
+ if (metadata !== void 0) {
2659
+ contextUsage = metadata.contextUsage;
2660
+ }
2655
2661
  for (const source of metadata?.sources ?? []) {
2656
2662
  const key = `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
2657
2663
  sources.set(key, source);
@@ -2662,7 +2668,8 @@ function generationArtifacts(messages) {
2662
2668
  }
2663
2669
  return {
2664
2670
  ...sources.size === 0 ? {} : { sources: [...sources.values()] },
2665
- ...providerToolCalls.size === 0 ? {} : { providerToolCalls: [...providerToolCalls.values()] }
2671
+ ...providerToolCalls.size === 0 ? {} : { providerToolCalls: [...providerToolCalls.values()] },
2672
+ ...contextUsage === void 0 ? {} : { contextUsage }
2666
2673
  };
2667
2674
  }
2668
2675
  function reasoningDeltaEvent2(turn, delta, details = {}) {
@@ -2722,4 +2729,4 @@ export {
2722
2729
  extractRagText,
2723
2730
  PromptRequest
2724
2731
  };
2725
- //# sourceMappingURL=chunk-3IYTCGHS.js.map
2732
+ //# sourceMappingURL=chunk-VXONXP2G.js.map