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

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 (78) hide show
  1. package/README.md +37 -3
  2. package/dist/agent/index.d.ts +28 -6
  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-LlCD_2UQ.d.ts} +2 -2
  8. package/dist/{chunk-AI5JMUW7.js → chunk-7OCVDT2X.js} +2 -2
  9. package/dist/{chunk-5MK3BISB.js → chunk-7YAH2F3J.js} +3 -3
  10. package/dist/{chunk-LXMAFD23.js → chunk-BAEFBTOW.js} +2 -2
  11. package/dist/chunk-BEU6FCTN.js +164 -0
  12. package/dist/chunk-BEU6FCTN.js.map +1 -0
  13. package/dist/{chunk-KFR4CDGK.js → chunk-DNQNOHD5.js} +2 -2
  14. package/dist/{chunk-VKYZZXP5.js → chunk-E5J4OY4K.js} +2 -2
  15. package/dist/{chunk-BY4OMNIU.js → chunk-FCANRQ5Q.js} +201 -191
  16. package/dist/chunk-FCANRQ5Q.js.map +1 -0
  17. package/dist/{chunk-PK5LKOFL.js → chunk-G5OACQEI.js} +4 -66
  18. package/dist/chunk-G5OACQEI.js.map +1 -0
  19. package/dist/{chunk-GQL5KRAH.js → chunk-H7BI3BSP.js} +2 -2
  20. package/dist/{chunk-D2ECOWN5.js → chunk-HSA6NL2E.js} +6 -4
  21. package/dist/{chunk-D2ECOWN5.js.map → chunk-HSA6NL2E.js.map} +1 -1
  22. package/dist/{chunk-BEYBU7VJ.js → chunk-HVHTVGPP.js} +2 -2
  23. package/dist/{chunk-KV6QCRQ4.js → chunk-JXZTTNCR.js} +3 -3
  24. package/dist/{chunk-3CMWKK32.js → chunk-RZDI7B6Z.js} +8 -5
  25. package/dist/chunk-RZDI7B6Z.js.map +1 -0
  26. package/dist/chunk-SROQA7I7.js +69 -0
  27. package/dist/chunk-SROQA7I7.js.map +1 -0
  28. package/dist/{chunk-TRQ3XRFD.js → chunk-TEV3OB7N.js} +26 -1
  29. package/dist/chunk-TEV3OB7N.js.map +1 -0
  30. package/dist/{chunk-FN7HLLAZ.js → chunk-UBE4WH6G.js} +2 -1
  31. package/dist/chunk-UBE4WH6G.js.map +1 -0
  32. package/dist/{chunk-ZCPOIDAQ.js → chunk-YDJA4R37.js} +4 -4
  33. package/dist/{chunk-GKDERULJ.js → chunk-YXLDR2O4.js} +2 -2
  34. package/dist/completion/index.js +6 -4
  35. package/dist/embeddings/index.js +2 -2
  36. package/dist/evals/index.d.ts +4 -3
  37. package/dist/evals/index.js +7 -6
  38. package/dist/evals/index.js.map +1 -1
  39. package/dist/extractor/index.js +5 -4
  40. package/dist/image-generation/index.js +2 -2
  41. package/dist/index.d.ts +7 -6
  42. package/dist/index.js +31 -38
  43. package/dist/internal/agent.d.ts +4 -3
  44. package/dist/internal/agent.js +13 -11
  45. package/dist/internal/agent.js.map +1 -1
  46. package/dist/mcp/index.js +7 -6
  47. package/dist/memory/index.js +5 -4
  48. package/dist/middleware-BqtLB_Xt.d.ts +56 -0
  49. package/dist/observability/index.d.ts +5 -4
  50. package/dist/observability/index.js +5 -4
  51. package/dist/pipeline/index.d.ts +5 -4
  52. package/dist/pipeline/index.js +6 -5
  53. package/dist/pipeline/index.js.map +1 -1
  54. package/dist/skills/index.js +7 -6
  55. package/dist/speech-generation/index.js +2 -2
  56. package/dist/{think-tool-D8frXxwV.d.ts → think-tool-Cz3QYNPX.d.ts} +1 -1
  57. package/dist/tool/index.d.ts +4 -3
  58. package/dist/tool/index.js +6 -5
  59. package/dist/transcription/index.js +2 -2
  60. package/dist/{types-CElwurHZ.d.ts → types-1KpjDfoN.d.ts} +2 -1
  61. package/dist/vector-store/index.d.ts +3 -2
  62. package/dist/vector-store/index.js +7 -4
  63. package/package.json +6 -2
  64. package/dist/chunk-3CMWKK32.js.map +0 -1
  65. package/dist/chunk-BY4OMNIU.js.map +0 -1
  66. package/dist/chunk-FN7HLLAZ.js.map +0 -1
  67. package/dist/chunk-PK5LKOFL.js.map +0 -1
  68. package/dist/chunk-TRQ3XRFD.js.map +0 -1
  69. /package/dist/{chunk-AI5JMUW7.js.map → chunk-7OCVDT2X.js.map} +0 -0
  70. /package/dist/{chunk-5MK3BISB.js.map → chunk-7YAH2F3J.js.map} +0 -0
  71. /package/dist/{chunk-LXMAFD23.js.map → chunk-BAEFBTOW.js.map} +0 -0
  72. /package/dist/{chunk-KFR4CDGK.js.map → chunk-DNQNOHD5.js.map} +0 -0
  73. /package/dist/{chunk-VKYZZXP5.js.map → chunk-E5J4OY4K.js.map} +0 -0
  74. /package/dist/{chunk-GQL5KRAH.js.map → chunk-H7BI3BSP.js.map} +0 -0
  75. /package/dist/{chunk-BEYBU7VJ.js.map → chunk-HVHTVGPP.js.map} +0 -0
  76. /package/dist/{chunk-KV6QCRQ4.js.map → chunk-JXZTTNCR.js.map} +0 -0
  77. /package/dist/{chunk-ZCPOIDAQ.js.map → chunk-YDJA4R37.js.map} +0 -0
  78. /package/dist/{chunk-GKDERULJ.js.map → chunk-YXLDR2O4.js.map} +0 -0
