@juspay/neurolink 10.10.0 → 10.10.2

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 (33) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/browser/neurolink.min.js +394 -392
  3. package/dist/context/stages/structuredSummarizer.js +15 -3
  4. package/dist/context/summarizationEngine.js +12 -2
  5. package/dist/context/toolPairRepair.d.ts +34 -5
  6. package/dist/context/toolPairRepair.js +218 -43
  7. package/dist/core/modules/GenerationHandler.js +21 -2
  8. package/dist/core/modules/structuredOutputPolicy.d.ts +8 -0
  9. package/dist/core/modules/structuredOutputPolicy.js +8 -0
  10. package/dist/core/redisConversationMemoryManager.js +8 -0
  11. package/dist/lib/context/stages/structuredSummarizer.js +15 -3
  12. package/dist/lib/context/summarizationEngine.js +12 -2
  13. package/dist/lib/context/toolPairRepair.d.ts +34 -5
  14. package/dist/lib/context/toolPairRepair.js +218 -43
  15. package/dist/lib/core/modules/GenerationHandler.js +21 -2
  16. package/dist/lib/core/modules/structuredOutputPolicy.d.ts +8 -0
  17. package/dist/lib/core/modules/structuredOutputPolicy.js +8 -0
  18. package/dist/lib/core/redisConversationMemoryManager.js +8 -0
  19. package/dist/lib/providers/anthropic/client.js +105 -3
  20. package/dist/lib/providers/anthropic/structuredOutput.d.ts +58 -0
  21. package/dist/lib/providers/anthropic/structuredOutput.js +98 -0
  22. package/dist/lib/types/context.d.ts +12 -0
  23. package/dist/lib/types/conversation.d.ts +11 -0
  24. package/dist/lib/types/generate.d.ts +11 -0
  25. package/dist/lib/utils/conversationMemory.js +18 -2
  26. package/dist/providers/anthropic/client.js +105 -3
  27. package/dist/providers/anthropic/structuredOutput.d.ts +58 -0
  28. package/dist/providers/anthropic/structuredOutput.js +97 -0
  29. package/dist/types/context.d.ts +12 -0
  30. package/dist/types/conversation.d.ts +11 -0
  31. package/dist/types/generate.d.ts +11 -0
  32. package/dist/utils/conversationMemory.js +18 -2
  33. package/package.json +4 -2
@@ -1,62 +1,237 @@
1
1
  /**
2
2
  * Tool Use/Result Pair Repair
3
3
  *
4
- * After compaction, validates that every tool_use (tool_call) has a
5
- * corresponding tool_result and vice versa. Inserts synthetic
6
- * placeholders for orphaned entries.
4
+ * After compaction (or a pointer-based history slice) the message array can
5
+ * contain a `tool_call` whose `tool_result` was dropped, or a `tool_result`
6
+ * whose `tool_call` was dropped. Providers reject both, so orphans are filled
7
+ * with synthetic placeholders.
8
+ *
9
+ * Pairing is BATCH- and ID-aware, not adjacency-based. A single agent step
10
+ * with parallel tool calls is persisted as every `tool_call` followed by every
11
+ * `tool_result` (see flushPendingToolData), so `tool_call` is routinely
12
+ * followed by another `tool_call` in perfectly healthy history. Matching on
13
+ * adjacency treats that as an orphan and injects a bogus "result unavailable"
14
+ * over a result that is present a few entries later.
15
+ *
16
+ * Two modes, chosen per batch:
17
+ * - ID mode — `toolCallId` present: pair by id, order-independent.
18
+ * - legacy mode — sessions written before `toolCallId` existed: pair
19
+ * positionally WITHIN the batch (call[i] ↔ result[i]).
7
20
  */
8
21
  import { randomUUID } from "crypto";
22
+ const MISSING_RESULT_CONTENT = "[Tool result unavailable - conversation was compacted]";
9
23
  /**
10
- * Repair orphaned tool_use/tool_result pairs in a message array.
11
- *
12
- * Ensures every tool_call has a following tool_result and vice versa.
24
+ * Collect the tool batch starting at `start` (which must index a tool-role
25
+ * message). Consumes the maximal run of calls followed by the maximal run of
26
+ * results. A leading run of results with no calls (head-cut orphan) yields a
27
+ * batch with an empty `calls` array.
13
28
  */
