markform 0.1.18 → 0.1.20

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 (32) hide show
  1. package/README.md +27 -2
  2. package/dist/ai-sdk.d.mts +1 -2
  3. package/dist/ai-sdk.mjs +2 -2
  4. package/dist/ai-sdk.mjs.map +1 -1
  5. package/dist/{apply-BYgtU64w.mjs → apply-DIvm1b1s.mjs} +430 -31
  6. package/dist/apply-DIvm1b1s.mjs.map +1 -0
  7. package/dist/bin.mjs +20 -2
  8. package/dist/bin.mjs.map +1 -1
  9. package/dist/{cli-D9w0Bp4J.mjs → cli-FFMoEhFS.mjs} +1039 -89
  10. package/dist/cli-FFMoEhFS.mjs.map +1 -0
  11. package/dist/cli.mjs +1 -1
  12. package/dist/{coreTypes-SDB3KRRJ.mjs → coreTypes-CPKXf2dc.mjs} +1 -1
  13. package/dist/{coreTypes-SDB3KRRJ.mjs.map → coreTypes-CPKXf2dc.mjs.map} +1 -1
  14. package/dist/{coreTypes-BMEs8h_2.d.mts → coreTypes-CkxML8g2.d.mts} +4 -9
  15. package/dist/index.d.mts +515 -22
  16. package/dist/index.mjs +5 -5
  17. package/dist/{session-Ci4B0Pna.mjs → session-CK0x28RO.mjs} +2 -2
  18. package/dist/session-CK0x28RO.mjs.map +1 -0
  19. package/dist/{session-CW9AQw6i.mjs → session-ZHBi3LVQ.mjs} +1 -1
  20. package/dist/{shared-fUKfJ1UA.mjs → shared-BTR35aMz.mjs} +1 -1
  21. package/dist/{shared-CCq4haEV.mjs → shared-DwdyWmvE.mjs} +1 -3
  22. package/dist/shared-DwdyWmvE.mjs.map +1 -0
  23. package/dist/{src-DDxi-2ne.mjs → src-wR7GoftB.mjs} +1707 -645
  24. package/dist/src-wR7GoftB.mjs.map +1 -0
  25. package/docs/markform-apis.md +81 -0
  26. package/docs/markform-reference.md +15 -1
  27. package/package.json +17 -15
  28. package/dist/apply-BYgtU64w.mjs.map +0 -1
  29. package/dist/cli-D9w0Bp4J.mjs.map +0 -1
  30. package/dist/session-Ci4B0Pna.mjs.map +0 -1
  31. package/dist/shared-CCq4haEV.mjs.map +0 -1
  32. package/dist/src-DDxi-2ne.mjs.map +0 -1
@@ -1,10 +1,11 @@
1
1
 
2
- import { L as PatchSchema, V as RunModeSchema } from "./coreTypes-SDB3KRRJ.mjs";
3
- import { A as DEFAULT_ROLE_INSTRUCTIONS, C as DEFAULT_MAX_STEPS_PER_TURN, D as DEFAULT_RESEARCH_MAX_ISSUES_PER_TURN, E as DEFAULT_PRIORITY, H as getWebSearchConfig, K as MarkformConfigError, O as DEFAULT_RESEARCH_MAX_PATCHES_PER_TURN, S as DEFAULT_MAX_PATCHES_PER_TURN, Y as MarkformParseError, b as DEFAULT_MAX_ISSUES_PER_TURN, d as serializeForm, g as preprocessCommentSyntax, h as detectSyntaxStyle, i as inspect, k as DEFAULT_ROLES, r as getFieldsForRoles, t as applyPatches, v as AGENT_ROLE, w as DEFAULT_MAX_TURNS, x as DEFAULT_MAX_PARALLEL_AGENTS } from "./apply-BYgtU64w.mjs";
2
+ import { L as PatchSchema, R as ProgressCountsSchema, V as RunModeSchema, pt as StructureSummarySchema } from "./coreTypes-CPKXf2dc.mjs";
3
+ import { A as parseOptionText, B as DEFAULT_RESEARCH_MAX_ISSUES_PER_TURN, C as extractTableContent, D as getStringAttr, E as getStringArrayAttr, F as DEFAULT_MAX_PATCHES_PER_TURN, H as DEFAULT_ROLES, I as DEFAULT_MAX_STEPS_PER_TURN, L as DEFAULT_MAX_TURNS, N as DEFAULT_MAX_ISSUES_PER_TURN, O as getValidateAttr, P as DEFAULT_MAX_PARALLEL_AGENTS, S as extractOptionItems, T as getNumberAttr, U as DEFAULT_ROLE_INSTRUCTIONS, V as DEFAULT_RESEARCH_MAX_PATCHES_PER_TURN, _ as preprocessCommentSyntax, b as CHECKBOX_MARKERS, c as computeProgressSummary, d as serializeForm, g as detectSyntaxStyle, i as inspect, j as AGENT_ROLE, k as isTagNode, l as computeStructureSummary, lt as MarkformParseError, nt as getWebSearchConfig, ot as MarkformConfigError, r as getFieldsForRoles, t as applyPatches, w as getBooleanAttr, x as extractFenceValue, y as tryParseSentinelResponse, z as DEFAULT_PRIORITY } from "./apply-DIvm1b1s.mjs";
4
4
  import { z } from "zod";
5
5
  import Markdoc from "@markdoc/markdoc";
6
6
  import YAML from "yaml";
7
7
  import { sha256 } from "js-sha256";
8
+ import { ulid } from "ulid";
8
9
  import { generateText, stepCountIs, zodSchema } from "ai";
9
10
  import { openai } from "@ai-sdk/openai";
10
11
  import * as z4 from "zod/v4";
@@ -33,271 +34,23 @@ const FIELD_KINDS = [
33
34
  "table"
34
35
  ];
35
36
 
36
- //#endregion
37
- //#region src/engine/parseHelpers.ts
38
- /** Map checkbox marker to state value */
39
- const CHECKBOX_MARKERS = {
40
- "[ ]": "todo",
41
- "[x]": "done",
42
- "[X]": "done",
43
- "[/]": "incomplete",
44
- "[*]": "active",
45
- "[-]": "na",
46
- "[y]": "yes",
47
- "[Y]": "yes",
48
- "[n]": "no",
49
- "[N]": "no"
50
- };
51
- const OPTION_TEXT_PATTERN = /^(\[[^\]]\])\s*(.*?)\s*$/;
52
- /**
53
- * Parse option text to extract marker and label.
54
- * Text is like "[ ] Label" or "[x] Label".
55
- */
56
- function parseOptionText(text) {
57
- const match = OPTION_TEXT_PATTERN.exec(text);
58
- if (!match) return null;
59
- return {
60
- marker: match[1] ?? "",
61
- label: (match[2] ?? "").trim()
62
- };
63
- }
64
- /**
65
- * Check if a node is a tag node with specific name.
66
- * Works with raw AST nodes (not transformed Tags).
67
- */
68
- function isTagNode(node, name$2) {
69
- if (typeof node !== "object" || node === null) return false;
70
- if (node.type === "tag" && node.tag) return name$2 === void 0 || node.tag === name$2;
71
- return false;
72
- }
73
- /**
74
- * Get string attribute value or undefined.
75
- */
76
- function getStringAttr(node, name$2) {
77
- const value = node.attributes?.[name$2];
78
- return typeof value === "string" ? value : void 0;
79
- }
80
- /**
81
- * Get number attribute value or undefined.
82
- */
83
- function getNumberAttr(node, name$2) {
84
- const value = node.attributes?.[name$2];
85
- return typeof value === "number" ? value : void 0;
86
- }
87
- /**
88
- * Get boolean attribute value or undefined.
89
- */
90
- function getBooleanAttr(node, name$2) {
91
- const value = node.attributes?.[name$2];
92
- return typeof value === "boolean" ? value : void 0;
93
- }
94
- /**
95
- * Get validator references from validate attribute.
96
- * Handles both single string and array formats.
97
- */
98
- function getValidateAttr(node) {
99
- const value = node.attributes?.validate;
100
- if (value === void 0 || value === null) return;
101
- if (Array.isArray(value)) return value;
102
- if (typeof value === "string") return [value];
103
- if (typeof value === "object") return [value];
104
- }
105
- /**
106
- * Get string array attribute value or undefined.
107
- * Handles both single string (converts to array) and array formats.
108
- */
109
- function getStringArrayAttr(node, name$2) {
110
- const value = node.attributes?.[name$2];
111
- if (value === void 0 || value === null) return;
112
- if (Array.isArray(value)) {
113
- const strings = value.filter((v) => typeof v === "string");
114
- return strings.length > 0 ? strings : void 0;
115
- }
116
- if (typeof value === "string") return [value];
117
- }
118
- /**
119
- * Extract option items from node children (for option lists).
120
- * Works with raw AST nodes. Collects text and ID from list items.
121
- */
122
- function extractOptionItems(node) {
123
- const items = [];
124
- /**
125
- * Collect all text content from a node tree into a single string.
126
- */
127
- function collectText(n) {
128
- let text = "";
129
- if (n.type === "text" && typeof n.attributes?.content === "string") text += n.attributes.content;
130
- if (n.type === "softbreak") text += "\n";
131
- if (n.children && Array.isArray(n.children)) for (const c of n.children) text += collectText(c);
132
- return text;
133
- }
134
- /**
135
- * Traverse to find list items and extract their content.
136
- */
137
- function traverse(child) {
138
- if (!child || typeof child !== "object") return;
139
- if (child.type === "item") {
140
- const text = collectText(child);
141
- let id = null;
142
- if (typeof child.attributes?.id === "string") id = child.attributes.id;
143
- else if (child.children && Array.isArray(child.children) && child.children.length > 0 && typeof child.children[0]?.attributes?.id === "string") id = child.children[0].attributes.id;
144
- if (text.trim()) items.push({
145
- id,
146
- text: text.trim()
147
- });
148
- return;
149
- }
150
- if (child.children && Array.isArray(child.children)) for (const c of child.children) traverse(c);
151
- }
152
- if (node.children && Array.isArray(node.children)) for (const child of node.children) traverse(child);
153
- return items;
154
- }
155
- /**
156
- * Extract fence value from node children.
157
- * Looks for ```value code blocks.
158
- */
159
- function extractFenceValue(node) {
160
- function traverse(child) {
161
- if (!child || typeof child !== "object") return null;
162
- if (child.type === "fence") {
163
- if (child.attributes?.language === "value") return typeof child.attributes?.content === "string" ? child.attributes.content : null;
164
- }
165
- if (child.children && Array.isArray(child.children)) for (const c of child.children) {
166
- const result = traverse(c);
167
- if (result !== null) return result;
168
- }
169
- return null;
170
- }
171
- if (node.children && Array.isArray(node.children)) for (const child of node.children) {
172
- const result = traverse(child);
173
- if (result !== null) return result;
174
- }
175
- return null;
176
- }
177
- /**
178
- * Extract table content from node children.
179
- * Handles both raw text and Markdoc-parsed table nodes.
180
- * Reconstructs markdown table format from the AST.
181
- */
182
- function extractTableContent(node) {
183
- const lines = [];
184
- function extractTextFromNode(n) {
185
- if (!n || typeof n !== "object") return "";
186
- if (n.type === "text" && typeof n.attributes?.content === "string") return n.attributes.content;
187
- if (n.children && Array.isArray(n.children)) return n.children.map(extractTextFromNode).join("");
188
- return "";
189
- }
190
- function extractTableRow(trNode) {
191
- if (!trNode.children || !Array.isArray(trNode.children)) return "";
192
- return `| ${trNode.children.filter((c) => c.type === "th" || c.type === "td").map((c) => extractTextFromNode(c).trim()).join(" | ")} |`;
193
- }
194
- function processNode(child) {
195
- if (!child || typeof child !== "object") return;
196
- if (child.type === "paragraph" || child.type === "inline") {
197
- const text = extractTextFromNode(child).trim();
198
- if (text) lines.push(text);
199
- return;
200
- }
201
- if (child.type === "text" && typeof child.attributes?.content === "string") {
202
- const text = child.attributes.content.trim();
203
- if (text) lines.push(text);
204
- return;
205
- }
206
- if (child.type === "table") {
207
- const thead = child.children?.find((c) => c.type === "thead");
208
- if (thead?.children) for (const tr of thead.children.filter((c) => c.type === "tr")) lines.push(extractTableRow(tr));
209
- if (thead?.children?.length) {
210
- const firstTr = thead.children.find((c) => c.type === "tr");
211
- if (firstTr?.children) {
212
- const colCount = firstTr.children.filter((c) => c.type === "th" || c.type === "td").length;
213
- const separatorCells = Array(colCount).fill("----");
214
- lines.push(`| ${separatorCells.join(" | ")} |`);
215
- }
216
- }
217
- const tbody = child.children?.find((c) => c.type === "tbody");
218
- if (tbody?.children) for (const tr of tbody.children.filter((c) => c.type === "tr")) lines.push(extractTableRow(tr));
219
- return;
220
- }
221
- if (child.children && Array.isArray(child.children)) for (const c of child.children) processNode(c);
222
- }
223
- if (node.children && Array.isArray(node.children)) for (const child of node.children) processNode(child);
224
- return lines.join("\n").trim() || null;
225
- }
226
-
227
- //#endregion
228
- //#region src/engine/parseSentinels.ts
229
- /** Sentinel values for text fields */
230
- const SENTINEL_SKIP = "%SKIP%";
231
- const SENTINEL_ABORT = "%ABORT%";
232
- /**
233
- * Parse a sentinel value with optional parenthesized reason.
234
- * Formats: `%SKIP%`, `%SKIP% (reason text)`, `%ABORT%`, `%ABORT% (reason text)`
235
- * Returns null if the content is not a sentinel.
236
- */
237
- function parseSentinel$1(content) {
238
- if (!content) return null;
239
- const trimmed = content.trim();
240
- const reasonPattern = /^\((.+)\)$/s;
241
- if (trimmed.startsWith(SENTINEL_SKIP)) {
242
- const rest = trimmed.slice(6).trim();
243
- if (rest === "") return { type: "skip" };
244
- const match = reasonPattern.exec(rest);
245
- if (match?.[1]) return {
246
- type: "skip",
247
- reason: match[1].trim()
248
- };
249
- return null;
250
- }
251
- if (trimmed.startsWith(SENTINEL_ABORT)) {
252
- const rest = trimmed.slice(7).trim();
253
- if (rest === "") return { type: "abort" };
254
- const match = reasonPattern.exec(rest);
255
- if (match?.[1]) return {
256
- type: "abort",
257
- reason: match[1].trim()
258
- };
259
- return null;
260
- }
261
- return null;
262
- }
263
- /**
264
- * Check for sentinel values in fence content and validate against state attribute.
265
- * Handles the common pattern of checking for %SKIP% and %ABORT% sentinels in field values.
266
- *
267
- * @param node - The field node to check
268
- * @param fieldId - The field ID for error messages
269
- * @param required - Whether the field is required (skip not allowed on required fields)
270
- * @returns A FieldResponse if a sentinel is found, null otherwise
271
- */
272
- function tryParseSentinelResponse(node, fieldId, required) {
273
- const fenceContent = extractFenceValue(node);
274
- const stateAttr = getStringAttr(node, "state");
275
- const sentinel = parseSentinel$1(fenceContent);
276
- if (!sentinel) return null;
277
- if (sentinel.type === "skip") {
278
- if (stateAttr !== void 0 && stateAttr !== "skipped") throw new MarkformParseError(`Field '${fieldId}' has conflicting state='${stateAttr}' with %SKIP% sentinel`);
279
- if (required) throw new MarkformParseError(`Field '${fieldId}' is required but has %SKIP% sentinel. Cannot skip required fields.`);
280
- return {
281
- state: "skipped",
282
- ...sentinel.reason && { reason: sentinel.reason }
283
- };
284
- }
285
- if (sentinel.type === "abort") {
286
- if (stateAttr !== void 0 && stateAttr !== "aborted") throw new MarkformParseError(`Field '${fieldId}' has conflicting state='${stateAttr}' with %ABORT% sentinel`);
287
- return {
288
- state: "aborted",
289
- ...sentinel.reason && { reason: sentinel.reason }
290
- };
291
- }
292
- return null;
293
- }
294
-
295
37
  //#endregion
296
38
  //#region src/engine/table/parseTable.ts
297
39
  /** Sentinel pattern: %SKIP% or %SKIP:reason% or %SKIP(reason)% */
298
40
  const SKIP_PATTERN = /^%SKIP(?:[:(](.*))?[)]?%$/i;
299
41
  /** Sentinel pattern: %ABORT% or %ABORT:reason% or %ABORT(reason)% */
300
42
  const ABORT_PATTERN = /^%ABORT(?:[:(](.*))?[)]?%$/i;
43
+ /** Markdown link pattern: [text](url) */
44
+ const MARKDOWN_LINK_PATTERN = /^\[([^\]]*)\]\(([^)]+)\)$/;
45
+ /**
46
+ * Extract URL from markdown link format if present.
47
+ * Returns the URL part from [text](url) format, or the original value if not a markdown link.
48
+ */
49
+ function extractUrlFromMarkdownLink(value) {
50
+ const match = MARKDOWN_LINK_PATTERN.exec(value);
51
+ if (match) return match[2];
52
+ return value;
53
+ }
301
54
  /**
302
55
  * Detect if a cell value is a sentinel.
303
56
  */
@@ -345,7 +98,7 @@ function parseCellValue(rawValue, columnType) {
345
98
  }
346
99
  case "url": return {
347
100
  state: "answered",
348
- value: trimmed
101
+ value: extractUrlFromMarkdownLink(trimmed)
349
102
  };
