@anvia/core 1.0.0-rc.5 → 1.0.0-rc.6

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 (58) hide show
  1. package/README.md +22 -6
  2. package/dist/agent/index.d.ts +20 -14
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/interactions/index.d.ts +1 -1
  5. package/dist/{agent-LlCD_2UQ.d.ts → agent-BK3jud9q.d.ts} +10 -10
  6. package/dist/{chunk-E5J4OY4K.js → chunk-7O45T5F2.js} +2 -2
  7. package/dist/{chunk-YDJA4R37.js → chunk-BOCJCECN.js} +2 -2
  8. package/dist/{chunk-HSA6NL2E.js → chunk-HT4P3SSG.js} +61 -5
  9. package/dist/chunk-HT4P3SSG.js.map +1 -0
  10. package/dist/{chunk-DNQNOHD5.js → chunk-QXQQ2DBM.js} +2 -2
  11. package/dist/{chunk-FCANRQ5Q.js → chunk-QXSVVYQK.js} +151 -28
  12. package/dist/chunk-QXSVVYQK.js.map +1 -0
  13. package/dist/{chunk-TEV3OB7N.js → chunk-VGJRXUPT.js} +10 -3
  14. package/dist/chunk-VGJRXUPT.js.map +1 -0
  15. package/dist/{client-DvUatElp.d.ts → client-BdQ_QZsY.d.ts} +2 -2
  16. package/dist/completion/index.d.ts +3 -3
  17. package/dist/completion/index.js +3 -1
  18. package/dist/{dynamic-tools-AEBOTgu1.d.ts → dynamic-tools--Aw37H9d.d.ts} +3 -3
  19. package/dist/evals/index.d.ts +6 -6
  20. package/dist/evals/index.js +3 -3
  21. package/dist/extractor/index.d.ts +1 -1
  22. package/dist/extractor/index.js +2 -2
  23. package/dist/guardrails/index.d.ts +4 -4
  24. package/dist/image-generation/index.d.ts +1 -1
  25. package/dist/index.d.ts +14 -14
  26. package/dist/index.js +7 -5
  27. package/dist/internal/agent.d.ts +11 -11
  28. package/dist/internal/agent.js +5 -5
  29. package/dist/mcp/index.d.ts +4 -4
  30. package/dist/memory/index.d.ts +3 -3
  31. package/dist/memory/index.js +2 -2
  32. package/dist/{message-schema-B2M7AYzR.d.ts → message-schema-_sP_RKhh.d.ts} +18 -2
  33. package/dist/{middleware-BqtLB_Xt.d.ts → middleware-QZsbz7Hf.d.ts} +1 -1
  34. package/dist/observability/index.d.ts +6 -6
  35. package/dist/observability/index.js +2 -2
  36. package/dist/pipeline/index.d.ts +11 -11
  37. package/dist/pipeline/index.js +3 -3
  38. package/dist/skills/index.d.ts +4 -4
  39. package/dist/speech-generation/index.d.ts +1 -1
  40. package/dist/{text-C_6eKrbC.d.ts → text-DTg1a8Mg.d.ts} +1 -1
  41. package/dist/{think-tool-Cz3QYNPX.d.ts → think-tool-C0n_dF2K.d.ts} +1 -1
  42. package/dist/tool/index.d.ts +6 -6
  43. package/dist/{tool-r62gf3QY.d.ts → tool-xHM_GmzT.d.ts} +1 -1
  44. package/dist/transcription/index.d.ts +1 -1
  45. package/dist/{types-1KpjDfoN.d.ts → types-2DBdXArn.d.ts} +7 -5
  46. package/dist/{types-DbolvLtZ.d.ts → types-B1KL4w14.d.ts} +1 -1
  47. package/dist/{types-C3gv9EX6.d.ts → types-D0Y2ZWS3.d.ts} +1 -1
  48. package/dist/{types-CIPaIbZo.d.ts → types-D7A6CIGt.d.ts} +1 -1
  49. package/dist/{types-D9rKQ_as.d.ts → types-DboZvHR_.d.ts} +8 -1
  50. package/dist/{types-RT3cuyRk.d.ts → types-Dyp7arZQ.d.ts} +1 -1
  51. package/dist/vector-store/index.d.ts +4 -4
  52. package/package.json +1 -1
  53. package/dist/chunk-FCANRQ5Q.js.map +0 -1
  54. package/dist/chunk-HSA6NL2E.js.map +0 -1
  55. package/dist/chunk-TEV3OB7N.js.map +0 -1
  56. /package/dist/{chunk-E5J4OY4K.js.map → chunk-7O45T5F2.js.map} +0 -0
  57. /package/dist/{chunk-YDJA4R37.js.map → chunk-BOCJCECN.js.map} +0 -0
  58. /package/dist/{chunk-DNQNOHD5.js.map → chunk-QXQQ2DBM.js.map} +0 -0
package/README.md CHANGED
@@ -126,7 +126,17 @@ console.log(result.output.priority); // fully typed
126
126
  ```
127
127
 
128
128
  `CompletionResult` consistently contains `output`, the original `text`, normalized `content`,
129
- `usage`, and `rawResponse`, plus optional message, context, source, and provider-tool metadata.
129
+ `usage`, and `rawResponse`, plus optional message, context, source, provider-tool, and finish-reason
130
+ metadata. First-party adapters normalize provider termination into `finishReason` (`stop`, `length`,
131
+ `content-filter`, `tool-calls`, or `other`) while preserving the provider value separately as
132
+ `providerFinishReason`.
133
+
134
+ Schema-backed completion detects `finishReason: "length"` before JSON parsing and throws
135
+ `CompletionStructuredOutputError` with `phase: "truncated"`. Ordinary text completion remains
136
+ intentional: partial text is returned unchanged with its finish reason so the application decides
137
+ whether to display, continue, or discard it. A direct structured stream can similarly end with one
138
+ typed error event after any already-emitted deltas; it does not silently retract public stream
139
+ progress.
130
140
 
131
141
  Use `streamCompletion` for the streaming form:
132
142
 
@@ -210,18 +220,24 @@ await agent.generate({
210
220
  });
211
221
  ```
212
222
 
213
- When an Agent has `outputSchema`, JSON parsing and schema-validation failures use the same retry
214
- budget when retries are explicitly enabled. A correction request includes the rejected response in
215
- the provider transcript and asks for raw JSON matching the schema, without Markdown or commentary.
223
+ When an Agent has `outputSchema`, truncation, JSON parsing, and schema-validation failures use the
224
+ same retry budget when retries are explicitly enabled. Each retry starts from the original request
225
+ rather than recursively accumulating failed attempts. Truncated output and reasoning are omitted;
226
+ parse and schema repairs include only a bounded, text-only preview of the latest failed response.
227
+ The correction asks for shorter raw JSON matching the schema, without Markdown or commentary.
216
228
  Transport failures and structured-output failures therefore cannot exceed `maxAttempts` in total.
