@anvia/core 1.0.0-rc.4 → 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 (97) hide show
  1. package/README.md +46 -3
  2. package/dist/agent/index.d.ts +41 -13
  3. package/dist/agent/index.js +17 -27
  4. package/dist/{interactions-csssHYcN.d.ts → agent/interactions/index.d.ts} +3 -55
  5. package/dist/agent/interactions/index.js +20 -0
  6. package/dist/agent/interactions/index.js.map +1 -0
  7. package/dist/{agent-CXScUOpX.d.ts → agent-BK3jud9q.d.ts} +10 -10
  8. package/dist/{chunk-VKYZZXP5.js → chunk-7O45T5F2.js} +2 -2
  9. package/dist/{chunk-AI5JMUW7.js → chunk-7OCVDT2X.js} +2 -2
  10. package/dist/{chunk-FXAIYTRE.js → chunk-7YAH2F3J.js} +3 -3
  11. package/dist/{chunk-RFHQY2IO.js → chunk-BAEFBTOW.js} +2 -2
  12. package/dist/chunk-BEU6FCTN.js +164 -0
  13. package/dist/chunk-BEU6FCTN.js.map +1 -0
  14. package/dist/{chunk-ZCPOIDAQ.js → chunk-BOCJCECN.js} +4 -4
  15. package/dist/{chunk-PK5LKOFL.js → chunk-G5OACQEI.js} +4 -66
  16. package/dist/chunk-G5OACQEI.js.map +1 -0
  17. package/dist/{chunk-GQL5KRAH.js → chunk-H7BI3BSP.js} +2 -2
  18. package/dist/{chunk-D2ECOWN5.js → chunk-HT4P3SSG.js} +66 -8
  19. package/dist/chunk-HT4P3SSG.js.map +1 -0
  20. package/dist/{chunk-BEYBU7VJ.js → chunk-HVHTVGPP.js} +2 -2
  21. package/dist/{chunk-J2W63PJI.js → chunk-JXZTTNCR.js} +3 -3
  22. package/dist/{chunk-KFR4CDGK.js → chunk-QXQQ2DBM.js} +2 -2
  23. package/dist/{chunk-5GXSQYQT.js → chunk-QXSVVYQK.js} +324 -191
  24. package/dist/chunk-QXSVVYQK.js.map +1 -0
  25. package/dist/{chunk-XYTPYUGB.js → chunk-RZDI7B6Z.js} +7 -5
  26. package/dist/{chunk-XYTPYUGB.js.map → chunk-RZDI7B6Z.js.map} +1 -1
  27. package/dist/chunk-SROQA7I7.js +69 -0
  28. package/dist/chunk-SROQA7I7.js.map +1 -0
  29. package/dist/{chunk-FN7HLLAZ.js → chunk-UBE4WH6G.js} +2 -1
  30. package/dist/chunk-UBE4WH6G.js.map +1 -0
  31. package/dist/{chunk-TRQ3XRFD.js → chunk-VGJRXUPT.js} +33 -1
  32. package/dist/chunk-VGJRXUPT.js.map +1 -0
  33. package/dist/{chunk-GKDERULJ.js → chunk-YXLDR2O4.js} +2 -2
  34. package/dist/{client-DvUatElp.d.ts → client-BdQ_QZsY.d.ts} +2 -2
  35. package/dist/completion/index.d.ts +3 -3
  36. package/dist/completion/index.js +8 -4
  37. package/dist/{dynamic-tools-AEBOTgu1.d.ts → dynamic-tools--Aw37H9d.d.ts} +3 -3
  38. package/dist/embeddings/index.js +2 -2
  39. package/dist/evals/index.d.ts +8 -7
  40. package/dist/evals/index.js +7 -6
  41. package/dist/evals/index.js.map +1 -1
  42. package/dist/extractor/index.d.ts +1 -1
  43. package/dist/extractor/index.js +5 -4
  44. package/dist/guardrails/index.d.ts +4 -4
  45. package/dist/image-generation/index.d.ts +1 -1
  46. package/dist/image-generation/index.js +2 -2
  47. package/dist/index.d.ts +17 -16
  48. package/dist/index.js +24 -29
  49. package/dist/internal/agent.d.ts +12 -11
  50. package/dist/internal/agent.js +13 -11
  51. package/dist/internal/agent.js.map +1 -1
  52. package/dist/mcp/index.d.ts +4 -4
  53. package/dist/mcp/index.js +7 -6
  54. package/dist/memory/index.d.ts +3 -3
  55. package/dist/memory/index.js +5 -4
  56. package/dist/{message-schema-B2M7AYzR.d.ts → message-schema-_sP_RKhh.d.ts} +18 -2
  57. package/dist/middleware-QZsbz7Hf.d.ts +56 -0
  58. package/dist/observability/index.d.ts +9 -8
  59. package/dist/observability/index.js +5 -4
  60. package/dist/pipeline/index.d.ts +13 -12
  61. package/dist/pipeline/index.js +6 -5
  62. package/dist/pipeline/index.js.map +1 -1
  63. package/dist/skills/index.d.ts +4 -4
  64. package/dist/skills/index.js +7 -6
  65. package/dist/speech-generation/index.d.ts +1 -1
  66. package/dist/speech-generation/index.js +2 -2
  67. package/dist/{text-C_6eKrbC.d.ts → text-DTg1a8Mg.d.ts} +1 -1
  68. package/dist/{think-tool-D8frXxwV.d.ts → think-tool-C0n_dF2K.d.ts} +2 -2
  69. package/dist/tool/index.d.ts +8 -7
  70. package/dist/tool/index.js +6 -5
  71. package/dist/{tool-r62gf3QY.d.ts → tool-xHM_GmzT.d.ts} +1 -1
  72. package/dist/transcription/index.d.ts +1 -1
  73. package/dist/transcription/index.js +2 -2
  74. package/dist/{types-CElwurHZ.d.ts → types-2DBdXArn.d.ts} +8 -5
  75. package/dist/{types-DbolvLtZ.d.ts → types-B1KL4w14.d.ts} +1 -1
  76. package/dist/{types-C3gv9EX6.d.ts → types-D0Y2ZWS3.d.ts} +1 -1
  77. package/dist/{types-CIPaIbZo.d.ts → types-D7A6CIGt.d.ts} +1 -1
  78. package/dist/{types-D9rKQ_as.d.ts → types-DboZvHR_.d.ts} +8 -1
  79. package/dist/{types-RT3cuyRk.d.ts → types-Dyp7arZQ.d.ts} +1 -1
  80. package/dist/vector-store/index.d.ts +4 -4
  81. package/dist/vector-store/index.js +5 -4
  82. package/package.json +6 -2
  83. package/dist/chunk-5GXSQYQT.js.map +0 -1
  84. package/dist/chunk-D2ECOWN5.js.map +0 -1
  85. package/dist/chunk-FN7HLLAZ.js.map +0 -1
  86. package/dist/chunk-PK5LKOFL.js.map +0 -1
  87. package/dist/chunk-TRQ3XRFD.js.map +0 -1
  88. /package/dist/{chunk-VKYZZXP5.js.map → chunk-7O45T5F2.js.map} +0 -0
  89. /package/dist/{chunk-AI5JMUW7.js.map → chunk-7OCVDT2X.js.map} +0 -0
  90. /package/dist/{chunk-FXAIYTRE.js.map → chunk-7YAH2F3J.js.map} +0 -0
  91. /package/dist/{chunk-RFHQY2IO.js.map → chunk-BAEFBTOW.js.map} +0 -0
  92. /package/dist/{chunk-ZCPOIDAQ.js.map → chunk-BOCJCECN.js.map} +0 -0
  93. /package/dist/{chunk-GQL5KRAH.js.map → chunk-H7BI3BSP.js.map} +0 -0
  94. /package/dist/{chunk-BEYBU7VJ.js.map → chunk-HVHTVGPP.js.map} +0 -0
  95. /package/dist/{chunk-J2W63PJI.js.map → chunk-JXZTTNCR.js.map} +0 -0
  96. /package/dist/{chunk-KFR4CDGK.js.map → chunk-QXQQ2DBM.js.map} +0 -0
  97. /package/dist/{chunk-GKDERULJ.js.map → chunk-YXLDR2O4.js.map} +0 -0