14
- export function repairToolPairs(messages) {
15
- const result = [];
29
+ function collectBatch(messages, start) {
30
+ let i = start;
31
+ const calls = [];
32
+ const results = [];
33
+ while (i < messages.length && messages[i].role === "tool_call") {
34
+ calls.push(messages[i]);
35
+ i++;
36
+ }
37
+ while (i < messages.length && messages[i].role === "tool_result") {
38
+ results.push(messages[i]);
39
+ i++;
40
+ }
41
+ return { calls, results, endIndex: i };
42
+ }
43
+ /** Synthetic `tool_result` standing in for a call whose result was dropped. */
44
+ function syntheticResult(call) {
45
+ return {
46
+ id: `repair-result-${randomUUID()}`,
47
+ role: "tool_result",
48
+ content: MISSING_RESULT_CONTENT,
49
+ tool: call.tool,
50
+ ...(call.toolCallId ? { toolCallId: call.toolCallId } : {}),
51
+ timestamp: call.timestamp,
52
+ metadata: { truncated: true },
53
+ };
54
+ }
55
+ /** Synthetic `tool_call` standing in for a result whose call was dropped. */
56
+ function syntheticCall(result) {
57
+ return {
58
+ id: `repair-call-${randomUUID()}`,
59
+ role: "tool_call",
60
+ content: `[Tool call for ${result.tool || "unknown"} - conversation was compacted]`,
61
+ tool: result.tool,
62
+ ...(result.toolCallId ? { toolCallId: result.toolCallId } : {}),
63
+ timestamp: result.timestamp,
64
+ metadata: { truncated: true },
65
+ };
66
+ }
67
+ /**
68
+ * Repair one batch, emitting calls then results with every call matched to
69
+ * exactly one result. Returns the rebuilt run plus how many placeholders of
70
+ * each kind were needed.
71
+ */
72
+ function repairBatch(batch) {
73
+ const { calls, results } = batch;
74
+ // ID mode requires ids on BOTH sides; a partially-migrated batch (some
75
+ // entries written before toolCallId existed) falls back to legacy pairing
76
+ // rather than treating the id-less half as universally orphaned.
77
+ const useIds = calls.length > 0 &&
78
+ results.length > 0 &&
79
+ calls.every((m) => !!m.toolCallId) &&
80
+ results.every((m) => !!m.toolCallId);
81
+ const outCalls = [...calls];
82
+ const outResults = [];
16
83
  let orphanedCallsFixed = 0;
17
84
  let orphanedResultsFixed = 0;
18
- for (let i = 0; i < messages.length; i++) {
19
- const msg = messages[i];
20
- const nextMsg = i + 1 < messages.length ? messages[i + 1] : undefined;
21
- if (msg.role === "tool_call") {
22
- result.push(msg);
23
- // Check if next message is the corresponding tool_result
24
- if (!nextMsg || nextMsg.role !== "tool_result") {
25
- // Insert synthetic tool_result
26
- result.push({
27
- id: `repair-result-${randomUUID()}`,
28
- role: "tool_result",
29
- content: "[Tool result unavailable - conversation was compacted]",
30
- tool: msg.tool,
31
- timestamp: msg.timestamp,
32
- metadata: { truncated: true },
33
- });
34
- orphanedCallsFixed++;
85
+ let changed = false;
86
+ if (useIds) {
87
+ // Duplicate ids (a retry that re-emitted a result) keep the FIRST result;
88
+ // later duplicates are dropped so a call never gains a second result.
89
+ const resultById = new Map();
90
+ for (const result of results) {
91
+ const key = result.toolCallId;
92
+ if (!resultById.has(key)) {
93
+ resultById.set(key, result);
94
+ }
95
+ else {
96
+ changed = true;
35
97
  }
36
98
  }
37
- else if (msg.role === "tool_result") {
38
- // Check if previous message was the corresponding tool_call
39
- const prevMsg = result.length > 0 ? result[result.length - 1] : undefined;
40
- if (!prevMsg ||
41
- (prevMsg.role !== "tool_call" && prevMsg.role !== "tool_result")) {
42
- // Insert synthetic tool_call before this result
43
- result.push({
44
- id: `repair-call-${randomUUID()}`,
45
- role: "tool_call",
46
- content: `[Tool call for ${msg.tool || "unknown"} - conversation was compacted]`,
47
- tool: msg.tool,
48
- timestamp: msg.timestamp,
49
- metadata: { truncated: true },
50
- });
51
- orphanedResultsFixed++;
99
+ for (const call of calls) {
100
+ const key = call.toolCallId;
101
+ const match = resultById.get(key);
102
+ if (match) {
103
+ outResults.push(match);
104
+ resultById.delete(key);
105
+ }
106
+ else {
107
+ outResults.push(syntheticResult(call));
108
+ orphanedCallsFixed++;
52
109
  }
53
- result.push(msg);
54
110
  }
55
- else {
111
+ // Results with no surviving call — the compactor cut the head of the batch.
112
+ for (const leftover of resultById.values()) {
113
+ outCalls.push(syntheticCall(leftover));
114
+ outResults.push(leftover);
115
+ orphanedResultsFixed++;
116
+ }
117
+ }
118
+ else {
119
+ // Legacy positional pairing, scoped to the batch.
120
+ const paired = Math.min(calls.length, results.length);
121
+ for (let i = 0; i < paired; i++) {
122
+ outResults.push(results[i]);
123
+ }
124
+ for (let i = paired; i < calls.length; i++) {
125
+ outResults.push(syntheticResult(calls[i]));
126
+ orphanedCallsFixed++;
127
+ }
128
+ for (let i = paired; i < results.length; i++) {
129
+ outCalls.push(syntheticCall(results[i]));
130
+ outResults.push(results[i]);
131
+ orphanedResultsFixed++;
132
+ }
133
+ }
134
+ return {
135
+ messages: [...outCalls, ...outResults],
136
+ orphanedCallsFixed,
137
+ orphanedResultsFixed,
138
+ changed,
139
+ };
140
+ }
141
+ /** True for the two roles that make up a tool batch. */
142
+ function isToolRole(msg) {
143
+ return msg?.role === "tool_call" || msg?.role === "tool_result";
144
+ }
145
+ /**
146
+ * True when a split at `index` would cut a single batch in half.
147
+ *
148
+ * A batch is calls-then-results, so a `tool_result` FOLLOWED BY a `tool_call`
149
+ * is the boundary BETWEEN two batches — a legal place to split. Treating every
150
+ * adjacent pair of tool messages as "inside a batch" would fuse a whole
151
+ * `call,result,call,result,…` history into one indivisible run, and the walks
152
+ * below would then skip past all of it.
153
+ */
154
+ function cutsBatch(messages, index) {
155
+ const before = messages[index - 1];
156
+ const after = messages[index];
157
+ if (!isToolRole(before) || !isToolRole(after)) {
158
+ return false;
159
+ }
160
+ return !(before?.role === "tool_result" && after?.role === "tool_call");
161
+ }
162
+ /**
163
+ * Move a summarize/keep split so it never falls INSIDE a tool batch.
164
+ *
165
+ * `splitIndex` means "messages[0..splitIndex) get summarized" — so the summary
166
+ * pointer lands on messages[splitIndex - 1]. Landing mid-batch leaves the
167
+ * recent window starting on an orphaned `tool_result`, which providers reject.
168
+ *
169
+ * Preferred direction is BACKWARD (summarize less, keep the whole batch in the
170
+ * recent window) since that never loses detail. When the batch starts at index
171
+ * 0 there is nothing left to summarize, so the split moves forward past the
172
+ * batch instead — the caller's "at least one message summarized" invariant
173
+ * wins over keeping the batch recent.
174
+ */
175
+ export function snapSplitToBatchBoundary(messages, splitIndex) {
176
+ if (splitIndex <= 0 || splitIndex >= messages.length) {
177
+ return splitIndex;
178
+ }
179
+ if (!cutsBatch(messages, splitIndex)) {
180
+ return splitIndex;
181
+ }
182
+ let start = splitIndex;
183
+ while (start > 0 && cutsBatch(messages, start)) {
184
+ start--;
185
+ }
186
+ if (start > 0) {
187
+ return start;
188
+ }
189
+ let end = splitIndex;
190
+ while (end < messages.length && cutsBatch(messages, end)) {
191
+ end++;
192
+ }
193
+ return end;
194
+ }
195
+ /**
196
+ * Repair orphaned tool_call/tool_result pairs in a message array.
197
+ *
198
+ * Guarantees on return: every `tool_call` is followed (within its batch) by
199
+ * exactly one `tool_result`, and no `tool_result` precedes its `tool_call`.
200
+ * A healthy batch — including a parallel one — is returned untouched.
201
+ */
202
+ export function repairToolPairs(messages) {
203
+ // Fast path: nothing tool-shaped to repair. Keeps the read-path cost at one
204
+ // linear scan for the overwhelmingly common text-only conversation.
205
+ const hasToolMessage = messages.some((msg) => msg.role === "tool_call" || msg.role === "tool_result");
206
+ if (!hasToolMessage) {
207
+ return {
208
+ repaired: false,
209
+ messages,
210
+ orphanedCallsFixed: 0,
211
+ orphanedResultsFixed: 0,
212
+ };
213
+ }
214
+ const result = [];
215
+ let orphanedCallsFixed = 0;
216
+ let orphanedResultsFixed = 0;
217
+ let changed = false;
218
+ let i = 0;
219
+ while (i < messages.length) {
220
+ const msg = messages[i];
221
+ if (msg.role !== "tool_call" && msg.role !== "tool_result") {
56
222
  result.push(msg);
223
+ i++;
224
+ continue;
57
225
  }
226
+ const batch = collectBatch(messages, i);
227
+ const repaired = repairBatch(batch);
228
+ result.push(...repaired.messages);
229
+ orphanedCallsFixed += repaired.orphanedCallsFixed;
230
+ orphanedResultsFixed += repaired.orphanedResultsFixed;
231
+ changed = changed || repaired.changed;
232
+ i = batch.endIndex;
58
233
  }
59
- const repaired = orphanedCallsFixed > 0 || orphanedResultsFixed > 0;
234
+ const repaired = orphanedCallsFixed > 0 || orphanedResultsFixed > 0 || changed;
60
235
  return {
61
236
  repaired,
62
237
  messages: repaired ? result : messages,
@@ -26,6 +26,7 @@ import { DEFAULT_MAX_STEPS, DEFAULT_WRAPUP_TIME_LEAD_MS, } from "../constants.js
26
26
  import { createStepBudgetGuard, estimateFixedOverheadTokens, } from "../../context/stepBudgetGuard.js";
27
27
  import { isTemperatureDeprecatedError, isSchemaComplexityError, isToolsSchemaConflictError, isToolsSchemaExclusionInForce, } from "./structuredOutputPolicy.js";
28
28
  import { coerceJsonToSchema } from "../../utils/json/coerce.js";
29
+ import { convertZodToJsonSchema } from "../../utils/schemaConversion.js";
29
30
  import { NoObjectGeneratedError } from "../../utils/generationErrors.js";
30
31
  import { Output, stepCountIs } from "../../utils/tool.js";
31
32
  import { generateText } from "../../utils/generation.js";
@@ -105,11 +106,14 @@ export function resolveTurnBudget(options, turnStartMs) {
105
106
  * `providerOptions:` spreads in the args literal would silently clobber each
106
107
  * other (object spread does not deep-merge).
107
108
  */
108
- function buildProviderOptions(options, isGoogleProvider, callerTimeoutMs) {
109
+ function buildProviderOptions(options, isGoogleProvider, callerTimeoutMs, finalResultSchema) {
109
110
  const providerOptions = {};
110
111
  if (callerTimeoutMs !== undefined) {
111
112
  providerOptions.neurolink = { timeoutMs: callerTimeoutMs };
112
113
  }
114
+ if (finalResultSchema) {
115
+ providerOptions.anthropic = { finalResultSchema };
116
+ }
113
117
  if (options.thinkingConfig?.enabled && isGoogleProvider) {
114
118
  // Gemini 3 uses thinkingLevel; Gemini 2.5 uses thinkingBudget.
115
119
  providerOptions.google = {
@@ -236,7 +240,22 @@ export class GenerationHandler {
236
240
  const prepareStep = options.prepareStep;
237
241
  const { callerTimeoutMs, turnBudgetMs, wrapupLeadMs, turnDeadline } = resolveTurnBudget(options, turnStartMs);
238
242
  let wrapupForced = false;
239
- const providerOptions = buildProviderOptions(options, isGoogleProvider, callerTimeoutMs);
243
+ // The native Anthropic Messages surface cannot combine AI-SDK structured
244
+ // output with tools (see structuredOutputPolicy — experimental_output
245
+ // replaces the tools array), so `useStructuredOutput` is false above and
246
+ // the schema would simply be dropped for every agent/MCP turn. Hand the
247
+ // JSON Schema to the provider instead: it appends an additive
248
+ // `final_result` tool and returns the answer as that tool's arguments,
249
+ // keeping the real tools callable. Bedrock is deliberately excluded — it
250
+ // runs on the third-party @ai-sdk/amazon-bedrock model, which has no such
251
+ // handling.
252
+ const finalResultSchema = this.providerName === "anthropic" &&
253
+ !!options.schema &&
254
+ shouldUseTools &&
255
+ Object.keys(tools).length > 0
256
+ ? convertZodToJsonSchema(options.schema)
257
+ : undefined;
258
+ const providerOptions = buildProviderOptions(options, isGoogleProvider, callerTimeoutMs, finalResultSchema);
240
259
  // Hoist system-role messages into generateText's top-level `system` option
241
260
  // rather than passing them inside `messages` (deprecated by the AI SDK,
242
261
  // rejected in v7). See extractSystemMessages for the rationale. (#1024)
@@ -23,6 +23,14 @@ export declare function isGeminiProvider(providerName: string, modelName: string
23
23
  * experimental_output + tools silently drops tool_use blocks on this surface, so
24
24
  * structured output must be disabled when tools are active. Vertex+Claude is NOT
25
25
  * matched here (different transport, no conflict).
26
+ *
27
+ * Being excluded here no longer means the schema is LOST for provider
28
+ * "anthropic": GenerationHandler forwards the JSON Schema to the provider via
29
+ * `providerOptions.anthropic.finalResultSchema`, and the provider appends an
30
+ * additive `final_result` tool (see providers/anthropic/structuredOutput.ts) —
31
+ * schema enforcement without giving up tool calling. "bedrock" has no such
32
+ * handling (it runs on the third-party @ai-sdk/amazon-bedrock model) and still
33
+ * falls back to text-mode coercion.
26
34
  */
27
35
  export declare function isNativeAnthropicProvider(providerName: string): boolean;
28
36
  /**
@@ -33,6 +33,14 @@ export function isGeminiProvider(providerName, modelName) {
33
33
  * experimental_output + tools silently drops tool_use blocks on this surface, so
34
34
  * structured output must be disabled when tools are active. Vertex+Claude is NOT
35
35
  * matched here (different transport, no conflict).
36
+ *
37
+ * Being excluded here no longer means the schema is LOST for provider
38
+ * "anthropic": GenerationHandler forwards the JSON Schema to the provider via
39
+ * `providerOptions.anthropic.finalResultSchema`, and the provider appends an
40
+ * additive `final_result` tool (see providers/anthropic/structuredOutput.ts) —
41
+ * schema enforcement without giving up tool calling. "bedrock" has no such
42
+ * handling (it runs on the third-party @ai-sdk/amazon-bedrock model) and still
43
+ * falls back to text-mode coercion.
36
44
  */
37
45
  export function isNativeAnthropicProvider(providerName) {
38
46
  return providerName === "anthropic" || providerName === "bedrock";
@@ -1406,6 +1406,10 @@ User message: "${userMessage}"`;
1406
1406
  role: "tool_call",
1407
1407
  content: "", // Can be empty for tool calls
1408
1408
  tool: toolName,
1409
+ // Persisted so repairToolPairs can pair by ID rather than adjacency —
1410
+ // a parallel batch writes all calls before any result, so position
1411
+ // carries no pairing information.
1412
+ ...(toolCallId ? { toolCallId } : {}),
1409
1413
  args: (toolCall.args ||
1410
1414
  toolCall.arguments ||
1411
1415
  toolCall.parameters ||
@@ -1493,6 +1497,10 @@ User message: "${userMessage}"`;
1493
1497
  role: "tool_result",
1494
1498
  content: serializedResult, // Full output (was "")
1495
1499
  tool: toolName,
1500
+ // Only a REAL id is persisted: the "unknown" sentinel above would
1501
+ // otherwise collide across every unidentifiable result and pair them
1502
+ // to each other. Absent id falls back to legacy positional pairing.
1503
+ ...(toolCallId && toolCallId !== "unknown" ? { toolCallId } : {}),
1496
1504
  result,
1497
1505
  metadata,
1498
1506
  };
@@ -30,6 +30,7 @@ import { toAnthropicImageBlock, fileToAnthropicBlock, } from "../anthropicImageB
30
30
  import { resolveSamplingParams } from "../../models/modelRegistry.js";
31
31
  import { createChunkQueue, createDeferredAnalytics, stringifyToolInput, } from "../openaiChatCompletionsClient.js";
32
32
  import { ANTHROPIC_BETA_HEADERS } from "./constants.js";
33
+ import { appendFinalResultInstruction, appendFinalResultTool, FINAL_RESULT_TOOL_NAME, stringifyFinalResultInput, } from "./structuredOutput.js";
33
34
  // AnthropicProviderConfig is imported from types/providers.ts
34
35
  // Re-export for backward compatibility
35
36
  // Configuration helpers - now using consolidated utility
@@ -1063,7 +1064,11 @@ export class AnthropicProvider extends BaseProvider {
1063
1064
  supportedUrls: {},
1064
1065
  doGenerate: async (options) => {
1065
1066
  await refreshAuth();
1066
- const { system, messages } = messagesToAnthropic(options.prompt);
1067
+ const built = messagesToAnthropic(options.prompt);
1068
+ const messages = built.messages;
1069
+ // `let`: the additive structured-output path below appends the
1070
+ // final_result instruction to the system prompt.
1071
+ let system = built.system;
1067
1072
  let tools = (options.tools ?? [])
1068
1073
  .filter((t) => t.type === "function")
1069
1074
  .map((t) => {
@@ -1107,6 +1112,24 @@ export class AnthropicProvider extends BaseProvider {
1107
1112
  ];
1108
1113
  toolChoice = { type: "tool", name: jsonTool };
1109
1114
  }
1115
+ // Additive structured output: when the caller wants a schema AND real
1116
+ // tools, the forced-json path above cannot be used (it replaces the
1117
+ // tools array), and the AI-SDK experimental_output path is excluded
1118
+ // for this surface by structuredOutputPolicy. GenerationHandler hands
1119
+ // the JSON Schema down here instead, and we APPEND a `final_result`
1120
+ // tool — tool_choice stays auto, so every real tool keeps working and
1121
+ // the model self-selects final_result when it is ready to answer.
1122
+ const finalResultSchema = options.providerOptions?.anthropic
1123
+ ?.finalResultSchema;
1124
+ let finalResultActive = false;
1125
+ if (!jsonTool && finalResultSchema) {
1126
+ const appended = appendFinalResultTool(tools, finalResultSchema);
1127
+ tools = appended.tools;
1128
+ finalResultActive = appended.applied;
1129
+ if (appended.applied) {
1130
+ system = appendFinalResultInstruction(system);
1131
+ }
1132
+ }
1110
1133
  // Extended thinking passthrough (providerOptions.anthropic.thinking).
1111
1134
  const thinking = options.providerOptions?.anthropic?.thinking;
1112
1135
  // Prompt-cache parity with the native Vertex+Claude path: upstream
@@ -1179,6 +1202,7 @@ export class AnthropicProvider extends BaseProvider {
1179
1202
  timeoutController?.cleanup();
1180
1203
  }
1181
1204
  const content = [];
1205
+ let finalResultText;
1182
1206
  for (const block of response.content) {
1183
1207
  if (block.type === "thinking") {
1184
1208
  content.push({ type: "reasoning", text: block.thinking });
@@ -1198,6 +1222,12 @@ export class AnthropicProvider extends BaseProvider {
1198
1222
  text: stringifyToolInput(block.input),
1199
1223
  });
1200
1224
  }
1225
+ else if (finalResultActive &&
1226
+ block.name === FINAL_RESULT_TOOL_NAME) {
1227
+ // Internal pattern: never surfaced as a tool call. Its arguments
1228
+ // ARE the structured answer.
1229
+ finalResultText = stringifyToolInput(block.input);
1230
+ }
1201
1231
  else {
1202
1232
  content.push({
1203
1233
  type: "tool-call",
@@ -1208,12 +1238,29 @@ export class AnthropicProvider extends BaseProvider {
1208
1238
  }
1209
1239
  }
1210
1240
  }
1241
+ // final_result is terminal — parity with the native Claude-on-Vertex
1242
+ // and Gemini loops, which break out of the tool loop the moment it
1243
+ // arrives. Reasoning blocks are kept; any prose preamble and any tool
1244
+ // calls issued alongside it are dropped so `text` is exactly the
1245
+ // structured payload and the AI-SDK loop stops here.
1246
+ if (finalResultText !== undefined) {
1247
+ const reasoning = content.filter((part) => part.type === "reasoning");
1248
+ content.length = 0;
1249
+ content.push(...reasoning, { type: "text", text: finalResultText });
1250
+ logger.debug("[Anthropic] Extracted structured output from final_result tool (generate)", { chars: finalResultText.length });
1251
+ }
1211
1252
  const cacheRead = response.usage.cache_read_input_tokens ?? 0;
1212
1253
  const cacheWrite = response.usage.cache_creation_input_tokens ?? 0;
1213
1254
  return {
1214
1255
  content,
1215
1256
  finishReason: {
1216
- unified: mapAnthropicStopReason(response.stop_reason),
1257
+ // A final_result call ends the turn: the provider reports
1258
+ // stop_reason "tool_use", but no tool call is surfaced, so
1259
+ // reporting "tool-calls" would misread as a step-capped turn.
1260
+ // `raw` still carries the provider's verbatim stop_reason.
1261
+ unified: finalResultText !== undefined
1262
+ ? "stop"
1263
+ : mapAnthropicStopReason(response.stop_reason),
1217
1264
  raw: response.stop_reason ?? "stop",
1218
1265
  },
1219
1266
  usage: {
@@ -1341,6 +1388,9 @@ export class AnthropicProvider extends BaseProvider {
1341
1388
  let anthropicTools;
1342
1389
  let payload;
1343
1390
  let shouldUseTools;
1391
+ // True once the additive `final_result` tool is in the request — the
1392
+ // streaming twin of the doGenerate path above.
1393
+ let finalResultActive = false;
1344
1394
  try {
1345
1395
  // options.tools is pre-merged by BaseProvider.stream() with base tools
1346
1396
  // (MCP/built-in) + user-provided tools (RAG, etc.)
@@ -1355,6 +1405,18 @@ export class AnthropicProvider extends BaseProvider {
1355
1405
  // convert to the Anthropic Messages payload (system + content blocks).
1356
1406
  const built = await this.buildMessagesForStream(options);
1357
1407
  payload = messagesToAnthropic(built);
1408
+ // Schema + tools: append final_result rather than pinning tool_choice to
1409
+ // a json tool, so the real tools stay callable for the whole turn.
1410
+ // Unlike generate, no plumbing is needed — this is a native loop, so the
1411
+ // caller's Zod/JSON schema is right here on the options.
1412
+ if (options.schema && anthropicTools && anthropicTools.length > 0) {
1413
+ const appended = appendFinalResultTool(anthropicTools, convertZodToJsonSchema(options.schema));
1414
+ anthropicTools = appended.tools;
1415
+ finalResultActive = appended.applied;
1416
+ if (appended.applied) {
1417
+ payload.system = appendFinalResultInstruction(payload.system);
1418
+ }
1419
+ }
1358
1420
  }
1359
1421
  catch (setupErr) {
1360
1422
  timeoutController?.cleanup();
@@ -1439,6 +1501,14 @@ export class AnthropicProvider extends BaseProvider {
1439
1501
  ...(totalCacheRead > 0 ? { cacheReadTokens: totalCacheRead } : {}),
1440
1502
  ...(totalCacheWrite > 0 ? { cacheCreationTokens: totalCacheWrite } : {}),
1441
1503
  });
1504
+ // Structured-output turns are delivered as ONE chunk, not incrementally:
1505
+ // a caller that passed a schema needs parseable JSON, and text deltas
1506
+ // emitted before the model calls final_result would prefix the payload
1507
+ // with prose and break every JSON.parse on the consumer side. Same
1508
+ // contract as the native Vertex loops. Non-schema streams are untouched
1509
+ // and stay fully incremental.
1510
+ let bufferedText = "";
1511
+ let finalResultText;
1442
1512
  const runLoop = async () => {
1443
1513
  const conversation = payload.messages.slice();
1444
1514
  for (let step = 0; step < maxSteps; step++) {
@@ -1532,7 +1602,12 @@ export class AnthropicProvider extends BaseProvider {
1532
1602
  const delta = event.delta;
1533
1603
  if (delta.type === "text_delta") {
1534
1604
  textAcc.set(event.index, (textAcc.get(event.index) ?? "") + delta.text);
1535
- pushChunk({ content: delta.text });
1605
+ if (finalResultActive) {
1606
+ bufferedText += delta.text;
1607
+ }
1608
+ else {
1609
+ pushChunk({ content: delta.text });
1610
+ }
1536
1611
  }
1537
1612
  else if (delta.type === "thinking_delta") {
1538
1613
  const acc = thinkingAcc.get(event.index) ?? {
@@ -1568,6 +1643,20 @@ export class AnthropicProvider extends BaseProvider {
1568
1643
  }
1569
1644
  }
1570
1645
  lastStop = stopReason;
1646
+ // final_result is terminal: its arguments ARE the answer, so the turn
1647
+ // ends here and any tool calls issued alongside it are not executed
1648
+ // (parity with the native Vertex loops). It is never executed as a
1649
+ // tool, never recorded in toolsUsed, and never stored as a tool
1650
+ // execution — the pattern stays invisible to callers.
1651
+ if (finalResultActive) {
1652
+ const finalCall = [...toolAcc.values()].find((acc) => acc.name === FINAL_RESULT_TOOL_NAME);
1653
+ if (finalCall) {
1654
+ finalResultText = stringifyFinalResultInput(finalCall.inputJson);
1655
+ lastStop = "end_turn";
1656
+ logger.debug("[Anthropic] Extracted structured output from final_result tool (stream)", { chars: finalResultText.length });
1657
+ break;
1658
+ }
1659
+ }
1571
1660
  if (stopReason !== "tool_use" || toolAcc.size === 0) {
1572
1661
  break;
1573
1662
  }
@@ -1710,6 +1799,19 @@ export class AnthropicProvider extends BaseProvider {
1710
1799
  throw this.formatProviderError(error);
1711
1800
  })
1712
1801
  .finally(() => {
1802
+ // Deliver the buffered structured-output turn: `finalResultText` when
1803
+ // the model called final_result, otherwise the prose it produced
1804
+ // instead — never nothing, so a model that ignores the instruction
1805
+ // degrades to today's plain-text behaviour rather than an empty
1806
+ // stream. In `finally` so a turn that dies mid-loop still surfaces
1807
+ // the text it had already buffered, exactly as the unbuffered path
1808
+ // surfaces its partial deltas.
1809
+ if (finalResultActive) {
1810
+ const output = finalResultText ?? bufferedText;
1811
+ if (output.length > 0) {
1812
+ pushChunk({ content: output });
1813
+ }
1814
+ }
1713
1815
  timeoutController?.cleanup();
1714
1816
  pushChunk({ done: true });
1715
1817
  });
@@ -0,0 +1,58 @@
1
+ import type Anthropic from "@anthropic-ai/sdk";
2
+ /**
3
+ * Additive structured output for the native Anthropic Messages API.
4
+ *
5
+ * Anthropic has no `response_format`, so a schema has to be expressed as a
6
+ * tool. The provider's pre-existing `responseFormat` path does that by
7
+ * REPLACING the tools array with a single json tool and pinning `tool_choice`
8
+ * to it — correct for a schema-only call, but mutually exclusive with real
9
+ * tools, so agent/MCP turns that pass both silently lost the schema.
10
+ *
11
+ * The additive pattern here APPENDS a `final_result` tool to the caller's
12
+ * tools and leaves `tool_choice` on auto: the model keeps calling real tools
13
+ * for as long as it needs, then emits its answer as `final_result` arguments
14
+ * that already conform to the schema. This mirrors the native
15
+ * Claude-on-Vertex loop in `googleVertex/client.ts`, which has used the same
16
+ * tool name, description, and instruction wording since it shipped.
17
+ */
18
+ /** Internal tool name — filtered out of every returned tool call / execution. */
19
+ export declare const FINAL_RESULT_TOOL_NAME = "final_result";
20
+ /** Appended to the system prompt whenever the final_result tool is in play. */
21
+ export declare const FINAL_RESULT_INSTRUCTION = "\n\nIMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.";
22
+ /**
23
+ * Build the `final_result` tool definition from a JSON Schema.
24
+ *
25
+ * `$ref`s are inlined and `$schema` dropped — Anthropic's `input_schema` must
26
+ * be a self-contained object schema. Schemas that are not object-rooted (a
27
+ * bare array/string schema) are wrapped so `input_schema.type` is always
28
+ * "object", which the Messages API requires.
29
+ */
30
+ export declare function buildFinalResultTool(jsonSchema: Record<string, unknown>): Anthropic.Messages.Tool;
31
+ /**
32
+ * Append `final_result` to an Anthropic tool list.
33
+ *
34
+ * Returns a NEW array so the caller's tool list is never mutated, and reports
35
+ * `applied: false` (with the list unchanged) when the pattern must not run:
36
+ * there are no real tools to preserve, or the caller already exposes a tool of
37
+ * that name — shadowing a caller's tool would break their turn.
38
+ */
39
+ export declare function appendFinalResultTool(tools: Anthropic.Messages.Tool[] | undefined, jsonSchema: Record<string, unknown>): {
40
+ tools: Anthropic.Messages.Tool[] | undefined;
41
+ applied: boolean;
42
+ };
43
+ /**
44
+ * Append the final_result instruction to an Anthropic `system` value.
45
+ *
46
+ * The block-array form gets a NEW trailing block rather than an edit to the
47
+ * existing one: rewriting a block that carries a `cache_control` marker would
48
+ * change the cached prefix and invalidate the prompt cache on every turn.
49
+ */
50
+ export declare function appendFinalResultInstruction(system: string | Anthropic.Messages.TextBlockParam[] | undefined): string | Anthropic.Messages.TextBlockParam[];
51
+ /**
52
+ * Canonical JSON text for a `final_result` payload.
53
+ *
54
+ * Accepts the raw accumulated `input_json` from a stream so a payload
55
+ * truncated by the token cap is still returned verbatim — the caller's
56
+ * coercion layer can repair it, whereas dropping it loses the whole answer.
57
+ */
58
+ export declare function stringifyFinalResultInput(inputJson: string): string;