229
+ Completed Agent results expose the last generation's `finishReason` and `providerFinishReason`, and
230
+ the same fields remain attached to each assistant message's Anvia generation metadata.
217
231
 
218
232
  Structured output remains strict: Core trims surrounding whitespace, parses JSON, and validates the
219
233
  result with the configured Zod schema. As a compatibility fallback for OpenAI-compatible providers
220
234
  that violate strict JSON mode, Core also accepts a response consisting entirely of one lowercase
221
235
  `json` Markdown fence or one unlabeled Markdown fence. It does not search prose for JSON, accept
222
236
  content before or after a fence, or bypass schema validation. `AgentStructuredOutputError` reports
223
- the `parse` or `schema` phase, attempt counts, output length/format metadata, cumulative attempt
224
- usage, and the original `cause`; its message never contains the rejected model response.
237
+ the `truncated`, `parse`, or `schema` phase, attempt counts, output length/format metadata, per-attempt
238
+ and cumulative usage, finish reasons, and the original `cause` when one exists; its message never
239
+ contains the rejected model response. The `completion.retry` observer event records the same safe
240
+ diagnostics and whether failed output was omitted or previewed, never the model output itself.
225
241
 
226
242
  Agent results are discriminated by `status`. Completed results include typed `output` and `text`;
227
243
  guardrail blocks return `status: "blocked"`, `stage`, and `text`; tool approvals and first-class
@@ -1,29 +1,29 @@
1
1
  export { M as ModelCallOptions } from '../model-call-options-CZkSw_xN.js';
2
2
  export { R as RetryContext, a as RetryOptions, b as RetrySetting } from '../retry-CjvSlKGW.js';
3
- export { A as Agent, a as AgentContextInput, b as AgentMemory, c as AgentMemoryOptions, d as AgentOptions, e as AgentToolInput, f as AgentToolOptions, C as CreateHybridVectorContextOptions, g as CreateVectorContextOptions, V as VectorContext, h as VectorContextBaseOptions, i as createVectorContext, j as isVectorContext } from '../agent-LlCD_2UQ.js';
4
- import { M as Message, U as Usage } from '../types-D9rKQ_as.js';
5
- import { A as AgentBlockedResult, t as AgentSuspendedResult } from '../types-1KpjDfoN.js';
6
- export { a as AgentChildStreamEvent, b as AgentDeltaEvent, c as AgentErrorEvent, d as AgentErrorStreamEvent, e as AgentFinishEvent, f as AgentInput, g as AgentLifecycle, h as AgentMemoryCompactionEvent, i as AgentPrompt, j as AgentResponse, k as AgentResult, l as AgentRunOptions, m as AgentRunSettings, n as AgentStartEvent, o as AgentSteerInput, p as AgentSteerReceipt, q as AgentStepFinishEvent, r as AgentStream, s as AgentStreamEvent, u as AgentToolCallDeltaEvent, v as AgentToolFinishEvent, w as AgentToolStartEvent } from '../types-1KpjDfoN.js';
3
+ export { A as Agent, a as AgentContextInput, b as AgentMemory, c as AgentMemoryOptions, d as AgentOptions, e as AgentToolInput, f as AgentToolOptions, C as CreateHybridVectorContextOptions, g as CreateVectorContextOptions, V as VectorContext, h as VectorContextBaseOptions, i as createVectorContext, j as isVectorContext } from '../agent-BK3jud9q.js';
4
+ import { M as Message, U as Usage, C as CompletionFinishReason } from '../types-DboZvHR_.js';
5
+ import { A as AgentBlockedResult, t as AgentSuspendedResult } from '../types-2DBdXArn.js';
6
+ export { a as AgentChildStreamEvent, b as AgentDeltaEvent, c as AgentErrorEvent, d as AgentErrorStreamEvent, e as AgentFinishEvent, f as AgentInput, g as AgentLifecycle, h as AgentMemoryCompactionEvent, i as AgentPrompt, j as AgentResponse, k as AgentResult, l as AgentRunOptions, m as AgentRunSettings, n as AgentStartEvent, o as AgentSteerInput, p as AgentSteerReceipt, q as AgentStepFinishEvent, r as AgentStream, s as AgentStreamEvent, u as AgentToolCallDeltaEvent, v as AgentToolFinishEvent, w as AgentToolStartEvent } from '../types-2DBdXArn.js';
7
7
  import '../zod-schema-C7F4clpm.js';
8
8
  import 'zod';
9
- import '../types-CIPaIbZo.js';
9
+ import '../types-D7A6CIGt.js';
10
10
  import '../type-utils-CtHVDRn_.js';
11
- import '../client-DvUatElp.js';
11
+ import '../client-BdQ_QZsY.js';
12
12
  import 'node:child_process';
13
13
  import 'node:stream';
14
14
  import '@modelcontextprotocol/sdk/client/auth.js';
15
15
  import '@modelcontextprotocol/sdk/client/streamableHttp.js';
16
16
  import '@modelcontextprotocol/sdk/shared/transport.js';
17
- import '../tool-r62gf3QY.js';
18
- import '../middleware-BqtLB_Xt.js';
19
- import '../types-DbolvLtZ.js';
20
- import '../types-RT3cuyRk.js';
21
- import '../dynamic-tools-AEBOTgu1.js';
17
+ import '../tool-xHM_GmzT.js';
18
+ import '../middleware-QZsbz7Hf.js';
19
+ import '../types-B1KL4w14.js';
20
+ import '../types-Dyp7arZQ.js';
21
+ import '../dynamic-tools--Aw37H9d.js';
22
22
  import '../types-Cr4uiYo5.js';
23
- import '../types-C3gv9EX6.js';
23
+ import '../types-D0Y2ZWS3.js';
24
24
  import './interactions/index.js';
25
25
 
26
- type AgentStructuredOutputPhase = "parse" | "schema";
26
+ type AgentStructuredOutputPhase = "truncated" | "parse" | "schema";
27
27
  type AgentStructuredOutputFormat = "raw" | "json-fence" | "unlabeled-fence";