@@ -1,23 +1,29 @@
1
+ import {
2
+ assertAgentInteractionResponse,
3
+ parseAgentContinuation,
4
+ parseAgentInteractionResponse,
5
+ parseAgentQuestionPrompts
6
+ } from "./chunk-BEU6FCTN.js";
1
7
  import {
2
8
  isMcpTool
3
- } from "./chunk-FXAIYTRE.js";
9
+ } from "./chunk-7YAH2F3J.js";
4
10
  import {
5
11
  MemoryCompactionConflictError,
6
12
  MemoryCompactionError,
7
13
  assertPositiveInteger,
8
14
  createMemoryCompactionSummary,
9
15
  cumulativeCompactedMessageCount
10
- } from "./chunk-KFR4CDGK.js";
16
+ } from "./chunk-QXQQ2DBM.js";
11
17
  import {
12
18
  startAgentRunObservers
13
- } from "./chunk-VKYZZXP5.js";
19
+ } from "./chunk-7O45T5F2.js";
14
20
  import {
15
21
  isSkillTool
16
22
  } from "./chunk-YK4WAAS4.js";
17
23
  import {
18
24
  isQuestionTool,
19
25
  isToolIndex
20
- } from "./chunk-J2W63PJI.js";
26
+ } from "./chunk-JXZTTNCR.js";
21
27
  import {
22
28
  ToolNotFoundError,
23
29
  assertFiniteMinScore,
@@ -30,14 +36,15 @@ import {
30
36
  retrieveDocuments,
31
37
  toolMayRequireApproval,
32
38
  toolResultContentToText
33
- } from "./chunk-XYTPYUGB.js";
39
+ } from "./chunk-RZDI7B6Z.js";
34
40
  import {
35
41
  AgentRunBlockedError,
36
42
  AgentRunCancelledError,
37
43
  AgentStreamClosedError,
44
+ AgentStructuredOutputError,
38
45
  AgentToolSuspensionError,
39
46
  MaxTurnsError
40
- } from "./chunk-TRQ3XRFD.js";
47
+ } from "./chunk-VGJRXUPT.js";
41
48
  import {
42
49
  mapWithConcurrency
43
50
  } from "./chunk-3RM57ZT2.js";