@@ -1,13 +1,29 @@
1
1
  import {
2
- isSkillTool
3
- } from "./chunk-YK4WAAS4.js";
2
+ assertAgentInteractionResponse,
3
+ parseAgentContinuation,
4
+ parseAgentInteractionResponse,
5
+ parseAgentQuestionPrompts
6
+ } from "./chunk-BEU6FCTN.js";
4
7
  import {
5
8
  isMcpTool
6
- } from "./chunk-5MK3BISB.js";
9
+ } from "./chunk-7YAH2F3J.js";
10
+ import {
11
+ MemoryCompactionConflictError,
12
+ MemoryCompactionError,
13
+ assertPositiveInteger,
14
+ createMemoryCompactionSummary,
15
+ cumulativeCompactedMessageCount
16
+ } from "./chunk-DNQNOHD5.js";
17
+ import {
18
+ startAgentRunObservers
19
+ } from "./chunk-E5J4OY4K.js";
20
+ import {
21
+ isSkillTool
22
+ } from "./chunk-YK4WAAS4.js";
7
23
  import {
8
24
  isQuestionTool,
9
25
  isToolIndex
10
- } from "./chunk-KV6QCRQ4.js";
26
+ } from "./chunk-JXZTTNCR.js";
11
27
  import {
12
28
  ToolNotFoundError,
13
29
  assertFiniteMinScore,
@@ -20,24 +36,15 @@ import {
20
36
  retrieveDocuments,
21
37
  toolMayRequireApproval,
22
38
  toolResultContentToText
23
- } from "./chunk-3CMWKK32.js";
24
- import {
25
- MemoryCompactionConflictError,
26
- MemoryCompactionError,
27
- assertPositiveInteger,
28
- createMemoryCompactionSummary,
29
- cumulativeCompactedMessageCount
30
- } from "./chunk-KFR4CDGK.js";
31
- import {
32
- startAgentRunObservers
33
- } from "./chunk-VKYZZXP5.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-TEV3OB7N.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-HSA6NL2E.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) {
@@ -1387,6 +1247,43 @@ function isGenerationDeltaEvent(type) {
1387
1247
  return type === "text_delta" || type === "reasoning_delta" || type === "tool_call_delta" || type === "tool_call" || type === "source" || type === "provider_tool_call";
1388
1248
  }
1389
1249
 
1250
+ // src/internal/agent-runtime/structured-output.ts
1251
+ var JSON_FENCE_START = "```json\n";
1252
+ var JSON_FENCE_CRLF_START = "```json\r\n";
1253
+ var UNLABELED_FENCE_START = "```\n";
1254
+ var UNLABELED_FENCE_CRLF_START = "```\r\n";
1255
+ var FENCE_END = "\n```";
1256
+ 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.";
1257
+ function normalizeStructuredOutput(text) {
1258
+ const trimmed = text.trim();
1259
+ const opening = fenceOpening(trimmed);
1260
+ if (opening === void 0 || !trimmed.endsWith(FENCE_END)) {
1261
+ return { text: trimmed, format: "raw" };
1262
+ }
1263
+ const closingStart = trimmed.length - 3;
1264
+ const precedingNewline = closingStart - 1;
1265
+ const contentEnd = trimmed[precedingNewline - 1] === "\r" ? precedingNewline - 1 : precedingNewline;
1266
+ return {
1267
+ text: trimmed.slice(opening.length, contentEnd).trim(),
1268
+ format: opening.format
1269
+ };
1270
+ }
1271
+ function fenceOpening(text) {
1272
+ if (text.startsWith(JSON_FENCE_START)) {
1273
+ return { length: JSON_FENCE_START.length, format: "json-fence" };
1274
+ }
1275
+ if (text.startsWith(JSON_FENCE_CRLF_START)) {
1276
+ return { length: JSON_FENCE_CRLF_START.length, format: "json-fence" };
1277
+ }
1278
+ if (text.startsWith(UNLABELED_FENCE_START)) {
1279
+ return { length: UNLABELED_FENCE_START.length, format: "unlabeled-fence" };
1280
+ }
1281
+ if (text.startsWith(UNLABELED_FENCE_CRLF_START)) {
1282
+ return { length: UNLABELED_FENCE_CRLF_START.length, format: "unlabeled-fence" };
1283
+ }
1284
+ return void 0;
1285
+ }
1286
+
1390
1287
  // src/internal/agent-runtime/tool-execution.ts
1391
1288
  var ToolCallExecutor = class {
1392
1289
  constructor(agent, activeHook, approvalHandler, lifecycle, runContext, concurrency, requestMiddlewares, abortSignal, cancel) {
@@ -2308,6 +2205,8 @@ var AgentRun = class _AgentRun {
2308
2205
  currentMessages = [];
2309
2206
  cancellationError;
2310
2207
  activeGeneration;
2208
+ validatedStructuredOutput;
2209
+ failedCompletionUsage = Usage.empty();
2311
2210
  abortController = new AbortController();
2312
2211
  removeExternalAbortListener;
2313
2212
  static fromAgent(agent, options) {
@@ -2605,6 +2504,12 @@ var AgentRun = class _AgentRun {
2605
2504
  if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2606
2505
  usage = Usage.add(usage, error.usage);
2607
2506
  }
2507
+ const failedCompletionUsage = this.takeFailedCompletionUsage();
2508
+ if (error instanceof AgentStructuredOutputError) {
2509
+ usage = Usage.add(usage, error.usage);
2510
+ } else {
2511
+ usage = Usage.add(usage, failedCompletionUsage);
2512
+ }
2608
2513
  this.runState = "closing";
2609
2514
  const runError = this.normalizeRunError(error);
2610
2515
  const reportedError = await this.reportRunFailure(
@@ -2777,7 +2682,7 @@ var AgentRun = class _AgentRun {
2777
2682
  request,
2778
2683
  modelInfo: generationStartArgs.modelInfo
2779
2684
  };
2780
- const bufferResponseEvents = this.shouldBufferStreamResponseEvents();
2685
+ const bufferResponseEvents = this.shouldBufferStreamResponseEvents() || this.agent.outputSchema !== void 0;
2781
2686
  const completionState = {
2782
2687
  response: void 0,
2783
2688
  firstDeltaMs: void 0,
@@ -2964,6 +2869,9 @@ var AgentRun = class _AgentRun {
2964
2869
  if (error instanceof MemoryCompactionError && error.usage !== void 0) {
2965
2870
  usage = Usage.add(usage, error.usage);
2966
2871
  }
2872
+ if (error instanceof AgentStructuredOutputError) {
2873
+ usage = Usage.add(usage, error.usage);
2874
+ }
2967
2875
  this.runState = "closing";
2968
2876
  const runError = this.normalizeRunError(error);
2969
2877
  const reportedError = await this.reportRunFailure(
@@ -2991,16 +2899,20 @@ var AgentRun = class _AgentRun {
2991
2899
  }
2992
2900
  async runCompletion(request, turn, runObservers) {
2993
2901
  assertCompletionRequestSupported(this.agent.model, request);
2902
+ this.validatedStructuredOutput = void 0;
2903
+ this.failedCompletionUsage = Usage.empty();
2994
2904
  const providerRequest = this.providerTraceRequest(request);
2995
2905
  const generationObservers = await runObservers.startGeneration(
2996
2906
  this.generationStartArgs(turn, request, providerRequest)
2997
2907
  );
2908
+ let currentRequest = request;
2909
+ let structuredRetryUsage = Usage.empty();
2998
2910
  try {
2999
2911
  for (let attempt = 1; ; attempt += 1) {
3000
2912
  let response;
3001
2913
  try {
3002
2914
  this.throwIfCancelled();
3003
- response = await this.agent.model.completion(request, this.modelCallOptions());
2915
+ response = await this.agent.model.completion(currentRequest, this.modelCallOptions());
3004
2916
  } catch (error) {
3005
2917
  const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
3006
2918
  if (retryOptions === void 0) {
@@ -3016,8 +2928,31 @@ var AgentRun = class _AgentRun {
3016
2928
  );
3017
2929
  continue;
3018
2930
  }
3019
- await generationObservers.end({ turn, response });
3020
- return response;
2931
+ const cumulativeUsage = Usage.add(structuredRetryUsage, response.usage);
2932
+ try {
2933
+ this.validateStructuredResponse(response, attempt, cumulativeUsage);
2934
+ } catch (error) {
2935
+ const retryOptions = this.retryOptionsForFailure(error, attempt, turn, false);
2936
+ if (retryOptions === void 0) {
2937
+ throw error;
2938
+ }
2939
+ structuredRetryUsage = cumulativeUsage;
2940
+ this.failedCompletionUsage = structuredRetryUsage;
2941
+ currentRequest = structuredOutputRetryRequest(currentRequest, response);
2942
+ await this.scheduleCompletionRetry(
2943
+ error,
2944
+ attempt,
2945
+ turn,
2946
+ false,
2947
+ retryOptions,
2948
+ runObservers
2949
+ );
2950
+ continue;
2951
+ }
2952
+ const finalResponse = structuredRetryUsage.totalTokens === 0 ? response : { ...response, usage: cumulativeUsage };
2953
+ await generationObservers.end({ turn, response: finalResponse });
2954
+ this.failedCompletionUsage = Usage.empty();
2955
+ return finalResponse;
3021
2956
  }
3022
2957
  } catch (error) {
3023
2958
  await settleFailureCleanup([() => generationObservers.error({ turn, error })]);
@@ -3046,12 +2981,14 @@ var AgentRun = class _AgentRun {
3046
2981
  if (!isStreamingCompletionModel(model)) {
3047
2982
  throw new TypeError("Streaming completion requires a streaming-capable model.");
3048
2983
  }
3049
- const accumulator = new CompletionStreamAccumulator();
2984
+ this.validatedStructuredOutput = void 0;
2985
+ let currentRequest = args.request;
3050
2986
  for (let attempt = 1; ; attempt += 1) {
2987
+ const accumulator = new CompletionStreamAccumulator();
3051
2988
  let hasProviderProgress = false;
3052
2989
  try {
3053
2990
  this.throwIfCancelled();
3054
- for await (const event of model.streamCompletion(args.request, this.modelCallOptions())) {
2991
+ for await (const event of model.streamCompletion(currentRequest, this.modelCallOptions())) {
3055
2992
  if (event.type === "error") {
3056
2993
  if (event.usage !== void 0) {
3057
2994
  args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, event.usage);
@@ -3077,7 +3014,34 @@ var AgentRun = class _AgentRun {
3077
3014
  }
3078
3015
  }
3079
3016
  }
3080
- args.state.response = accumulator.response();
3017
+ const response = accumulator.response();
3018
+ const cumulativeStructuredUsage = Usage.add(args.state.providerErrorUsage, response.usage);
3019
+ try {
3020
+ this.validateStructuredResponse(response, attempt, cumulativeStructuredUsage);
3021
+ } catch (error) {
3022
+ const retryOptions = this.retryOptionsForFailure(error, attempt, args.turn, true);
3023
+ if (retryOptions === void 0) {
3024
+ if (error instanceof AgentStructuredOutputError) {
3025
+ args.state.providerErrorUsage = Usage.empty();
3026
+ }
3027
+ throw error;
3028
+ }
3029
+ args.state.providerErrorUsage = Usage.add(args.state.providerErrorUsage, response.usage);
3030
+ args.state.firstDeltaMs = void 0;
3031
+ args.state.emittedToolCallIds.clear();
3032
+ currentRequest = structuredOutputRetryRequest(currentRequest, response);
3033
+ await this.scheduleCompletionRetry(
3034
+ error,
3035
+ attempt,
3036
+ args.turn,
3037
+ true,
3038
+ retryOptions,
3039
+ args.runObservers
3040
+ );
3041
+ continue;
3042
+ }
3043
+ args.state.response = args.state.providerErrorUsage.totalTokens === 0 ? response : { ...response, usage: cumulativeStructuredUsage };
3044
+ args.state.providerErrorUsage = Usage.empty();
3081
3045
  return;
3082
3046
  } catch (error) {
3083
3047
  const retryOptions = hasProviderProgress ? void 0 : this.retryOptionsForFailure(error, attempt, args.turn, true);
@@ -3508,16 +3472,55 @@ var AgentRun = class _AgentRun {
3508
3472
  output: this.parseOutput(text)
3509
3473
  };
3510
3474
  }
3511
- parseOutput(text) {
3475
+ validateStructuredResponse(response, attempt, usage) {
3476
+ if (this.agent.outputSchema === void 0) return;
3477
+ if (response.choice.some((item) => item.type === "tool-call")) return;
3478
+ const text = textFromAssistantContent(response.choice);
3479
+ const output = this.parseOutput(text, attempt, usage, { useValidatedOutput: false });
3480
+ this.validatedStructuredOutput = { text, output };
3481
+ }
3482
+ takeFailedCompletionUsage() {
3483
+ const usage = this.failedCompletionUsage;
3484
+ this.failedCompletionUsage = Usage.empty();
3485
+ return usage;
3486
+ }
3487
+ parseOutput(text, attempt = 1, usage = Usage.empty(), options = {}) {
3512
3488
  const schema = this.agent.outputSchema;
3513
3489
  if (schema === void 0) return text;
3490
+ if (options.useValidatedOutput !== false && this.validatedStructuredOutput?.text === text) {
3491
+ return this.validatedStructuredOutput.output;
3492
+ }
3493
+ const normalized = normalizeStructuredOutput(text);
3494
+ const maxAttempts = this.completionRetryOptions?.maxAttempts ?? 1;
3514
3495
  let json;
3515
3496
  try {
3516
- json = JSON.parse(text);
3497
+ json = JSON.parse(normalized.text);
3498
+ } catch (error) {
3499
+ throw new AgentStructuredOutputError({
3500
+ phase: "parse",
3501
+ attempt,
3502
+ maxAttempts,
3503
+ outputLength: text.length,
3504
+ normalizedLength: normalized.text.length,
3505
+ outputFormat: normalized.format,
3506
+ usage,
3507
+ cause: error
3508
+ });
3509
+ }
3510
+ try {
3511
+ return schema.parse(json);
3517
3512
  } catch (error) {
3518
- throw new Error("Agent expected the model response to be valid JSON.", { cause: error });
3513
+ throw new AgentStructuredOutputError({
3514
+ phase: "schema",
3515
+ attempt,
3516
+ maxAttempts,
3517
+ outputLength: text.length,
3518
+ normalizedLength: normalized.text.length,
3519
+ outputFormat: normalized.format,
3520
+ usage,
3521
+ cause: error
3522
+ });
3519
3523
  }
3520
- return schema.parse(json);
3521
3524
  }
3522
3525
  memoryCompactionResult() {
3523
3526
  return this.memoryCompaction === void 0 ? {} : { memoryCompaction: lifecycleSnapshot(this.memoryCompaction) };
@@ -4046,6 +4049,20 @@ function latestAssistantText(messages) {
4046
4049
  }
4047
4050
  return "";
4048
4051
  }
4052
+ function structuredOutputRetryRequest(request, response) {
4053
+ const invalidResponse = {
4054
+ role: "assistant",
4055
+ content: [...response.choice]
4056
+ };
4057
+ const correction = {
4058
+ role: "user",
4059
+ content: STRUCTURED_OUTPUT_RETRY_PROMPT
4060
+ };
4061
+ return {
4062
+ ...request,
4063
+ chatHistory: [...request.chatHistory, invalidResponse, correction]
4064
+ };
4065
+ }
4049
4066
  function providerMessages(messages) {
4050
4067
  const providerMessages2 = [];
4051
4068
  for (const message of messages) {
@@ -4119,7 +4136,7 @@ var DefaultAgentStream = class {
4119
4136
  };
4120
4137
 
4121
4138
  // src/agent/agent-tool.ts
4122
- import { z as z2 } from "zod";
4139
+ import { z } from "zod";
4123
4140
  function createAgentTool(agent, options) {
4124
4141
  if (options.suspension !== "reject") {
4125
4142
  throw new TypeError('Agent.asTool() requires suspension: "reject".');
@@ -4128,8 +4145,8 @@ function createAgentTool(agent, options) {
4128
4145
  return createTool({
4129
4146
  name: options.name,
4130
4147
  description,
4131
- inputSchema: z2.object({
4132
- prompt: z2.string().describe("The prompt to send to the agent.")
4148
+ inputSchema: z.object({
4149
+ prompt: z.string().describe("The prompt to send to the agent.")
4133
4150
  }),
4134
4151
  execute: async ({ prompt }, context) => {
4135
4152
  if (options.stream === true && context.emitStreamEvent !== void 0 && agent.model.capabilities.streaming && isStreamingCompletionModel(agent.model)) {
@@ -4681,13 +4698,6 @@ var Agent = class {
4681
4698
  };
4682
4699
 
4683
4700
  export {
4684
- agentInteractionRequestSchema,
4685
- agentInteractionResponseSchema,
4686
- agentContinuationSchema,
4687
- parseAgentInteractionRequest,
4688
- parseAgentInteractionResponse,
4689
- parseAgentContinuation,
4690
- assertAgentInteractionResponse,
4691
4701
  getAgentToolState,
4692
4702
  createHook,
4693
4703
  createVectorContext,
@@ -4696,4 +4706,4 @@ export {
4696
4706
  markResolvedAgentOptions,
4697
4707
  Agent
4698
4708
  };
4699
- //# sourceMappingURL=chunk-BY4OMNIU.js.map
4709
+ //# sourceMappingURL=chunk-FCANRQ5Q.js.map