28
28
  declare class AgentStructuredOutputError extends Error {
29
29
  readonly phase: AgentStructuredOutputPhase;
@@ -32,7 +32,10 @@ declare class AgentStructuredOutputError extends Error {
32
32
  readonly outputLength: number;
33
33
  readonly normalizedLength: number;
34
34
  readonly outputFormat: AgentStructuredOutputFormat;
35
+ readonly attemptUsage: Usage;
35
36
  readonly usage: Usage;
37
+ readonly finishReason: CompletionFinishReason | undefined;
38
+ readonly providerFinishReason: string | undefined;
36
39
  constructor(options: {
37
40
  phase: AgentStructuredOutputPhase;
38
41
  attempt: number;
@@ -40,8 +43,11 @@ declare class AgentStructuredOutputError extends Error {
40
43
  outputLength: number;
41
44
  normalizedLength: number;
42
45
  outputFormat: AgentStructuredOutputFormat;
46
+ attemptUsage: Usage;
43
47
  usage: Usage;
44
- cause: unknown;
48
+ finishReason?: CompletionFinishReason | undefined;
49
+ providerFinishReason?: string | undefined;
50
+ cause?: unknown;
45
51
  });
46
52
  }
47
53
  declare class MaxTurnsError extends Error {
@@ -2,11 +2,11 @@ import {
2
2
  Agent,
3
3
  createVectorContext,
4
4
  isVectorContext
5
- } from "../chunk-FCANRQ5Q.js";
5
+ } from "../chunk-QXSVVYQK.js";
6
6
  import "../chunk-BEU6FCTN.js";
7
7
  import "../chunk-7YAH2F3J.js";
8
- import "../chunk-DNQNOHD5.js";
9
- import "../chunk-E5J4OY4K.js";
8
+ import "../chunk-QXQQ2DBM.js";
9
+ import "../chunk-7O45T5F2.js";
10
10
  import "../chunk-YK4WAAS4.js";
11
11
  import "../chunk-CQNNSZPG.js";
12
12
  import "../chunk-JXZTTNCR.js";
@@ -18,11 +18,11 @@ import {
18
18
  AgentStructuredOutputError,
19
19
  AgentToolSuspensionError,
20
20
  MaxTurnsError
21
- } from "../chunk-TEV3OB7N.js";
21
+ } from "../chunk-VGJRXUPT.js";
22
22
  import "../chunk-H7BI3BSP.js";
23
23
  import "../chunk-3RM57ZT2.js";
24
24
  import "../chunk-MGNTXGTX.js";
25
- import "../chunk-HSA6NL2E.js";
25
+ import "../chunk-HT4P3SSG.js";
26
26
  import "../chunk-G5OACQEI.js";
27
27
  import "../chunk-SROQA7I7.js";
28
28
  import "../chunk-UBE4WH6G.js";
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { o as JsonValue, J as JsonObject, _ as ToolQuestionAnswer } from '../../types-D9rKQ_as.js';
2
+ import { p as JsonValue, J as JsonObject, $ as ToolQuestionAnswer } from '../../types-DboZvHR_.js';
3
3
  import '../../model-call-options-CZkSw_xN.js';
4
4
 
5
5
  type AgentQuestionChoice = Readonly<{
@@ -1,16 +1,16 @@
1
1
  import { b as RetrySetting } from './retry-CjvSlKGW.js';
2
- import { D as Document, C as CompletionModel, P as ProviderTool, J as JsonObject, u as ToolChoice } from './types-D9rKQ_as.js';
2
+ import { D as Document, c as CompletionModel, P as ProviderTool, J as JsonObject, v as ToolChoice } from './types-DboZvHR_.js';
3
3
  import { Z as ZodSchema } from './zod-schema-C7F4clpm.js';
4
- import { d as GuardrailPolicyInput, c as GuardrailPolicy } from './types-CIPaIbZo.js';
5
- import { a as McpServer } from './client-DvUatElp.js';
6
- import { g as AgentLifecycle, E as AgentObservabilityOptions, l as AgentRunOptions, k as AgentResult, r as AgentStream, s as AgentStreamEvent } from './types-1KpjDfoN.js';
7
- import { A as AgentMiddleware } from './middleware-BqtLB_Xt.js';
8
- import { A as AnyTool, T as Tool, c as ToolCallContext, N as NormalizedToolOutput } from './tool-r62gf3QY.js';
9
- import { D as MemoryStore, y as MemorySavePolicy, m as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, x as MemoryOptions } from './types-DbolvLtZ.js';
10
- import { a as SkillSet } from './types-RT3cuyRk.js';
11
- import { T as ToolIndex } from './dynamic-tools-AEBOTgu1.js';
4
+ import { d as GuardrailPolicyInput, c as GuardrailPolicy } from './types-D7A6CIGt.js';
5
+ import { a as McpServer } from './client-BdQ_QZsY.js';
6
+ import { g as AgentLifecycle, E as AgentObservabilityOptions, l as AgentRunOptions, k as AgentResult, r as AgentStream, s as AgentStreamEvent } from './types-2DBdXArn.js';
7
+ import { A as AgentMiddleware } from './middleware-QZsbz7Hf.js';
8
+ import { A as AnyTool, T as Tool, c as ToolCallContext, N as NormalizedToolOutput } from './tool-xHM_GmzT.js';
9
+ import { D as MemoryStore, y as MemorySavePolicy, m as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, x as MemoryOptions } from './types-B1KL4w14.js';
10
+ import { a as SkillSet } from './types-Dyp7arZQ.js';
11
+ import { T as ToolIndex } from './dynamic-tools--Aw37H9d.js';
12
12
  import { E as EmbeddingModel, c as SparseEmbeddingModel } from './types-Cr4uiYo5.js';
13
- import { V as VectorFilter, a as VectorSearchResult, d as VectorStore, H as HybridVectorStore, e as VectorFusion } from './types-C3gv9EX6.js';
13
+ import { V as VectorFilter, a as VectorSearchResult, d as VectorStore, H as HybridVectorStore, e as VectorFusion } from './types-D0Y2ZWS3.js';
14
14
 
15
15
  type VectorContextBaseOptions<T = unknown> = {
16
16
  topK: number;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Usage
3
- } from "./chunk-HSA6NL2E.js";
3
+ } from "./chunk-HT4P3SSG.js";
4
4
 
5
5
  // src/observability/snapshot.ts
6
6
  function observerSnapshot(value) {
@@ -320,4 +320,4 @@ export {
320
320
  AgentObserverDispatchError,
321
321
  startAgentRunObservers
322
322
  };
323
- //# sourceMappingURL=chunk-E5J4OY4K.js.map
323
+ //# sourceMappingURL=chunk-7O45T5F2.js.map
@@ -2,7 +2,7 @@ import {
2
2
  CompletionCapabilityError,
3
3
  Usage,
4
4
  generateCompletion
5
- } from "./chunk-HSA6NL2E.js";
5
+ } from "./chunk-HT4P3SSG.js";
6
6
  import {
7
7
  toProviderJsonSchema
8
8
  } from "./chunk-G5OACQEI.js";
@@ -124,4 +124,4 @@ export {
124
124
  ExtractionError,
125
125
  extract
126
126
  };
127
- //# sourceMappingURL=chunk-YDJA4R37.js.map
127
+ //# sourceMappingURL=chunk-BOCJCECN.js.map
@@ -123,6 +123,12 @@ function getAssistantGenerationMetadata(message) {
123
123
  modelId: generation.modelId,
124
124
  usage
125
125
  };
126
+ if (isCompletionFinishReason(generation.finishReason)) {
127
+ metadata.finishReason = generation.finishReason;
128
+ }
129
+ if (typeof generation.providerFinishReason === "string") {
130
+ metadata.providerFinishReason = generation.providerFinishReason;
131
+ }
126
132
  if (isContextUsageValue(generation.contextUsage)) {
127
133
  metadata.contextUsage = {
128
134
  ...generation.contextUsage,
@@ -216,6 +222,9 @@ function isProviderToolCallArray(value) {
216
222
  (toolCall) => isJsonObjectValue(toolCall) && typeof toolCall.id === "string" && typeof toolCall.name === "string" && (toolCall.status === void 0 || typeof toolCall.status === "string") && (toolCall.details === void 0 || isJsonObjectValue(toolCall.details))
217
223
  );
218
224
  }
225
+ function isCompletionFinishReason(value) {
226
+ return value === "stop" || value === "length" || value === "content-filter" || value === "tool-calls" || value === "other";
227
+ }
219
228
  var CompletionCapabilityError = class extends Error {
220
229
  constructor(message) {
221
230
  super(message);
@@ -306,6 +315,23 @@ function messagesFromInput(input) {
306
315
  }
307
316
 
308
317
  // src/completion/generate-completion.ts
318
+ var CompletionStructuredOutputError = class extends Error {
319
+ phase;
320
+ outputLength;
321
+ usage;
322
+ finishReason;
323
+ providerFinishReason;
324
+ constructor(options) {
325
+ const failure = options.phase === "truncated" ? "because the provider reached its output limit" : options.phase === "parse" ? "during JSON parsing" : "during schema validation";
326
+ super(`Structured completion output failed ${failure}.`, { cause: options.cause });
327
+ this.name = "CompletionStructuredOutputError";
328
+ this.phase = options.phase;
329
+ this.outputLength = options.outputLength;
330
+ this.usage = options.usage;
331
+ this.finishReason = options.finishReason;
332
+ this.providerFinishReason = options.providerFinishReason;
333
+ }
334
+ };
309
335
  async function generateCompletion(options) {
310
336
  throwIfAborted(options.abortSignal);
311
337
  const request = requestFromOptions(options);
@@ -466,12 +492,16 @@ function structuredOutputSchema(options) {
466
492
  function resultFromResponse(response, outputSchema) {
467
493
  const text = textFromAssistantContent(response.choice);
468
494
  const result = {
469
- output: outputSchema === void 0 ? text : parseCompletionOutput(text, outputSchema),
495
+ output: outputSchema === void 0 ? text : parseCompletionOutput(text, outputSchema, response),
470
496
  text,
471
497
  content: [...response.choice],
472
498
  usage: response.usage,
473
499
  rawResponse: response.rawResponse
474
500
  };
501
+ if (response.finishReason !== void 0) result.finishReason = response.finishReason;
502
+ if (response.providerFinishReason !== void 0) {
503
+ result.providerFinishReason = response.providerFinishReason;
504
+ }
475
505
  if (response.contextUsage !== void 0) result.contextUsage = response.contextUsage;
476
506
  if (response.messageId !== void 0) result.messageId = response.messageId;
477
507
  if (response.sources !== void 0) result.sources = [...response.sources];
@@ -480,16 +510,41 @@ function resultFromResponse(response, outputSchema) {
480
510
  }
481
511
  return result;
482
512
  }
483
- function parseCompletionOutput(text, schema) {
513
+ function parseCompletionOutput(text, schema, response) {
514
+ if (response.finishReason === "length") {
515
+ throw new CompletionStructuredOutputError({
516
+ phase: "truncated",
517
+ outputLength: text.length,
518
+ usage: response.usage,
519
+ finishReason: response.finishReason,
520
+ providerFinishReason: response.providerFinishReason
521
+ });
522
+ }
484
523
  let json;
485
524
  try {
486
525
  json = JSON.parse(text);
487
526
  } catch (error) {
488
- throw new Error("generateCompletion expected the model response to be valid JSON.", {
527
+ throw new CompletionStructuredOutputError({
528
+ phase: "parse",
529
+ outputLength: text.length,
530
+ usage: response.usage,
531
+ finishReason: response.finishReason,
532
+ providerFinishReason: response.providerFinishReason,
533
+ cause: error
534
+ });
535
+ }
536
+ try {
537
+ return schema.parse(json);
538
+ } catch (error) {
539
+ throw new CompletionStructuredOutputError({
540
+ phase: "schema",
541
+ outputLength: text.length,
542
+ usage: response.usage,
543
+ finishReason: response.finishReason,
544
+ providerFinishReason: response.providerFinishReason,
489
545
  cause: error
490
546
  });
491
547
  }
492
- return schema.parse(json);
493
548
  }
494
549
  function modelCallOptions(abortSignal) {
495
550
  return abortSignal === void 0 ? void 0 : { abortSignal };
@@ -510,8 +565,9 @@ export {
510
565
  assertCompletionRequestSupported,
511
566
  textFromAssistantContent,
512
567
  createCompletionRequest,
568
+ CompletionStructuredOutputError,
513
569
  generateCompletion,
514
570
  streamCompletion,
515
571
  isStreamingCompletionModel
516
572
  };
517
- //# sourceMappingURL=chunk-HSA6NL2E.js.map
573
+ //# sourceMappingURL=chunk-HT4P3SSG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/completion/types.ts","../src/internal/completion-request.ts","../src/completion/generate-completion.ts"],"sourcesContent":["import type { ModelCallOptions } from \"../model-call-options\";\nimport { 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 TextPart = Readonly<{\n type: \"text\";\n text: string;\n signature?: string;\n}>;\n\nexport type ImageDetail = \"auto\" | \"low\" | \"high\";\n\nexport type FileData =\n | Readonly<{ type: \"url\"; url: string }>\n | Readonly<{ type: \"data\"; data: string }>\n | Readonly<{ type: \"text\"; text: string }>;\n\nexport type ImagePart = Readonly<{\n type: \"image\";\n image: Exclude<FileData, Readonly<{ type: \"text\"; text: string }>>;\n mediaType?: string;\n detail?: ImageDetail;\n}>;\n\nexport type FilePart = Readonly<{\n type: \"file\";\n data: FileData;\n mediaType: string;\n filename?: string;\n}>;\n\nexport type ReasoningPart = Readonly<{\n type: \"reasoning\";\n text: string;\n id?: string;\n details?: readonly ReasoningDetail[];\n}>;\n\nexport type ReasoningDetail =\n | Readonly<{\n type: \"text\";\n text: string;\n signature?: string;\n }>\n | Readonly<{\n type: \"summary\";\n text: string;\n }>\n | Readonly<{\n type: \"encrypted\";\n data: string;\n }>\n | Readonly<{\n type: \"redacted\";\n data: string;\n }>;\n\nexport type ReasoningContentType = ReasoningDetail[\"type\"];\n\nexport type ToolCallPart = Readonly<{\n type: \"tool-call\";\n toolCallId: string;\n callId?: string;\n toolName: string;\n input: JsonValue;\n signature?: string;\n}>;\n\nexport type ToolResultContentPart = TextPart | FilePart;\n\nexport type ToolResultOutput =\n | Readonly<{ type: \"text\"; value: string }>\n | Readonly<{ type: \"json\"; value: JsonValue }>\n | Readonly<{ type: \"content\"; value: readonly ToolResultContentPart[] }>\n | Readonly<{ type: \"execution-denied\"; reason?: string }>\n | Readonly<{ type: \"error-text\"; value: string }>\n | Readonly<{ type: \"error-json\"; value: JsonValue }>;\n\nexport type ToolResultPart = Readonly<{\n type: \"tool-result\";\n toolCallId: string;\n callId?: string;\n toolName: string;\n output: ToolResultOutput;\n}>;\n\nexport type ToolApprovalResponsePart = Readonly<{\n type: \"tool-approval-response\";\n interactionId: string;\n toolCallId: string;\n callId?: string;\n toolName: string;\n approved: boolean;\n reason?: string;\n}>;\n\nexport type ToolQuestionAnswer = Readonly<{\n questionId: string;\n value: string;\n}>;\n\nexport type ToolQuestionResponsePart = Readonly<{\n type: \"tool-question-response\";\n interactionId: string;\n toolCallId: string;\n callId?: string;\n toolName: string;\n answers: readonly ToolQuestionAnswer[];\n}>;\n\nexport type ToolInteractionResponsePart = ToolApprovalResponsePart | ToolQuestionResponsePart;\n\nexport type UserContentPart = TextPart | ImagePart | FilePart;\nexport type AssistantContentPart = TextPart | ImagePart | FilePart | ReasoningPart | ToolCallPart;\n\nexport type SystemMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"system\";\n content: string;\n metadata?: Metadata;\n}>;\n\nexport type UserMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"user\";\n content: string | readonly UserContentPart[];\n metadata?: Metadata;\n}>;\n\nexport type AssistantMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"assistant\";\n id?: string;\n content: string | readonly AssistantContentPart[];\n metadata?: Metadata;\n}>;\n\nexport type ToolMessage<Metadata extends JsonObject = JsonObject> = Readonly<{\n role: \"tool\";\n content: readonly (ToolResultPart | ToolInteractionResponsePart)[];\n metadata?: Metadata;\n}>;\n\nexport type Message<Metadata extends JsonObject = JsonObject> =\n | SystemMessage<Metadata>\n | UserMessage<Metadata>\n | AssistantMessage<Metadata>\n | ToolMessage<Metadata>;\n\nexport function reasoningDisplayText(\n reasoning: ReasoningPart | readonly ReasoningDetail[],\n): string {\n const details = \"type\" in reasoning ? reasoning.details : reasoning;\n if (details === undefined) {\n return \"type\" in reasoning ? reasoning.text : \"\";\n }\n return details\n .flatMap((item) => {\n if (item.type === \"text\" || item.type === \"summary\") {\n return [item.text];\n }\n return [];\n })\n .join(\"\");\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 = {\n modelId: string;\n context: ModelContextLimits;\n};\n\nexport type ContextUsage = {\n model: CompletionModelInfo;\n usedTokens: number;\n remainingTokens: number;\n usedPercent: number;\n remainingPercent: number;\n};\n\nexport function calculateContextUsage(\n usage: Usage,\n model: CompletionModelInfo | undefined,\n): ContextUsage | 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>(\n response: CompletionResponse<RawResponse>,\n model: CompletionModelInfo | undefined,\n): CompletionResponse<RawResponse> {\n const contextUsage = calculateContextUsage(response.usage, model);\n return contextUsage === undefined ? response : { ...response, contextUsage };\n}\n\nexport function resolveModelContextLimits(\n modelId: string,\n catalog: Readonly<Record<string, ModelContextLimits>>,\n override?: ModelContextLimits,\n): ModelContextLimits | undefined {\n return override ?? catalog[modelId];\n}\n\nexport type AssistantGenerationMetadata = {\n provider: string;\n modelId: string;\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\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.modelId !== \"string\" ||\n !isUsageValue(generation.usage)\n ) {\n return undefined;\n }\n let usage: Usage = { ...generation.usage };\n if (generation.usage.details !== undefined) {\n usage = { ...usage, details: { ...generation.usage.details } };\n }\n const metadata: AssistantGenerationMetadata = {\n provider: generation.provider,\n modelId: generation.modelId,\n usage,\n };\n if (isCompletionFinishReason(generation.finishReason)) {\n metadata.finishReason = generation.finishReason;\n }\n if (typeof generation.providerFinishReason === \"string\") {\n metadata.providerFinishReason = generation.providerFinishReason;\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 let copy: ProviderToolCall = { ...toolCall };\n if (toolCall.details !== undefined) {\n copy = { ...copy, details: { ...toolCall.details } };\n }\n return copy;\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.modelId === \"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 = {\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 providerOptions?: JsonObject;\n outputSchema?: JsonObject;\n};\n\nexport type CompletionFinishReason = \"stop\" | \"length\" | \"content-filter\" | \"tool-calls\" | \"other\";\n\nexport type CompletionResponse<RawResponse = unknown> = {\n choice: AssistantContentPart[];\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n rawResponse: RawResponse;\n messageId?: string;\n sources?: CompletionSource[];\n providerToolCalls?: ProviderToolCall[];\n};\n\nexport type CompletionResult<Output = string, RawResponse = unknown> = {\n output: Output;\n text: string;\n content: readonly AssistantContentPart[];\n usage: Usage;\n finishReason?: CompletionFinishReason;\n providerFinishReason?: string;\n contextUsage?: ContextUsage;\n rawResponse: RawResponse;\n messageId?: string;\n sources?: readonly CompletionSource[];\n providerToolCalls?: readonly ProviderToolCall[];\n};\n\nfunction isCompletionFinishReason(value: JsonValue | undefined): value is CompletionFinishReason {\n return (\n value === \"stop\" ||\n value === \"length\" ||\n value === \"content-filter\" ||\n value === \"tool-calls\" ||\n value === \"other\"\n );\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> {\n readonly provider: string;\n readonly modelId: string;\n readonly contextLimits?: ModelContextLimits | undefined;\n readonly capabilities: CompletionModelCapabilities;\n traceRequest?(\n request: CompletionRequest,\n options?: { stream?: boolean | undefined },\n ): JsonObject | undefined;\n completion(\n request: CompletionRequest,\n options?: ModelCallOptions,\n ): Promise<CompletionResponse<RawResponse>>;\n}\n\nexport type ToolCallArgumentsMode = \"append\" | \"replace\";\n\nexport type CompletionStreamPart =\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: ToolCallPart;\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\nexport type CompletionModelStreamEvent<RawResponse = unknown> =\n | CompletionStreamPart\n | {\n type: \"final\";\n response: CompletionResponse<RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n usage?: Usage;\n };\n\nexport type CompletionStreamEvent<Output = string, RawResponse = unknown> =\n | CompletionStreamPart\n | {\n type: \"final\";\n result: CompletionResult<Output, RawResponse>;\n }\n | {\n type: \"error\";\n error: unknown;\n usage: Usage;\n };\n\nexport interface StreamingCompletionModel<RawResponse = unknown>\n extends CompletionModel<RawResponse> {\n streamCompletion(\n request: CompletionRequest,\n options?: ModelCallOptions,\n ): AsyncIterable<CompletionModelStreamEvent<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}:${model.modelId}`;\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: readonly AssistantContentPart[]): 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\" || typeof message.content === \"string\"\n ? false\n : 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\" && typeof message.content !== \"string\"\n ? message.content.some((content) => content.type === \"file\" && content.data.type !== \"text\")\n : false,\n );\n}\n","import { parseMessage, parseMessages } from \"../completion/message-schema\";\nimport type {\n CompletionRequest,\n CompletionTool,\n Document,\n JsonObject,\n Message as MessageType,\n ToolChoice,\n ToolDefinition,\n} from \"../completion/types\";\nimport { isProviderTool } from \"../completion/types\";\n\nexport type CompletionRequestOptions = {\n instructions?: string | undefined;\n documents?: readonly Document[] | undefined;\n tools?: readonly CompletionTool[] | undefined;\n temperature?: number | undefined;\n maxTokens?: number | undefined;\n toolChoice?: ToolChoice | undefined;\n outputSchema?: JsonObject | undefined;\n providerOptions?: JsonObject | undefined;\n};\n\nexport function createCompletionRequest(\n input: string | MessageType | readonly MessageType[],\n options: CompletionRequestOptions,\n): CompletionRequest {\n const configuredTools = options.tools ?? [];\n const chatHistory = messagesFromInput(input);\n assertNoAgentInteractionParts(chatHistory);\n const request: CompletionRequest = {\n chatHistory,\n documents: [...(options.documents ?? [])],\n tools: configuredTools.filter((tool): tool is ToolDefinition => !isProviderTool(tool)),\n };\n const providerTools = configuredTools.filter(isProviderTool);\n\n if (providerTools.length > 0) request.providerTools = providerTools;\n if (options.instructions !== undefined && options.instructions.length > 0) {\n request.instructions = options.instructions;\n }\n if (options.temperature !== undefined) request.temperature = options.temperature;\n if (options.maxTokens !== undefined) request.maxTokens = options.maxTokens;\n if (options.toolChoice !== undefined) request.toolChoice = options.toolChoice;\n if (options.outputSchema !== undefined) request.outputSchema = options.outputSchema;\n if (options.providerOptions !== undefined) request.providerOptions = options.providerOptions;\n\n return request;\n}\n\nfunction assertNoAgentInteractionParts(messages: readonly MessageType[]): void {\n for (const message of messages) {\n if (message.role === \"tool\" && message.content.some((part) => part.type !== \"tool-result\")) {\n throw new TypeError(\n \"Completion messages contain an unresolved Agent interaction response. Resume the Agent with its continuation instead of sending interaction parts directly to a provider.\",\n );\n }\n }\n}\n\nfunction messagesFromInput(input: string | MessageType | readonly MessageType[]): MessageType[] {\n if (typeof input === \"string\") {\n return [{ role: \"user\", content: input }];\n }\n if (Array.isArray(input)) {\n if (input.length === 0) {\n throw new Error(\"input must contain at least one Message.\");\n }\n return parseMessages(input);\n }\n return [parseMessage(input)];\n}\n","import { abortError, throwIfAborted } from \"../internal/abort\";\nimport { createCompletionRequest } from \"../internal/completion-request\";\nimport type { ModelCallOptions } from \"../model-call-options\";\nimport {\n type ResolvedRetryOptions,\n type RetrySetting,\n resolveRetryOptions,\n retryDelayMs,\n retryOptionsForFailure,\n runWithRetries,\n waitForRetry,\n} from \"../retry\";\nimport { toProviderJsonSchema, type ZodSchema } from \"../schema/zod-schema\";\nimport type {\n CompletionModel,\n CompletionModelStreamEvent,\n CompletionRequest,\n CompletionResponse,\n CompletionResult,\n CompletionStreamEvent,\n CompletionTool,\n Document,\n JsonObject,\n Message as MessageType,\n StreamingCompletionModel,\n ToolChoice,\n} from \"./types\";\nimport { assertCompletionRequestSupported, textFromAssistantContent, Usage } from \"./types\";\n\nexport type CompletionStructuredOutputPhase = \"truncated\" | \"parse\" | \"schema\";\n\nexport class CompletionStructuredOutputError extends Error {\n readonly phase: CompletionStructuredOutputPhase;\n readonly outputLength: number;\n readonly usage: Usage;\n readonly finishReason: CompletionResponse[\"finishReason\"];\n readonly providerFinishReason: string | undefined;\n\n constructor(options: {\n phase: CompletionStructuredOutputPhase;\n outputLength: number;\n usage: Usage;\n finishReason?: CompletionResponse[\"finishReason\"];\n providerFinishReason?: string | undefined;\n cause?: unknown;\n }) {\n const failure =\n options.phase === \"truncated\"\n ? \"because the provider reached its output limit\"\n : options.phase === \"parse\"\n ? \"during JSON parsing\"\n : \"during schema validation\";\n super(`Structured completion output failed ${failure}.`, { cause: options.cause });\n this.name = \"CompletionStructuredOutputError\";\n this.phase = options.phase;\n this.outputLength = options.outputLength;\n this.usage = options.usage;\n this.finishReason = options.finishReason;\n this.providerFinishReason = options.providerFinishReason;\n }\n}\n\nexport type CompletionInput =\n | { prompt: string; messages?: never }\n | { messages: readonly MessageType[]; prompt?: never };\n\nexport type CompletionBaseOptions<Model extends CompletionModel = CompletionModel> =\n CompletionInput & {\n model: Model;\n instructions?: string | undefined;\n documents?: readonly Document[] | undefined;\n tools?: readonly CompletionTool[] | undefined;\n temperature?: number | undefined;\n maxTokens?: number | undefined;\n toolChoice?: ToolChoice | undefined;\n providerOptions?: JsonObject | undefined;\n retries?: RetrySetting | undefined;\n abortSignal?: AbortSignal | undefined;\n };\n\nexport type GenerateCompletionOptions<Model extends CompletionModel = CompletionModel> =\n CompletionBaseOptions<Model> & { outputSchema?: never };\n\nexport type GenerateStructuredCompletionOptions<\n Output,\n Model extends CompletionModel = CompletionModel,\n> = CompletionBaseOptions<Model> & { outputSchema: ZodSchema<Output> };\n\nexport type StreamCompletionOptions<\n Model extends StreamingCompletionModel = StreamingCompletionModel,\n> = GenerateCompletionOptions<Model>;\n\nexport type StreamStructuredCompletionOptions<\n Output,\n Model extends StreamingCompletionModel = StreamingCompletionModel,\n> = GenerateStructuredCompletionOptions<Output, Model>;\n\ntype RawResponseOf<Model> =\n Model extends CompletionModel<infer RawResponse> ? RawResponse : unknown;\n\nexport function generateCompletion<Output, Model extends CompletionModel>(\n options: GenerateStructuredCompletionOptions<Output, Model>,\n): Promise<CompletionResult<Output, RawResponseOf<Model>>>;\nexport function generateCompletion<Model extends CompletionModel>(\n options: GenerateCompletionOptions<Model>,\n): Promise<CompletionResult<string, RawResponseOf<Model>>>;\nexport async function generateCompletion<Output, Model extends CompletionModel>(\n options: GenerateCompletionOptions<Model> | GenerateStructuredCompletionOptions<Output, Model>,\n): Promise<CompletionResult<Output | string, RawResponseOf<Model>>> {\n throwIfAborted(options.abortSignal);\n const request = requestFromOptions(options);\n assertCompletionRequestSupported(options.model, request);\n const retries = resolveOptionalRetries(options.retries);\n const response = await sendCompletion(options.model, request, retries, options.abortSignal);\n return resultFromResponse(response, structuredOutputSchema(options));\n}\n\nexport function streamCompletion<Output, Model extends StreamingCompletionModel>(\n options: StreamStructuredCompletionOptions<Output, Model>,\n): AsyncIterable<CompletionStreamEvent<Output, RawResponseOf<Model>>>;\nexport function streamCompletion<Model extends StreamingCompletionModel>(\n options: StreamCompletionOptions<Model>,\n): AsyncIterable<CompletionStreamEvent<string, RawResponseOf<Model>>>;\nexport function streamCompletion<Output, Model extends StreamingCompletionModel>(\n options: StreamCompletionOptions<Model> | StreamStructuredCompletionOptions<Output, Model>,\n): AsyncIterable<CompletionStreamEvent<Output | string, RawResponseOf<Model>>> {\n throwIfAborted(options.abortSignal);\n const request = requestFromOptions(options);\n if (!isStreamingCompletionModel(options.model) || !options.model.capabilities.streaming) {\n throw new Error(\"This completion model does not support streaming\");\n }\n assertCompletionRequestSupported(options.model, request, { streaming: true });\n const retries = resolveOptionalRetries(options.retries);\n return streamCompletionWithRetries(\n options.model,\n request,\n retries,\n options.abortSignal,\n structuredOutputSchema(options),\n );\n}\n\nasync function sendCompletion<Model extends CompletionModel>(\n model: Model,\n request: CompletionRequest,\n retries: ResolvedRetryOptions | undefined,\n abortSignal: AbortSignal | undefined,\n): Promise<CompletionResponse<RawResponseOf<Model>>> {\n const callOptions = modelCallOptions(abortSignal);\n return runWithRetries(\n () => {\n throwIfAborted(abortSignal);\n return model.completion(request, callOptions) as Promise<\n CompletionResponse<RawResponseOf<Model>>\n >;\n },\n retries,\n { streaming: false, abortSignal },\n );\n}\n\nfunction resolveOptionalRetries(\n setting: RetrySetting | undefined,\n): ResolvedRetryOptions | undefined {\n return setting === undefined || setting === false ? undefined : resolveRetryOptions(setting);\n}\n\nasync function* streamCompletionWithRetries<Output, Model extends StreamingCompletionModel>(\n model: Model,\n request: CompletionRequest,\n retries: ResolvedRetryOptions | undefined,\n abortSignal: AbortSignal | undefined,\n outputSchema: ZodSchema<Output> | undefined,\n): AsyncIterable<CompletionStreamEvent<Output | string, RawResponseOf<Model>>> {\n let attempt = 1;\n let swallowedUsage = Usage.empty();\n const callOptions = modelCallOptions(abortSignal);\n\n while (true) {\n let exposedProgress = false;\n let retryDelay: number | undefined;\n try {\n throwIfAborted(abortSignal);\n const events = model.streamCompletion(request, callOptions) as AsyncIterable<\n CompletionModelStreamEvent<RawResponseOf<Model>>\n >;\n for await (const event of events) {\n if (event.type === \"error\" && !exposedProgress) {\n const retryOptions = retryOptionsForFailure(retries, {\n error: event.error,\n attempt,\n streaming: true,\n });\n if (retryOptions !== undefined) {\n swallowedUsage = Usage.add(swallowedUsage, event.usage ?? Usage.empty());\n retryDelay = retryDelayMs(retryOptions, attempt);\n break;\n }\n }\n\n if (event.type === \"error\") {\n yield {\n type: \"error\",\n error: event.error,\n usage: Usage.add(swallowedUsage, event.usage ?? Usage.empty()),\n };\n return;\n }\n\n if (event.type === \"final\") {\n const response =\n swallowedUsage.totalTokens === 0\n ? event.response\n : {\n ...event.response,\n usage: Usage.add(swallowedUsage, event.response.usage),\n };\n try {\n yield {\n type: \"final\",\n result: resultFromResponse(response, outputSchema),\n };\n } catch (error) {\n yield { type: \"error\", error, usage: response.usage };\n }\n return;\n }\n\n exposedProgress = true;\n yield event;\n }\n\n if (retryDelay !== undefined) {\n await waitForRetry(retryDelay, abortSignal);\n attempt += 1;\n continue;\n }\n\n yield {\n type: \"error\",\n error: new Error(\"The completion model stream ended without a final event.\"),\n usage: swallowedUsage,\n };\n return;\n } catch (error) {\n const normalizedError =\n abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;\n if (!exposedProgress) {\n const retryOptions = retryOptionsForFailure(retries, {\n error: normalizedError,\n attempt,\n streaming: true,\n });\n if (retryOptions !== undefined) {\n try {\n await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);\n attempt += 1;\n continue;\n } catch (waitError) {\n yield { type: \"error\", error: waitError, usage: swallowedUsage };\n return;\n }\n }\n }\n yield { type: \"error\", error: normalizedError, usage: swallowedUsage };\n return;\n }\n }\n}\n\nfunction requestFromOptions<Model extends CompletionModel, Output>(\n options: GenerateCompletionOptions<Model> | GenerateStructuredCompletionOptions<Output, Model>,\n): CompletionRequest {\n const input = inputFromOptions(options);\n return createCompletionRequest(input, {\n instructions: options.instructions,\n documents: options.documents,\n tools: options.tools,\n temperature: options.temperature,\n maxTokens: options.maxTokens,\n toolChoice: options.toolChoice,\n providerOptions: options.providerOptions,\n outputSchema:\n \"outputSchema\" in options && options.outputSchema !== undefined\n ? toProviderJsonSchema(options.outputSchema)\n : undefined,\n });\n}\n\nfunction inputFromOptions(options: CompletionInput): string | readonly MessageType[] {\n const prompt = (options as { prompt?: unknown }).prompt;\n const messages = (options as { messages?: unknown }).messages;\n const hasPrompt = prompt !== undefined;\n const hasMessages = messages !== undefined;\n if (hasPrompt === hasMessages) {\n throw new TypeError(\"Exactly one of prompt or messages must be provided.\");\n }\n if (hasPrompt) {\n if (typeof prompt !== \"string\" || prompt.trim().length === 0) {\n throw new TypeError(\"Completion prompt must be a non-empty string.\");\n }\n return prompt;\n }\n if (!Array.isArray(messages)) {\n throw new TypeError(\"Completion messages must be an array of Message values.\");\n }\n return messages as readonly MessageType[];\n}\n\nfunction structuredOutputSchema<Output>(options: {\n outputSchema?: ZodSchema<Output> | undefined;\n}): ZodSchema<Output> | undefined {\n return options.outputSchema;\n}\n\nfunction resultFromResponse<Output, RawResponse>(\n response: CompletionResponse<RawResponse>,\n outputSchema: ZodSchema<Output> | undefined,\n): CompletionResult<Output | string, RawResponse> {\n const text = textFromAssistantContent(response.choice);\n const result: CompletionResult<Output | string, RawResponse> = {\n output: outputSchema === undefined ? text : parseCompletionOutput(text, outputSchema, response),\n text,\n content: [...response.choice],\n usage: response.usage,\n rawResponse: response.rawResponse,\n };\n if (response.finishReason !== undefined) result.finishReason = response.finishReason;\n if (response.providerFinishReason !== undefined) {\n result.providerFinishReason = response.providerFinishReason;\n }\n if (response.contextUsage !== undefined) result.contextUsage = response.contextUsage;\n if (response.messageId !== undefined) result.messageId = response.messageId;\n if (response.sources !== undefined) result.sources = [...response.sources];\n if (response.providerToolCalls !== undefined) {\n result.providerToolCalls = [...response.providerToolCalls];\n }\n return result;\n}\n\nfunction parseCompletionOutput<Output, RawResponse>(\n text: string,\n schema: ZodSchema<Output>,\n response: CompletionResponse<RawResponse>,\n): Output {\n if (response.finishReason === \"length\") {\n throw new CompletionStructuredOutputError({\n phase: \"truncated\",\n outputLength: text.length,\n usage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch (error) {\n throw new CompletionStructuredOutputError({\n phase: \"parse\",\n outputLength: text.length,\n usage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n cause: error,\n });\n }\n try {\n return schema.parse(json);\n } catch (error) {\n throw new CompletionStructuredOutputError({\n phase: \"schema\",\n outputLength: text.length,\n usage: response.usage,\n finishReason: response.finishReason,\n providerFinishReason: response.providerFinishReason,\n cause: error,\n });\n }\n}\n\nfunction modelCallOptions(abortSignal: AbortSignal | undefined): ModelCallOptions | undefined {\n return abortSignal === undefined ? undefined : { abortSignal };\n}\n\nexport function isStreamingCompletionModel(\n model: CompletionModel,\n): model is StreamingCompletionModel {\n return typeof (model as { streamCompletion?: unknown }).streamCompletion === \"function\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2JO,SAAS,qBACd,WACQ;AACR,QAAM,UAAU,UAAU,YAAY,UAAU,UAAU;AAC1D,MAAI,YAAY,QAAW;AACzB,WAAO,UAAU,YAAY,UAAU,OAAO;AAAA,EAChD;AACA,SAAO,QACJ,QAAQ,CAAC,SAAS;AACjB,QAAI,KAAK,SAAS,UAAU,KAAK,SAAS,WAAW;AACnD,aAAO,CAAC,KAAK,IAAI;AAAA,IACnB;AACA,WAAO,CAAC;AAAA,EACV,CAAC,EACA,KAAK,EAAE;AACZ;AAgCO,SAAS,eAAe,OAAuC;AACpE,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG;AACvE,WAAO;AAAA,EACT;AACA,QAAM,YAAY;AAClB,SACE,UAAU,SAAS,cACnB,OAAO,UAAU,aAAa,YAC9B,UAAU,SAAS,KAAK,EAAE,SAAS,KACnC,OAAO,UAAU,SAAS,YAC1B,UAAU,KAAK,KAAK,EAAE,SAAS,MAC9B,UAAU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,MAAyC,qBAAqB;AAC/E;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  generateCompletion
3
- } from "./chunk-HSA6NL2E.js";
3
+ } from "./chunk-HT4P3SSG.js";
4
4
 
5
5
  // src/memory/errors.ts
6
6
  var MemoryCompactionError = class extends Error {
@@ -235,4 +235,4 @@ export {
235
235
  createMemoryCompactionSummary,
236
236
  cumulativeCompactedMessageCount
237
237
  };
238
- //# sourceMappingURL=chunk-DNQNOHD5.js.map
238
+ //# sourceMappingURL=chunk-QXQQ2DBM.js.map