350
103
  case "date": return {
351
104
  state: "answered",
@@ -423,7 +176,7 @@ function parseMarkdownTable(content, columns, dataStartLine) {
423
176
  error: "Invalid table separator row"
424
177
  };
425
178
  if (dataStartLine !== void 0) {
426
- const rows$1 = [];
179
+ const rows = [];
427
180
  for (let i = dataStartLine; i < lines.length; i++) {
428
181
  const rawCells = parseTableRow(lines[i]);
429
182
  const row = {};
@@ -432,13 +185,13 @@ function parseMarkdownTable(content, columns, dataStartLine) {
432
185
  const rawValue = rawCells[j] ?? "";
433
186
  row[column.id] = parseCellValue(rawValue, column.type);
434
187
  }
435
- rows$1.push(row);
188
+ rows.push(row);
436
189
  }
437
190
  return {
438
191
  ok: true,
439
192
  value: {
440
193
  kind: "table",
441
- rows: rows$1
194
+ rows
442
195
  }
443
196
  };
444
197
  }
@@ -1270,9 +1023,9 @@ function findAllCheckboxes(markdown) {
1270
1023
  if (inCodeBlock) continue;
1271
1024
  const match = CHECKBOX_PATTERN.exec(line);
1272
1025
  if (!match) continue;
1273
- const marker$2 = match[2] ?? "";
1026
+ const marker = match[2] ?? "";
1274
1027
  const rest = match[3] ?? "";
1275
- const state = CHECKBOX_MARKERS[marker$2];
1028
+ const state = CHECKBOX_MARKERS[marker];
1276
1029
  if (state === void 0) continue;
1277
1030
  let label = rest;
1278
1031
  let id;
@@ -2652,7 +2405,7 @@ function coerceToCheckboxes(field, rawValue) {
2652
2405
  const checkboxMode = field.checkboxMode;
2653
2406
  if (Array.isArray(rawValue)) {
2654
2407
  const defaultState = checkboxMode === "explicit" ? "yes" : "done";
2655
- const values$1 = {};
2408
+ const values = {};
2656
2409
  for (const item of rawValue) {
2657
2410
  if (typeof item !== "string") return {
2658
2411
  ok: false,
@@ -2662,20 +2415,20 @@ function coerceToCheckboxes(field, rawValue) {
2662
2415
  ok: false,
2663
2416
  error: `Invalid option '${item}' for checkboxes field '${field.id}'. Valid options: ${Array.from(validOptions).join(", ")}`
2664
2417
  };
2665
- values$1[item] = defaultState;
2418
+ values[item] = defaultState;
2666
2419
  }
2667
- const patch$1 = {
2420
+ const patch = {
2668
2421
  op: "set_checkboxes",
2669
2422
  fieldId: field.id,
2670
- value: values$1
2423
+ value: values
2671
2424
  };
2672
2425
  if (rawValue.length === 0) return {
2673
2426
  ok: true,
2674
- patch: patch$1
2427
+ patch
2675
2428
  };
2676
2429
  return {
2677
2430
  ok: true,
2678
- patch: patch$1,
2431
+ patch,
2679
2432
  warning: `Coerced array to checkboxes object with '${defaultState}' state for field '${field.id}'`
2680
2433
  };
2681
2434
  }
@@ -3043,13 +2796,13 @@ var FormHarness = class {
3043
2796
  this.turnNumber++;
3044
2797
  if (this.turnNumber > this.config.maxTurns) {
3045
2798
  this.state = "complete";
3046
- const result$1 = inspect(this.form, { targetRoles: this.config.targetRoles });
2799
+ const result = inspect(this.form, { targetRoles: this.config.targetRoles });
3047
2800
  return {
3048
- structureSummary: result$1.structureSummary,
3049
- progressSummary: result$1.progressSummary,
2801
+ structureSummary: result.structureSummary,
2802
+ progressSummary: result.progressSummary,
3050
2803
  issues: [],
3051
2804
  stepBudget: 0,
3052
- isComplete: result$1.isComplete,
2805
+ isComplete: result.isComplete,
3053
2806
  turnNumber: this.turnNumber
3054
2807
  };
3055
2808
  }
@@ -3474,7 +3227,476 @@ function computeExecutionPlan(form) {
3474
3227
  }
3475
3228
 
3476
3229
  //#endregion
3477
- //#region ../../node_modules/.pnpm/@ai-sdk+provider@3.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
3230
+ //#region src/harness/timeUtils.ts
3231
+ /**
3232
+ * Time utilities - Shared helpers for time and ID generation.
3233
+ *
3234
+ * Centralizes time-related operations for:
3235
+ * - Consistent behavior across the codebase
3236
+ * - Easy mocking in tests
3237
+ * - Clear audit of time-dependent code
3238
+ */
3239
+ /**
3240
+ * Get the current time as an ISO 8601 string.
3241
+ *
3242
+ * All code that needs "now" should call this function instead of
3243
+ * `new Date()` directly. This allows:
3244
+ * - Consistent timestamp format (ISO 8601)
3245
+ * - Clear visibility into time-dependent code
3246
+ * - Future support for clock mocking in tests
3247
+ *
3248
+ * @returns ISO 8601 timestamp string
3249
+ *
3250
+ * @example
3251
+ * ```typescript
3252
+ * const startedAt = currentTime();
3253
+ * // ... do work ...
3254
+ * const completedAt = currentTime();
3255
+ * ```
3256
+ */
3257
+ function currentTime() {
3258
+ return (/* @__PURE__ */ new Date()).toISOString();
3259
+ }
3260
+ /**
3261
+ * Generate a unique session ID using ULID with a "sess-" prefix.
3262
+ *
3263
+ * ULIDs are:
3264
+ * - Lexicographically sortable by time
3265
+ * - 128-bit compatible with UUID
3266
+ * - URL-safe (no special characters)
3267
+ * - Monotonically increasing within the same millisecond
3268
+ *
3269
+ * The "sess-" prefix makes IDs self-identifying, following the policy
3270
+ * that all IDs should indicate their type at a glance. The ULID is
3271
+ * lowercased for consistency and readability.
3272
+ *
3273
+ * @returns Prefixed lowercase ULID string (31 characters: "sess-" + 26-char ULID)
3274
+ *
3275
+ * @example
3276
+ * ```typescript
3277
+ * const sessionId = generateSessionId();
3278
+ * // => "sess-01arz3ndektsv4rrffq69g5fav"
3279
+ * ```
3280
+ */
3281
+ function generateSessionId() {
3282
+ return `sess-${ulid().toLowerCase()}`;
3283
+ }
3284
+
3285
+ //#endregion
3286
+ //#region src/harness/fillRecordCollector.ts
3287
+ /**
3288
+ * Thread-safe collector for FillRecord data.
3289
+ *
3290
+ * Uses an append-only event log pattern for thread safety.
3291
+ * Events are aggregated when getRecord() is called.
3292
+ */
3293
+ var FillRecordCollector = class {
3294
+ startedAt;
3295
+ sessionId;
3296
+ form;
3297
+ provider;
3298
+ model;
3299
+ parallelEnabled;
3300
+ maxParallelAgents;
3301
+ customData;
3302
+ events = [];
3303
+ explicitStatus;
3304
+ explicitStatusDetail;
3305
+ pendingToolCalls = /* @__PURE__ */ new Map();
3306
+ pendingLlmCalls = /* @__PURE__ */ new Map();
3307
+ constructor(options) {
3308
+ this.startedAt = currentTime();
3309
+ this.sessionId = generateSessionId();
3310
+ this.form = options.form;
3311
+ this.provider = options.provider;
3312
+ this.model = options.model;
3313
+ this.parallelEnabled = options.parallelEnabled ?? false;
3314
+ this.maxParallelAgents = options.maxParallelAgents;
3315
+ this.customData = options.customData ?? {};
3316
+ }
3317
+ onTurnStart(turn) {
3318
+ this.events.push({
3319
+ type: "turn_start",
3320
+ timestamp: currentTime(),
3321
+ turnNumber: turn.turnNumber,
3322
+ issuesCount: turn.issuesCount,
3323
+ order: turn.order,
3324
+ executionId: turn.executionId
3325
+ });
3326
+ }
3327
+ onTurnComplete(progress) {
3328
+ this.events.push({
3329
+ type: "turn_complete",
3330
+ timestamp: currentTime(),
3331
+ turnNumber: progress.turnNumber,
3332
+ patchesApplied: progress.patchesApplied,
3333
+ patchesRejected: progress.rejectedPatches?.length ?? 0,
3334
+ issuesAddressed: progress.issuesShown
3335
+ });
3336
+ }
3337
+ onLlmCallStart(call) {
3338
+ const event = {
3339
+ type: "llm_call_start",
3340
+ timestamp: currentTime(),
3341
+ model: call.model,
3342
+ executionId: call.executionId
3343
+ };
3344
+ this.events.push(event);
3345
+ this.pendingLlmCalls.set(call.executionId, event);
3346
+ }
3347
+ onLlmCallEnd(call) {
3348
+ this.events.push({
3349
+ type: "llm_call_end",
3350
+ timestamp: currentTime(),
3351
+ model: call.model,
3352
+ inputTokens: call.inputTokens,
3353
+ outputTokens: call.outputTokens,
3354
+ executionId: call.executionId
3355
+ });
3356
+ this.pendingLlmCalls.delete(call.executionId);
3357
+ }
3358
+ onToolStart(call) {
3359
+ const event = {
3360
+ type: "tool_start",
3361
+ timestamp: currentTime(),
3362
+ name: call.name,
3363
+ input: call.input,
3364
+ executionId: call.executionId
3365
+ };
3366
+ this.events.push(event);
3367
+ const key = `${call.executionId}:${call.name}`;
3368
+ this.pendingToolCalls.set(key, event);
3369
+ }
3370
+ onToolEnd(call) {
3371
+ this.events.push({
3372
+ type: "tool_end",
3373
+ timestamp: currentTime(),
3374
+ name: call.name,
3375
+ output: call.output,
3376
+ durationMs: call.durationMs,
3377
+ error: call.error,
3378
+ executionId: call.executionId
3379
+ });
3380
+ const key = `${call.executionId}:${call.name}`;
3381
+ this.pendingToolCalls.delete(key);
3382
+ }
3383
+ onWebSearch(info) {
3384
+ this.events.push({
3385
+ type: "web_search",
3386
+ timestamp: currentTime(),
3387
+ query: info.query,
3388
+ resultCount: info.resultCount,
3389
+ provider: info.provider,
3390
+ executionId: info.executionId
3391
+ });
3392
+ }
3393
+ /**
3394
+ * Add custom data during execution.
3395
+ */
3396
+ addCustomData(key, value) {
3397
+ this.customData[key] = value;
3398
+ }
3399
+ /**
3400
+ * Set explicit status (overrides auto-detection from progress).
3401
+ */
3402
+ setStatus(status, detail) {
3403
+ this.explicitStatus = status;
3404
+ this.explicitStatusDetail = detail;
3405
+ }
3406
+ /**
3407
+ * Assemble the complete FillRecord from collected events.
3408
+ */
3409
+ getRecord(formProgress) {
3410
+ const completedAt = currentTime();
3411
+ const durationMs = new Date(completedAt).getTime() - new Date(this.startedAt).getTime();
3412
+ const timeline = this.buildTimeline();
3413
+ const llmTotals = this.calculateLlmTotals();
3414
+ const toolSummary = this.calculateToolSummary();
3415
+ const timingBreakdown = this.calculateTimingBreakdown(durationMs, llmTotals.llmTimeMs, toolSummary.totalDurationMs);
3416
+ const execution = this.buildExecutionMetadata(timeline);
3417
+ const status = this.determineStatus(formProgress);
3418
+ return {
3419
+ sessionId: this.sessionId,
3420
+ startedAt: this.startedAt,
3421
+ completedAt,
3422
+ durationMs,
3423
+ form: this.form,
3424
+ status,
3425
+ statusDetail: this.explicitStatusDetail,
3426
+ formProgress,
3427
+ llm: {
3428
+ provider: this.provider,
3429
+ model: this.model,
3430
+ totalCalls: llmTotals.totalCalls,
3431
+ inputTokens: llmTotals.inputTokens,
3432
+ outputTokens: llmTotals.outputTokens
3433
+ },
3434
+ toolSummary,
3435
+ timingBreakdown,
3436
+ timeline,
3437
+ execution,
3438
+ customData: Object.keys(this.customData).length > 0 ? this.customData : void 0
3439
+ };
3440
+ }
3441
+ buildTimeline() {
3442
+ const turns = /* @__PURE__ */ new Map();
3443
+ const turnStartEvents = /* @__PURE__ */ new Map();
3444
+ const turnToolCalls = /* @__PURE__ */ new Map();
3445
+ const turnTokens = /* @__PURE__ */ new Map();
3446
+ for (const event of this.events) if (event.type === "turn_start") {
3447
+ turnStartEvents.set(event.turnNumber, event);
3448
+ turnToolCalls.set(event.turnNumber, []);
3449
+ turnTokens.set(event.turnNumber, {
3450
+ input: 0,
3451
+ output: 0
3452
+ });
3453
+ }
3454
+ const activeToolsByTurn = /* @__PURE__ */ new Map();
3455
+ let currentTurnNumber = 0;
3456
+ for (const event of this.events) if (event.type === "turn_start") {
3457
+ currentTurnNumber = event.turnNumber;
3458
+ activeToolsByTurn.set(currentTurnNumber, /* @__PURE__ */ new Map());
3459
+ } else if (event.type === "tool_start") {
3460
+ const activeTurn = this.findTurnForExecutionId(event.executionId, turnStartEvents) ?? currentTurnNumber;
3461
+ const activeTools = activeToolsByTurn.get(activeTurn);
3462
+ if (activeTools) {
3463
+ const key = `${event.executionId}:${event.name}`;
3464
+ activeTools.set(key, {
3465
+ start: event,
3466
+ turnNumber: activeTurn
3467
+ });
3468
+ }
3469
+ } else if (event.type === "tool_end") {
3470
+ const key = `${event.executionId}:${event.name}`;
3471
+ let foundTurn;
3472
+ for (const [turnNum, activeTools] of activeToolsByTurn) if (activeTools.has(key)) {
3473
+ foundTurn = turnNum;
3474
+ break;
3475
+ }
3476
+ if (foundTurn !== void 0) {
3477
+ const activeTools = activeToolsByTurn.get(foundTurn);
3478
+ const startInfo = activeTools.get(key);
3479
+ if (startInfo) {
3480
+ const toolCall = {
3481
+ tool: event.name,
3482
+ startedAt: startInfo.start.timestamp,
3483
+ completedAt: event.timestamp,
3484
+ durationMs: event.durationMs,
3485
+ success: !event.error,
3486
+ input: this.normalizeInput(startInfo.start.input),
3487
+ result: event.error ? { error: event.error } : this.extractResultCount(event.output)
3488
+ };
3489
+ turnToolCalls.get(foundTurn)?.push(toolCall);
3490
+ activeTools.delete(key);
3491
+ }
3492
+ }
3493
+ } else if (event.type === "llm_call_end") {
3494
+ const turnNum = this.findTurnForExecutionId(event.executionId, turnStartEvents) ?? currentTurnNumber;
3495
+ const tokens = turnTokens.get(turnNum);
3496
+ if (tokens) {
3497
+ tokens.input += event.inputTokens;
3498
+ tokens.output += event.outputTokens;
3499
+ }
3500
+ }
3501
+ for (const event of this.events) if (event.type === "turn_complete") {
3502
+ const startEvent = turnStartEvents.get(event.turnNumber);
3503
+ if (startEvent) {
3504
+ const tokens = turnTokens.get(event.turnNumber) ?? {
3505
+ input: 0,
3506
+ output: 0
3507
+ };
3508
+ const toolCalls = turnToolCalls.get(event.turnNumber) ?? [];
3509
+ const entry = {
3510
+ turnNumber: event.turnNumber,
3511
+ order: startEvent.order,
3512
+ executionId: startEvent.executionId,
3513
+ startedAt: startEvent.timestamp,
3514
+ completedAt: event.timestamp,
3515
+ durationMs: new Date(event.timestamp).getTime() - new Date(startEvent.timestamp).getTime(),
3516
+ issuesAddressed: event.issuesAddressed,
3517
+ patchesApplied: event.patchesApplied,
3518
+ patchesRejected: event.patchesRejected,
3519
+ tokens,
3520
+ toolCalls
3521
+ };
3522
+ turns.set(event.turnNumber, entry);
3523
+ }
3524
+ }
3525
+ return Array.from(turns.values()).sort((a, b) => a.turnNumber - b.turnNumber);
3526
+ }
3527
+ findTurnForExecutionId(executionId, turnStartEvents) {
3528
+ for (const [turnNumber, event] of turnStartEvents) if (event.executionId === executionId) return turnNumber;
3529
+ }
3530
+ normalizeInput(input) {
3531
+ if (input && typeof input === "object" && !Array.isArray(input)) return input;
3532
+ return { value: input };
3533
+ }
3534
+ extractResultCount(output) {
3535
+ if (output && typeof output === "object") {
3536
+ const obj = output;
3537
+ if (Array.isArray(obj.results)) return { resultCount: obj.results.length };
3538
+ if (typeof obj.applied === "number") return { resultCount: obj.applied };
3539
+ if (typeof obj.resultCount === "number") return { resultCount: obj.resultCount };
3540
+ }
3541
+ }
3542
+ calculateLlmTotals() {
3543
+ let totalCalls = 0;
3544
+ let inputTokens = 0;
3545
+ let outputTokens = 0;
3546
+ let llmTimeMs = 0;
3547
+ const llmStartTimes = /* @__PURE__ */ new Map();
3548
+ for (const event of this.events) if (event.type === "llm_call_start") llmStartTimes.set(event.executionId, event.timestamp);
3549
+ else if (event.type === "llm_call_end") {
3550
+ totalCalls++;
3551
+ inputTokens += event.inputTokens;
3552
+ outputTokens += event.outputTokens;
3553
+ const startTime = llmStartTimes.get(event.executionId);
3554
+ if (startTime) {
3555
+ llmTimeMs += new Date(event.timestamp).getTime() - new Date(startTime).getTime();
3556
+ llmStartTimes.delete(event.executionId);
3557
+ }
3558
+ }
3559
+ return {
3560
+ totalCalls,
3561
+ inputTokens,
3562
+ outputTokens,
3563
+ llmTimeMs
3564
+ };
3565
+ }
3566
+ calculateToolSummary() {
3567
+ const toolCalls = /* @__PURE__ */ new Map();
3568
+ let totalCalls = 0;
3569
+ let successfulCalls = 0;
3570
+ let failedCalls = 0;
3571
+ let totalDurationMs = 0;
3572
+ for (const event of this.events) if (event.type === "tool_end") {
3573
+ totalCalls++;
3574
+ totalDurationMs += event.durationMs;
3575
+ if (event.error) failedCalls++;
3576
+ else successfulCalls++;
3577
+ let stats = toolCalls.get(event.name);
3578
+ if (!stats) {
3579
+ stats = {
3580
+ durations: [],
3581
+ successes: 0,
3582
+ failures: 0,
3583
+ resultCounts: []
3584
+ };
3585
+ toolCalls.set(event.name, stats);
3586
+ }
3587
+ stats.durations.push(event.durationMs);
3588
+ if (event.error) stats.failures++;
3589
+ else stats.successes++;
3590
+ const resultCount = this.extractResultCountFromOutput(event.output);
3591
+ if (resultCount !== void 0) stats.resultCounts.push(resultCount);
3592
+ }
3593
+ const byTool = [];
3594
+ for (const [toolName, stats] of toolCalls) {
3595
+ const callCount = stats.durations.length;
3596
+ const sortedDurations = [...stats.durations].sort((a, b) => a - b);
3597
+ byTool.push({
3598
+ toolName,
3599
+ callCount,
3600
+ successCount: stats.successes,
3601
+ failureCount: stats.failures,
3602
+ successRate: callCount > 0 ? stats.successes / callCount * 100 : 0,
3603
+ results: stats.resultCounts.length > 0 ? {
3604
+ totalResults: stats.resultCounts.reduce((a, b) => a + b, 0),
3605
+ avgResultsPerCall: stats.resultCounts.reduce((a, b) => a + b, 0) / stats.resultCounts.length,
3606
+ zeroResultCalls: stats.resultCounts.filter((c) => c === 0).length
3607
+ } : void 0,
3608
+ timing: {
3609
+ totalMs: stats.durations.reduce((a, b) => a + b, 0),
3610
+ avgMs: callCount > 0 ? stats.durations.reduce((a, b) => a + b, 0) / callCount : 0,
3611
+ minMs: sortedDurations[0] ?? 0,
3612
+ maxMs: sortedDurations[sortedDurations.length - 1] ?? 0,
3613
+ p50Ms: this.percentile(sortedDurations, 50),
3614
+ p95Ms: this.percentile(sortedDurations, 95)
3615
+ }
3616
+ });
3617
+ }
3618
+ return {
3619
+ totalCalls,
3620
+ successfulCalls,
3621
+ failedCalls,
3622
+ successRate: totalCalls > 0 ? successfulCalls / totalCalls * 100 : 0,
3623
+ totalDurationMs,
3624
+ byTool
3625
+ };
3626
+ }
3627
+ extractResultCountFromOutput(output) {
3628
+ if (output && typeof output === "object") {
3629
+ const obj = output;
3630
+ if (Array.isArray(obj.results)) return obj.results.length;
3631
+ if (typeof obj.resultCount === "number") return obj.resultCount;
3632
+ }
3633
+ }
3634
+ percentile(sorted, p) {
3635
+ if (sorted.length === 0) return 0;
3636
+ if (sorted.length === 1) return sorted[0];
3637
+ const index = p / 100 * (sorted.length - 1);
3638
+ const lower = Math.floor(index);
3639
+ const upper = Math.ceil(index);
3640
+ if (lower === upper) return Math.round(sorted[lower]);
3641
+ const weight = index - lower;
3642
+ return Math.round(sorted[lower] * (1 - weight) + sorted[upper] * weight);
3643
+ }
3644
+ calculateTimingBreakdown(totalMs, llmTimeMs, toolTimeMs) {
3645
+ const overheadMs = Math.max(0, totalMs - llmTimeMs - toolTimeMs);
3646
+ return {
3647
+ totalMs,
3648
+ llmTimeMs,
3649
+ toolTimeMs,
3650
+ overheadMs,
3651
+ breakdown: [
3652
+ {
3653
+ category: "llm",
3654
+ label: "LLM API calls",
3655
+ ms: llmTimeMs,
3656
+ percentage: totalMs > 0 ? llmTimeMs / totalMs * 100 : 0
3657
+ },
3658
+ {
3659
+ category: "tools",
3660
+ label: "Tool execution",
3661
+ ms: toolTimeMs,
3662
+ percentage: totalMs > 0 ? toolTimeMs / totalMs * 100 : 0
3663
+ },
3664
+ {
3665
+ category: "overhead",
3666
+ label: "Overhead",
3667
+ ms: overheadMs,
3668
+ percentage: totalMs > 0 ? overheadMs / totalMs * 100 : 0
3669
+ }
3670
+ ]
3671
+ };
3672
+ }
3673
+ buildExecutionMetadata(timeline) {
3674
+ const orderLevels = /* @__PURE__ */ new Set();
3675
+ const executionThreads = /* @__PURE__ */ new Set();
3676
+ for (const entry of timeline) {
3677
+ orderLevels.add(entry.order);
3678
+ executionThreads.add(entry.executionId);
3679
+ }
3680
+ return {
3681
+ totalTurns: timeline.length,
3682
+ parallelEnabled: this.parallelEnabled,
3683
+ maxParallelAgents: this.parallelEnabled ? this.maxParallelAgents : void 0,
3684
+ orderLevels: Array.from(orderLevels).sort((a, b) => a - b),
3685
+ executionThreads: Array.from(executionThreads)
3686
+ };
3687
+ }
3688
+ determineStatus(formProgress) {
3689
+ if (this.explicitStatus) return this.explicitStatus;
3690
+ const hasUnanswered = formProgress.unansweredFields > 0;
3691
+ const allRequiredFilled = formProgress.answeredFields >= formProgress.requiredFields;
3692
+ if (!hasUnanswered) return "completed";
3693
+ if (allRequiredFilled) return "completed";
3694
+ return "partial";
3695
+ }
3696
+ };
3697
+
3698
+ //#endregion
3699
+ //#region ../../node_modules/.pnpm/@ai-sdk+provider@3.0.6/node_modules/@ai-sdk/provider/dist/index.mjs
3478
3700
  var marker$1 = "vercel.ai.error";
3479
3701
  var symbol$1 = Symbol.for(marker$1);
3480
3702
  var _a, _b;
@@ -3643,33 +3865,48 @@ var marker13 = `vercel.ai.error.${name12}`;
3643
3865
  var symbol13 = Symbol.for(marker13);
3644
3866
  var _a13, _b13;
3645
3867
  var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
3646
- constructor({ value, cause }) {
3868
+ constructor({ value, cause, context }) {
3869
+ let contextPrefix = "Type validation failed";
3870
+ if (context == null ? void 0 : context.field) contextPrefix += ` for ${context.field}`;
3871
+ if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
3872
+ contextPrefix += " (";
3873
+ const parts = [];
3874
+ if (context.entityName) parts.push(context.entityName);
3875
+ if (context.entityId) parts.push(`id: "${context.entityId}"`);
3876
+ contextPrefix += parts.join(", ");
3877
+ contextPrefix += ")";
3878
+ }
3647
3879
  super({
3648
3880
  name: name12,
3649
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
3881
+ message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
3650
3882
  Error message: ${getErrorMessage(cause)}`,
3651
3883
  cause
3652
3884
  });
3653
3885
  this[_a13] = true;
3654
3886
  this.value = value;
3887
+ this.context = context;
3655
3888
  }
3656
3889
  static isInstance(error) {
3657
3890
  return AISDKError.hasMarker(error, marker13);
3658
3891
  }
3659
3892
  /**
3660
3893
  * Wraps an error into a TypeValidationError.
3661
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
3894
+ * If the cause is already a TypeValidationError with the same value and context, it returns the cause.
3662
3895
  * Otherwise, it creates a new TypeValidationError.
3663
3896
  *
3664
3897
  * @param {Object} params - The parameters for wrapping the error.
3665
3898
  * @param {unknown} params.value - The value that failed validation.
3666
3899
  * @param {unknown} params.cause - The original error or cause of the validation failure.
3900
+ * @param {TypeValidationContext} params.context - Optional context about what is being validated.
3667
3901
  * @returns {TypeValidationError} A TypeValidationError instance.
3668
3902
  */
3669
- static wrap({ value, cause }) {
3670
- return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({
3903
+ static wrap({ value, cause, context }) {
3904
+ var _a15, _b15, _c;
3905
+ if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) return cause;
3906
+ return new _TypeValidationError({
3671
3907
  value,
3672
- cause
3908
+ cause,
3909
+ context
3673
3910
  });
3674
3911
  }
3675
3912
  };
@@ -3815,7 +4052,7 @@ var EventSourceParserStream = class extends TransformStream {
3815
4052
  };
3816
4053
 
3817
4054
  //#endregion
3818
- //#region ../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.2.1/node_modules/@ai-sdk/provider-utils/dist/index.mjs
4055
+ //#region ../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.12_zod@4.3.6/node_modules/@ai-sdk/provider-utils/dist/index.mjs
3819
4056
  function combineHeaders(...headers) {
3820
4057
  return headers.reduce((combinedHeaders, currentHeaders) => ({
3821
4058
  ...combinedHeaders,
@@ -3832,12 +4069,12 @@ function createToolNameMapping({ tools = [], providerToolNames }) {
3832
4069
  }
3833
4070
  return {
3834
4071
  toProviderToolName: (customToolName) => {
3835
- var _a2$1;
3836
- return (_a2$1 = customToolNameToProviderToolName[customToolName]) != null ? _a2$1 : customToolName;
4072
+ var _a2;
4073
+ return (_a2 = customToolNameToProviderToolName[customToolName]) != null ? _a2 : customToolName;
3837
4074
  },
3838
4075
  toCustomToolName: (providerToolName) => {
3839
- var _a2$1;
3840
- return (_a2$1 = providerToolNameToCustomToolName[providerToolName]) != null ? _a2$1 : providerToolName;
4076
+ var _a2;
4077
+ return (_a2 = providerToolNameToCustomToolName[providerToolName]) != null ? _a2 : providerToolName;
3841
4078
  }
3842
4079
  };
3843
4080
  }
@@ -3875,6 +4112,21 @@ function isAbortError(error) {
3875
4112
  return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
3876
4113
  }
3877
4114
  var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
4115
+ var BUN_ERROR_CODES = [
4116
+ "ConnectionRefused",
4117
+ "ConnectionClosed",
4118
+ "FailedToOpenSocket",
4119
+ "ECONNRESET",
4120
+ "ECONNREFUSED",
4121
+ "ETIMEDOUT",
4122
+ "EPIPE"
4123
+ ];
4124
+ function isBunNetworkError(error) {
4125
+ if (!(error instanceof Error)) return false;
4126
+ const code = error.code;
4127
+ if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) return true;
4128
+ return false;
4129
+ }
3878
4130
  function handleFetchError({ error, url, requestBodyValues }) {
3879
4131
  if (isAbortError(error)) return error;
3880
4132
  if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
@@ -3887,13 +4139,20 @@ function handleFetchError({ error, url, requestBodyValues }) {
3887
4139
  isRetryable: true
3888
4140
  });
3889
4141
  }
4142
+ if (isBunNetworkError(error)) return new APICallError({
4143
+ message: `Cannot connect to API: ${error.message}`,
4144
+ cause: error,
4145
+ url,
4146
+ requestBodyValues,
4147
+ isRetryable: true
4148
+ });
3890
4149
  return error;
3891
4150
  }
3892
4151
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
3893
- var _a2$1, _b2$1, _c;
4152
+ var _a2, _b2, _c;
3894
4153
  if (globalThisAny.window) return `runtime/browser`;
3895
- if ((_a2$1 = globalThisAny.navigator) == null ? void 0 : _a2$1.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
3896
- if ((_c = (_b2$1 = globalThisAny.process) == null ? void 0 : _b2$1.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
4154
+ if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
4155
+ if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
3897
4156
  if (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;
3898
4157
  return "runtime/unknown";
3899
4158
  }
@@ -3915,7 +4174,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
3915
4174
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
3916
4175
  return Object.fromEntries(normalizedHeaders.entries());
3917
4176
  }
3918
- var VERSION$2 = "4.0.1";
4177
+ var VERSION$2 = "4.0.12";
3919
4178
  function isNonNullable(value) {
3920
4179
  return value != null;
3921
4180
  }
@@ -3973,15 +4232,23 @@ function secureJsonParse(text) {
3973
4232
  }
3974
4233
  }
3975
4234
  function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
3976
- if (jsonSchema2.type === "object") {
4235
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
3977
4236
  jsonSchema2.additionalProperties = false;
3978
- const properties = jsonSchema2.properties;
3979
- if (properties != null) for (const property in properties) properties[property] = addAdditionalPropertiesToJsonSchema(properties[property]);
3980
- }
3981
- if (jsonSchema2.type === "array" && jsonSchema2.items != null) if (Array.isArray(jsonSchema2.items)) jsonSchema2.items = jsonSchema2.items.map((item) => addAdditionalPropertiesToJsonSchema(item));
3982
- else jsonSchema2.items = addAdditionalPropertiesToJsonSchema(jsonSchema2.items);
4237
+ const { properties } = jsonSchema2;
4238
+ if (properties != null) for (const key of Object.keys(properties)) properties[key] = visit(properties[key]);
4239
+ }
4240
+ if (jsonSchema2.items != null) jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
4241
+ if (jsonSchema2.anyOf != null) jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
4242
+ if (jsonSchema2.allOf != null) jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
4243
+ if (jsonSchema2.oneOf != null) jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
4244
+ const { definitions } = jsonSchema2;
4245
+ if (definitions != null) for (const key of Object.keys(definitions)) definitions[key] = visit(definitions[key]);
3983
4246
  return jsonSchema2;
3984
4247
  }
4248
+ function visit(def) {
4249
+ if (typeof def === "boolean") return def;
4250
+ return addAdditionalPropertiesToJsonSchema(def);
4251
+ }
3985
4252
  var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
3986
4253
  var defaultOptions = {
3987
4254
  name: void 0,
@@ -4015,9 +4282,9 @@ function parseAnyDef() {
4015
4282
  return {};
4016
4283
  }
4017
4284
  function parseArrayDef(def, refs) {
4018
- var _a2$1, _b2$1, _c;
4285
+ var _a2, _b2, _c;
4019
4286
  const res = { type: "array" };
4020
- if (((_a2$1 = def.type) == null ? void 0 : _a2$1._def) && ((_c = (_b2$1 = def.type) == null ? void 0 : _b2$1._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {
4287
+ if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {
4021
4288
  ...refs,
4022
4289
  currentPath: [...refs.currentPath, "items"]
4023
4290
  });
@@ -4283,8 +4550,8 @@ function escapeNonAlphaNumeric(source) {
4283
4550
  return result;
4284
4551
  }
4285
4552
  function addFormat(schema, value, message, refs) {
4286
- var _a2$1;
4287
- if (schema.format || ((_a2$1 = schema.anyOf) == null ? void 0 : _a2$1.some((x) => x.format))) {
4553
+ var _a2;
4554
+ if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {
4288
4555
  if (!schema.anyOf) schema.anyOf = [];
4289
4556
  if (schema.format) {
4290
4557
  schema.anyOf.push({ format: schema.format });
@@ -4297,8 +4564,8 @@ function addFormat(schema, value, message, refs) {
4297
4564
  } else schema.format = value;
4298
4565
  }
4299
4566
  function addPattern(schema, regex, message, refs) {
4300
- var _a2$1;
4301
- if (schema.pattern || ((_a2$1 = schema.allOf) == null ? void 0 : _a2$1.some((x) => x.pattern))) {
4567
+ var _a2;
4568
+ if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {
4302
4569
  if (!schema.allOf) schema.allOf = [];
4303
4570
  if (schema.pattern) {
4304
4571
  schema.allOf.push({ pattern: schema.pattern });
@@ -4311,7 +4578,7 @@ function addPattern(schema, regex, message, refs) {
4311
4578
  } else schema.pattern = stringifyRegExpWithFlags(regex, refs);
4312
4579
  }
4313
4580
  function stringifyRegExpWithFlags(regex, refs) {
4314
- var _a2$1;
4581
+ var _a2;
4315
4582
  if (!refs.applyRegexFlags || !regex.flags) return regex.source;
4316
4583
  const flags = {
4317
4584
  i: regex.flags.includes("i"),
@@ -4336,7 +4603,7 @@ function stringifyRegExpWithFlags(regex, refs) {
4336
4603
  pattern += source[i];
4337
4604
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
4338
4605
  inCharRange = false;
4339
- } else if (source[i + 1] === "-" && ((_a2$1 = source[i + 2]) == null ? void 0 : _a2$1.match(/[a-z]/))) {
4606
+ } else if (source[i + 1] === "-" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {
4340
4607
  pattern += source[i];
4341
4608
  inCharRange = true;
4342
4609
  } else pattern += `${source[i]}${source[i].toUpperCase()}`;
@@ -4378,15 +4645,15 @@ function stringifyRegExpWithFlags(regex, refs) {
4378
4645
  return pattern;
4379
4646
  }
4380
4647
  function parseRecordDef(def, refs) {
4381
- var _a2$1, _b2$1, _c, _d, _e, _f;
4648
+ var _a2, _b2, _c, _d, _e, _f;
4382
4649
  const schema = {
4383
4650
  type: "object",
4384
- additionalProperties: (_a2$1 = parseDef(def.valueType._def, {
4651
+ additionalProperties: (_a2 = parseDef(def.valueType._def, {
4385
4652
  ...refs,
4386
4653
  currentPath: [...refs.currentPath, "additionalProperties"]
4387
- })) != null ? _a2$1 : refs.allowedAdditionalProperties
4654
+ })) != null ? _a2 : refs.allowedAdditionalProperties
4388
4655
  };
4389
- if (((_b2$1 = def.keyType) == null ? void 0 : _b2$1._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
4656
+ if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
4390
4657
  const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
4391
4658
  return {
4392
4659
  ...schema,
@@ -4475,9 +4742,6 @@ function parseUnionDef(def, refs) {
4475
4742
  case "boolean": return [...acc, type];
4476
4743
  case "bigint": return [...acc, "integer"];
4477
4744
  case "object": if (x._def.value === null) return [...acc, "null"];
4478
- case "symbol":
4479
- case "undefined":
4480
- case "function":
4481
4745
  default: return acc;
4482
4746
  }
4483
4747
  }, []);
@@ -4598,8 +4862,8 @@ function safeIsOptional(schema) {
4598
4862
  }
4599
4863
  }
4600
4864
  var parseOptionalDef = (def, refs) => {
4601
- var _a2$1;
4602
- if (refs.currentPath.toString() === ((_a2$1 = refs.propertyPath) == null ? void 0 : _a2$1.toString())) return parseDef(def.innerType._def, refs);
4865
+ var _a2;
4866
+ if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) return parseDef(def.innerType._def, refs);
4603
4867
  const innerSchema = parseDef(def.innerType._def, {
4604
4868
  ...refs,
4605
4869
  currentPath: [
@@ -4733,10 +4997,10 @@ var getRelativePath = (pathA, pathB) => {
4733
4997
  return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
4734
4998
  };
4735
4999
  function parseDef(def, refs, forceResolution = false) {
4736
- var _a2$1;
5000
+ var _a2;
4737
5001
  const seenItem = refs.seen.get(def);
4738
5002
  if (refs.override) {
4739
- const overrideResult = (_a2$1 = refs.override) == null ? void 0 : _a2$1.call(refs, def, refs, seenItem, forceResolution);
5003
+ const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(refs, def, refs, seenItem, forceResolution);
4740
5004
  if (overrideResult !== ignoreOverride) return overrideResult;
4741
5005
  }
4742
5006
  if (seenItem && !forceResolution) {
@@ -4788,57 +5052,57 @@ var getRefs = (options) => {
4788
5052
  ..._options,
4789
5053
  currentPath,
4790
5054
  propertyPath: void 0,
4791
- seen: new Map(Object.entries(_options.definitions).map(([name2$1, def]) => [def._def, {
5055
+ seen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [def._def, {
4792
5056
  def: def._def,
4793
5057
  path: [
4794
5058
  ..._options.basePath,
4795
5059
  _options.definitionPath,
4796
- name2$1
5060
+ name2
4797
5061
  ],
4798
5062
  jsonSchema: void 0
4799
5063
  }]))
4800
5064
  };
4801
5065
  };
4802
5066
  var zod3ToJsonSchema = (schema, options) => {
4803
- var _a2$1;
5067
+ var _a2;
4804
5068
  const refs = getRefs(options);
4805
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3$1, schema2]) => {
4806
- var _a3$1;
5069
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema2]) => {
5070
+ var _a3;
4807
5071
  return {
4808
5072
  ...acc,
4809
- [name3$1]: (_a3$1 = parseDef(schema2._def, {
5073
+ [name3]: (_a3 = parseDef(schema2._def, {
4810
5074
  ...refs,
4811
5075
  currentPath: [
4812
5076
  ...refs.basePath,
4813
5077
  refs.definitionPath,
4814
- name3$1
5078
+ name3
4815
5079
  ]
4816
- }, true)) != null ? _a3$1 : parseAnyDef()
5080
+ }, true)) != null ? _a3 : parseAnyDef()
4817
5081
  };
4818
5082
  }, {}) : void 0;
4819
- const name2$1 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
4820
- const main = (_a2$1 = parseDef(schema._def, name2$1 === void 0 ? refs : {
5083
+ const name2 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
5084
+ const main = (_a2 = parseDef(schema._def, name2 === void 0 ? refs : {
4821
5085
  ...refs,
4822
5086
  currentPath: [
4823
5087
  ...refs.basePath,
4824
5088
  refs.definitionPath,
4825
- name2$1
5089
+ name2
4826
5090
  ]
4827
- }, false)) != null ? _a2$1 : parseAnyDef();
5091
+ }, false)) != null ? _a2 : parseAnyDef();
4828
5092
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
4829
5093
  if (title !== void 0) main.title = title;
4830
- const combined = name2$1 === void 0 ? definitions ? {
5094
+ const combined = name2 === void 0 ? definitions ? {
4831
5095
  ...main,
4832
5096
  [refs.definitionPath]: definitions
4833
5097
  } : main : {
4834
5098
  $ref: [
4835
5099
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
4836
5100
  refs.definitionPath,
4837
- name2$1
5101
+ name2
4838
5102
  ].join("/"),
4839
5103
  [refs.definitionPath]: {
4840
5104
  ...definitions,
4841
- [name2$1]: main
5105
+ [name2]: main
4842
5106
  }
4843
5107
  };
4844
5108
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -4873,7 +5137,7 @@ function asSchema(schema) {
4873
5137
  }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema$1(schema) : standardSchema(schema) : schema();
4874
5138
  }
4875
5139
  function standardSchema(standardSchema2) {
4876
- return jsonSchema(() => standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }), { validate: async (value) => {
5140
+ return jsonSchema(() => addAdditionalPropertiesToJsonSchema(standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" })), { validate: async (value) => {
4877
5141
  const result = await standardSchema2["~standard"].validate(value);
4878
5142
  return "value" in result ? {
4879
5143
  success: true,
@@ -4888,8 +5152,8 @@ function standardSchema(standardSchema2) {
4888
5152
  } });
4889
5153
  }
4890
5154
  function zod3Schema(zodSchema2, options) {
4891
- var _a2$1;
4892
- const useReferences = (_a2$1 = options == null ? void 0 : options.useReferences) != null ? _a2$1 : false;
5155
+ var _a2;
5156
+ const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
4893
5157
  return jsonSchema(() => zod3ToJsonSchema(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
4894
5158
  const result = await zodSchema2.safeParseAsync(value);
4895
5159
  return result.success ? {
@@ -4902,8 +5166,8 @@ function zod3Schema(zodSchema2, options) {
4902
5166
  } });
4903
5167
  }
4904
5168
  function zod4Schema(zodSchema2, options) {
4905
- var _a2$1;
4906
- const useReferences = (_a2$1 = options == null ? void 0 : options.useReferences) != null ? _a2$1 : false;
5169
+ var _a2;
5170
+ const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
4907
5171
  return jsonSchema(() => addAdditionalPropertiesToJsonSchema(z4.toJSONSchema(zodSchema2, {
4908
5172
  target: "draft-7",
4909
5173
  io: "input",
@@ -4926,18 +5190,20 @@ function zodSchema$1(zodSchema2, options) {
4926
5190
  if (isZod4Schema(zodSchema2)) return zod4Schema(zodSchema2, options);
4927
5191
  else return zod3Schema(zodSchema2, options);
4928
5192
  }
4929
- async function validateTypes({ value, schema }) {
5193
+ async function validateTypes({ value, schema, context }) {
4930
5194
  const result = await safeValidateTypes({
4931
5195
  value,
4932
- schema
5196
+ schema,
5197
+ context
4933
5198
  });
4934
5199
  if (!result.success) throw TypeValidationError.wrap({
4935
5200
  value,
4936
- cause: result.error
5201
+ cause: result.error,
5202
+ context
4937
5203
  });
4938
5204
  return result.value;
4939
5205
  }
4940
- async function safeValidateTypes({ value, schema }) {
5206
+ async function safeValidateTypes({ value, schema, context }) {
4941
5207
  const actualSchema = asSchema(schema);
4942
5208
  try {
4943
5209
  if (actualSchema.validate == null) return {
@@ -4955,7 +5221,8 @@ async function safeValidateTypes({ value, schema }) {
4955
5221
  success: false,
4956
5222
  error: TypeValidationError.wrap({
4957
5223
  value,
4958
- cause: result.error
5224
+ cause: result.error,
5225
+ context
4959
5226
  }),
4960
5227
  rawValue: value
4961
5228
  };
@@ -4964,7 +5231,8 @@ async function safeValidateTypes({ value, schema }) {
4964
5231
  success: false,
4965
5232
  error: TypeValidationError.wrap({
4966
5233
  value,
4967
- cause: error
5234
+ cause: error,
5235
+ context
4968
5236
  }),
4969
5237
  rawValue: value
4970
5238
  };
@@ -5228,8 +5496,8 @@ function withoutTrailingSlash(url) {
5228
5496
  }
5229
5497
 
5230
5498
  //#endregion
5231
- //#region ../../node_modules/.pnpm/@ai-sdk+anthropic@3.0.1_zod@4.2.1/node_modules/@ai-sdk/anthropic/dist/index.mjs
5232
- var VERSION$1 = "3.0.1";
5499
+ //#region ../../node_modules/.pnpm/@ai-sdk+anthropic@3.0.34_zod@4.3.6/node_modules/@ai-sdk/anthropic/dist/index.mjs
5500
+ var VERSION$1 = "3.0.34";
5233
5501
  var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
5234
5502
  errorSchema: lazySchema(() => zodSchema$1(z$1.object({
5235
5503
  type: z$1.literal("error"),
@@ -5732,21 +6000,23 @@ var anthropicMessagesChunkSchema = lazySchema(() => zodSchema$1(z$1.discriminate
5732
6000
  skill_id: z$1.string(),
5733
6001
  version: z$1.string()
5734
6002
  })).nullish()
5735
- }).nullish(),
5736
- context_management: z$1.object({ applied_edits: z$1.array(z$1.union([z$1.object({
5737
- type: z$1.literal("clear_tool_uses_20250919"),
5738
- cleared_tool_uses: z$1.number(),
5739
- cleared_input_tokens: z$1.number()
5740
- }), z$1.object({
5741
- type: z$1.literal("clear_thinking_20251015"),
5742
- cleared_thinking_turns: z$1.number(),
5743
- cleared_input_tokens: z$1.number()
5744
- })])) }).nullish()
6003
+ }).nullish()
5745
6004
  }),
5746
6005
  usage: z$1.looseObject({
6006
+ input_tokens: z$1.number().nullish(),
5747
6007
  output_tokens: z$1.number(),
5748
- cache_creation_input_tokens: z$1.number().nullish()
5749
- })
6008
+ cache_creation_input_tokens: z$1.number().nullish(),
6009
+ cache_read_input_tokens: z$1.number().nullish()
6010
+ }),
6011
+ context_management: z$1.object({ applied_edits: z$1.array(z$1.union([z$1.object({
6012
+ type: z$1.literal("clear_tool_uses_20250919"),
6013
+ cleared_tool_uses: z$1.number(),
6014
+ cleared_input_tokens: z$1.number()
6015
+ }), z$1.object({
6016
+ type: z$1.literal("clear_thinking_20251015"),
6017
+ cleared_thinking_turns: z$1.number(),
6018
+ cleared_input_tokens: z$1.number()
6019
+ })])) }).nullish()
5750
6020
  }),
5751
6021
  z$1.object({ type: z$1.literal("message_stop") }),
5752
6022
  z$1.object({ type: z$1.literal("ping") })
@@ -5829,9 +6099,9 @@ var anthropicProviderOptions = z$1.object({
5829
6099
  });
5830
6100
  var MAX_CACHE_BREAKPOINTS = 4;
5831
6101
  function getCacheControl(providerMetadata) {
5832
- var _a$1;
6102
+ var _a;
5833
6103
  const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;
5834
- return (_a$1 = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a$1 : anthropic2 == null ? void 0 : anthropic2.cache_control;
6104
+ return (_a = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a : anthropic2 == null ? void 0 : anthropic2.cache_control;
5835
6105
  }
5836
6106
  var CacheControlValidator = class {
5837
6107
  constructor() {
@@ -5878,6 +6148,7 @@ var factory = createProviderToolFactory({
5878
6148
  file_text: z$1.string().optional(),
5879
6149
  insert_line: z$1.number().int().optional(),
5880
6150
  new_str: z$1.string().optional(),
6151
+ insert_text: z$1.string().optional(),
5881
6152
  old_str: z$1.string().optional(),
5882
6153
  view_range: z$1.array(z$1.number().int()).optional()
5883
6154
  })))
@@ -5907,7 +6178,8 @@ var webSearch_20250305OutputSchema = lazySchema(() => zodSchema$1(z$1.array(z$1.
5907
6178
  var factory2 = createProviderToolFactoryWithOutputSchema({
5908
6179
  id: "anthropic.web_search_20250305",
5909
6180
  inputSchema: lazySchema(() => zodSchema$1(z$1.object({ query: z$1.string() }))),
5910
- outputSchema: webSearch_20250305OutputSchema
6181
+ outputSchema: webSearch_20250305OutputSchema,
6182
+ supportsDeferredResults: true
5911
6183
  });
5912
6184
  var webSearch_20250305 = (args = {}) => {
5913
6185
  return factory2(args);
@@ -5941,13 +6213,14 @@ var webFetch_20250910OutputSchema = lazySchema(() => zodSchema$1(z$1.object({
5941
6213
  var factory3 = createProviderToolFactoryWithOutputSchema({
5942
6214
  id: "anthropic.web_fetch_20250910",
5943
6215
  inputSchema: lazySchema(() => zodSchema$1(z$1.object({ url: z$1.string() }))),
5944
- outputSchema: webFetch_20250910OutputSchema
6216
+ outputSchema: webFetch_20250910OutputSchema,
6217
+ supportsDeferredResults: true
5945
6218
  });
5946
6219
  var webFetch_20250910 = (args = {}) => {
5947
6220
  return factory3(args);
5948
6221
  };
5949
6222
  async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput }) {
5950
- var _a$1;
6223
+ var _a;
5951
6224
  tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
5952
6225
  const toolWarnings = [];
5953
6226
  const betas = /* @__PURE__ */ new Set();
@@ -5959,31 +6232,31 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
5959
6232
  betas
5960
6233
  };
5961
6234
  const anthropicTools2 = [];
5962
- for (const tool$1 of tools) switch (tool$1.type) {
6235
+ for (const tool of tools) switch (tool.type) {
5963
6236
  case "function": {
5964
- const cacheControl = validator.getCacheControl(tool$1.providerOptions, {
6237
+ const cacheControl = validator.getCacheControl(tool.providerOptions, {
5965
6238
  type: "tool definition",
5966
6239
  canCache: true
5967
6240
  });
5968
- const anthropicOptions = (_a$1 = tool$1.providerOptions) == null ? void 0 : _a$1.anthropic;
6241
+ const anthropicOptions = (_a = tool.providerOptions) == null ? void 0 : _a.anthropic;
5969
6242
  const deferLoading = anthropicOptions == null ? void 0 : anthropicOptions.deferLoading;
5970
6243
  const allowedCallers = anthropicOptions == null ? void 0 : anthropicOptions.allowedCallers;
5971
6244
  anthropicTools2.push({
5972
- name: tool$1.name,
5973
- description: tool$1.description,
5974
- input_schema: tool$1.inputSchema,
6245
+ name: tool.name,
6246
+ description: tool.description,
6247
+ input_schema: tool.inputSchema,
5975
6248
  cache_control: cacheControl,
5976
- ...supportsStructuredOutput === true && tool$1.strict != null ? { strict: tool$1.strict } : {},
6249
+ ...supportsStructuredOutput === true && tool.strict != null ? { strict: tool.strict } : {},
5977
6250
  ...deferLoading != null ? { defer_loading: deferLoading } : {},
5978
6251
  ...allowedCallers != null ? { allowed_callers: allowedCallers } : {},
5979
- ...tool$1.inputExamples != null ? { input_examples: tool$1.inputExamples.map((example) => example.input) } : {}
6252
+ ...tool.inputExamples != null ? { input_examples: tool.inputExamples.map((example) => example.input) } : {}
5980
6253
  });
5981
6254
  if (supportsStructuredOutput === true) betas.add("structured-outputs-2025-11-13");
5982
- if (tool$1.inputExamples != null || allowedCallers != null) betas.add("advanced-tool-use-2025-11-20");
6255
+ if (tool.inputExamples != null || allowedCallers != null) betas.add("advanced-tool-use-2025-11-20");
5983
6256
  break;
5984
6257
  }
5985
6258
  case "provider":
5986
- switch (tool$1.id) {
6259
+ switch (tool.id) {
5987
6260
  case "anthropic.code_execution_20250522":
5988
6261
  betas.add("code-execution-2025-05-22");
5989
6262
  anthropicTools2.push({
@@ -6004,9 +6277,21 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6004
6277
  anthropicTools2.push({
6005
6278
  name: "computer",
6006
6279
  type: "computer_20250124",
6007
- display_width_px: tool$1.args.displayWidthPx,
6008
- display_height_px: tool$1.args.displayHeightPx,
6009
- display_number: tool$1.args.displayNumber,
6280
+ display_width_px: tool.args.displayWidthPx,
6281
+ display_height_px: tool.args.displayHeightPx,
6282
+ display_number: tool.args.displayNumber,
6283
+ cache_control: void 0
6284
+ });
6285
+ break;
6286
+ case "anthropic.computer_20251124":
6287
+ betas.add("computer-use-2025-11-24");
6288
+ anthropicTools2.push({
6289
+ name: "computer",
6290
+ type: "computer_20251124",
6291
+ display_width_px: tool.args.displayWidthPx,
6292
+ display_height_px: tool.args.displayHeightPx,
6293
+ display_number: tool.args.displayNumber,
6294
+ enable_zoom: tool.args.enableZoom,
6010
6295
  cache_control: void 0
6011
6296
  });
6012
6297
  break;
@@ -6015,9 +6300,9 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6015
6300
  anthropicTools2.push({
6016
6301
  name: "computer",
6017
6302
  type: "computer_20241022",
6018
- display_width_px: tool$1.args.displayWidthPx,
6019
- display_height_px: tool$1.args.displayHeightPx,
6020
- display_number: tool$1.args.displayNumber,
6303
+ display_width_px: tool.args.displayWidthPx,
6304
+ display_height_px: tool.args.displayHeightPx,
6305
+ display_number: tool.args.displayNumber,
6021
6306
  cache_control: void 0
6022
6307
  });
6023
6308
  break;
@@ -6047,7 +6332,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6047
6332
  break;
6048
6333
  case "anthropic.text_editor_20250728": {
6049
6334
  const args = await validateTypes({
6050
- value: tool$1.args,
6335
+ value: tool.args,
6051
6336
  schema: textEditor_20250728ArgsSchema
6052
6337
  });
6053
6338
  anthropicTools2.push({
@@ -6084,7 +6369,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6084
6369
  case "anthropic.web_fetch_20250910": {
6085
6370
  betas.add("web-fetch-2025-09-10");
6086
6371
  const args = await validateTypes({
6087
- value: tool$1.args,
6372
+ value: tool.args,
6088
6373
  schema: webFetch_20250910ArgsSchema
6089
6374
  });
6090
6375
  anthropicTools2.push({
@@ -6101,7 +6386,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6101
6386
  }
6102
6387
  case "anthropic.web_search_20250305": {
6103
6388
  const args = await validateTypes({
6104
- value: tool$1.args,
6389
+ value: tool.args,
6105
6390
  schema: webSearch_20250305ArgsSchema
6106
6391
  });
6107
6392
  anthropicTools2.push({
@@ -6132,7 +6417,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6132
6417
  default:
6133
6418
  toolWarnings.push({
6134
6419
  type: "unsupported",
6135
- feature: `provider-defined tool ${tool$1.id}`
6420
+ feature: `provider-defined tool ${tool.id}`
6136
6421
  });
6137
6422
  break;
6138
6423
  }
@@ -6140,7 +6425,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6140
6425
  default:
6141
6426
  toolWarnings.push({
6142
6427
  type: "unsupported",
6143
- feature: `tool ${tool$1}`
6428
+ feature: `tool ${tool}`
6144
6429
  });
6145
6430
  break;
6146
6431
  }
@@ -6193,11 +6478,11 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
6193
6478
  }
6194
6479
  }
6195
6480
  function convertAnthropicMessagesUsage(usage) {
6196
- var _a$1, _b$1;
6481
+ var _a, _b;
6197
6482
  const inputTokens = usage.input_tokens;
6198
6483
  const outputTokens = usage.output_tokens;
6199
- const cacheCreationTokens = (_a$1 = usage.cache_creation_input_tokens) != null ? _a$1 : 0;
6200
- const cacheReadTokens = (_b$1 = usage.cache_read_input_tokens) != null ? _b$1 : 0;
6484
+ const cacheCreationTokens = (_a = usage.cache_creation_input_tokens) != null ? _a : 0;
6485
+ const cacheReadTokens = (_b = usage.cache_read_input_tokens) != null ? _b : 0;
6201
6486
  return {
6202
6487
  inputTokens: {
6203
6488
  total: inputTokens + cacheCreationTokens + cacheReadTokens,
@@ -6329,7 +6614,8 @@ var factory6 = createProviderToolFactoryWithOutputSchema({
6329
6614
  pattern: z$1.string(),
6330
6615
  limit: z$1.number().optional()
6331
6616
  }))),
6332
- outputSchema: toolSearchRegex_20251119OutputSchema
6617
+ outputSchema: toolSearchRegex_20251119OutputSchema,
6618
+ supportsDeferredResults: true
6333
6619
  });
6334
6620
  var toolSearchRegex_20251119 = (args = {}) => {
6335
6621
  return factory6(args);
@@ -6340,21 +6626,30 @@ function convertToString(data) {
6340
6626
  if (data instanceof URL) throw new UnsupportedFunctionalityError({ functionality: "URL-based text documents are not supported for citations" });
6341
6627
  throw new UnsupportedFunctionalityError({ functionality: `unsupported data type for text documents: ${typeof data}` });
6342
6628
  }
6629
+ function isUrlData(data) {
6630
+ return data instanceof URL || isUrlString(data);
6631
+ }
6632
+ function isUrlString(data) {
6633
+ return typeof data === "string" && /^https?:\/\//i.test(data);
6634
+ }
6635
+ function getUrlString(data) {
6636
+ return data instanceof URL ? data.toString() : data;
6637
+ }
6343
6638
  async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping }) {
6344
- var _a$1, _b$1, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
6639
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
6345
6640
  const betas = /* @__PURE__ */ new Set();
6346
6641
  const blocks = groupIntoBlocks(prompt);
6347
6642
  const validator = cacheControlValidator || new CacheControlValidator();
6348
6643
  let system = void 0;
6349
6644
  const messages = [];
6350
6645
  async function shouldEnableCitations(providerMetadata) {
6351
- var _a2$1, _b2$1;
6646
+ var _a2, _b2;
6352
6647
  const anthropicOptions = await parseProviderOptions({
6353
6648
  provider: "anthropic",
6354
6649
  providerOptions: providerMetadata,
6355
6650
  schema: anthropicFilePartProviderOptions
6356
6651
  });
6357
- return (_b2$1 = (_a2$1 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2$1.enabled) != null ? _b2$1 : false;
6652
+ return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;
6358
6653
  }
6359
6654
  async function getDocumentMetadata(providerMetadata) {
6360
6655
  const anthropicOptions = await parseProviderOptions({
@@ -6392,10 +6687,10 @@ async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warning
6392
6687
  for (let j = 0; j < content.length; j++) {
6393
6688
  const part = content[j];
6394
6689
  const isLastPart = j === content.length - 1;
6395
- const cacheControl = (_a$1 = validator.getCacheControl(part.providerOptions, {
6690
+ const cacheControl = (_a = validator.getCacheControl(part.providerOptions, {
6396
6691
  type: "user message part",
6397
6692
  canCache: true
6398
- })) != null ? _a$1 : isLastPart ? validator.getCacheControl(message.providerOptions, {
6693
+ })) != null ? _a : isLastPart ? validator.getCacheControl(message.providerOptions, {
6399
6694
  type: "user message",
6400
6695
  canCache: true
6401
6696
  }) : void 0;
@@ -6410,9 +6705,9 @@ async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warning
6410
6705
  case "file":
6411
6706
  if (part.mediaType.startsWith("image/")) anthropicContent.push({
6412
6707
  type: "image",
6413
- source: part.data instanceof URL ? {
6708
+ source: isUrlData(part.data) ? {
6414
6709
  type: "url",
6415
- url: part.data.toString()
6710
+ url: getUrlString(part.data)
6416
6711
  } : {
6417
6712
  type: "base64",
6418
6713
  media_type: part.mediaType === "image/*" ? "image/jpeg" : part.mediaType,
@@ -6426,15 +6721,15 @@ async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warning
6426
6721
  const metadata = await getDocumentMetadata(part.providerOptions);
6427
6722
  anthropicContent.push({
6428
6723
  type: "document",
6429
- source: part.data instanceof URL ? {
6724
+ source: isUrlData(part.data) ? {
6430
6725
  type: "url",
6431
- url: part.data.toString()
6726
+ url: getUrlString(part.data)
6432
6727
  } : {
6433
6728
  type: "base64",
6434
6729
  media_type: "application/pdf",
6435
6730
  data: convertToBase64(part.data)
6436
6731
  },
6437
- title: (_b$1 = metadata.title) != null ? _b$1 : part.filename,
6732
+ title: (_b = metadata.title) != null ? _b : part.filename,
6438
6733
  ...metadata.context && { context: metadata.context },
6439
6734
  ...enableCitations && { citations: { enabled: true } },
6440
6735
  cache_control: cacheControl
@@ -6444,9 +6739,9 @@ async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warning
6444
6739
  const metadata = await getDocumentMetadata(part.providerOptions);
6445
6740
  anthropicContent.push({
6446
6741
  type: "document",
6447
- source: part.data instanceof URL ? {
6742
+ source: isUrlData(part.data) ? {
6448
6743
  type: "url",
6449
- url: part.data.toString()
6744
+ url: getUrlString(part.data)
6450
6745
  } : {
6451
6746
  type: "text",
6452
6747
  media_type: "text/plain",
@@ -6539,8 +6834,6 @@ async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warning
6539
6834
  case "execution-denied":
6540
6835
  contentValue = (_e = output.reason) != null ? _e : "Tool execution denied.";
6541
6836
  break;
6542
- case "json":
6543
- case "error-json":
6544
6837
  default:
6545
6838
  contentValue = JSON.stringify(output.value);
6546
6839
  break;
@@ -6814,13 +7107,20 @@ async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warning
6814
7107
  if (providerToolName === "web_fetch") {
6815
7108
  const output = part.output;
6816
7109
  if (output.type === "error-json") {
6817
- const errorValue = JSON.parse(output.value);
7110
+ let errorValue = {};
7111
+ try {
7112
+ if (typeof output.value === "string") errorValue = JSON.parse(output.value);
7113
+ else if (typeof output.value === "object" && output.value !== null) errorValue = output.value;
7114
+ } catch (e) {
7115
+ const extractedErrorCode = (_p = output.value) == null ? void 0 : _p.errorCode;
7116
+ errorValue = { errorCode: typeof extractedErrorCode === "string" ? extractedErrorCode : "unknown" };
7117
+ }
6818
7118
  anthropicContent.push({
6819
7119
  type: "web_fetch_tool_result",
6820
7120
  tool_use_id: part.toolCallId,
6821
7121
  content: {
6822
7122
  type: "web_fetch_tool_result_error",
6823
- error_code: errorValue.errorCode
7123
+ error_code: (_q = errorValue.errorCode) != null ? _q : "unknown"
6824
7124
  },
6825
7125
  cache_control: cacheControl
6826
7126
  });
@@ -7009,7 +7309,18 @@ function mapAnthropicStopReason({ finishReason, isJsonResponseFromTool }) {
7009
7309
  }
7010
7310
  }
7011
7311
  function createCitationSource(citation, citationDocuments, generateId3) {
7012
- var _a$1;
7312
+ var _a;
7313
+ if (citation.type === "web_search_result_location") return {
7314
+ type: "source",
7315
+ sourceType: "url",
7316
+ id: generateId3(),
7317
+ url: citation.url,
7318
+ title: citation.title,
7319
+ providerMetadata: { anthropic: {
7320
+ citedText: citation.cited_text,
7321
+ encryptedIndex: citation.encrypted_index
7322
+ } }
7323
+ };
7013
7324
  if (citation.type !== "page_location" && citation.type !== "char_location") return;
7014
7325
  const documentInfo = citationDocuments[citation.document_index];
7015
7326
  if (!documentInfo) return;
@@ -7018,7 +7329,7 @@ function createCitationSource(citation, citationDocuments, generateId3) {
7018
7329
  sourceType: "document",
7019
7330
  id: generateId3(),
7020
7331
  mediaType: documentInfo.mediaType,
7021
- title: (_a$1 = citation.document_title) != null ? _a$1 : documentInfo.title,
7332
+ title: (_a = citation.document_title) != null ? _a : documentInfo.title,
7022
7333
  filename: documentInfo.filename,
7023
7334
  providerMetadata: { anthropic: citation.type === "page_location" ? {
7024
7335
  citedText: citation.cited_text,
@@ -7034,10 +7345,10 @@ function createCitationSource(citation, citationDocuments, generateId3) {
7034
7345
  var AnthropicMessagesLanguageModel = class {
7035
7346
  constructor(modelId, config) {
7036
7347
  this.specificationVersion = "v3";
7037
- var _a$1;
7348
+ var _a;
7038
7349
  this.modelId = modelId;
7039
7350
  this.config = config;
7040
- this.generateId = (_a$1 = config.generateId) != null ? _a$1 : generateId;
7351
+ this.generateId = (_a = config.generateId) != null ? _a : generateId;
7041
7352
  }
7042
7353
  supportsUrl(url) {
7043
7354
  return url.protocol === "https:";
@@ -7045,12 +7356,21 @@ var AnthropicMessagesLanguageModel = class {
7045
7356
  get provider() {
7046
7357
  return this.config.provider;
7047
7358
  }
7359
+ /**
7360
+ * Extracts the dynamic provider name from the config.provider string.
7361
+ * e.g., 'my-custom-anthropic.messages' -> 'my-custom-anthropic'
7362
+ */
7363
+ get providerOptionsName() {
7364
+ const provider = this.config.provider;
7365
+ const dotIndex = provider.indexOf(".");
7366
+ return dotIndex === -1 ? provider : provider.substring(0, dotIndex);
7367
+ }
7048
7368
  get supportedUrls() {
7049
- var _a$1, _b$1, _c;
7050
- return (_c = (_b$1 = (_a$1 = this.config).supportedUrls) == null ? void 0 : _b$1.call(_a$1)) != null ? _c : {};
7369
+ var _a, _b, _c;
7370
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
7051
7371
  }
7052
7372
  async getArgs({ userSuppliedBetas, prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions, stream }) {
7053
- var _a$1, _b$1, _c, _d, _e, _f;
7373
+ var _a, _b, _c, _d, _e, _f;
7054
7374
  const warnings = [];
7055
7375
  if (frequencyPenalty != null) warnings.push({
7056
7376
  type: "unsupported",
@@ -7086,14 +7406,22 @@ var AnthropicMessagesLanguageModel = class {
7086
7406
  details: "JSON response format requires a schema. The response format is ignored."
7087
7407
  });
7088
7408
  }
7089
- const anthropicOptions = await parseProviderOptions({
7409
+ const providerOptionsName = this.providerOptionsName;
7410
+ const canonicalOptions = await parseProviderOptions({
7090
7411
  provider: "anthropic",
7091
7412
  providerOptions,
7092
7413
  schema: anthropicProviderOptions
7093
7414
  });
7415
+ const customProviderOptions = providerOptionsName !== "anthropic" ? await parseProviderOptions({
7416
+ provider: providerOptionsName,
7417
+ providerOptions,
7418
+ schema: anthropicProviderOptions
7419
+ }) : null;
7420
+ const usedCustomProviderKey = customProviderOptions != null;
7421
+ const anthropicOptions = Object.assign({}, canonicalOptions != null ? canonicalOptions : {}, customProviderOptions != null ? customProviderOptions : {});
7094
7422
  const { maxOutputTokens: maxOutputTokensForModel, supportsStructuredOutput: modelSupportsStructuredOutput, isKnownModel } = getModelCapabilities(this.modelId);
7095
- const supportsStructuredOutput = ((_a$1 = this.config.supportsNativeStructuredOutput) != null ? _a$1 : true) && modelSupportsStructuredOutput;
7096
- const structureOutputMode = (_b$1 = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _b$1 : "auto";
7423
+ const supportsStructuredOutput = ((_a = this.config.supportsNativeStructuredOutput) != null ? _a : true) && modelSupportsStructuredOutput;
7424
+ const structureOutputMode = (_b = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _b : "auto";
7097
7425
  const useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput;
7098
7426
  const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !useStructuredOutput ? {
7099
7427
  type: "function",
@@ -7231,6 +7559,13 @@ var AnthropicMessagesLanguageModel = class {
7231
7559
  });
7232
7560
  }
7233
7561
  baseArgs.max_tokens = maxTokens + (thinkingBudget != null ? thinkingBudget : 0);
7562
+ } else if (topP != null && temperature != null) {
7563
+ warnings.push({
7564
+ type: "unsupported",
7565
+ feature: "topP",
7566
+ details: `topP is not supported when temperature is set. topP is ignored.`
7567
+ });
7568
+ baseArgs.top_p = void 0;
7234
7569
  }
7235
7570
  if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) {
7236
7571
  if (maxOutputTokens != null) warnings.push({
@@ -7246,7 +7581,7 @@ var AnthropicMessagesLanguageModel = class {
7246
7581
  betas.add("code-execution-2025-08-25");
7247
7582
  betas.add("skills-2025-10-02");
7248
7583
  betas.add("files-api-2025-04-14");
7249
- if (!(tools == null ? void 0 : tools.some((tool$1) => tool$1.type === "provider" && tool$1.id === "anthropic.code_execution_20250825"))) warnings.push({
7584
+ if (!(tools == null ? void 0 : tools.some((tool) => tool.type === "provider" && tool.id === "anthropic.code_execution_20250825"))) warnings.push({
7250
7585
  type: "other",
7251
7586
  message: "code execution tool is required when using skills"
7252
7587
  });
@@ -7259,7 +7594,7 @@ var AnthropicMessagesLanguageModel = class {
7259
7594
  toolChoice: { type: "required" },
7260
7595
  disableParallelToolUse: true,
7261
7596
  cacheControlValidator,
7262
- supportsStructuredOutput
7597
+ supportsStructuredOutput: false
7263
7598
  } : {
7264
7599
  tools: tools != null ? tools : [],
7265
7600
  toolChoice,
@@ -7286,53 +7621,55 @@ var AnthropicMessagesLanguageModel = class {
7286
7621
  ...userSuppliedBetas
7287
7622
  ]),
7288
7623
  usesJsonResponseTool: jsonResponseTool != null,
7289
- toolNameMapping
7624
+ toolNameMapping,
7625
+ providerOptionsName,
7626
+ usedCustomProviderKey
7290
7627
  };
7291
7628
  }
7292
7629
  async getHeaders({ betas, headers }) {
7293
7630
  return combineHeaders(await resolve(this.config.headers), headers, betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {});
7294
7631
  }
7295
7632
  async getBetasFromHeaders(requestHeaders) {
7296
- var _a$1, _b$1;
7297
- const configBetaHeader = (_a$1 = (await resolve(this.config.headers))["anthropic-beta"]) != null ? _a$1 : "";
7298
- const requestBetaHeader = (_b$1 = requestHeaders == null ? void 0 : requestHeaders["anthropic-beta"]) != null ? _b$1 : "";
7633
+ var _a, _b;
7634
+ const configBetaHeader = (_a = (await resolve(this.config.headers))["anthropic-beta"]) != null ? _a : "";
7635
+ const requestBetaHeader = (_b = requestHeaders == null ? void 0 : requestHeaders["anthropic-beta"]) != null ? _b : "";
7299
7636
  return new Set([...configBetaHeader.toLowerCase().split(","), ...requestBetaHeader.toLowerCase().split(",")].map((beta) => beta.trim()).filter((beta) => beta !== ""));
7300
7637
  }
7301
7638
  buildRequestUrl(isStreaming) {
7302
- var _a$1, _b$1, _c;
7303
- return (_c = (_b$1 = (_a$1 = this.config).buildRequestUrl) == null ? void 0 : _b$1.call(_a$1, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
7639
+ var _a, _b, _c;
7640
+ return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
7304
7641
  }
7305
7642
  transformRequestBody(args) {
7306
- var _a$1, _b$1, _c;
7307
- return (_c = (_b$1 = (_a$1 = this.config).transformRequestBody) == null ? void 0 : _b$1.call(_a$1, args)) != null ? _c : args;
7643
+ var _a, _b, _c;
7644
+ return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
7308
7645
  }
7309
7646
  extractCitationDocuments(prompt) {
7310
7647
  const isCitationPart = (part) => {
7311
- var _a$1, _b$1;
7648
+ var _a, _b;
7312
7649
  if (part.type !== "file") return false;
7313
7650
  if (part.mediaType !== "application/pdf" && part.mediaType !== "text/plain") return false;
7314
- const anthropic2 = (_a$1 = part.providerOptions) == null ? void 0 : _a$1.anthropic;
7651
+ const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;
7315
7652
  const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;
7316
- return (_b$1 = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b$1 : false;
7653
+ return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;
7317
7654
  };
7318
7655
  return prompt.filter((message) => message.role === "user").flatMap((message) => message.content).filter(isCitationPart).map((part) => {
7319
- var _a$1;
7656
+ var _a;
7320
7657
  const filePart = part;
7321
7658
  return {
7322
- title: (_a$1 = filePart.filename) != null ? _a$1 : "Untitled Document",
7659
+ title: (_a = filePart.filename) != null ? _a : "Untitled Document",
7323
7660
  filename: filePart.filename,
7324
7661
  mediaType: filePart.mediaType
7325
7662
  };
7326
7663
  });
7327
7664
  }
7328
7665
  async doGenerate(options) {
7329
- var _a$1, _b$1, _c, _d, _e, _f, _g, _h, _i, _j;
7330
- const { args, warnings, betas, usesJsonResponseTool, toolNameMapping } = await this.getArgs({
7666
+ var _a, _b, _c, _d, _e, _f;
7667
+ const { args, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
7331
7668
  ...options,
7332
7669
  stream: false,
7333
7670
  userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
7334
7671
  });
7335
- const citationDocuments = this.extractCitationDocuments(options.prompt);
7672
+ const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
7336
7673
  const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
7337
7674
  url: this.buildRequestUrl(false),
7338
7675
  headers: await this.getHeaders({
@@ -7347,6 +7684,7 @@ var AnthropicMessagesLanguageModel = class {
7347
7684
  });
7348
7685
  const content = [];
7349
7686
  const mcpToolCalls = {};
7687
+ const serverToolCalls = {};
7350
7688
  let isJsonResponseFromTool = false;
7351
7689
  for (const part of response.content) switch (part.type) {
7352
7690
  case "text":
@@ -7420,13 +7758,16 @@ var AnthropicMessagesLanguageModel = class {
7420
7758
  input: JSON.stringify(inputToSerialize),
7421
7759
  providerExecuted: true
7422
7760
  });
7423
- } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") content.push({
7424
- type: "tool-call",
7425
- toolCallId: part.id,
7426
- toolName: toolNameMapping.toCustomToolName(part.name),
7427
- input: JSON.stringify(part.input),
7428
- providerExecuted: true
7429
- });
7761
+ } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") {
7762
+ serverToolCalls[part.id] = part.name;
7763
+ content.push({
7764
+ type: "tool-call",
7765
+ toolCallId: part.id,
7766
+ toolName: toolNameMapping.toCustomToolName(part.name),
7767
+ input: JSON.stringify(part.input),
7768
+ providerExecuted: true
7769
+ });
7770
+ }
7430
7771
  break;
7431
7772
  case "mcp_tool_use":
7432
7773
  mcpToolCalls[part.id] = {
@@ -7455,27 +7796,32 @@ var AnthropicMessagesLanguageModel = class {
7455
7796
  });
7456
7797
  break;
7457
7798
  case "web_fetch_tool_result":
7458
- if (part.content.type === "web_fetch_result") content.push({
7459
- type: "tool-result",
7460
- toolCallId: part.tool_use_id,
7461
- toolName: toolNameMapping.toCustomToolName("web_fetch"),
7462
- result: {
7463
- type: "web_fetch_result",
7464
- url: part.content.url,
7465
- retrievedAt: part.content.retrieved_at,
7466
- content: {
7467
- type: part.content.content.type,
7468
- title: part.content.content.title,
7469
- citations: part.content.content.citations,
7470
- source: {
7471
- type: part.content.content.source.type,
7472
- mediaType: part.content.content.source.media_type,
7473
- data: part.content.content.source.data
7474
- }
7475
- }
7476
- }
7477
- });
7478
- else if (part.content.type === "web_fetch_tool_result_error") content.push({
7799
+ if (part.content.type === "web_fetch_result") {
7800
+ citationDocuments.push({
7801
+ title: (_a = part.content.content.title) != null ? _a : part.content.url,
7802
+ mediaType: part.content.content.source.media_type
7803
+ });
7804
+ content.push({
7805
+ type: "tool-result",
7806
+ toolCallId: part.tool_use_id,
7807
+ toolName: toolNameMapping.toCustomToolName("web_fetch"),
7808
+ result: {
7809
+ type: "web_fetch_result",
7810
+ url: part.content.url,
7811
+ retrievedAt: part.content.retrieved_at,
7812
+ content: {
7813
+ type: part.content.content.type,
7814
+ title: part.content.content.title,
7815
+ citations: part.content.content.citations,
7816
+ source: {
7817
+ type: part.content.content.source.type,
7818
+ mediaType: part.content.content.source.media_type,
7819
+ data: part.content.content.source.data
7820
+ }
7821
+ }
7822
+ }
7823
+ });
7824
+ } else if (part.content.type === "web_fetch_tool_result_error") content.push({
7479
7825
  type: "tool-result",
7480
7826
  toolCallId: part.tool_use_id,
7481
7827
  toolName: toolNameMapping.toCustomToolName("web_fetch"),
@@ -7493,11 +7839,11 @@ var AnthropicMessagesLanguageModel = class {
7493
7839
  toolCallId: part.tool_use_id,
7494
7840
  toolName: toolNameMapping.toCustomToolName("web_search"),
7495
7841
  result: part.content.map((result) => {
7496
- var _a2$1;
7842
+ var _a2;
7497
7843
  return {
7498
7844
  url: result.url,
7499
7845
  title: result.title,
7500
- pageAge: (_a2$1 = result.page_age) != null ? _a2$1 : null,
7846
+ pageAge: (_a2 = result.page_age) != null ? _a2 : null,
7501
7847
  encryptedContent: result.encrypted_content,
7502
7848
  type: result.type
7503
7849
  };
@@ -7509,7 +7855,7 @@ var AnthropicMessagesLanguageModel = class {
7509
7855
  id: this.generateId(),
7510
7856
  url: result.url,
7511
7857
  title: result.title,
7512
- providerMetadata: { anthropic: { pageAge: (_a$1 = result.page_age) != null ? _a$1 : null } }
7858
+ providerMetadata: { anthropic: { pageAge: (_b = result.page_age) != null ? _b : null } }
7513
7859
  });
7514
7860
  } else content.push({
7515
7861
  type: "tool-result",
@@ -7532,7 +7878,7 @@ var AnthropicMessagesLanguageModel = class {
7532
7878
  stdout: part.content.stdout,
7533
7879
  stderr: part.content.stderr,
7534
7880
  return_code: part.content.return_code,
7535
- content: (_b$1 = part.content.content) != null ? _b$1 : []
7881
+ content: (_c = part.content.content) != null ? _c : []
7536
7882
  }
7537
7883
  });
7538
7884
  else if (part.content.type === "code_execution_tool_result_error") content.push({
@@ -7555,11 +7901,19 @@ var AnthropicMessagesLanguageModel = class {
7555
7901
  result: part.content
7556
7902
  });
7557
7903
  break;
7558
- case "tool_search_tool_result":
7904
+ case "tool_search_tool_result": {
7905
+ let providerToolName = serverToolCalls[part.tool_use_id];
7906
+ if (providerToolName == null) {
7907
+ const bm25CustomName = toolNameMapping.toCustomToolName("tool_search_tool_bm25");
7908
+ const regexCustomName = toolNameMapping.toCustomToolName("tool_search_tool_regex");
7909
+ if (bm25CustomName !== "tool_search_tool_bm25") providerToolName = "tool_search_tool_bm25";
7910
+ else if (regexCustomName !== "tool_search_tool_regex") providerToolName = "tool_search_tool_regex";
7911
+ else providerToolName = "tool_search_tool_regex";
7912
+ }
7559
7913
  if (part.content.type === "tool_search_tool_search_result") content.push({
7560
7914
  type: "tool-result",
7561
7915
  toolCallId: part.tool_use_id,
7562
- toolName: toolNameMapping.toCustomToolName("tool_search"),
7916
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
7563
7917
  result: part.content.tool_references.map((ref) => ({
7564
7918
  type: ref.type,
7565
7919
  toolName: ref.tool_name
@@ -7568,7 +7922,7 @@ var AnthropicMessagesLanguageModel = class {
7568
7922
  else content.push({
7569
7923
  type: "tool-result",
7570
7924
  toolCallId: part.tool_use_id,
7571
- toolName: toolNameMapping.toCustomToolName("tool_search"),
7925
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
7572
7926
  isError: true,
7573
7927
  result: {
7574
7928
  type: "tool_search_tool_result_error",
@@ -7576,6 +7930,7 @@ var AnthropicMessagesLanguageModel = class {
7576
7930
  }
7577
7931
  });
7578
7932
  break;
7933
+ }
7579
7934
  }
7580
7935
  return {
7581
7936
  content,
@@ -7584,42 +7939,48 @@ var AnthropicMessagesLanguageModel = class {
7584
7939
  finishReason: response.stop_reason,
7585
7940
  isJsonResponseFromTool
7586
7941
  }),
7587
- raw: (_c = response.stop_reason) != null ? _c : void 0
7942
+ raw: (_d = response.stop_reason) != null ? _d : void 0
7588
7943
  },
7589
7944
  usage: convertAnthropicMessagesUsage(response.usage),
7590
7945
  request: { body: args },
7591
7946
  response: {
7592
- id: (_d = response.id) != null ? _d : void 0,
7593
- modelId: (_e = response.model) != null ? _e : void 0,
7947
+ id: (_e = response.id) != null ? _e : void 0,
7948
+ modelId: (_f = response.model) != null ? _f : void 0,
7594
7949
  headers: responseHeaders,
7595
7950
  body: rawResponse
7596
7951
  },
7597
7952
  warnings,
7598
- providerMetadata: { anthropic: {
7599
- usage: response.usage,
7600
- cacheCreationInputTokens: (_f = response.usage.cache_creation_input_tokens) != null ? _f : null,
7601
- stopSequence: (_g = response.stop_sequence) != null ? _g : null,
7602
- container: response.container ? {
7603
- expiresAt: response.container.expires_at,
7604
- id: response.container.id,
7605
- skills: (_i = (_h = response.container.skills) == null ? void 0 : _h.map((skill) => ({
7606
- type: skill.type,
7607
- skillId: skill.skill_id,
7608
- version: skill.version
7609
- }))) != null ? _i : null
7610
- } : null,
7611
- contextManagement: (_j = mapAnthropicResponseContextManagement(response.context_management)) != null ? _j : null
7612
- } }
7953
+ providerMetadata: (() => {
7954
+ var _a2, _b2, _c2, _d2, _e2;
7955
+ const anthropicMetadata = {
7956
+ usage: response.usage,
7957
+ cacheCreationInputTokens: (_a2 = response.usage.cache_creation_input_tokens) != null ? _a2 : null,
7958
+ stopSequence: (_b2 = response.stop_sequence) != null ? _b2 : null,
7959
+ container: response.container ? {
7960
+ expiresAt: response.container.expires_at,
7961
+ id: response.container.id,
7962
+ skills: (_d2 = (_c2 = response.container.skills) == null ? void 0 : _c2.map((skill) => ({
7963
+ type: skill.type,
7964
+ skillId: skill.skill_id,
7965
+ version: skill.version
7966
+ }))) != null ? _d2 : null
7967
+ } : null,
7968
+ contextManagement: (_e2 = mapAnthropicResponseContextManagement(response.context_management)) != null ? _e2 : null
7969
+ };
7970
+ const providerMetadata = { anthropic: anthropicMetadata };
7971
+ if (usedCustomProviderKey && providerOptionsName !== "anthropic") providerMetadata[providerOptionsName] = anthropicMetadata;
7972
+ return providerMetadata;
7973
+ })()
7613
7974
  };
7614
7975
  }
7615
7976
  async doStream(options) {
7616
- var _a$1, _b$1;
7617
- const { args: body, warnings, betas, usesJsonResponseTool, toolNameMapping } = await this.getArgs({
7977
+ var _a, _b;
7978
+ const { args: body, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
7618
7979
  ...options,
7619
7980
  stream: true,
7620
7981
  userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
7621
7982
  });
7622
- const citationDocuments = this.extractCitationDocuments(options.prompt);
7983
+ const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
7623
7984
  const url = this.buildRequestUrl(true);
7624
7985
  const { responseHeaders, value: response } = await postJsonToApi({
7625
7986
  url,
@@ -7645,6 +8006,7 @@ var AnthropicMessagesLanguageModel = class {
7645
8006
  };
7646
8007
  const contentBlocks = {};
7647
8008
  const mcpToolCalls = {};
8009
+ const serverToolCalls = {};
7648
8010
  let contextManagement = null;
7649
8011
  let rawUsage = void 0;
7650
8012
  let cacheCreationInputTokens = null;
@@ -7661,7 +8023,7 @@ var AnthropicMessagesLanguageModel = class {
7661
8023
  });
7662
8024
  },
7663
8025
  transform(chunk, controller) {
7664
- var _a2$1, _b2$1, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
8026
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
7665
8027
  if (options.includeRawChunks) controller.enqueue({
7666
8028
  type: "raw",
7667
8029
  rawValue: chunk.rawValue
@@ -7760,6 +8122,7 @@ var AnthropicMessagesLanguageModel = class {
7760
8122
  providerExecuted: true
7761
8123
  });
7762
8124
  } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") {
8125
+ serverToolCalls[part.id] = part.name;
7763
8126
  const customToolName = toolNameMapping.toCustomToolName(part.name);
7764
8127
  contentBlocks[value.index] = {
7765
8128
  type: "tool-call",
@@ -7779,27 +8142,32 @@ var AnthropicMessagesLanguageModel = class {
7779
8142
  }
7780
8143
  return;
7781
8144
  case "web_fetch_tool_result":
7782
- if (part.content.type === "web_fetch_result") controller.enqueue({
7783
- type: "tool-result",
7784
- toolCallId: part.tool_use_id,
7785
- toolName: toolNameMapping.toCustomToolName("web_fetch"),
7786
- result: {
7787
- type: "web_fetch_result",
7788
- url: part.content.url,
7789
- retrievedAt: part.content.retrieved_at,
7790
- content: {
7791
- type: part.content.content.type,
7792
- title: part.content.content.title,
7793
- citations: part.content.content.citations,
7794
- source: {
7795
- type: part.content.content.source.type,
7796
- mediaType: part.content.content.source.media_type,
7797
- data: part.content.content.source.data
8145
+ if (part.content.type === "web_fetch_result") {
8146
+ citationDocuments.push({
8147
+ title: (_a2 = part.content.content.title) != null ? _a2 : part.content.url,
8148
+ mediaType: part.content.content.source.media_type
8149
+ });
8150
+ controller.enqueue({
8151
+ type: "tool-result",
8152
+ toolCallId: part.tool_use_id,
8153
+ toolName: toolNameMapping.toCustomToolName("web_fetch"),
8154
+ result: {
8155
+ type: "web_fetch_result",
8156
+ url: part.content.url,
8157
+ retrievedAt: part.content.retrieved_at,
8158
+ content: {
8159
+ type: part.content.content.type,
8160
+ title: part.content.content.title,
8161
+ citations: part.content.content.citations,
8162
+ source: {
8163
+ type: part.content.content.source.type,
8164
+ mediaType: part.content.content.source.media_type,
8165
+ data: part.content.content.source.data
8166
+ }
7798
8167
  }
7799
8168
  }
7800
- }
7801
- });
7802
- else if (part.content.type === "web_fetch_tool_result_error") controller.enqueue({
8169
+ });
8170
+ } else if (part.content.type === "web_fetch_tool_result_error") controller.enqueue({
7803
8171
  type: "tool-result",
7804
8172
  toolCallId: part.tool_use_id,
7805
8173
  toolName: toolNameMapping.toCustomToolName("web_fetch"),
@@ -7817,11 +8185,11 @@ var AnthropicMessagesLanguageModel = class {
7817
8185
  toolCallId: part.tool_use_id,
7818
8186
  toolName: toolNameMapping.toCustomToolName("web_search"),
7819
8187
  result: part.content.map((result) => {
7820
- var _a3$1;
8188
+ var _a3;
7821
8189
  return {
7822
8190
  url: result.url,
7823
8191
  title: result.title,
7824
- pageAge: (_a3$1 = result.page_age) != null ? _a3$1 : null,
8192
+ pageAge: (_a3 = result.page_age) != null ? _a3 : null,
7825
8193
  encryptedContent: result.encrypted_content,
7826
8194
  type: result.type
7827
8195
  };
@@ -7833,7 +8201,7 @@ var AnthropicMessagesLanguageModel = class {
7833
8201
  id: generateId3(),
7834
8202
  url: result.url,
7835
8203
  title: result.title,
7836
- providerMetadata: { anthropic: { pageAge: (_a2$1 = result.page_age) != null ? _a2$1 : null } }
8204
+ providerMetadata: { anthropic: { pageAge: (_b2 = result.page_age) != null ? _b2 : null } }
7837
8205
  });
7838
8206
  } else controller.enqueue({
7839
8207
  type: "tool-result",
@@ -7856,7 +8224,7 @@ var AnthropicMessagesLanguageModel = class {
7856
8224
  stdout: part.content.stdout,
7857
8225
  stderr: part.content.stderr,
7858
8226
  return_code: part.content.return_code,
7859
- content: (_b2$1 = part.content.content) != null ? _b2$1 : []
8227
+ content: (_c = part.content.content) != null ? _c : []
7860
8228
  }
7861
8229
  });
7862
8230
  else if (part.content.type === "code_execution_tool_result_error") controller.enqueue({
@@ -7879,11 +8247,19 @@ var AnthropicMessagesLanguageModel = class {
7879
8247
  result: part.content
7880
8248
  });
7881
8249
  return;
7882
- case "tool_search_tool_result":
8250
+ case "tool_search_tool_result": {
8251
+ let providerToolName = serverToolCalls[part.tool_use_id];
8252
+ if (providerToolName == null) {
8253
+ const bm25CustomName = toolNameMapping.toCustomToolName("tool_search_tool_bm25");
8254
+ const regexCustomName = toolNameMapping.toCustomToolName("tool_search_tool_regex");
8255
+ if (bm25CustomName !== "tool_search_tool_bm25") providerToolName = "tool_search_tool_bm25";
8256
+ else if (regexCustomName !== "tool_search_tool_regex") providerToolName = "tool_search_tool_regex";
8257
+ else providerToolName = "tool_search_tool_regex";
8258
+ }
7883
8259
  if (part.content.type === "tool_search_tool_search_result") controller.enqueue({
7884
8260
  type: "tool-result",
7885
8261
  toolCallId: part.tool_use_id,
7886
- toolName: toolNameMapping.toCustomToolName("tool_search"),
8262
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
7887
8263
  result: part.content.tool_references.map((ref) => ({
7888
8264
  type: ref.type,
7889
8265
  toolName: ref.tool_name
@@ -7892,7 +8268,7 @@ var AnthropicMessagesLanguageModel = class {
7892
8268
  else controller.enqueue({
7893
8269
  type: "tool-result",
7894
8270
  toolCallId: part.tool_use_id,
7895
- toolName: toolNameMapping.toCustomToolName("tool_search"),
8271
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
7896
8272
  isError: true,
7897
8273
  result: {
7898
8274
  type: "tool_search_tool_result_error",
@@ -7900,6 +8276,7 @@ var AnthropicMessagesLanguageModel = class {
7900
8276
  }
7901
8277
  });
7902
8278
  return;
8279
+ }
7903
8280
  case "mcp_tool_use":
7904
8281
  mcpToolCalls[part.id] = {
7905
8282
  type: "tool-call",
@@ -8041,10 +8418,10 @@ var AnthropicMessagesLanguageModel = class {
8041
8418
  }
8042
8419
  case "message_start":
8043
8420
  usage.input_tokens = value.message.usage.input_tokens;
8044
- usage.cache_read_input_tokens = (_c = value.message.usage.cache_read_input_tokens) != null ? _c : 0;
8045
- usage.cache_creation_input_tokens = (_d = value.message.usage.cache_creation_input_tokens) != null ? _d : 0;
8421
+ usage.cache_read_input_tokens = (_d = value.message.usage.cache_read_input_tokens) != null ? _d : 0;
8422
+ usage.cache_creation_input_tokens = (_e = value.message.usage.cache_creation_input_tokens) != null ? _e : 0;
8046
8423
  rawUsage = { ...value.message.usage };
8047
- cacheCreationInputTokens = (_e = value.message.usage.cache_creation_input_tokens) != null ? _e : null;
8424
+ cacheCreationInputTokens = (_f = value.message.usage.cache_creation_input_tokens) != null ? _f : null;
8048
8425
  if (value.message.container != null) container = {
8049
8426
  expiresAt: value.message.container.expires_at,
8050
8427
  id: value.message.container.id,
@@ -8059,8 +8436,8 @@ var AnthropicMessagesLanguageModel = class {
8059
8436
  };
8060
8437
  controller.enqueue({
8061
8438
  type: "response-metadata",
8062
- id: (_f = value.message.id) != null ? _f : void 0,
8063
- modelId: (_g = value.message.model) != null ? _g : void 0
8439
+ id: (_g = value.message.id) != null ? _g : void 0,
8440
+ modelId: (_h = value.message.model) != null ? _h : void 0
8064
8441
  });
8065
8442
  if (value.message.content != null) for (let contentIndex = 0; contentIndex < value.message.content.length; contentIndex++) {
8066
8443
  const part = value.message.content[contentIndex];
@@ -8075,7 +8452,7 @@ var AnthropicMessagesLanguageModel = class {
8075
8452
  id: part.id,
8076
8453
  toolName: part.name
8077
8454
  });
8078
- const inputStr = JSON.stringify((_h = part.input) != null ? _h : {});
8455
+ const inputStr = JSON.stringify((_i = part.input) != null ? _i : {});
8079
8456
  controller.enqueue({
8080
8457
  type: "tool-input-delta",
8081
8458
  id: part.id,
@@ -8096,44 +8473,54 @@ var AnthropicMessagesLanguageModel = class {
8096
8473
  }
8097
8474
  return;
8098
8475
  case "message_delta":
8476
+ if (value.usage.input_tokens != null && usage.input_tokens !== value.usage.input_tokens) usage.input_tokens = value.usage.input_tokens;
8099
8477
  usage.output_tokens = value.usage.output_tokens;
8478
+ if (value.usage.cache_read_input_tokens != null) usage.cache_read_input_tokens = value.usage.cache_read_input_tokens;
8479
+ if (value.usage.cache_creation_input_tokens != null) {
8480
+ usage.cache_creation_input_tokens = value.usage.cache_creation_input_tokens;
8481
+ cacheCreationInputTokens = value.usage.cache_creation_input_tokens;
8482
+ }
8100
8483
  finishReason = {
8101
8484
  unified: mapAnthropicStopReason({
8102
8485
  finishReason: value.delta.stop_reason,
8103
8486
  isJsonResponseFromTool
8104
8487
  }),
8105
- raw: (_i = value.delta.stop_reason) != null ? _i : void 0
8488
+ raw: (_j = value.delta.stop_reason) != null ? _j : void 0
8106
8489
  };
8107
- stopSequence = (_j = value.delta.stop_sequence) != null ? _j : null;
8490
+ stopSequence = (_k = value.delta.stop_sequence) != null ? _k : null;
8108
8491
  container = value.delta.container != null ? {
8109
8492
  expiresAt: value.delta.container.expires_at,
8110
8493
  id: value.delta.container.id,
8111
- skills: (_l = (_k = value.delta.container.skills) == null ? void 0 : _k.map((skill) => ({
8494
+ skills: (_m = (_l = value.delta.container.skills) == null ? void 0 : _l.map((skill) => ({
8112
8495
  type: skill.type,
8113
8496
  skillId: skill.skill_id,
8114
8497
  version: skill.version
8115
- }))) != null ? _l : null
8498
+ }))) != null ? _m : null
8116
8499
  } : null;
8117
- if (value.delta.context_management) contextManagement = mapAnthropicResponseContextManagement(value.delta.context_management);
8500
+ if (value.context_management) contextManagement = mapAnthropicResponseContextManagement(value.context_management);
8118
8501
  rawUsage = {
8119
8502
  ...rawUsage,
8120
8503
  ...value.usage
8121
8504
  };
8122
8505
  return;
8123
- case "message_stop":
8506
+ case "message_stop": {
8507
+ const anthropicMetadata = {
8508
+ usage: rawUsage != null ? rawUsage : null,
8509
+ cacheCreationInputTokens,
8510
+ stopSequence,
8511
+ container,
8512
+ contextManagement
8513
+ };
8514
+ const providerMetadata = { anthropic: anthropicMetadata };
8515
+ if (usedCustomProviderKey && providerOptionsName !== "anthropic") providerMetadata[providerOptionsName] = anthropicMetadata;
8124
8516
  controller.enqueue({
8125
8517
  type: "finish",
8126
8518
  finishReason,
8127
8519
  usage: convertAnthropicMessagesUsage(usage),
8128
- providerMetadata: { anthropic: {
8129
- usage: rawUsage != null ? rawUsage : null,
8130
- cacheCreationInputTokens,
8131
- stopSequence,
8132
- container,
8133
- contextManagement
8134
- } }
8520
+ providerMetadata
8135
8521
  });
8136
8522
  return;
8523
+ }
8137
8524
  case "error":
8138
8525
  controller.enqueue({
8139
8526
  type: "error",
@@ -8151,8 +8538,8 @@ var AnthropicMessagesLanguageModel = class {
8151
8538
  try {
8152
8539
  await firstChunkReader.read();
8153
8540
  let result = await firstChunkReader.read();
8154
- if (((_a$1 = result.value) == null ? void 0 : _a$1.type) === "raw") result = await firstChunkReader.read();
8155
- if (((_b$1 = result.value) == null ? void 0 : _b$1.type) === "error") {
8541
+ if (((_a = result.value) == null ? void 0 : _a.type) === "raw") result = await firstChunkReader.read();
8542
+ if (((_b = result.value) == null ? void 0 : _b.type) === "error") {
8156
8543
  const error = result.value.error;
8157
8544
  throw new APICallError({
8158
8545
  message: error.message,
@@ -8176,7 +8563,7 @@ var AnthropicMessagesLanguageModel = class {
8176
8563
  }
8177
8564
  };
8178
8565
  function getModelCapabilities(modelId) {
8179
- if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5")) return {
8566
+ if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5") || modelId.includes("claude-haiku-4-5")) return {
8180
8567
  maxOutputTokens: 64e3,
8181
8568
  supportsStructuredOutput: true,
8182
8569
  isKnownModel: true
@@ -8186,7 +8573,7 @@ function getModelCapabilities(modelId) {
8186
8573
  supportsStructuredOutput: true,
8187
8574
  isKnownModel: true
8188
8575
  };
8189
- else if (modelId.includes("claude-sonnet-4-") || modelId.includes("claude-3-7-sonnet") || modelId.includes("claude-haiku-4-5")) return {
8576
+ else if (modelId.includes("claude-sonnet-4-") || modelId.includes("claude-3-7-sonnet")) return {
8190
8577
  maxOutputTokens: 64e3,
8191
8578
  supportsStructuredOutput: false,
8192
8579
  isKnownModel: true
@@ -8295,6 +8682,47 @@ var computer_20250124 = createProviderToolFactory({
8295
8682
  text: z$1.string().optional()
8296
8683
  })))
8297
8684
  });
8685
+ var computer_20251124 = createProviderToolFactory({
8686
+ id: "anthropic.computer_20251124",
8687
+ inputSchema: lazySchema(() => zodSchema$1(z$1.object({
8688
+ action: z$1.enum([
8689
+ "key",
8690
+ "hold_key",
8691
+ "type",
8692
+ "cursor_position",
8693
+ "mouse_move",
8694
+ "left_mouse_down",
8695
+ "left_mouse_up",
8696
+ "left_click",
8697
+ "left_click_drag",
8698
+ "right_click",
8699
+ "middle_click",
8700
+ "double_click",
8701
+ "triple_click",
8702
+ "scroll",
8703
+ "wait",
8704
+ "screenshot",
8705
+ "zoom"
8706
+ ]),
8707
+ coordinate: z$1.tuple([z$1.number().int(), z$1.number().int()]).optional(),
8708
+ duration: z$1.number().optional(),
8709
+ region: z$1.tuple([
8710
+ z$1.number().int(),
8711
+ z$1.number().int(),
8712
+ z$1.number().int(),
8713
+ z$1.number().int()
8714
+ ]).optional(),
8715
+ scroll_amount: z$1.number().optional(),
8716
+ scroll_direction: z$1.enum([
8717
+ "up",
8718
+ "down",
8719
+ "left",
8720
+ "right"
8721
+ ]).optional(),
8722
+ start_coordinate: z$1.tuple([z$1.number().int(), z$1.number().int()]).optional(),
8723
+ text: z$1.string().optional()
8724
+ })))
8725
+ });
8298
8726
  var memory_20250818 = createProviderToolFactory({
8299
8727
  id: "anthropic.memory_20250818",
8300
8728
  inputSchema: lazySchema(() => zodSchema$1(z$1.discriminatedUnion("command", [
@@ -8345,6 +8773,7 @@ var textEditor_20241022 = createProviderToolFactory({
8345
8773
  file_text: z$1.string().optional(),
8346
8774
  insert_line: z$1.number().int().optional(),
8347
8775
  new_str: z$1.string().optional(),
8776
+ insert_text: z$1.string().optional(),
8348
8777
  old_str: z$1.string().optional(),
8349
8778
  view_range: z$1.array(z$1.number().int()).optional()
8350
8779
  })))
@@ -8363,6 +8792,7 @@ var textEditor_20250124 = createProviderToolFactory({
8363
8792
  file_text: z$1.string().optional(),
8364
8793
  insert_line: z$1.number().int().optional(),
8365
8794
  new_str: z$1.string().optional(),
8795
+ insert_text: z$1.string().optional(),
8366
8796
  old_str: z$1.string().optional(),
8367
8797
  view_range: z$1.array(z$1.number().int()).optional()
8368
8798
  })))
@@ -8380,6 +8810,7 @@ var textEditor_20250429 = createProviderToolFactory({
8380
8810
  file_text: z$1.string().optional(),
8381
8811
  insert_line: z$1.number().int().optional(),
8382
8812
  new_str: z$1.string().optional(),
8813
+ insert_text: z$1.string().optional(),
8383
8814
  old_str: z$1.string().optional(),
8384
8815
  view_range: z$1.array(z$1.number().int()).optional()
8385
8816
  })))
@@ -8394,7 +8825,8 @@ var factory7 = createProviderToolFactoryWithOutputSchema({
8394
8825
  query: z$1.string(),
8395
8826
  limit: z$1.number().optional()
8396
8827
  }))),
8397
- outputSchema: toolSearchBm25_20251119OutputSchema
8828
+ outputSchema: toolSearchBm25_20251119OutputSchema,
8829
+ supportsDeferredResults: true
8398
8830
  });
8399
8831
  var toolSearchBm25_20251119 = (args = {}) => {
8400
8832
  return factory7(args);
@@ -8406,6 +8838,7 @@ var anthropicTools = {
8406
8838
  codeExecution_20250825,
8407
8839
  computer_20241022,
8408
8840
  computer_20250124,
8841
+ computer_20251124,
8409
8842
  memory_20250818,
8410
8843
  textEditor_20241022,
8411
8844
  textEditor_20250124,
@@ -8417,30 +8850,40 @@ var anthropicTools = {
8417
8850
  toolSearchBm25_20251119
8418
8851
  };
8419
8852
  function createAnthropic(options = {}) {
8420
- var _a$1, _b$1;
8421
- const baseURL = (_a$1 = withoutTrailingSlash(loadOptionalSetting({
8853
+ var _a, _b;
8854
+ const baseURL = (_a = withoutTrailingSlash(loadOptionalSetting({
8422
8855
  settingValue: options.baseURL,
8423
8856
  environmentVariableName: "ANTHROPIC_BASE_URL"
8424
- }))) != null ? _a$1 : "https://api.anthropic.com/v1";
8425
- const providerName = (_b$1 = options.name) != null ? _b$1 : "anthropic.messages";
8426
- const getHeaders = () => withUserAgentSuffix({
8427
- "anthropic-version": "2023-06-01",
8428
- "x-api-key": loadApiKey({
8857
+ }))) != null ? _a : "https://api.anthropic.com/v1";
8858
+ const providerName = (_b = options.name) != null ? _b : "anthropic.messages";
8859
+ if (options.apiKey && options.authToken) throw new InvalidArgumentError({
8860
+ argument: "apiKey/authToken",
8861
+ message: "Both apiKey and authToken were provided. Please use only one authentication method."
8862
+ });
8863
+ const getHeaders = () => {
8864
+ const authHeaders = options.authToken ? { Authorization: `Bearer ${options.authToken}` } : { "x-api-key": loadApiKey({
8429
8865
  apiKey: options.apiKey,
8430
8866
  environmentVariableName: "ANTHROPIC_API_KEY",
8431
8867
  description: "Anthropic"
8432
- }),
8433
- ...options.headers
8434
- }, `ai-sdk/anthropic/${VERSION$1}`);
8868
+ }) };
8869
+ return withUserAgentSuffix({
8870
+ "anthropic-version": "2023-06-01",
8871
+ ...authHeaders,
8872
+ ...options.headers
8873
+ }, `ai-sdk/anthropic/${VERSION$1}`);
8874
+ };
8435
8875
  const createChatModel = (modelId) => {
8436
- var _a2$1;
8876
+ var _a2;
8437
8877
  return new AnthropicMessagesLanguageModel(modelId, {
8438
8878
  provider: providerName,
8439
8879
  baseURL,
8440
8880
  headers: getHeaders,
8441
8881
  fetch: options.fetch,
8442
- generateId: (_a2$1 = options.generateId) != null ? _a2$1 : generateId,
8443
- supportedUrls: () => ({ "image/*": [/^https?:\/\/.*$/] })
8882
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
8883
+ supportedUrls: () => ({
8884
+ "image/*": [/^https?:\/\/.*$/],
8885
+ "application/pdf": [/^https?:\/\/.*$/]
8886
+ })
8444
8887
  });
8445
8888
  };
8446
8889
  const provider = function(modelId) {
@@ -8725,10 +9168,13 @@ var LiveAgent = class {
8725
9168
  ...this.webSearchTools,
8726
9169
  ...this.additionalTools
8727
9170
  };
8728
- const tools = wrapToolsWithCallbacks(rawTools, this.callbacks);
9171
+ const tools = wrapToolsWithCallbacks(rawTools, this.callbacks, this.provider);
8729
9172
  const modelId = this.model.modelId ?? "unknown";
8730
9173
  if (this.callbacks?.onLlmCallStart) try {
8731
- this.callbacks.onLlmCallStart({ model: modelId });
9174
+ this.callbacks.onLlmCallStart({
9175
+ model: modelId,
9176
+ executionId: "0-serial"
9177
+ });
8732
9178
  } catch {}
8733
9179
  const result = await generateText({
8734
9180
  model: this.model,
@@ -8741,22 +9187,41 @@ var LiveAgent = class {
8741
9187
  this.callbacks.onLlmCallEnd({
8742
9188
  model: modelId,
8743
9189
  inputTokens: result.usage?.inputTokens ?? 0,
8744
- outputTokens: result.usage?.outputTokens ?? 0
9190
+ outputTokens: result.usage?.outputTokens ?? 0,
9191
+ executionId: "0-serial"
8745
9192
  });
8746
9193
  } catch {}
8747
9194
  const patches = [];
8748
9195
  const toolCallCounts = /* @__PURE__ */ new Map();
9196
+ const executionId = "0-serial";
8749
9197
  for (const step of result.steps) for (const toolCall of step.toolCalls) {
8750
9198
  const count = toolCallCounts.get(toolCall.toolName) ?? 0;
8751
9199
  toolCallCounts.set(toolCall.toolName, count + 1);
8752
9200
  if (toolCall.toolName === FILL_FORM_TOOL_NAME && "input" in toolCall) {
8753
9201
  const input = toolCall.input;
9202
+ const startTime = Date.now();
9203
+ if (this.callbacks?.onToolStart) try {
9204
+ this.callbacks.onToolStart({
9205
+ name: FILL_FORM_TOOL_NAME,
9206
+ input,
9207
+ executionId
9208
+ });
9209
+ } catch {}
8754
9210
  patches.push(...input.patches);
9211
+ if (this.callbacks?.onToolEnd) try {
9212
+ this.callbacks.onToolEnd({
9213
+ name: FILL_FORM_TOOL_NAME,
9214
+ output: { patchCount: input.patches.length },
9215
+ durationMs: Date.now() - startTime,
9216
+ executionId,
9217
+ error: void 0
9218
+ });
9219
+ } catch {}
8755
9220
  }
8756
9221
  }
8757
9222
  const toolCalls = [];
8758
- for (const [name$2, count] of toolCallCounts) toolCalls.push({
8759
- name: name$2,
9223
+ for (const [name, count] of toolCallCounts) toolCalls.push({
9224
+ name,
8760
9225
  count
8761
9226
  });
8762
9227
  const requiredRemaining = issues.filter((i) => i.severity === "required").length;
@@ -8791,11 +9256,11 @@ var LiveAgent = class {
8791
9256
  function extractToolSchemas(tools) {
8792
9257
  const schemas = {};
8793
9258
  const sortedNames = Object.keys(tools).sort();
8794
- for (const name$2 of sortedNames) {
8795
- const tool$1 = tools[name$2];
8796
- if (tool$1) schemas[name$2] = {
8797
- description: tool$1.description ?? "",
8798
- inputSchema: sortObjectKeys(tool$1.inputSchema ?? {})
9259
+ for (const name of sortedNames) {
9260
+ const tool = tools[name];
9261
+ if (tool) schemas[name] = {
9262
+ description: tool.description ?? "",
9263
+ inputSchema: sortObjectKeys(tool.inputSchema ?? {})
8799
9264
  };
8800
9265
  }
8801
9266
  return schemas;
@@ -8993,47 +9458,58 @@ function findField(form, fieldId) {
8993
9458
  * Only wraps tools that have an execute function.
8994
9459
  * Declarative tools (schema only) are passed through unchanged.
8995
9460
  */
8996
- function wrapToolsWithCallbacks(tools, callbacks) {
8997
- if (!callbacks?.onToolStart && !callbacks?.onToolEnd) return tools;
9461
+ function wrapToolsWithCallbacks(tools, callbacks, provider) {
9462
+ if (!callbacks?.onToolStart && !callbacks?.onToolEnd && !callbacks?.onWebSearch) return tools;
8998
9463
  const wrapped = {};
8999
- for (const [name$2, tool$1] of Object.entries(tools)) {
9000
- const execute = tool$1.execute;
9001
- if (typeof execute === "function") wrapped[name$2] = wrapTool(name$2, tool$1, execute, callbacks);
9002
- else wrapped[name$2] = tool$1;
9464
+ for (const [name, tool] of Object.entries(tools)) {
9465
+ const execute = tool.execute;
9466
+ if (typeof execute === "function") wrapped[name] = wrapTool(name, tool, execute, callbacks, provider);
9467
+ else wrapped[name] = tool;
9003
9468
  }
9004
9469
  return wrapped;
9005
9470
  }
9006
9471
  /**
9007
9472
  * Wrap a single tool with callbacks.
9008
9473
  */
9009
- function wrapTool(name$2, tool$1, originalExecute, callbacks) {
9474
+ function wrapTool(name, tool, originalExecute, callbacks, provider) {
9010
9475
  return {
9011
- ...tool$1,
9476
+ ...tool,
9012
9477
  execute: async (input) => {
9013
9478
  const startTime = Date.now();
9479
+ const executionId = "0-serial";
9014
9480
  if (callbacks.onToolStart) try {
9015
9481
  callbacks.onToolStart({
9016
- name: name$2,
9017
- input
9482
+ name,
9483
+ input,
9484
+ executionId
9018
9485
  });
9019
9486
  } catch {}
9020
9487
  try {
9021
9488
  const output = await originalExecute(input);
9022
9489
  if (callbacks.onToolEnd) try {
9023
9490
  callbacks.onToolEnd({
9024
- name: name$2,
9491
+ name,
9025
9492
  output,
9026
- durationMs: Date.now() - startTime
9493
+ durationMs: Date.now() - startTime,
9494
+ executionId
9495
+ });
9496
+ } catch {}
9497
+ if (callbacks.onWebSearch && isWebSearchTool(name)) try {
9498
+ const webSearchInfo = extractWebSearchInfo(input, output, provider ?? "unknown");
9499
+ if (webSearchInfo) callbacks.onWebSearch({
9500
+ ...webSearchInfo,
9501
+ executionId
9027
9502
  });
9028
9503
  } catch {}
9029
9504
  return output;
9030
9505
  } catch (error) {
9031
9506
  if (callbacks.onToolEnd) try {
9032
9507
  callbacks.onToolEnd({
9033
- name: name$2,
9508
+ name,
9034
9509
  output: null,
9035
9510
  durationMs: Date.now() - startTime,
9036
- error: error instanceof Error ? error.message : String(error)
9511
+ error: error instanceof Error ? error.message : String(error),
9512
+ executionId
9037
9513
  });
9038
9514
  } catch {}
9039
9515
  throw error;
@@ -9042,6 +9518,38 @@ function wrapTool(name$2, tool$1, originalExecute, callbacks) {
9042
9518
  };
9043
9519
  }
9044
9520
  /**
9521
+ * Check if a tool name indicates a web search tool.
9522
+ */
9523
+ function isWebSearchTool(name) {
9524
+ return name === "web_search" || name === "google_search" || name.includes("search");
9525
+ }
9526
+ /**
9527
+ * Extract web search info from tool input/output.
9528
+ * Different providers may have different structures.
9529
+ */
9530
+ function extractWebSearchInfo(input, output, provider) {
9531
+ let query;
9532
+ if (input && typeof input === "object") {
9533
+ const inputObj = input;
9534
+ if (typeof inputObj.query === "string") query = inputObj.query;
9535
+ else if (typeof inputObj.q === "string") query = inputObj.q;
9536
+ }
9537
+ if (!query) return;
9538
+ let resultCount = 0;
9539
+ if (output && typeof output === "object") {
9540
+ const outputObj = output;
9541
+ if (Array.isArray(outputObj.results)) resultCount = outputObj.results.length;
9542
+ else if (Array.isArray(outputObj.searchResults)) resultCount = outputObj.searchResults.length;
9543
+ else if (typeof outputObj.resultCount === "number") resultCount = outputObj.resultCount;
9544
+ else if (typeof outputObj.totalResults === "number") resultCount = outputObj.totalResults;
9545
+ }
9546
+ return {
9547
+ query,
9548
+ resultCount,
9549
+ provider
9550
+ };
9551
+ }
9552
+ /**
9045
9553
  * Load web search tools for a provider.
9046
9554
  * Uses centralized config from llms.ts.
9047
9555
  */
@@ -9049,23 +9557,23 @@ function loadWebSearchTools(provider) {
9049
9557
  if (!getWebSearchConfig(provider)?.toolName) return {};
9050
9558
  switch (provider) {
9051
9559
  case "openai": {
9052
- const tool$1 = openai.tools?.webSearch?.({}) ?? openai.tools?.webSearchPreview?.({});
9053
- if (tool$1) return { web_search: tool$1 };
9560
+ const tool = openai.tools?.webSearch?.({}) ?? openai.tools?.webSearchPreview?.({});
9561
+ if (tool) return { web_search: tool };
9054
9562
  return {};
9055
9563
  }
9056
9564
  case "anthropic": {
9057
- const tool$1 = anthropic.tools?.webSearch_20250305?.({});
9058
- if (tool$1) return { web_search: tool$1 };
9565
+ const tool = anthropic.tools?.webSearch_20250305?.({});
9566
+ if (tool) return { web_search: tool };
9059
9567
  return {};
9060
9568
  }
9061
9569
  case "google": {
9062
- const tool$1 = google.tools?.googleSearch?.({});
9063
- if (tool$1) return { google_search: tool$1 };
9570
+ const tool = google.tools?.googleSearch?.({});
9571
+ if (tool) return { google_search: tool };
9064
9572
  return {};
9065
9573
  }
9066
9574
  case "xai": {
9067
- const tool$1 = xai.tools?.webSearch?.({});
9068
- if (tool$1) return { web_search: tool$1 };
9575
+ const tool = xai.tools?.webSearch?.({});
9576
+ if (tool) return { web_search: tool };
9069
9577
  return {};
9070
9578
  }
9071
9579
  default: return {};
@@ -9440,10 +9948,156 @@ function createParallelHarness(form, config) {
9440
9948
 
9441
9949
  //#endregion
9442
9950
  //#region src/harness/programmaticFill.ts
9443
- function buildErrorResult(form, errors, warnings) {
9951
+ /**
9952
+ * Get current progress counts for a form.
9953
+ * Runs inspect to get issues, then computes progress summary.
9954
+ */
9955
+ function getProgressCounts(form, targetRoles) {
9956
+ const inspectResult = inspect(form, { targetRoles });
9957
+ return computeProgressSummary(form.schema, form.responsesByFieldId, form.notes, inspectResult.issues).counts;
9958
+ }
9959
+ /**
9960
+ * Create a FillRecordCollector if recordFill is enabled.
9961
+ */
9962
+ function createCollectorIfNeeded(options, form, provider, model) {
9963
+ if (!options.recordFill) return void 0;
9964
+ const structureSummary = computeStructureSummary(form.schema);
9965
+ return new FillRecordCollector({
9966
+ form: {
9967
+ id: form.schema.id,
9968
+ title: form.schema.title,
9969
+ description: form.schema.description,
9970
+ structure: structureSummary
9971
+ },
9972
+ provider,
9973
+ model,
9974
+ parallelEnabled: options.enableParallel,
9975
+ maxParallelAgents: options.maxParallelAgents
9976
+ });
9977
+ }
9978
+ /**
9979
+ * Log a warning when a user callback throws.
9980
+ */
9981
+ function warnCallbackError(name, error) {
9982
+ const message = error instanceof Error ? error.message : String(error);
9983
+ console.warn(`[markform] User callback ${name} threw: ${message}`);
9984
+ }
9985
+ /**
9986
+ * Merge user callbacks with collector callbacks.
9987
+ * Returns a new callbacks object that forwards to both.
9988
+ *
9989
+ * Error handling:
9990
+ * - Collector callbacks: errors propagate (bugs in our code should surface)
9991
+ * - User callbacks: errors are caught and logged as warnings
9992
+ */
9993
+ function mergeCallbacks(userCallbacks, collector) {
9994
+ if (!collector) return userCallbacks;
9995
+ if (!userCallbacks) return collector;
9996
+ return {
9997
+ onTurnStart: (turn) => {
9998
+ collector.onTurnStart(turn);
9999
+ try {
10000
+ userCallbacks.onTurnStart?.(turn);
10001
+ } catch (e) {
10002
+ warnCallbackError("onTurnStart", e);
10003
+ }
10004
+ },
10005
+ onTurnComplete: (progress) => {
10006
+ collector.onTurnComplete(progress);
10007
+ try {
10008
+ userCallbacks.onTurnComplete?.(progress);
10009
+ } catch (e) {
10010
+ warnCallbackError("onTurnComplete", e);
10011
+ }
10012
+ },
10013
+ onLlmCallStart: (call) => {
10014
+ collector.onLlmCallStart(call);
10015
+ try {
10016
+ userCallbacks.onLlmCallStart?.(call);
10017
+ } catch (e) {
10018
+ warnCallbackError("onLlmCallStart", e);
10019
+ }
10020
+ },
10021
+ onLlmCallEnd: (call) => {
10022
+ collector.onLlmCallEnd(call);
10023
+ try {
10024
+ userCallbacks.onLlmCallEnd?.(call);
10025
+ } catch (e) {
10026
+ warnCallbackError("onLlmCallEnd", e);
10027
+ }
10028
+ },
10029
+ onToolStart: (call) => {
10030
+ collector.onToolStart(call);
10031
+ try {
10032
+ userCallbacks.onToolStart?.(call);
10033
+ } catch (e) {
10034
+ warnCallbackError("onToolStart", e);
10035
+ }
10036
+ },
10037
+ onToolEnd: (call) => {
10038
+ collector.onToolEnd(call);
10039
+ try {
10040
+ userCallbacks.onToolEnd?.(call);
10041
+ } catch (e) {
10042
+ warnCallbackError("onToolEnd", e);
10043
+ }
10044
+ },
10045
+ onIssuesIdentified: userCallbacks.onIssuesIdentified ? (info) => {
10046
+ try {
10047
+ userCallbacks.onIssuesIdentified?.(info);
10048
+ } catch (e) {
10049
+ warnCallbackError("onIssuesIdentified", e);
10050
+ }
10051
+ } : void 0,
10052
+ onPatchesGenerated: userCallbacks.onPatchesGenerated ? (info) => {
10053
+ try {
10054
+ userCallbacks.onPatchesGenerated?.(info);
10055
+ } catch (e) {
10056
+ warnCallbackError("onPatchesGenerated", e);
10057
+ }
10058
+ } : void 0,
10059
+ onOrderLevelStart: userCallbacks.onOrderLevelStart ? (info) => {
10060
+ try {
10061
+ userCallbacks.onOrderLevelStart?.(info);
10062
+ } catch (e) {
10063
+ warnCallbackError("onOrderLevelStart", e);
10064
+ }
10065
+ } : void 0,
10066
+ onOrderLevelComplete: userCallbacks.onOrderLevelComplete ? (info) => {
10067
+ try {
10068
+ userCallbacks.onOrderLevelComplete?.(info);
10069
+ } catch (e) {
10070
+ warnCallbackError("onOrderLevelComplete", e);
10071
+ }
10072
+ } : void 0,
10073
+ onBatchStart: userCallbacks.onBatchStart ? (info) => {
10074
+ try {
10075
+ userCallbacks.onBatchStart?.(info);
10076
+ } catch (e) {
10077
+ warnCallbackError("onBatchStart", e);
10078
+ }
10079
+ } : void 0,
10080
+ onBatchComplete: userCallbacks.onBatchComplete ? (info) => {
10081
+ try {
10082
+ userCallbacks.onBatchComplete?.(info);
10083
+ } catch (e) {
10084
+ warnCallbackError("onBatchComplete", e);
10085
+ }
10086
+ } : void 0,
10087
+ onWebSearch: (info) => {
10088
+ collector.onWebSearch(info);
10089
+ try {
10090
+ userCallbacks.onWebSearch?.(info);
10091
+ } catch (e) {
10092
+ warnCallbackError("onWebSearch", e);
10093
+ }
10094
+ }
10095
+ };
10096
+ }
10097
+ function buildErrorResult(form, errors, warnings, record) {
9444
10098
  const values = {};
9445
10099
  for (const [fieldId, response] of Object.entries(form.responsesByFieldId)) if (response.state === "answered" && response.value) values[fieldId] = response.value;
9446
- return {
10100
+ const result = {
9447
10101
  status: {
9448
10102
  ok: false,
9449
10103
  reason: "error",
@@ -9456,8 +10110,10 @@ function buildErrorResult(form, errors, warnings) {
9456
10110
  totalPatches: 0,
9457
10111
  inputContextWarnings: warnings.length > 0 ? warnings : void 0
9458
10112
  };
10113
+ if (record) result.record = record;
10114
+ return result;
9459
10115
  }
9460
- function buildResult(form, turns, totalPatches, status, inputContextWarnings, remainingIssues) {
10116
+ function buildResult(form, turns, totalPatches, status, inputContextWarnings, remainingIssues, record) {
9461
10117
  const values = {};
9462
10118
  for (const [fieldId, response] of Object.entries(form.responsesByFieldId)) if (response.state === "answered" && response.value) values[fieldId] = response.value;
9463
10119
  const result = {
@@ -9475,6 +10131,7 @@ function buildResult(form, turns, totalPatches, status, inputContextWarnings, re
9475
10131
  severity: issue.severity,
9476
10132
  priority: issue.priority
9477
10133
  }));
10134
+ if (record) result.record = record;
9478
10135
  return result;
9479
10136
  }
9480
10137
  /**
@@ -9554,6 +10211,10 @@ async function fillForm(options) {
9554
10211
  const message = error instanceof Error ? error.message : String(error);
9555
10212
  return buildErrorResult(form, [`Model resolution error: ${message}`], []);
9556
10213
  }
10214
+ else if (typeof options.model === "string" && options.model.includes("/")) provider = options.model.split("/")[0];
10215
+ const modelString = typeof options.model === "string" ? options.model : "custom";
10216
+ const collector = createCollectorIfNeeded(options, form, provider ?? "unknown", modelString);
10217
+ const mergedCallbacks = mergeCallbacks(options.callbacks, collector);
9557
10218
  let totalPatches = 0;
9558
10219
  let inputContextWarnings = [];
9559
10220
  if (options.inputContext) {
@@ -9566,7 +10227,7 @@ async function fillForm(options) {
9566
10227
  inputContextWarnings = coercionResult.warnings;
9567
10228
  }
9568
10229
  if (options.enableParallel) {
9569
- if (computeExecutionPlan(form).parallelBatches.length > 0) return fillFormParallel(form, model, provider, options, totalPatches, inputContextWarnings);
10230
+ if (computeExecutionPlan(form).parallelBatches.length > 0) return fillFormParallel(form, model, provider, options, totalPatches, inputContextWarnings, collector, mergedCallbacks);
9570
10231
  }
9571
10232
  const maxTurnsTotal = options.maxTurnsTotal ?? DEFAULT_MAX_TURNS;
9572
10233
  const startingTurnNumber = options.startingTurnNumber ?? 0;
@@ -9588,7 +10249,7 @@ async function fillForm(options) {
9588
10249
  provider,
9589
10250
  enableWebSearch: options.enableWebSearch,
9590
10251
  additionalTools: options.additionalTools,
9591
- callbacks: options.callbacks,
10252
+ callbacks: mergedCallbacks,
9592
10253
  maxStepsPerTurn: options.maxStepsPerTurn
9593
10254
  });
9594
10255
  let turnCount = startingTurnNumber;
@@ -9596,40 +10257,79 @@ async function fillForm(options) {
9596
10257
  let stepResult = harness.step();
9597
10258
  let previousRejections;
9598
10259
  while (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {
9599
- if (options.maxTurnsThisCall !== void 0 && turnsThisCall >= options.maxTurnsThisCall) return buildResult(form, turnCount, totalPatches, {
9600
- ok: false,
9601
- reason: "batch_limit",
9602
- message: `Reached per-call limit (${options.maxTurnsThisCall} turns)`
9603
- }, inputContextWarnings, stepResult.issues);
9604
- if (options.signal?.aborted) return buildResult(form, turnCount, totalPatches, {
9605
- ok: false,
9606
- reason: "cancelled"
9607
- }, inputContextWarnings, stepResult.issues);
9608
- if (options.callbacks?.onTurnStart) try {
9609
- options.callbacks.onTurnStart({
10260
+ if (options.maxTurnsThisCall !== void 0 && turnsThisCall >= options.maxTurnsThisCall) {
10261
+ let record;
10262
+ if (collector) {
10263
+ collector.setStatus("partial", "batch_limit");
10264
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10265
+ }
10266
+ return buildResult(form, turnCount, totalPatches, {
10267
+ ok: false,
10268
+ reason: "batch_limit",
10269
+ message: `Reached per-call limit (${options.maxTurnsThisCall} turns)`
10270
+ }, inputContextWarnings, stepResult.issues, record);
10271
+ }
10272
+ if (options.signal?.aborted) {
10273
+ let record;
10274
+ if (collector) {
10275
+ collector.setStatus("cancelled");
10276
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10277
+ }
10278
+ return buildResult(form, turnCount, totalPatches, {
10279
+ ok: false,
10280
+ reason: "cancelled"
10281
+ }, inputContextWarnings, stepResult.issues, record);
10282
+ }
10283
+ if (mergedCallbacks?.onTurnStart) try {
10284
+ mergedCallbacks.onTurnStart({
9610
10285
  turnNumber: turnCount + 1,
9611
- issuesCount: stepResult.issues.length
10286
+ issuesCount: stepResult.issues.length,
10287
+ order: 0,
10288
+ executionId: "0-serial"
9612
10289
  });
9613
10290
  } catch {}
9614
10291
  const turnIssues = stepResult.issues;
9615
- if (options.callbacks?.onIssuesIdentified) try {
9616
- options.callbacks.onIssuesIdentified({
10292
+ if (mergedCallbacks?.onIssuesIdentified) try {
10293
+ mergedCallbacks.onIssuesIdentified({
9617
10294
  turnNumber: turnCount + 1,
9618
10295
  issues: turnIssues
9619
10296
  });
9620
10297
  } catch {}
9621
- const { patches, stats } = await agent.fillFormTool(turnIssues, form, maxPatchesPerTurn, previousRejections);
9622
- if (options.callbacks?.onPatchesGenerated) try {
9623
- options.callbacks.onPatchesGenerated({
10298
+ let response;
10299
+ try {
10300
+ response = await agent.fillFormTool(turnIssues, form, maxPatchesPerTurn, previousRejections);
10301
+ } catch (error) {
10302
+ const errorMessage = error instanceof Error ? error.message : String(error);
10303
+ let record;
10304
+ if (collector) {
10305
+ collector.setStatus("failed", errorMessage);
10306
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10307
+ }
10308
+ return buildResult(form, turnCount, totalPatches, {
10309
+ ok: false,
10310
+ reason: "error",
10311
+ message: errorMessage
10312
+ }, inputContextWarnings, turnIssues, record);
10313
+ }
10314
+ const { patches, stats } = response;
10315
+ if (mergedCallbacks?.onPatchesGenerated) try {
10316
+ mergedCallbacks.onPatchesGenerated({
9624
10317
  turnNumber: turnCount + 1,
9625
10318
  patches,
9626
10319
  stats
9627
10320
  });
9628
10321
  } catch {}
9629
- if (options.signal?.aborted) return buildResult(form, turnCount, totalPatches, {
9630
- ok: false,
9631
- reason: "cancelled"
9632
- }, inputContextWarnings, turnIssues);
10322
+ if (options.signal?.aborted) {
10323
+ let record;
10324
+ if (collector) {
10325
+ collector.setStatus("cancelled");
10326
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10327
+ }
10328
+ return buildResult(form, turnCount, totalPatches, {
10329
+ ok: false,
10330
+ reason: "cancelled"
10331
+ }, inputContextWarnings, turnIssues, record);
10332
+ }
9633
10333
  let llmStats;
9634
10334
  let context;
9635
10335
  if (stats) {
@@ -9650,9 +10350,9 @@ async function fillForm(options) {
9650
10350
  turnCount++;
9651
10351
  turnsThisCall++;
9652
10352
  previousRejections = stepResult.rejectedPatches;
9653
- if (options.callbacks?.onTurnComplete) try {
10353
+ if (mergedCallbacks?.onTurnComplete) try {
9654
10354
  const requiredIssues = stepResult.issues.filter((i) => i.severity === "required");
9655
- options.callbacks.onTurnComplete({
10355
+ mergedCallbacks.onTurnComplete({
9656
10356
  turnNumber: turnCount,
9657
10357
  issuesShown: turnIssues.length,
9658
10358
  patchesApplied: actualPatchesApplied,
@@ -9666,12 +10366,25 @@ async function fillForm(options) {
9666
10366
  } catch {}
9667
10367
  if (!stepResult.isComplete && !harness.hasReachedMaxTurns()) stepResult = harness.step();
9668
10368
  }
9669
- if (stepResult.isComplete) return buildResult(form, turnCount, totalPatches, { ok: true }, inputContextWarnings);
10369
+ const finalProgressCounts = getProgressCounts(form, targetRoles);
10370
+ if (stepResult.isComplete) {
10371
+ let record;
10372
+ if (collector) {
10373
+ collector.setStatus("completed");
10374
+ record = collector.getRecord(finalProgressCounts);
10375
+ }
10376
+ return buildResult(form, turnCount, totalPatches, { ok: true }, inputContextWarnings, void 0, record);
10377
+ }
10378
+ let record;
10379
+ if (collector) {
10380
+ collector.setStatus("partial", "max_turns");
10381
+ record = collector.getRecord(finalProgressCounts);
10382
+ }
9670
10383
  return buildResult(form, turnCount, totalPatches, {
9671
10384
  ok: false,
9672
10385
  reason: "max_turns",
9673
10386
  message: `Reached maximum total turns (${maxTurnsTotal})`
9674
- }, inputContextWarnings, stepResult.issues);
10387
+ }, inputContextWarnings, stepResult.issues, record);
9675
10388
  }
9676
10389
  /**
9677
10390
  * Fill a form using parallel execution.
@@ -9679,7 +10392,7 @@ async function fillForm(options) {
9679
10392
  * For each order level, runs serial items with the primary agent (multi-turn),
9680
10393
  * then runs parallel batch items concurrently (multi-turn per agent).
9681
10394
  */
9682
- async function fillFormParallel(form, model, provider, options, initialPatches, inputContextWarnings) {
10395
+ async function fillFormParallel(form, model, provider, options, initialPatches, inputContextWarnings, collector, mergedCallbacks) {
9683
10396
  const plan = computeExecutionPlan(form);
9684
10397
  const maxTurnsTotal = options.maxTurnsTotal ?? DEFAULT_MAX_TURNS;
9685
10398
  const startingTurnNumber = options.startingTurnNumber ?? 0;
@@ -9696,39 +10409,63 @@ async function fillFormParallel(form, model, provider, options, initialPatches,
9696
10409
  provider,
9697
10410
  enableWebSearch: options.enableWebSearch,
9698
10411
  additionalTools: options.additionalTools,
9699
- callbacks: options.callbacks,
10412
+ callbacks: mergedCallbacks,
9700
10413
  maxStepsPerTurn: options.maxStepsPerTurn
9701
10414
  });
9702
10415
  for (const order of plan.orderLevels) {
9703
- if (options.signal?.aborted) return buildResult(form, turnCount, totalPatches, {
9704
- ok: false,
9705
- reason: "cancelled"
9706
- }, inputContextWarnings);
9707
- if (turnCount >= maxTurnsTotal) return buildResult(form, turnCount, totalPatches, {
9708
- ok: false,
9709
- reason: "max_turns",
9710
- message: `Reached maximum total turns (${maxTurnsTotal})`
9711
- }, inputContextWarnings);
10416
+ if (options.signal?.aborted) {
10417
+ let record;
10418
+ if (collector) {
10419
+ collector.setStatus("cancelled");
10420
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10421
+ }
10422
+ return buildResult(form, turnCount, totalPatches, {
10423
+ ok: false,
10424
+ reason: "cancelled"
10425
+ }, inputContextWarnings, void 0, record);
10426
+ }
10427
+ if (turnCount >= maxTurnsTotal) {
10428
+ let record;
10429
+ if (collector) {
10430
+ collector.setStatus("partial", "max_turns");
10431
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10432
+ }
10433
+ return buildResult(form, turnCount, totalPatches, {
10434
+ ok: false,
10435
+ reason: "max_turns",
10436
+ message: `Reached maximum total turns (${maxTurnsTotal})`
10437
+ }, inputContextWarnings, void 0, record);
10438
+ }
9712
10439
  try {
9713
- options.callbacks?.onOrderLevelStart?.({ order });
10440
+ mergedCallbacks?.onOrderLevelStart?.({ order });
9714
10441
  } catch {}
9715
10442
  const serialItems = plan.looseSerial.filter((i) => i.order === order);
9716
10443
  if (serialItems.length > 0) {
9717
- const result = await runMultiTurnForItems(form, primaryAgent, serialItems, targetRoles, maxPatchesPerTurn, maxIssuesPerTurn, maxTurnsTotal, turnCount, options);
10444
+ const result = await runMultiTurnForItems(form, primaryAgent, serialItems, targetRoles, maxPatchesPerTurn, maxIssuesPerTurn, maxTurnsTotal, turnCount, options, order, `${order}-serial`, mergedCallbacks);
9718
10445
  totalPatches += result.patchesApplied;
9719
10446
  turnCount += result.turnsUsed;
9720
- if (result.aborted) return buildResult(form, turnCount, totalPatches, result.status, inputContextWarnings);
10447
+ if (result.aborted && result.status) {
10448
+ let record;
10449
+ if (collector) {
10450
+ const status = result.status;
10451
+ if (!status.ok) if (status.reason === "cancelled") collector.setStatus("cancelled");
10452
+ else if (status.reason === "error") collector.setStatus("failed", status.message);
10453
+ else collector.setStatus("partial", status.reason);
10454
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10455
+ }
10456
+ return buildResult(form, turnCount, totalPatches, result.status, inputContextWarnings, void 0, record);
10457
+ }
9721
10458
  }
9722
10459
  for (const batch of plan.parallelBatches) {
9723
10460
  const batchItems = batch.items.filter((i) => i.order === order);
9724
10461
  if (batchItems.length === 0) continue;
9725
10462
  try {
9726
- options.callbacks?.onBatchStart?.({
10463
+ mergedCallbacks?.onBatchStart?.({
9727
10464
  batchId: batch.batchId,
9728
10465
  itemCount: batchItems.length
9729
10466
  });
9730
10467
  } catch {}
9731
- const results = await runWithConcurrency(batchItems.map((item) => {
10468
+ const results = await runWithConcurrency(batchItems.map((item, itemIndex) => {
9732
10469
  return runMultiTurnForItems(form, options._testAgent ?? createLiveAgent({
9733
10470
  model,
9734
10471
  systemPromptAddition: options.systemPromptAddition,
@@ -9736,18 +10473,26 @@ async function fillFormParallel(form, model, provider, options, initialPatches,
9736
10473
  provider,
9737
10474
  enableWebSearch: options.enableWebSearch,
9738
10475
  additionalTools: options.additionalTools,
9739
- callbacks: options.callbacks,
10476
+ callbacks: mergedCallbacks,
9740
10477
  maxStepsPerTurn: options.maxStepsPerTurn
9741
- }), [item], targetRoles, maxPatchesPerTurn, maxIssuesPerTurn, maxTurnsTotal, turnCount, options);
10478
+ }), [item], targetRoles, maxPatchesPerTurn, maxIssuesPerTurn, maxTurnsTotal, turnCount, options, order, `${order}-batch-${batch.batchId}-${itemIndex}`, mergedCallbacks);
9742
10479
  }).map((p) => p), maxParallelAgents);
9743
10480
  let batchPatches = 0;
10481
+ const batchErrors = [];
9744
10482
  for (const result of results) if (result.status === "fulfilled") {
9745
10483
  totalPatches += result.value.patchesApplied;
9746
10484
  batchPatches += result.value.patchesApplied;
9747
10485
  turnCount += result.value.turnsUsed;
10486
+ const itemStatus = result.value.status;
10487
+ if (result.value.aborted && itemStatus && !itemStatus.ok && itemStatus.message) batchErrors.push(itemStatus.message);
10488
+ } else {
10489
+ const reason = result.reason;
10490
+ const errorMsg = reason instanceof Error ? reason.message : String(reason);
10491
+ batchErrors.push(`Parallel agent error: ${errorMsg}`);
9748
10492
  }
10493
+ if (batchErrors.length > 0 && collector) console.warn(`[markform] Parallel batch ${batch.batchId} had errors:`, batchErrors);
9749
10494
  try {
9750
- options.callbacks?.onBatchComplete?.({
10495
+ mergedCallbacks?.onBatchComplete?.({
9751
10496
  batchId: batch.batchId,
9752
10497
  patchesApplied: batchPatches
9753
10498
  });
@@ -9755,27 +10500,47 @@ async function fillFormParallel(form, model, provider, options, initialPatches,
9755
10500
  }
9756
10501
  const levelInspect = inspect(form);
9757
10502
  try {
9758
- options.callbacks?.onOrderLevelComplete?.({
10503
+ mergedCallbacks?.onOrderLevelComplete?.({
9759
10504
  order,
9760
10505
  patchesApplied: totalPatches
9761
10506
  });
9762
10507
  } catch {}
9763
- if (levelInspect.isComplete) return buildResult(form, turnCount, totalPatches, { ok: true }, inputContextWarnings);
10508
+ if (levelInspect.isComplete) {
10509
+ let record;
10510
+ if (collector) {
10511
+ collector.setStatus("completed");
10512
+ record = collector.getRecord(getProgressCounts(form, targetRoles));
10513
+ }
10514
+ return buildResult(form, turnCount, totalPatches, { ok: true }, inputContextWarnings, void 0, record);
10515
+ }
9764
10516
  }
9765
10517
  const finalInspect = inspect(form);
9766
- if (finalInspect.isComplete) return buildResult(form, turnCount, totalPatches, { ok: true }, inputContextWarnings);
10518
+ const finalProgressCounts = getProgressCounts(form, targetRoles);
10519
+ if (finalInspect.isComplete) {
10520
+ let record;
10521
+ if (collector) {
10522
+ collector.setStatus("completed");
10523
+ record = collector.getRecord(finalProgressCounts);
10524
+ }
10525
+ return buildResult(form, turnCount, totalPatches, { ok: true }, inputContextWarnings, void 0, record);
10526
+ }
10527
+ let record;
10528
+ if (collector) {
10529
+ collector.setStatus("partial", "max_turns");
10530
+ record = collector.getRecord(finalProgressCounts);
10531
+ }
9767
10532
  return buildResult(form, turnCount, totalPatches, {
9768
10533
  ok: false,
9769
10534
  reason: "max_turns",
9770
10535
  message: `Reached maximum total turns (${maxTurnsTotal})`
9771
- }, inputContextWarnings, finalInspect.issues);
10536
+ }, inputContextWarnings, finalInspect.issues, record);
9772
10537
  }
9773
10538
  /**
9774
10539
  * Run a multi-turn loop for a set of execution plan items.
9775
10540
  * Scoped issues are filtered to only the target items' fields.
9776
10541
  * Retries with rejection feedback, same as the serial fillForm path.
9777
10542
  */
9778
- async function runMultiTurnForItems(form, agent, items, targetRoles, maxPatchesPerTurn, _maxIssuesPerTurn, maxTurnsTotal, startTurn, options) {
10543
+ async function runMultiTurnForItems(form, agent, items, targetRoles, maxPatchesPerTurn, _maxIssuesPerTurn, maxTurnsTotal, startTurn, options, order, executionId, mergedCallbacks) {
9779
10544
  let turnsUsed = 0;
9780
10545
  let patchesApplied = 0;
9781
10546
  let previousRejections;
@@ -9802,12 +10567,29 @@ async function runMultiTurnForItems(form, agent, items, targetRoles, maxPatchesP
9802
10567
  });
9803
10568
  if (scopedIssues.length === 0) break;
9804
10569
  try {
9805
- options.callbacks?.onTurnStart?.({
10570
+ mergedCallbacks?.onTurnStart?.({
9806
10571
  turnNumber: startTurn + turnsUsed + 1,
9807
- issuesCount: scopedIssues.length
10572
+ issuesCount: scopedIssues.length,
10573
+ order,
10574
+ executionId
9808
10575
  });
9809
10576
  } catch {}
9810
- const response = await agent.fillFormTool(scopedIssues, form, maxPatchesPerTurn, previousRejections);
10577
+ let response;
10578
+ try {
10579
+ response = await agent.fillFormTool(scopedIssues, form, maxPatchesPerTurn, previousRejections);
10580
+ } catch (error) {
10581
+ const errorMessage = error instanceof Error ? error.message : String(error);
10582
+ return {
10583
+ patchesApplied,
10584
+ turnsUsed,
10585
+ aborted: true,
10586
+ status: {
10587
+ ok: false,
10588
+ reason: "error",
10589
+ message: errorMessage
10590
+ }
10591
+ };
10592
+ }
9811
10593
  if (response.patches.length > 0) {
9812
10594
  const applyResult = applyPatches(form, response.patches);
9813
10595
  patchesApplied += applyResult.appliedPatches.length;
@@ -9817,7 +10599,7 @@ async function runMultiTurnForItems(form, agent, items, targetRoles, maxPatchesP
9817
10599
  try {
9818
10600
  const postInspect = inspect(form, { targetRoles });
9819
10601
  const requiredIssues = postInspect.issues.filter((i) => i.severity === "required");
9820
- options.callbacks?.onTurnComplete?.({
10602
+ mergedCallbacks?.onTurnComplete?.({
9821
10603
  turnNumber: startTurn + turnsUsed,
9822
10604
  issuesShown: scopedIssues.length,
9823
10605
  patchesApplied: response.patches.length,
@@ -9863,6 +10645,286 @@ function resolveHarnessConfig(form, options) {
9863
10645
  };
9864
10646
  }
9865
10647
 
10648
+ //#endregion
10649
+ //#region src/harness/formatFillRecordSummary.ts
10650
+ /**
10651
+ * Format a number with thousands separators.
10652
+ */
10653
+ function formatNumber(n) {
10654
+ return n.toLocaleString("en-US");
10655
+ }
10656
+ /**
10657
+ * Format milliseconds as a human-readable duration.
10658
+ */
10659
+ function formatDuration(ms) {
10660
+ if (ms < 1e3) return `${ms}ms`;
10661
+ const seconds = ms / 1e3;
10662
+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
10663
+ return `${Math.floor(seconds / 60)}m ${(seconds % 60).toFixed(0)}s`;
10664
+ }
10665
+ /**
10666
+ * Format a percentage.
10667
+ */
10668
+ function formatPercent(value, total) {
10669
+ if (total === 0) return "0%";
10670
+ return `${Math.round(value / total * 100)}%`;
10671
+ }
10672
+ /**
10673
+ * Format FillRecord as a human-readable text summary.
10674
+ *
10675
+ * @param record - The FillRecord to format
10676
+ * @param options - Formatting options (verbose mode for more detail)
10677
+ * @returns Multi-line text summary
10678
+ *
10679
+ * @example
10680
+ * ```typescript
10681
+ * const result = await fillForm({ form, model, recordFill: true });
10682
+ * if (result.record) {
10683
+ * console.log(formatFillRecordSummary(result.record));
10684
+ * }
10685
+ * ```
10686
+ */
10687
+ function formatFillRecordSummary(record, options = {}) {
10688
+ const { verbose = false } = options;
10689
+ const lines = [];
10690
+ const statusText = record.status === "completed" ? "Fill completed" : "Fill incomplete";
10691
+ const turnsText = `${record.execution.totalTurns} turn${record.execution.totalTurns !== 1 ? "s" : ""}`;
10692
+ let statusLine = `${statusText} in ${formatDuration(record.durationMs)} (${turnsText})`;
10693
+ if (record.status !== "completed" && record.statusDetail) statusLine += ` - ${record.statusDetail}`;
10694
+ lines.push(statusLine);
10695
+ const timelineEmpty = record.timeline.length === 0;
10696
+ const hadTurns = record.execution.totalTurns > 0;
10697
+ const hadFieldsFilled = record.formProgress.filledFields > 0;
10698
+ if (timelineEmpty && (hadTurns || hadFieldsFilled)) lines.push("Warning: timeline is empty but work was recorded (possible callback wiring issue)");
10699
+ lines.push("");
10700
+ const tokenLine = `Tokens: ${formatNumber(record.llm.inputTokens)} input / ${formatNumber(record.llm.outputTokens)} output (${record.llm.provider}/${record.llm.model})`;
10701
+ lines.push(tokenLine);
10702
+ const { toolSummary } = record;
10703
+ let toolLine = `Tools: ${formatNumber(toolSummary.totalCalls)} calls`;
10704
+ if (toolSummary.totalCalls > 0) {
10705
+ toolLine += ` (${formatNumber(toolSummary.successfulCalls)} succeeded`;
10706
+ if (toolSummary.failedCalls > 0) toolLine += `, ${formatNumber(toolSummary.failedCalls)} failed`;
10707
+ toolLine += ")";
10708
+ }
10709
+ lines.push(toolLine);
10710
+ if (verbose && toolSummary.byTool.length > 0) for (const tool of toolSummary.byTool) {
10711
+ const avgDuration = formatDuration(tool.timing.avgMs);
10712
+ let toolDetail = ` - ${tool.toolName}: ${tool.callCount} calls, avg ${avgDuration}`;
10713
+ if (tool.timing.p95Ms !== void 0 && tool.callCount > 1) toolDetail += `, p95 ${formatDuration(tool.timing.p95Ms)}`;
10714
+ lines.push(toolDetail);
10715
+ }
10716
+ if (verbose) {
10717
+ lines.push("");
10718
+ const { timingBreakdown } = record;
10719
+ const llmPct = timingBreakdown.breakdown.find((b) => b.category === "llm")?.percentage ?? 0;
10720
+ const toolPct = timingBreakdown.breakdown.find((b) => b.category === "tools")?.percentage ?? 0;
10721
+ const overheadPct = timingBreakdown.breakdown.find((b) => b.category === "overhead")?.percentage ?? 0;
10722
+ const timingLine = `Timing: ${llmPct}% LLM (${formatDuration(timingBreakdown.llmTimeMs)}) | ${toolPct}% tools (${formatDuration(timingBreakdown.toolTimeMs)}) | ${overheadPct}% overhead (${formatDuration(timingBreakdown.overheadMs)})`;
10723
+ lines.push(timingLine);
10724
+ }
10725
+ lines.push("");
10726
+ const { formProgress } = record;
10727
+ const progressPct = formatPercent(formProgress.answeredFields, formProgress.totalFields);
10728
+ const progressLine = `Progress: ${formProgress.answeredFields}/${formProgress.totalFields} fields filled (${progressPct})`;
10729
+ lines.push(progressLine);
10730
+ return lines.join("\n");
10731
+ }
10732
+
10733
+ //#endregion
10734
+ //#region src/harness/fillRecord.ts
10735
+ /**
10736
+ * FillRecord types - Captures complete records of form fill operations.
10737
+ *
10738
+ * Provides detailed tracking of:
10739
+ * - LLM usage (tokens per turn and totals)
10740
+ * - Tool invocations with timing and results
10741
+ * - Turn-by-turn timeline with execution context
10742
+ * - Form progress and completion status
10743
+ *
10744
+ * @see docs/project/specs/active/plan-2026-01-29-fill-record.md
10745
+ */
10746
+ /**
10747
+ * Per-tool statistics with timing percentiles.
10748
+ * Enables analysis like "web_search p95 is 2.5s" or "fill_form has 98% success rate"
10749
+ */
10750
+ const ToolStatsSchema = z.object({
10751
+ toolName: z.string(),
10752
+ callCount: z.number().int().nonnegative(),
10753
+ successCount: z.number().int().nonnegative(),
10754
+ failureCount: z.number().int().nonnegative(),
10755
+ successRate: z.number().nonnegative(),
10756
+ results: z.object({
10757
+ totalResults: z.number().int().nonnegative(),
10758
+ avgResultsPerCall: z.number().nonnegative(),
10759
+ zeroResultCalls: z.number().int().nonnegative()
10760
+ }).optional(),
10761
+ timing: z.object({
10762
+ totalMs: z.number().int().nonnegative(),
10763
+ avgMs: z.number().nonnegative(),
10764
+ minMs: z.number().int().nonnegative(),
10765
+ maxMs: z.number().int().nonnegative(),
10766
+ p50Ms: z.number().int().nonnegative(),
10767
+ p95Ms: z.number().int().nonnegative()
10768
+ })
10769
+ });
10770
+ /**
10771
+ * Individual tool call in the timeline.
10772
+ */
10773
+ const ToolCallRecordSchema = z.object({
10774
+ tool: z.string(),
10775
+ startedAt: z.string().datetime(),
10776
+ completedAt: z.string().datetime(),
10777
+ durationMs: z.number().int().nonnegative(),
10778
+ success: z.boolean(),
10779
+ input: z.record(z.string(), z.unknown()),
10780
+ result: z.object({
10781
+ resultCount: z.number().int().nonnegative().optional(),
10782
+ error: z.string().optional()
10783
+ }).optional()
10784
+ });
10785
+ /**
10786
+ * Single turn in the fill timeline.
10787
+ */
10788
+ const TimelineEntrySchema = z.object({
10789
+ turnNumber: z.number().int().positive(),
10790
+ order: z.number().int().nonnegative(),
10791
+ executionId: z.string(),
10792
+ startedAt: z.string().datetime(),
10793
+ completedAt: z.string().datetime(),
10794
+ durationMs: z.number().int().nonnegative(),
10795
+ issuesAddressed: z.number().int().nonnegative(),
10796
+ patchesApplied: z.number().int().nonnegative(),
10797
+ patchesRejected: z.number().int().nonnegative(),
10798
+ tokens: z.object({
10799
+ input: z.number().int().nonnegative(),
10800
+ output: z.number().int().nonnegative()
10801
+ }),
10802
+ toolCalls: z.array(ToolCallRecordSchema)
10803
+ });
10804
+ /**
10805
+ * Breakdown item for visualization.
10806
+ */
10807
+ const TimingBreakdownItemSchema = z.object({
10808
+ category: z.enum([
10809
+ "llm",
10810
+ "tools",
10811
+ "overhead"
10812
+ ]),
10813
+ label: z.string(),
10814
+ ms: z.number().int().nonnegative(),
10815
+ percentage: z.number().nonnegative()
10816
+ });
10817
+ /**
10818
+ * Timing breakdown showing where time was spent.
10819
+ */
10820
+ const TimingBreakdownSchema = z.object({
10821
+ totalMs: z.number().int().nonnegative(),
10822
+ llmTimeMs: z.number().int().nonnegative(),
10823
+ toolTimeMs: z.number().int().nonnegative(),
10824
+ overheadMs: z.number().int().nonnegative(),
10825
+ breakdown: z.array(TimingBreakdownItemSchema)
10826
+ });
10827
+ /**
10828
+ * Aggregated tool usage statistics.
10829
+ */
10830
+ const ToolSummarySchema = z.object({
10831
+ totalCalls: z.number().int().nonnegative(),
10832
+ successfulCalls: z.number().int().nonnegative(),
10833
+ failedCalls: z.number().int().nonnegative(),
10834
+ successRate: z.number().nonnegative(),
10835
+ totalDurationMs: z.number().int().nonnegative(),
10836
+ byTool: z.array(ToolStatsSchema)
10837
+ });
10838
+ /**
10839
+ * Execution metadata for the fill.
10840
+ */
10841
+ const ExecutionMetadataSchema = z.object({
10842
+ totalTurns: z.number().int().nonnegative(),
10843
+ parallelEnabled: z.boolean(),
10844
+ maxParallelAgents: z.number().int().positive().optional(),
10845
+ orderLevels: z.array(z.number().int().nonnegative()),
10846
+ executionThreads: z.array(z.string())
10847
+ });
10848
+ /**
10849
+ * Fill status enum.
10850
+ */
10851
+ const FillRecordStatusSchema = z.enum([
10852
+ "completed",
10853
+ "partial",
10854
+ "failed",
10855
+ "cancelled"
10856
+ ]);
10857
+ /**
10858
+ * Complete record of a form fill operation.
10859
+ *
10860
+ * Captures everything that happened during the fill for:
10861
+ * - Provenance/corroboration
10862
+ * - Cost analysis
10863
+ * - Debugging
10864
+ * - Analytics
10865
+ */
10866
+ const FillRecordSchema = z.object({
10867
+ sessionId: z.string().uuid(),
10868
+ startedAt: z.string().datetime(),
10869
+ completedAt: z.string().datetime(),
10870
+ durationMs: z.number().int().nonnegative(),
10871
+ form: z.object({
10872
+ id: z.string(),
10873
+ title: z.string().optional(),
10874
+ description: z.string().optional(),
10875
+ structure: StructureSummarySchema
10876
+ }),
10877
+ status: FillRecordStatusSchema,
10878
+ statusDetail: z.string().optional(),
10879
+ formProgress: ProgressCountsSchema,
10880
+ llm: z.object({
10881
+ provider: z.string(),
10882
+ model: z.string(),
10883
+ totalCalls: z.number().int().nonnegative(),
10884
+ inputTokens: z.number().int().nonnegative(),
10885
+ outputTokens: z.number().int().nonnegative()
10886
+ }),
10887
+ toolSummary: ToolSummarySchema,
10888
+ timingBreakdown: TimingBreakdownSchema,
10889
+ timeline: z.array(TimelineEntrySchema),
10890
+ execution: ExecutionMetadataSchema,
10891
+ customData: z.record(z.string(), z.unknown()).optional()
10892
+ });
10893
+ /**
10894
+ * Strip unstable fields from FillRecord for golden test comparisons.
10895
+ *
10896
+ * In mock mode, all remaining fields should be deterministic:
10897
+ * - status, statusDetail: based on completion logic
10898
+ * - form: form metadata (static)
10899
+ * - formProgress: counts of filled fields (deterministic from mock source)
10900
+ * - llm: provider/model/tokens (tokens are 0 in mock mode)
10901
+ * - toolSummary: call counts and success rates (without timing)
10902
+ * - execution: turn counts, parallel settings (deterministic)
10903
+ */
10904
+ function stripUnstableFillRecordFields(record) {
10905
+ const stableByTool = record.toolSummary.byTool.map((toolStats) => {
10906
+ const { timing, ...rest } = toolStats;
10907
+ return rest;
10908
+ });
10909
+ const stableToolSummary = {
10910
+ totalCalls: record.toolSummary.totalCalls,
10911
+ successfulCalls: record.toolSummary.successfulCalls,
10912
+ failedCalls: record.toolSummary.failedCalls,
10913
+ successRate: record.toolSummary.successRate,
10914
+ byTool: stableByTool
10915
+ };
10916
+ return {
10917
+ form: record.form,
10918
+ status: record.status,
10919
+ statusDetail: record.statusDetail,
10920
+ formProgress: record.formProgress,
10921
+ llm: record.llm,
10922
+ toolSummary: stableToolSummary,
10923
+ execution: record.execution,
10924
+ customData: record.customData
10925
+ };
10926
+ }
10927
+
9866
10928
  //#endregion
9867
10929
  //#region src/research/runResearch.ts
9868
10930
  /**
@@ -9982,8 +11044,8 @@ function validateResearchForm(form) {
9982
11044
  //#endregion
9983
11045
  //#region src/index.ts
9984
11046
  /** Markform version (injected at build time). */
9985
- const VERSION = "0.1.18";
11047
+ const VERSION = "0.1.20";
9986
11048
 
9987
11049
  //#endregion
9988
- export { formToJsonSchema as A, getFieldId as C, parseScopeRef as D, isQualifiedRef as E, findAllHeadings as F, findEnclosingHeadings as I, parseCellValue as L, findAllCheckboxes as M, injectCheckboxIds as N, serializeScopeRef as O, injectHeaderIds as P, parseMarkdownTable as R, findFieldById as S, isFieldRef as T, createMockAgent as _, resolveHarnessConfig as a, coerceInputContext as b, createParallelHarness as c, getProviderNames as d, resolveModel as f, MockAgent as g, computeExecutionPlan as h, runResearch as i, parseForm as j, fieldToJsonSchema as k, scopeIssuesForItem as l, createLiveAgent as m, isResearchForm as n, fillForm as o, buildMockWireFormat as p, validateResearchForm as r, ParallelHarness as s, VERSION as t, getProviderInfo as u, FormHarness as v, isCellRef as w, coerceToFieldPatch as x, createHarness as y, parseRawTable as z };
9989
- //# sourceMappingURL=src-DDxi-2ne.mjs.map
11050
+ export { FormHarness as A, serializeScopeRef as B, resolveModel as C, computeExecutionPlan as D, FillRecordCollector as E, getFieldId as F, injectCheckboxIds as G, formToJsonSchema as H, isCellRef as I, findEnclosingHeadings as J, injectHeaderIds as K, isFieldRef as L, coerceInputContext as M, coerceToFieldPatch as N, MockAgent as O, findFieldById as P, isQualifiedRef as R, getProviderNames as S, createLiveAgent as T, parseForm as U, fieldToJsonSchema as V, findAllCheckboxes as W, parseMarkdownTable as X, parseCellValue as Y, parseRawTable as Z, fillForm as _, ExecutionMetadataSchema as a, scopeIssuesForItem as b, TimelineEntrySchema as c, ToolCallRecordSchema as d, ToolStatsSchema as f, resolveHarnessConfig as g, formatFillRecordSummary as h, runResearch as i, createHarness as j, createMockAgent as k, TimingBreakdownItemSchema as l, stripUnstableFillRecordFields as m, isResearchForm as n, FillRecordSchema as o, ToolSummarySchema as p, findAllHeadings as q, validateResearchForm as r, FillRecordStatusSchema as s, VERSION as t, TimingBreakdownSchema as u, ParallelHarness as v, buildMockWireFormat as w, getProviderInfo as x, createParallelHarness as y, parseScopeRef as z };
11051
+ //# sourceMappingURL=src-wR7GoftB.mjs.map