@@ -49,13 +56,15 @@ import {
49
56
  isProviderTool,
50
57
  isStreamingCompletionModel,
51
58
  textFromAssistantContent
52
- } from "./chunk-D2ECOWN5.js";
59
+ } from "./chunk-HT4P3SSG.js";
53
60
  import {
54
- isJsonValue,
55
61
  parseMessage,
56
62
  parseMessages,
57
63
  toProviderJsonSchema
58
- } from "./chunk-PK5LKOFL.js";
64
+ } from "./chunk-G5OACQEI.js";
65
+ import {
66
+ isJsonValue
67
+ } from "./chunk-SROQA7I7.js";
59
68
  import {
60
69
  abortError,
61
70
  resolveRetryOptions,
@@ -64,7 +73,7 @@ import {
64
73
  retryOptionsForFailure,
65
74
  throwIfAborted,
66
75
  waitForRetry
67
- } from "./chunk-FN7HLLAZ.js";
76
+ } from "./chunk-UBE4WH6G.js";
68
77
  import {
69
78
  appendGuardrailPolicies,
70
79
  hasEnforcedOutputGuardrails,
@@ -72,155 +81,6 @@ import {
72
81
  runOutputGuardrails
73
82
  } from "./chunk-AZB6N7P4.js";
74
83
 
75
- // src/agent/interactions.ts
76
- import { z } from "zod";
77
- var nonblank = z.string().trim().min(1);
78
- var jsonValueSchema = z.custom(isJsonValue, {
79
- message: "Expected a strict JSON value"
80
- });
81
- var jsonObjectSchema = z.custom(
82
- (value) => typeof value === "object" && value !== null && !Array.isArray(value) && isJsonValue(value),
83
- { message: "Expected a strict JSON object" }
84
- );
85
- var questionChoiceSchema = z.object({
86
- label: nonblank,
87
- value: nonblank
88
- }).strict();
89
- var questionPromptSchema = z.object({
90
- id: nonblank,
91
- text: nonblank,
92
- choices: z.array(questionChoiceSchema).min(1).optional(),
93
- allowCustom: z.boolean().optional()
94
- }).strict().superRefine((question, context) => {
95
- if (question.choices === void 0 && question.allowCustom === false) {
96
- context.addIssue({
97
- code: "custom",
98
- message: "A free-text question cannot disable custom answers.",
99
- path: ["allowCustom"]
100
- });
101
- }
102
- const values = /* @__PURE__ */ new Set();
103
- for (const [index, choice] of (question.choices ?? []).entries()) {
104
- if (values.has(choice.value)) {
105
- context.addIssue({
106
- code: "custom",
107
- message: "Question choice values must be unique.",
108
- path: ["choices", index, "value"]
109
- });
110
- }
111
- values.add(choice.value);
112
- }
113
- });
114
- var questionAnswerSchema = z.object({
115
- questionId: nonblank,
116
- value: nonblank
117
- }).strict();
118
- var interactionBase = {
119
- id: nonblank,
120
- toolName: nonblank,
121
- toolCallId: nonblank,
122
- callId: z.string().optional(),
123
- internalCallId: nonblank
124
- };
125
- var approvalRequestSchema = z.object({
126
- type: z.literal("tool-approval"),
127
- ...interactionBase,
128
- input: jsonValueSchema,
129
- reason: z.string().optional()
130
- }).strict();
131
- var questionRequestSchema = z.object({
132
- type: z.literal("tool-question"),
133
- ...interactionBase,
134
- questions: z.array(questionPromptSchema).min(1)
135
- }).strict().superRefine((request, context) => {
136
- const ids = /* @__PURE__ */ new Set();
137
- for (const [index, question] of request.questions.entries()) {
138
- if (ids.has(question.id)) {
139
- context.addIssue({
140
- code: "custom",
141
- message: "Question IDs must be unique.",
142
- path: ["questions", index, "id"]
143
- });
144
- }
145
- ids.add(question.id);
146
- }
147
- });
148
- var agentInteractionRequestSchema = z.discriminatedUnion("type", [
149
- approvalRequestSchema,
150
- questionRequestSchema
151
- ]);
152
- var agentInteractionResponseSchema = z.discriminatedUnion("type", [
153
- z.object({
154
- type: z.literal("tool-approval"),
155
- approved: z.boolean(),
156
- reason: z.string().optional()
157
- }).strict(),
158
- z.object({
159
- type: z.literal("tool-question"),
160
- answers: z.array(questionAnswerSchema)
161
- }).strict()
162
- ]);
163
- var agentContinuationSchema = z.object({
164
- version: z.literal(1),
165
- agentId: nonblank,
166
- sourceRunId: nonblank,
167
- interaction: agentInteractionRequestSchema,
168
- state: jsonObjectSchema
169
- }).strict();
170
- function parseAgentInteractionRequest(value) {
171
- return freeze(agentInteractionRequestSchema.parse(value));
172
- }
173
- function parseAgentInteractionResponse(value) {
174
- return freeze(agentInteractionResponseSchema.parse(value));
175
- }
176
- function parseAgentQuestionPrompts(value) {
177
- const request = questionRequestSchema.parse({
178
- type: "tool-question",
179
- id: "validation",
180
- toolName: "validation",
181
- toolCallId: "validation",
182
- internalCallId: "validation",
183
- questions: value
184
- });
185
- return freeze(request.questions);
186
- }
187
- function parseAgentContinuation(value) {
188
- return freeze(agentContinuationSchema.parse(value));
189
- }
190
- function assertAgentInteractionResponse(request, response) {
191
- if (request.type !== response.type) {
192
- throw new TypeError("Interaction response type does not match the pending request.");
193
- }
194
- if (request.type === "tool-question" && response.type === "tool-question") {
195
- assertQuestionAnswers(request, response.answers);
196
- }
197
- }
198
- function assertQuestionAnswers(request, answers) {
199
- const parsed = answers.map((answer) => questionAnswerSchema.parse(answer));
200
- const byId = new Map(parsed.map((answer) => [answer.questionId, answer]));
201
- if (byId.size !== parsed.length) {
202
- throw new TypeError("Question answers must not contain duplicate question IDs.");
203
- }
204
- if (byId.size !== request.questions.length) {
205
- throw new TypeError("Question responses must answer every question exactly once.");
206
- }
207
- for (const question of request.questions) {
208
- const answer = byId.get(question.id);
209
- if (answer === void 0) {
210
- throw new TypeError(`Question response is missing an answer for "${question.id}".`);
211
- }
212
- const choices = question.choices;
213
- if (choices !== void 0 && question.allowCustom !== true && !choices.some((choice) => choice.value === answer.value)) {
214
- throw new TypeError(`Question "${question.id}" requires one of its configured choices.`);
215
- }
216
- }
217
- }
218
- function freeze(value) {
219
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
220
- for (const child of Object.values(value)) freeze(child);
221
- return Object.freeze(value);
222
- }
223
-
224
84
  // src/agent/tool-state.ts
225
85
  var agentToolStates = /* @__PURE__ */ new WeakMap();
226
86
  function registerAgentToolState(agent, publicState, toolsByName) {
@@ -1103,6 +963,12 @@ var CompletionStreamAccumulator = class {
1103
963
  usage: finalResponse.usage,
1104
964
  rawResponse: finalResponse.rawResponse
1105
965
  };
966
+ if (finalResponse.finishReason !== void 0) {
967
+ mergedResponse.finishReason = finalResponse.finishReason;
968
+ }
969
+ if (finalResponse.providerFinishReason !== void 0) {
970
+ mergedResponse.providerFinishReason = finalResponse.providerFinishReason;
971
+ }
1106
972
  if (finalResponse.messageId !== void 0) {
1107
973
  mergedResponse.messageId = finalResponse.messageId;
1108
974
  }
@@ -1387,6 +1253,58 @@ function isGenerationDeltaEvent(type) {
1387
1253
  return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call" || type === "source" || type === "provider_tool_call";
1388
1254
  }
1389
1255
 
1256
+ // src/internal/agent-runtime/structured-output.ts
1257
+ var JSON_FENCE_START = "```json\n";
1258
+ var JSON_FENCE_CRLF_START = "```json\r\n";
1259
+ var UNLABELED_FENCE_START = "```\n";
1260
+ var UNLABELED_FENCE_CRLF_START = "```\r\n";
1261
+ var FENCE_END = "\n```";
1262
+ var STRUCTURED_OUTPUT_RETRY_PROMPT = "Your previous response was invalid structured output. Return only raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.";
1263
+ var STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT = "Your previous response exceeded the provider output limit. Return substantially shorter raw JSON that matches the supplied JSON schema. Do not use Markdown fences or include commentary.";
1264
+ var STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH = 8192;
1265
+ var STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER = "\n...[output omitted]...\n";
1266
+ function structuredOutputRepairPreview(text) {
1267
+ if (text.length <= STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH) {
1268
+ return { text, includedOutputLength: text.length };
1269
+ }
1270
+ const availableLength = STRUCTURED_OUTPUT_REPAIR_PREVIEW_MAX_LENGTH - STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER.length;
1271
+ const headLength = Math.ceil(availableLength / 2);
1272
+ const tailLength = availableLength - headLength;
1273
+ return {
1274
+ text: `${text.slice(0, headLength)}${STRUCTURED_OUTPUT_REPAIR_PREVIEW_MARKER}${text.slice(-tailLength)}`,
1275
+ includedOutputLength: headLength + tailLength
1276
+ };
1277
+ }
1278
+ function normalizeStructuredOutput(text) {
1279
+ const trimmed = text.trim();
1280
+ const opening = fenceOpening(trimmed);
1281
+ if (opening === void 0 || !trimmed.endsWith(FENCE_END)) {
1282
+ return { text: trimmed, format: "raw" };
1283
+ }
1284
+ const closingStart = trimmed.length - 3;
1285
+ const precedingNewline = closingStart - 1;
1286
+ const contentEnd = trimmed[precedingNewline - 1] === "\r" ? precedingNewline - 1 : precedingNewline;
1287
+ return {
1288
+ text: trimmed.slice(opening.length, contentEnd).trim(),
1289
+ format: opening.format
1290
+ };
1291
+ }
1292
+ function fenceOpening(text) {
1293
+ if (text.startsWith(JSON_FENCE_START)) {
1294
+ return { length: JSON_FENCE_START.length, format: "json-fence" };
1295
+ }
1296
+ if (text.startsWith(JSON_FENCE_CRLF_START)) {
1297
+ return { length: JSON_FENCE_CRLF_START.length, format: "json-fence" };
1298
+ }
1299
+ if (text.startsWith(UNLABELED_FENCE_START)) {
1300
+ return { length: UNLABELED_FENCE_START.length, format: "unlabeled-fence" };
1301
+ }
1302
+ if (text.startsWith(UNLABELED_FENCE_CRLF_START)) {
1303
+ return { length: UNLABELED_FENCE_CRLF_START.length, format: "unlabeled-fence" };
1304
+ }
1305
+ return void 0;
1306
+ }
1307
+
1390
1308
  // src/internal/agent-runtime/tool-execution.ts
1391
1309
  var ToolCallExecutor = class {
1392
1310
  constructor(agent, activeHook, approvalHandler, lifecycle, runContext, concurrency, requestMiddlewares, abortSignal, cancel) {
@@ -2308,6 +2226,8 @@ var AgentRun = class _AgentRun {
2308
2226
  currentMessages = [];
2309
2227
  cancellationError;
2310
2228
  activeGeneration;
2229
+ validatedStructuredOutput;
2230
+ failedCompletionUsage = Usage.empty();
2311
2231
  abortController = new AbortController();
2312
2232
  removeExternalAbortListener;
2313
2233
  static fromAgent(agent, options) {
@@ -2605,6 +2525,12 @@ var AgentRun = class _AgentRun {
2605
2525
  if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2606
2526
  usage = Usage.add(usage, error.usage);
2607
2527
  }
2528
+ const failedCompletionUsage = this.takeFailedCompletionUsage();
2529
+ if (error instanceof AgentStructuredOutputError) {
2530
+ usage = Usage.add(usage, error.usage);
2531
+ } else {
2532
+ usage = Usage.add(usage, failedCompletionUsage);
2533
+ }
2608
2534
  this.runState = "closing";
2609
2535
  const runError = this.normalizeRunError(error);
2610
2536
  const reportedError = await this.reportRunFailure(
@@ -2777,7 +2703,7 @@ var AgentRun = class _AgentRun {
2777
2703
  request,
2778
2704
  modelInfo: generationStartArgs.modelInfo
2779
2705
  };
2780
- const bufferResponseEvents = this.shouldBufferStreamResponseEvents();
2706
+ const bufferResponseEvents = this.shouldBufferStreamResponseEvents() || this.agent.outputSchema !== void 0;
2781
2707
  const completionState = {
2782
2708
  response: void 0,
2783
2709
  firstDeltaMs: void 0,
@@ -2964,6 +2890,9 @@ var AgentRun = class _AgentRun {
2964
2890
  if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2965
2891
  usage = Usage.add(usage, error.usage);
2966
2892
  }
2893
+ if (error instanceof AgentStructuredOutputError) {
2894
+ usage = Usage.add(usage, error.usage);
2895
+ }
2967
2896
  this.runState = "closing";
2968
2897
  const runError = this.normalizeRunError(error);
2969
2898
  const reportedError = await this.reportRunFailure(
@@ -2991,16 +2920,20 @@ var AgentRun = class _AgentRun {
2991
2920
  }
2992
2921
  async runCompletion(request, turn, runObservers) {
2993
2922
  assertCompletionRequestSupported(this.agent.model, request);
2923
+ this.validatedStructuredOutput = void 0;
2924
+ this.failedCompletionUsage = Usage.empty();
2994
2925
  const providerRequest = this.providerTraceRequest(request);
2995
2926
  const generationObservers = await runObservers.startGeneration(
2996
2927
  this.generationStartArgs(turn, request, providerRequest)
2997
2928
  );
2929
+ let currentRequest = request;
2930
+ let structuredRetryUsage = Usage.empty();
2998
2931
  try {
2999
2932
  for (let attempt = 1; ; attempt += 1) {
3000
2933
  let response;
3001
2934
  try {
3002
2935
  this.throwIfCancelled();
3003
- response = await this.agent.model.completion(request, this.modelCallOptions());
2936
+ response = await this.agent.model.completion(currentRequest, this.modelCallOptions());
3004
2937
  } catch (error) {
3005
2938
  const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
3006
2939
  if (retryOptions === void 0) {
@@ -3016,8 +2949,33 @@ var AgentRun = class _AgentRun {
3016
2949
  );
3017
2950
  continue;
3018
2951
  }
3019
- await generationObservers.end({ turn, response });
3020
- return response;
2952
+ const cumulativeUsage = Usage.add(structuredRetryUsage, response.usage);
2953
+ try {
2954
+ this.validateStructuredResponse(response, attempt, cumulativeUsage);
2955
+ } catch (error) {
2956
+ const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
2957
+ if (retryOptions === void 0) {
2958
+ throw error;
2959
+ }
2960
+ structuredRetryUsage = cumulativeUsage;
2961
+ this.failedCompletionUsage = structuredRetryUsage;
2962
+ const retryRequest = structuredOutputRetryRequest(request, response, error);
2963
+ currentRequest = retryRequest.request;
2964
+ await this.scheduleCompletionRetry(
2965
+ error,
2966
+ attempt,
2967
+ turn,
2968
+ false,
2969
+ retryOptions,
2970
+ runObservers,
2971
+ structuredOutputRetryEventAttributes(error, retryRequest)
2972
+ );
2973
+ continue;
2974
+ }
2975
+ const finalResponse = structuredRetryUsage.totalTokens === 0 ? response : { ...response, usage: cumulativeUsage };
2976
+ await generationObservers.end({ turn, response: finalResponse });
2977
+ this.failedCompletionUsage = Usage.empty();
2978
+ return finalResponse;
3021
2979
  }
3022
2980
  } catch (error) {
3023
2981
  await settleFailureCleanup([() => generationObservers.error({ turn, error })]);
@@ -3046,12 +3004,14 @@ var AgentRun = class _AgentRun {
3046
3004
  if (!isStreamingCompletionModel(model)) {
3047
3005
  throw new TypeError("Streaming completion requires a streaming-capable model.");
3048
3006
  }
3049
- const accumulator = new CompletionStreamAccumulator();
3007
+ this.validatedStructuredOutput = void 0;
3008
+ let currentRequest = args.request;
3050
3009
  for (let attempt = 1; ; attempt += 1) {
3010
+ const accumulator = new CompletionStreamAccumulator();
3051
3011
  let hasProviderProgress = false;
3052
3012
  try {
3053
3013
  this.throwIfCancelled();
3054
- for await (const event of model.streamCompletion(args.request, this.modelCallOptions())) {
3014
+ for await (const event of model.streamCompletion(currentRequest, this.modelCallOptions())) {
3055
3015
  if (event.type === "error") {
3056
3016
  if (event.usage !== void 0) {
3057
3017
  args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, event.usage);
@@ -3077,7 +3037,36 @@ var AgentRun = class _AgentRun {
3077
3037
  }
3078
3038
  }
3079
3039
  }
3080
- args.state.response = accumulator.response();
3040
+ const response = accumulator.response();
3041
+ const cumulativeStructuredUsage = Usage.add(args.state.providerErrorUsage, response.usage);
3042
+ try {
3043
+ this.validateStructuredResponse(response, attempt, cumulativeStructuredUsage);
3044
+ } catch (error) {
3045
+ const retryOptions = this.retryOptionsForFailure(error, attempt, args.turn, true);
3046
+ if (retryOptions === void 0) {
3047
+ if (error instanceof AgentStructuredOutputError) {
3048
+ args.state.providerErrorUsage = Usage.empty();
3049
+ }
3050
+ throw error;
3051
+ }
3052
+ args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, response.usage);
3053
+ args.state.firstDeltaMs = void 0;
3054
+ args.state.emittedToolCallIds.clear();
3055
+ const retryRequest = structuredOutputRetryRequest(args.request, response, error);
3056
+ currentRequest = retryRequest.request;
3057
+ await this.scheduleCompletionRetry(
3058
+ error,
3059
+ attempt,
3060
+ args.turn,
3061
+ true,
3062
+ retryOptions,
3063
+ args.runObservers,
3064
+ structuredOutputRetryEventAttributes(error, retryRequest)
3065
+ );
3066
+ continue;
3067
+ }
3068
+ args.state.response = args.state.providerErrorUsage.totalTokens === 0 ? response : { ...response, usage: cumulativeStructuredUsage };
3069
+ args.state.providerErrorUsage = Usage.empty();
3081
3070
  return;
3082
3071
  } catch (error) {
3083
3072
  const retryOptions = hasProviderProgress ? void 0 : this.retryOptionsForFailure(error, attempt, args.turn, true);
@@ -3216,6 +3205,10 @@ var AgentRun = class _AgentRun {
3216
3205
  modelId: this.agent.model.modelId,
3217
3206
  usage: { ...response.usage }
3218
3207
  };
3208
+ if (response.finishReason !== void 0) generation.finishReason = response.finishReason;
3209
+ if (response.providerFinishReason !== void 0) {
3210
+ generation.providerFinishReason = response.providerFinishReason;
3211
+ }
3219
3212
  if (response.contextUsage !== void 0) generation.contextUsage = response.contextUsage;
3220
3213
  if (response.sources !== void 0) generation.sources = response.sources;
3221
3214
  if (response.providerToolCalls !== void 0) {
@@ -3261,20 +3254,24 @@ var AgentRun = class _AgentRun {
3261
3254
  streaming
3262
3255
  });
3263
3256
  }
3264
- async scheduleCompletionRetry(error, attempt, turn, streaming, options, runObservers) {
3257
+ async scheduleCompletionRetry(error, attempt, turn, streaming, options, runObservers, additionalAttributes) {
3265
3258
  const delayMs = retryDelayMs(options, attempt);
3259
+ const attributes = {
3260
+ turn,
3261
+ attempt,
3262
+ nextAttempt: attempt + 1,
3263
+ maxAttempts: options.maxAttempts,
3264
+ delayMs,
3265
+ streaming,
3266
+ ...retryErrorAttributes(error)
3267
+ };
3268
+ if (additionalAttributes !== void 0) {
3269
+ Object.assign(attributes, additionalAttributes);
3270
+ }
3266
3271
  await runObservers.event({
3267
3272
  name: "completion.retry",
3268
3273
  level: "WARNING",
3269
- attributes: {
3270
- turn,
3271
- attempt,
3272
- nextAttempt: attempt + 1,
3273
- maxAttempts: options.maxAttempts,
3274
- delayMs,
3275
- streaming,
3276
- ...retryErrorAttributes(error)
3277
- }
3274
+ attributes
3278
3275
  });
3279
3276
  await waitForRetry(delayMs, this.abortController.signal);
3280
3277
  }
@@ -3508,16 +3505,81 @@ var AgentRun = class _AgentRun {
3508
3505
  output: this.parseOutput(text)
3509
3506
  };
3510
3507
  }
3511
- parseOutput(text) {
3508
+ validateStructuredResponse(response, attempt, usage) {
3509
+ if (this.agent.outputSchema === void 0) return;
3510
+ if (response.choice.some((item) => item.type === "tool-call")) return;
3511
+ const text = textFromAssistantContent(response.choice);
3512
+ const normalized = normalizeStructuredOutput(text);
3513
+ if (response.finishReason === "length") {
3514
+ throw new AgentStructuredOutputError({
3515
+ phase: "truncated",
3516
+ attempt,
3517
+ maxAttempts: this.completionRetryOptions?.maxAttempts ?? 1,
3518
+ outputLength: text.length,
3519
+ normalizedLength: normalized.text.length,
3520
+ outputFormat: normalized.format,
3521
+ attemptUsage: response.usage,
3522
+ usage,
3523
+ finishReason: response.finishReason,
3524
+ providerFinishReason: response.providerFinishReason
3525
+ });
3526
+ }
3527
+ const output = this.parseOutput(text, attempt, usage, {
3528
+ useValidatedOutput: false,
3529
+ attemptUsage: response.usage,
3530
+ finishReason: response.finishReason,
3531
+ providerFinishReason: response.providerFinishReason
3532
+ });
3533
+ this.validatedStructuredOutput = { text, output };
3534
+ }
3535
+ takeFailedCompletionUsage() {
3536
+ const usage = this.failedCompletionUsage;
3537
+ this.failedCompletionUsage = Usage.empty();
3538
+ return usage;
3539
+ }
3540
+ parseOutput(text, attempt = 1, usage = Usage.empty(), options = {}) {
3512
3541
  const schema = this.agent.outputSchema;
3513
3542
  if (schema === void 0) return text;
3543
+ if (options.useValidatedOutput !== false && this.validatedStructuredOutput?.text === text) {
3544
+ return this.validatedStructuredOutput.output;
3545
+ }
3546
+ const normalized = normalizeStructuredOutput(text);
3547
+ const maxAttempts = this.completionRetryOptions?.maxAttempts ?? 1;
3514
3548
  let json;
3515
3549
  try {
3516
- json = JSON.parse(text);
3550
+ json = JSON.parse(normalized.text);
3517
3551
  } catch (error) {
3518
- throw new Error("Agent expected the model response to be valid JSON.", { cause: error });
3552
+ throw new AgentStructuredOutputError({
3553
+ phase: "parse",
3554
+ attempt,
3555
+ maxAttempts,
3556
+ outputLength: text.length,
3557
+ normalizedLength: normalized.text.length,
3558
+ outputFormat: normalized.format,
3559
+ attemptUsage: options.attemptUsage ?? usage,
3560
+ usage,
3561
+ finishReason: options.finishReason,
3562
+ providerFinishReason: options.providerFinishReason,
3563
+ cause: error
3564
+ });
3565
+ }
3566
+ try {
3567
+ return schema.parse(json);
3568
+ } catch (error) {
3569
+ throw new AgentStructuredOutputError({
3570
+ phase: "schema",
3571
+ attempt,
3572
+ maxAttempts,
3573
+ outputLength: text.length,
3574
+ normalizedLength: normalized.text.length,
3575
+ outputFormat: normalized.format,
3576
+ attemptUsage: options.attemptUsage ?? usage,
3577
+ usage,
3578
+ finishReason: options.finishReason,
3579
+ providerFinishReason: options.providerFinishReason,
3580
+ cause: error
3581
+ });
3519
3582
  }
3520
- return schema.parse(json);
3521
3583
  }
3522
3584
  memoryCompactionResult() {
3523
3585
  return this.memoryCompaction === void 0 ? {} : { memoryCompaction: lifecycleSnapshot(this.memoryCompaction) };
@@ -3981,10 +4043,14 @@ function responseStreamEvents(turn, response, includeProviderArtifacts = true) {
3981
4043
  function generationArtifacts(messages) {
3982
4044
  const sources = /* @__PURE__ */ new Map();
3983
4045
  const providerToolCalls = /* @__PURE__ */ new Map();
4046
+ let finishReason;
4047
+ let providerFinishReason;
3984
4048
  let contextUsage;
3985
4049
  for (const message of messages) {
3986
4050
  const metadata = getAssistantGenerationMetadata(message);
3987
4051
  if (metadata !== void 0) {
4052
+ finishReason = metadata.finishReason;
4053
+ providerFinishReason = metadata.providerFinishReason;
3988
4054
  contextUsage = metadata.contextUsage;
3989
4055
  }
3990
4056
  for (const source of metadata?.sources ?? []) {
@@ -4000,6 +4066,10 @@ function generationArtifacts(messages) {
4000
4066
  if (providerToolCalls.size > 0) {
4001
4067
  artifacts.providerToolCalls = [...providerToolCalls.values()];
4002
4068
  }
4069
+ if (finishReason !== void 0) artifacts.finishReason = finishReason;
4070
+ if (providerFinishReason !== void 0) {
4071
+ artifacts.providerFinishReason = providerFinishReason;
4072
+ }
4003
4073
  if (contextUsage !== void 0) artifacts.contextUsage = contextUsage;
4004
4074
  return artifacts;
4005
4075
  }
@@ -4046,6 +4116,76 @@ function latestAssistantText(messages) {
4046
4116
  }
4047
4117
  return "";
4048
4118
  }
4119
+ function structuredOutputRetryRequest(request, response, error) {
4120
+ const truncated = error instanceof AgentStructuredOutputError && error.phase === "truncated";
4121
+ const correction = {
4122
+ role: "user",
4123
+ content: truncated ? STRUCTURED_OUTPUT_TRUNCATED_RETRY_PROMPT : STRUCTURED_OUTPUT_RETRY_PROMPT
4124
+ };
4125
+ if (truncated) {
4126
+ return {
4127
+ request: {
4128
+ ...request,
4129
+ chatHistory: [...request.chatHistory, correction]
4130
+ },
4131
+ previousResponse: "omitted",
4132
+ includedOutputLength: 0
4133
+ };
4134
+ }
4135
+ const preview = structuredOutputRepairPreview(textFromAssistantContent(response.choice));
4136
+ if (preview.includedOutputLength === 0) {
4137
+ return {
4138
+ request: {
4139
+ ...request,
4140
+ chatHistory: [...request.chatHistory, correction]
4141
+ },
4142
+ previousResponse: "omitted",
4143
+ includedOutputLength: 0
4144
+ };
4145
+ }
4146
+ const invalidResponse = {
4147
+ role: "assistant",
4148
+ content: [{ type: "text", text: preview.text }]
4149
+ };
4150
+ return {
4151
+ request: {
4152
+ ...request,
4153
+ chatHistory: [...request.chatHistory, invalidResponse, correction]
4154
+ },
4155
+ previousResponse: "preview",
4156
+ includedOutputLength: preview.includedOutputLength
4157
+ };
4158
+ }
4159
+ function structuredOutputRetryEventAttributes(error, retryRequest) {
4160
+ const attributes = {
4161
+ previousResponse: retryRequest.previousResponse,
4162
+ includedOutputLength: retryRequest.includedOutputLength
4163
+ };
4164
+ if (!(error instanceof AgentStructuredOutputError)) return attributes;
4165
+ Object.assign(attributes, {
4166
+ failurePhase: error.phase,
4167
+ outputLength: error.outputLength,
4168
+ normalizedLength: error.normalizedLength,
4169
+ attemptUsage: usageEventValue(error.attemptUsage),
4170
+ cumulativeUsage: usageEventValue(error.usage)
4171
+ });
4172
+ if (error.finishReason !== void 0) attributes.finishReason = error.finishReason;
4173
+ if (error.providerFinishReason !== void 0) {
4174
+ attributes.providerFinishReason = error.providerFinishReason;
4175
+ }
4176
+ return attributes;
4177
+ }
4178
+ function usageEventValue(usage) {
4179
+ const value = {
4180
+ inputTokens: usage.inputTokens,
4181
+ outputTokens: usage.outputTokens,
4182
+ totalTokens: usage.totalTokens,
4183
+ cachedInputTokens: usage.cachedInputTokens,
4184
+ cacheCreationInputTokens: usage.cacheCreationInputTokens
4185
+ };
4186
+ if (usage.details !== void 0) value.details = { ...usage.details };
4187
+ return value;
4188
+ }
4049
4189
  function providerMessages(messages) {
4050
4190
  const providerMessages2 = [];
4051
4191
  for (const message of messages) {
@@ -4119,7 +4259,7 @@ var DefaultAgentStream = class {
4119
4259
  };
4120
4260
 
4121
4261
  // src/agent/agent-tool.ts
4122
- import { z as z2 } from "zod";
4262
+ import { z } from "zod";
4123
4263
  function createAgentTool(agent, options) {
4124
4264
  if (options.suspension !== "reject") {
4125
4265
  throw new TypeError('Agent.asTool() requires suspension: "reject".');
@@ -4128,8 +4268,8 @@ function createAgentTool(agent, options) {
4128
4268
  return createTool({
4129
4269
  name: options.name,
4130
4270
  description,
4131
- inputSchema: z2.object({
4132
- prompt: z2.string().describe("The prompt to send to the agent.")
4271
+ inputSchema: z.object({
4272
+ prompt: z.string().describe("The prompt to send to the agent.")
4133
4273
  }),
4134
4274
  execute: async ({ prompt }, context) => {
4135
4275
  if (options.stream === true && context.emitStreamEvent !== void 0 && agent.model.capabilities.streaming && isStreamingCompletionModel(agent.model)) {
@@ -4681,13 +4821,6 @@ var Agent = class {
4681
4821
  };
4682
4822
 
4683
4823
  export {
4684
- agentInteractionRequestSchema,
4685
- agentInteractionResponseSchema,
4686
- agentContinuationSchema,
4687
- parseAgentInteractionRequest,
4688
- parseAgentInteractionResponse,
4689
- parseAgentContinuation,
4690
- assertAgentInteractionResponse,
4691
4824
  getAgentToolState,
4692
4825
  createHook,
4693
4826
  createVectorContext,
@@ -4696,4 +4829,4 @@ export {
4696
4829
  markResolvedAgentOptions,
4697
4830
  Agent
4698
4831
  };
4699
- //# sourceMappingURL=chunk-5GXSQYQT.js.map
4832
+ //# sourceMappingURL=chunk-QXSVVYQK.js.map