markform 0.1.21 → 0.1.22
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.
- package/README.md +32 -4
- package/dist/ai-sdk.d.mts +1 -1
- package/dist/ai-sdk.mjs +1 -1
- package/dist/{apply-CD-t7ovb.mjs → apply-C7mO7VkZ.mjs} +100 -74
- package/dist/apply-C7mO7VkZ.mjs.map +1 -0
- package/dist/bin.mjs +1 -1
- package/dist/{cli-ChdIy1a7.mjs → cli-C8F9yDsv.mjs} +17 -1213
- package/dist/cli-C8F9yDsv.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/{coreTypes-BQrWf_Wt.d.mts → coreTypes-BlsJkU1w.d.mts} +1 -1
- package/dist/fillRecord-DTl5lnK0.d.mts +345 -0
- package/dist/fillRecordRenderer-CruJrLkj.mjs +1256 -0
- package/dist/fillRecordRenderer-CruJrLkj.mjs.map +1 -0
- package/dist/index.d.mts +5 -342
- package/dist/index.mjs +3 -3
- package/dist/render.d.mts +74 -0
- package/dist/render.mjs +4 -0
- package/dist/{session-ZgegwtkT.mjs → session-BCcltrLA.mjs} +1 -1
- package/dist/{session-ZgegwtkT.mjs.map → session-BCcltrLA.mjs.map} +1 -1
- package/dist/{session-BPuQ-ok0.mjs → session-VeSkVrck.mjs} +1 -1
- package/dist/{shared-DwdyWmvE.mjs → shared-CsdT2T7k.mjs} +1 -1
- package/dist/{shared-DwdyWmvE.mjs.map → shared-CsdT2T7k.mjs.map} +1 -1
- package/dist/{shared-BTR35aMz.mjs → shared-fb0nkzQi.mjs} +1 -1
- package/dist/{src-DOPe4tmu.mjs → src-CbRnGzMK.mjs} +16 -11
- package/dist/{src-DOPe4tmu.mjs.map → src-CbRnGzMK.mjs.map} +1 -1
- package/dist/urlFormat-lls7CsEP.mjs +71 -0
- package/dist/urlFormat-lls7CsEP.mjs.map +1 -0
- package/docs/markform-apis.md +53 -0
- package/examples/simple/simple-skipped-filled.report.md +8 -8
- package/examples/twitter-thread/twitter-thread.form.md +373 -0
- package/package.json +5 -1
- package/dist/apply-CD-t7ovb.mjs.map +0 -1
- package/dist/cli-ChdIy1a7.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"src-DOPe4tmu.mjs","names":["marker","symbol","name","VERSION","ZodFirstPartyTypeKind2","ZodFirstPartyTypeKind3","zodSchema","TypeValidationError2","TypeValidationError3","InvalidArgumentError2","APICallError3","APICallError4","VERSION","zodSchema","z","lazySchema2","zodSchema2","z2","z3","lazySchema3","zodSchema3","z4","lazySchema4","zodSchema4","z5","lazySchema5","zodSchema5","z6","createProviderToolFactoryWithOutputSchema2","lazySchema6","zodSchema6","z7","createProviderToolFactoryWithOutputSchema3","lazySchema7","zodSchema7","z8","createProviderToolFactoryWithOutputSchema4","lazySchema8","zodSchema8","z9","createProviderToolFactoryWithOutputSchema5","UnsupportedFunctionalityError2","validateTypes2","parseProviderOptions2","createProviderToolFactory2","lazySchema9","zodSchema9","z10","createProviderToolFactory3","lazySchema10","zodSchema10","z11","createProviderToolFactory4","lazySchema11","zodSchema11","z12","createProviderToolFactory5","lazySchema12","zodSchema12","z13","createProviderToolFactory6","lazySchema13","zodSchema13","z14","createProviderToolFactory7","lazySchema14","zodSchema14","z15","createProviderToolFactory8","lazySchema15","zodSchema15","z16","createProviderToolFactory9","lazySchema16","zodSchema16","z17","createProviderToolFactory10","lazySchema17","zodSchema17","z18","lazySchema18","zodSchema18","z19","createProviderToolFactoryWithOutputSchema6","generateId2"],"sources":["../src/engine/fieldRegistry.ts","../src/engine/table/parseTable.ts","../src/engine/parseFields.ts","../src/markdown/markdownHeaders.ts","../src/engine/injectIds.ts","../src/engine/parse.ts","../src/engine/jsonSchema.ts","../src/engine/scopeRef.ts","../src/engine/valueCoercion.ts","../src/harness/harness.ts","../src/harness/mockAgent.ts","../src/engine/executionPlan.ts","../src/harness/timeUtils.ts","../src/harness/fillRecordCollector.ts","../../../node_modules/.pnpm/@ai-sdk+provider@3.0.6/node_modules/@ai-sdk/provider/dist/index.mjs","../../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js","../../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js","../../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.12_zod@4.3.6/node_modules/@ai-sdk/provider-utils/dist/index.mjs","../../../node_modules/.pnpm/@ai-sdk+anthropic@3.0.34_zod@4.3.6/node_modules/@ai-sdk/anthropic/dist/index.mjs","../src/harness/prompts.ts","../src/harness/toolApi.ts","../src/harness/liveAgent.ts","../src/harness/modelResolver.ts","../src/harness/parallelHarness.ts","../src/harness/programmaticFill.ts","../src/harness/harnessConfigResolver.ts","../src/harness/formatFillRecordSummary.ts","../src/harness/fillRecord.ts","../src/research/runResearch.ts","../src/research/researchFormValidation.ts","../src/index.ts"],"sourcesContent":["/**\n * Field Kind Registry - Single source of truth for field kind relationships.\n *\n * Note: This registry maps field *kinds* (e.g., 'string', 'checkboxes') to their\n * corresponding TypeScript types. The name \"FieldTypeMap\" is retained for stability\n * but conceptually maps kinds → types.\n *\n * This module defines the relationships between FieldKind, Field, FieldValue,\n * and Patch types in a type-safe way. Adding a new field kind requires:\n *\n * - Add the kind to FIELD_KINDS tuple below\n * - Add entry to FieldTypeMap interface\n * - Define the Field interface (extends FieldBase)\n * - Define the Value interface\n * - Define the SetPatch interface\n * - Add Zod schemas in the schemas section\n *\n * TypeScript will error if any of these are missing or inconsistent.\n */\n\nimport type { z } from 'zod';\n\n// =============================================================================\n// Field kinds (tuple for type inference)\n// =============================================================================\n\n/**\n * All field kinds as a const tuple - the single source of truth.\n * Adding a new kind here will cause TypeScript errors until all\n * corresponding types and handlers are added.\n */\nexport const FIELD_KINDS = [\n 'string',\n 'number',\n 'string_list',\n 'checkboxes',\n 'single_select',\n 'multi_select',\n 'url',\n 'url_list',\n 'date',\n 'year',\n 'table',\n] as const;\n\n/** Field kind discriminant - derived from the tuple */\nexport type FieldKind = (typeof FIELD_KINDS)[number];\n\n// =============================================================================\n// Type map - links kind to Field, Value, and Patch\n// =============================================================================\n\nimport type {\n StringField,\n NumberField,\n StringListField,\n CheckboxesField,\n SingleSelectField,\n MultiSelectField,\n UrlField,\n UrlListField,\n DateField,\n YearField,\n TableField,\n StringValue,\n NumberValue,\n StringListValue,\n CheckboxesValue,\n SingleSelectValue,\n MultiSelectValue,\n UrlValue,\n UrlListValue,\n DateValue,\n YearValue,\n TableValue,\n SetStringPatch,\n SetNumberPatch,\n SetStringListPatch,\n SetCheckboxesPatch,\n SetSingleSelectPatch,\n SetMultiSelectPatch,\n SetUrlPatch,\n SetUrlListPatch,\n SetDatePatch,\n SetYearPatch,\n SetTablePatch,\n} from './coreTypes.js';\n\n/**\n * Type map linking each field kind to its corresponding types.\n * TypeScript will error if any kind is missing from this map.\n */\nexport interface FieldTypeMap {\n string: {\n field: StringField;\n value: StringValue;\n patch: SetStringPatch;\n emptyValue: { kind: 'string'; value: null };\n };\n number: {\n field: NumberField;\n value: NumberValue;\n patch: SetNumberPatch;\n emptyValue: { kind: 'number'; value: null };\n };\n string_list: {\n field: StringListField;\n value: StringListValue;\n patch: SetStringListPatch;\n emptyValue: { kind: 'string_list'; items: [] };\n };\n checkboxes: {\n field: CheckboxesField;\n value: CheckboxesValue;\n patch: SetCheckboxesPatch;\n emptyValue: { kind: 'checkboxes'; values: Record<string, never> };\n };\n single_select: {\n field: SingleSelectField;\n value: SingleSelectValue;\n patch: SetSingleSelectPatch;\n emptyValue: { kind: 'single_select'; selected: null };\n };\n multi_select: {\n field: MultiSelectField;\n value: MultiSelectValue;\n patch: SetMultiSelectPatch;\n emptyValue: { kind: 'multi_select'; selected: [] };\n };\n url: {\n field: UrlField;\n value: UrlValue;\n patch: SetUrlPatch;\n emptyValue: { kind: 'url'; value: null };\n };\n url_list: {\n field: UrlListField;\n value: UrlListValue;\n patch: SetUrlListPatch;\n emptyValue: { kind: 'url_list'; items: [] };\n };\n date: {\n field: DateField;\n value: DateValue;\n patch: SetDatePatch;\n emptyValue: { kind: 'date'; value: null };\n };\n year: {\n field: YearField;\n value: YearValue;\n patch: SetYearPatch;\n emptyValue: { kind: 'year'; value: null };\n };\n table: {\n field: TableField;\n value: TableValue;\n patch: SetTablePatch;\n emptyValue: { kind: 'table'; rows: [] };\n };\n}\n\n// =============================================================================\n// Compile-time assertions - error if FieldTypeMap is incomplete\n// =============================================================================\n\n/**\n * Asserts that T has all keys from K.\n * Used to ensure FieldTypeMap covers all FieldKind values.\n */\ntype AssertAllKeys<K extends string, T extends Record<K, unknown>> = T;\n\n/** Compile-time check: FieldTypeMap must have entry for every FieldKind */\ntype _AssertMapComplete = AssertAllKeys<FieldKind, FieldTypeMap>;\n\n/** Compile-time check: FieldTypeMap keys must exactly match FieldKind */\ntype _AssertMapExact = keyof FieldTypeMap extends FieldKind\n ? FieldKind extends keyof FieldTypeMap\n ? true\n : never\n : never;\n\n// If either assertion fails, you'll get a type error here:\nconst _typeCheck: _AssertMapComplete = {} as FieldTypeMap;\nconst _exactCheck: _AssertMapExact = true;\n\n// =============================================================================\n// Derived union types - automatically include all registered types\n// =============================================================================\n\n/** Union of all Field kinds - derived from the registry */\nexport type Field = FieldTypeMap[FieldKind]['field'];\n\n/** Union of all FieldValue types - derived from the registry */\nexport type FieldValue = FieldTypeMap[FieldKind]['value'];\n\n/** Union of all set patch types - derived from the registry */\nexport type SetValuePatch = FieldTypeMap[FieldKind]['patch'];\n\n// =============================================================================\n// Exhaustiveness check helper\n// =============================================================================\n\n/**\n * Exhaustiveness check helper for switch statements.\n * If you add a new FieldKind but forget to handle it in a switch,\n * TypeScript will error because the kind won't be assignable to never.\n *\n * Usage:\n * ```ts\n * switch (field.kind) {\n * case \"string\": ...\n * case \"number\": ...\n * // ... all cases ...\n * default:\n * return assertNever(field.kind);\n * }\n * ```\n */\nexport function assertNever(x: never, message?: string): never {\n throw new Error(message ?? `Unexpected value: ${JSON.stringify(x)}`);\n}\n\n// =============================================================================\n// Empty value factory - type-safe way to create empty values\n// =============================================================================\n\n/**\n * Create an empty/default value for a field.\n * Exhaustiveness is checked at compile time.\n */\nexport function createEmptyValue(kind: FieldKind): FieldValue {\n switch (kind) {\n case 'string':\n return { kind: 'string', value: null };\n case 'number':\n return { kind: 'number', value: null };\n case 'string_list':\n return { kind: 'string_list', items: [] };\n case 'checkboxes':\n return { kind: 'checkboxes', values: {} };\n case 'single_select':\n return { kind: 'single_select', selected: null };\n case 'multi_select':\n return { kind: 'multi_select', selected: [] };\n case 'url':\n return { kind: 'url', value: null };\n case 'url_list':\n return { kind: 'url_list', items: [] };\n case 'date':\n return { kind: 'date', value: null };\n case 'year':\n return { kind: 'year', value: null };\n case 'table':\n return { kind: 'table', rows: [] };\n default:\n return assertNever(kind);\n }\n}\n\n// =============================================================================\n// Zod schema registry - ensures schemas match types\n// =============================================================================\n\nimport {\n StringFieldSchema,\n NumberFieldSchema,\n StringListFieldSchema,\n CheckboxesFieldSchema,\n SingleSelectFieldSchema,\n MultiSelectFieldSchema,\n UrlFieldSchema,\n UrlListFieldSchema,\n DateFieldSchema,\n YearFieldSchema,\n TableFieldSchema,\n StringValueSchema,\n NumberValueSchema,\n StringListValueSchema,\n CheckboxesValueSchema,\n SingleSelectValueSchema,\n MultiSelectValueSchema,\n UrlValueSchema,\n UrlListValueSchema,\n DateValueSchema,\n YearValueSchema,\n TableValueSchema,\n SetStringPatchSchema,\n SetNumberPatchSchema,\n SetStringListPatchSchema,\n SetCheckboxesPatchSchema,\n SetSingleSelectPatchSchema,\n SetMultiSelectPatchSchema,\n SetUrlPatchSchema,\n SetUrlListPatchSchema,\n SetDatePatchSchema,\n SetYearPatchSchema,\n SetTablePatchSchema,\n} from './coreTypes.js';\n\n/**\n * Zod schema registry - maps each kind to its schemas.\n * This ensures schemas are defined for every field kind.\n */\nexport const FIELD_SCHEMAS = {\n string: {\n field: StringFieldSchema,\n value: StringValueSchema,\n patch: SetStringPatchSchema,\n },\n number: {\n field: NumberFieldSchema,\n value: NumberValueSchema,\n patch: SetNumberPatchSchema,\n },\n string_list: {\n field: StringListFieldSchema,\n value: StringListValueSchema,\n patch: SetStringListPatchSchema,\n },\n checkboxes: {\n field: CheckboxesFieldSchema,\n value: CheckboxesValueSchema,\n patch: SetCheckboxesPatchSchema,\n },\n single_select: {\n field: SingleSelectFieldSchema,\n value: SingleSelectValueSchema,\n patch: SetSingleSelectPatchSchema,\n },\n multi_select: {\n field: MultiSelectFieldSchema,\n value: MultiSelectValueSchema,\n patch: SetMultiSelectPatchSchema,\n },\n url: {\n field: UrlFieldSchema,\n value: UrlValueSchema,\n patch: SetUrlPatchSchema,\n },\n url_list: {\n field: UrlListFieldSchema,\n value: UrlListValueSchema,\n patch: SetUrlListPatchSchema,\n },\n date: {\n field: DateFieldSchema,\n value: DateValueSchema,\n patch: SetDatePatchSchema,\n },\n year: {\n field: YearFieldSchema,\n value: YearValueSchema,\n patch: SetYearPatchSchema,\n },\n table: {\n field: TableFieldSchema,\n value: TableValueSchema,\n patch: SetTablePatchSchema,\n },\n} as const satisfies Record<\n FieldKind,\n {\n field: z.ZodType;\n value: z.ZodType;\n patch: z.ZodType;\n }\n>;\n\n/** Type-safe schema lookup by kind */\nexport function getFieldSchemas<K extends FieldKind>(kind: K) {\n return FIELD_SCHEMAS[kind];\n}\n","/**\n * Markdown Table Parsing for Table Fields.\n *\n * Parses GFM-style pipe tables from markdown content within table-field tags.\n * Handles cell value parsing with type coercion and sentinel detection.\n */\n\nimport type {\n TableColumn,\n ColumnTypeName,\n CellResponse,\n TableRowResponse,\n TableValue,\n Id,\n} from '../coreTypes.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Result of parsing a markdown table */\nexport type ParseTableResult = { ok: true; value: TableValue } | { ok: false; error: string };\n\n/** Parsed raw table structure before type coercion */\nexport interface ParsedRawTable {\n headers: string[];\n rows: string[][];\n}\n\n// =============================================================================\n// Sentinel Detection\n// =============================================================================\n\n/** Sentinel pattern: %SKIP% or %SKIP:reason% or %SKIP(reason)% */\nconst SKIP_PATTERN = /^%SKIP(?:[:(](.*))?[)]?%$/i;\n\n/** Sentinel pattern: %ABORT% or %ABORT:reason% or %ABORT(reason)% */\nconst ABORT_PATTERN = /^%ABORT(?:[:(](.*))?[)]?%$/i;\n\n/** Markdown link pattern: [text](url) */\nconst MARKDOWN_LINK_PATTERN = /^\\[([^\\]]*)\\]\\(([^)]+)\\)$/;\n\n/**\n * Extract URL from markdown link format if present.\n * Returns the URL part from [text](url) format, or the original value if not a markdown link.\n */\nfunction extractUrlFromMarkdownLink(value: string): string {\n const match = MARKDOWN_LINK_PATTERN.exec(value);\n if (match) {\n return match[2]!; // Return the URL part\n }\n return value;\n}\n\n/**\n * Detect if a cell value is a sentinel.\n */\nfunction parseSentinel(value: string): { type: 'skip' | 'abort'; reason?: string } | null {\n const trimmed = value.trim();\n\n const skipMatch = SKIP_PATTERN.exec(trimmed);\n if (skipMatch) {\n return { type: 'skip', reason: skipMatch[1] };\n }\n\n const abortMatch = ABORT_PATTERN.exec(trimmed);\n if (abortMatch) {\n return { type: 'abort', reason: abortMatch[1] };\n }\n\n return null;\n}\n\n// =============================================================================\n// Cell Value Parsing\n// =============================================================================\n\n/**\n * Parse a cell value according to its column type.\n * Returns a CellResponse with appropriate state.\n */\nexport function parseCellValue(rawValue: string, columnType: ColumnTypeName): CellResponse {\n const trimmed = rawValue.trim();\n\n // Check for empty cell\n if (!trimmed) {\n return { state: 'skipped' };\n }\n\n // Check for sentinels\n const sentinel = parseSentinel(trimmed);\n if (sentinel) {\n return {\n state: sentinel.type === 'skip' ? 'skipped' : 'aborted',\n reason: sentinel.reason,\n };\n }\n\n // Parse based on column type\n switch (columnType) {\n case 'string':\n return { state: 'answered', value: trimmed };\n\n case 'number': {\n const num = parseFloat(trimmed);\n if (isNaN(num)) {\n // Invalid number - treat as string but this will fail validation\n return { state: 'answered', value: trimmed };\n }\n return { state: 'answered', value: num };\n }\n\n case 'url': {\n // Extract URL from markdown link format if present (e.g., [text](url) -> url)\n // This handles round-trip where URLs are serialized as markdown links\n const url = extractUrlFromMarkdownLink(trimmed);\n return { state: 'answered', value: url };\n }\n\n case 'date':\n // Date format validation - more thorough validation happens in validate.ts\n return { state: 'answered', value: trimmed };\n\n case 'year': {\n const year = parseInt(trimmed, 10);\n if (isNaN(year) || !Number.isInteger(year)) {\n // Invalid year - treat as string but this will fail validation\n return { state: 'answered', value: trimmed };\n }\n return { state: 'answered', value: year };\n }\n }\n}\n\n// =============================================================================\n// Raw Table Parsing\n// =============================================================================\n\n/**\n * Parse markdown table structure without type coercion.\n * Handles GFM pipe table format.\n */\nexport function parseRawMarkdownTable(content: string): ParseTableResult {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length < 2) {\n // Empty table or just header is ok\n if (lines.length === 0) {\n return { ok: true, value: { kind: 'table', rows: [] } };\n }\n // Just header row without separator\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n // Parse header row\n const headerLine = lines[0]!;\n const headers = parseTableRow(headerLine);\n if (headers.length === 0) {\n return { ok: false, error: 'Invalid table header row' };\n }\n\n // Validate separator row\n const separatorLine = lines[1]!;\n if (!isValidSeparator(separatorLine, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n\n // Parse data rows\n const dataRows: string[][] = [];\n for (let i = 2; i < lines.length; i++) {\n const row = parseTableRow(lines[i]!);\n // Normalize row length to match headers\n while (row.length < headers.length) {\n row.push('');\n }\n if (row.length > headers.length) {\n row.length = headers.length;\n }\n dataRows.push(row);\n }\n\n return {\n ok: true,\n value: { kind: 'table', rows: [] }, // Placeholder - actual rows are built with column context\n };\n}\n\n/**\n * Parse a table row into cell values.\n * Handles leading/trailing pipes and cell trimming.\n */\nfunction parseTableRow(line: string): string[] {\n let trimmed = line.trim();\n\n // Remove leading pipe\n if (trimmed.startsWith('|')) {\n trimmed = trimmed.slice(1);\n }\n\n // Remove trailing pipe\n if (trimmed.endsWith('|')) {\n trimmed = trimmed.slice(0, -1);\n }\n\n // Split by pipe and trim each cell\n return trimmed.split('|').map((cell) => cell.trim());\n}\n\n/**\n * Extract header labels from table content.\n * Returns array of header labels from the first row, or empty array if no valid header.\n */\nexport function extractTableHeaderLabels(content: string | null): string[] {\n if (!content || content.trim() === '') {\n return [];\n }\n\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length === 0) {\n return [];\n }\n\n return parseTableRow(lines[0]!);\n}\n\n/**\n * Check if a line is a valid table separator row.\n * Each cell should contain only dashes and optional colons for alignment.\n */\nfunction isValidSeparator(line: string, expectedCols: number): boolean {\n const cells = parseTableRow(line);\n\n // Must have same number of columns as header\n if (cells.length !== expectedCols) {\n return false;\n }\n\n // Each cell must match the separator pattern\n const separatorPattern = /^:?-+:?$/;\n return cells.every((cell) => separatorPattern.test(cell.trim()));\n}\n\n// =============================================================================\n// Full Table Parsing with Schema\n// =============================================================================\n\n/**\n * Parse a markdown table with column schema for type coercion.\n *\n * @param content - The markdown table content\n * @param columns - Column definitions from the table field schema\n * @param dataStartLine - Optional line index where data rows start (skips header validation)\n * @returns Parsed table value with typed cells\n */\nexport function parseMarkdownTable(\n content: string,\n columns: TableColumn[],\n dataStartLine?: number,\n): ParseTableResult {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n // Empty content - return empty table\n if (lines.length === 0) {\n return { ok: true, value: { kind: 'table', rows: [] } };\n }\n\n // Need at least header and separator (unless empty)\n if (lines.length < 2) {\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n // Parse header row\n const headerLine = lines[0]!;\n const headers = parseTableRow(headerLine);\n\n // Validate separator row\n const separatorLine = lines[1]!;\n if (!isValidSeparator(separatorLine, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n\n // When dataStartLine is provided, parse data positionally based on columns\n // (attribute-based column definitions)\n if (dataStartLine !== undefined) {\n const rows: TableRowResponse[] = [];\n\n for (let i = dataStartLine; i < lines.length; i++) {\n const rawCells = parseTableRow(lines[i]!);\n const row: TableRowResponse = {};\n\n for (let j = 0; j < columns.length; j++) {\n const column = columns[j]!;\n const rawValue = rawCells[j] ?? '';\n row[column.id] = parseCellValue(rawValue, column.type);\n }\n\n rows.push(row);\n }\n\n return { ok: true, value: { kind: 'table', rows } };\n }\n\n // Build column ID to index mapping from headers (for inline column parsing)\n // Headers should match column IDs or labels\n const columnIdToIndex = new Map<Id, number>();\n\n for (let i = 0; i < headers.length; i++) {\n const header = headers[i]!;\n // Find column by ID or label\n const column = columns.find((c) => c.id === header || c.label === header);\n if (column) {\n columnIdToIndex.set(column.id, i);\n }\n }\n\n // Parse data rows\n const rows: TableRowResponse[] = [];\n\n for (let i = 2; i < lines.length; i++) {\n const rawCells = parseTableRow(lines[i]!);\n const row: TableRowResponse = {};\n\n // Process each column\n for (const column of columns) {\n const cellIndex = columnIdToIndex.get(column.id);\n const rawValue = cellIndex !== undefined ? (rawCells[cellIndex] ?? '') : '';\n row[column.id] = parseCellValue(rawValue, column.type);\n }\n\n rows.push(row);\n }\n\n return { ok: true, value: { kind: 'table', rows } };\n}\n\n/**\n * Parse just the raw table structure without schema.\n * Useful for validation and error reporting.\n */\nexport function parseRawTable(\n content: string,\n): { ok: true; headers: string[]; rows: string[][] } | { ok: false; error: string } {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length === 0) {\n return { ok: true, headers: [], rows: [] };\n }\n\n if (lines.length < 2) {\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n const headers = parseTableRow(lines[0]!);\n const separatorLine = lines[1]!;\n\n if (!isValidSeparator(separatorLine, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n\n const rows: string[][] = [];\n for (let i = 2; i < lines.length; i++) {\n const row = parseTableRow(lines[i]!);\n // Normalize row length\n while (row.length < headers.length) {\n row.push('');\n }\n if (row.length > headers.length) {\n row.length = headers.length;\n }\n rows.push(row);\n }\n\n return { ok: true, headers, rows };\n}\n\n// =============================================================================\n// Column Extraction from Inline Table\n// =============================================================================\n\n/**\n * Result of extracting column definitions from inline table format.\n */\nexport type ExtractColumnsResult =\n | {\n ok: true;\n columns: TableColumn[];\n dataStartLine: number; // Line index where data rows start (after separator)\n }\n | {\n ok: false;\n error: string;\n };\n\n/**\n * Slugify a label to create a valid column ID.\n * Converts \"Start Date\" -> \"start_date\", \"Name\" -> \"name\", etc.\n */\nfunction slugify(label: string): string {\n return label\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '');\n}\n\n/**\n * Check if a cell value looks like a column type definition.\n * Valid formats: \"string\", \"number\", \"url\", \"date\", \"year\"\n * With optional \",required\" suffix.\n */\nfunction isTypeDefinition(cell: string): boolean {\n const typePattern = /^(string|number|url|date|year)(,required)?$/i;\n return typePattern.test(cell.trim());\n}\n\n/**\n * Parse a column type definition cell.\n * Format: \"type\" or \"type,required\"\n */\nfunction parseTypeCell(cell: string): { type: ColumnTypeName; required: boolean } {\n const trimmed = cell.trim().toLowerCase();\n const parts = trimmed.split(',');\n const type = parts[0] as ColumnTypeName;\n const required = parts.length > 1 && parts[1] === 'required';\n return { type, required };\n}\n\n/**\n * Extract column definitions from inline table format.\n *\n * Supports two formats:\n * 1. Simple format (header + separator + data):\n * | Name | Age |\n * |------|-----|\n * | Alice | 30 |\n * -> Columns default to type=string, required=false\n *\n * 2. Full format (header + type row + separator + data):\n * | Name | Age |\n * | string,required | number |\n * |------|-----|\n * | Alice | 30 |\n */\nexport function extractColumnsFromTable(content: string): ExtractColumnsResult {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length < 2) {\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n // Parse header row\n const headers = parseTableRow(lines[0]!);\n if (headers.length === 0) {\n return { ok: false, error: 'Invalid table header row' };\n }\n\n // Check second row - is it a type row or separator?\n const secondRow = parseTableRow(lines[1]!);\n const isSecondRowTypes =\n secondRow.length > 0 && secondRow.every((cell) => isTypeDefinition(cell));\n\n let typeRow: { type: ColumnTypeName; required: boolean }[] | undefined;\n let separatorLineIndex: number;\n\n if (isSecondRowTypes) {\n // Second row is type definitions\n if (secondRow.length !== headers.length) {\n return { ok: false, error: 'Type row must have same number of columns as header' };\n }\n typeRow = secondRow.map((cell) => parseTypeCell(cell));\n separatorLineIndex = 2;\n\n // Validate we have a separator row\n if (lines.length < 3) {\n return { ok: false, error: 'Table with type row must have a separator row' };\n }\n if (!isValidSeparator(lines[2]!, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n } else {\n // Second row should be separator\n if (!isValidSeparator(lines[1]!, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n separatorLineIndex = 1;\n }\n\n // Build columns\n const columns: TableColumn[] = headers.map((header, i) => {\n const id = slugify(header) || `col${i}`;\n const label = header;\n const typeDef = typeRow?.[i] ?? { type: 'string' as ColumnTypeName, required: false };\n return {\n id,\n label,\n type: typeDef.type,\n required: typeDef.required,\n };\n });\n\n return {\n ok: true,\n columns,\n dataStartLine: separatorLineIndex + 1,\n };\n}\n\n/**\n * Parse a markdown table with columns extracted from inline format.\n * Used when columnIds attribute is not provided.\n */\nexport function parseInlineTable(content: string): ParseTableResult {\n const extractResult = extractColumnsFromTable(content);\n if (!extractResult.ok) {\n return { ok: false, error: extractResult.error };\n }\n\n const { columns, dataStartLine } = extractResult;\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n // Parse data rows\n const rows: TableRowResponse[] = [];\n for (let i = dataStartLine; i < lines.length; i++) {\n const rawCells = parseTableRow(lines[i]!);\n const row: TableRowResponse = {};\n\n for (let j = 0; j < columns.length; j++) {\n const column = columns[j]!;\n const rawValue = rawCells[j] ?? '';\n row[column.id] = parseCellValue(rawValue, column.type);\n }\n\n rows.push(row);\n }\n\n return { ok: true, value: { kind: 'table', rows } };\n}\n","/**\n * Field kind parsers for Markform.\n *\n * This module contains the parsing logic for each field kind:\n * string, number, string-list, single-select, multi-select, checkboxes,\n * url, url-list, date, and year.\n */\n\nimport type { Node } from '@markdoc/markdoc';\n\nimport { AGENT_ROLE, DEFAULT_PRIORITY } from '../settings.js';\nimport { FIELD_KINDS, type FieldKind } from './fieldRegistry.js';\nimport type {\n ApprovalMode,\n CheckboxesField,\n CheckboxesValue,\n CheckboxMode,\n CheckboxValue,\n ColumnTypeName,\n ColumnTypeSpec,\n DateField,\n DateValue,\n Field,\n FieldResponse,\n FieldValue,\n MultiSelectField,\n MultiSelectValue,\n NumberField,\n NumberValue,\n Option,\n SingleSelectField,\n SingleSelectValue,\n StringField,\n StringListField,\n StringListValue,\n StringValue,\n TableColumn,\n TableField,\n TableValue,\n UrlField,\n UrlListField,\n UrlListValue,\n UrlValue,\n ValidatorRef,\n YearField,\n YearValue,\n} from './coreTypes.js';\nimport {\n CHECKBOX_MARKERS,\n extractFenceValue,\n extractTableContent,\n extractOptionItems,\n getBooleanAttr,\n getNumberAttr,\n getStringArrayAttr,\n getStringAttr,\n getValidateAttr,\n isTagNode,\n parseOptionText,\n} from './parseHelpers.js';\nimport { MarkformParseError } from '../errors.js';\nimport { tryParseSentinelResponse } from './parseSentinels.js';\nimport { parseMarkdownTable, extractTableHeaderLabels } from './table/parseTable.js';\n\n// =============================================================================\n// Field Response Helpers\n// =============================================================================\n\n/**\n * Determine if a field value is empty.\n * For old forms without state attributes, this infers whether the field has been filled.\n */\nexport function isValueEmpty(value: FieldValue): boolean {\n switch (value.kind) {\n case 'string':\n case 'number':\n case 'url':\n case 'date':\n case 'year':\n return value.value === null;\n case 'string_list':\n case 'url_list':\n return value.items.length === 0;\n case 'single_select':\n return value.selected === null;\n case 'multi_select':\n return value.selected.length === 0;\n case 'checkboxes': {\n // Empty if all checkboxes are in default unchecked state (todo/unfilled)\n const values = Object.values(value.values);\n return values.every((v) => v === 'todo' || v === 'unfilled');\n }\n case 'table':\n return (value.rows?.length ?? 0) === 0;\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = value;\n throw new Error(`Unhandled field value kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n}\n\n/**\n * Create a FieldResponse from a FieldValue.\n * For old forms without state attributes, infers state from value content.\n */\nfunction createFieldResponse(value: FieldValue): FieldResponse {\n if (isValueEmpty(value)) {\n return { state: 'unanswered' };\n }\n return { state: 'answered', value };\n}\n\n/**\n * Parse state attribute from field node and validate consistency.\n * Returns a FieldResponse based on state attribute, sentinel values, or value content.\n */\nexport function parseFieldResponse(\n node: Node,\n value: FieldValue,\n fieldId: string,\n required: boolean,\n): FieldResponse {\n const stateAttr = getStringAttr(node, 'state');\n const isFilled = !isValueEmpty(value);\n\n // Validate state attribute value if present\n if (stateAttr !== undefined) {\n if (\n stateAttr !== 'empty' &&\n stateAttr !== 'answered' &&\n stateAttr !== 'skipped' &&\n stateAttr !== 'aborted'\n ) {\n throw new MarkformParseError(\n `Invalid state attribute '${stateAttr}' on field '${fieldId}'. Must be empty, answered, skipped, or aborted`,\n );\n }\n\n // Validate state vs filled consistency\n if (stateAttr === 'skipped' || stateAttr === 'aborted') {\n if (isFilled) {\n throw new MarkformParseError(\n `Field '${fieldId}' has state='${stateAttr}' but contains a value. ${stateAttr} fields cannot have values.`,\n );\n }\n }\n\n // Validate skipped on required fields\n if (stateAttr === 'skipped' && required) {\n throw new MarkformParseError(\n `Field '${fieldId}' is required but has state='skipped'. Cannot skip required fields.`,\n );\n }\n\n // Return response based on explicit state attribute\n if (stateAttr === 'skipped') {\n return { state: 'skipped' };\n }\n if (stateAttr === 'aborted') {\n return { state: 'aborted' };\n }\n if (stateAttr === 'empty') {\n return { state: 'unanswered' };\n }\n if (stateAttr === 'answered') {\n if (!isFilled) {\n throw new MarkformParseError(`Field '${fieldId}' has state='answered' but has no value`);\n }\n return { state: 'answered', value };\n }\n }\n\n // No state attribute - infer from value content (backward compatibility)\n return createFieldResponse(value);\n}\n\n/**\n * Get priority attribute value or default to DEFAULT_PRIORITY.\n */\nfunction getPriorityAttr(node: Node): 'high' | 'medium' | 'low' {\n const value = getStringAttr(node, 'priority');\n if (value === 'high' || value === 'medium' || value === 'low') {\n return value;\n }\n return DEFAULT_PRIORITY;\n}\n\n// =============================================================================\n// Common Field Attribute Helpers\n// =============================================================================\n\ninterface BaseFieldAttrs {\n id: string;\n label: string;\n required: boolean;\n}\n\n/**\n * Parse and validate base field attributes (id, label, required).\n * Throws ParseError if id or label is missing.\n */\nfunction parseBaseFieldAttrs(node: Node, kind: FieldKind): BaseFieldAttrs {\n const id = getStringAttr(node, 'id');\n const label = getStringAttr(node, 'label');\n\n if (!id) {\n throw new MarkformParseError(`field kind=\"${kind}\" missing required 'id' attribute`);\n }\n if (!label) {\n throw new MarkformParseError(`field '${id}' missing required 'label' attribute`);\n }\n\n const required = getBooleanAttr(node, 'required') ?? false;\n return { id, label, required };\n}\n\ninterface CommonFieldAttrs {\n priority: 'high' | 'medium' | 'low';\n role: string;\n validate?: ValidatorRef[];\n report?: boolean;\n parallel?: string;\n order?: number;\n}\n\n/**\n * Get common field attributes (priority, role, validate, report, parallel, order).\n */\nfunction getCommonFieldAttrs(node: Node): CommonFieldAttrs {\n return {\n priority: getPriorityAttr(node),\n role: getStringAttr(node, 'role') ?? AGENT_ROLE,\n validate: getValidateAttr(node),\n report: getBooleanAttr(node, 'report'),\n parallel: getStringAttr(node, 'parallel'),\n order: getNumberAttr(node, 'order'),\n };\n}\n\n// =============================================================================\n// Placeholder/Examples Validation Helpers\n// =============================================================================\n\n/**\n * Validate that placeholder/examples are not used on chooser fields.\n * Throws ParseError if either attribute is present.\n */\nfunction validateNoPlaceholderExamples(node: Node, fieldType: string, fieldId: string): void {\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n if (placeholder !== undefined) {\n throw new MarkformParseError(\n `${fieldType} '${fieldId}' has 'placeholder' attribute, but placeholder is only valid on text-entry fields (string, number, string-list, url, url-list)`,\n );\n }\n if (examples !== undefined) {\n throw new MarkformParseError(\n `${fieldType} '${fieldId}' has 'examples' attribute, but examples is only valid on text-entry fields (string, number, string-list, url, url-list)`,\n );\n }\n}\n\n/**\n * Check if a string is a valid URL.\n */\nfunction isValidUrl(str: string): boolean {\n try {\n new URL(str);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate examples for number fields - all must parse as numbers.\n */\nfunction validateNumberExamples(examples: string[] | undefined, fieldId: string): void {\n if (!examples) return;\n for (const example of examples) {\n const parsed = Number(example);\n if (Number.isNaN(parsed)) {\n throw new MarkformParseError(\n `number-field '${fieldId}' has invalid example '${example}' - must be a valid number`,\n );\n }\n }\n}\n\n/**\n * Validate examples for URL fields - all must be valid URLs.\n */\nfunction validateUrlExamples(examples: string[] | undefined, fieldId: string): void {\n if (!examples) return;\n for (const example of examples) {\n if (!isValidUrl(example)) {\n throw new MarkformParseError(\n `url-field '${fieldId}' has invalid example '${example}' - must be a valid URL`,\n );\n }\n }\n}\n\n/**\n * Warn if placeholder doesn't match the expected type.\n * Returns a warning message or undefined.\n * Note: Currently unused as the warning system is not yet implemented.\n */\nfunction _warnPlaceholderTypeMismatch(\n placeholder: string | undefined,\n fieldType: 'number' | 'url',\n fieldId: string,\n): string | undefined {\n if (!placeholder) return undefined;\n\n if (fieldType === 'number') {\n const parsed = Number(placeholder);\n if (Number.isNaN(parsed)) {\n return `number-field '${fieldId}' has placeholder '${placeholder}' that doesn't parse as a number`;\n }\n } else if (fieldType === 'url') {\n if (!isValidUrl(placeholder)) {\n return `url-field '${fieldId}' has placeholder '${placeholder}' that doesn't look like a valid URL`;\n }\n }\n return undefined;\n}\n\n// =============================================================================\n// String Field Parser\n// =============================================================================\n\n/**\n * Parse a string-field tag.\n */\nexport function parseStringField(node: Node): { field: StringField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'string');\n\n const field: StringField = {\n kind: 'string',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n multiline: getBooleanAttr(node, 'multiline'),\n pattern: getStringAttr(node, 'pattern'),\n minLength: getNumberAttr(node, 'minLength'),\n maxLength: getNumberAttr(node, 'maxLength'),\n placeholder: getStringAttr(node, 'placeholder'),\n examples: getStringArrayAttr(node, 'examples'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : null;\n const value: StringValue = {\n kind: 'string',\n value: trimmedContent,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Number Field Parser\n// =============================================================================\n\n/**\n * Parse a number-field tag.\n */\nexport function parseNumberField(node: Node): { field: NumberField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'number');\n\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n // Validate examples are valid numbers\n validateNumberExamples(examples, id);\n\n // Note: Placeholder type mismatch is a warning, not an error\n // The warnPlaceholderTypeMismatch function is available but warnings are not yet surfaced\n\n const field: NumberField = {\n kind: 'number',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n min: getNumberAttr(node, 'min'),\n max: getNumberAttr(node, 'max'),\n integer: getBooleanAttr(node, 'integer'),\n placeholder,\n examples,\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse number normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : '';\n let numValue: number | null = null;\n if (trimmedContent) {\n const parsed = Number(trimmedContent);\n if (!Number.isNaN(parsed)) {\n numValue = parsed;\n }\n }\n\n const value: NumberValue = {\n kind: 'number',\n value: numValue,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// String List Field Parser\n// =============================================================================\n\n/**\n * Parse a string-list tag.\n */\nexport function parseStringListField(node: Node): {\n field: StringListField;\n response: FieldResponse;\n} {\n const { id, label, required } = parseBaseFieldAttrs(node, 'string_list');\n\n const field: StringListField = {\n kind: 'string_list',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n minItems: getNumberAttr(node, 'minItems'),\n maxItems: getNumberAttr(node, 'maxItems'),\n itemMinLength: getNumberAttr(node, 'itemMinLength'),\n itemMaxLength: getNumberAttr(node, 'itemMaxLength'),\n uniqueItems: getBooleanAttr(node, 'uniqueItems'),\n placeholder: getStringAttr(node, 'placeholder'),\n examples: getStringArrayAttr(node, 'examples'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse list normally\n const fenceContent = extractFenceValue(node);\n const items: string[] = [];\n if (fenceContent !== null) {\n const lines = fenceContent.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n items.push(trimmed);\n }\n }\n }\n\n const value: StringListValue = {\n kind: 'string_list',\n items,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Option Parsing (for Select/Checkbox fields)\n// =============================================================================\n\n/**\n * Parse options from a select/checkbox field.\n */\nfunction parseOptions(\n node: Node,\n fieldId: string,\n): { options: Option[]; selected: Record<string, CheckboxValue> } {\n const items = extractOptionItems(node);\n const options: Option[] = [];\n const selected: Record<string, CheckboxValue> = {};\n const seenIds = new Set<string>();\n\n for (const item of items) {\n const parsed = parseOptionText(item.text);\n if (!parsed) {\n continue;\n }\n\n if (!item.id) {\n throw new MarkformParseError(\n `Option in field '${fieldId}' missing ID annotation. Use {% #option_id %}`,\n );\n }\n\n if (seenIds.has(item.id)) {\n throw new MarkformParseError(`Duplicate option ID '${item.id}' in field '${fieldId}'`);\n }\n seenIds.add(item.id);\n\n options.push({ id: item.id, label: parsed.label });\n\n const state = CHECKBOX_MARKERS[parsed.marker];\n if (state !== undefined) {\n selected[item.id] = state;\n }\n }\n\n return { options, selected };\n}\n\n// =============================================================================\n// Single Select Field Parser\n// =============================================================================\n\n/**\n * Parse a single-select tag.\n */\nexport function parseSingleSelectField(node: Node): {\n field: SingleSelectField;\n response: FieldResponse;\n} {\n const { id, label, required } = parseBaseFieldAttrs(node, 'single_select');\n\n // Validate that placeholder/examples are not used on chooser fields\n validateNoPlaceholderExamples(node, 'single-select', id);\n\n const { options, selected } = parseOptions(node, id);\n\n const field: SingleSelectField = {\n kind: 'single_select',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n options,\n };\n\n // Find the selected option (exactly one with done/[x] state)\n let selectedOption: string | null = null;\n for (const [optId, state] of Object.entries(selected)) {\n if (state === 'done') {\n selectedOption = optId;\n break;\n }\n }\n\n const value: SingleSelectValue = {\n kind: 'single_select',\n selected: selectedOption,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Multi Select Field Parser\n// =============================================================================\n\n/**\n * Parse a multi-select tag.\n */\nexport function parseMultiSelectField(node: Node): {\n field: MultiSelectField;\n response: FieldResponse;\n} {\n const { id, label, required } = parseBaseFieldAttrs(node, 'multi_select');\n\n // Validate that placeholder/examples are not used on chooser fields\n validateNoPlaceholderExamples(node, 'multi-select', id);\n\n const { options, selected } = parseOptions(node, id);\n\n const field: MultiSelectField = {\n kind: 'multi_select',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n options,\n minSelections: getNumberAttr(node, 'minSelections'),\n maxSelections: getNumberAttr(node, 'maxSelections'),\n };\n\n // Collect all selected options (those with done/[x] state)\n const selectedOptions: string[] = [];\n for (const [optId, state] of Object.entries(selected)) {\n if (state === 'done') {\n selectedOptions.push(optId);\n }\n }\n\n const value: MultiSelectValue = {\n kind: 'multi_select',\n selected: selectedOptions,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Checkboxes Field Parser\n// =============================================================================\n\n/**\n * Parse a checkboxes tag.\n */\nexport function parseCheckboxesField(node: Node): {\n field: CheckboxesField;\n response: FieldResponse;\n} {\n // Checkboxes has special id/label handling (can't use parseBaseFieldAttrs due to required logic)\n const id = getStringAttr(node, 'id');\n const label = getStringAttr(node, 'label');\n\n if (!id) {\n throw new MarkformParseError('field kind=\"checkboxes\" missing required \\'id\\' attribute');\n }\n if (!label) {\n throw new MarkformParseError(`field '${id}' missing required 'label' attribute`);\n }\n\n // Validate that placeholder/examples are not used on chooser fields\n validateNoPlaceholderExamples(node, 'checkboxes', id);\n\n const { options, selected } = parseOptions(node, id);\n\n const checkboxModeStr = getStringAttr(node, 'checkboxMode');\n let checkboxMode: CheckboxMode = 'multi'; // default\n if (\n checkboxModeStr === 'multi' ||\n checkboxModeStr === 'simple' ||\n checkboxModeStr === 'explicit'\n ) {\n checkboxMode = checkboxModeStr;\n }\n\n const approvalModeStr = getStringAttr(node, 'approvalMode');\n let approvalMode: ApprovalMode = 'none'; // default\n if (approvalModeStr === 'blocking') {\n approvalMode = 'blocking';\n }\n\n // Handle required attribute based on checkboxMode:\n // - explicit mode is inherently required (cannot be set to false)\n // - multi/simple modes default to optional (false)\n const explicitRequired = getBooleanAttr(node, 'required');\n let required: boolean;\n if (checkboxMode === 'explicit') {\n if (explicitRequired === false) {\n throw new MarkformParseError(\n `Checkbox field \"${label}\" has checkboxMode=\"explicit\" which is inherently required. ` +\n `Cannot set required=false. Remove required attribute or change checkboxMode.`,\n );\n }\n required = true; // explicit mode is always required\n } else {\n required = explicitRequired ?? false; // multi/simple default to optional\n }\n\n const field: CheckboxesField = {\n kind: 'checkboxes',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n checkboxMode,\n minDone: getNumberAttr(node, 'minDone'),\n options,\n approvalMode,\n };\n\n // Initialize all options to their default state based on mode\n const values: Record<string, CheckboxValue> = {};\n\n for (const opt of options) {\n const state = selected[opt.id];\n if (state === undefined || state === 'todo') {\n // For explicit mode, \"todo\" (from [ ]) means \"unfilled\"\n values[opt.id] = checkboxMode === 'explicit' ? 'unfilled' : 'todo';\n } else {\n values[opt.id] = state;\n }\n }\n\n const value: CheckboxesValue = {\n kind: 'checkboxes',\n values,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// URL Field Parser\n// =============================================================================\n\n/**\n * Parse a url-field tag.\n */\nexport function parseUrlField(node: Node): { field: UrlField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'url');\n\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n // Validate examples are valid URLs\n validateUrlExamples(examples, id);\n\n // Note: Placeholder type mismatch is a warning, not an error\n\n const field: UrlField = {\n kind: 'url',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n placeholder,\n examples,\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : null;\n const value: UrlValue = {\n kind: 'url',\n value: trimmedContent,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// URL List Field Parser\n// =============================================================================\n\n/**\n * Parse a url-list tag.\n */\nexport function parseUrlListField(node: Node): { field: UrlListField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'url_list');\n\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n // Validate examples are valid URLs\n validateUrlExamples(examples, id);\n\n // Note: Placeholder type mismatch is a warning, not an error\n\n const field: UrlListField = {\n kind: 'url_list',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n minItems: getNumberAttr(node, 'minItems'),\n maxItems: getNumberAttr(node, 'maxItems'),\n uniqueItems: getBooleanAttr(node, 'uniqueItems'),\n placeholder,\n examples,\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse list normally\n const fenceContent = extractFenceValue(node);\n const items: string[] = [];\n if (fenceContent !== null) {\n const lines = fenceContent.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n items.push(trimmed);\n }\n }\n }\n\n const value: UrlListValue = {\n kind: 'url_list',\n items,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Date Field Parser\n// =============================================================================\n\n/**\n * Parse a date-field tag.\n */\nexport function parseDateField(node: Node): { field: DateField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'date');\n\n const field: DateField = {\n kind: 'date',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n min: getStringAttr(node, 'min'),\n max: getStringAttr(node, 'max'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse normally\n // Convert empty strings to null explicitly (nullish coalescing doesn't work for empty strings)\n const fenceContent = extractFenceValue(node);\n let dateValue: string | null = null;\n if (fenceContent !== null) {\n const trimmed = fenceContent.trim();\n if (trimmed.length > 0) {\n dateValue = trimmed;\n }\n }\n const value: DateValue = {\n kind: 'date',\n value: dateValue,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Year Field Parser\n// =============================================================================\n\n/**\n * Parse a year-field tag.\n */\nexport function parseYearField(node: Node): { field: YearField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'year');\n\n const field: YearField = {\n kind: 'year',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n min: getNumberAttr(node, 'min'),\n max: getNumberAttr(node, 'max'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse year normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : '';\n let yearValue: number | null = null;\n if (trimmedContent) {\n const parsed = Number.parseInt(trimmedContent, 10);\n if (!Number.isNaN(parsed)) {\n yearValue = parsed;\n }\n }\n\n const value: YearValue = {\n kind: 'year',\n value: yearValue,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Table Field Parser\n// =============================================================================\n\n/**\n * Validate column type string.\n */\nfunction isValidColumnType(type: unknown): type is ColumnTypeName {\n return (\n type === 'string' || type === 'number' || type === 'url' || type === 'date' || type === 'year'\n );\n}\n\n/**\n * Parse column definitions from attributes.\n * columnIds is required. columnLabels is optional (backfilled from tableHeaderLabels if provided).\n */\nfunction parseColumnsFromAttributes(\n node: Node,\n fieldId: string,\n tableHeaderLabels?: string[],\n): TableColumn[] {\n const columnIds = getStringArrayAttr(node, 'columnIds');\n const columnLabels = getStringArrayAttr(node, 'columnLabels');\n const columnTypesRaw = node.attributes?.columnTypes as ColumnTypeSpec[] | undefined;\n\n if (!columnIds || columnIds.length === 0) {\n throw new MarkformParseError(\n `table-field '${fieldId}' requires 'columnIds' attribute. ` +\n `Example: columnIds=[\"name\", \"title\", \"department\"]`,\n );\n }\n\n // Validate unique column IDs\n const seenIds = new Set<string>();\n for (const id of columnIds) {\n if (seenIds.has(id)) {\n throw new MarkformParseError(`table-field '${fieldId}' has duplicate column ID '${id}'`);\n }\n seenIds.add(id);\n }\n\n const columns: TableColumn[] = [];\n for (let i = 0; i < columnIds.length; i++) {\n const id = columnIds[i]!;\n // Priority: explicit columnLabels > table header labels > column ID\n const label = columnLabels?.[i] ?? tableHeaderLabels?.[i] ?? id;\n\n // Parse column type - can be string or { type, required }\n const typeSpec = columnTypesRaw?.[i];\n let type: ColumnTypeName = 'string'; // default\n let required = false;\n\n if (typeSpec !== undefined) {\n if (typeof typeSpec === 'string') {\n if (!isValidColumnType(typeSpec)) {\n throw new MarkformParseError(\n `table-field '${fieldId}' has invalid column type '${String(typeSpec)}' for column '${id}'. ` +\n `Valid types: string, number, url, date, year`,\n );\n }\n type = typeSpec;\n } else if (typeof typeSpec === 'object' && typeSpec !== null) {\n const typeObj = typeSpec as { type?: unknown; required?: boolean };\n if (!isValidColumnType(typeObj.type)) {\n throw new MarkformParseError(\n `table-field '${fieldId}' has invalid column type '${String(typeObj.type)}' for column '${id}'. ` +\n `Valid types: string, number, url, date, year`,\n );\n }\n type = typeObj.type;\n required = typeObj.required ?? false;\n }\n }\n\n columns.push({ id, label, type, required });\n }\n\n return columns;\n}\n\n/**\n * Parse a table-field tag.\n *\n * Column definitions come from attributes:\n * - columnIds (required): array of snake_case column identifiers\n * - columnLabels (optional): array of display labels (backfilled from table header row if omitted)\n * - columnTypes (optional): array of column types (defaults to all 'string')\n *\n * Table content is a raw markdown table inside the tag (NOT a value fence).\n */\nexport function parseTableField(node: Node): { field: TableField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'table');\n\n // Check for sentinel values first (entire field can be skipped/aborted)\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n\n // Get table content - raw markdown table inside the tag\n const tableContent = extractTableContent(node);\n\n // Extract header labels from table content for label backfilling\n const tableHeaderLabels = extractTableHeaderLabels(tableContent);\n\n // Parse columns from attributes (columnIds is required)\n const columns = parseColumnsFromAttributes(node, id, tableHeaderLabels);\n const dataStartLine = 2; // header + separator\n\n const field: TableField = {\n kind: 'table',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n columns,\n minRows: getNumberAttr(node, 'minRows'),\n maxRows: getNumberAttr(node, 'maxRows'),\n };\n\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n if (tableContent === null || tableContent.trim() === '') {\n // Empty table\n const value: TableValue = { kind: 'table', rows: [] };\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n }\n\n // Parse the markdown table with column schema\n // dataStartLine = 2 to skip header + separator rows\n const parseResult = parseMarkdownTable(tableContent, columns, dataStartLine);\n if (!parseResult.ok) {\n throw new MarkformParseError(`table-field '${id}': ${parseResult.error}`);\n }\n\n const response = parseFieldResponse(node, parseResult.value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Unified Field Parser\n// =============================================================================\n\n/**\n * Map legacy tag names to field kinds for error messages.\n */\nconst LEGACY_TAG_TO_KIND: Record<string, FieldKind> = {\n 'string-field': 'string',\n 'number-field': 'number',\n 'string-list': 'string_list',\n 'single-select': 'single_select',\n 'multi-select': 'multi_select',\n checkboxes: 'checkboxes',\n 'url-field': 'url',\n 'url-list': 'url_list',\n 'date-field': 'date',\n 'year-field': 'year',\n 'table-field': 'table',\n};\n\n/**\n * Recursively check if any children of a node are field tags.\n * Throws MarkformParseError if a nested field is found.\n */\nfunction validateNoNestedFields(node: Node, outerFieldId: string): void {\n if (!node.children || !Array.isArray(node.children)) {\n return;\n }\n\n for (const child of node.children) {\n if (isTagNode(child, 'field')) {\n const innerId = getStringAttr(child, 'id') ?? 'unknown';\n throw new MarkformParseError(\n `Field tags cannot be nested. Found '${innerId}' inside '${outerFieldId}'`,\n );\n }\n // Recursively check grandchildren\n validateNoNestedFields(child, outerFieldId);\n }\n}\n\n/**\n * Parse a unified field tag: {% field kind=\"...\" ... %}\n */\nfunction parseUnifiedField(node: Node): { field: Field; response: FieldResponse } {\n const kind = getStringAttr(node, 'kind');\n\n if (!kind) {\n throw new MarkformParseError(\"field tag missing required 'kind' attribute\");\n }\n\n // Validate no nested field tags before processing\n const fieldId = getStringAttr(node, 'id') ?? 'unknown';\n validateNoNestedFields(node, fieldId);\n\n // Validate kind is a known field kind\n if (!FIELD_KINDS.includes(kind as FieldKind)) {\n throw new MarkformParseError(\n `field tag has invalid kind '${kind}'. Valid kinds: ${FIELD_KINDS.join(', ')}`,\n );\n }\n\n // Dispatch to specific parsers based on kind\n switch (kind as FieldKind) {\n case 'string':\n return parseStringField(node);\n case 'number':\n return parseNumberField(node);\n case 'string_list':\n return parseStringListField(node);\n case 'single_select':\n return parseSingleSelectField(node);\n case 'multi_select':\n return parseMultiSelectField(node);\n case 'checkboxes':\n return parseCheckboxesField(node);\n case 'url':\n return parseUrlField(node);\n case 'url_list':\n return parseUrlListField(node);\n case 'date':\n return parseDateField(node);\n case 'year':\n return parseYearField(node);\n case 'table':\n return parseTableField(node);\n }\n}\n\n// =============================================================================\n// Field Dispatcher\n// =============================================================================\n\n/**\n * Parse a field tag and return field schema and response.\n * Accepts both unified field syntax {% field kind=\"...\" %} and legacy tags.\n */\nexport function parseField(node: Node): { field: Field; response: FieldResponse } | null {\n if (!isTagNode(node)) {\n return null;\n }\n\n // Handle unified field tag\n if (node.tag === 'field') {\n return parseUnifiedField(node);\n }\n\n // Reject legacy tags with clear error messages\n if (node.tag) {\n const kind = LEGACY_TAG_TO_KIND[node.tag];\n if (kind !== undefined) {\n throw new MarkformParseError(\n `Legacy field tag '${node.tag}' is no longer supported. Use {% field kind=\"${kind}\" %} instead`,\n );\n }\n }\n\n return null;\n}\n","/**\n * Low-level utilities for extracting heading information from markdown.\n *\n * This module provides functions to find headings and determine which headings\n * enclose a given position. Used by plan documents and ID injection.\n */\n\nimport type { SourceRange } from '../engine/coreTypes.js';\n\n/**\n * Information about a markdown heading.\n */\nexport interface HeadingInfo {\n /** Heading level (1-6 for h1-h6) */\n level: number;\n\n /** Heading text content (without # prefix) */\n title: string;\n\n /** Line number (1-indexed) where heading starts */\n line: number;\n\n /** Full source position */\n position: SourceRange;\n}\n\n// ATX heading pattern: 1-6 # chars, space, then title\nconst ATX_HEADING_PATTERN = /^(#{1,6})\\s+(.*)$/;\n\n/**\n * Find all headings in a markdown document.\n * Returns headings in document order.\n *\n * Only ATX-style headings (# Title) are recognized.\n * Headings inside fenced code blocks are ignored.\n */\nexport function findAllHeadings(markdown: string): HeadingInfo[] {\n const lines = markdown.split('\\n');\n const headings: HeadingInfo[] = [];\n let inCodeBlock = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const lineNumber = i + 1; // 1-indexed\n\n // Track code block state\n if (line.startsWith('```') || line.startsWith('~~~')) {\n inCodeBlock = !inCodeBlock;\n continue;\n }\n\n // Skip if inside code block\n if (inCodeBlock) {\n continue;\n }\n\n // Check for ATX heading\n const match = ATX_HEADING_PATTERN.exec(line);\n if (match) {\n const hashes = match[1] ?? '';\n const title = (match[2] ?? '').trim();\n\n headings.push({\n level: hashes.length,\n title,\n line: lineNumber,\n position: {\n start: { line: lineNumber, col: 1 },\n end: { line: lineNumber, col: line.length + 1 },\n },\n });\n }\n }\n\n return headings;\n}\n\n/**\n * Find all headings that enclose a given line position.\n * Returns headings from innermost (most specific) to outermost (least specific).\n *\n * A heading \"encloses\" a line if:\n * 1. The heading appears before the line\n * 2. No heading of equal or higher level appears between them\n *\n * @param markdown - The markdown source text\n * @param line - The line number (1-indexed)\n * @returns Array of enclosing headings, innermost first\n */\nexport function findEnclosingHeadings(markdown: string, line: number): HeadingInfo[] {\n if (line <= 0) {\n return [];\n }\n\n const allHeadings = findAllHeadings(markdown);\n\n // Filter to headings that appear before this line (not on the line)\n const precedingHeadings = allHeadings.filter((h) => h.line < line);\n\n if (precedingHeadings.length === 0) {\n return [];\n }\n\n // Build the enclosing headings list\n // Walk backwards through preceding headings and collect those that aren't\n // \"shadowed\" by a heading of equal or higher level\n const result: HeadingInfo[] = [];\n let minLevelSeen = Infinity;\n\n for (let i = precedingHeadings.length - 1; i >= 0; i--) {\n const heading = precedingHeadings[i];\n if (!heading) continue;\n\n // If this heading is at a higher level (smaller number) than any we've seen,\n // it encloses the position\n if (heading.level < minLevelSeen) {\n result.push(heading);\n minLevelSeen = heading.level;\n }\n }\n\n return result;\n}\n","/**\n * ID injection utilities for checkboxes and headers.\n *\n * Provides functions to find checkboxes in markdown and inject ID annotations\n * using generator functions. Used by plan documents and programmatic ID generation.\n */\n\nimport type { CheckboxValue, SourceRange } from './coreTypes.js';\nimport { CHECKBOX_MARKERS } from './parseHelpers.js';\nimport { findAllHeadings, findEnclosingHeadings } from '../markdown/markdownHeaders.js';\nimport type { HeadingInfo } from '../markdown/markdownHeaders.js';\nimport { MarkformParseError } from '../errors.js';\n\n// Re-export HeadingInfo for convenience\nexport type { HeadingInfo };\n\n/**\n * Information about a checkbox found in markdown.\n */\nexport interface CheckboxInfo {\n /** Existing ID, if any (from {% #id %} annotation) */\n id?: string;\n\n /** Checkbox label text */\n label: string;\n\n /** Current checkbox state from marker */\n state: CheckboxValue;\n\n /** Line number (1-indexed) where checkbox appears */\n line: number;\n\n /** Source position of the checkbox line */\n position: SourceRange;\n\n /** Enclosing headings, innermost first */\n enclosingHeadings: HeadingInfo[];\n}\n\n// Pattern to match checkbox list items: optional indent, -, [marker], text\n// Captures: 1=indent, 2=marker (including brackets), 3=rest of line\nconst CHECKBOX_PATTERN = /^(\\s*)-\\s+(\\[[^\\]]\\])\\s+(.*)$/;\n\n// Pattern to extract Markdoc ID annotation: {% #id %}\nconst MARKDOC_ID_PATTERN = /\\{%\\s*#(\\w+)\\s*%\\}/;\n\n// Pattern to extract HTML comment ID annotation: <!-- #id -->\nconst HTML_COMMENT_ID_PATTERN = /<!--\\s*#(\\w+)\\s*-->/;\n\n/**\n * Find all checkboxes in a markdown document.\n * Returns checkboxes in document order with enclosing heading info.\n */\nexport function findAllCheckboxes(markdown: string): CheckboxInfo[] {\n const lines = markdown.split('\\n');\n const checkboxes: CheckboxInfo[] = [];\n let inCodeBlock = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const lineNumber = i + 1; // 1-indexed\n\n // Track code block state\n if (line.trimStart().startsWith('```') || line.trimStart().startsWith('~~~')) {\n inCodeBlock = !inCodeBlock;\n continue;\n }\n\n // Skip if inside code block\n if (inCodeBlock) {\n continue;\n }\n\n // Check for checkbox pattern\n const match = CHECKBOX_PATTERN.exec(line);\n if (!match) {\n continue;\n }\n\n const marker = match[2] ?? '';\n const rest = match[3] ?? '';\n\n // Get checkbox state from marker\n const state = CHECKBOX_MARKERS[marker];\n if (state === undefined) {\n continue; // Invalid marker\n }\n\n // Extract label and ID\n let label = rest;\n let id: string | undefined;\n\n // Check for Markdoc ID annotation\n const markdocMatch = MARKDOC_ID_PATTERN.exec(rest);\n if (markdocMatch) {\n id = markdocMatch[1];\n label = rest.replace(MARKDOC_ID_PATTERN, '').trim();\n } else {\n // Check for HTML comment ID annotation\n const htmlMatch = HTML_COMMENT_ID_PATTERN.exec(rest);\n if (htmlMatch) {\n id = htmlMatch[1];\n label = rest.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n }\n\n // Get enclosing headings for this line\n const enclosingHeadings = findEnclosingHeadings(markdown, lineNumber);\n\n checkboxes.push({\n id,\n label,\n state,\n line: lineNumber,\n position: {\n start: { line: lineNumber, col: 1 },\n end: { line: lineNumber, col: line.length + 1 },\n },\n enclosingHeadings,\n });\n }\n\n return checkboxes;\n}\n\n/**\n * Options for ID injection.\n */\nexport interface InjectCheckboxIdsOptions {\n /**\n * Generator function to create IDs for checkboxes.\n * Receives checkbox info and 0-based index of checkboxes needing IDs.\n */\n generator: (info: CheckboxInfo, index: number) => string;\n\n /**\n * If true (default), only inject IDs for checkboxes missing them.\n * If false, replace all IDs.\n */\n onlyMissing?: boolean;\n}\n\n/**\n * Result of ID injection.\n */\nexport interface InjectIdsResult {\n /** Updated markdown with injected IDs */\n markdown: string;\n\n /** Number of IDs that were injected */\n injectedCount: number;\n\n /** Map of checkbox label to injected ID */\n injectedIds: Map<string, string>;\n}\n\n/**\n * Inject IDs into checkboxes in a markdown document.\n *\n * Uses a generator function to create unique IDs for each checkbox.\n * Throws if duplicate IDs are generated or if generated IDs conflict\n * with existing ones.\n */\nexport function injectCheckboxIds(\n markdown: string,\n options: InjectCheckboxIdsOptions,\n): InjectIdsResult {\n const { generator, onlyMissing = true } = options;\n const checkboxes = findAllCheckboxes(markdown);\n\n // Collect existing IDs (to check for conflicts)\n const existingIds = new Set<string>();\n for (const checkbox of checkboxes) {\n if (checkbox.id && onlyMissing) {\n existingIds.add(checkbox.id);\n }\n }\n\n // Determine which checkboxes need IDs\n const needsId = checkboxes.filter((cb) => (onlyMissing ? !cb.id : true));\n\n // Generate IDs and check for duplicates/conflicts\n const generatedIds = new Map<string, string>(); // label -> id\n const allGeneratedIds = new Set<string>();\n\n for (let i = 0; i < needsId.length; i++) {\n const checkbox = needsId[i]!;\n const newId = generator(checkbox, i);\n\n // Check for duplicate generated IDs\n if (allGeneratedIds.has(newId)) {\n throw new MarkformParseError(\n `Duplicate generated ID '${newId}' for checkbox '${checkbox.label}'`,\n { line: checkbox.line },\n );\n }\n\n // Check for conflict with existing IDs (only when onlyMissing=true)\n if (onlyMissing && existingIds.has(newId)) {\n throw new MarkformParseError(`Generated ID '${newId}' conflicts with existing ID`, {\n line: checkbox.line,\n });\n }\n\n allGeneratedIds.add(newId);\n generatedIds.set(checkbox.label, newId);\n }\n\n // If no changes needed, return original markdown\n if (needsId.length === 0) {\n return {\n markdown,\n injectedCount: 0,\n injectedIds: new Map(),\n };\n }\n\n // Apply changes to markdown (process in reverse order to preserve line numbers)\n const lines = markdown.split('\\n');\n const sortedByLine = [...needsId].sort((a, b) => b.line - a.line);\n\n for (const checkbox of sortedByLine) {\n const lineIndex = checkbox.line - 1;\n const line = lines[lineIndex]!;\n const newId = generatedIds.get(checkbox.label)!;\n\n // Remove existing ID annotation if replacing\n let updatedLine = line;\n if (!onlyMissing || checkbox.id) {\n // Remove existing Markdoc ID\n updatedLine = updatedLine.replace(MARKDOC_ID_PATTERN, '').trim();\n // Remove existing HTML comment ID\n updatedLine = updatedLine.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n\n // Append new ID annotation\n lines[lineIndex] = `${updatedLine} {% #${newId} %}`;\n }\n\n return {\n markdown: lines.join('\\n'),\n injectedCount: needsId.length,\n injectedIds: generatedIds,\n };\n}\n\n/**\n * Options for header ID injection.\n */\nexport interface InjectHeaderIdsOptions {\n /**\n * Generator function to create IDs for headings.\n * Receives heading info and 0-based index of headings needing IDs.\n */\n generator: (info: HeadingInfo, index: number) => string;\n\n /**\n * If true (default), only inject IDs for headings missing them.\n * If false, replace all IDs.\n */\n onlyMissing?: boolean;\n\n /**\n * Heading levels to process. Defaults to all levels [1, 2, 3, 4, 5, 6].\n */\n levels?: number[];\n}\n\n/**\n * Extended HeadingInfo that includes existing ID if present.\n */\ninterface HeadingWithId extends HeadingInfo {\n id?: string;\n}\n\n/**\n * Find all headings with their existing IDs.\n * Strips ID annotations from title for clean generator input.\n */\nfunction findAllHeadingsWithIds(markdown: string): HeadingWithId[] {\n const headings = findAllHeadings(markdown);\n const lines = markdown.split('\\n');\n\n return headings.map((heading) => {\n const line = lines[heading.line - 1] ?? '';\n\n // Check for existing ID annotation\n let id: string | undefined;\n let cleanTitle = heading.title;\n\n const markdocMatch = MARKDOC_ID_PATTERN.exec(line);\n if (markdocMatch) {\n id = markdocMatch[1];\n // Strip ID annotation from title\n cleanTitle = heading.title.replace(MARKDOC_ID_PATTERN, '').trim();\n } else {\n const htmlMatch = HTML_COMMENT_ID_PATTERN.exec(line);\n if (htmlMatch) {\n id = htmlMatch[1];\n // Strip ID annotation from title\n cleanTitle = heading.title.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n }\n\n return { ...heading, title: cleanTitle, id };\n });\n}\n\n/**\n * Inject IDs into headings in a markdown document.\n *\n * Uses a generator function to create unique IDs for each heading.\n * Throws if duplicate IDs are generated or if generated IDs conflict\n * with existing ones.\n */\nexport function injectHeaderIds(\n markdown: string,\n options: InjectHeaderIdsOptions,\n): InjectIdsResult {\n const { generator, onlyMissing = true, levels = [1, 2, 3, 4, 5, 6] } = options;\n const allHeadings = findAllHeadingsWithIds(markdown);\n\n // Filter by levels\n const levelSet = new Set(levels);\n const headings = allHeadings.filter((h) => levelSet.has(h.level));\n\n // Collect existing IDs (to check for conflicts)\n const existingIds = new Set<string>();\n for (const heading of headings) {\n if (heading.id && onlyMissing) {\n existingIds.add(heading.id);\n }\n }\n\n // Determine which headings need IDs\n const needsId = headings.filter((h) => (onlyMissing ? !h.id : true));\n\n // Generate IDs and check for duplicates/conflicts\n const generatedIds = new Map<string, string>(); // title -> id\n const allGeneratedIds = new Set<string>();\n\n for (let i = 0; i < needsId.length; i++) {\n const heading = needsId[i]!;\n const newId = generator(heading, i);\n\n // Check for duplicate generated IDs\n if (allGeneratedIds.has(newId)) {\n throw new MarkformParseError(\n `Duplicate generated ID '${newId}' for heading '${heading.title}'`,\n { line: heading.line },\n );\n }\n\n // Check for conflict with existing IDs (only when onlyMissing=true)\n if (onlyMissing && existingIds.has(newId)) {\n throw new MarkformParseError(`Generated ID '${newId}' conflicts with existing ID`, {\n line: heading.line,\n });\n }\n\n allGeneratedIds.add(newId);\n generatedIds.set(heading.title, newId);\n }\n\n // If no changes needed, return original markdown\n if (needsId.length === 0) {\n return {\n markdown,\n injectedCount: 0,\n injectedIds: new Map(),\n };\n }\n\n // Apply changes to markdown (process in reverse order to preserve line numbers)\n const lines = markdown.split('\\n');\n const sortedByLine = [...needsId].sort((a, b) => b.line - a.line);\n\n for (const heading of sortedByLine) {\n const lineIndex = heading.line - 1;\n const line = lines[lineIndex]!;\n const newId = generatedIds.get(heading.title)!;\n\n // Remove existing ID annotation if replacing\n let updatedLine = line;\n if (!onlyMissing || heading.id) {\n // Remove existing Markdoc ID\n updatedLine = updatedLine.replace(MARKDOC_ID_PATTERN, '').trim();\n // Remove existing HTML comment ID\n updatedLine = updatedLine.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n\n // Append new ID annotation\n lines[lineIndex] = `${updatedLine} {% #${newId} %}`;\n }\n\n return {\n markdown: lines.join('\\n'),\n injectedCount: needsId.length,\n injectedIds: generatedIds,\n };\n}\n","/**\n * Markdoc parser for .form.md files.\n *\n * Parses Markdoc documents and extracts form schema, values, and documentation blocks.\n */\n\nimport Markdoc from '@markdoc/markdoc';\nimport type { Node } from '@markdoc/markdoc';\nimport YAML from 'yaml';\n\nimport type {\n CheckboxesField,\n CheckboxesValue,\n DocumentationBlock,\n DocumentationTag,\n FieldGroup,\n FieldResponse,\n FormMetadata,\n FormSchema,\n Id,\n IdIndexEntry,\n Note,\n ParsedForm,\n SyntaxStyle,\n TagRegion,\n TagType,\n} from './coreTypes.js';\nimport { MarkformSectionInputSchema } from './coreTypes.js';\nimport type { ZodError } from 'zod';\nimport {\n AGENT_ROLE,\n DEFAULT_PRIORITY,\n DEFAULT_ROLES,\n DEFAULT_ROLE_INSTRUCTIONS,\n transformHarnessConfigToTs,\n} from '../settings.js';\nimport { parseField } from './parseFields.js';\nimport {\n getBooleanAttr,\n getNumberAttr,\n getStringAttr,\n getValidateAttr,\n isTagNode,\n} from './parseHelpers.js';\nimport { MarkformParseError } from '../errors.js';\nimport { detectSyntaxStyle, preprocessCommentSyntax } from './preprocess.js';\nimport { findAllCheckboxes } from './injectIds.js';\n\n// Re-export ParseError for backward compatibility\nexport { ParseError } from '../errors.js';\n\n/**\n * Valid tag names inside a form.\n * Any other tag will produce a ParseError.\n */\nconst VALID_FORM_TAGS = new Set([\n 'group',\n 'field',\n 'note',\n 'description',\n 'instructions',\n 'documentation',\n]);\n\n// =============================================================================\n// Frontmatter Parsing\n// =============================================================================\n\ninterface FrontmatterResult {\n frontmatter: Record<string, unknown>;\n metadata?: FormMetadata;\n /** Description from markform.description in frontmatter */\n description?: string;\n}\n\n/**\n * Format Zod validation errors for user-friendly display.\n */\nfunction formatZodError(error: ZodError): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.map(String).join('.');\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join('; ');\n}\n\n/**\n * Extract YAML frontmatter from Markdoc AST.\n * Uses Markdoc's native frontmatter extraction and parses the YAML.\n * Validates the markform section using Zod schema.\n */\nfunction extractFrontmatter(ast: Node): FrontmatterResult {\n const rawFrontmatter = ast.attributes.frontmatter as string | undefined;\n if (!rawFrontmatter) {\n return { frontmatter: {} };\n }\n\n try {\n const parsed = YAML.parse(rawFrontmatter) as Record<string, unknown> | null;\n const frontmatter = parsed ?? {};\n\n // Extract metadata from markform section\n const rawMarkformSection = frontmatter.markform;\n if (!rawMarkformSection) {\n return { frontmatter };\n }\n\n // Validate markform section with Zod schema\n const validationResult = MarkformSectionInputSchema.safeParse(rawMarkformSection);\n if (!validationResult.success) {\n throw new MarkformParseError(\n `Invalid markform frontmatter: ${formatZodError(validationResult.error)}`,\n );\n }\n const markformSection = validationResult.data;\n\n // Transform harness config from snake_case to camelCase\n const harnessConfig =\n markformSection.harness && Object.keys(markformSection.harness).length > 0\n ? transformHarnessConfigToTs(markformSection.harness)\n : undefined;\n\n // Build metadata\n // Note: roles and role_instructions can be either inside markform: or at top-level\n // Prefer markform section, fall back to top-level for backwards compatibility\n const metadata: FormMetadata = {\n markformVersion: markformSection.spec ?? 'MF/0.1',\n ...(markformSection.title && { title: markformSection.title }),\n ...(markformSection.description && { description: markformSection.description }),\n roles: markformSection.roles ??\n (frontmatter.roles as string[] | undefined) ?? [...DEFAULT_ROLES],\n roleInstructions:\n markformSection.role_instructions ??\n (frontmatter.role_instructions as Record<string, string> | undefined) ??\n DEFAULT_ROLE_INSTRUCTIONS,\n ...(harnessConfig && { harnessConfig }),\n ...(markformSection.run_mode && { runMode: markformSection.run_mode }),\n };\n\n return { frontmatter, metadata, description: markformSection.description };\n } catch (error) {\n // Re-throw ParseError as-is, wrap other errors\n if (error instanceof MarkformParseError) {\n throw error;\n }\n throw new MarkformParseError('Failed to parse frontmatter YAML');\n }\n}\n\n/**\n * Extract the raw source content minus frontmatter.\n * This is the content that will be used for splice-based serialization.\n */\nfunction extractRawSource(preprocessed: string): string {\n // YAML frontmatter is delimited by --- at start and end\n const frontmatterRegex = /^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/;\n const frontmatterMatch = frontmatterRegex.exec(preprocessed);\n if (frontmatterMatch) {\n return preprocessed.slice(frontmatterMatch[0].length);\n }\n return preprocessed;\n}\n\n/**\n * Build a line-to-offset mapping for converting Markdoc line numbers to byte offsets.\n * Returns an array where lineOffsets[lineNumber] = byte offset of line start.\n * Line numbers are 0-indexed (Markdoc uses 0-indexed lines).\n */\nfunction buildLineOffsets(source: string): number[] {\n const offsets: number[] = [0]; // Line 0 starts at offset 0\n for (let i = 0; i < source.length; i++) {\n if (source[i] === '\\n') {\n offsets.push(i + 1); // Next line starts after the newline\n }\n }\n return offsets;\n}\n\n/**\n * Extract tag region from a Markdoc AST node.\n * Uses the node's location property (line numbers) and converts to byte offsets.\n */\nfunction extractTagRegion(\n node: Node,\n tagType: TagType,\n tagId: Id,\n lineOffsets: number[],\n frontmatterLineCount: number,\n sourceLength: number,\n hasValue?: boolean,\n): TagRegion | null {\n // Markdoc nodes have location with start/end line numbers (0-indexed)\n const location = node.location;\n if (!location?.start || !location?.end) {\n return null;\n }\n\n // Adjust line numbers for frontmatter removal\n // rawSource starts after frontmatter, so we need to adjust the line numbers\n const startLine = location.start.line - frontmatterLineCount;\n const endLine = location.end.line - frontmatterLineCount;\n\n // Skip if the tag is in the frontmatter area (shouldn't happen, but be safe)\n if (startLine < 0 || endLine < 0) {\n return null;\n }\n\n // Convert line numbers to byte offsets\n // Markdoc's end line is the line containing the closing tag\n // We need to find the end of that line\n const startOffset = lineOffsets[startLine] ?? 0;\n let endOffset: number;\n\n // For end offset, we want the end of the end line (start of next line or end of source)\n if (endLine + 1 < lineOffsets.length) {\n endOffset = lineOffsets[endLine + 1] ?? sourceLength;\n } else {\n endOffset = sourceLength;\n }\n\n // Sanity check: make sure offsets are valid\n if (startOffset >= endOffset || startOffset < 0 || endOffset > sourceLength) {\n return null;\n }\n\n return {\n tagId,\n tagType,\n startOffset,\n endOffset,\n ...(hasValue !== undefined && { includesValue: hasValue }),\n };\n}\n\n/**\n * Collect all tag regions from the AST for content preservation.\n * Traverses the AST and extracts positions of all Markform tags.\n */\nfunction collectTagRegions(\n ast: Node,\n rawSource: string,\n frontmatterLineCount: number,\n responsesByFieldId: Record<Id, FieldResponse>,\n): TagRegion[] {\n const regions: TagRegion[] = [];\n const lineOffsets = buildLineOffsets(rawSource);\n const sourceLength = rawSource.length;\n\n function traverse(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n // Check for form tag\n if (isTagNode(node, 'form')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n const region = extractTagRegion(\n node,\n 'form',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for group tag\n if (isTagNode(node, 'group')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n const region = extractTagRegion(\n node,\n 'group',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for field tag\n if (isTagNode(node, 'field')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n // Check if field has a value by looking at responsesByFieldId\n const hasValue = responsesByFieldId[id]?.value !== undefined;\n const region = extractTagRegion(\n node,\n 'field',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n hasValue,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for note tag\n if (isTagNode(node, 'note')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n const region = extractTagRegion(\n node,\n 'note',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for documentation tags (instructions, description, etc.)\n const DOC_TAGS = ['instructions', 'description', 'documentation'];\n if (node.type === 'tag' && node.tag && DOC_TAGS.includes(node.tag)) {\n const ref = getStringAttr(node, 'ref');\n // Use ref as the ID for doc blocks, or generate one\n const docId = ref ?? `doc_${regions.length}`;\n const region = extractTagRegion(\n node,\n 'documentation',\n docId,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n\n // Recurse into children\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n traverse(child);\n }\n }\n }\n\n traverse(ast);\n\n // Sort by startOffset to ensure document order\n regions.sort((a, b) => a.startOffset - b.startOffset);\n\n return regions;\n}\n\n// =============================================================================\n// Group and Form Parsing\n// =============================================================================\n\n/**\n * Parse a group tag.\n */\nfunction parseFieldGroup(\n node: Node,\n responsesByFieldId: Record<Id, FieldResponse>,\n orderIndex: Id[],\n idIndex: Map<Id, IdIndexEntry>,\n parentId?: Id,\n): FieldGroup {\n const id = getStringAttr(node, 'id');\n const title = getStringAttr(node, 'title');\n\n if (!id) {\n throw new MarkformParseError(\"group missing required 'id' attribute\");\n }\n\n if (idIndex.has(id)) {\n throw new MarkformParseError(`Duplicate ID '${id}'`);\n }\n\n // Validate that state attribute is not on group\n const stateAttr = getStringAttr(node, 'state');\n if (stateAttr !== undefined) {\n throw new MarkformParseError(\n `Field-group '${id}' has state attribute. state attribute is not allowed on groups.`,\n );\n }\n\n idIndex.set(id, { nodeType: 'group', parentId });\n\n const children: FieldGroup['children'] = [];\n\n // Traverse children to find fields\n function processChildren(child: Node): void {\n if (!child || typeof child !== 'object') {\n return;\n }\n\n const result = parseField(child);\n if (result) {\n if (idIndex.has(result.field.id)) {\n throw new MarkformParseError(`Duplicate ID '${result.field.id}'`);\n }\n\n idIndex.set(result.field.id, { nodeType: 'field', parentId: id });\n children.push(result.field);\n responsesByFieldId[result.field.id] = result.response;\n orderIndex.push(result.field.id);\n\n // Add options to idIndex for select/checkbox fields\n if ('options' in result.field) {\n for (const opt of result.field.options) {\n const qualifiedRef = `${result.field.id}.${opt.id}`;\n if (idIndex.has(qualifiedRef)) {\n throw new MarkformParseError(`Duplicate option ref '${qualifiedRef}'`);\n }\n idIndex.set(qualifiedRef, {\n nodeType: 'option',\n parentId: id,\n fieldId: result.field.id,\n });\n }\n }\n }\n\n if (child.children && Array.isArray(child.children)) {\n for (const c of child.children) {\n processChildren(c);\n }\n }\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n processChildren(child);\n }\n }\n\n const parallel = getStringAttr(node, 'parallel');\n const order = getNumberAttr(node, 'order');\n\n // Validate: fields inside a group must not have `parallel`\n // Validate: fields inside a group must not explicitly specify a different `order`\n const groupEffectiveOrder = order ?? 0;\n for (const child of children) {\n if (child.parallel) {\n throw new MarkformParseError(\n `Field '${child.id}' has parallel='${child.parallel}' but is inside ` +\n `group '${id}'. The parallel attribute is only allowed on ` +\n `top-level fields and groups.`,\n );\n }\n // Only error if the child *explicitly* sets order to a different value.\n // Unset order on a child is fine — it inherits the group's order.\n if (child.order !== undefined) {\n const childEffectiveOrder = child.order;\n if (childEffectiveOrder !== groupEffectiveOrder) {\n throw new MarkformParseError(\n `Field '${child.id}' has order=${child.order} but is inside ` +\n `group '${id}' with order=${groupEffectiveOrder}. ` +\n `A field inside a group must not specify a different order.`,\n );\n }\n }\n }\n\n return {\n id,\n title,\n validate: getValidateAttr(node),\n children,\n report: getBooleanAttr(node, 'report'),\n parallel,\n order,\n };\n}\n\n/**\n * Parse a form tag.\n * Handles both explicit groups and fields placed directly under the form.\n * Also handles implicit checkboxes when form has no explicit fields.\n */\nfunction parseFormTag(\n node: Node,\n responsesByFieldId: Record<Id, FieldResponse>,\n orderIndex: Id[],\n idIndex: Map<Id, IdIndexEntry>,\n markdown: string,\n): FormSchema {\n const id = getStringAttr(node, 'id');\n const title = getStringAttr(node, 'title');\n\n if (!id) {\n throw new MarkformParseError(\"form missing required 'id' attribute\");\n }\n\n if (idIndex.has(id)) {\n throw new MarkformParseError(`Duplicate ID '${id}'`);\n }\n\n idIndex.set(id, { nodeType: 'form' });\n\n const groups: FieldGroup[] = [];\n const ungroupedFields: FieldGroup['children'] = [];\n\n // Process children to find groups and ungrouped fields\n function processContent(child: Node): void {\n if (!child || typeof child !== 'object') {\n return;\n }\n\n // Check for unknown tags inside form\n if (isTagNode(child) && !VALID_FORM_TAGS.has((child as { tag: string }).tag)) {\n throw new MarkformParseError(`Unknown tag '${(child as { tag: string }).tag}' inside form`);\n }\n\n if (isTagNode(child, 'group')) {\n const group = parseFieldGroup(child, responsesByFieldId, orderIndex, idIndex, id);\n groups.push(group);\n return; // parseFieldGroup already processed the children\n }\n\n // Check for field tags directly under the form (not in a group)\n const result = parseField(child);\n if (result) {\n if (idIndex.has(result.field.id)) {\n throw new MarkformParseError(`Duplicate ID '${result.field.id}'`);\n }\n\n idIndex.set(result.field.id, { nodeType: 'field', parentId: id });\n ungroupedFields.push(result.field);\n responsesByFieldId[result.field.id] = result.response;\n orderIndex.push(result.field.id);\n\n // Add options to idIndex for select/checkbox fields\n if ('options' in result.field) {\n for (const opt of result.field.options) {\n const qualifiedRef = `${result.field.id}.${opt.id}`;\n if (idIndex.has(qualifiedRef)) {\n throw new MarkformParseError(`Duplicate option ref '${qualifiedRef}'`);\n }\n idIndex.set(qualifiedRef, {\n nodeType: 'option',\n parentId: id,\n fieldId: result.field.id,\n });\n }\n }\n return; // Don't recurse into field children\n }\n\n // Recurse into children for non-group, non-field nodes\n if (child.children && Array.isArray(child.children)) {\n for (const c of child.children) {\n processContent(c);\n }\n }\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n processContent(child);\n }\n }\n\n // If there are ungrouped fields, create an implicit group to hold them\n // The 'default' ID is a special name for implicit groups, but can also be used explicitly\n if (ungroupedFields.length > 0) {\n const implicitGroupId = 'default';\n // Check if 'default' was already used explicitly - if so, merge fields into it\n const existingDefault = groups.find((g) => g.id === implicitGroupId);\n if (existingDefault) {\n // Merge ungrouped fields into the existing explicit 'default' group\n existingDefault.children = [...(existingDefault.children ?? []), ...ungroupedFields];\n } else {\n idIndex.set(implicitGroupId, { nodeType: 'group', parentId: id });\n groups.push({\n id: implicitGroupId,\n children: ungroupedFields,\n implicit: true,\n });\n }\n }\n\n // Count all explicit fields\n const hasExplicitFields =\n ungroupedFields.length > 0 || groups.some((g) => g.children && g.children.length > 0);\n\n // Check if there are explicit fields that use checkbox syntax\n // (checkboxes, single_select, multi_select all use checkbox-like list items)\n const hasExplicitCheckboxStyleFields = groups.some((g) =>\n g.children?.some(\n (f) => f.kind === 'checkboxes' || f.kind === 'single_select' || f.kind === 'multi_select',\n ),\n );\n\n // Find all checkboxes in the markdown\n const allCheckboxes = findAllCheckboxes(markdown);\n\n if (allCheckboxes.length > 0) {\n if (hasExplicitFields) {\n // If there are explicit fields that use checkbox syntax, checkboxes are inside them\n // But if there are only non-checkbox-style fields, the checkboxes are orphans\n if (!hasExplicitCheckboxStyleFields) {\n throw new MarkformParseError(\n 'Checkboxes found outside of field tags. Either wrap all checkboxes in ' +\n 'fields or remove all explicit fields for implicit checkboxes mode.',\n );\n }\n // If there are explicit checkboxes fields, the checkboxes are inside them (OK)\n } else {\n // No explicit fields - create implicit checkboxes field\n const seenIds = new Set<string>();\n const options: { id: string; label: string }[] = [];\n const values: CheckboxesValue['values'] = {};\n\n for (const checkbox of allCheckboxes) {\n if (!checkbox.id) {\n throw new MarkformParseError(\n `Option in implicit field 'checkboxes' missing ID annotation. Use {% #option_id %}`,\n { line: checkbox.line },\n );\n }\n\n if (seenIds.has(checkbox.id)) {\n throw new MarkformParseError(\n `Duplicate option ID '${checkbox.id}' in field 'checkboxes'`,\n { line: checkbox.line },\n );\n }\n\n seenIds.add(checkbox.id);\n options.push({\n id: checkbox.id,\n label: checkbox.label,\n });\n values[checkbox.id] = checkbox.state;\n }\n\n // Create implicit checkboxes field\n // The 'checkboxes' ID is a special name for implicit checkboxes, but can also be used explicitly\n const implicitField: CheckboxesField = {\n kind: 'checkboxes',\n id: 'checkboxes',\n label: 'Checkboxes',\n checkboxMode: 'multi',\n implicit: true,\n options,\n required: false,\n priority: DEFAULT_PRIORITY,\n role: AGENT_ROLE,\n approvalMode: 'none',\n };\n\n // Add to idIndex\n idIndex.set('checkboxes', { nodeType: 'field', parentId: id });\n orderIndex.push('checkboxes');\n\n // Add options to idIndex\n for (const opt of options) {\n const qualifiedRef = `checkboxes.${opt.id}`;\n idIndex.set(qualifiedRef, {\n nodeType: 'option',\n parentId: id,\n fieldId: 'checkboxes',\n });\n }\n\n // Create response for the implicit field\n const checkboxesValue: CheckboxesValue = {\n kind: 'checkboxes',\n values,\n };\n responsesByFieldId.checkboxes = {\n state: 'answered',\n value: checkboxesValue,\n };\n\n // Create or get default group for implicit field\n let defaultGroup = groups.find((g) => g.id === 'default');\n if (!defaultGroup) {\n defaultGroup = {\n id: 'default',\n children: [],\n implicit: true,\n };\n idIndex.set('default', { nodeType: 'group', parentId: id });\n groups.push(defaultGroup);\n }\n defaultGroup.children = defaultGroup.children || [];\n defaultGroup.children.push(implicitField);\n }\n }\n\n // Validate parallel batch consistency: same order and same role within each batch.\n // Collect all top-level items that have parallel set.\n // For explicit groups, the group itself is the item.\n // For implicit groups, each child field is a top-level item.\n validateParallelBatches(groups);\n\n return { id, title, groups };\n}\n\n/**\n * Validate that parallel batches have consistent order and role values.\n */\nfunction validateParallelBatches(groups: FieldGroup[]): void {\n // Collect batch membership: batchId → array of { order, role, itemId }\n const batches = new Map<string, { order: number; role: string; itemId: string }[]>();\n\n for (const group of groups) {\n if (group.implicit) {\n // Implicit group: each child field is a top-level item\n for (const field of group.children) {\n if (field.parallel) {\n const list = batches.get(field.parallel) ?? [];\n list.push({\n order: field.order ?? 0,\n role: field.role,\n itemId: field.id,\n });\n batches.set(field.parallel, list);\n }\n }\n } else {\n // Explicit group: the group is the item\n if (group.parallel) {\n // For a group's role, use the role of the first child (they should all match\n // since fields inside a group share the group's execution context).\n // If the group has no children, use AGENT_ROLE as default.\n const groupRole = group.children[0]?.role ?? AGENT_ROLE;\n const list = batches.get(group.parallel) ?? [];\n list.push({\n order: group.order ?? 0,\n role: groupRole,\n itemId: group.id,\n });\n batches.set(group.parallel, list);\n }\n }\n }\n\n // Validate each batch\n for (const [batchId, items] of batches) {\n if (items.length < 2) continue;\n\n const firstOrder = items[0]!.order;\n const firstRole = items[0]!.role;\n\n const differentOrders = items.filter((i) => i.order !== firstOrder);\n if (differentOrders.length > 0) {\n const orderValues = [...new Set(items.map((i) => i.order))].join(', ');\n throw new MarkformParseError(\n `Parallel batch '${batchId}' has items with different order values (${orderValues}). ` +\n `All items in a parallel batch must have the same order.`,\n );\n }\n\n const differentRoles = items.filter((i) => i.role !== firstRole);\n if (differentRoles.length > 0) {\n const roles = [...new Set(items.map((i) => i.role))].join(', ');\n throw new MarkformParseError(\n `Parallel batch '${batchId}' has items with different roles (${roles}). ` +\n `All items in a parallel batch must have the same role.`,\n );\n }\n }\n}\n\n// =============================================================================\n// Note Parsing\n// =============================================================================\n\n/**\n * Extract all notes from AST.\n * Looks for {% note %} tags with id, ref, role, and optional state.\n */\nfunction extractNotes(ast: Node, idIndex: Map<Id, IdIndexEntry>): Note[] {\n const notes: Note[] = [];\n const seenIds = new Set<string>();\n\n function traverse(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n // Check for note tags\n if (isTagNode(node, 'note')) {\n const id = getStringAttr(node, 'id');\n const ref = getStringAttr(node, 'ref');\n const role = getStringAttr(node, 'role');\n const stateAttr = getStringAttr(node, 'state');\n\n // Validate required attributes\n if (!id) {\n throw new MarkformParseError(\"note missing required 'id' attribute\");\n }\n if (!ref) {\n throw new MarkformParseError(`note '${id}' missing required 'ref' attribute`);\n }\n if (!role) {\n throw new MarkformParseError(`note '${id}' missing required 'role' attribute`);\n }\n\n // Reject state attribute on notes (markform-254: notes are general-purpose only)\n if (stateAttr !== undefined) {\n throw new MarkformParseError(\n `note '${id}' has 'state' attribute. Notes no longer support state linking; use FieldResponse.reason for skip/abort reasons.`,\n );\n }\n\n // Validate ref exists in idIndex\n if (!idIndex.has(ref)) {\n throw new MarkformParseError(`note '${id}' references unknown ID '${ref}'`);\n }\n\n // Validate duplicate note IDs\n if (seenIds.has(id)) {\n throw new MarkformParseError(`Duplicate note ID '${id}'`);\n }\n seenIds.add(id);\n\n // Extract text content\n let text = '';\n function extractText(n: Node): void {\n if (n.type === 'text' && typeof n.attributes?.content === 'string') {\n text += n.attributes.content;\n }\n if (n.children && Array.isArray(n.children)) {\n for (const c of n.children) {\n extractText(c);\n }\n }\n }\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n extractText(child);\n }\n }\n\n notes.push({\n id,\n ref,\n role,\n text: text.trim(),\n });\n }\n\n // Recurse into children\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n traverse(child);\n }\n }\n }\n\n traverse(ast);\n return notes;\n}\n\n// =============================================================================\n// Documentation Block Parsing\n// =============================================================================\n\n/** Valid documentation tag names */\nconst DOC_TAG_NAMES = ['description', 'instructions', 'documentation'] as const;\n\n/**\n * Extract all documentation blocks from AST.\n * Looks for {% description %}, {% instructions %}, and {% documentation %} tags.\n */\nfunction extractDocBlocks(ast: Node, idIndex: Map<Id, IdIndexEntry>): DocumentationBlock[] {\n const docs: DocumentationBlock[] = [];\n const seenRefs = new Set<string>();\n\n function traverse(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n // Check for description, instructions, or documentation tags\n const nodeTag = node.type === 'tag' && node.tag ? node.tag : null;\n if (nodeTag && (DOC_TAG_NAMES as readonly string[]).includes(nodeTag)) {\n const tag = nodeTag as DocumentationTag;\n const ref = getStringAttr(node, 'ref');\n\n if (!ref) {\n throw new MarkformParseError(`${tag} block missing required 'ref' attribute`);\n }\n\n // Validate ref exists\n if (!idIndex.has(ref)) {\n throw new MarkformParseError(`${tag} block references unknown ID '${ref}'`);\n }\n\n const uniqueKey = `${ref}:${tag}`;\n\n if (seenRefs.has(uniqueKey)) {\n throw new MarkformParseError(`Duplicate ${tag} block for ref='${ref}'`);\n }\n seenRefs.add(uniqueKey);\n\n // Extract body content - collect all text from children\n let bodyMarkdown = '';\n function extractText(n: Node): void {\n if (n.type === 'text' && typeof n.attributes?.content === 'string') {\n bodyMarkdown += n.attributes.content;\n } else if (n.type === 'softbreak' || n.type === 'hardbreak') {\n // Preserve line breaks from markdown - softbreak is a single newline,\n // hardbreak is an explicit break (e.g., two spaces at end of line)\n bodyMarkdown += '\\n';\n }\n if (n.children && Array.isArray(n.children)) {\n for (const c of n.children) {\n extractText(c);\n }\n }\n }\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n extractText(child);\n }\n }\n\n docs.push({\n tag,\n ref,\n bodyMarkdown: bodyMarkdown.trim(),\n report: getBooleanAttr(node, 'report'),\n });\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n traverse(child);\n }\n }\n }\n\n traverse(ast);\n return docs;\n}\n\n// =============================================================================\n// Main Parser\n// =============================================================================\n\n/**\n * Parse a Markform .form.md document.\n *\n * Supports both Markdoc syntax (`{% tag %}`) and HTML comment syntax (`<!-- f:tag -->`).\n * The original syntax style is detected and preserved for round-trip serialization.\n *\n * @param markdown - The full markdown content including frontmatter\n * @returns The parsed form representation\n * @throws ParseError if the document is invalid\n */\nexport function parseForm(markdown: string): ParsedForm {\n // Step 0: Detect syntax style and preprocess HTML comment syntax to Markdoc\n const syntaxStyle: SyntaxStyle = detectSyntaxStyle(markdown);\n const preprocessed = preprocessCommentSyntax(markdown);\n\n // Step 0.5: Extract raw source (content minus frontmatter) for content preservation\n const rawSource = extractRawSource(preprocessed);\n // Calculate the number of lines in frontmatter for line number adjustment\n const frontmatter = preprocessed.slice(0, preprocessed.length - rawSource.length);\n const frontmatterLineCount = (frontmatter.match(/\\n/g) ?? []).length;\n\n // Step 1: Parse Markdoc AST (raw AST, not transformed)\n // Markdoc natively handles frontmatter extraction and stores it in ast.attributes.frontmatter\n const ast = Markdoc.parse(preprocessed);\n\n // Step 2: Extract frontmatter and metadata from AST\n const { metadata, description } = extractFrontmatter(ast);\n\n // Step 3: Find the form tag in the raw AST\n let formSchema: FormSchema | null = null;\n const responsesByFieldId: Record<Id, FieldResponse> = {};\n const orderIndex: Id[] = [];\n const idIndex = new Map<Id, IdIndexEntry>();\n\n function findFormTag(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n if (isTagNode(node, 'form')) {\n if (formSchema) {\n throw new MarkformParseError('Multiple form tags found - only one allowed');\n }\n formSchema = parseFormTag(node, responsesByFieldId, orderIndex, idIndex, preprocessed);\n return;\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n findFormTag(child);\n }\n }\n }\n\n findFormTag(ast);\n\n if (!formSchema) {\n throw new MarkformParseError('No form tag found in document');\n }\n\n // Build final schema with description from frontmatter\n // Type assertion needed because TypeScript doesn't track closure assignments well\n const parsedSchema = formSchema as FormSchema;\n const schema: FormSchema = {\n ...parsedSchema,\n ...(description && { description }),\n };\n\n // Step 4: Extract notes (needs idIndex to validate refs)\n const notes = extractNotes(ast, idIndex);\n\n // Step 5: Extract doc blocks (needs idIndex to validate refs)\n const docs = extractDocBlocks(ast, idIndex);\n\n // Step 6: Collect tag regions for content preservation\n const tagRegions = collectTagRegions(ast, rawSource, frontmatterLineCount, responsesByFieldId);\n\n return {\n schema,\n responsesByFieldId,\n notes,\n docs,\n orderIndex,\n idIndex,\n ...(metadata && { metadata }),\n syntaxStyle,\n rawSource,\n tagRegions,\n };\n}\n","/**\n * JSON Schema export for Markform forms.\n *\n * Converts parsed forms to JSON Schema format (draft 2020-12).\n * Includes x-markform extension properties for Markform-specific metadata.\n */\n\nimport type {\n CheckboxesField,\n CheckboxMode,\n ApprovalMode,\n DateField,\n DocumentationBlock,\n Field,\n FieldPriorityLevel,\n MultiSelectField,\n NumberField,\n ParsedForm,\n SingleSelectField,\n StringField,\n StringListField,\n TableColumn,\n TableField,\n UrlField,\n UrlListField,\n YearField,\n} from './coreTypes.js';\n\n// =============================================================================\n// JSON Schema Types (subset we use)\n// =============================================================================\n\n/** JSON Schema type values */\ntype JsonSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';\n\n/** JSON Schema format values */\ntype JsonSchemaFormat = 'date' | 'uri' | 'email' | 'uri-reference';\n\n/** JSON Schema property definition */\ninterface JsonSchemaProperty {\n type?: JsonSchemaType | JsonSchemaType[];\n title?: string;\n description?: string;\n enum?: (string | number | boolean | null)[];\n const?: string | number | boolean | null;\n format?: JsonSchemaFormat;\n pattern?: string;\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n // JSON Schema 2019-09/2020-12 format validation keywords\n formatMinimum?: string;\n formatMaximum?: string;\n items?: JsonSchemaProperty;\n properties?: Record<string, JsonSchemaProperty>;\n required?: string[];\n minItems?: number;\n maxItems?: number;\n uniqueItems?: boolean;\n additionalProperties?: boolean | JsonSchemaProperty;\n // Composition keywords\n anyOf?: JsonSchemaProperty[];\n oneOf?: JsonSchemaProperty[];\n 'x-markform'?: MarkformFieldExtension;\n}\n\n/** Root JSON Schema object (does not extend JsonSchemaProperty to allow different x-markform type) */\ninterface JsonSchemaRoot {\n $schema: string;\n $id?: string;\n type: 'object';\n title?: string;\n description?: string;\n properties?: Record<string, JsonSchemaProperty>;\n required?: string[];\n 'x-markform'?: MarkformSchemaExtension;\n}\n\n// =============================================================================\n// Markform Extension Types\n// =============================================================================\n\n/** Form-level Markform extension data */\nexport interface MarkformSchemaExtension {\n spec: string;\n roles?: string[];\n roleInstructions?: Record<string, string>;\n groups?: { id: string; title?: string }[];\n}\n\n/** Field-level Markform extension data */\nexport interface MarkformFieldExtension {\n role?: string;\n priority?: FieldPriorityLevel;\n group?: string;\n checkboxMode?: CheckboxMode;\n approvalMode?: ApprovalMode;\n minDone?: number;\n placeholder?: string;\n examples?: string[];\n}\n\n// =============================================================================\n// Options and Result Types\n// =============================================================================\n\n/** JSON Schema draft version */\nexport type JsonSchemaDraft = '2020-12' | '2019-09' | 'draft-07';\n\n/** Options for JSON Schema generation */\nexport interface JsonSchemaOptions {\n /** Include x-markform extension properties (default: true) */\n includeExtensions?: boolean;\n /** JSON Schema draft version (default: '2020-12') */\n draft?: JsonSchemaDraft;\n}\n\n/** Result from JSON Schema generation */\nexport interface JsonSchemaResult {\n /** The generated JSON Schema */\n schema: JsonSchemaRoot;\n}\n\n// =============================================================================\n// Schema URL Map\n// =============================================================================\n\nconst SCHEMA_URLS: Record<JsonSchemaDraft, string> = {\n '2020-12': 'https://json-schema.org/draft/2020-12/schema',\n '2019-09': 'https://json-schema.org/draft/2019-09/schema',\n 'draft-07': 'http://json-schema.org/draft-07/schema#',\n};\n\n// =============================================================================\n// Documentation Helpers\n// =============================================================================\n\n/**\n * Find description for a field from doc blocks.\n */\nfunction findDescription(docs: DocumentationBlock[], fieldId: string): string | undefined {\n // Look for 'description' or 'documentation' tags that reference this field\n for (const doc of docs) {\n if (doc.ref === fieldId && (doc.tag === 'description' || doc.tag === 'documentation')) {\n return doc.bodyMarkdown.trim();\n }\n }\n return undefined;\n}\n\n// =============================================================================\n// Field Type Converters\n// =============================================================================\n\nfunction stringFieldToJsonSchema(\n field: StringField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minLength !== undefined) {\n schema.minLength = field.minLength;\n }\n if (field.maxLength !== undefined) {\n schema.maxLength = field.maxLength;\n }\n if (field.pattern !== undefined) {\n schema.pattern = field.pattern;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction numberFieldToJsonSchema(\n field: NumberField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: field.integer ? 'integer' : 'number',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.min !== undefined) {\n schema.minimum = field.min;\n }\n if (field.max !== undefined) {\n schema.maximum = field.max;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction dateFieldToJsonSchema(\n field: DateField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n format: 'date',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n // Use formatMinimum/formatMaximum for date constraints (JSON Schema 2019-09/2020-12 only)\n // These keywords don't exist in draft-07, so we skip them for that draft\n if (options.draft !== 'draft-07') {\n if (field.min) {\n schema.formatMinimum = field.min;\n }\n if (field.max) {\n schema.formatMaximum = field.max;\n }\n }\n\n // Also include in x-markform extension for backward compatibility\n if (options.includeExtensions) {\n const ext = buildFieldExtension(field, groupId);\n if (field.min) {\n (ext as MarkformFieldExtension & { minDate?: string }).minDate = field.min;\n }\n if (field.max) {\n (ext as MarkformFieldExtension & { maxDate?: string }).maxDate = field.max;\n }\n schema['x-markform'] = ext;\n }\n\n return schema;\n}\n\nfunction yearFieldToJsonSchema(\n field: YearField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'integer',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.min !== undefined) {\n schema.minimum = field.min;\n }\n if (field.max !== undefined) {\n schema.maximum = field.max;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction urlFieldToJsonSchema(\n field: UrlField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n format: 'uri',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction stringListFieldToJsonSchema(\n field: StringListField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const itemSchema: JsonSchemaProperty = { type: 'string' };\n if (field.itemMinLength !== undefined) {\n itemSchema.minLength = field.itemMinLength;\n }\n if (field.itemMaxLength !== undefined) {\n itemSchema.maxLength = field.itemMaxLength;\n }\n\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: itemSchema,\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minItems !== undefined) {\n schema.minItems = field.minItems;\n }\n if (field.maxItems !== undefined) {\n schema.maxItems = field.maxItems;\n }\n if (field.uniqueItems) {\n schema.uniqueItems = true;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction urlListFieldToJsonSchema(\n field: UrlListField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: { type: 'string', format: 'uri' },\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minItems !== undefined) {\n schema.minItems = field.minItems;\n }\n if (field.maxItems !== undefined) {\n schema.maxItems = field.maxItems;\n }\n if (field.uniqueItems) {\n schema.uniqueItems = true;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction singleSelectFieldToJsonSchema(\n field: SingleSelectField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n enum: field.options.map((opt) => opt.id),\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction multiSelectFieldToJsonSchema(\n field: MultiSelectField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: {\n type: 'string',\n enum: field.options.map((opt) => opt.id),\n },\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minSelections !== undefined) {\n schema.minItems = field.minSelections;\n }\n if (field.maxSelections !== undefined) {\n schema.maxItems = field.maxSelections;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction checkboxesFieldToJsonSchema(\n field: CheckboxesField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n // Checkboxes are represented as an object with each option as a property\n // The value for each property depends on the checkbox mode\n // Boolean values are also accepted and coerced: true→done/yes, false→todo/no\n const validStates = getValidCheckboxStates(field.checkboxMode);\n\n const properties: Record<string, JsonSchemaProperty> = {};\n for (const opt of field.options) {\n properties[opt.id] = {\n anyOf: [{ type: 'string', enum: validStates }, { type: 'boolean' }],\n title: opt.label,\n };\n }\n\n const schema: JsonSchemaProperty = {\n type: 'object',\n properties,\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (options.includeExtensions) {\n const ext = buildFieldExtension(field, groupId);\n ext.checkboxMode = field.checkboxMode;\n if (field.minDone !== undefined) {\n ext.minDone = field.minDone;\n }\n if (field.approvalMode !== 'none') {\n ext.approvalMode = field.approvalMode;\n }\n schema['x-markform'] = ext;\n }\n\n return schema;\n}\n\nfunction getValidCheckboxStates(mode: CheckboxMode): string[] {\n switch (mode) {\n case 'multi':\n return ['todo', 'done', 'incomplete', 'active', 'na'];\n case 'simple':\n return ['todo', 'done'];\n case 'explicit':\n return ['unfilled', 'yes', 'no'];\n }\n}\n\nfunction tableFieldToJsonSchema(\n field: TableField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const rowProperties: Record<string, JsonSchemaProperty> = {};\n const requiredColumns: string[] = [];\n\n for (const col of field.columns) {\n rowProperties[col.id] = columnToJsonSchema(col);\n if (col.required) {\n requiredColumns.push(col.id);\n }\n }\n\n const rowSchema: JsonSchemaProperty = {\n type: 'object',\n properties: rowProperties,\n };\n\n if (requiredColumns.length > 0) {\n rowSchema.required = requiredColumns;\n }\n\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: rowSchema,\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minRows !== undefined) {\n schema.minItems = field.minRows;\n }\n if (field.maxRows !== undefined) {\n schema.maxItems = field.maxRows;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction columnToJsonSchema(col: TableColumn): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n title: col.label,\n };\n\n switch (col.type) {\n case 'string':\n schema.type = 'string';\n break;\n case 'number':\n schema.type = 'number';\n break;\n case 'url':\n schema.type = 'string';\n schema.format = 'uri';\n break;\n case 'date':\n schema.type = 'string';\n schema.format = 'date';\n break;\n case 'year':\n schema.type = 'integer';\n break;\n }\n\n return schema;\n}\n\n// =============================================================================\n// Extension Builders\n// =============================================================================\n\nfunction buildFieldExtension(field: Field, groupId?: string): MarkformFieldExtension {\n const ext: MarkformFieldExtension = {};\n\n if (field.role) {\n ext.role = field.role;\n }\n\n if (field.priority && field.priority !== 'medium') {\n ext.priority = field.priority;\n }\n\n if (groupId) {\n ext.group = groupId;\n }\n\n if (field.placeholder) {\n ext.placeholder = field.placeholder;\n }\n\n if (field.examples && field.examples.length > 0) {\n ext.examples = field.examples;\n }\n\n return ext;\n}\n\nfunction buildSchemaExtension(form: ParsedForm): MarkformSchemaExtension {\n const ext: MarkformSchemaExtension = {\n spec: form.metadata?.markformVersion ?? 'MF/0.1',\n };\n\n if (form.metadata?.roles && form.metadata.roles.length > 0) {\n ext.roles = form.metadata.roles;\n }\n\n if (form.metadata?.roleInstructions && Object.keys(form.metadata.roleInstructions).length > 0) {\n ext.roleInstructions = form.metadata.roleInstructions;\n }\n\n // Build groups list (excluding implicit groups)\n const groups: { id: string; title?: string }[] = [];\n for (const group of form.schema.groups) {\n if (!group.implicit) {\n groups.push({\n id: group.id,\n ...(group.title ? { title: group.title } : {}),\n });\n }\n }\n if (groups.length > 0) {\n ext.groups = groups;\n }\n\n return ext;\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Convert a single field to its JSON Schema representation.\n */\nexport function fieldToJsonSchema(\n field: Field,\n docs: DocumentationBlock[],\n options?: JsonSchemaOptions,\n groupId?: string,\n): JsonSchemaProperty {\n const opts: Required<JsonSchemaOptions> = {\n includeExtensions: options?.includeExtensions ?? true,\n draft: options?.draft ?? '2020-12',\n };\n\n switch (field.kind) {\n case 'string':\n return stringFieldToJsonSchema(field, docs, opts, groupId);\n case 'number':\n return numberFieldToJsonSchema(field, docs, opts, groupId);\n case 'date':\n return dateFieldToJsonSchema(field, docs, opts, groupId);\n case 'year':\n return yearFieldToJsonSchema(field, docs, opts, groupId);\n case 'url':\n return urlFieldToJsonSchema(field, docs, opts, groupId);\n case 'string_list':\n return stringListFieldToJsonSchema(field, docs, opts, groupId);\n case 'url_list':\n return urlListFieldToJsonSchema(field, docs, opts, groupId);\n case 'single_select':\n return singleSelectFieldToJsonSchema(field, docs, opts, groupId);\n case 'multi_select':\n return multiSelectFieldToJsonSchema(field, docs, opts, groupId);\n case 'checkboxes':\n return checkboxesFieldToJsonSchema(field, docs, opts, groupId);\n case 'table':\n return tableFieldToJsonSchema(field, docs, opts, groupId);\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = field;\n throw new Error(`Unhandled field kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n}\n\n/**\n * Convert a parsed form to JSON Schema.\n *\n * Main API for JSON Schema generation. Use from libraries or CLI.\n */\nexport function formToJsonSchema(form: ParsedForm, options?: JsonSchemaOptions): JsonSchemaResult {\n const opts: Required<JsonSchemaOptions> = {\n includeExtensions: options?.includeExtensions ?? true,\n draft: options?.draft ?? '2020-12',\n };\n\n const properties: Record<string, JsonSchemaProperty> = {};\n const requiredFields: string[] = [];\n\n // Process all fields from all groups\n for (const group of form.schema.groups) {\n const groupId = group.implicit ? undefined : group.id;\n for (const field of group.children) {\n properties[field.id] = fieldToJsonSchema(field, form.docs, opts, groupId);\n if (field.required) {\n requiredFields.push(field.id);\n }\n }\n }\n\n // Build root schema\n const schema: JsonSchemaRoot = {\n $schema: SCHEMA_URLS[opts.draft],\n $id: form.schema.id,\n type: 'object',\n properties,\n };\n\n if (form.schema.title) {\n schema.title = form.schema.title;\n }\n\n // Find form-level description\n const formDescription = findDescription(form.docs, form.schema.id);\n if (formDescription) {\n schema.description = formDescription;\n }\n\n if (requiredFields.length > 0) {\n schema.required = requiredFields;\n }\n\n if (opts.includeExtensions) {\n schema['x-markform'] = buildSchemaExtension(form);\n }\n\n return { schema };\n}\n","/**\n * Scope Reference Parsing and Serialization.\n *\n * Handles parsing and serialization of scope reference strings used in issues and validation.\n *\n * Scope reference formats:\n * - `fieldId` - simple field reference\n * - `fieldId.optionId` - qualified option/column reference (context-dependent)\n * - `fieldId[row].columnId` - cell reference (tables only)\n *\n * The distinction between option and column references is made during resolution\n * with schema context (see scopeRefValidation.ts).\n */\n\nimport type { Id } from './coreTypes.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Simple field reference */\nexport interface FieldScopeRef {\n type: 'field';\n fieldId: Id;\n}\n\n/**\n * Qualified reference - could be option or column.\n * Disambiguation happens during resolution with schema context.\n */\nexport interface QualifiedScopeRef {\n type: 'qualified';\n fieldId: Id;\n qualifierId: Id; // optionId or columnId\n}\n\n/** Cell reference - table field specific */\nexport interface CellScopeRef {\n type: 'cell';\n fieldId: Id;\n row: number; // 0-indexed row number\n columnId: Id;\n}\n\n/** Union of all parsed scope reference types */\nexport type ParsedScopeRef = FieldScopeRef | QualifiedScopeRef | CellScopeRef;\n\n/** Result of parsing a scope reference */\nexport type ParseScopeRefResult = { ok: true; ref: ParsedScopeRef } | { ok: false; error: string };\n\n// =============================================================================\n// Regex Patterns\n// =============================================================================\n\n/**\n * Pattern for cell reference: fieldId[row].columnId\n * - fieldId: identifier (letters, digits, underscores, hyphens)\n * - row: non-negative integer\n * - columnId: identifier\n */\nconst CELL_REF_PATTERN = /^([a-zA-Z_][a-zA-Z0-9_-]*)\\[(\\d+)\\]\\.([a-zA-Z_][a-zA-Z0-9_-]*)$/;\n\n/**\n * Pattern for qualified reference: fieldId.qualifierId\n * - fieldId: identifier\n * - qualifierId: identifier (optionId or columnId)\n */\nconst QUALIFIED_REF_PATTERN = /^([a-zA-Z_][a-zA-Z0-9_-]*)\\.([a-zA-Z_][a-zA-Z0-9_-]*)$/;\n\n/**\n * Pattern for simple field reference: fieldId\n * - fieldId: identifier\n */\nconst FIELD_REF_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_-]*$/;\n\n// =============================================================================\n// Parsing\n// =============================================================================\n\n/**\n * Parse a scope reference string into a structured format.\n *\n * @param refStr - The scope reference string to parse\n * @returns Parsed scope reference or error\n *\n * @example\n * parseScopeRef('myField')\n * // => { ok: true, ref: { type: 'field', fieldId: 'myField' } }\n *\n * parseScopeRef('myField.optA')\n * // => { ok: true, ref: { type: 'qualified', fieldId: 'myField', qualifierId: 'optA' } }\n *\n * parseScopeRef('myTable[2].name')\n * // => { ok: true, ref: { type: 'cell', fieldId: 'myTable', row: 2, columnId: 'name' } }\n */\nexport function parseScopeRef(refStr: string): ParseScopeRefResult {\n // Trim whitespace\n const trimmed = refStr.trim();\n\n if (!trimmed) {\n return { ok: false, error: 'Empty scope reference' };\n }\n\n // Try cell reference first (most specific pattern)\n const cellMatch = CELL_REF_PATTERN.exec(trimmed);\n if (cellMatch) {\n const fieldId = cellMatch[1]!;\n const rowStr = cellMatch[2]!;\n const columnId = cellMatch[3]!;\n const row = parseInt(rowStr, 10);\n if (row < 0 || !Number.isInteger(row)) {\n return { ok: false, error: `Invalid row index: ${rowStr}` };\n }\n return {\n ok: true,\n ref: { type: 'cell', fieldId, row, columnId },\n };\n }\n\n // Try qualified reference\n const qualifiedMatch = QUALIFIED_REF_PATTERN.exec(trimmed);\n if (qualifiedMatch) {\n const fieldId = qualifiedMatch[1]!;\n const qualifierId = qualifiedMatch[2]!;\n return {\n ok: true,\n ref: { type: 'qualified', fieldId, qualifierId },\n };\n }\n\n // Try simple field reference\n if (FIELD_REF_PATTERN.test(trimmed)) {\n return {\n ok: true,\n ref: { type: 'field', fieldId: trimmed },\n };\n }\n\n return { ok: false, error: `Invalid scope reference format: ${refStr}` };\n}\n\n// =============================================================================\n// Serialization\n// =============================================================================\n\n/**\n * Serialize a parsed scope reference back to a string.\n *\n * @param ref - The parsed scope reference\n * @returns Serialized string\n *\n * @example\n * serializeScopeRef({ type: 'field', fieldId: 'myField' })\n * // => 'myField'\n *\n * serializeScopeRef({ type: 'qualified', fieldId: 'myField', qualifierId: 'optA' })\n * // => 'myField.optA'\n *\n * serializeScopeRef({ type: 'cell', fieldId: 'myTable', row: 2, columnId: 'name' })\n * // => 'myTable[2].name'\n */\nexport function serializeScopeRef(ref: ParsedScopeRef): string {\n switch (ref.type) {\n case 'field':\n return ref.fieldId;\n case 'qualified':\n return `${ref.fieldId}.${ref.qualifierId}`;\n case 'cell':\n return `${ref.fieldId}[${ref.row}].${ref.columnId}`;\n }\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Check if a scope reference is a cell reference.\n */\nexport function isCellRef(ref: ParsedScopeRef): ref is CellScopeRef {\n return ref.type === 'cell';\n}\n\n/**\n * Check if a scope reference is a qualified reference.\n */\nexport function isQualifiedRef(ref: ParsedScopeRef): ref is QualifiedScopeRef {\n return ref.type === 'qualified';\n}\n\n/**\n * Check if a scope reference is a simple field reference.\n */\nexport function isFieldRef(ref: ParsedScopeRef): ref is FieldScopeRef {\n return ref.type === 'field';\n}\n\n/**\n * Extract the field ID from any scope reference.\n */\nexport function getFieldId(ref: ParsedScopeRef): Id {\n return ref.fieldId;\n}\n","/**\n * Unified value coercion layer for converting raw input values to typed Patches.\n *\n * This module provides the single source of truth for:\n * - Field lookup by ID (using idIndex for O(1) lookups)\n * - Coercing raw values to typed Patches with validation\n * - Batch coercion of InputContext with warnings/errors\n */\n\nimport type {\n CheckboxValue,\n Field,\n OptionId,\n ParsedForm,\n Patch,\n TableRowPatch,\n} from './coreTypes.js';\n\n// =============================================================================\n// Raw Input Types\n// =============================================================================\n\n/** Raw value that can be coerced to a field value. */\nexport type RawFieldValue = string | number | boolean | string[] | Record<string, unknown> | null;\n\n/** Input context is a map of field IDs to raw values. */\nexport type InputContext = Record<string, RawFieldValue>;\n\n// =============================================================================\n// Coercion Results\n// =============================================================================\n\nexport type CoercionResult =\n | { ok: true; patch: Patch }\n | { ok: true; patch: Patch; warning: string }\n | { ok: false; error: string };\n\nexport interface CoerceInputContextResult {\n patches: Patch[];\n /** Non-fatal warnings (e.g., \"coerced '123' to number for field X\") */\n warnings: string[];\n /** Fatal errors (e.g., \"field 'foo' not found\") */\n errors: string[];\n}\n\n// =============================================================================\n// Field Lookup\n// =============================================================================\n\n/**\n * Find a field by ID.\n *\n * Uses idIndex for O(1) validation that the ID exists and is a field,\n * then retrieves the Field object from the schema.\n */\nexport function findFieldById(form: ParsedForm, fieldId: string): Field | undefined {\n // O(1) check: verify the ID exists and is a field\n const entry = form.idIndex.get(fieldId);\n if (entry?.nodeType !== 'field') {\n return undefined;\n }\n\n // Retrieve the Field object from the schema\n for (const group of form.schema.groups) {\n for (const field of group.children) {\n if (field.id === fieldId) {\n return field;\n }\n }\n }\n\n return undefined;\n}\n\n// =============================================================================\n// Coercion Helpers\n// =============================================================================\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\n// =============================================================================\n// Field-Specific Coercion\n// =============================================================================\n\nfunction coerceToString(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'number') {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: String(rawValue) },\n warning: `Coerced number ${rawValue} to string for field '${fieldId}'`,\n };\n }\n\n if (typeof rawValue === 'boolean') {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: String(rawValue) },\n warning: `Coerced boolean ${rawValue} to string for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to string for field '${fieldId}'`,\n };\n}\n\nfunction coerceToNumber(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_number', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'number') {\n return {\n ok: true,\n patch: { op: 'set_number', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n const parsed = Number(rawValue);\n if (!Number.isNaN(parsed)) {\n return {\n ok: true,\n patch: { op: 'set_number', fieldId, value: parsed },\n warning: `Coerced string '${rawValue}' to number for field '${fieldId}'`,\n };\n }\n return {\n ok: false,\n error: `Cannot coerce non-numeric string '${rawValue}' to number for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to number for field '${fieldId}'`,\n };\n}\n\nfunction coerceToStringList(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: [] },\n };\n }\n\n if (isStringArray(rawValue)) {\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: [rawValue] },\n warning: `Coerced single string to array for field '${fieldId}'`,\n };\n }\n\n if (Array.isArray(rawValue)) {\n // Try to coerce non-string items\n const items: string[] = [];\n for (const item of rawValue) {\n if (typeof item === 'string') {\n items.push(item);\n } else if (typeof item === 'number' || typeof item === 'boolean') {\n items.push(String(item));\n } else {\n return {\n ok: false,\n error: `Cannot coerce array with non-string items to string_list for field '${fieldId}'`,\n };\n }\n }\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: items },\n warning: `Coerced array items to strings for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to string_list for field '${fieldId}'`,\n };\n}\n\nfunction coerceToSingleSelect(field: Field, rawValue: RawFieldValue): CoercionResult {\n if (field.kind !== 'single_select') {\n return { ok: false, error: `Field '${field.id}' is not a single_select field` };\n }\n\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_single_select', fieldId: field.id, value: null },\n };\n }\n\n if (typeof rawValue !== 'string') {\n return {\n ok: false,\n error: `single_select field '${field.id}' requires a string option ID, got ${typeof rawValue}`,\n };\n }\n\n const validOptions = new Set(field.options.map((o) => o.id));\n if (!validOptions.has(rawValue)) {\n return {\n ok: false,\n error: `Invalid option '${rawValue}' for single_select field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n\n return {\n ok: true,\n patch: { op: 'set_single_select', fieldId: field.id, value: rawValue },\n };\n}\n\nfunction coerceToMultiSelect(field: Field, rawValue: RawFieldValue): CoercionResult {\n if (field.kind !== 'multi_select') {\n return { ok: false, error: `Field '${field.id}' is not a multi_select field` };\n }\n\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_multi_select', fieldId: field.id, value: [] },\n };\n }\n\n const validOptions = new Set(field.options.map((o) => o.id));\n let selected: string[];\n let warning: string | undefined;\n\n if (typeof rawValue === 'string') {\n selected = [rawValue];\n warning = `Coerced single string to array for multi_select field '${field.id}'`;\n } else if (isStringArray(rawValue)) {\n selected = rawValue;\n } else {\n return {\n ok: false,\n error: `multi_select field '${field.id}' requires a string or string array, got ${typeof rawValue}`,\n };\n }\n\n // Validate all options\n for (const optId of selected) {\n if (!validOptions.has(optId)) {\n return {\n ok: false,\n error: `Invalid option '${optId}' for multi_select field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n }\n\n const patch: Patch = { op: 'set_multi_select', fieldId: field.id, value: selected };\n return warning ? { ok: true, patch, warning } : { ok: true, patch };\n}\n\nfunction coerceToCheckboxes(field: Field, rawValue: RawFieldValue): CoercionResult {\n if (field.kind !== 'checkboxes') {\n return { ok: false, error: `Field '${field.id}' is not a checkboxes field` };\n }\n\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_checkboxes', fieldId: field.id, value: {} },\n };\n }\n\n const validOptions = new Set(field.options.map((o) => o.id));\n const checkboxMode = field.checkboxMode;\n\n // Coerce array of option IDs to checkbox object with default state\n if (Array.isArray(rawValue)) {\n const defaultState = checkboxMode === 'explicit' ? 'yes' : 'done';\n const values: Record<string, CheckboxValue> = {};\n\n for (const item of rawValue) {\n if (typeof item !== 'string') {\n return {\n ok: false,\n error: `Array items for checkboxes field '${field.id}' must be strings (option IDs), got ${typeof item}`,\n };\n }\n if (!validOptions.has(item)) {\n return {\n ok: false,\n error: `Invalid option '${item}' for checkboxes field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n values[item] = defaultState;\n }\n\n const patch: Patch = { op: 'set_checkboxes', fieldId: field.id, value: values };\n\n // Empty array: no warning needed\n if (rawValue.length === 0) {\n return { ok: true, patch };\n }\n\n return {\n ok: true,\n patch,\n warning: `Coerced array to checkboxes object with '${defaultState}' state for field '${field.id}'`,\n };\n }\n\n if (!isPlainObject(rawValue)) {\n return {\n ok: false,\n error: `checkboxes field '${field.id}' requires a Record<string, CheckboxValue> or array of option IDs, got ${typeof rawValue}`,\n };\n }\n\n const values: Record<OptionId, CheckboxValue> = {};\n let hadBooleanCoercion = false;\n\n // Valid checkbox values based on mode\n const validValues = new Set<string>(\n checkboxMode === 'explicit'\n ? ['unfilled', 'yes', 'no']\n : checkboxMode === 'simple'\n ? ['todo', 'done']\n : ['todo', 'done', 'incomplete', 'active', 'na'],\n );\n\n for (const [optId, value] of Object.entries(rawValue)) {\n if (!validOptions.has(optId)) {\n return {\n ok: false,\n error: `Invalid option '${optId}' for checkboxes field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n\n // Coerce boolean values to appropriate checkbox strings\n if (typeof value === 'boolean') {\n hadBooleanCoercion = true;\n if (checkboxMode === 'explicit') {\n values[optId] = value ? 'yes' : 'no';\n } else {\n values[optId] = value ? 'done' : 'todo';\n }\n continue;\n }\n\n if (typeof value !== 'string' || !validValues.has(value)) {\n return {\n ok: false,\n error: `Invalid checkbox value '${String(value)}' for option '${optId}' in field '${field.id}'. Valid values for ${checkboxMode} mode: ${Array.from(validValues).join(', ')} (or use true/false)`,\n };\n }\n\n values[optId] = value as CheckboxValue;\n }\n\n const patch: Patch = { op: 'set_checkboxes', fieldId: field.id, value: values };\n if (hadBooleanCoercion) {\n return {\n ok: true,\n patch,\n warning: `Coerced boolean values to checkbox strings for field '${field.id}'`,\n };\n }\n return { ok: true, patch };\n}\n\nfunction coerceToUrl(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_url', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_url', fieldId, value: rawValue },\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to url for field '${fieldId}'`,\n };\n}\n\nfunction coerceToUrlList(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: [] },\n };\n }\n\n if (isStringArray(rawValue)) {\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: [rawValue] },\n warning: `Coerced single string to array for field '${fieldId}'`,\n };\n }\n\n if (Array.isArray(rawValue)) {\n // Try to coerce non-string items\n const items: string[] = [];\n for (const item of rawValue) {\n if (typeof item === 'string') {\n items.push(item);\n } else {\n return {\n ok: false,\n error: `Cannot coerce array with non-string items to url_list for field '${fieldId}'`,\n };\n }\n }\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: items },\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to url_list for field '${fieldId}'`,\n };\n}\n\nfunction coerceToDate(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_date', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_date', fieldId, value: rawValue },\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to date for field '${fieldId}'`,\n };\n}\n\nfunction coerceToYear(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_year', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'number') {\n if (!Number.isInteger(rawValue)) {\n return {\n ok: false,\n error: `Year must be an integer for field '${fieldId}', got ${rawValue}`,\n };\n }\n return {\n ok: true,\n patch: { op: 'set_year', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n const parsed = Number.parseInt(rawValue, 10);\n if (Number.isNaN(parsed)) {\n return {\n ok: false,\n error: `Cannot coerce non-numeric string '${rawValue}' to year for field '${fieldId}'`,\n };\n }\n return {\n ok: true,\n patch: { op: 'set_year', fieldId, value: parsed },\n warning: `Coerced string '${rawValue}' to year for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to year for field '${fieldId}'`,\n };\n}\n\n/**\n * Coerce raw value to SetTablePatch.\n * Accepts:\n * - Array of row objects: [{ col1: value1, col2: value2 }, ...]\n * - Empty array: [] (valid for optional tables or minRows=0)\n */\nfunction coerceToTable(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n // Handle null as clear\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_table', fieldId, value: [] },\n };\n }\n\n // Must be an array\n if (!Array.isArray(rawValue)) {\n return {\n ok: false,\n error: `Table value for field '${fieldId}' must be an array of rows, got ${typeof rawValue}`,\n };\n }\n\n // Empty array is valid\n if (rawValue.length === 0) {\n return {\n ok: true,\n patch: { op: 'set_table', fieldId, value: [] },\n };\n }\n\n // Process each row\n const rows: TableRowPatch[] = [];\n for (let i = 0; i < rawValue.length; i++) {\n const row = rawValue[i];\n if (typeof row !== 'object' || row === null || Array.isArray(row)) {\n return {\n ok: false,\n error: `Row ${i} for table field '${fieldId}' must be an object, got ${Array.isArray(row) ? 'array' : typeof row}`,\n };\n }\n rows.push(row as TableRowPatch);\n }\n\n return {\n ok: true,\n patch: { op: 'set_table', fieldId, value: rows },\n };\n}\n\n// =============================================================================\n// Main Coercion Functions\n// =============================================================================\n\n/**\n * Coerce a raw value to a Patch for a specific field.\n */\nexport function coerceToFieldPatch(\n form: ParsedForm,\n fieldId: string,\n rawValue: RawFieldValue,\n): CoercionResult {\n const field = findFieldById(form, fieldId);\n if (!field) {\n return { ok: false, error: `Field '${fieldId}' not found` };\n }\n\n switch (field.kind) {\n case 'string':\n return coerceToString(fieldId, rawValue);\n case 'number':\n return coerceToNumber(fieldId, rawValue);\n case 'string_list':\n return coerceToStringList(fieldId, rawValue);\n case 'single_select':\n return coerceToSingleSelect(field, rawValue);\n case 'multi_select':\n return coerceToMultiSelect(field, rawValue);\n case 'checkboxes':\n return coerceToCheckboxes(field, rawValue);\n case 'url':\n return coerceToUrl(fieldId, rawValue);\n case 'url_list':\n return coerceToUrlList(fieldId, rawValue);\n case 'date':\n return coerceToDate(fieldId, rawValue);\n case 'year':\n return coerceToYear(fieldId, rawValue);\n case 'table':\n return coerceToTable(fieldId, rawValue);\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = field;\n throw new Error(`Unhandled field kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n}\n\n/**\n * Coerce an entire InputContext to patches.\n *\n * Returns patches for valid entries, collects warnings for coercions,\n * and errors for invalid entries.\n */\nexport function coerceInputContext(\n form: ParsedForm,\n inputContext: InputContext,\n): CoerceInputContextResult {\n const patches: Patch[] = [];\n const warnings: string[] = [];\n const errors: string[] = [];\n\n for (const [fieldId, rawValue] of Object.entries(inputContext)) {\n // Skip null values (no-op, field unchanged)\n if (rawValue === null) {\n continue;\n }\n\n const result = coerceToFieldPatch(form, fieldId, rawValue);\n\n if (result.ok) {\n patches.push(result.patch);\n if ('warning' in result && result.warning) {\n warnings.push(result.warning);\n }\n } else {\n errors.push(result.error);\n }\n }\n\n return { patches, warnings, errors };\n}\n","/**\n * Form Harness - Execution harness for form filling.\n *\n * Manages the step protocol for agent-driven form completion:\n * INIT -> STEP -> WAIT -> APPLY -> (repeat) -> COMPLETE\n */\n\n// Use pure JS sha256 to avoid node:crypto dependency, enabling use in\n// browsers, edge runtimes (Cloudflare Workers, Convex), and other non-Node environments.\nimport { sha256 } from 'js-sha256';\n\nimport { applyPatches } from '../engine/apply.js';\nimport { inspect, getFieldsForRoles } from '../engine/inspect.js';\nimport { serializeForm } from '../engine/serialize.js';\nimport type {\n ClearFieldPatch,\n HarnessConfig,\n InspectIssue,\n ParsedForm,\n Patch,\n PatchRejection,\n PatchWarning,\n SessionTurn,\n SessionTurnContext,\n SessionTurnStats,\n StepResult,\n WireFormat,\n} from '../engine/coreTypes.js';\nimport {\n DEFAULT_MAX_ISSUES_PER_TURN,\n DEFAULT_MAX_PATCHES_PER_TURN,\n DEFAULT_MAX_TURNS,\n AGENT_ROLE,\n} from '../settings.js';\n\n// =============================================================================\n// Default Configuration\n// =============================================================================\n\nconst DEFAULT_CONFIG: HarnessConfig = {\n maxIssuesPerTurn: DEFAULT_MAX_ISSUES_PER_TURN,\n maxPatchesPerTurn: DEFAULT_MAX_PATCHES_PER_TURN,\n maxTurns: DEFAULT_MAX_TURNS,\n};\n\n// =============================================================================\n// Harness State\n// =============================================================================\n\ntype HarnessState = 'init' | 'step' | 'wait' | 'complete';\n\n// =============================================================================\n// Form Harness Class\n// =============================================================================\n\n/**\n * Form harness for managing agent-driven form filling.\n */\nexport class FormHarness {\n private form: ParsedForm;\n private config: HarnessConfig;\n private state: HarnessState = 'init';\n private turnNumber = 0;\n private turns: SessionTurn[] = [];\n\n constructor(form: ParsedForm, config: Partial<HarnessConfig> = {}) {\n this.form = form;\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Get the current harness state.\n */\n getState(): HarnessState {\n return this.state;\n }\n\n /**\n * Get the current turn number.\n */\n getTurnNumber(): number {\n return this.turnNumber;\n }\n\n /**\n * Get the recorded session turns.\n */\n getTurns(): SessionTurn[] {\n return [...this.turns];\n }\n\n /**\n * Get the current form.\n */\n getForm(): ParsedForm {\n return this.form;\n }\n\n /**\n * Check if the harness has reached max turns.\n *\n * Returns true when we've completed all allowed turns. This happens when:\n * - turnNumber >= maxTurns AND we've already applied (state is \"complete\")\n * - OR turnNumber > maxTurns (we've exceeded the limit)\n *\n * This allows the harness loop to run N times when maxTurns=N by returning\n * false when we're at turn N but haven't applied yet (state is \"wait\").\n */\n hasReachedMaxTurns(): boolean {\n // If we've exceeded the limit, always return true\n if (this.turnNumber > this.config.maxTurns) {\n return true;\n }\n // At the last turn, check if we've completed it (state transitioned to \"complete\")\n if (this.turnNumber === this.config.maxTurns && this.state === 'complete') {\n return true;\n }\n return false;\n }\n\n /**\n * Perform a step - inspect the form and return current state.\n *\n * This transitions from INIT/WAIT -> STEP state.\n * Returns the current form state with prioritized issues.\n *\n * On first step with fillMode='overwrite', clears all target role fields\n * so they will be reported as needing to be filled.\n */\n step(): StepResult {\n if (this.state === 'complete') {\n throw new Error('Harness is complete - cannot step');\n }\n\n // On first step with fillMode='overwrite', clear all target role fields\n if (this.state === 'init' && this.config.fillMode === 'overwrite') {\n this.clearTargetRoleFields();\n }\n\n // Increment turn number\n this.turnNumber++;\n\n // Check max turns\n if (this.turnNumber > this.config.maxTurns) {\n this.state = 'complete';\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n return {\n structureSummary: result.structureSummary,\n progressSummary: result.progressSummary,\n issues: [],\n stepBudget: 0,\n isComplete: result.isComplete,\n turnNumber: this.turnNumber,\n };\n }\n\n this.state = 'step';\n\n // Inspect form and compute step result\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n const stepResult = this.computeStepResult(result);\n\n // Transition state based on whether there's more work\n this.state = stepResult.issues.length === 0 ? 'complete' : 'wait';\n\n return stepResult;\n }\n\n /**\n * Apply patches to the form.\n *\n * This transitions from WAIT -> STEP/COMPLETE state.\n * Records the turn in the session transcript.\n *\n * @param patches - Patches to apply\n * @param issues - Issues that were shown to the agent (for recording)\n * @param llmStats - Optional LLM stats for session logging\n * @param context - Optional context prompts sent to LLM (for session logging)\n * @param wire - Optional wire format for comprehensive session logging\n * @returns StepResult after applying patches\n */\n apply(\n patches: Patch[],\n issues: InspectIssue[],\n llmStats?: SessionTurnStats,\n context?: SessionTurnContext,\n wire?: WireFormat,\n ): StepResult {\n if (this.state !== 'wait') {\n throw new Error(`Cannot apply in state: ${this.state}`);\n }\n\n if (patches.length > this.config.maxPatchesPerTurn) {\n throw new Error(`Too many patches: ${patches.length} > ${this.config.maxPatchesPerTurn}`);\n }\n\n // Apply patches with best-effort semantics - valid patches are applied even when some fail\n const applyResult = applyPatches(this.form, patches);\n const patchesActuallyApplied = applyResult.appliedPatches.length;\n\n // Re-inspect after applying patches to get full issue list including optional_unanswered\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n const stepResult = this.computeStepResult(result);\n\n // Add actual patch count and rejection details to step result\n stepResult.patchesApplied = patchesActuallyApplied;\n stepResult.rejectedPatches = applyResult.rejectedPatches;\n\n // Record turn in session transcript (include rejections, warnings, and wire format)\n this.recordTurn(\n issues,\n patches,\n result,\n llmStats,\n context,\n applyResult.rejectedPatches,\n applyResult.warnings,\n wire,\n );\n\n // Transition state: complete if no more work OR max turns reached\n const noMoreWork = stepResult.issues.length === 0;\n if (noMoreWork || this.turnNumber >= this.config.maxTurns) {\n this.state = 'complete';\n } else {\n this.state = 'wait';\n }\n\n return stepResult;\n }\n\n /**\n * Compute step result from inspect result.\n * Applies issue filtering and computes step budget.\n */\n private computeStepResult(result: ReturnType<typeof inspect>): StepResult {\n // Issue filtering pipeline (order matters):\n // 0. Filter by order level - only surface issues for the current (lowest incomplete) order\n // 1. Filter by maxGroupsPerTurn/maxFieldsPerTurn - limits scope diversity\n // 2. Cap by maxIssuesPerTurn - limits total count shown to agent\n const orderFiltered = this.filterIssuesByOrder(result.issues);\n const filteredIssues = this.filterIssuesByScope(orderFiltered);\n const limitedIssues = filteredIssues.slice(0, this.config.maxIssuesPerTurn);\n\n // Step budget = min of max patches per turn and issues to address\n const stepBudget = Math.min(this.config.maxPatchesPerTurn, limitedIssues.length);\n\n return {\n structureSummary: result.structureSummary,\n progressSummary: result.progressSummary,\n issues: limitedIssues,\n stepBudget,\n isComplete: result.isComplete,\n turnNumber: this.turnNumber,\n };\n }\n\n /**\n * Record a turn in the session transcript.\n */\n private recordTurn(\n issues: InspectIssue[],\n patches: Patch[],\n result: ReturnType<typeof inspect>,\n llmStats?: SessionTurnStats,\n context?: SessionTurnContext,\n rejectedPatches?: PatchRejection[],\n warnings?: PatchWarning[],\n wire?: WireFormat,\n ): void {\n const markdown = serializeForm(this.form);\n const hash = sha256(markdown);\n\n const requiredIssueCount = result.issues.filter((i) => i.severity === 'required').length;\n\n const turn: SessionTurn = {\n turn: this.turnNumber,\n inspect: { issues },\n apply: {\n patches,\n ...(rejectedPatches && rejectedPatches.length > 0 && { rejectedPatches }),\n ...(warnings && warnings.length > 0 && { warnings }),\n },\n after: {\n requiredIssueCount,\n markdownSha256: hash,\n answeredFieldCount: result.progressSummary.counts.answeredFields,\n skippedFieldCount: result.progressSummary.counts.skippedFields,\n },\n };\n\n if (context) {\n turn.context = context;\n }\n\n if (llmStats) {\n turn.llm = llmStats;\n }\n\n if (wire) {\n turn.wire = wire;\n }\n\n this.turns.push(turn);\n }\n\n /**\n * Check if the form is complete.\n */\n isComplete(): boolean {\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n return result.isComplete;\n }\n\n /**\n * Get the current markdown content of the form.\n */\n getMarkdown(): string {\n return serializeForm(this.form);\n }\n\n /**\n * Get the SHA256 hash of the current form markdown.\n */\n getMarkdownHash(): string {\n const markdown = serializeForm(this.form);\n return sha256(markdown);\n }\n\n /**\n * Filter issues based on maxFieldsPerTurn and maxGroupsPerTurn limits.\n *\n * Issues are processed in priority order. An issue is included if:\n * - Adding it doesn't exceed the field limit (for field/option scoped issues)\n * - Adding it doesn't exceed the group limit\n *\n * Form-level issues are always included.\n */\n private filterIssuesByScope(issues: InspectIssue[]): InspectIssue[] {\n const maxFields = this.config.maxFieldsPerTurn;\n const maxGroups = this.config.maxGroupsPerTurn;\n\n // If no limits configured, return all issues\n if (maxFields === undefined && maxGroups === undefined) {\n return issues;\n }\n\n const result: InspectIssue[] = [];\n const seenFields = new Set<string>();\n const seenGroups = new Set<string>();\n\n for (const issue of issues) {\n // Form-level issues always pass\n if (issue.scope === 'form') {\n result.push(issue);\n continue;\n }\n\n // Extract field ID from ref (for options, it's \"fieldId.optionId\")\n const fieldId = this.getFieldIdFromRef(issue.ref, issue.scope);\n\n // Get the parent group for the field (if any)\n const groupId = fieldId ? this.getGroupForField(fieldId) : undefined;\n\n // Check field limit\n if (maxFields !== undefined && fieldId) {\n if (!seenFields.has(fieldId) && seenFields.size >= maxFields) {\n continue; // Would exceed field limit\n }\n }\n\n // Check group limit\n if (maxGroups !== undefined && groupId) {\n if (!seenGroups.has(groupId) && seenGroups.size >= maxGroups) {\n continue; // Would exceed group limit\n }\n }\n\n // Include the issue and track the field/group\n result.push(issue);\n if (fieldId) {\n seenFields.add(fieldId);\n }\n if (groupId) {\n seenGroups.add(groupId);\n }\n }\n\n return result;\n }\n\n /**\n * Filter issues by order level.\n *\n * Only includes issues for fields at the current (lowest incomplete) order level.\n * Fields at higher order levels are deferred until all lower-order fields are complete.\n * If no order attributes are used, all issues pass through (all at order 0).\n */\n private filterIssuesByOrder(issues: InspectIssue[]): InspectIssue[] {\n // Build a map: fieldId → effective order\n const fieldOrderMap = new Map<string, number>();\n for (const group of this.form.schema.groups) {\n const groupOrder = group.order ?? 0;\n for (const field of group.children) {\n // If field has explicit order, use it; otherwise inherit group's order\n fieldOrderMap.set(field.id, field.order ?? groupOrder);\n }\n }\n\n // Find all distinct order levels that still have open issues\n const openOrderLevels = new Set<number>();\n for (const issue of issues) {\n const fieldId = this.getFieldIdFromRef(issue.ref, issue.scope);\n if (fieldId) {\n const order = fieldOrderMap.get(fieldId) ?? 0;\n openOrderLevels.add(order);\n } else if (issue.scope === 'form') {\n // Form-level issues are always at order 0\n openOrderLevels.add(0);\n }\n }\n\n if (openOrderLevels.size <= 1) {\n // All issues are at the same order level (or no issues) — no filtering needed\n return issues;\n }\n\n // Find the lowest order level with open issues\n const currentOrder = Math.min(...openOrderLevels);\n\n // Only include issues at the current order level\n return issues.filter((issue) => {\n if (issue.scope === 'form') {\n return true; // Form-level issues always pass\n }\n const fieldId = this.getFieldIdFromRef(issue.ref, issue.scope);\n if (!fieldId) {\n return true; // Can't determine order — include\n }\n const order = fieldOrderMap.get(fieldId) ?? 0;\n return order === currentOrder;\n });\n }\n\n /**\n * Extract field ID from an issue ref.\n */\n private getFieldIdFromRef(ref: string, scope: InspectIssue['scope']): string | undefined {\n if (scope === 'field') {\n return ref;\n }\n if (scope === 'option') {\n // Option refs are \"fieldId.optionId\"\n const dotIndex = ref.indexOf('.');\n return dotIndex > 0 ? ref.slice(0, dotIndex) : undefined;\n }\n // Group-level issues don't have a field\n return undefined;\n }\n\n /**\n * Get the parent group ID for a field.\n */\n private getGroupForField(fieldId: string): string | undefined {\n const entry = this.form.idIndex.get(fieldId);\n if (!entry) {\n return undefined;\n }\n\n // If the field has a parent and that parent is a group, return it\n if (entry.parentId) {\n const parentEntry = this.form.idIndex.get(entry.parentId);\n if (parentEntry?.nodeType === 'group') {\n return entry.parentId;\n }\n }\n\n return undefined;\n }\n\n /**\n * Clear all fields that match the target roles.\n * Used when fillMode='overwrite' to re-fill already-filled fields.\n */\n private clearTargetRoleFields(): void {\n const targetRoles = this.config.targetRoles ?? [AGENT_ROLE];\n const targetFields = getFieldsForRoles(this.form, targetRoles);\n\n // Create clear patches for all target role fields\n const clearPatches: ClearFieldPatch[] = targetFields.map((field) => ({\n op: 'clear_field' as const,\n fieldId: field.id,\n }));\n\n // Apply clear patches (this modifies the form in place)\n if (clearPatches.length > 0) {\n applyPatches(this.form, clearPatches);\n }\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a new form harness.\n *\n * @param form - The parsed form to fill\n * @param config - Optional harness configuration\n * @returns A new FormHarness instance\n */\nexport function createHarness(form: ParsedForm, config?: Partial<HarnessConfig>): FormHarness {\n return new FormHarness(form, config);\n}\n","/**\n * Mock Agent - Deterministic agent for testing harness execution.\n *\n * Uses a pre-filled \"completed mock\" form to generate patches\n * that fill the form deterministically.\n */\n\nimport type {\n CheckboxesValue,\n DateValue,\n Field,\n FieldValue,\n Id,\n InspectIssue,\n MultiSelectValue,\n NumberValue,\n Patch,\n ParsedForm,\n SingleSelectValue,\n StringListValue,\n StringValue,\n TableRowPatch,\n TableValue,\n UrlListValue,\n UrlValue,\n YearValue,\n} from '../engine/coreTypes.js';\nimport type { Agent, AgentResponse } from './harnessTypes.js';\n\n// Re-export Agent type for backwards compatibility\nexport type { Agent, AgentResponse } from './harnessTypes.js';\n\n// =============================================================================\n// Mock Agent Implementation\n// =============================================================================\n\n/**\n * Mock agent that generates patches from a pre-filled form.\n */\nexport class MockAgent implements Agent {\n private completedValues: Record<Id, FieldValue>;\n private fieldMap: Map<Id, Field>;\n\n /**\n * Create a mock agent from a completed form.\n *\n * @param completedForm - A fully-filled form to use as source of values\n */\n constructor(completedForm: ParsedForm) {\n // Extract values from responses\n this.completedValues = {};\n for (const [fieldId, response] of Object.entries(completedForm.responsesByFieldId)) {\n if (response.state === 'answered' && response.value) {\n this.completedValues[fieldId] = response.value;\n }\n }\n\n // Build field map for quick lookup\n this.fieldMap = new Map();\n for (const group of completedForm.schema.groups) {\n for (const field of group.children) {\n this.fieldMap.set(field.id, field);\n }\n }\n }\n\n /**\n * Invoke the fill_form tool using the completed mock to address issues.\n *\n * Processes issues in priority order, generating patches for\n * fields that have values in the completed mock. For fields with no\n * value (empty optional fields), generates skip_field patches.\n * Returns AgentResponse with patches but no stats (mock doesn't track LLM usage).\n */\n async fillFormTool(\n issues: InspectIssue[],\n _form: ParsedForm,\n maxPatches: number,\n ): Promise<AgentResponse> {\n const patches: Patch[] = [];\n const addressedFields = new Set<Id>();\n\n // Process issues in priority order\n for (const issue of issues) {\n if (patches.length >= maxPatches) {\n break;\n }\n\n // Skip non-field issues\n if (issue.scope !== 'field') {\n continue;\n }\n\n const fieldId = issue.ref;\n\n // Skip if we've already addressed this field\n if (addressedFields.has(fieldId)) {\n continue;\n }\n\n // Get field schema\n const field = this.fieldMap.get(fieldId);\n if (!field) {\n continue;\n }\n\n // Get the completed value for this field\n const completedValue = this.completedValues[fieldId];\n\n // If no value exists, generate skip_field patch for optional fields\n if (!completedValue || !this.hasValue(completedValue)) {\n if (!field.required) {\n patches.push({\n op: 'skip_field',\n fieldId,\n role: 'agent',\n reason: 'No value in mock form',\n });\n addressedFields.add(fieldId);\n }\n continue;\n }\n\n // Generate patch based on field kind\n const patch = this.createPatch(fieldId, field, completedValue);\n if (patch) {\n patches.push(patch);\n addressedFields.add(fieldId);\n }\n }\n\n // Return AgentResponse (no stats for mock agent)\n return Promise.resolve({ patches });\n }\n\n /**\n * Check if a field value actually has content (not null/empty).\n */\n private hasValue(value: FieldValue): boolean {\n switch (value.kind) {\n case 'string':\n return value.value !== null && value.value !== '';\n case 'number':\n return value.value !== null;\n case 'string_list':\n return value.items.length > 0;\n case 'single_select':\n return value.selected !== null;\n case 'multi_select':\n return value.selected.length > 0;\n case 'checkboxes':\n return true; // Checkboxes always have some state\n case 'url':\n return value.value !== null && value.value !== '';\n case 'url_list':\n return value.items.length > 0;\n case 'date':\n return value.value !== null;\n case 'year':\n return value.value !== null;\n case 'table':\n return (value.rows?.length ?? 0) > 0;\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = value;\n throw new Error(`Unhandled field value kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n }\n\n /**\n * Create a patch for a field based on its kind and completed value.\n */\n private createPatch(fieldId: Id, field: Field, value: FieldValue): Patch | null {\n switch (field.kind) {\n case 'string': {\n const v = value as StringValue;\n return {\n op: 'set_string',\n fieldId,\n value: v.value,\n };\n }\n\n case 'number': {\n const v = value as NumberValue;\n return {\n op: 'set_number',\n fieldId,\n value: v.value,\n };\n }\n\n case 'string_list': {\n const v = value as StringListValue;\n return {\n op: 'set_string_list',\n fieldId,\n value: v.items,\n };\n }\n\n case 'single_select': {\n const v = value as SingleSelectValue;\n return {\n op: 'set_single_select',\n fieldId,\n value: v.selected,\n };\n }\n\n case 'multi_select': {\n const v = value as MultiSelectValue;\n return {\n op: 'set_multi_select',\n fieldId,\n value: v.selected,\n };\n }\n\n case 'checkboxes': {\n const v = value as CheckboxesValue;\n return {\n op: 'set_checkboxes',\n fieldId,\n value: v.values,\n };\n }\n\n case 'url': {\n const v = value as UrlValue;\n return {\n op: 'set_url',\n fieldId,\n value: v.value,\n };\n }\n\n case 'url_list': {\n const v = value as UrlListValue;\n return {\n op: 'set_url_list',\n fieldId,\n value: v.items,\n };\n }\n\n case 'date': {\n const v = value as DateValue;\n return {\n op: 'set_date',\n fieldId,\n value: v.value,\n };\n }\n\n case 'year': {\n const v = value as YearValue;\n return {\n op: 'set_year',\n fieldId,\n value: v.value,\n };\n }\n\n case 'table': {\n const v = value as TableValue;\n // Convert TableRowResponse[] to TableRowPatch[]\n // TableRowResponse has CellResponse {state, value}, but patch needs just the value\n const patchRows: TableRowPatch[] = v.rows.map((row) => {\n const patchRow: TableRowPatch = {};\n for (const [colId, cellResponse] of Object.entries(row)) {\n // Use null for undefined values (skipped/empty cells)\n patchRow[colId] = cellResponse.value ?? null;\n }\n return patchRow;\n });\n return {\n op: 'set_table',\n fieldId,\n value: patchRows,\n };\n }\n\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = field;\n throw new Error(`Unhandled field kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a mock agent from a completed form.\n *\n * @param completedForm - A fully-filled form to use as source of values\n * @returns A new MockAgent instance\n */\nexport function createMockAgent(completedForm: ParsedForm): MockAgent {\n return new MockAgent(completedForm);\n}\n","/**\n * Execution plan computation for parallel form filling.\n *\n * Partitions a form's top-level items into a loose-serial pool and\n * zero or more parallel batches, grouped by order level.\n */\n\nimport type { ExecutionPlan, ExecutionPlanItem, ParallelBatch, ParsedForm } from './coreTypes.js';\n\n/**\n * Compute an execution plan from a parsed form.\n *\n * Walks top-level items (groups, or individual fields in implicit groups)\n * in document order and partitions them by their `parallel` attribute:\n * - Items without `parallel` go to the loose-serial pool.\n * - Items with the same `parallel` value form a parallel batch.\n *\n * Also computes distinct order levels across all items.\n */\nexport function computeExecutionPlan(form: ParsedForm): ExecutionPlan {\n const looseSerial: ExecutionPlanItem[] = [];\n const batchMap = new Map<string, ExecutionPlanItem[]>();\n const orderSet = new Set<number>();\n\n for (const group of form.schema.groups) {\n if (group.implicit) {\n // Implicit group: each child field is a top-level item\n for (const field of group.children) {\n const order = field.order ?? 0;\n orderSet.add(order);\n const item: ExecutionPlanItem = {\n itemId: field.id,\n itemType: 'field',\n order,\n };\n if (field.parallel) {\n const list = batchMap.get(field.parallel) ?? [];\n list.push(item);\n batchMap.set(field.parallel, list);\n } else {\n looseSerial.push(item);\n }\n }\n } else {\n // Explicit group: the group is the item\n const order = group.order ?? 0;\n orderSet.add(order);\n const item: ExecutionPlanItem = {\n itemId: group.id,\n itemType: 'group',\n order,\n };\n if (group.parallel) {\n const list = batchMap.get(group.parallel) ?? [];\n list.push(item);\n batchMap.set(group.parallel, list);\n } else {\n looseSerial.push(item);\n }\n }\n }\n\n const parallelBatches: ParallelBatch[] = [];\n for (const [batchId, items] of batchMap) {\n parallelBatches.push({ batchId, items });\n }\n\n const orderLevels = [...orderSet].sort((a, b) => a - b);\n\n return { looseSerial, parallelBatches, orderLevels };\n}\n","/**\n * Time utilities - Shared helpers for time and ID generation.\n *\n * Centralizes time-related operations for:\n * - Consistent behavior across the codebase\n * - Easy mocking in tests\n * - Clear audit of time-dependent code\n */\n\nimport { ulid } from 'ulid';\n\n/**\n * Get the current time as an ISO 8601 string.\n *\n * All code that needs \"now\" should call this function instead of\n * `new Date()` directly. This allows:\n * - Consistent timestamp format (ISO 8601)\n * - Clear visibility into time-dependent code\n * - Future support for clock mocking in tests\n *\n * @returns ISO 8601 timestamp string\n *\n * @example\n * ```typescript\n * const startedAt = currentTime();\n * // ... do work ...\n * const completedAt = currentTime();\n * ```\n */\nexport function currentTime(): string {\n return new Date().toISOString();\n}\n\n/**\n * Get the current time in milliseconds since Unix epoch.\n *\n * Use this when you need numeric timestamps for duration calculations.\n *\n * @returns Milliseconds since Unix epoch\n */\nexport function currentTimeMs(): number {\n return Date.now();\n}\n\n/**\n * Generate a unique session ID using ULID with a \"sess-\" prefix.\n *\n * ULIDs are:\n * - Lexicographically sortable by time\n * - 128-bit compatible with UUID\n * - URL-safe (no special characters)\n * - Monotonically increasing within the same millisecond\n *\n * The \"sess-\" prefix makes IDs self-identifying, following the policy\n * that all IDs should indicate their type at a glance. The ULID is\n * lowercased for consistency and readability.\n *\n * @returns Prefixed lowercase ULID string (31 characters: \"sess-\" + 26-char ULID)\n *\n * @example\n * ```typescript\n * const sessionId = generateSessionId();\n * // => \"sess-01arz3ndektsv4rrffq69g5fav\"\n * ```\n */\nexport function generateSessionId(): string {\n return `sess-${ulid().toLowerCase()}`;\n}\n","/**\n * FillRecordCollector - Append-only collector for fill records.\n *\n * Implements FillCallbacks to capture all events during a form fill operation\n * and assembles them into a FillRecord at the end.\n *\n * Concurrency model: Uses an append-only event log pattern that safely handles\n * interleaved async operations. JavaScript's single-threaded event loop ensures\n * that synchronous array pushes are atomic, so concurrent async callbacks can\n * safely append events without data races.\n *\n * @see docs/project/specs/active/plan-2026-01-29-fill-record.md\n */\n\nimport type { ProgressCounts, StructureSummary } from '../engine/coreTypes.js';\nimport type { FillCallbacks, TurnProgress } from './harnessTypes.js';\nimport type {\n FillRecord,\n FillRecordStatus,\n TimelineEntry,\n ToolCallRecord,\n ToolStats,\n ToolSummary,\n TimingBreakdown,\n TimingBreakdownItem,\n ExecutionMetadata,\n} from './fillRecord.js';\nimport { currentTime, generateSessionId } from './timeUtils.js';\n\n// =============================================================================\n// Internal Event Types\n// =============================================================================\n\ninterface TurnStartEvent {\n type: 'turn_start';\n timestamp: string;\n turnNumber: number;\n issuesCount: number;\n order: number;\n executionId: string;\n}\n\ninterface TurnCompleteEvent {\n type: 'turn_complete';\n timestamp: string;\n turnNumber: number;\n patchesApplied: number;\n patchesRejected: number;\n issuesAddressed: number;\n executionId?: string;\n}\n\ninterface LlmCallStartEvent {\n type: 'llm_call_start';\n timestamp: string;\n model: string;\n executionId: string;\n}\n\ninterface LlmCallEndEvent {\n type: 'llm_call_end';\n timestamp: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n executionId: string;\n}\n\ninterface ToolStartEvent {\n type: 'tool_start';\n timestamp: string;\n name: string;\n input: unknown;\n executionId: string;\n}\n\ninterface ToolEndEvent {\n type: 'tool_end';\n timestamp: string;\n name: string;\n output: unknown;\n durationMs: number;\n error?: string;\n executionId: string;\n}\n\ninterface WebSearchEvent {\n type: 'web_search';\n timestamp: string;\n query: string;\n resultCount: number;\n provider: string;\n executionId: string;\n}\n\ntype CollectorEvent =\n | TurnStartEvent\n | TurnCompleteEvent\n | LlmCallStartEvent\n | LlmCallEndEvent\n | ToolStartEvent\n | ToolEndEvent\n | WebSearchEvent;\n\n// =============================================================================\n// Options Interface\n// =============================================================================\n\nexport interface FillRecordCollectorOptions {\n /** Form metadata */\n form: {\n id: string;\n title?: string;\n description?: string;\n structure: StructureSummary;\n };\n /** LLM provider name */\n provider: string;\n /** Model identifier */\n model: string;\n /** Whether parallel execution is enabled */\n parallelEnabled?: boolean;\n /** Maximum parallel agents */\n maxParallelAgents?: number;\n /** Custom data to include in record */\n customData?: Record<string, unknown>;\n}\n\n// =============================================================================\n// FillRecordCollector Implementation\n// =============================================================================\n\n/**\n * Collector for FillRecord data from async form fill operations.\n *\n * Uses an append-only event log pattern that safely handles interleaved\n * async callbacks from parallel execution. Events are aggregated when\n * getRecord() is called.\n */\nexport class FillRecordCollector implements FillCallbacks {\n private readonly startedAt: string;\n private readonly sessionId: string;\n private readonly form: FillRecordCollectorOptions['form'];\n private readonly provider: string;\n private readonly model: string;\n private readonly parallelEnabled: boolean;\n private readonly maxParallelAgents?: number;\n private customData: Record<string, unknown>;\n\n // Append-only event log - safe for interleaved async operations\n private events: CollectorEvent[] = [];\n\n // Explicit status override\n private explicitStatus?: FillRecordStatus;\n private explicitStatusDetail?: string;\n\n // Track pending tool calls by name (for matching start/end)\n private pendingToolCalls = new Map<string, ToolStartEvent>();\n\n // Track pending LLM calls by executionId\n private pendingLlmCalls = new Map<string, LlmCallStartEvent>();\n\n constructor(options: FillRecordCollectorOptions) {\n this.startedAt = currentTime();\n this.sessionId = generateSessionId();\n this.form = options.form;\n this.provider = options.provider;\n this.model = options.model;\n this.parallelEnabled = options.parallelEnabled ?? false;\n this.maxParallelAgents = options.maxParallelAgents;\n this.customData = options.customData ?? {};\n }\n\n // ===========================================================================\n // FillCallbacks Implementation\n // ===========================================================================\n\n onTurnStart(turn: {\n turnNumber: number;\n issuesCount: number;\n order: number;\n executionId: string;\n }): void {\n this.events.push({\n type: 'turn_start',\n timestamp: currentTime(),\n turnNumber: turn.turnNumber,\n issuesCount: turn.issuesCount,\n order: turn.order,\n executionId: turn.executionId,\n });\n }\n\n onTurnComplete(progress: TurnProgress): void {\n this.events.push({\n type: 'turn_complete',\n timestamp: currentTime(),\n turnNumber: progress.turnNumber,\n patchesApplied: progress.patchesApplied,\n patchesRejected: progress.rejectedPatches?.length ?? 0,\n issuesAddressed: progress.issuesShown,\n executionId: progress.executionId,\n });\n }\n\n onLlmCallStart(call: { model: string; executionId: string }): void {\n const event: LlmCallStartEvent = {\n type: 'llm_call_start',\n timestamp: currentTime(),\n model: call.model,\n executionId: call.executionId,\n };\n this.events.push(event);\n this.pendingLlmCalls.set(call.executionId, event);\n }\n\n onLlmCallEnd(call: {\n model: string;\n inputTokens: number;\n outputTokens: number;\n executionId: string;\n }): void {\n this.events.push({\n type: 'llm_call_end',\n timestamp: currentTime(),\n model: call.model,\n inputTokens: call.inputTokens,\n outputTokens: call.outputTokens,\n executionId: call.executionId,\n });\n this.pendingLlmCalls.delete(call.executionId);\n }\n\n onToolStart(call: { name: string; input: unknown; executionId: string }): void {\n const event: ToolStartEvent = {\n type: 'tool_start',\n timestamp: currentTime(),\n name: call.name,\n input: call.input,\n executionId: call.executionId,\n };\n this.events.push(event);\n // Use composite key for parallel tool calls\n const key = `${call.executionId}:${call.name}`;\n this.pendingToolCalls.set(key, event);\n }\n\n onToolEnd(call: {\n name: string;\n output: unknown;\n durationMs: number;\n error?: string;\n executionId: string;\n }): void {\n this.events.push({\n type: 'tool_end',\n timestamp: currentTime(),\n name: call.name,\n output: call.output,\n durationMs: call.durationMs,\n error: call.error,\n executionId: call.executionId,\n });\n const key = `${call.executionId}:${call.name}`;\n this.pendingToolCalls.delete(key);\n }\n\n onWebSearch(info: {\n query: string;\n resultCount: number;\n provider: string;\n executionId: string;\n }): void {\n this.events.push({\n type: 'web_search',\n timestamp: currentTime(),\n query: info.query,\n resultCount: info.resultCount,\n provider: info.provider,\n executionId: info.executionId,\n });\n }\n\n // ===========================================================================\n // Public Methods\n // ===========================================================================\n\n /**\n * Add custom data during execution.\n */\n addCustomData(key: string, value: unknown): void {\n this.customData[key] = value;\n }\n\n /**\n * Set explicit status (overrides auto-detection from progress).\n */\n setStatus(status: FillRecordStatus, detail?: string): void {\n this.explicitStatus = status;\n this.explicitStatusDetail = detail;\n }\n\n /**\n * Assemble the complete FillRecord from collected events.\n */\n getRecord(formProgress: ProgressCounts): FillRecord {\n const completedAt = currentTime();\n const durationMs = new Date(completedAt).getTime() - new Date(this.startedAt).getTime();\n\n // Build timeline from events\n const timeline = this.buildTimeline();\n\n // Calculate LLM totals\n const llmTotals = this.calculateLlmTotals();\n\n // Calculate tool summary\n const toolSummary = this.calculateToolSummary();\n\n // Calculate timing breakdown\n const timingBreakdown = this.calculateTimingBreakdown(\n durationMs,\n llmTotals.llmTimeMs,\n toolSummary.totalDurationMs,\n );\n\n // Build execution metadata\n const execution = this.buildExecutionMetadata(timeline);\n\n // Determine status\n const status = this.determineStatus(formProgress);\n\n return {\n sessionId: this.sessionId,\n startedAt: this.startedAt,\n completedAt,\n durationMs,\n form: this.form,\n status,\n statusDetail: this.explicitStatusDetail,\n formProgress,\n llm: {\n provider: this.provider,\n model: this.model,\n totalCalls: llmTotals.totalCalls,\n inputTokens: llmTotals.inputTokens,\n outputTokens: llmTotals.outputTokens,\n },\n toolSummary,\n timingBreakdown,\n timeline,\n execution,\n customData: Object.keys(this.customData).length > 0 ? this.customData : undefined,\n };\n }\n\n // ===========================================================================\n // Private Aggregation Methods\n // ===========================================================================\n\n private buildTimeline(): TimelineEntry[] {\n // Use composite key (executionId:turnNumber) to properly track parallel turns\n const turnKey = (execId: string, turnNum: number) => `${execId}:${turnNum}`;\n\n // Fill start time for calculating relative offsets\n const fillStartMs = new Date(this.startedAt).getTime();\n\n const turns = new Map<string, TimelineEntry>();\n const turnStartEvents = new Map<string, TurnStartEvent>();\n const turnToolCalls = new Map<string, ToolCallRecord[]>();\n const turnTokens = new Map<string, { input: number; output: number }>();\n\n // First pass: collect turn start events and tool calls\n for (const event of this.events) {\n if (event.type === 'turn_start') {\n const key = turnKey(event.executionId, event.turnNumber);\n turnStartEvents.set(key, event);\n turnToolCalls.set(key, []);\n turnTokens.set(key, { input: 0, output: 0 });\n }\n }\n\n // Track active tool calls per turn (keyed by composite key)\n const activeToolsByTurn = new Map<\n string,\n Map<string, { start: ToolStartEvent; turnKey: string }>\n >();\n // Track current turn key for each executionId (for proper sequential turn tracking)\n const currentTurnKeyByExecutionId = new Map<string, string>();\n\n // Second pass: match tool start/end events and LLM tokens\n for (const event of this.events) {\n if (event.type === 'turn_start') {\n const key = turnKey(event.executionId, event.turnNumber);\n currentTurnKeyByExecutionId.set(event.executionId, key);\n activeToolsByTurn.set(key, new Map());\n } else if (event.type === 'tool_start') {\n // Use the current turn for this executionId (not the most recent globally)\n const activeTurnKey = currentTurnKeyByExecutionId.get(event.executionId);\n if (activeTurnKey) {\n const activeTools = activeToolsByTurn.get(activeTurnKey);\n if (activeTools) {\n const toolKey = `${event.executionId}:${event.name}`;\n activeTools.set(toolKey, { start: event, turnKey: activeTurnKey });\n }\n }\n } else if (event.type === 'tool_end') {\n const toolKey = `${event.executionId}:${event.name}`;\n // Find which turn this tool call belongs to\n let foundTurnKey: string | undefined;\n for (const [tk, activeTools] of activeToolsByTurn) {\n if (activeTools.has(toolKey)) {\n foundTurnKey = tk;\n break;\n }\n }\n\n if (foundTurnKey !== undefined) {\n const activeTools = activeToolsByTurn.get(foundTurnKey)!;\n const startInfo = activeTools.get(toolKey);\n if (startInfo) {\n const toolCall: ToolCallRecord = {\n tool: event.name,\n startedAt: startInfo.start.timestamp,\n completedAt: event.timestamp,\n startMs: new Date(startInfo.start.timestamp).getTime() - fillStartMs,\n durationMs: event.durationMs,\n success: !event.error,\n input: this.normalizeInput(startInfo.start.input),\n result: event.error ? { error: event.error } : this.extractResultCount(event.output),\n };\n turnToolCalls.get(foundTurnKey)?.push(toolCall);\n activeTools.delete(toolKey);\n }\n }\n } else if (event.type === 'llm_call_end') {\n // Use the current turn for this executionId\n const tk = currentTurnKeyByExecutionId.get(event.executionId);\n if (tk) {\n const tokens = turnTokens.get(tk);\n if (tokens) {\n tokens.input += event.inputTokens;\n tokens.output += event.outputTokens;\n }\n }\n }\n }\n\n // Third pass: build timeline entries from turn complete events\n // Match turn_complete events to their start events by executionId + turnNumber\n const turnCompleteByKey = new Map<string, TurnCompleteEvent>();\n for (const event of this.events) {\n if (event.type === 'turn_complete') {\n // Use executionId if available (parallel execution), otherwise fall back to matching by turnNumber\n if (event.executionId) {\n const key = turnKey(event.executionId, event.turnNumber);\n turnCompleteByKey.set(key, event);\n } else {\n // Legacy fallback: find first unmatched start event with same turnNumber\n for (const [key, startEvent] of turnStartEvents) {\n if (startEvent.turnNumber === event.turnNumber && !turnCompleteByKey.has(key)) {\n turnCompleteByKey.set(key, event);\n break;\n }\n }\n }\n }\n }\n\n for (const [key, startEvent] of turnStartEvents) {\n const completeEvent = turnCompleteByKey.get(key);\n if (completeEvent) {\n const tokens = turnTokens.get(key) ?? { input: 0, output: 0 };\n const toolCalls = turnToolCalls.get(key) ?? [];\n\n const turnStartMs = new Date(startEvent.timestamp).getTime();\n const entry: TimelineEntry = {\n turnNumber: startEvent.turnNumber,\n order: startEvent.order,\n executionId: startEvent.executionId,\n startedAt: startEvent.timestamp,\n completedAt: completeEvent.timestamp,\n startMs: turnStartMs - fillStartMs,\n durationMs: new Date(completeEvent.timestamp).getTime() - turnStartMs,\n issuesAddressed: completeEvent.issuesAddressed,\n patchesApplied: completeEvent.patchesApplied,\n patchesRejected: completeEvent.patchesRejected,\n tokens,\n toolCalls,\n };\n turns.set(key, entry);\n }\n }\n\n // Sort by startedAt timestamp (proper chronological order for parallel execution)\n return Array.from(turns.values()).sort(\n (a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime(),\n );\n }\n\n private findTurnKeyForExecutionId(\n executionId: string,\n turnStartEvents: Map<string, TurnStartEvent>,\n ): string | undefined {\n // Find the most recent turn for this executionId\n let latestKey: string | undefined;\n let latestTime = '';\n for (const [key, event] of turnStartEvents) {\n if (event.executionId === executionId && event.timestamp > latestTime) {\n latestKey = key;\n latestTime = event.timestamp;\n }\n }\n return latestKey;\n }\n\n private normalizeInput(input: unknown): Record<string, unknown> {\n if (input && typeof input === 'object' && !Array.isArray(input)) {\n return input as Record<string, unknown>;\n }\n return { value: input };\n }\n\n private extractResultCount(output: unknown): { resultCount?: number } | undefined {\n if (output && typeof output === 'object') {\n const obj = output as Record<string, unknown>;\n // Check for common patterns\n if (Array.isArray(obj.results)) {\n return { resultCount: obj.results.length };\n }\n if (typeof obj.applied === 'number') {\n return { resultCount: obj.applied };\n }\n if (typeof obj.resultCount === 'number') {\n return { resultCount: obj.resultCount };\n }\n }\n return undefined;\n }\n\n private calculateLlmTotals(): {\n totalCalls: number;\n inputTokens: number;\n outputTokens: number;\n llmTimeMs: number;\n } {\n let totalCalls = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let llmTimeMs = 0;\n\n const llmStartTimes = new Map<string, string>();\n\n for (const event of this.events) {\n if (event.type === 'llm_call_start') {\n llmStartTimes.set(event.executionId, event.timestamp);\n } else if (event.type === 'llm_call_end') {\n totalCalls++;\n inputTokens += event.inputTokens;\n outputTokens += event.outputTokens;\n\n const startTime = llmStartTimes.get(event.executionId);\n if (startTime) {\n llmTimeMs += new Date(event.timestamp).getTime() - new Date(startTime).getTime();\n llmStartTimes.delete(event.executionId);\n }\n }\n }\n\n return { totalCalls, inputTokens, outputTokens, llmTimeMs };\n }\n\n private calculateToolSummary(): ToolSummary {\n const toolCalls = new Map<\n string,\n { durations: number[]; successes: number; failures: number; resultCounts: number[] }\n >();\n\n let totalCalls = 0;\n let successfulCalls = 0;\n let failedCalls = 0;\n let totalDurationMs = 0;\n\n for (const event of this.events) {\n if (event.type === 'tool_end') {\n totalCalls++;\n totalDurationMs += event.durationMs;\n\n if (event.error) {\n failedCalls++;\n } else {\n successfulCalls++;\n }\n\n let stats = toolCalls.get(event.name);\n if (!stats) {\n stats = { durations: [], successes: 0, failures: 0, resultCounts: [] };\n toolCalls.set(event.name, stats);\n }\n\n stats.durations.push(event.durationMs);\n if (event.error) {\n stats.failures++;\n } else {\n stats.successes++;\n }\n\n // Extract result count if available\n const resultCount = this.extractResultCountFromOutput(event.output);\n if (resultCount !== undefined) {\n stats.resultCounts.push(resultCount);\n }\n }\n }\n\n const byTool: ToolStats[] = [];\n for (const [toolName, stats] of toolCalls) {\n const callCount = stats.durations.length;\n const sortedDurations = [...stats.durations].sort((a, b) => a - b);\n\n byTool.push({\n toolName,\n callCount,\n successCount: stats.successes,\n failureCount: stats.failures,\n successRate: callCount > 0 ? (stats.successes / callCount) * 100 : 0,\n results:\n stats.resultCounts.length > 0\n ? {\n totalResults: stats.resultCounts.reduce((a, b) => a + b, 0),\n avgResultsPerCall:\n stats.resultCounts.reduce((a, b) => a + b, 0) / stats.resultCounts.length,\n zeroResultCalls: stats.resultCounts.filter((c) => c === 0).length,\n }\n : undefined,\n timing: {\n totalMs: stats.durations.reduce((a, b) => a + b, 0),\n avgMs: callCount > 0 ? stats.durations.reduce((a, b) => a + b, 0) / callCount : 0,\n minMs: sortedDurations[0] ?? 0,\n maxMs: sortedDurations[sortedDurations.length - 1] ?? 0,\n p50Ms: this.percentile(sortedDurations, 50),\n p95Ms: this.percentile(sortedDurations, 95),\n },\n });\n }\n\n return {\n totalCalls,\n successfulCalls,\n failedCalls,\n successRate: totalCalls > 0 ? (successfulCalls / totalCalls) * 100 : 0,\n totalDurationMs,\n byTool,\n };\n }\n\n private extractResultCountFromOutput(output: unknown): number | undefined {\n if (output && typeof output === 'object') {\n const obj = output as Record<string, unknown>;\n if (Array.isArray(obj.results)) {\n return obj.results.length;\n }\n if (typeof obj.resultCount === 'number') {\n return obj.resultCount;\n }\n }\n return undefined;\n }\n\n private percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0;\n if (sorted.length === 1) return sorted[0]!;\n\n const index = (p / 100) * (sorted.length - 1);\n const lower = Math.floor(index);\n const upper = Math.ceil(index);\n\n if (lower === upper) {\n return Math.round(sorted[lower]!);\n }\n\n const weight = index - lower;\n return Math.round(sorted[lower]! * (1 - weight) + sorted[upper]! * weight);\n }\n\n private calculateTimingBreakdown(\n totalMs: number,\n llmTimeMs: number,\n toolTimeMs: number,\n ): TimingBreakdown {\n const overheadMs = Math.max(0, totalMs - llmTimeMs - toolTimeMs);\n\n const breakdown: TimingBreakdownItem[] = [\n {\n category: 'llm',\n label: 'LLM API calls',\n ms: llmTimeMs,\n percentage: totalMs > 0 ? (llmTimeMs / totalMs) * 100 : 0,\n },\n {\n category: 'tools',\n label: 'Tool execution',\n ms: toolTimeMs,\n percentage: totalMs > 0 ? (toolTimeMs / totalMs) * 100 : 0,\n },\n {\n category: 'overhead',\n label: 'Overhead',\n ms: overheadMs,\n percentage: totalMs > 0 ? (overheadMs / totalMs) * 100 : 0,\n },\n ];\n\n return {\n totalMs,\n llmTimeMs,\n toolTimeMs,\n overheadMs,\n breakdown,\n };\n }\n\n private buildExecutionMetadata(timeline: TimelineEntry[]): ExecutionMetadata {\n const orderLevels = new Set<number>();\n const executionThreads = new Set<string>();\n\n for (const entry of timeline) {\n orderLevels.add(entry.order);\n executionThreads.add(entry.executionId);\n }\n\n return {\n totalTurns: timeline.length,\n parallelEnabled: this.parallelEnabled,\n maxParallelAgents: this.parallelEnabled ? this.maxParallelAgents : undefined,\n orderLevels: Array.from(orderLevels).sort((a, b) => a - b),\n executionThreads: Array.from(executionThreads),\n };\n }\n\n private determineStatus(formProgress: ProgressCounts): FillRecordStatus {\n // Explicit status takes precedence\n if (this.explicitStatus) {\n return this.explicitStatus;\n }\n\n // Determine from form progress\n const hasUnanswered = formProgress.unansweredFields > 0;\n const allRequiredFilled = formProgress.answeredFields >= formProgress.requiredFields;\n\n if (!hasUnanswered) {\n return 'completed';\n }\n\n if (allRequiredFilled) {\n return 'completed';\n }\n\n return 'partial';\n }\n}\n","// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\n }\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n 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)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\n if (typeof callbacks == \"function\")\n throw new TypeError(\n \"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;\n let incompleteLine = \"\", isFirstChunk = !0, id, data = \"\", eventType = \"\";\n function feed(newChunk) {\n const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, \"\") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);\n for (const line of complete)\n parseLine(line);\n incompleteLine = incomplete, isFirstChunk = !1;\n }\n function parseLine(line) {\n if (line === \"\") {\n dispatchEvent();\n return;\n }\n if (line.startsWith(\":\")) {\n onComment && onComment(line.slice(line.startsWith(\": \") ? 2 : 1));\n return;\n }\n const fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex !== -1) {\n const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === \" \" ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n return;\n }\n processField(line, \"\", line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value;\n break;\n case \"data\":\n data = `${data}${value}\n`;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n data.length > 0 && onEvent({\n id,\n event: eventType || void 0,\n // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n // then remove the last character from the data buffer.\n data: data.endsWith(`\n`) ? data.slice(0, -1) : data\n }), id = void 0, data = \"\", eventType = \"\";\n }\n function reset(options = {}) {\n incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = \"\", eventType = \"\", incompleteLine = \"\";\n }\n return { feed, reset };\n}\nfunction splitLines(chunk) {\n const lines = [];\n let incompleteLine = \"\", searchIndex = 0;\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {\n incompleteLine = chunk.slice(searchIndex);\n break;\n } else {\n const line = chunk.slice(searchIndex, lineEnd);\n lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === \"\\r\" && chunk[searchIndex] === `\n` && searchIndex++;\n }\n }\n return [lines, incompleteLine];\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n },\n onRetry,\n onComment\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","// src/combine-headers.ts\nfunction combineHeaders(...headers) {\n return headers.reduce(\n (combinedHeaders, currentHeaders) => ({\n ...combinedHeaders,\n ...currentHeaders != null ? currentHeaders : {}\n }),\n {}\n );\n}\n\n// src/convert-async-iterator-to-readable-stream.ts\nfunction convertAsyncIteratorToReadableStream(iterator) {\n let cancelled = false;\n return new ReadableStream({\n /**\n * Called when the consumer wants to pull more data from the stream.\n *\n * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n * @returns {Promise<void>}\n */\n async pull(controller) {\n if (cancelled) return;\n try {\n const { value, done } = await iterator.next();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n },\n /**\n * Called when the consumer cancels the stream.\n */\n async cancel(reason) {\n cancelled = true;\n if (iterator.return) {\n try {\n await iterator.return(reason);\n } catch (e) {\n }\n }\n }\n });\n}\n\n// src/create-tool-name-mapping.ts\nfunction createToolNameMapping({\n tools = [],\n providerToolNames\n}) {\n const customToolNameToProviderToolName = {};\n const providerToolNameToCustomToolName = {};\n for (const tool2 of tools) {\n if (tool2.type === \"provider\" && tool2.id in providerToolNames) {\n const providerToolName = providerToolNames[tool2.id];\n customToolNameToProviderToolName[tool2.name] = providerToolName;\n providerToolNameToCustomToolName[providerToolName] = tool2.name;\n }\n }\n return {\n toProviderToolName: (customToolName) => {\n var _a2;\n return (_a2 = customToolNameToProviderToolName[customToolName]) != null ? _a2 : customToolName;\n },\n toCustomToolName: (providerToolName) => {\n var _a2;\n return (_a2 = providerToolNameToCustomToolName[providerToolName]) != null ? _a2 : providerToolName;\n }\n };\n}\n\n// src/delay.ts\nasync function delay(delayInMs, options) {\n if (delayInMs == null) {\n return Promise.resolve();\n }\n const signal = options == null ? void 0 : options.abortSignal;\n return new Promise((resolve2, reject) => {\n if (signal == null ? void 0 : signal.aborted) {\n reject(createAbortError());\n return;\n }\n const timeoutId = setTimeout(() => {\n cleanup();\n resolve2();\n }, delayInMs);\n const cleanup = () => {\n clearTimeout(timeoutId);\n signal == null ? void 0 : signal.removeEventListener(\"abort\", onAbort);\n };\n const onAbort = () => {\n cleanup();\n reject(createAbortError());\n };\n signal == null ? void 0 : signal.addEventListener(\"abort\", onAbort);\n });\n}\nfunction createAbortError() {\n return new DOMException(\"Delay was aborted\", \"AbortError\");\n}\n\n// src/delayed-promise.ts\nvar DelayedPromise = class {\n constructor() {\n this.status = { type: \"pending\" };\n this._resolve = void 0;\n this._reject = void 0;\n }\n get promise() {\n if (this._promise) {\n return this._promise;\n }\n this._promise = new Promise((resolve2, reject) => {\n if (this.status.type === \"resolved\") {\n resolve2(this.status.value);\n } else if (this.status.type === \"rejected\") {\n reject(this.status.error);\n }\n this._resolve = resolve2;\n this._reject = reject;\n });\n return this._promise;\n }\n resolve(value) {\n var _a2;\n this.status = { type: \"resolved\", value };\n if (this._promise) {\n (_a2 = this._resolve) == null ? void 0 : _a2.call(this, value);\n }\n }\n reject(error) {\n var _a2;\n this.status = { type: \"rejected\", error };\n if (this._promise) {\n (_a2 = this._reject) == null ? void 0 : _a2.call(this, error);\n }\n }\n isResolved() {\n return this.status.type === \"resolved\";\n }\n isRejected() {\n return this.status.type === \"rejected\";\n }\n isPending() {\n return this.status.type === \"pending\";\n }\n};\n\n// src/extract-response-headers.ts\nfunction extractResponseHeaders(response) {\n return Object.fromEntries([...response.headers]);\n}\n\n// src/uint8-utils.ts\nvar { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n const base64Url = base64String.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const latin1string = atob(base64Url);\n return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n let latin1string = \"\";\n for (let i = 0; i < array.length; i++) {\n latin1string += String.fromCodePoint(array[i]);\n }\n return btoa(latin1string);\n}\nfunction convertToBase64(value) {\n return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n\n// src/convert-image-model-file-to-data-uri.ts\nfunction convertImageModelFileToDataUri(file) {\n if (file.type === \"url\") return file.url;\n return `data:${file.mediaType};base64,${typeof file.data === \"string\" ? file.data : convertUint8ArrayToBase64(file.data)}`;\n}\n\n// src/convert-to-form-data.ts\nfunction convertToFormData(input, options = {}) {\n const { useArrayBrackets = true } = options;\n const formData = new FormData();\n for (const [key, value] of Object.entries(input)) {\n if (value == null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 1) {\n formData.append(key, value[0]);\n continue;\n }\n const arrayKey = useArrayBrackets ? `${key}[]` : key;\n for (const item of value) {\n formData.append(arrayKey, item);\n }\n continue;\n }\n formData.append(key, value);\n }\n return formData;\n}\n\n// src/download-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_DownloadError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {\n constructor({\n url,\n statusCode,\n statusText,\n cause,\n message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`\n }) {\n super({ name, message, cause });\n this[_a] = true;\n this.url = url;\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker);\n }\n};\n\n// src/download-blob.ts\nasync function downloadBlob(url) {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n throw new DownloadError({\n url,\n statusCode: response.status,\n statusText: response.statusText\n });\n }\n return await response.blob();\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n throw new DownloadError({ url, cause: error });\n }\n}\n\n// src/generate-id.ts\nimport { InvalidArgumentError } from \"@ai-sdk/provider\";\nvar createIdGenerator = ({\n prefix,\n size = 16,\n alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n separator = \"-\"\n} = {}) => {\n const generator = () => {\n const alphabetLength = alphabet.length;\n const chars = new Array(size);\n for (let i = 0; i < size; i++) {\n chars[i] = alphabet[Math.random() * alphabetLength | 0];\n }\n return chars.join(\"\");\n };\n if (prefix == null) {\n return generator;\n }\n if (alphabet.includes(separator)) {\n throw new InvalidArgumentError({\n argument: \"separator\",\n message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n });\n }\n return () => `${prefix}${separator}${generator()}`;\n};\nvar generateId = createIdGenerator();\n\n// src/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/get-from-api.ts\nimport { APICallError as APICallError2 } from \"@ai-sdk/provider\";\n\n// src/handle-fetch-error.ts\nimport { APICallError } from \"@ai-sdk/provider\";\n\n// src/is-abort-error.ts\nfunction isAbortError(error) {\n return (error instanceof Error || error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || // Next.js\n error.name === \"TimeoutError\");\n}\n\n// src/handle-fetch-error.ts\nvar FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nvar BUN_ERROR_CODES = [\n \"ConnectionRefused\",\n \"ConnectionClosed\",\n \"FailedToOpenSocket\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ETIMEDOUT\",\n \"EPIPE\"\n];\nfunction isBunNetworkError(error) {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = error.code;\n if (typeof code === \"string\" && BUN_ERROR_CODES.includes(code)) {\n return true;\n }\n return false;\n}\nfunction handleFetchError({\n error,\n url,\n requestBodyValues\n}) {\n if (isAbortError(error)) {\n return error;\n }\n if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n const cause = error.cause;\n if (cause != null) {\n return new APICallError({\n message: `Cannot connect to API: ${cause.message}`,\n cause,\n url,\n requestBodyValues,\n isRetryable: true\n // retry when network error\n });\n }\n }\n if (isBunNetworkError(error)) {\n return new APICallError({\n message: `Cannot connect to API: ${error.message}`,\n cause: error,\n url,\n requestBodyValues,\n isRetryable: true\n });\n }\n return error;\n}\n\n// src/get-runtime-environment-user-agent.ts\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n var _a2, _b2, _c;\n if (globalThisAny.window) {\n return `runtime/browser`;\n }\n if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) {\n return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n }\n if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) {\n return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n }\n if (globalThisAny.EdgeRuntime) {\n return `runtime/vercel-edge`;\n }\n return \"runtime/unknown\";\n}\n\n// src/normalize-headers.ts\nfunction normalizeHeaders(headers) {\n if (headers == null) {\n return {};\n }\n const normalized = {};\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n normalized[key.toLowerCase()] = value;\n });\n } else {\n if (!Array.isArray(headers)) {\n headers = Object.entries(headers);\n }\n for (const [key, value] of headers) {\n if (value != null) {\n normalized[key.toLowerCase()] = value;\n }\n }\n }\n return normalized;\n}\n\n// src/with-user-agent-suffix.ts\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n const normalizedHeaders = new Headers(normalizeHeaders(headers));\n const currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n normalizedHeaders.set(\n \"user-agent\",\n [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \")\n );\n return Object.fromEntries(normalizedHeaders.entries());\n}\n\n// src/version.ts\nvar VERSION = true ? \"4.0.12\" : \"0.0.0-test\";\n\n// src/get-from-api.ts\nvar getOriginalFetch = () => globalThis.fetch;\nvar getFromApi = async ({\n url,\n headers = {},\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch: fetch2 = getOriginalFetch()\n}) => {\n try {\n const response = await fetch2(url, {\n method: \"GET\",\n headers: withUserAgentSuffix(\n headers,\n `ai-sdk/provider-utils/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n signal: abortSignal\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!response.ok) {\n let errorInformation;\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: {}\n });\n } catch (error) {\n if (isAbortError(error) || APICallError2.isInstance(error)) {\n throw error;\n }\n throw new APICallError2({\n message: \"Failed to process error response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {}\n });\n }\n throw errorInformation.value;\n }\n try {\n return await successfulResponseHandler({\n response,\n url,\n requestBodyValues: {}\n });\n } catch (error) {\n if (error instanceof Error) {\n if (isAbortError(error) || APICallError2.isInstance(error)) {\n throw error;\n }\n }\n throw new APICallError2({\n message: \"Failed to process successful response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {}\n });\n }\n } catch (error) {\n throw handleFetchError({ error, url, requestBodyValues: {} });\n }\n};\n\n// src/inject-json-instruction.ts\nvar DEFAULT_SCHEMA_PREFIX = \"JSON schema:\";\nvar DEFAULT_SCHEMA_SUFFIX = \"You MUST answer with a JSON object that matches the JSON schema above.\";\nvar DEFAULT_GENERIC_SUFFIX = \"You MUST answer with JSON.\";\nfunction injectJsonInstruction({\n prompt,\n schema,\n schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,\n schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX\n}) {\n return [\n prompt != null && prompt.length > 0 ? prompt : void 0,\n prompt != null && prompt.length > 0 ? \"\" : void 0,\n // add a newline if prompt is not null\n schemaPrefix,\n schema != null ? JSON.stringify(schema) : void 0,\n schemaSuffix\n ].filter((line) => line != null).join(\"\\n\");\n}\nfunction injectJsonInstructionIntoMessages({\n messages,\n schema,\n schemaPrefix,\n schemaSuffix\n}) {\n var _a2, _b2;\n const systemMessage = ((_a2 = messages[0]) == null ? void 0 : _a2.role) === \"system\" ? { ...messages[0] } : { role: \"system\", content: \"\" };\n systemMessage.content = injectJsonInstruction({\n prompt: systemMessage.content,\n schema,\n schemaPrefix,\n schemaSuffix\n });\n return [\n systemMessage,\n ...((_b2 = messages[0]) == null ? void 0 : _b2.role) === \"system\" ? messages.slice(1) : messages\n ];\n}\n\n// src/is-non-nullable.ts\nfunction isNonNullable(value) {\n return value != null;\n}\n\n// src/is-url-supported.ts\nfunction isUrlSupported({\n mediaType,\n url,\n supportedUrls\n}) {\n url = url.toLowerCase();\n mediaType = mediaType.toLowerCase();\n return Object.entries(supportedUrls).map(([key, value]) => {\n const mediaType2 = key.toLowerCase();\n return mediaType2 === \"*\" || mediaType2 === \"*/*\" ? { mediaTypePrefix: \"\", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\\*/, \"\"), regexes: value };\n }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));\n}\n\n// src/load-api-key.ts\nimport { LoadAPIKeyError } from \"@ai-sdk/provider\";\nfunction loadApiKey({\n apiKey,\n environmentVariableName,\n apiKeyParameterName = \"apiKey\",\n description\n}) {\n if (typeof apiKey === \"string\") {\n return apiKey;\n }\n if (apiKey != null) {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string.`\n });\n }\n if (typeof process === \"undefined\") {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`\n });\n }\n apiKey = process.env[environmentVariableName];\n if (apiKey == null) {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`\n });\n }\n if (typeof apiKey !== \"string\") {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n });\n }\n return apiKey;\n}\n\n// src/load-optional-setting.ts\nfunction loadOptionalSetting({\n settingValue,\n environmentVariableName\n}) {\n if (typeof settingValue === \"string\") {\n return settingValue;\n }\n if (settingValue != null || typeof process === \"undefined\") {\n return void 0;\n }\n settingValue = process.env[environmentVariableName];\n if (settingValue == null || typeof settingValue !== \"string\") {\n return void 0;\n }\n return settingValue;\n}\n\n// src/load-setting.ts\nimport { LoadSettingError } from \"@ai-sdk/provider\";\nfunction loadSetting({\n settingValue,\n environmentVariableName,\n settingName,\n description\n}) {\n if (typeof settingValue === \"string\") {\n return settingValue;\n }\n if (settingValue != null) {\n throw new LoadSettingError({\n message: `${description} setting must be a string.`\n });\n }\n if (typeof process === \"undefined\") {\n throw new LoadSettingError({\n message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`\n });\n }\n settingValue = process.env[environmentVariableName];\n if (settingValue == null) {\n throw new LoadSettingError({\n message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`\n });\n }\n if (typeof settingValue !== \"string\") {\n throw new LoadSettingError({\n message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n });\n }\n return settingValue;\n}\n\n// src/media-type-to-extension.ts\nfunction mediaTypeToExtension(mediaType) {\n var _a2;\n const [_type, subtype = \"\"] = mediaType.toLowerCase().split(\"/\");\n return (_a2 = {\n mpeg: \"mp3\",\n \"x-wav\": \"wav\",\n opus: \"ogg\",\n mp4: \"m4a\",\n \"x-m4a\": \"m4a\"\n }[subtype]) != null ? _a2 : subtype;\n}\n\n// src/parse-json.ts\nimport {\n JSONParseError,\n TypeValidationError as TypeValidationError3\n} from \"@ai-sdk/provider\";\n\n// src/secure-json-parse.ts\nvar suspectProtoRx = /\"__proto__\"\\s*:/;\nvar suspectConstructorRx = /\"constructor\"\\s*:/;\nfunction _parse(text) {\n const obj = JSON.parse(text);\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {\n return obj;\n }\n return filter(obj);\n}\nfunction filter(obj) {\n let next = [obj];\n while (next.length) {\n const nodes = next;\n next = [];\n for (const node of nodes) {\n if (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n if (Object.prototype.hasOwnProperty.call(node, \"constructor\") && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === \"object\") {\n next.push(value);\n }\n }\n }\n }\n return obj;\n}\nfunction secureJsonParse(text) {\n const { stackTraceLimit } = Error;\n try {\n Error.stackTraceLimit = 0;\n } catch (e) {\n return _parse(text);\n }\n try {\n return _parse(text);\n } finally {\n Error.stackTraceLimit = stackTraceLimit;\n }\n}\n\n// src/validate-types.ts\nimport { TypeValidationError as TypeValidationError2 } from \"@ai-sdk/provider\";\n\n// src/schema.ts\nimport { TypeValidationError } from \"@ai-sdk/provider\";\nimport * as z4 from \"zod/v4\";\n\n// src/add-additional-properties-to-json-schema.ts\nfunction addAdditionalPropertiesToJsonSchema(jsonSchema2) {\n if (jsonSchema2.type === \"object\" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes(\"object\")) {\n jsonSchema2.additionalProperties = false;\n const { properties } = jsonSchema2;\n if (properties != null) {\n for (const key of Object.keys(properties)) {\n properties[key] = visit(properties[key]);\n }\n }\n }\n if (jsonSchema2.items != null) {\n jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);\n }\n if (jsonSchema2.anyOf != null) {\n jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);\n }\n if (jsonSchema2.allOf != null) {\n jsonSchema2.allOf = jsonSchema2.allOf.map(visit);\n }\n if (jsonSchema2.oneOf != null) {\n jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);\n }\n const { definitions } = jsonSchema2;\n if (definitions != null) {\n for (const key of Object.keys(definitions)) {\n definitions[key] = visit(definitions[key]);\n }\n }\n return jsonSchema2;\n}\nfunction visit(def) {\n if (typeof def === \"boolean\") return def;\n return addAdditionalPropertiesToJsonSchema(def);\n}\n\n// src/to-json-schema/zod3-to-json-schema/options.ts\nvar ignoreOverride = Symbol(\n \"Let zodToJsonSchema decide on which parser to use\"\n);\nvar defaultOptions = {\n name: void 0,\n $refStrategy: \"root\",\n basePath: [\"#\"],\n effectStrategy: \"input\",\n pipeStrategy: \"all\",\n dateStrategy: \"format:date-time\",\n mapStrategy: \"entries\",\n removeAdditionalStrategy: \"passthrough\",\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: \"definitions\",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n patternStrategy: \"escape\",\n applyRegexFlags: false,\n emailStrategy: \"format:email\",\n base64Strategy: \"contentEncoding:base64\",\n nameStrategy: \"ref\"\n};\nvar getDefaultOptions = (options) => typeof options === \"string\" ? {\n ...defaultOptions,\n name: options\n} : {\n ...defaultOptions,\n ...options\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nimport { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/any.ts\nfunction parseAnyDef() {\n return {};\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/array.ts\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\nfunction parseArrayDef(def, refs) {\n var _a2, _b2, _c;\n const res = {\n type: \"array\"\n };\n 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) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"]\n });\n }\n if (def.minLength) {\n res.minItems = def.minLength.value;\n }\n if (def.maxLength) {\n res.maxItems = def.maxLength.value;\n }\n if (def.exactLength) {\n res.minItems = def.exactLength.value;\n res.maxItems = def.exactLength.value;\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts\nfunction parseBigintDef(def) {\n const res = {\n type: \"integer\",\n format: \"int64\"\n };\n if (!def.checks) return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case \"max\":\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n break;\n case \"multipleOf\":\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts\nfunction parseBooleanDef() {\n return { type: \"boolean\" };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/branded.ts\nfunction parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/catch.ts\nvar parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/date.ts\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))\n };\n }\n switch (strategy) {\n case \"string\":\n case \"format:date-time\":\n return {\n type: \"string\",\n format: \"date-time\"\n };\n case \"format:date\":\n return {\n type: \"string\",\n format: \"date\"\n };\n case \"integer\":\n return integerDateParser(def);\n }\n}\nvar integerDateParser = (def) => {\n const res = {\n type: \"integer\",\n format: \"unix-time\"\n };\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n res.minimum = check.value;\n break;\n case \"max\":\n res.maximum = check.value;\n break;\n }\n }\n return res;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/default.ts\nfunction parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue()\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/effects.ts\nfunction parseEffectsDef(_def, refs) {\n return refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/enum.ts\nfunction parseEnumDef(def) {\n return {\n type: \"string\",\n enum: Array.from(def.values)\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts\nvar isJsonSchema7AllOfType = (type) => {\n if (\"type\" in type && type.type === \"string\") return false;\n return \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"1\"]\n })\n ].filter((x) => !!x);\n const mergedAllOf = [];\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n } else {\n let nestedSchema = schema;\n if (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/literal.ts\nfunction parseLiteralDef(def) {\n const parsedType = typeof def.value;\n if (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") {\n return {\n type: Array.isArray(def.value) ? \"array\" : \"object\"\n };\n }\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n const: def.value\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nimport {\n ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2\n} from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/string.ts\nvar emojiRegex = void 0;\nvar zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === void 0) {\n emojiRegex = RegExp(\n \"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\",\n \"u\"\n );\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n const res = {\n type: \"string\"\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n break;\n case \"max\":\n res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(\n res,\n RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n check.message,\n refs\n );\n break;\n case \"endsWith\":\n addPattern(\n res,\n RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n check.message,\n refs\n );\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n break;\n case \"includes\": {\n addPattern(\n res,\n RegExp(escapeLiteralCheckValue(check.value, refs)),\n check.message,\n refs\n );\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n res.contentEncoding = \"base64\";\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n /* @__PURE__ */ ((_) => {\n })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nvar ALPHA_NUMERIC = new Set(\n \"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\"\n);\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\nfunction addFormat(schema, value, message, refs) {\n var _a2;\n if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format\n });\n delete schema.format;\n }\n schema.anyOf.push({\n format: value,\n ...message && refs.errorMessages && { errorMessage: { format: message } }\n });\n } else {\n schema.format = value;\n }\n}\nfunction addPattern(schema, regex, message, refs) {\n var _a2;\n if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern\n });\n delete schema.pattern;\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...message && refs.errorMessages && { errorMessage: { pattern: message } }\n });\n } else {\n schema.pattern = stringifyRegExpWithFlags(regex, refs);\n }\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n var _a2;\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n const flags = {\n i: regex.flags.includes(\"i\"),\n // Case-insensitive\n m: regex.flags.includes(\"m\"),\n // `^` and `$` matches adjacent to newline characters\n s: regex.flags.includes(\"s\")\n // `.` matches newlines\n };\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n } else if (source[i + 1] === \"-\" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {\n pattern += source[i];\n inCharRange = true;\n } else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n } else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\n]))`;\n continue;\n } else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\n` : `[${source[i]}\\r\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n } else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n } else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n } catch (e) {\n console.warn(\n `Could not convert regex pattern at ${refs.currentPath.join(\n \"/\"\n )} to a flag-independent form! Falling back to the flag-ignorant source`\n );\n return regex.source;\n }\n return pattern;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nfunction parseRecordDef(def, refs) {\n var _a2, _b2, _c, _d, _e, _f;\n const schema = {\n type: \"object\",\n additionalProperties: (_a2 = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"]\n })) != null ? _a2 : refs.allowedAdditionalProperties\n };\n if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType\n };\n } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values\n }\n };\n } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {\n const { type, ...keyType } = parseBrandedDef(\n def.keyType._def,\n refs\n );\n return {\n ...schema,\n propertyNames: keyType\n };\n }\n return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/map.ts\nfunction parseMapDef(def, refs) {\n if (refs.mapStrategy === \"record\") {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"]\n }) || parseAnyDef();\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"]\n }) || parseAnyDef();\n return {\n type: \"array\",\n maxItems: 125,\n items: {\n type: \"array\",\n items: [keys, values],\n minItems: 2,\n maxItems: 2\n }\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts\nfunction parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== \"number\";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(\n new Set(actualValues.map((values) => typeof values))\n );\n return {\n type: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n enum: actualValues\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/never.ts\nfunction parseNeverDef() {\n return { not: parseAnyDef() };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/null.ts\nfunction parseNullDef() {\n return {\n type: \"null\"\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/union.ts\nvar primitiveMappings = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"integer\",\n ZodBoolean: \"boolean\",\n ZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n if (options.every(\n (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)\n )) {\n const types = options.reduce((types2, x) => {\n const type = primitiveMappings[x._def.typeName];\n return type && !types2.includes(type) ? [...types2, type] : types2;\n }, []);\n return {\n type: types.length > 1 ? types : types[0]\n };\n } else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n const types = options.reduce(\n (acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return [...acc, type];\n case \"bigint\":\n return [...acc, \"integer\"];\n case \"object\":\n if (x._def.value === null) return [...acc, \"null\"];\n case \"symbol\":\n case \"undefined\":\n case \"function\":\n default:\n return acc;\n }\n },\n []\n );\n if (types.length === options.length) {\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce(\n (acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n },\n []\n )\n };\n }\n } else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n return {\n type: \"string\",\n enum: options.reduce(\n (acc, x) => [\n ...acc,\n ...x._def.values.filter((x2) => !acc.includes(x2))\n ],\n []\n )\n };\n }\n return asAnyOf(def, refs);\n}\nvar asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", `${i}`]\n })\n ).filter(\n (x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0)\n );\n return anyOf.length ? { anyOf } : void 0;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts\nfunction parseNullableDef(def, refs) {\n if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(\n def.innerType._def.typeName\n ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n return {\n type: [\n primitiveMappings[def.innerType._def.typeName],\n \"null\"\n ]\n };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"0\"]\n });\n return base && { anyOf: [base, { type: \"null\" }] };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/number.ts\nfunction parseNumberDef(def) {\n const res = {\n type: \"number\"\n };\n if (!def.checks) return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"int\":\n res.type = \"integer\";\n break;\n case \"min\":\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case \"max\":\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n break;\n case \"multipleOf\":\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/object.ts\nfunction parseObjectDef(def, refs) {\n const result = {\n type: \"object\",\n properties: {}\n };\n const required = [];\n const shape = def.shape();\n for (const propName in shape) {\n let propDef = shape[propName];\n if (propDef === void 0 || propDef._def === void 0) {\n continue;\n }\n const propOptional = safeIsOptional(propDef);\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", propName],\n propertyPath: [...refs.currentPath, \"properties\", propName]\n });\n if (parsedDef === void 0) {\n continue;\n }\n result.properties[propName] = parsedDef;\n if (!propOptional) {\n required.push(propName);\n }\n }\n if (required.length) {\n result.required = required;\n }\n const additionalProperties = decideAdditionalProperties(def, refs);\n if (additionalProperties !== void 0) {\n result.additionalProperties = additionalProperties;\n }\n return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n if (def.catchall._def.typeName !== \"ZodNever\") {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"]\n });\n }\n switch (def.unknownKeys) {\n case \"passthrough\":\n return refs.allowedAdditionalProperties;\n case \"strict\":\n return refs.rejectedAdditionalProperties;\n case \"strip\":\n return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n }\n}\nfunction safeIsOptional(schema) {\n try {\n return schema.isOptional();\n } catch (e) {\n return true;\n }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/optional.ts\nvar parseOptionalDef = (def, refs) => {\n var _a2;\n if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"1\"]\n });\n return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts\nvar parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === \"input\") {\n return parseDef(def.in._def, refs);\n } else if (refs.pipeStrategy === \"output\") {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", a ? \"1\" : \"0\"]\n });\n return {\n allOf: [a, b].filter((x) => x !== void 0)\n };\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/promise.ts\nfunction parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/set.ts\nfunction parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"]\n });\n const schema = {\n type: \"array\",\n uniqueItems: true,\n items\n };\n if (def.minSize) {\n schema.minItems = def.minSize.value;\n }\n if (def.maxSize) {\n schema.maxItems = def.maxSize.value;\n }\n return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts\nfunction parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: \"array\",\n minItems: def.items.length,\n items: def.items.map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`]\n })\n ).reduce(\n (acc, x) => x === void 0 ? acc : [...acc, x],\n []\n ),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalItems\"]\n })\n };\n } else {\n return {\n type: \"array\",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items.map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`]\n })\n ).reduce(\n (acc, x) => x === void 0 ? acc : [...acc, x],\n []\n )\n };\n }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts\nfunction parseUndefinedDef() {\n return {\n not: parseAnyDef()\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts\nfunction parseUnknownDef() {\n return parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts\nvar parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nvar selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind3.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodNumber:\n return parseNumberDef(def);\n case ZodFirstPartyTypeKind3.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodBigInt:\n return parseBigintDef(def);\n case ZodFirstPartyTypeKind3.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind3.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodUndefined:\n return parseUndefinedDef();\n case ZodFirstPartyTypeKind3.ZodNull:\n return parseNullDef();\n case ZodFirstPartyTypeKind3.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodUnion:\n case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodLiteral:\n return parseLiteralDef(def);\n case ZodFirstPartyTypeKind3.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind3.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind3.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodLazy:\n return () => def.getter()._def;\n case ZodFirstPartyTypeKind3.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodNaN:\n case ZodFirstPartyTypeKind3.ZodNever:\n return parseNeverDef();\n case ZodFirstPartyTypeKind3.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodAny:\n return parseAnyDef();\n case ZodFirstPartyTypeKind3.ZodUnknown:\n return parseUnknownDef();\n case ZodFirstPartyTypeKind3.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodFunction:\n case ZodFirstPartyTypeKind3.ZodVoid:\n case ZodFirstPartyTypeKind3.ZodSymbol:\n return void 0;\n default:\n return /* @__PURE__ */ ((_) => void 0)(typeName);\n }\n};\n\n// src/to-json-schema/zod3-to-json-schema/get-relative-path.ts\nvar getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i]) break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n\n// src/to-json-schema/zod3-to-json-schema/parse-def.ts\nfunction parseDef(def, refs, forceResolution = false) {\n var _a2;\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(\n refs,\n def,\n refs,\n seenItem,\n forceResolution\n );\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== void 0) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };\n refs.seen.set(def, newItem);\n const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n const jsonSchema2 = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n if (jsonSchema2) {\n addMeta(def, refs, jsonSchema2);\n }\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema2, def, refs);\n newItem.jsonSchema = jsonSchema2;\n return postProcessResult;\n }\n newItem.jsonSchema = jsonSchema2;\n return jsonSchema2;\n}\nvar get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case \"root\":\n return { $ref: item.path.join(\"/\") };\n case \"relative\":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case \"none\":\n case \"seen\": {\n if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(\n `Recursive reference detected at ${refs.currentPath.join(\n \"/\"\n )}! Defaulting to any`\n );\n return parseAnyDef();\n }\n return refs.$refStrategy === \"seen\" ? parseAnyDef() : void 0;\n }\n }\n};\nvar addMeta = (def, refs, jsonSchema2) => {\n if (def.description) {\n jsonSchema2.description = def.description;\n }\n return jsonSchema2;\n};\n\n// src/to-json-schema/zod3-to-json-schema/refs.ts\nvar getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;\n return {\n ..._options,\n currentPath,\n propertyPath: void 0,\n seen: new Map(\n Object.entries(_options.definitions).map(([name2, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name2],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: void 0\n }\n ])\n )\n };\n};\n\n// src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts\nvar zod3ToJsonSchema = (schema, options) => {\n var _a2;\n const refs = getRefs(options);\n let definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce(\n (acc, [name3, schema2]) => {\n var _a3;\n return {\n ...acc,\n [name3]: (_a3 = parseDef(\n schema2._def,\n {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name3]\n },\n true\n )) != null ? _a3 : parseAnyDef()\n };\n },\n {}\n ) : void 0;\n const name2 = typeof options === \"string\" ? options : (options == null ? void 0 : options.nameStrategy) === \"title\" ? void 0 : options == null ? void 0 : options.name;\n const main = (_a2 = parseDef(\n schema._def,\n name2 === void 0 ? refs : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name2]\n },\n false\n )) != null ? _a2 : parseAnyDef();\n const title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n if (title !== void 0) {\n main.title = title;\n }\n const combined = name2 === void 0 ? definitions ? {\n ...main,\n [refs.definitionPath]: definitions\n } : main : {\n $ref: [\n ...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n refs.definitionPath,\n name2\n ].join(\"/\"),\n [refs.definitionPath]: {\n ...definitions,\n [name2]: main\n }\n };\n combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n return combined;\n};\n\n// src/schema.ts\nvar schemaSymbol = Symbol.for(\"vercel.ai.schema\");\nfunction lazySchema(createSchema) {\n let schema;\n return () => {\n if (schema == null) {\n schema = createSchema();\n }\n return schema;\n };\n}\nfunction jsonSchema(jsonSchema2, {\n validate\n} = {}) {\n return {\n [schemaSymbol]: true,\n _type: void 0,\n // should never be used directly\n get jsonSchema() {\n if (typeof jsonSchema2 === \"function\") {\n jsonSchema2 = jsonSchema2();\n }\n return jsonSchema2;\n },\n validate\n };\n}\nfunction isSchema(value) {\n return typeof value === \"object\" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && \"jsonSchema\" in value && \"validate\" in value;\n}\nfunction asSchema(schema) {\n return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : \"~standard\" in schema ? schema[\"~standard\"].vendor === \"zod\" ? zodSchema(schema) : standardSchema(schema) : schema();\n}\nfunction standardSchema(standardSchema2) {\n return jsonSchema(\n () => addAdditionalPropertiesToJsonSchema(\n standardSchema2[\"~standard\"].jsonSchema.input({\n target: \"draft-07\"\n })\n ),\n {\n validate: async (value) => {\n const result = await standardSchema2[\"~standard\"].validate(value);\n return \"value\" in result ? { success: true, value: result.value } : {\n success: false,\n error: new TypeValidationError({\n value,\n cause: result.issues\n })\n };\n }\n }\n );\n}\nfunction zod3Schema(zodSchema2, options) {\n var _a2;\n const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () => zod3ToJsonSchema(zodSchema2, {\n $refStrategy: useReferences ? \"root\" : \"none\"\n }),\n {\n validate: async (value) => {\n const result = await zodSchema2.safeParseAsync(value);\n return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n }\n }\n );\n}\nfunction zod4Schema(zodSchema2, options) {\n var _a2;\n const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () => addAdditionalPropertiesToJsonSchema(\n z4.toJSONSchema(zodSchema2, {\n target: \"draft-7\",\n io: \"input\",\n reused: useReferences ? \"ref\" : \"inline\"\n })\n ),\n {\n validate: async (value) => {\n const result = await z4.safeParseAsync(zodSchema2, value);\n return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n }\n }\n );\n}\nfunction isZod4Schema(zodSchema2) {\n return \"_zod\" in zodSchema2;\n}\nfunction zodSchema(zodSchema2, options) {\n if (isZod4Schema(zodSchema2)) {\n return zod4Schema(zodSchema2, options);\n } else {\n return zod3Schema(zodSchema2, options);\n }\n}\n\n// src/validate-types.ts\nasync function validateTypes({\n value,\n schema,\n context\n}) {\n const result = await safeValidateTypes({ value, schema, context });\n if (!result.success) {\n throw TypeValidationError2.wrap({ value, cause: result.error, context });\n }\n return result.value;\n}\nasync function safeValidateTypes({\n value,\n schema,\n context\n}) {\n const actualSchema = asSchema(schema);\n try {\n if (actualSchema.validate == null) {\n return { success: true, value, rawValue: value };\n }\n const result = await actualSchema.validate(value);\n if (result.success) {\n return { success: true, value: result.value, rawValue: value };\n }\n return {\n success: false,\n error: TypeValidationError2.wrap({ value, cause: result.error, context }),\n rawValue: value\n };\n } catch (error) {\n return {\n success: false,\n error: TypeValidationError2.wrap({ value, cause: error, context }),\n rawValue: value\n };\n }\n}\n\n// src/parse-json.ts\nasync function parseJSON({\n text,\n schema\n}) {\n try {\n const value = secureJsonParse(text);\n if (schema == null) {\n return value;\n }\n return validateTypes({ value, schema });\n } catch (error) {\n if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {\n throw error;\n }\n throw new JSONParseError({ text, cause: error });\n }\n}\nasync function safeParseJSON({\n text,\n schema\n}) {\n try {\n const value = secureJsonParse(text);\n if (schema == null) {\n return { success: true, value, rawValue: value };\n }\n return await safeValidateTypes({ value, schema });\n } catch (error) {\n return {\n success: false,\n error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),\n rawValue: void 0\n };\n }\n}\nfunction isParsableJson(input) {\n try {\n secureJsonParse(input);\n return true;\n } catch (e) {\n return false;\n }\n}\n\n// src/parse-json-event-stream.ts\nimport {\n EventSourceParserStream\n} from \"eventsource-parser/stream\";\nfunction parseJsonEventStream({\n stream,\n schema\n}) {\n return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(\n new TransformStream({\n async transform({ data }, controller) {\n if (data === \"[DONE]\") {\n return;\n }\n controller.enqueue(await safeParseJSON({ text: data, schema }));\n }\n })\n );\n}\n\n// src/parse-provider-options.ts\nimport { InvalidArgumentError as InvalidArgumentError2 } from \"@ai-sdk/provider\";\nasync function parseProviderOptions({\n provider,\n providerOptions,\n schema\n}) {\n if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {\n return void 0;\n }\n const parsedProviderOptions = await safeValidateTypes({\n value: providerOptions[provider],\n schema\n });\n if (!parsedProviderOptions.success) {\n throw new InvalidArgumentError2({\n argument: \"providerOptions\",\n message: `invalid ${provider} provider options`,\n cause: parsedProviderOptions.error\n });\n }\n return parsedProviderOptions.value;\n}\n\n// src/post-to-api.ts\nimport { APICallError as APICallError3 } from \"@ai-sdk/provider\";\nvar getOriginalFetch2 = () => globalThis.fetch;\nvar postJsonToApi = async ({\n url,\n headers,\n body,\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n}) => postToApi({\n url,\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers\n },\n body: {\n content: JSON.stringify(body),\n values: body\n },\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n});\nvar postFormDataToApi = async ({\n url,\n headers,\n formData,\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n}) => postToApi({\n url,\n headers,\n body: {\n content: formData,\n values: Object.fromEntries(formData.entries())\n },\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n});\nvar postToApi = async ({\n url,\n headers = {},\n body,\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch: fetch2 = getOriginalFetch2()\n}) => {\n try {\n const response = await fetch2(url, {\n method: \"POST\",\n headers: withUserAgentSuffix(\n headers,\n `ai-sdk/provider-utils/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n body: body.content,\n signal: abortSignal\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!response.ok) {\n let errorInformation;\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: body.values\n });\n } catch (error) {\n if (isAbortError(error) || APICallError3.isInstance(error)) {\n throw error;\n }\n throw new APICallError3({\n message: \"Failed to process error response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: body.values\n });\n }\n throw errorInformation.value;\n }\n try {\n return await successfulResponseHandler({\n response,\n url,\n requestBodyValues: body.values\n });\n } catch (error) {\n if (error instanceof Error) {\n if (isAbortError(error) || APICallError3.isInstance(error)) {\n throw error;\n }\n }\n throw new APICallError3({\n message: \"Failed to process successful response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: body.values\n });\n }\n } catch (error) {\n throw handleFetchError({ error, url, requestBodyValues: body.values });\n }\n};\n\n// src/types/tool.ts\nfunction tool(tool2) {\n return tool2;\n}\nfunction dynamicTool(tool2) {\n return { ...tool2, type: \"dynamic\" };\n}\n\n// src/provider-tool-factory.ts\nfunction createProviderToolFactory({\n id,\n inputSchema\n}) {\n return ({\n execute,\n outputSchema,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n ...args\n }) => tool({\n type: \"provider\",\n id,\n args,\n inputSchema,\n outputSchema,\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable\n });\n}\nfunction createProviderToolFactoryWithOutputSchema({\n id,\n inputSchema,\n outputSchema,\n supportsDeferredResults\n}) {\n return ({\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n ...args\n }) => tool({\n type: \"provider\",\n id,\n args,\n inputSchema,\n outputSchema,\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n supportsDeferredResults\n });\n}\n\n// src/remove-undefined-entries.ts\nfunction removeUndefinedEntries(record) {\n return Object.fromEntries(\n Object.entries(record).filter(([_key, value]) => value != null)\n );\n}\n\n// src/resolve.ts\nasync function resolve(value) {\n if (typeof value === \"function\") {\n value = value();\n }\n return Promise.resolve(value);\n}\n\n// src/response-handler.ts\nimport { APICallError as APICallError4, EmptyResponseBodyError } from \"@ai-sdk/provider\";\nvar createJsonErrorResponseHandler = ({\n errorSchema,\n errorToMessage,\n isRetryable\n}) => async ({ response, url, requestBodyValues }) => {\n const responseBody = await response.text();\n const responseHeaders = extractResponseHeaders(response);\n if (responseBody.trim() === \"\") {\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n })\n };\n }\n try {\n const parsedError = await parseJSON({\n text: responseBody,\n schema: errorSchema\n });\n return {\n responseHeaders,\n value: new APICallError4({\n message: errorToMessage(parsedError),\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n data: parsedError,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)\n })\n };\n } catch (parseError) {\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n })\n };\n }\n};\nvar createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {\n const responseHeaders = extractResponseHeaders(response);\n if (response.body == null) {\n throw new EmptyResponseBodyError({});\n }\n return {\n responseHeaders,\n value: parseJsonEventStream({\n stream: response.body,\n schema: chunkSchema\n })\n };\n};\nvar createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {\n const responseBody = await response.text();\n const parsedResult = await safeParseJSON({\n text: responseBody,\n schema: responseSchema\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!parsedResult.success) {\n throw new APICallError4({\n message: \"Invalid JSON response\",\n cause: parsedResult.error,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n url,\n requestBodyValues\n });\n }\n return {\n responseHeaders,\n value: parsedResult.value,\n rawValue: parsedResult.rawValue\n };\n};\nvar createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n const responseHeaders = extractResponseHeaders(response);\n if (!response.body) {\n throw new APICallError4({\n message: \"Response body is empty\",\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody: void 0\n });\n }\n try {\n const buffer = await response.arrayBuffer();\n return {\n responseHeaders,\n value: new Uint8Array(buffer)\n };\n } catch (error) {\n throw new APICallError4({\n message: \"Failed to read response as array buffer\",\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody: void 0,\n cause: error\n });\n }\n};\nvar createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n const responseHeaders = extractResponseHeaders(response);\n const responseBody = await response.text();\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody\n })\n };\n};\n\n// src/without-trailing-slash.ts\nfunction withoutTrailingSlash(url) {\n return url == null ? void 0 : url.replace(/\\/$/, \"\");\n}\n\n// src/is-async-iterable.ts\nfunction isAsyncIterable(obj) {\n return obj != null && typeof obj[Symbol.asyncIterator] === \"function\";\n}\n\n// src/types/execute-tool.ts\nasync function* executeTool({\n execute,\n input,\n options\n}) {\n const result = execute(input, options);\n if (isAsyncIterable(result)) {\n let lastOutput;\n for await (const output of result) {\n lastOutput = output;\n yield { type: \"preliminary\", output };\n }\n yield { type: \"final\", output: lastOutput };\n } else {\n yield { type: \"final\", output: await result };\n }\n}\n\n// src/index.ts\nimport {\n EventSourceParserStream as EventSourceParserStream2\n} from \"eventsource-parser/stream\";\nexport {\n DelayedPromise,\n DownloadError,\n EventSourceParserStream2 as EventSourceParserStream,\n VERSION,\n asSchema,\n combineHeaders,\n convertAsyncIteratorToReadableStream,\n convertBase64ToUint8Array,\n convertImageModelFileToDataUri,\n convertToBase64,\n convertToFormData,\n convertUint8ArrayToBase64,\n createBinaryResponseHandler,\n createEventSourceResponseHandler,\n createIdGenerator,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n createProviderToolFactory,\n createProviderToolFactoryWithOutputSchema,\n createStatusCodeErrorResponseHandler,\n createToolNameMapping,\n delay,\n downloadBlob,\n dynamicTool,\n executeTool,\n extractResponseHeaders,\n generateId,\n getErrorMessage,\n getFromApi,\n getRuntimeEnvironmentUserAgent,\n injectJsonInstructionIntoMessages,\n isAbortError,\n isNonNullable,\n isParsableJson,\n isUrlSupported,\n jsonSchema,\n lazySchema,\n loadApiKey,\n loadOptionalSetting,\n loadSetting,\n mediaTypeToExtension,\n normalizeHeaders,\n parseJSON,\n parseJsonEventStream,\n parseProviderOptions,\n postFormDataToApi,\n postJsonToApi,\n postToApi,\n removeUndefinedEntries,\n resolve,\n safeParseJSON,\n safeValidateTypes,\n tool,\n validateTypes,\n withUserAgentSuffix,\n withoutTrailingSlash,\n zodSchema\n};\n//# sourceMappingURL=index.mjs.map","// src/anthropic-provider.ts\nimport {\n InvalidArgumentError,\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId as generateId2,\n loadApiKey,\n loadOptionalSetting,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/version.ts\nvar VERSION = true ? \"3.0.34\" : \"0.0.0-test\";\n\n// src/anthropic-messages-language-model.ts\nimport {\n APICallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n createToolNameMapping,\n generateId,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi,\n resolve\n} from \"@ai-sdk/provider-utils\";\n\n// src/anthropic-error.ts\nimport {\n createJsonErrorResponseHandler,\n lazySchema,\n zodSchema\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\nvar anthropicErrorDataSchema = lazySchema(\n () => zodSchema(\n z.object({\n type: z.literal(\"error\"),\n error: z.object({\n type: z.string(),\n message: z.string()\n })\n })\n )\n);\nvar anthropicFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: anthropicErrorDataSchema,\n errorToMessage: (data) => data.error.message\n});\n\n// src/anthropic-messages-api.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar anthropicMessagesResponseSchema = lazySchema2(\n () => zodSchema2(\n z2.object({\n type: z2.literal(\"message\"),\n id: z2.string().nullish(),\n model: z2.string().nullish(),\n content: z2.array(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text\"),\n text: z2.string(),\n citations: z2.array(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"web_search_result_location\"),\n cited_text: z2.string(),\n url: z2.string(),\n title: z2.string(),\n encrypted_index: z2.string()\n }),\n z2.object({\n type: z2.literal(\"page_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_page_number: z2.number(),\n end_page_number: z2.number()\n }),\n z2.object({\n type: z2.literal(\"char_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_char_index: z2.number(),\n end_char_index: z2.number()\n })\n ])\n ).optional()\n }),\n z2.object({\n type: z2.literal(\"thinking\"),\n thinking: z2.string(),\n signature: z2.string()\n }),\n z2.object({\n type: z2.literal(\"redacted_thinking\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n // Programmatic tool calling: caller info when triggered from code execution\n caller: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_20250825\"),\n tool_id: z2.string()\n }),\n z2.object({\n type: z2.literal(\"direct\")\n })\n ]).optional()\n }),\n z2.object({\n type: z2.literal(\"server_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.record(z2.string(), z2.unknown()).nullish()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n server_name: z2.string()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_result\"),\n tool_use_id: z2.string(),\n is_error: z2.boolean(),\n content: z2.array(\n z2.union([\n z2.string(),\n z2.object({ type: z2.literal(\"text\"), text: z2.string() })\n ])\n )\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"web_fetch_result\"),\n url: z2.string(),\n retrieved_at: z2.string(),\n content: z2.object({\n type: z2.literal(\"document\"),\n title: z2.string().nullable(),\n citations: z2.object({ enabled: z2.boolean() }).optional(),\n source: z2.union([\n z2.object({\n type: z2.literal(\"base64\"),\n media_type: z2.literal(\"application/pdf\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text\"),\n media_type: z2.literal(\"text/plain\"),\n data: z2.string()\n })\n ])\n })\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"web_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.array(\n z2.object({\n type: z2.literal(\"web_search_result\"),\n url: z2.string(),\n title: z2.string(),\n encrypted_content: z2.string(),\n page_age: z2.string().nullish()\n })\n ),\n z2.object({\n type: z2.literal(\"web_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // code execution results for code_execution_20250522 tool:\n z2.object({\n type: z2.literal(\"code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_result\"),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number(),\n content: z2.array(\n z2.object({\n type: z2.literal(\"code_execution_output\"),\n file_id: z2.string()\n })\n ).optional().default([])\n }),\n z2.object({\n type: z2.literal(\"code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // bash code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"bash_code_execution_result\"),\n content: z2.array(\n z2.object({\n type: z2.literal(\"bash_code_execution_output\"),\n file_id: z2.string()\n })\n ),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number()\n }),\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // text editor code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result_error\"),\n error_code: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_view_result\"),\n content: z2.string(),\n file_type: z2.string(),\n num_lines: z2.number().nullable(),\n start_line: z2.number().nullable(),\n total_lines: z2.number().nullable()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_create_result\"),\n is_file_update: z2.boolean()\n }),\n z2.object({\n type: z2.literal(\n \"text_editor_code_execution_str_replace_result\"\n ),\n lines: z2.array(z2.string()).nullable(),\n new_lines: z2.number().nullable(),\n new_start: z2.number().nullable(),\n old_lines: z2.number().nullable(),\n old_start: z2.number().nullable()\n })\n ])\n }),\n // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119:\n z2.object({\n type: z2.literal(\"tool_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"tool_search_tool_search_result\"),\n tool_references: z2.array(\n z2.object({\n type: z2.literal(\"tool_reference\"),\n tool_name: z2.string()\n })\n )\n }),\n z2.object({\n type: z2.literal(\"tool_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n })\n ])\n ),\n stop_reason: z2.string().nullish(),\n stop_sequence: z2.string().nullish(),\n usage: z2.looseObject({\n input_tokens: z2.number(),\n output_tokens: z2.number(),\n cache_creation_input_tokens: z2.number().nullish(),\n cache_read_input_tokens: z2.number().nullish()\n }),\n container: z2.object({\n expires_at: z2.string(),\n id: z2.string(),\n skills: z2.array(\n z2.object({\n type: z2.union([z2.literal(\"anthropic\"), z2.literal(\"custom\")]),\n skill_id: z2.string(),\n version: z2.string()\n })\n ).nullish()\n }).nullish(),\n context_management: z2.object({\n applied_edits: z2.array(\n z2.union([\n z2.object({\n type: z2.literal(\"clear_tool_uses_20250919\"),\n cleared_tool_uses: z2.number(),\n cleared_input_tokens: z2.number()\n }),\n z2.object({\n type: z2.literal(\"clear_thinking_20251015\"),\n cleared_thinking_turns: z2.number(),\n cleared_input_tokens: z2.number()\n })\n ])\n )\n }).nullish()\n })\n )\n);\nvar anthropicMessagesChunkSchema = lazySchema2(\n () => zodSchema2(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"message_start\"),\n message: z2.object({\n id: z2.string().nullish(),\n model: z2.string().nullish(),\n role: z2.string().nullish(),\n usage: z2.looseObject({\n input_tokens: z2.number(),\n cache_creation_input_tokens: z2.number().nullish(),\n cache_read_input_tokens: z2.number().nullish()\n }),\n // Programmatic tool calling: content may be pre-populated for deferred tool calls\n content: z2.array(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n caller: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_20250825\"),\n tool_id: z2.string()\n }),\n z2.object({\n type: z2.literal(\"direct\")\n })\n ]).optional()\n })\n ])\n ).nullish(),\n stop_reason: z2.string().nullish(),\n container: z2.object({\n expires_at: z2.string(),\n id: z2.string()\n }).nullish()\n })\n }),\n z2.object({\n type: z2.literal(\"content_block_start\"),\n index: z2.number(),\n content_block: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text\"),\n text: z2.string()\n }),\n z2.object({\n type: z2.literal(\"thinking\"),\n thinking: z2.string()\n }),\n z2.object({\n type: z2.literal(\"tool_use\"),\n id: z2.string(),\n name: z2.string(),\n // Programmatic tool calling: input may be present directly for deferred tool calls\n input: z2.record(z2.string(), z2.unknown()).optional(),\n // Programmatic tool calling: caller info when triggered from code execution\n caller: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_20250825\"),\n tool_id: z2.string()\n }),\n z2.object({\n type: z2.literal(\"direct\")\n })\n ]).optional()\n }),\n z2.object({\n type: z2.literal(\"redacted_thinking\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"server_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.record(z2.string(), z2.unknown()).nullish()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n server_name: z2.string()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_result\"),\n tool_use_id: z2.string(),\n is_error: z2.boolean(),\n content: z2.array(\n z2.union([\n z2.string(),\n z2.object({ type: z2.literal(\"text\"), text: z2.string() })\n ])\n )\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"web_fetch_result\"),\n url: z2.string(),\n retrieved_at: z2.string(),\n content: z2.object({\n type: z2.literal(\"document\"),\n title: z2.string().nullable(),\n citations: z2.object({ enabled: z2.boolean() }).optional(),\n source: z2.union([\n z2.object({\n type: z2.literal(\"base64\"),\n media_type: z2.literal(\"application/pdf\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text\"),\n media_type: z2.literal(\"text/plain\"),\n data: z2.string()\n })\n ])\n })\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"web_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.array(\n z2.object({\n type: z2.literal(\"web_search_result\"),\n url: z2.string(),\n title: z2.string(),\n encrypted_content: z2.string(),\n page_age: z2.string().nullish()\n })\n ),\n z2.object({\n type: z2.literal(\"web_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // code execution results for code_execution_20250522 tool:\n z2.object({\n type: z2.literal(\"code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_result\"),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number(),\n content: z2.array(\n z2.object({\n type: z2.literal(\"code_execution_output\"),\n file_id: z2.string()\n })\n ).optional().default([])\n }),\n z2.object({\n type: z2.literal(\"code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // bash code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"bash_code_execution_result\"),\n content: z2.array(\n z2.object({\n type: z2.literal(\"bash_code_execution_output\"),\n file_id: z2.string()\n })\n ),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number()\n }),\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // text editor code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result_error\"),\n error_code: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_view_result\"),\n content: z2.string(),\n file_type: z2.string(),\n num_lines: z2.number().nullable(),\n start_line: z2.number().nullable(),\n total_lines: z2.number().nullable()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_create_result\"),\n is_file_update: z2.boolean()\n }),\n z2.object({\n type: z2.literal(\n \"text_editor_code_execution_str_replace_result\"\n ),\n lines: z2.array(z2.string()).nullable(),\n new_lines: z2.number().nullable(),\n new_start: z2.number().nullable(),\n old_lines: z2.number().nullable(),\n old_start: z2.number().nullable()\n })\n ])\n }),\n // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119:\n z2.object({\n type: z2.literal(\"tool_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"tool_search_tool_search_result\"),\n tool_references: z2.array(\n z2.object({\n type: z2.literal(\"tool_reference\"),\n tool_name: z2.string()\n })\n )\n }),\n z2.object({\n type: z2.literal(\"tool_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"content_block_delta\"),\n index: z2.number(),\n delta: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"input_json_delta\"),\n partial_json: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text_delta\"),\n text: z2.string()\n }),\n z2.object({\n type: z2.literal(\"thinking_delta\"),\n thinking: z2.string()\n }),\n z2.object({\n type: z2.literal(\"signature_delta\"),\n signature: z2.string()\n }),\n z2.object({\n type: z2.literal(\"citations_delta\"),\n citation: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"web_search_result_location\"),\n cited_text: z2.string(),\n url: z2.string(),\n title: z2.string(),\n encrypted_index: z2.string()\n }),\n z2.object({\n type: z2.literal(\"page_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_page_number: z2.number(),\n end_page_number: z2.number()\n }),\n z2.object({\n type: z2.literal(\"char_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_char_index: z2.number(),\n end_char_index: z2.number()\n })\n ])\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"content_block_stop\"),\n index: z2.number()\n }),\n z2.object({\n type: z2.literal(\"error\"),\n error: z2.object({\n type: z2.string(),\n message: z2.string()\n })\n }),\n z2.object({\n type: z2.literal(\"message_delta\"),\n delta: z2.object({\n stop_reason: z2.string().nullish(),\n stop_sequence: z2.string().nullish(),\n container: z2.object({\n expires_at: z2.string(),\n id: z2.string(),\n skills: z2.array(\n z2.object({\n type: z2.union([\n z2.literal(\"anthropic\"),\n z2.literal(\"custom\")\n ]),\n skill_id: z2.string(),\n version: z2.string()\n })\n ).nullish()\n }).nullish()\n }),\n usage: z2.looseObject({\n input_tokens: z2.number().nullish(),\n output_tokens: z2.number(),\n cache_creation_input_tokens: z2.number().nullish(),\n cache_read_input_tokens: z2.number().nullish()\n }),\n context_management: z2.object({\n applied_edits: z2.array(\n z2.union([\n z2.object({\n type: z2.literal(\"clear_tool_uses_20250919\"),\n cleared_tool_uses: z2.number(),\n cleared_input_tokens: z2.number()\n }),\n z2.object({\n type: z2.literal(\"clear_thinking_20251015\"),\n cleared_thinking_turns: z2.number(),\n cleared_input_tokens: z2.number()\n })\n ])\n )\n }).nullish()\n }),\n z2.object({\n type: z2.literal(\"message_stop\")\n }),\n z2.object({\n type: z2.literal(\"ping\")\n })\n ])\n )\n);\nvar anthropicReasoningMetadataSchema = lazySchema2(\n () => zodSchema2(\n z2.object({\n signature: z2.string().optional(),\n redactedData: z2.string().optional()\n })\n )\n);\n\n// src/anthropic-messages-options.ts\nimport { z as z3 } from \"zod/v4\";\nvar anthropicFilePartProviderOptions = z3.object({\n /**\n * Citation configuration for this document.\n * When enabled, this document will generate citations in the response.\n */\n citations: z3.object({\n /**\n * Enable citations for this document\n */\n enabled: z3.boolean()\n }).optional(),\n /**\n * Custom title for the document.\n * If not provided, the filename will be used.\n */\n title: z3.string().optional(),\n /**\n * Context about the document that will be passed to the model\n * but not used towards cited content.\n * Useful for storing document metadata as text or stringified JSON.\n */\n context: z3.string().optional()\n});\nvar anthropicProviderOptions = z3.object({\n /**\n * Whether to send reasoning to the model.\n *\n * This allows you to deactivate reasoning inputs for models that do not support them.\n */\n sendReasoning: z3.boolean().optional(),\n /**\n * Determines how structured outputs are generated.\n *\n * - `outputFormat`: Use the `output_format` parameter to specify the structured output format.\n * - `jsonTool`: Use a special 'json' tool to specify the structured output format.\n * - `auto`: Use 'outputFormat' when supported, otherwise use 'jsonTool' (default).\n */\n structuredOutputMode: z3.enum([\"outputFormat\", \"jsonTool\", \"auto\"]).optional(),\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include thinking content blocks showing Claude's thinking process before the final answer.\n * Requires a minimum budget of 1,024 tokens and counts towards the `max_tokens` limit.\n */\n thinking: z3.object({\n type: z3.union([z3.literal(\"enabled\"), z3.literal(\"disabled\")]),\n budgetTokens: z3.number().optional()\n }).optional(),\n /**\n * Whether to disable parallel function calling during tool use. Default is false.\n * When set to true, Claude will use at most one tool per response.\n */\n disableParallelToolUse: z3.boolean().optional(),\n /**\n * Cache control settings for this message.\n * See https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n cacheControl: z3.object({\n type: z3.literal(\"ephemeral\"),\n ttl: z3.union([z3.literal(\"5m\"), z3.literal(\"1h\")]).optional()\n }).optional(),\n /**\n * MCP servers to be utilized in this request.\n */\n mcpServers: z3.array(\n z3.object({\n type: z3.literal(\"url\"),\n name: z3.string(),\n url: z3.string(),\n authorizationToken: z3.string().nullish(),\n toolConfiguration: z3.object({\n enabled: z3.boolean().nullish(),\n allowedTools: z3.array(z3.string()).nullish()\n }).nullish()\n })\n ).optional(),\n /**\n * Agent Skills configuration. Skills enable Claude to perform specialized tasks\n * like document processing (PPTX, DOCX, PDF, XLSX) and data analysis.\n * Requires code execution tool to be enabled.\n */\n container: z3.object({\n id: z3.string().optional(),\n skills: z3.array(\n z3.object({\n type: z3.union([z3.literal(\"anthropic\"), z3.literal(\"custom\")]),\n skillId: z3.string(),\n version: z3.string().optional()\n })\n ).optional()\n }).optional(),\n /**\n * Whether to enable tool streaming (and structured output streaming).\n *\n * When set to false, the model will return all tool calls and results\n * at once after a delay.\n *\n * @default true\n */\n toolStreaming: z3.boolean().optional(),\n /**\n * @default 'high'\n */\n effort: z3.enum([\"low\", \"medium\", \"high\"]).optional(),\n contextManagement: z3.object({\n edits: z3.array(\n z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"clear_tool_uses_20250919\"),\n trigger: z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"input_tokens\"),\n value: z3.number()\n }),\n z3.object({\n type: z3.literal(\"tool_uses\"),\n value: z3.number()\n })\n ]).optional(),\n keep: z3.object({\n type: z3.literal(\"tool_uses\"),\n value: z3.number()\n }).optional(),\n clearAtLeast: z3.object({\n type: z3.literal(\"input_tokens\"),\n value: z3.number()\n }).optional(),\n clearToolInputs: z3.boolean().optional(),\n excludeTools: z3.array(z3.string()).optional()\n }),\n z3.object({\n type: z3.literal(\"clear_thinking_20251015\"),\n keep: z3.union([\n z3.literal(\"all\"),\n z3.object({\n type: z3.literal(\"thinking_turns\"),\n value: z3.number()\n })\n ]).optional()\n })\n ])\n )\n }).optional()\n});\n\n// src/anthropic-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\n\n// src/get-cache-control.ts\nvar MAX_CACHE_BREAKPOINTS = 4;\nfunction getCacheControl(providerMetadata) {\n var _a;\n const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;\n const cacheControlValue = (_a = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a : anthropic2 == null ? void 0 : anthropic2.cache_control;\n return cacheControlValue;\n}\nvar CacheControlValidator = class {\n constructor() {\n this.breakpointCount = 0;\n this.warnings = [];\n }\n getCacheControl(providerMetadata, context) {\n const cacheControlValue = getCacheControl(providerMetadata);\n if (!cacheControlValue) {\n return void 0;\n }\n if (!context.canCache) {\n this.warnings.push({\n type: \"unsupported\",\n feature: \"cache_control on non-cacheable context\",\n details: `cache_control cannot be set on ${context.type}. It will be ignored.`\n });\n return void 0;\n }\n this.breakpointCount++;\n if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) {\n this.warnings.push({\n type: \"unsupported\",\n feature: \"cacheControl breakpoint limit\",\n details: `Maximum ${MAX_CACHE_BREAKPOINTS} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`\n });\n return void 0;\n }\n return cacheControlValue;\n }\n getWarnings() {\n return this.warnings;\n }\n};\n\n// src/tool/text-editor_20250728.ts\nimport { createProviderToolFactory } from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nimport { lazySchema as lazySchema3, zodSchema as zodSchema3 } from \"@ai-sdk/provider-utils\";\nvar textEditor_20250728ArgsSchema = lazySchema3(\n () => zodSchema3(\n z4.object({\n maxCharacters: z4.number().optional()\n })\n )\n);\nvar textEditor_20250728InputSchema = lazySchema3(\n () => zodSchema3(\n z4.object({\n command: z4.enum([\"view\", \"create\", \"str_replace\", \"insert\"]),\n path: z4.string(),\n file_text: z4.string().optional(),\n insert_line: z4.number().int().optional(),\n new_str: z4.string().optional(),\n insert_text: z4.string().optional(),\n old_str: z4.string().optional(),\n view_range: z4.array(z4.number().int()).optional()\n })\n )\n);\nvar factory = createProviderToolFactory({\n id: \"anthropic.text_editor_20250728\",\n inputSchema: textEditor_20250728InputSchema\n});\nvar textEditor_20250728 = (args = {}) => {\n return factory(args);\n};\n\n// src/tool/web-search_20250305.ts\nimport {\n createProviderToolFactoryWithOutputSchema,\n lazySchema as lazySchema4,\n zodSchema as zodSchema4\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\nvar webSearch_20250305ArgsSchema = lazySchema4(\n () => zodSchema4(\n z5.object({\n maxUses: z5.number().optional(),\n allowedDomains: z5.array(z5.string()).optional(),\n blockedDomains: z5.array(z5.string()).optional(),\n userLocation: z5.object({\n type: z5.literal(\"approximate\"),\n city: z5.string().optional(),\n region: z5.string().optional(),\n country: z5.string().optional(),\n timezone: z5.string().optional()\n }).optional()\n })\n )\n);\nvar webSearch_20250305OutputSchema = lazySchema4(\n () => zodSchema4(\n z5.array(\n z5.object({\n url: z5.string(),\n title: z5.string().nullable(),\n pageAge: z5.string().nullable(),\n encryptedContent: z5.string(),\n type: z5.literal(\"web_search_result\")\n })\n )\n )\n);\nvar webSearch_20250305InputSchema = lazySchema4(\n () => zodSchema4(\n z5.object({\n query: z5.string()\n })\n )\n);\nvar factory2 = createProviderToolFactoryWithOutputSchema({\n id: \"anthropic.web_search_20250305\",\n inputSchema: webSearch_20250305InputSchema,\n outputSchema: webSearch_20250305OutputSchema,\n supportsDeferredResults: true\n});\nvar webSearch_20250305 = (args = {}) => {\n return factory2(args);\n};\n\n// src/tool/web-fetch-20250910.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema2,\n lazySchema as lazySchema5,\n zodSchema as zodSchema5\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar webFetch_20250910ArgsSchema = lazySchema5(\n () => zodSchema5(\n z6.object({\n maxUses: z6.number().optional(),\n allowedDomains: z6.array(z6.string()).optional(),\n blockedDomains: z6.array(z6.string()).optional(),\n citations: z6.object({ enabled: z6.boolean() }).optional(),\n maxContentTokens: z6.number().optional()\n })\n )\n);\nvar webFetch_20250910OutputSchema = lazySchema5(\n () => zodSchema5(\n z6.object({\n type: z6.literal(\"web_fetch_result\"),\n url: z6.string(),\n content: z6.object({\n type: z6.literal(\"document\"),\n title: z6.string().nullable(),\n citations: z6.object({ enabled: z6.boolean() }).optional(),\n source: z6.union([\n z6.object({\n type: z6.literal(\"base64\"),\n mediaType: z6.literal(\"application/pdf\"),\n data: z6.string()\n }),\n z6.object({\n type: z6.literal(\"text\"),\n mediaType: z6.literal(\"text/plain\"),\n data: z6.string()\n })\n ])\n }),\n retrievedAt: z6.string().nullable()\n })\n )\n);\nvar webFetch_20250910InputSchema = lazySchema5(\n () => zodSchema5(\n z6.object({\n url: z6.string()\n })\n )\n);\nvar factory3 = createProviderToolFactoryWithOutputSchema2({\n id: \"anthropic.web_fetch_20250910\",\n inputSchema: webFetch_20250910InputSchema,\n outputSchema: webFetch_20250910OutputSchema,\n supportsDeferredResults: true\n});\nvar webFetch_20250910 = (args = {}) => {\n return factory3(args);\n};\n\n// src/anthropic-prepare-tools.ts\nimport { validateTypes } from \"@ai-sdk/provider-utils\";\nasync function prepareTools({\n tools,\n toolChoice,\n disableParallelToolUse,\n cacheControlValidator,\n supportsStructuredOutput\n}) {\n var _a;\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n const betas = /* @__PURE__ */ new Set();\n const validator = cacheControlValidator || new CacheControlValidator();\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings, betas };\n }\n const anthropicTools2 = [];\n for (const tool of tools) {\n switch (tool.type) {\n case \"function\": {\n const cacheControl = validator.getCacheControl(tool.providerOptions, {\n type: \"tool definition\",\n canCache: true\n });\n const anthropicOptions = (_a = tool.providerOptions) == null ? void 0 : _a.anthropic;\n const deferLoading = anthropicOptions == null ? void 0 : anthropicOptions.deferLoading;\n const allowedCallers = anthropicOptions == null ? void 0 : anthropicOptions.allowedCallers;\n anthropicTools2.push({\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n cache_control: cacheControl,\n ...supportsStructuredOutput === true && tool.strict != null ? { strict: tool.strict } : {},\n ...deferLoading != null ? { defer_loading: deferLoading } : {},\n ...allowedCallers != null ? { allowed_callers: allowedCallers } : {},\n ...tool.inputExamples != null ? {\n input_examples: tool.inputExamples.map(\n (example) => example.input\n )\n } : {}\n });\n if (supportsStructuredOutput === true) {\n betas.add(\"structured-outputs-2025-11-13\");\n }\n if (tool.inputExamples != null || allowedCallers != null) {\n betas.add(\"advanced-tool-use-2025-11-20\");\n }\n break;\n }\n case \"provider\": {\n switch (tool.id) {\n case \"anthropic.code_execution_20250522\": {\n betas.add(\"code-execution-2025-05-22\");\n anthropicTools2.push({\n type: \"code_execution_20250522\",\n name: \"code_execution\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.code_execution_20250825\": {\n betas.add(\"code-execution-2025-08-25\");\n anthropicTools2.push({\n type: \"code_execution_20250825\",\n name: \"code_execution\"\n });\n break;\n }\n case \"anthropic.computer_20250124\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"computer\",\n type: \"computer_20250124\",\n display_width_px: tool.args.displayWidthPx,\n display_height_px: tool.args.displayHeightPx,\n display_number: tool.args.displayNumber,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.computer_20251124\": {\n betas.add(\"computer-use-2025-11-24\");\n anthropicTools2.push({\n name: \"computer\",\n type: \"computer_20251124\",\n display_width_px: tool.args.displayWidthPx,\n display_height_px: tool.args.displayHeightPx,\n display_number: tool.args.displayNumber,\n enable_zoom: tool.args.enableZoom,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.computer_20241022\": {\n betas.add(\"computer-use-2024-10-22\");\n anthropicTools2.push({\n name: \"computer\",\n type: \"computer_20241022\",\n display_width_px: tool.args.displayWidthPx,\n display_height_px: tool.args.displayHeightPx,\n display_number: tool.args.displayNumber,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20250124\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"str_replace_editor\",\n type: \"text_editor_20250124\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20241022\": {\n betas.add(\"computer-use-2024-10-22\");\n anthropicTools2.push({\n name: \"str_replace_editor\",\n type: \"text_editor_20241022\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20250429\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"str_replace_based_edit_tool\",\n type: \"text_editor_20250429\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20250728\": {\n const args = await validateTypes({\n value: tool.args,\n schema: textEditor_20250728ArgsSchema\n });\n anthropicTools2.push({\n name: \"str_replace_based_edit_tool\",\n type: \"text_editor_20250728\",\n max_characters: args.maxCharacters,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.bash_20250124\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"bash\",\n type: \"bash_20250124\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.bash_20241022\": {\n betas.add(\"computer-use-2024-10-22\");\n anthropicTools2.push({\n name: \"bash\",\n type: \"bash_20241022\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.memory_20250818\": {\n betas.add(\"context-management-2025-06-27\");\n anthropicTools2.push({\n name: \"memory\",\n type: \"memory_20250818\"\n });\n break;\n }\n case \"anthropic.web_fetch_20250910\": {\n betas.add(\"web-fetch-2025-09-10\");\n const args = await validateTypes({\n value: tool.args,\n schema: webFetch_20250910ArgsSchema\n });\n anthropicTools2.push({\n type: \"web_fetch_20250910\",\n name: \"web_fetch\",\n max_uses: args.maxUses,\n allowed_domains: args.allowedDomains,\n blocked_domains: args.blockedDomains,\n citations: args.citations,\n max_content_tokens: args.maxContentTokens,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.web_search_20250305\": {\n const args = await validateTypes({\n value: tool.args,\n schema: webSearch_20250305ArgsSchema\n });\n anthropicTools2.push({\n type: \"web_search_20250305\",\n name: \"web_search\",\n max_uses: args.maxUses,\n allowed_domains: args.allowedDomains,\n blocked_domains: args.blockedDomains,\n user_location: args.userLocation,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.tool_search_regex_20251119\": {\n betas.add(\"advanced-tool-use-2025-11-20\");\n anthropicTools2.push({\n type: \"tool_search_tool_regex_20251119\",\n name: \"tool_search_tool_regex\"\n });\n break;\n }\n case \"anthropic.tool_search_bm25_20251119\": {\n betas.add(\"advanced-tool-use-2025-11-20\");\n anthropicTools2.push({\n type: \"tool_search_tool_bm25_20251119\",\n name: \"tool_search_tool_bm25\"\n });\n break;\n }\n default: {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n break;\n }\n }\n break;\n }\n default: {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `tool ${tool}`\n });\n break;\n }\n }\n }\n if (toolChoice == null) {\n return {\n tools: anthropicTools2,\n toolChoice: disableParallelToolUse ? { type: \"auto\", disable_parallel_tool_use: disableParallelToolUse } : void 0,\n toolWarnings,\n betas\n };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n return {\n tools: anthropicTools2,\n toolChoice: {\n type: \"auto\",\n disable_parallel_tool_use: disableParallelToolUse\n },\n toolWarnings,\n betas\n };\n case \"required\":\n return {\n tools: anthropicTools2,\n toolChoice: {\n type: \"any\",\n disable_parallel_tool_use: disableParallelToolUse\n },\n toolWarnings,\n betas\n };\n case \"none\":\n return { tools: void 0, toolChoice: void 0, toolWarnings, betas };\n case \"tool\":\n return {\n tools: anthropicTools2,\n toolChoice: {\n type: \"tool\",\n name: toolChoice.toolName,\n disable_parallel_tool_use: disableParallelToolUse\n },\n toolWarnings,\n betas\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/convert-anthropic-messages-usage.ts\nfunction convertAnthropicMessagesUsage(usage) {\n var _a, _b;\n const inputTokens = usage.input_tokens;\n const outputTokens = usage.output_tokens;\n const cacheCreationTokens = (_a = usage.cache_creation_input_tokens) != null ? _a : 0;\n const cacheReadTokens = (_b = usage.cache_read_input_tokens) != null ? _b : 0;\n return {\n inputTokens: {\n total: inputTokens + cacheCreationTokens + cacheReadTokens,\n noCache: inputTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: cacheCreationTokens\n },\n outputTokens: {\n total: outputTokens,\n text: void 0,\n reasoning: void 0\n },\n raw: usage\n };\n}\n\n// src/convert-to-anthropic-messages-prompt.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nimport {\n convertToBase64,\n parseProviderOptions,\n validateTypes as validateTypes2,\n isNonNullable\n} from \"@ai-sdk/provider-utils\";\n\n// src/tool/code-execution_20250522.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema3,\n lazySchema as lazySchema6,\n zodSchema as zodSchema6\n} from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar codeExecution_20250522OutputSchema = lazySchema6(\n () => zodSchema6(\n z7.object({\n type: z7.literal(\"code_execution_result\"),\n stdout: z7.string(),\n stderr: z7.string(),\n return_code: z7.number(),\n content: z7.array(\n z7.object({\n type: z7.literal(\"code_execution_output\"),\n file_id: z7.string()\n })\n ).optional().default([])\n })\n )\n);\nvar codeExecution_20250522InputSchema = lazySchema6(\n () => zodSchema6(\n z7.object({\n code: z7.string()\n })\n )\n);\nvar factory4 = createProviderToolFactoryWithOutputSchema3({\n id: \"anthropic.code_execution_20250522\",\n inputSchema: codeExecution_20250522InputSchema,\n outputSchema: codeExecution_20250522OutputSchema\n});\nvar codeExecution_20250522 = (args = {}) => {\n return factory4(args);\n};\n\n// src/tool/code-execution_20250825.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema4,\n lazySchema as lazySchema7,\n zodSchema as zodSchema7\n} from \"@ai-sdk/provider-utils\";\nimport { z as z8 } from \"zod/v4\";\nvar codeExecution_20250825OutputSchema = lazySchema7(\n () => zodSchema7(\n z8.discriminatedUnion(\"type\", [\n z8.object({\n type: z8.literal(\"code_execution_result\"),\n stdout: z8.string(),\n stderr: z8.string(),\n return_code: z8.number(),\n content: z8.array(\n z8.object({\n type: z8.literal(\"code_execution_output\"),\n file_id: z8.string()\n })\n ).optional().default([])\n }),\n z8.object({\n type: z8.literal(\"bash_code_execution_result\"),\n content: z8.array(\n z8.object({\n type: z8.literal(\"bash_code_execution_output\"),\n file_id: z8.string()\n })\n ),\n stdout: z8.string(),\n stderr: z8.string(),\n return_code: z8.number()\n }),\n z8.object({\n type: z8.literal(\"bash_code_execution_tool_result_error\"),\n error_code: z8.string()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_tool_result_error\"),\n error_code: z8.string()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_view_result\"),\n content: z8.string(),\n file_type: z8.string(),\n num_lines: z8.number().nullable(),\n start_line: z8.number().nullable(),\n total_lines: z8.number().nullable()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_create_result\"),\n is_file_update: z8.boolean()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_str_replace_result\"),\n lines: z8.array(z8.string()).nullable(),\n new_lines: z8.number().nullable(),\n new_start: z8.number().nullable(),\n old_lines: z8.number().nullable(),\n old_start: z8.number().nullable()\n })\n ])\n )\n);\nvar codeExecution_20250825InputSchema = lazySchema7(\n () => zodSchema7(\n z8.discriminatedUnion(\"type\", [\n // Programmatic tool calling format (mapped from { code } by AI SDK)\n z8.object({\n type: z8.literal(\"programmatic-tool-call\"),\n code: z8.string()\n }),\n z8.object({\n type: z8.literal(\"bash_code_execution\"),\n command: z8.string()\n }),\n z8.discriminatedUnion(\"command\", [\n z8.object({\n type: z8.literal(\"text_editor_code_execution\"),\n command: z8.literal(\"view\"),\n path: z8.string()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution\"),\n command: z8.literal(\"create\"),\n path: z8.string(),\n file_text: z8.string().nullish()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution\"),\n command: z8.literal(\"str_replace\"),\n path: z8.string(),\n old_str: z8.string(),\n new_str: z8.string()\n })\n ])\n ])\n )\n);\nvar factory5 = createProviderToolFactoryWithOutputSchema4({\n id: \"anthropic.code_execution_20250825\",\n inputSchema: codeExecution_20250825InputSchema,\n outputSchema: codeExecution_20250825OutputSchema,\n // Programmatic tool calling: tool results may be deferred to a later turn\n // when code execution triggers a client-executed tool that needs to be\n // resolved before the code execution result can be returned.\n supportsDeferredResults: true\n});\nvar codeExecution_20250825 = (args = {}) => {\n return factory5(args);\n};\n\n// src/tool/tool-search-regex_20251119.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema5,\n lazySchema as lazySchema8,\n zodSchema as zodSchema8\n} from \"@ai-sdk/provider-utils\";\nimport { z as z9 } from \"zod/v4\";\nvar toolSearchRegex_20251119OutputSchema = lazySchema8(\n () => zodSchema8(\n z9.array(\n z9.object({\n type: z9.literal(\"tool_reference\"),\n toolName: z9.string()\n })\n )\n )\n);\nvar toolSearchRegex_20251119InputSchema = lazySchema8(\n () => zodSchema8(\n z9.object({\n /**\n * A regex pattern to search for tools.\n * Uses Python re.search() syntax. Maximum 200 characters.\n *\n * Examples:\n * - \"weather\" - matches tool names/descriptions containing \"weather\"\n * - \"get_.*_data\" - matches tools like get_user_data, get_weather_data\n * - \"database.*query|query.*database\" - OR patterns for flexibility\n * - \"(?i)slack\" - case-insensitive search\n */\n pattern: z9.string(),\n /**\n * Maximum number of tools to return. Optional.\n */\n limit: z9.number().optional()\n })\n )\n);\nvar factory6 = createProviderToolFactoryWithOutputSchema5({\n id: \"anthropic.tool_search_regex_20251119\",\n inputSchema: toolSearchRegex_20251119InputSchema,\n outputSchema: toolSearchRegex_20251119OutputSchema,\n supportsDeferredResults: true\n});\nvar toolSearchRegex_20251119 = (args = {}) => {\n return factory6(args);\n};\n\n// src/convert-to-anthropic-messages-prompt.ts\nfunction convertToString(data) {\n if (typeof data === \"string\") {\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n }\n if (data instanceof Uint8Array) {\n return new TextDecoder().decode(data);\n }\n if (data instanceof URL) {\n throw new UnsupportedFunctionalityError2({\n functionality: \"URL-based text documents are not supported for citations\"\n });\n }\n throw new UnsupportedFunctionalityError2({\n functionality: `unsupported data type for text documents: ${typeof data}`\n });\n}\nfunction isUrlData(data) {\n return data instanceof URL || isUrlString(data);\n}\nfunction isUrlString(data) {\n return typeof data === \"string\" && /^https?:\\/\\//i.test(data);\n}\nfunction getUrlString(data) {\n return data instanceof URL ? data.toString() : data;\n}\nasync function convertToAnthropicMessagesPrompt({\n prompt,\n sendReasoning,\n warnings,\n cacheControlValidator,\n toolNameMapping\n}) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;\n const betas = /* @__PURE__ */ new Set();\n const blocks = groupIntoBlocks(prompt);\n const validator = cacheControlValidator || new CacheControlValidator();\n let system = void 0;\n const messages = [];\n async function shouldEnableCitations(providerMetadata) {\n var _a2, _b2;\n const anthropicOptions = await parseProviderOptions({\n provider: \"anthropic\",\n providerOptions: providerMetadata,\n schema: anthropicFilePartProviderOptions\n });\n return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;\n }\n async function getDocumentMetadata(providerMetadata) {\n const anthropicOptions = await parseProviderOptions({\n provider: \"anthropic\",\n providerOptions: providerMetadata,\n schema: anthropicFilePartProviderOptions\n });\n return {\n title: anthropicOptions == null ? void 0 : anthropicOptions.title,\n context: anthropicOptions == null ? void 0 : anthropicOptions.context\n };\n }\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n const isLastBlock = i === blocks.length - 1;\n const type = block.type;\n switch (type) {\n case \"system\": {\n if (system != null) {\n throw new UnsupportedFunctionalityError2({\n functionality: \"Multiple system messages that are separated by user/assistant messages\"\n });\n }\n system = block.messages.map(({ content, providerOptions }) => ({\n type: \"text\",\n text: content,\n cache_control: validator.getCacheControl(providerOptions, {\n type: \"system message\",\n canCache: true\n })\n }));\n break;\n }\n case \"user\": {\n const anthropicContent = [];\n for (const message of block.messages) {\n const { role, content } = message;\n switch (role) {\n case \"user\": {\n for (let j = 0; j < content.length; j++) {\n const part = content[j];\n const isLastPart = j === content.length - 1;\n const cacheControl = (_a = validator.getCacheControl(part.providerOptions, {\n type: \"user message part\",\n canCache: true\n })) != null ? _a : isLastPart ? validator.getCacheControl(message.providerOptions, {\n type: \"user message\",\n canCache: true\n }) : void 0;\n switch (part.type) {\n case \"text\": {\n anthropicContent.push({\n type: \"text\",\n text: part.text,\n cache_control: cacheControl\n });\n break;\n }\n case \"file\": {\n if (part.mediaType.startsWith(\"image/\")) {\n anthropicContent.push({\n type: \"image\",\n source: isUrlData(part.data) ? {\n type: \"url\",\n url: getUrlString(part.data)\n } : {\n type: \"base64\",\n media_type: part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType,\n data: convertToBase64(part.data)\n },\n cache_control: cacheControl\n });\n } else if (part.mediaType === \"application/pdf\") {\n betas.add(\"pdfs-2024-09-25\");\n const enableCitations = await shouldEnableCitations(\n part.providerOptions\n );\n const metadata = await getDocumentMetadata(\n part.providerOptions\n );\n anthropicContent.push({\n type: \"document\",\n source: isUrlData(part.data) ? {\n type: \"url\",\n url: getUrlString(part.data)\n } : {\n type: \"base64\",\n media_type: \"application/pdf\",\n data: convertToBase64(part.data)\n },\n title: (_b = metadata.title) != null ? _b : part.filename,\n ...metadata.context && { context: metadata.context },\n ...enableCitations && {\n citations: { enabled: true }\n },\n cache_control: cacheControl\n });\n } else if (part.mediaType === \"text/plain\") {\n const enableCitations = await shouldEnableCitations(\n part.providerOptions\n );\n const metadata = await getDocumentMetadata(\n part.providerOptions\n );\n anthropicContent.push({\n type: \"document\",\n source: isUrlData(part.data) ? {\n type: \"url\",\n url: getUrlString(part.data)\n } : {\n type: \"text\",\n media_type: \"text/plain\",\n data: convertToString(part.data)\n },\n title: (_c = metadata.title) != null ? _c : part.filename,\n ...metadata.context && { context: metadata.context },\n ...enableCitations && {\n citations: { enabled: true }\n },\n cache_control: cacheControl\n });\n } else {\n throw new UnsupportedFunctionalityError2({\n functionality: `media type: ${part.mediaType}`\n });\n }\n break;\n }\n }\n }\n break;\n }\n case \"tool\": {\n for (let i2 = 0; i2 < content.length; i2++) {\n const part = content[i2];\n if (part.type === \"tool-approval-response\") {\n continue;\n }\n const isLastPart = i2 === content.length - 1;\n const cacheControl = (_d = validator.getCacheControl(part.providerOptions, {\n type: \"tool result part\",\n canCache: true\n })) != null ? _d : isLastPart ? validator.getCacheControl(message.providerOptions, {\n type: \"tool result message\",\n canCache: true\n }) : void 0;\n const output = part.output;\n let contentValue;\n switch (output.type) {\n case \"content\":\n contentValue = output.value.map((contentPart) => {\n switch (contentPart.type) {\n case \"text\":\n return {\n type: \"text\",\n text: contentPart.text\n };\n case \"image-data\": {\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: contentPart.mediaType,\n data: contentPart.data\n }\n };\n }\n case \"image-url\": {\n return {\n type: \"image\",\n source: {\n type: \"url\",\n url: contentPart.url\n }\n };\n }\n case \"file-url\": {\n return {\n type: \"document\",\n source: {\n type: \"url\",\n url: contentPart.url\n }\n };\n }\n case \"file-data\": {\n if (contentPart.mediaType === \"application/pdf\") {\n betas.add(\"pdfs-2024-09-25\");\n return {\n type: \"document\",\n source: {\n type: \"base64\",\n media_type: contentPart.mediaType,\n data: contentPart.data\n }\n };\n }\n warnings.push({\n type: \"other\",\n message: `unsupported tool content part type: ${contentPart.type} with media type: ${contentPart.mediaType}`\n });\n return void 0;\n }\n default: {\n warnings.push({\n type: \"other\",\n message: `unsupported tool content part type: ${contentPart.type}`\n });\n return void 0;\n }\n }\n }).filter(isNonNullable);\n break;\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_e = output.reason) != null ? _e : \"Tool execution denied.\";\n break;\n case \"json\":\n case \"error-json\":\n default:\n contentValue = JSON.stringify(output.value);\n break;\n }\n anthropicContent.push({\n type: \"tool_result\",\n tool_use_id: part.toolCallId,\n content: contentValue,\n is_error: output.type === \"error-text\" || output.type === \"error-json\" ? true : void 0,\n cache_control: cacheControl\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n messages.push({ role: \"user\", content: anthropicContent });\n break;\n }\n case \"assistant\": {\n const anthropicContent = [];\n const mcpToolUseIds = /* @__PURE__ */ new Set();\n for (let j = 0; j < block.messages.length; j++) {\n const message = block.messages[j];\n const isLastMessage = j === block.messages.length - 1;\n const { content } = message;\n for (let k = 0; k < content.length; k++) {\n const part = content[k];\n const isLastContentPart = k === content.length - 1;\n const cacheControl = (_f = validator.getCacheControl(part.providerOptions, {\n type: \"assistant message part\",\n canCache: true\n })) != null ? _f : isLastContentPart ? validator.getCacheControl(message.providerOptions, {\n type: \"assistant message\",\n canCache: true\n }) : void 0;\n switch (part.type) {\n case \"text\": {\n anthropicContent.push({\n type: \"text\",\n text: (\n // trim the last text part if it's the last message in the block\n // because Anthropic does not allow trailing whitespace\n // in pre-filled assistant responses\n isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text\n ),\n cache_control: cacheControl\n });\n break;\n }\n case \"reasoning\": {\n if (sendReasoning) {\n const reasoningMetadata = await parseProviderOptions({\n provider: \"anthropic\",\n providerOptions: part.providerOptions,\n schema: anthropicReasoningMetadataSchema\n });\n if (reasoningMetadata != null) {\n if (reasoningMetadata.signature != null) {\n validator.getCacheControl(part.providerOptions, {\n type: \"thinking block\",\n canCache: false\n });\n anthropicContent.push({\n type: \"thinking\",\n thinking: part.text,\n signature: reasoningMetadata.signature\n });\n } else if (reasoningMetadata.redactedData != null) {\n validator.getCacheControl(part.providerOptions, {\n type: \"redacted thinking block\",\n canCache: false\n });\n anthropicContent.push({\n type: \"redacted_thinking\",\n data: reasoningMetadata.redactedData\n });\n } else {\n warnings.push({\n type: \"other\",\n message: \"unsupported reasoning metadata\"\n });\n }\n } else {\n warnings.push({\n type: \"other\",\n message: \"unsupported reasoning metadata\"\n });\n }\n } else {\n warnings.push({\n type: \"other\",\n message: \"sending reasoning content is disabled for this model\"\n });\n }\n break;\n }\n case \"tool-call\": {\n if (part.providerExecuted) {\n const providerToolName = toolNameMapping.toProviderToolName(\n part.toolName\n );\n const isMcpToolUse = ((_h = (_g = part.providerOptions) == null ? void 0 : _g.anthropic) == null ? void 0 : _h.type) === \"mcp-tool-use\";\n if (isMcpToolUse) {\n mcpToolUseIds.add(part.toolCallId);\n const serverName = (_j = (_i = part.providerOptions) == null ? void 0 : _i.anthropic) == null ? void 0 : _j.serverName;\n if (serverName == null || typeof serverName !== \"string\") {\n warnings.push({\n type: \"other\",\n message: \"mcp tool use server name is required and must be a string\"\n });\n break;\n }\n anthropicContent.push({\n type: \"mcp_tool_use\",\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n server_name: serverName,\n cache_control: cacheControl\n });\n } else if (\n // code execution 20250825:\n providerToolName === \"code_execution\" && part.input != null && typeof part.input === \"object\" && \"type\" in part.input && typeof part.input.type === \"string\" && (part.input.type === \"bash_code_execution\" || part.input.type === \"text_editor_code_execution\")\n ) {\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: part.input.type,\n // map back to subtool name\n input: part.input,\n cache_control: cacheControl\n });\n } else if (\n // code execution 20250825 programmatic tool calling:\n // Strip the fake 'programmatic-tool-call' type before sending to Anthropic\n providerToolName === \"code_execution\" && part.input != null && typeof part.input === \"object\" && \"type\" in part.input && part.input.type === \"programmatic-tool-call\"\n ) {\n const { type: _, ...inputWithoutType } = part.input;\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: \"code_execution\",\n input: inputWithoutType,\n cache_control: cacheControl\n });\n } else {\n if (providerToolName === \"code_execution\" || // code execution 20250522\n providerToolName === \"web_fetch\" || providerToolName === \"web_search\") {\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: providerToolName,\n input: part.input,\n cache_control: cacheControl\n });\n } else if (providerToolName === \"tool_search_tool_regex\" || providerToolName === \"tool_search_tool_bm25\") {\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: providerToolName,\n input: part.input,\n cache_control: cacheControl\n });\n } else {\n warnings.push({\n type: \"other\",\n message: `provider executed tool call for tool ${part.toolName} is not supported`\n });\n }\n }\n break;\n }\n const callerOptions = (_k = part.providerOptions) == null ? void 0 : _k.anthropic;\n const caller = (callerOptions == null ? void 0 : callerOptions.caller) ? callerOptions.caller.type === \"code_execution_20250825\" && callerOptions.caller.toolId ? {\n type: \"code_execution_20250825\",\n tool_id: callerOptions.caller.toolId\n } : callerOptions.caller.type === \"direct\" ? { type: \"direct\" } : void 0 : void 0;\n anthropicContent.push({\n type: \"tool_use\",\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n ...caller && { caller },\n cache_control: cacheControl\n });\n break;\n }\n case \"tool-result\": {\n const providerToolName = toolNameMapping.toProviderToolName(\n part.toolName\n );\n if (mcpToolUseIds.has(part.toolCallId)) {\n const output = part.output;\n if (output.type !== \"json\" && output.type !== \"error-json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n anthropicContent.push({\n type: \"mcp_tool_result\",\n tool_use_id: part.toolCallId,\n is_error: output.type === \"error-json\",\n content: output.value,\n cache_control: cacheControl\n });\n } else if (providerToolName === \"code_execution\") {\n const output = part.output;\n if (output.type === \"error-text\" || output.type === \"error-json\") {\n let errorInfo = {};\n try {\n if (typeof output.value === \"string\") {\n errorInfo = JSON.parse(output.value);\n } else if (typeof output.value === \"object\" && output.value !== null) {\n errorInfo = output.value;\n }\n } catch (e) {\n }\n if (errorInfo.type === \"code_execution_tool_result_error\") {\n anthropicContent.push({\n type: \"code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"code_execution_tool_result_error\",\n error_code: (_l = errorInfo.errorCode) != null ? _l : \"unknown\"\n },\n cache_control: cacheControl\n });\n } else {\n anthropicContent.push({\n type: \"bash_code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n cache_control: cacheControl,\n content: {\n type: \"bash_code_execution_tool_result_error\",\n error_code: (_m = errorInfo.errorCode) != null ? _m : \"unknown\"\n }\n });\n }\n break;\n }\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n if (output.value == null || typeof output.value !== \"object\" || !(\"type\" in output.value) || typeof output.value.type !== \"string\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output value is not a valid code execution result for tool ${part.toolName}`\n });\n break;\n }\n if (output.value.type === \"code_execution_result\") {\n const codeExecutionOutput = await validateTypes2({\n value: output.value,\n schema: codeExecution_20250522OutputSchema\n });\n anthropicContent.push({\n type: \"code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: codeExecutionOutput.type,\n stdout: codeExecutionOutput.stdout,\n stderr: codeExecutionOutput.stderr,\n return_code: codeExecutionOutput.return_code,\n content: (_n = codeExecutionOutput.content) != null ? _n : []\n },\n cache_control: cacheControl\n });\n } else {\n const codeExecutionOutput = await validateTypes2({\n value: output.value,\n schema: codeExecution_20250825OutputSchema\n });\n if (codeExecutionOutput.type === \"code_execution_result\") {\n anthropicContent.push({\n type: \"code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: codeExecutionOutput.type,\n stdout: codeExecutionOutput.stdout,\n stderr: codeExecutionOutput.stderr,\n return_code: codeExecutionOutput.return_code,\n content: (_o = codeExecutionOutput.content) != null ? _o : []\n },\n cache_control: cacheControl\n });\n } else if (codeExecutionOutput.type === \"bash_code_execution_result\" || codeExecutionOutput.type === \"bash_code_execution_tool_result_error\") {\n anthropicContent.push({\n type: \"bash_code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n cache_control: cacheControl,\n content: codeExecutionOutput\n });\n } else {\n anthropicContent.push({\n type: \"text_editor_code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n cache_control: cacheControl,\n content: codeExecutionOutput\n });\n }\n }\n break;\n }\n if (providerToolName === \"web_fetch\") {\n const output = part.output;\n if (output.type === \"error-json\") {\n let errorValue = {};\n try {\n if (typeof output.value === \"string\") {\n errorValue = JSON.parse(output.value);\n } else if (typeof output.value === \"object\" && output.value !== null) {\n errorValue = output.value;\n }\n } catch (e) {\n const extractedErrorCode = (_p = output.value) == null ? void 0 : _p.errorCode;\n errorValue = {\n errorCode: typeof extractedErrorCode === \"string\" ? extractedErrorCode : \"unknown\"\n };\n }\n anthropicContent.push({\n type: \"web_fetch_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"web_fetch_tool_result_error\",\n error_code: (_q = errorValue.errorCode) != null ? _q : \"unknown\"\n },\n cache_control: cacheControl\n });\n break;\n }\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n const webFetchOutput = await validateTypes2({\n value: output.value,\n schema: webFetch_20250910OutputSchema\n });\n anthropicContent.push({\n type: \"web_fetch_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"web_fetch_result\",\n url: webFetchOutput.url,\n retrieved_at: webFetchOutput.retrievedAt,\n content: {\n type: \"document\",\n title: webFetchOutput.content.title,\n citations: webFetchOutput.content.citations,\n source: {\n type: webFetchOutput.content.source.type,\n media_type: webFetchOutput.content.source.mediaType,\n data: webFetchOutput.content.source.data\n }\n }\n },\n cache_control: cacheControl\n });\n break;\n }\n if (providerToolName === \"web_search\") {\n const output = part.output;\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n const webSearchOutput = await validateTypes2({\n value: output.value,\n schema: webSearch_20250305OutputSchema\n });\n anthropicContent.push({\n type: \"web_search_tool_result\",\n tool_use_id: part.toolCallId,\n content: webSearchOutput.map((result) => ({\n url: result.url,\n title: result.title,\n page_age: result.pageAge,\n encrypted_content: result.encryptedContent,\n type: result.type\n })),\n cache_control: cacheControl\n });\n break;\n }\n if (providerToolName === \"tool_search_tool_regex\" || providerToolName === \"tool_search_tool_bm25\") {\n const output = part.output;\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n const toolSearchOutput = await validateTypes2({\n value: output.value,\n schema: toolSearchRegex_20251119OutputSchema\n });\n const toolReferences = toolSearchOutput.map((ref) => ({\n type: \"tool_reference\",\n tool_name: ref.toolName\n }));\n anthropicContent.push({\n type: \"tool_search_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"tool_search_tool_search_result\",\n tool_references: toolReferences\n },\n cache_control: cacheControl\n });\n break;\n }\n warnings.push({\n type: \"other\",\n message: `provider executed tool result for tool ${part.toolName} is not supported`\n });\n break;\n }\n }\n }\n }\n messages.push({ role: \"assistant\", content: anthropicContent });\n break;\n }\n default: {\n const _exhaustiveCheck = type;\n throw new Error(`content type: ${_exhaustiveCheck}`);\n }\n }\n }\n return {\n prompt: { system, messages },\n betas\n };\n}\nfunction groupIntoBlocks(prompt) {\n const blocks = [];\n let currentBlock = void 0;\n for (const message of prompt) {\n const { role } = message;\n switch (role) {\n case \"system\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"system\") {\n currentBlock = { type: \"system\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n case \"assistant\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"assistant\") {\n currentBlock = { type: \"assistant\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n case \"user\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"user\") {\n currentBlock = { type: \"user\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n case \"tool\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"user\") {\n currentBlock = { type: \"user\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return blocks;\n}\n\n// src/map-anthropic-stop-reason.ts\nfunction mapAnthropicStopReason({\n finishReason,\n isJsonResponseFromTool\n}) {\n switch (finishReason) {\n case \"pause_turn\":\n case \"end_turn\":\n case \"stop_sequence\":\n return \"stop\";\n case \"refusal\":\n return \"content-filter\";\n case \"tool_use\":\n return isJsonResponseFromTool ? \"stop\" : \"tool-calls\";\n case \"max_tokens\":\n case \"model_context_window_exceeded\":\n return \"length\";\n default:\n return \"other\";\n }\n}\n\n// src/anthropic-messages-language-model.ts\nfunction createCitationSource(citation, citationDocuments, generateId3) {\n var _a;\n if (citation.type === \"web_search_result_location\") {\n return {\n type: \"source\",\n sourceType: \"url\",\n id: generateId3(),\n url: citation.url,\n title: citation.title,\n providerMetadata: {\n anthropic: {\n citedText: citation.cited_text,\n encryptedIndex: citation.encrypted_index\n }\n }\n };\n }\n if (citation.type !== \"page_location\" && citation.type !== \"char_location\") {\n return;\n }\n const documentInfo = citationDocuments[citation.document_index];\n if (!documentInfo) {\n return;\n }\n return {\n type: \"source\",\n sourceType: \"document\",\n id: generateId3(),\n mediaType: documentInfo.mediaType,\n title: (_a = citation.document_title) != null ? _a : documentInfo.title,\n filename: documentInfo.filename,\n providerMetadata: {\n anthropic: citation.type === \"page_location\" ? {\n citedText: citation.cited_text,\n startPageNumber: citation.start_page_number,\n endPageNumber: citation.end_page_number\n } : {\n citedText: citation.cited_text,\n startCharIndex: citation.start_char_index,\n endCharIndex: citation.end_char_index\n }\n }\n };\n}\nvar AnthropicMessagesLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n var _a;\n this.modelId = modelId;\n this.config = config;\n this.generateId = (_a = config.generateId) != null ? _a : generateId;\n }\n supportsUrl(url) {\n return url.protocol === \"https:\";\n }\n get provider() {\n return this.config.provider;\n }\n /**\n * Extracts the dynamic provider name from the config.provider string.\n * e.g., 'my-custom-anthropic.messages' -> 'my-custom-anthropic'\n */\n get providerOptionsName() {\n const provider = this.config.provider;\n const dotIndex = provider.indexOf(\".\");\n return dotIndex === -1 ? provider : provider.substring(0, dotIndex);\n }\n get supportedUrls() {\n var _a, _b, _c;\n return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};\n }\n async getArgs({\n userSuppliedBetas,\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n tools,\n toolChoice,\n providerOptions,\n stream\n }) {\n var _a, _b, _c, _d, _e, _f;\n const warnings = [];\n if (frequencyPenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"frequencyPenalty\" });\n }\n if (presencePenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"presencePenalty\" });\n }\n if (seed != null) {\n warnings.push({ type: \"unsupported\", feature: \"seed\" });\n }\n if (temperature != null && temperature > 1) {\n warnings.push({\n type: \"unsupported\",\n feature: \"temperature\",\n details: `${temperature} exceeds anthropic maximum of 1.0. clamped to 1.0`\n });\n temperature = 1;\n } else if (temperature != null && temperature < 0) {\n warnings.push({\n type: \"unsupported\",\n feature: \"temperature\",\n details: `${temperature} is below anthropic minimum of 0. clamped to 0`\n });\n temperature = 0;\n }\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\") {\n if (responseFormat.schema == null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"responseFormat\",\n details: \"JSON response format requires a schema. The response format is ignored.\"\n });\n }\n }\n const providerOptionsName = this.providerOptionsName;\n const canonicalOptions = await parseProviderOptions2({\n provider: \"anthropic\",\n providerOptions,\n schema: anthropicProviderOptions\n });\n const customProviderOptions = providerOptionsName !== \"anthropic\" ? await parseProviderOptions2({\n provider: providerOptionsName,\n providerOptions,\n schema: anthropicProviderOptions\n }) : null;\n const usedCustomProviderKey = customProviderOptions != null;\n const anthropicOptions = Object.assign(\n {},\n canonicalOptions != null ? canonicalOptions : {},\n customProviderOptions != null ? customProviderOptions : {}\n );\n const {\n maxOutputTokens: maxOutputTokensForModel,\n supportsStructuredOutput: modelSupportsStructuredOutput,\n isKnownModel\n } = getModelCapabilities(this.modelId);\n const supportsStructuredOutput = ((_a = this.config.supportsNativeStructuredOutput) != null ? _a : true) && modelSupportsStructuredOutput;\n const structureOutputMode = (_b = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _b : \"auto\";\n const useStructuredOutput = structureOutputMode === \"outputFormat\" || structureOutputMode === \"auto\" && supportsStructuredOutput;\n const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null && !useStructuredOutput ? {\n type: \"function\",\n name: \"json\",\n description: \"Respond with a JSON object.\",\n inputSchema: responseFormat.schema\n } : void 0;\n const contextManagement = anthropicOptions == null ? void 0 : anthropicOptions.contextManagement;\n const cacheControlValidator = new CacheControlValidator();\n const toolNameMapping = createToolNameMapping({\n tools,\n providerToolNames: {\n \"anthropic.code_execution_20250522\": \"code_execution\",\n \"anthropic.code_execution_20250825\": \"code_execution\",\n \"anthropic.computer_20241022\": \"computer\",\n \"anthropic.computer_20250124\": \"computer\",\n \"anthropic.text_editor_20241022\": \"str_replace_editor\",\n \"anthropic.text_editor_20250124\": \"str_replace_editor\",\n \"anthropic.text_editor_20250429\": \"str_replace_based_edit_tool\",\n \"anthropic.text_editor_20250728\": \"str_replace_based_edit_tool\",\n \"anthropic.bash_20241022\": \"bash\",\n \"anthropic.bash_20250124\": \"bash\",\n \"anthropic.memory_20250818\": \"memory\",\n \"anthropic.web_search_20250305\": \"web_search\",\n \"anthropic.web_fetch_20250910\": \"web_fetch\",\n \"anthropic.tool_search_regex_20251119\": \"tool_search_tool_regex\",\n \"anthropic.tool_search_bm25_20251119\": \"tool_search_tool_bm25\"\n }\n });\n const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({\n prompt,\n sendReasoning: (_c = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _c : true,\n warnings,\n cacheControlValidator,\n toolNameMapping\n });\n const isThinking = ((_d = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _d.type) === \"enabled\";\n let thinkingBudget = (_e = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _e.budgetTokens;\n const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel;\n const baseArgs = {\n // model id:\n model: this.modelId,\n // standardized settings:\n max_tokens: maxTokens,\n temperature,\n top_k: topK,\n top_p: topP,\n stop_sequences: stopSequences,\n // provider specific settings:\n ...isThinking && {\n thinking: { type: \"enabled\", budget_tokens: thinkingBudget }\n },\n ...(anthropicOptions == null ? void 0 : anthropicOptions.effort) && {\n output_config: { effort: anthropicOptions.effort }\n },\n // structured output:\n ...useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null && {\n output_format: {\n type: \"json_schema\",\n schema: responseFormat.schema\n }\n },\n // mcp servers:\n ...(anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && {\n mcp_servers: anthropicOptions.mcpServers.map((server) => ({\n type: server.type,\n name: server.name,\n url: server.url,\n authorization_token: server.authorizationToken,\n tool_configuration: server.toolConfiguration ? {\n allowed_tools: server.toolConfiguration.allowedTools,\n enabled: server.toolConfiguration.enabled\n } : void 0\n }))\n },\n // container: For programmatic tool calling (just an ID string) or agent skills (object with id and skills)\n ...(anthropicOptions == null ? void 0 : anthropicOptions.container) && {\n container: anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0 ? (\n // Object format when skills are provided (agent skills feature)\n {\n id: anthropicOptions.container.id,\n skills: anthropicOptions.container.skills.map((skill) => ({\n type: skill.type,\n skill_id: skill.skillId,\n version: skill.version\n }))\n }\n ) : (\n // String format for container ID only (programmatic tool calling)\n anthropicOptions.container.id\n )\n },\n // prompt:\n system: messagesPrompt.system,\n messages: messagesPrompt.messages,\n ...contextManagement && {\n context_management: {\n edits: contextManagement.edits.map((edit) => {\n const strategy = edit.type;\n switch (strategy) {\n case \"clear_tool_uses_20250919\":\n return {\n type: edit.type,\n ...edit.trigger !== void 0 && {\n trigger: edit.trigger\n },\n ...edit.keep !== void 0 && { keep: edit.keep },\n ...edit.clearAtLeast !== void 0 && {\n clear_at_least: edit.clearAtLeast\n },\n ...edit.clearToolInputs !== void 0 && {\n clear_tool_inputs: edit.clearToolInputs\n },\n ...edit.excludeTools !== void 0 && {\n exclude_tools: edit.excludeTools\n }\n };\n case \"clear_thinking_20251015\":\n return {\n type: edit.type,\n ...edit.keep !== void 0 && { keep: edit.keep }\n };\n default:\n warnings.push({\n type: \"other\",\n message: `Unknown context management strategy: ${strategy}`\n });\n return void 0;\n }\n }).filter((edit) => edit !== void 0)\n }\n }\n };\n if (isThinking) {\n if (thinkingBudget == null) {\n warnings.push({\n type: \"compatibility\",\n feature: \"extended thinking\",\n details: \"thinking budget is required when thinking is enabled. using default budget of 1024 tokens.\"\n });\n baseArgs.thinking = {\n type: \"enabled\",\n budget_tokens: 1024\n };\n thinkingBudget = 1024;\n }\n if (baseArgs.temperature != null) {\n baseArgs.temperature = void 0;\n warnings.push({\n type: \"unsupported\",\n feature: \"temperature\",\n details: \"temperature is not supported when thinking is enabled\"\n });\n }\n if (topK != null) {\n baseArgs.top_k = void 0;\n warnings.push({\n type: \"unsupported\",\n feature: \"topK\",\n details: \"topK is not supported when thinking is enabled\"\n });\n }\n if (topP != null) {\n baseArgs.top_p = void 0;\n warnings.push({\n type: \"unsupported\",\n feature: \"topP\",\n details: \"topP is not supported when thinking is enabled\"\n });\n }\n baseArgs.max_tokens = maxTokens + (thinkingBudget != null ? thinkingBudget : 0);\n } else {\n if (topP != null && temperature != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"topP\",\n details: `topP is not supported when temperature is set. topP is ignored.`\n });\n baseArgs.top_p = void 0;\n }\n }\n if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) {\n if (maxOutputTokens != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"maxOutputTokens\",\n details: `${baseArgs.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${maxOutputTokensForModel} max output tokens. The max output tokens have been limited to ${maxOutputTokensForModel}.`\n });\n }\n baseArgs.max_tokens = maxOutputTokensForModel;\n }\n if ((anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0) {\n betas.add(\"mcp-client-2025-04-04\");\n }\n if (contextManagement) {\n betas.add(\"context-management-2025-06-27\");\n }\n if ((anthropicOptions == null ? void 0 : anthropicOptions.container) && anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0) {\n betas.add(\"code-execution-2025-08-25\");\n betas.add(\"skills-2025-10-02\");\n betas.add(\"files-api-2025-04-14\");\n if (!(tools == null ? void 0 : tools.some(\n (tool) => tool.type === \"provider\" && tool.id === \"anthropic.code_execution_20250825\"\n ))) {\n warnings.push({\n type: \"other\",\n message: \"code execution tool is required when using skills\"\n });\n }\n }\n if (anthropicOptions == null ? void 0 : anthropicOptions.effort) {\n betas.add(\"effort-2025-11-24\");\n }\n if (stream && ((_f = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _f : true)) {\n betas.add(\"fine-grained-tool-streaming-2025-05-14\");\n }\n const usingNativeOutputFormat = useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null;\n if (usingNativeOutputFormat) {\n betas.add(\"structured-outputs-2025-11-13\");\n }\n const {\n tools: anthropicTools2,\n toolChoice: anthropicToolChoice,\n toolWarnings,\n betas: toolsBetas\n } = await prepareTools(\n jsonResponseTool != null ? {\n tools: [...tools != null ? tools : [], jsonResponseTool],\n toolChoice: { type: \"required\" },\n disableParallelToolUse: true,\n cacheControlValidator,\n supportsStructuredOutput: false\n } : {\n tools: tools != null ? tools : [],\n toolChoice,\n disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,\n cacheControlValidator,\n supportsStructuredOutput\n }\n );\n const cacheWarnings = cacheControlValidator.getWarnings();\n return {\n args: {\n ...baseArgs,\n tools: anthropicTools2,\n tool_choice: anthropicToolChoice,\n stream: stream === true ? true : void 0\n // do not send when not streaming\n },\n warnings: [...warnings, ...toolWarnings, ...cacheWarnings],\n betas: /* @__PURE__ */ new Set([...betas, ...toolsBetas, ...userSuppliedBetas]),\n usesJsonResponseTool: jsonResponseTool != null,\n toolNameMapping,\n providerOptionsName,\n usedCustomProviderKey\n };\n }\n async getHeaders({\n betas,\n headers\n }) {\n return combineHeaders(\n await resolve(this.config.headers),\n headers,\n betas.size > 0 ? { \"anthropic-beta\": Array.from(betas).join(\",\") } : {}\n );\n }\n async getBetasFromHeaders(requestHeaders) {\n var _a, _b;\n const configHeaders = await resolve(this.config.headers);\n const configBetaHeader = (_a = configHeaders[\"anthropic-beta\"]) != null ? _a : \"\";\n const requestBetaHeader = (_b = requestHeaders == null ? void 0 : requestHeaders[\"anthropic-beta\"]) != null ? _b : \"\";\n return new Set(\n [\n ...configBetaHeader.toLowerCase().split(\",\"),\n ...requestBetaHeader.toLowerCase().split(\",\")\n ].map((beta) => beta.trim()).filter((beta) => beta !== \"\")\n );\n }\n buildRequestUrl(isStreaming) {\n var _a, _b, _c;\n return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;\n }\n transformRequestBody(args) {\n var _a, _b, _c;\n return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;\n }\n extractCitationDocuments(prompt) {\n const isCitationPart = (part) => {\n var _a, _b;\n if (part.type !== \"file\") {\n return false;\n }\n if (part.mediaType !== \"application/pdf\" && part.mediaType !== \"text/plain\") {\n return false;\n }\n const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;\n const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;\n return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;\n };\n return prompt.filter((message) => message.role === \"user\").flatMap((message) => message.content).filter(isCitationPart).map((part) => {\n var _a;\n const filePart = part;\n return {\n title: (_a = filePart.filename) != null ? _a : \"Untitled Document\",\n filename: filePart.filename,\n mediaType: filePart.mediaType\n };\n });\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f;\n const {\n args,\n warnings,\n betas,\n usesJsonResponseTool,\n toolNameMapping,\n providerOptionsName,\n usedCustomProviderKey\n } = await this.getArgs({\n ...options,\n stream: false,\n userSuppliedBetas: await this.getBetasFromHeaders(options.headers)\n });\n const citationDocuments = [\n ...this.extractCitationDocuments(options.prompt)\n ];\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: this.buildRequestUrl(false),\n headers: await this.getHeaders({ betas, headers: options.headers }),\n body: this.transformRequestBody(args),\n failedResponseHandler: anthropicFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n anthropicMessagesResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const content = [];\n const mcpToolCalls = {};\n const serverToolCalls = {};\n let isJsonResponseFromTool = false;\n for (const part of response.content) {\n switch (part.type) {\n case \"text\": {\n if (!usesJsonResponseTool) {\n content.push({ type: \"text\", text: part.text });\n if (part.citations) {\n for (const citation of part.citations) {\n const source = createCitationSource(\n citation,\n citationDocuments,\n this.generateId\n );\n if (source) {\n content.push(source);\n }\n }\n }\n }\n break;\n }\n case \"thinking\": {\n content.push({\n type: \"reasoning\",\n text: part.thinking,\n providerMetadata: {\n anthropic: {\n signature: part.signature\n }\n }\n });\n break;\n }\n case \"redacted_thinking\": {\n content.push({\n type: \"reasoning\",\n text: \"\",\n providerMetadata: {\n anthropic: {\n redactedData: part.data\n }\n }\n });\n break;\n }\n case \"tool_use\": {\n const isJsonResponseTool = usesJsonResponseTool && part.name === \"json\";\n if (isJsonResponseTool) {\n isJsonResponseFromTool = true;\n content.push({\n type: \"text\",\n text: JSON.stringify(part.input)\n });\n } else {\n const caller = part.caller;\n const callerInfo = caller ? {\n type: caller.type,\n toolId: \"tool_id\" in caller ? caller.tool_id : void 0\n } : void 0;\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: JSON.stringify(part.input),\n ...callerInfo && {\n providerMetadata: {\n anthropic: {\n caller: callerInfo\n }\n }\n }\n });\n }\n break;\n }\n case \"server_tool_use\": {\n if (part.name === \"text_editor_code_execution\" || part.name === \"bash_code_execution\") {\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n input: JSON.stringify({ type: part.name, ...part.input }),\n providerExecuted: true\n });\n } else if (part.name === \"web_search\" || part.name === \"code_execution\" || part.name === \"web_fetch\") {\n const inputToSerialize = part.name === \"code_execution\" && part.input != null && typeof part.input === \"object\" && \"code\" in part.input && !(\"type\" in part.input) ? { type: \"programmatic-tool-call\", ...part.input } : part.input;\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: toolNameMapping.toCustomToolName(part.name),\n input: JSON.stringify(inputToSerialize),\n providerExecuted: true\n });\n } else if (part.name === \"tool_search_tool_regex\" || part.name === \"tool_search_tool_bm25\") {\n serverToolCalls[part.id] = part.name;\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: toolNameMapping.toCustomToolName(part.name),\n input: JSON.stringify(part.input),\n providerExecuted: true\n });\n }\n break;\n }\n case \"mcp_tool_use\": {\n mcpToolCalls[part.id] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: JSON.stringify(part.input),\n providerExecuted: true,\n dynamic: true,\n providerMetadata: {\n anthropic: {\n type: \"mcp-tool-use\",\n serverName: part.server_name\n }\n }\n };\n content.push(mcpToolCalls[part.id]);\n break;\n }\n case \"mcp_tool_result\": {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: mcpToolCalls[part.tool_use_id].toolName,\n isError: part.is_error,\n result: part.content,\n dynamic: true,\n providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata\n });\n break;\n }\n case \"web_fetch_tool_result\": {\n if (part.content.type === \"web_fetch_result\") {\n citationDocuments.push({\n title: (_a = part.content.content.title) != null ? _a : part.content.url,\n mediaType: part.content.content.source.media_type\n });\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n result: {\n type: \"web_fetch_result\",\n url: part.content.url,\n retrievedAt: part.content.retrieved_at,\n content: {\n type: part.content.content.type,\n title: part.content.content.title,\n citations: part.content.content.citations,\n source: {\n type: part.content.content.source.type,\n mediaType: part.content.content.source.media_type,\n data: part.content.content.source.data\n }\n }\n }\n });\n } else if (part.content.type === \"web_fetch_tool_result_error\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n isError: true,\n result: {\n type: \"web_fetch_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n case \"web_search_tool_result\": {\n if (Array.isArray(part.content)) {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n result: part.content.map((result) => {\n var _a2;\n return {\n url: result.url,\n title: result.title,\n pageAge: (_a2 = result.page_age) != null ? _a2 : null,\n encryptedContent: result.encrypted_content,\n type: result.type\n };\n })\n });\n for (const result of part.content) {\n content.push({\n type: \"source\",\n sourceType: \"url\",\n id: this.generateId(),\n url: result.url,\n title: result.title,\n providerMetadata: {\n anthropic: {\n pageAge: (_b = result.page_age) != null ? _b : null\n }\n }\n });\n }\n } else {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n isError: true,\n result: {\n type: \"web_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n // code execution 20250522:\n case \"code_execution_tool_result\": {\n if (part.content.type === \"code_execution_result\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: {\n type: part.content.type,\n stdout: part.content.stdout,\n stderr: part.content.stderr,\n return_code: part.content.return_code,\n content: (_c = part.content.content) != null ? _c : []\n }\n });\n } else if (part.content.type === \"code_execution_tool_result_error\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n isError: true,\n result: {\n type: \"code_execution_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n // code execution 20250825:\n case \"bash_code_execution_tool_result\":\n case \"text_editor_code_execution_tool_result\": {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: part.content\n });\n break;\n }\n // tool search tool results:\n case \"tool_search_tool_result\": {\n let providerToolName = serverToolCalls[part.tool_use_id];\n if (providerToolName == null) {\n const bm25CustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_bm25\"\n );\n const regexCustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_regex\"\n );\n if (bm25CustomName !== \"tool_search_tool_bm25\") {\n providerToolName = \"tool_search_tool_bm25\";\n } else if (regexCustomName !== \"tool_search_tool_regex\") {\n providerToolName = \"tool_search_tool_regex\";\n } else {\n providerToolName = \"tool_search_tool_regex\";\n }\n }\n if (part.content.type === \"tool_search_tool_search_result\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n result: part.content.tool_references.map((ref) => ({\n type: ref.type,\n toolName: ref.tool_name\n }))\n });\n } else {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n isError: true,\n result: {\n type: \"tool_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n }\n }\n return {\n content,\n finishReason: {\n unified: mapAnthropicStopReason({\n finishReason: response.stop_reason,\n isJsonResponseFromTool\n }),\n raw: (_d = response.stop_reason) != null ? _d : void 0\n },\n usage: convertAnthropicMessagesUsage(response.usage),\n request: { body: args },\n response: {\n id: (_e = response.id) != null ? _e : void 0,\n modelId: (_f = response.model) != null ? _f : void 0,\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n providerMetadata: (() => {\n var _a2, _b2, _c2, _d2, _e2;\n const anthropicMetadata = {\n usage: response.usage,\n cacheCreationInputTokens: (_a2 = response.usage.cache_creation_input_tokens) != null ? _a2 : null,\n stopSequence: (_b2 = response.stop_sequence) != null ? _b2 : null,\n container: response.container ? {\n expiresAt: response.container.expires_at,\n id: response.container.id,\n skills: (_d2 = (_c2 = response.container.skills) == null ? void 0 : _c2.map((skill) => ({\n type: skill.type,\n skillId: skill.skill_id,\n version: skill.version\n }))) != null ? _d2 : null\n } : null,\n contextManagement: (_e2 = mapAnthropicResponseContextManagement(\n response.context_management\n )) != null ? _e2 : null\n };\n const providerMetadata = {\n anthropic: anthropicMetadata\n };\n if (usedCustomProviderKey && providerOptionsName !== \"anthropic\") {\n providerMetadata[providerOptionsName] = anthropicMetadata;\n }\n return providerMetadata;\n })()\n };\n }\n async doStream(options) {\n var _a, _b;\n const {\n args: body,\n warnings,\n betas,\n usesJsonResponseTool,\n toolNameMapping,\n providerOptionsName,\n usedCustomProviderKey\n } = await this.getArgs({\n ...options,\n stream: true,\n userSuppliedBetas: await this.getBetasFromHeaders(options.headers)\n });\n const citationDocuments = [\n ...this.extractCitationDocuments(options.prompt)\n ];\n const url = this.buildRequestUrl(true);\n const { responseHeaders, value: response } = await postJsonToApi({\n url,\n headers: await this.getHeaders({ betas, headers: options.headers }),\n body: this.transformRequestBody(body),\n failedResponseHandler: anthropicFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n anthropicMessagesChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n const usage = {\n input_tokens: 0,\n output_tokens: 0,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0\n };\n const contentBlocks = {};\n const mcpToolCalls = {};\n const serverToolCalls = {};\n let contextManagement = null;\n let rawUsage = void 0;\n let cacheCreationInputTokens = null;\n let stopSequence = null;\n let container = null;\n let isJsonResponseFromTool = false;\n let blockType = void 0;\n const generateId3 = this.generateId;\n const transformedStream = response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n switch (value.type) {\n case \"ping\": {\n return;\n }\n case \"content_block_start\": {\n const part = value.content_block;\n const contentBlockType = part.type;\n blockType = contentBlockType;\n switch (contentBlockType) {\n case \"text\": {\n if (usesJsonResponseTool) {\n return;\n }\n contentBlocks[value.index] = { type: \"text\" };\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n return;\n }\n case \"thinking\": {\n contentBlocks[value.index] = { type: \"reasoning\" };\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index)\n });\n return;\n }\n case \"redacted_thinking\": {\n contentBlocks[value.index] = { type: \"reasoning\" };\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index),\n providerMetadata: {\n anthropic: {\n redactedData: part.data\n }\n }\n });\n return;\n }\n case \"tool_use\": {\n const isJsonResponseTool = usesJsonResponseTool && part.name === \"json\";\n if (isJsonResponseTool) {\n isJsonResponseFromTool = true;\n contentBlocks[value.index] = { type: \"text\" };\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n } else {\n const caller = part.caller;\n const callerInfo = caller ? {\n type: caller.type,\n toolId: \"tool_id\" in caller ? caller.tool_id : void 0\n } : void 0;\n const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0;\n const initialInput = hasNonEmptyInput ? JSON.stringify(part.input) : \"\";\n contentBlocks[value.index] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: initialInput,\n firstDelta: initialInput.length === 0,\n ...callerInfo && { caller: callerInfo }\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: part.name\n });\n }\n return;\n }\n case \"server_tool_use\": {\n if ([\n \"web_fetch\",\n \"web_search\",\n // code execution 20250825:\n \"code_execution\",\n // code execution 20250825 text editor:\n \"text_editor_code_execution\",\n // code execution 20250825 bash:\n \"bash_code_execution\"\n ].includes(part.name)) {\n const providerToolName = part.name === \"text_editor_code_execution\" || part.name === \"bash_code_execution\" ? \"code_execution\" : part.name;\n const customToolName = toolNameMapping.toCustomToolName(providerToolName);\n contentBlocks[value.index] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: customToolName,\n input: \"\",\n providerExecuted: true,\n firstDelta: true,\n providerToolName: part.name\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: customToolName,\n providerExecuted: true\n });\n } else if (part.name === \"tool_search_tool_regex\" || part.name === \"tool_search_tool_bm25\") {\n serverToolCalls[part.id] = part.name;\n const customToolName = toolNameMapping.toCustomToolName(\n part.name\n );\n contentBlocks[value.index] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: customToolName,\n input: \"\",\n providerExecuted: true,\n firstDelta: true,\n providerToolName: part.name\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: customToolName,\n providerExecuted: true\n });\n }\n return;\n }\n case \"web_fetch_tool_result\": {\n if (part.content.type === \"web_fetch_result\") {\n citationDocuments.push({\n title: (_a2 = part.content.content.title) != null ? _a2 : part.content.url,\n mediaType: part.content.content.source.media_type\n });\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n result: {\n type: \"web_fetch_result\",\n url: part.content.url,\n retrievedAt: part.content.retrieved_at,\n content: {\n type: part.content.content.type,\n title: part.content.content.title,\n citations: part.content.content.citations,\n source: {\n type: part.content.content.source.type,\n mediaType: part.content.content.source.media_type,\n data: part.content.content.source.data\n }\n }\n }\n });\n } else if (part.content.type === \"web_fetch_tool_result_error\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n isError: true,\n result: {\n type: \"web_fetch_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n case \"web_search_tool_result\": {\n if (Array.isArray(part.content)) {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n result: part.content.map((result) => {\n var _a3;\n return {\n url: result.url,\n title: result.title,\n pageAge: (_a3 = result.page_age) != null ? _a3 : null,\n encryptedContent: result.encrypted_content,\n type: result.type\n };\n })\n });\n for (const result of part.content) {\n controller.enqueue({\n type: \"source\",\n sourceType: \"url\",\n id: generateId3(),\n url: result.url,\n title: result.title,\n providerMetadata: {\n anthropic: {\n pageAge: (_b2 = result.page_age) != null ? _b2 : null\n }\n }\n });\n }\n } else {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n isError: true,\n result: {\n type: \"web_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n // code execution 20250522:\n case \"code_execution_tool_result\": {\n if (part.content.type === \"code_execution_result\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: {\n type: part.content.type,\n stdout: part.content.stdout,\n stderr: part.content.stderr,\n return_code: part.content.return_code,\n content: (_c = part.content.content) != null ? _c : []\n }\n });\n } else if (part.content.type === \"code_execution_tool_result_error\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n isError: true,\n result: {\n type: \"code_execution_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n // code execution 20250825:\n case \"bash_code_execution_tool_result\":\n case \"text_editor_code_execution_tool_result\": {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: part.content\n });\n return;\n }\n // tool search tool results:\n case \"tool_search_tool_result\": {\n let providerToolName = serverToolCalls[part.tool_use_id];\n if (providerToolName == null) {\n const bm25CustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_bm25\"\n );\n const regexCustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_regex\"\n );\n if (bm25CustomName !== \"tool_search_tool_bm25\") {\n providerToolName = \"tool_search_tool_bm25\";\n } else if (regexCustomName !== \"tool_search_tool_regex\") {\n providerToolName = \"tool_search_tool_regex\";\n } else {\n providerToolName = \"tool_search_tool_regex\";\n }\n }\n if (part.content.type === \"tool_search_tool_search_result\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n result: part.content.tool_references.map((ref) => ({\n type: ref.type,\n toolName: ref.tool_name\n }))\n });\n } else {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n isError: true,\n result: {\n type: \"tool_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n case \"mcp_tool_use\": {\n mcpToolCalls[part.id] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: JSON.stringify(part.input),\n providerExecuted: true,\n dynamic: true,\n providerMetadata: {\n anthropic: {\n type: \"mcp-tool-use\",\n serverName: part.server_name\n }\n }\n };\n controller.enqueue(mcpToolCalls[part.id]);\n return;\n }\n case \"mcp_tool_result\": {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: mcpToolCalls[part.tool_use_id].toolName,\n isError: part.is_error,\n result: part.content,\n dynamic: true,\n providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata\n });\n return;\n }\n default: {\n const _exhaustiveCheck = contentBlockType;\n throw new Error(\n `Unsupported content block type: ${_exhaustiveCheck}`\n );\n }\n }\n }\n case \"content_block_stop\": {\n if (contentBlocks[value.index] != null) {\n const contentBlock = contentBlocks[value.index];\n switch (contentBlock.type) {\n case \"text\": {\n controller.enqueue({\n type: \"text-end\",\n id: String(value.index)\n });\n break;\n }\n case \"reasoning\": {\n controller.enqueue({\n type: \"reasoning-end\",\n id: String(value.index)\n });\n break;\n }\n case \"tool-call\":\n const isJsonResponseTool = usesJsonResponseTool && contentBlock.toolName === \"json\";\n if (!isJsonResponseTool) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: contentBlock.toolCallId\n });\n let finalInput = contentBlock.input === \"\" ? \"{}\" : contentBlock.input;\n if (contentBlock.providerToolName === \"code_execution\") {\n try {\n const parsed = JSON.parse(finalInput);\n if (parsed != null && typeof parsed === \"object\" && \"code\" in parsed && !(\"type\" in parsed)) {\n finalInput = JSON.stringify({\n type: \"programmatic-tool-call\",\n ...parsed\n });\n }\n } catch (e) {\n }\n }\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: contentBlock.toolCallId,\n toolName: contentBlock.toolName,\n input: finalInput,\n providerExecuted: contentBlock.providerExecuted,\n ...contentBlock.caller && {\n providerMetadata: {\n anthropic: {\n caller: contentBlock.caller\n }\n }\n }\n });\n }\n break;\n }\n delete contentBlocks[value.index];\n }\n blockType = void 0;\n return;\n }\n case \"content_block_delta\": {\n const deltaType = value.delta.type;\n switch (deltaType) {\n case \"text_delta\": {\n if (usesJsonResponseTool) {\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta: value.delta.text\n });\n return;\n }\n case \"thinking_delta\": {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: value.delta.thinking\n });\n return;\n }\n case \"signature_delta\": {\n if (blockType === \"thinking\") {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: \"\",\n providerMetadata: {\n anthropic: {\n signature: value.delta.signature\n }\n }\n });\n }\n return;\n }\n case \"input_json_delta\": {\n const contentBlock = contentBlocks[value.index];\n let delta = value.delta.partial_json;\n if (delta.length === 0) {\n return;\n }\n if (isJsonResponseFromTool) {\n if ((contentBlock == null ? void 0 : contentBlock.type) !== \"text\") {\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta\n });\n } else {\n if ((contentBlock == null ? void 0 : contentBlock.type) !== \"tool-call\") {\n return;\n }\n if (contentBlock.firstDelta && (contentBlock.providerToolName === \"bash_code_execution\" || contentBlock.providerToolName === \"text_editor_code_execution\")) {\n delta = `{\"type\": \"${contentBlock.providerToolName}\",${delta.substring(1)}`;\n }\n controller.enqueue({\n type: \"tool-input-delta\",\n id: contentBlock.toolCallId,\n delta\n });\n contentBlock.input += delta;\n contentBlock.firstDelta = false;\n }\n return;\n }\n case \"citations_delta\": {\n const citation = value.delta.citation;\n const source = createCitationSource(\n citation,\n citationDocuments,\n generateId3\n );\n if (source) {\n controller.enqueue(source);\n }\n return;\n }\n default: {\n const _exhaustiveCheck = deltaType;\n throw new Error(\n `Unsupported delta type: ${_exhaustiveCheck}`\n );\n }\n }\n }\n case \"message_start\": {\n usage.input_tokens = value.message.usage.input_tokens;\n usage.cache_read_input_tokens = (_d = value.message.usage.cache_read_input_tokens) != null ? _d : 0;\n usage.cache_creation_input_tokens = (_e = value.message.usage.cache_creation_input_tokens) != null ? _e : 0;\n rawUsage = {\n ...value.message.usage\n };\n cacheCreationInputTokens = (_f = value.message.usage.cache_creation_input_tokens) != null ? _f : null;\n if (value.message.container != null) {\n container = {\n expiresAt: value.message.container.expires_at,\n id: value.message.container.id,\n skills: null\n };\n }\n if (value.message.stop_reason != null) {\n finishReason = {\n unified: mapAnthropicStopReason({\n finishReason: value.message.stop_reason,\n isJsonResponseFromTool\n }),\n raw: value.message.stop_reason\n };\n }\n controller.enqueue({\n type: \"response-metadata\",\n id: (_g = value.message.id) != null ? _g : void 0,\n modelId: (_h = value.message.model) != null ? _h : void 0\n });\n if (value.message.content != null) {\n for (let contentIndex = 0; contentIndex < value.message.content.length; contentIndex++) {\n const part = value.message.content[contentIndex];\n if (part.type === \"tool_use\") {\n const caller = part.caller;\n const callerInfo = caller ? {\n type: caller.type,\n toolId: \"tool_id\" in caller ? caller.tool_id : void 0\n } : void 0;\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: part.name\n });\n const inputStr = JSON.stringify((_i = part.input) != null ? _i : {});\n controller.enqueue({\n type: \"tool-input-delta\",\n id: part.id,\n delta: inputStr\n });\n controller.enqueue({\n type: \"tool-input-end\",\n id: part.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: inputStr,\n ...callerInfo && {\n providerMetadata: {\n anthropic: {\n caller: callerInfo\n }\n }\n }\n });\n }\n }\n }\n return;\n }\n case \"message_delta\": {\n if (value.usage.input_tokens != null && usage.input_tokens !== value.usage.input_tokens) {\n usage.input_tokens = value.usage.input_tokens;\n }\n usage.output_tokens = value.usage.output_tokens;\n if (value.usage.cache_read_input_tokens != null) {\n usage.cache_read_input_tokens = value.usage.cache_read_input_tokens;\n }\n if (value.usage.cache_creation_input_tokens != null) {\n usage.cache_creation_input_tokens = value.usage.cache_creation_input_tokens;\n cacheCreationInputTokens = value.usage.cache_creation_input_tokens;\n }\n finishReason = {\n unified: mapAnthropicStopReason({\n finishReason: value.delta.stop_reason,\n isJsonResponseFromTool\n }),\n raw: (_j = value.delta.stop_reason) != null ? _j : void 0\n };\n stopSequence = (_k = value.delta.stop_sequence) != null ? _k : null;\n container = value.delta.container != null ? {\n expiresAt: value.delta.container.expires_at,\n id: value.delta.container.id,\n skills: (_m = (_l = value.delta.container.skills) == null ? void 0 : _l.map((skill) => ({\n type: skill.type,\n skillId: skill.skill_id,\n version: skill.version\n }))) != null ? _m : null\n } : null;\n if (value.context_management) {\n contextManagement = mapAnthropicResponseContextManagement(\n value.context_management\n );\n }\n rawUsage = {\n ...rawUsage,\n ...value.usage\n };\n return;\n }\n case \"message_stop\": {\n const anthropicMetadata = {\n usage: rawUsage != null ? rawUsage : null,\n cacheCreationInputTokens,\n stopSequence,\n container,\n contextManagement\n };\n const providerMetadata = {\n anthropic: anthropicMetadata\n };\n if (usedCustomProviderKey && providerOptionsName !== \"anthropic\") {\n providerMetadata[providerOptionsName] = anthropicMetadata;\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertAnthropicMessagesUsage(usage),\n providerMetadata\n });\n return;\n }\n case \"error\": {\n controller.enqueue({ type: \"error\", error: value.error });\n return;\n }\n default: {\n const _exhaustiveCheck = value;\n throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n }\n }\n }\n })\n );\n const [streamForFirstChunk, streamForConsumer] = transformedStream.tee();\n const firstChunkReader = streamForFirstChunk.getReader();\n try {\n await firstChunkReader.read();\n let result = await firstChunkReader.read();\n if (((_a = result.value) == null ? void 0 : _a.type) === \"raw\") {\n result = await firstChunkReader.read();\n }\n if (((_b = result.value) == null ? void 0 : _b.type) === \"error\") {\n const error = result.value.error;\n throw new APICallError({\n message: error.message,\n url,\n requestBodyValues: body,\n statusCode: error.type === \"overloaded_error\" ? 529 : 500,\n responseHeaders,\n responseBody: JSON.stringify(error),\n isRetryable: error.type === \"overloaded_error\"\n });\n }\n } finally {\n firstChunkReader.cancel().catch(() => {\n });\n firstChunkReader.releaseLock();\n }\n return {\n stream: streamForConsumer,\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction getModelCapabilities(modelId) {\n if (modelId.includes(\"claude-sonnet-4-5\") || modelId.includes(\"claude-opus-4-5\") || modelId.includes(\"claude-haiku-4-5\")) {\n return {\n maxOutputTokens: 64e3,\n supportsStructuredOutput: true,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-opus-4-1\")) {\n return {\n maxOutputTokens: 32e3,\n supportsStructuredOutput: true,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-sonnet-4-\") || modelId.includes(\"claude-3-7-sonnet\")) {\n return {\n maxOutputTokens: 64e3,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-opus-4-\")) {\n return {\n maxOutputTokens: 32e3,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-3-5-haiku\")) {\n return {\n maxOutputTokens: 8192,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-3-haiku\")) {\n return {\n maxOutputTokens: 4096,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else {\n return {\n maxOutputTokens: 4096,\n supportsStructuredOutput: false,\n isKnownModel: false\n };\n }\n}\nfunction mapAnthropicResponseContextManagement(contextManagement) {\n return contextManagement ? {\n appliedEdits: contextManagement.applied_edits.map((edit) => {\n const strategy = edit.type;\n switch (strategy) {\n case \"clear_tool_uses_20250919\":\n return {\n type: edit.type,\n clearedToolUses: edit.cleared_tool_uses,\n clearedInputTokens: edit.cleared_input_tokens\n };\n case \"clear_thinking_20251015\":\n return {\n type: edit.type,\n clearedThinkingTurns: edit.cleared_thinking_turns,\n clearedInputTokens: edit.cleared_input_tokens\n };\n }\n }).filter((edit) => edit !== void 0)\n } : null;\n}\n\n// src/tool/bash_20241022.ts\nimport {\n createProviderToolFactory as createProviderToolFactory2,\n lazySchema as lazySchema9,\n zodSchema as zodSchema9\n} from \"@ai-sdk/provider-utils\";\nimport { z as z10 } from \"zod/v4\";\nvar bash_20241022InputSchema = lazySchema9(\n () => zodSchema9(\n z10.object({\n command: z10.string(),\n restart: z10.boolean().optional()\n })\n )\n);\nvar bash_20241022 = createProviderToolFactory2({\n id: \"anthropic.bash_20241022\",\n inputSchema: bash_20241022InputSchema\n});\n\n// src/tool/bash_20250124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory3,\n lazySchema as lazySchema10,\n zodSchema as zodSchema10\n} from \"@ai-sdk/provider-utils\";\nimport { z as z11 } from \"zod/v4\";\nvar bash_20250124InputSchema = lazySchema10(\n () => zodSchema10(\n z11.object({\n command: z11.string(),\n restart: z11.boolean().optional()\n })\n )\n);\nvar bash_20250124 = createProviderToolFactory3({\n id: \"anthropic.bash_20250124\",\n inputSchema: bash_20250124InputSchema\n});\n\n// src/tool/computer_20241022.ts\nimport {\n createProviderToolFactory as createProviderToolFactory4,\n lazySchema as lazySchema11,\n zodSchema as zodSchema11\n} from \"@ai-sdk/provider-utils\";\nimport { z as z12 } from \"zod/v4\";\nvar computer_20241022InputSchema = lazySchema11(\n () => zodSchema11(\n z12.object({\n action: z12.enum([\n \"key\",\n \"type\",\n \"mouse_move\",\n \"left_click\",\n \"left_click_drag\",\n \"right_click\",\n \"middle_click\",\n \"double_click\",\n \"screenshot\",\n \"cursor_position\"\n ]),\n coordinate: z12.array(z12.number().int()).optional(),\n text: z12.string().optional()\n })\n )\n);\nvar computer_20241022 = createProviderToolFactory4({\n id: \"anthropic.computer_20241022\",\n inputSchema: computer_20241022InputSchema\n});\n\n// src/tool/computer_20250124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory5,\n lazySchema as lazySchema12,\n zodSchema as zodSchema12\n} from \"@ai-sdk/provider-utils\";\nimport { z as z13 } from \"zod/v4\";\nvar computer_20250124InputSchema = lazySchema12(\n () => zodSchema12(\n z13.object({\n action: z13.enum([\n \"key\",\n \"hold_key\",\n \"type\",\n \"cursor_position\",\n \"mouse_move\",\n \"left_mouse_down\",\n \"left_mouse_up\",\n \"left_click\",\n \"left_click_drag\",\n \"right_click\",\n \"middle_click\",\n \"double_click\",\n \"triple_click\",\n \"scroll\",\n \"wait\",\n \"screenshot\"\n ]),\n coordinate: z13.tuple([z13.number().int(), z13.number().int()]).optional(),\n duration: z13.number().optional(),\n scroll_amount: z13.number().optional(),\n scroll_direction: z13.enum([\"up\", \"down\", \"left\", \"right\"]).optional(),\n start_coordinate: z13.tuple([z13.number().int(), z13.number().int()]).optional(),\n text: z13.string().optional()\n })\n )\n);\nvar computer_20250124 = createProviderToolFactory5({\n id: \"anthropic.computer_20250124\",\n inputSchema: computer_20250124InputSchema\n});\n\n// src/tool/computer_20251124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory6,\n lazySchema as lazySchema13,\n zodSchema as zodSchema13\n} from \"@ai-sdk/provider-utils\";\nimport { z as z14 } from \"zod/v4\";\nvar computer_20251124InputSchema = lazySchema13(\n () => zodSchema13(\n z14.object({\n action: z14.enum([\n \"key\",\n \"hold_key\",\n \"type\",\n \"cursor_position\",\n \"mouse_move\",\n \"left_mouse_down\",\n \"left_mouse_up\",\n \"left_click\",\n \"left_click_drag\",\n \"right_click\",\n \"middle_click\",\n \"double_click\",\n \"triple_click\",\n \"scroll\",\n \"wait\",\n \"screenshot\",\n \"zoom\"\n ]),\n coordinate: z14.tuple([z14.number().int(), z14.number().int()]).optional(),\n duration: z14.number().optional(),\n region: z14.tuple([\n z14.number().int(),\n z14.number().int(),\n z14.number().int(),\n z14.number().int()\n ]).optional(),\n scroll_amount: z14.number().optional(),\n scroll_direction: z14.enum([\"up\", \"down\", \"left\", \"right\"]).optional(),\n start_coordinate: z14.tuple([z14.number().int(), z14.number().int()]).optional(),\n text: z14.string().optional()\n })\n )\n);\nvar computer_20251124 = createProviderToolFactory6({\n id: \"anthropic.computer_20251124\",\n inputSchema: computer_20251124InputSchema\n});\n\n// src/tool/memory_20250818.ts\nimport {\n createProviderToolFactory as createProviderToolFactory7,\n lazySchema as lazySchema14,\n zodSchema as zodSchema14\n} from \"@ai-sdk/provider-utils\";\nimport { z as z15 } from \"zod/v4\";\nvar memory_20250818InputSchema = lazySchema14(\n () => zodSchema14(\n z15.discriminatedUnion(\"command\", [\n z15.object({\n command: z15.literal(\"view\"),\n path: z15.string(),\n view_range: z15.tuple([z15.number(), z15.number()]).optional()\n }),\n z15.object({\n command: z15.literal(\"create\"),\n path: z15.string(),\n file_text: z15.string()\n }),\n z15.object({\n command: z15.literal(\"str_replace\"),\n path: z15.string(),\n old_str: z15.string(),\n new_str: z15.string()\n }),\n z15.object({\n command: z15.literal(\"insert\"),\n path: z15.string(),\n insert_line: z15.number(),\n insert_text: z15.string()\n }),\n z15.object({\n command: z15.literal(\"delete\"),\n path: z15.string()\n }),\n z15.object({\n command: z15.literal(\"rename\"),\n old_path: z15.string(),\n new_path: z15.string()\n })\n ])\n )\n);\nvar memory_20250818 = createProviderToolFactory7({\n id: \"anthropic.memory_20250818\",\n inputSchema: memory_20250818InputSchema\n});\n\n// src/tool/text-editor_20241022.ts\nimport {\n createProviderToolFactory as createProviderToolFactory8,\n lazySchema as lazySchema15,\n zodSchema as zodSchema15\n} from \"@ai-sdk/provider-utils\";\nimport { z as z16 } from \"zod/v4\";\nvar textEditor_20241022InputSchema = lazySchema15(\n () => zodSchema15(\n z16.object({\n command: z16.enum([\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"]),\n path: z16.string(),\n file_text: z16.string().optional(),\n insert_line: z16.number().int().optional(),\n new_str: z16.string().optional(),\n insert_text: z16.string().optional(),\n old_str: z16.string().optional(),\n view_range: z16.array(z16.number().int()).optional()\n })\n )\n);\nvar textEditor_20241022 = createProviderToolFactory8({\n id: \"anthropic.text_editor_20241022\",\n inputSchema: textEditor_20241022InputSchema\n});\n\n// src/tool/text-editor_20250124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory9,\n lazySchema as lazySchema16,\n zodSchema as zodSchema16\n} from \"@ai-sdk/provider-utils\";\nimport { z as z17 } from \"zod/v4\";\nvar textEditor_20250124InputSchema = lazySchema16(\n () => zodSchema16(\n z17.object({\n command: z17.enum([\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"]),\n path: z17.string(),\n file_text: z17.string().optional(),\n insert_line: z17.number().int().optional(),\n new_str: z17.string().optional(),\n insert_text: z17.string().optional(),\n old_str: z17.string().optional(),\n view_range: z17.array(z17.number().int()).optional()\n })\n )\n);\nvar textEditor_20250124 = createProviderToolFactory9({\n id: \"anthropic.text_editor_20250124\",\n inputSchema: textEditor_20250124InputSchema\n});\n\n// src/tool/text-editor_20250429.ts\nimport {\n createProviderToolFactory as createProviderToolFactory10,\n lazySchema as lazySchema17,\n zodSchema as zodSchema17\n} from \"@ai-sdk/provider-utils\";\nimport { z as z18 } from \"zod/v4\";\nvar textEditor_20250429InputSchema = lazySchema17(\n () => zodSchema17(\n z18.object({\n command: z18.enum([\"view\", \"create\", \"str_replace\", \"insert\"]),\n path: z18.string(),\n file_text: z18.string().optional(),\n insert_line: z18.number().int().optional(),\n new_str: z18.string().optional(),\n insert_text: z18.string().optional(),\n old_str: z18.string().optional(),\n view_range: z18.array(z18.number().int()).optional()\n })\n )\n);\nvar textEditor_20250429 = createProviderToolFactory10({\n id: \"anthropic.text_editor_20250429\",\n inputSchema: textEditor_20250429InputSchema\n});\n\n// src/tool/tool-search-bm25_20251119.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema6,\n lazySchema as lazySchema18,\n zodSchema as zodSchema18\n} from \"@ai-sdk/provider-utils\";\nimport { z as z19 } from \"zod/v4\";\nvar toolSearchBm25_20251119OutputSchema = lazySchema18(\n () => zodSchema18(\n z19.array(\n z19.object({\n type: z19.literal(\"tool_reference\"),\n toolName: z19.string()\n })\n )\n )\n);\nvar toolSearchBm25_20251119InputSchema = lazySchema18(\n () => zodSchema18(\n z19.object({\n /**\n * A natural language query to search for tools.\n * Claude will use BM25 text search to find relevant tools.\n */\n query: z19.string(),\n /**\n * Maximum number of tools to return. Optional.\n */\n limit: z19.number().optional()\n })\n )\n);\nvar factory7 = createProviderToolFactoryWithOutputSchema6({\n id: \"anthropic.tool_search_bm25_20251119\",\n inputSchema: toolSearchBm25_20251119InputSchema,\n outputSchema: toolSearchBm25_20251119OutputSchema,\n supportsDeferredResults: true\n});\nvar toolSearchBm25_20251119 = (args = {}) => {\n return factory7(args);\n};\n\n// src/anthropic-tools.ts\nvar anthropicTools = {\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20241022,\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20250124,\n /**\n * Claude can analyze data, create visualizations, perform complex calculations,\n * run system commands, create and edit files, and process uploaded files directly within\n * the API conversation.\n *\n * The code execution tool allows Claude to run Bash commands and manipulate files,\n * including writing code, in a secure, sandboxed environment.\n */\n codeExecution_20250522,\n /**\n * Claude can analyze data, create visualizations, perform complex calculations,\n * run system commands, create and edit files, and process uploaded files directly within\n * the API conversation.\n *\n * The code execution tool allows Claude to run both Python and Bash commands and manipulate files,\n * including writing code, in a secure, sandboxed environment.\n *\n * This is the latest version with enhanced Bash support and file operations.\n */\n codeExecution_20250825,\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * Image results are supported.\n *\n * @param displayWidthPx - The width of the display being controlled by the model in pixels.\n * @param displayHeightPx - The height of the display being controlled by the model in pixels.\n * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.\n */\n computer_20241022,\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * Image results are supported.\n *\n * @param displayWidthPx - The width of the display being controlled by the model in pixels.\n * @param displayHeightPx - The height of the display being controlled by the model in pixels.\n * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.\n */\n computer_20250124,\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * This version adds the zoom action for detailed screen region inspection.\n *\n * Image results are supported.\n *\n * Supported models: Claude Opus 4.5\n *\n * @param displayWidthPx - The width of the display being controlled by the model in pixels.\n * @param displayHeightPx - The height of the display being controlled by the model in pixels.\n * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.\n * @param enableZoom - Enable zoom action. Set to true to allow Claude to zoom into specific screen regions. Default: false.\n */\n computer_20251124,\n /**\n * The memory tool enables Claude to store and retrieve information across conversations through a memory file directory.\n * Claude can create, read, update, and delete files that persist between sessions,\n * allowing it to build knowledge over time without keeping everything in the context window.\n * The memory tool operates client-side—you control where and how the data is stored through your own infrastructure.\n *\n * Supported models: Claude Sonnet 4.5, Claude Sonnet 4, Claude Opus 4.1, Claude Opus 4.\n */\n memory_20250818,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Supported models: Claude Sonnet 3.5\n */\n textEditor_20241022,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Supported models: Claude Sonnet 3.7\n */\n textEditor_20250124,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Note: This version does not support the \"undo_edit\" command.\n *\n * @deprecated Use textEditor_20250728 instead\n */\n textEditor_20250429,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Note: This version does not support the \"undo_edit\" command and adds optional max_characters parameter.\n *\n * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1\n *\n * @param maxCharacters - Optional maximum number of characters to view in the file\n */\n textEditor_20250728,\n /**\n * Creates a web fetch tool that gives Claude direct access to real-time web content.\n *\n * @param maxUses - The max_uses parameter limits the number of web fetches performed\n * @param allowedDomains - Only fetch from these domains\n * @param blockedDomains - Never fetch from these domains\n * @param citations - Unlike web search where citations are always enabled, citations are optional for web fetch. Set \"citations\": {\"enabled\": true} to enable Claude to cite specific passages from fetched documents.\n * @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context.\n */\n webFetch_20250910,\n /**\n * Creates a web search tool that gives Claude direct access to real-time web content.\n *\n * @param maxUses - Maximum number of web searches Claude can perform during the conversation.\n * @param allowedDomains - Optional list of domains that Claude is allowed to search.\n * @param blockedDomains - Optional list of domains that Claude should avoid when searching.\n * @param userLocation - Optional user location information to provide geographically relevant search results.\n */\n webSearch_20250305,\n /**\n * Creates a tool search tool that uses regex patterns to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand. Instead of loading all\n * tool definitions into the context window upfront, Claude searches your tool\n * catalog and loads only the tools it needs.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n *\n * Supported models: Claude Opus 4.5, Claude Sonnet 4.5\n */\n toolSearchRegex_20251119,\n /**\n * Creates a tool search tool that uses BM25 (natural language) to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand. Instead of loading all\n * tool definitions into the context window upfront, Claude searches your tool\n * catalog and loads only the tools it needs.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n *\n * Supported models: Claude Opus 4.5, Claude Sonnet 4.5\n */\n toolSearchBm25_20251119\n};\n\n// src/anthropic-provider.ts\nfunction createAnthropic(options = {}) {\n var _a, _b;\n const baseURL = (_a = withoutTrailingSlash(\n loadOptionalSetting({\n settingValue: options.baseURL,\n environmentVariableName: \"ANTHROPIC_BASE_URL\"\n })\n )) != null ? _a : \"https://api.anthropic.com/v1\";\n const providerName = (_b = options.name) != null ? _b : \"anthropic.messages\";\n if (options.apiKey && options.authToken) {\n throw new InvalidArgumentError({\n argument: \"apiKey/authToken\",\n message: \"Both apiKey and authToken were provided. Please use only one authentication method.\"\n });\n }\n const getHeaders = () => {\n const authHeaders = options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {\n \"x-api-key\": loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"ANTHROPIC_API_KEY\",\n description: \"Anthropic\"\n })\n };\n return withUserAgentSuffix(\n {\n \"anthropic-version\": \"2023-06-01\",\n ...authHeaders,\n ...options.headers\n },\n `ai-sdk/anthropic/${VERSION}`\n );\n };\n const createChatModel = (modelId) => {\n var _a2;\n return new AnthropicMessagesLanguageModel(modelId, {\n provider: providerName,\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: (_a2 = options.generateId) != null ? _a2 : generateId2,\n supportedUrls: () => ({\n \"image/*\": [/^https?:\\/\\/.*$/],\n \"application/pdf\": [/^https?:\\/\\/.*$/]\n })\n });\n };\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Anthropic model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.messages = createChatModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n provider.tools = anthropicTools;\n return provider;\n}\nvar anthropic = createAnthropic();\n\n// src/forward-anthropic-container-id-from-last-step.ts\nfunction forwardAnthropicContainerIdFromLastStep({\n steps\n}) {\n var _a, _b, _c;\n for (let i = steps.length - 1; i >= 0; i--) {\n const containerId = (_c = (_b = (_a = steps[i].providerMetadata) == null ? void 0 : _a.anthropic) == null ? void 0 : _b.container) == null ? void 0 : _c.id;\n if (containerId) {\n return {\n providerOptions: {\n anthropic: {\n container: { id: containerId }\n }\n }\n };\n }\n }\n return void 0;\n}\nexport {\n VERSION,\n anthropic,\n createAnthropic,\n forwardAnthropicContainerIdFromLastStep\n};\n//# sourceMappingURL=index.mjs.map","/**\n * Agent Prompts - Centralized prompt definitions for the live agent.\n *\n * All hardcoded prompts are defined here for easy review, modification,\n * and future configurability. This file serves as the single source of\n * truth for agent behavior instructions.\n */\n\n// =============================================================================\n// System Prompts\n// =============================================================================\n\n/**\n * Default system prompt for the live agent.\n *\n * This is the base instruction set that defines the agent's core behavior\n * for form filling. It emphasizes accuracy over completeness and prohibits\n * fabrication of data.\n */\nexport const DEFAULT_SYSTEM_PROMPT = `# Form Instructions\n\nResearch and fill the form fields using all available tools. Focus on accuracy over completeness.\n\n## Guidelines\n1. Address required fields first (severity: \"required\"), then optional fields (severity: \"recommended\")\n2. NEVER fabricate or guess information - only use data you can verify\n3. If you cannot find verifiable information, use skip_field with a reason\n\n## Patch Format Examples\n\nUse the fill_form tool with patches in these formats:\n\n| Type | Example |\n|------|---------|\n| string | \\`{ op: \"set_string\", fieldId: \"name\", value: \"Acme Corp\" }\\` |\n| number | \\`{ op: \"set_number\", fieldId: \"age\", value: 32 }\\` |\n| string_list | \\`{ op: \"set_string_list\", fieldId: \"tags\", value: [\"ai\", \"ml\"] }\\` |\n| url | \\`{ op: \"set_url\", fieldId: \"website\", value: \"https://example.com\" }\\` |\n| url_list | \\`{ op: \"set_url_list\", fieldId: \"sources\", value: [\"https://a.com\", \"https://b.com\"] }\\` |\n| date | \\`{ op: \"set_date\", fieldId: \"event_date\", value: \"2024-06-15\" }\\` |\n| year | \\`{ op: \"set_year\", fieldId: \"founded\", value: 2024 }\\` |\n| single_select | \\`{ op: \"set_single_select\", fieldId: \"priority\", value: \"high\" }\\` |\n| multi_select | \\`{ op: \"set_multi_select\", fieldId: \"categories\", value: [\"frontend\", \"backend\"] }\\` |\n| checkboxes | \\`{ op: \"set_checkboxes\", fieldId: \"tasks\", value: { \"task1\": \"done\", \"task2\": \"todo\" } }\\` |\n| table | \\`{ op: \"set_table\", fieldId: \"team\", value: [{ \"name\": \"Alice\", \"role\": \"Engineer\" }] }\\` |\n\n## Important: checkboxes vs multi_select\n\nThese two types look similar but have DIFFERENT value formats:\n\n- **multi_select** → array of option IDs: \\`[\"opt1\", \"opt2\"]\\`\n- **checkboxes** → object mapping IDs to states: \\`{ \"opt1\": \"done\", \"opt2\": \"todo\" }\\`\n\n**Checkbox states by mode:**\n- Mode \"simple\": \\`\"done\"\\` or \\`\"todo\"\\`\n- Mode \"multi\": \\`\"done\"\\`, \\`\"todo\"\\`, \\`\"incomplete\"\\`, \\`\"active\"\\`, or \\`\"na\"\\`\n- Mode \"explicit\": \\`\"yes\"\\` or \\`\"no\"\\` (if unknown, use abort_field)\n\n**WRONG:** \\`{ op: \"set_checkboxes\", value: [\"task1\", \"task2\"] }\\`\n**RIGHT:** \\`{ op: \"set_checkboxes\", value: { \"task1\": \"done\", \"task2\": \"done\" } }\\`\n\n## Skipping Fields\n\nIf you cannot find verifiable information:\n\\`{ op: \"skip_field\", fieldId: \"...\", reason: \"Could not find verified data\" }\\`\n`;\n\n/**\n * Web search instructions appended when web search tools are available.\n *\n * These instructions enforce that the agent must verify all information\n * through web search before filling fields.\n */\nexport const WEB_SEARCH_INSTRUCTIONS = `# Web Search\nYou have access to web search tools. You MUST use them to verify ALL information before filling fields.\n\nGuidelines:\n1. Search for official sources (company websites, Crunchbase, LinkedIn, press releases)\n2. Cross-reference information across multiple sources when possible\n3. Only fill fields with data you found and verified through search\n4. If a search returns no results or uncertain information, use skip_field with a reason explaining what you searched for\n5. NEVER fill fields with guessed or assumed information\n`;\n\n// =============================================================================\n// Context Prompt Templates\n// =============================================================================\n\n/**\n * Header for the issues section in the context prompt.\n */\nexport const ISSUES_HEADER = '# Current Form Issues';\n\n/**\n * Template for the issues intro text.\n * @param issueCount - Actual number of issues shown\n */\nexport function getIssuesIntro(issueCount: number): string {\n return `You need to address ${issueCount} issue${issueCount === 1 ? '' : 's'}. Here are the current issues:`;\n}\n\n/**\n * Patch format examples by field kind.\n *\n * This is the single source of truth for patch format documentation.\n * Used in PATCH_FORMAT_INSTRUCTIONS and rejection feedback hints.\n */\nexport const PATCH_FORMATS: Record<string, string> = {\n string: '{ op: \"set_string\", fieldId: \"...\", value: \"text here\" }',\n number: '{ op: \"set_number\", fieldId: \"...\", value: 42 }',\n string_list: '{ op: \"set_string_list\", fieldId: \"...\", value: [\"item1\", \"item2\"] }',\n single_select: '{ op: \"set_single_select\", fieldId: \"...\", value: \"option_id\" }',\n multi_select: '{ op: \"set_multi_select\", fieldId: \"...\", value: [\"opt1\", \"opt2\"] }',\n checkboxes: '{ op: \"set_checkboxes\", fieldId: \"...\", value: { \"opt1\": \"done\", \"opt2\": \"todo\" } }',\n url: '{ op: \"set_url\", fieldId: \"...\", value: \"https://example.com\" }',\n url_list: '{ op: \"set_url_list\", fieldId: \"...\", value: [\"https://a.com\", \"https://b.com\"] }',\n date: '{ op: \"set_date\", fieldId: \"...\", value: \"2024-06-15\" }',\n year: '{ op: \"set_year\", fieldId: \"...\", value: 2024 }',\n table: '{ op: \"set_table\", fieldId: \"...\", value: [{ col1: \"val1\", col2: \"val2\" }] }',\n};\n\n/**\n * Checkbox-mode-specific format hints.\n * Used to provide clearer examples based on the checkbox mode.\n */\nexport const CHECKBOX_MODE_HINTS: Record<string, string> = {\n simple: '{ \"opt1\": \"done\", \"opt2\": \"todo\" } // states: done, todo',\n multi:\n '{ \"opt1\": \"todo\", \"opt2\": \"todo\", \"opt3\": \"done\", \"opt4\": \"incomplete\", \"opt5\": \"active\", \"opt6\": \"na\" } // states: done, todo, incomplete, active, na',\n explicit: '{ \"opt1\": \"yes\", \"opt2\": \"no\" } // states: yes, no',\n};\n\n/**\n * Options for generating patch format hints.\n */\nexport interface PatchFormatHintOptions {\n fieldId?: string;\n columnIds?: string[];\n checkboxMode?: 'simple' | 'multi' | 'explicit';\n optionIds?: string[];\n}\n\n/**\n * Get the correct patch format for a field kind.\n *\n * @param fieldKind - The field kind (e.g., \"table\", \"string\")\n * @param options - Optional configuration for the hint\n * @returns The patch format example string\n */\nexport function getPatchFormatHint(\n fieldKind: string,\n fieldIdOrOptions?: string | PatchFormatHintOptions,\n columnIds?: string[],\n): string {\n // Handle legacy call signature: getPatchFormatHint(kind, fieldId, columnIds)\n let options: PatchFormatHintOptions = {};\n if (typeof fieldIdOrOptions === 'string') {\n options = { fieldId: fieldIdOrOptions, columnIds };\n } else if (fieldIdOrOptions) {\n options = fieldIdOrOptions;\n }\n\n let format = PATCH_FORMATS[fieldKind];\n if (!format) {\n return `Use the correct set_${fieldKind} operation for this field type.`;\n }\n\n // Substitute field ID if provided\n if (options.fieldId) {\n format = format.replace('fieldId: \"...\"', `fieldId: \"${options.fieldId}\"`);\n }\n\n // For checkboxes, use mode-specific hints with actual option IDs if available\n if (fieldKind === 'checkboxes') {\n const mode = options.checkboxMode ?? 'multi';\n const optIds = options.optionIds ?? ['opt1', 'opt2'];\n const stateMap: Record<string, [string, string]> = {\n simple: ['done', 'todo'],\n multi: ['done', 'todo'],\n explicit: ['yes', 'no'],\n };\n const [state1, state2] = stateMap[mode] ?? ['done', 'todo'];\n\n // Build concrete example with actual option IDs\n const valueExample =\n optIds.length >= 2\n ? `{ \"${optIds[0]}\": \"${state1}\", \"${optIds[1]}\": \"${state2}\" }`\n : optIds.length === 1\n ? `{ \"${optIds[0]}\": \"${state1}\" }`\n : `{ \"opt1\": \"${state1}\", \"opt2\": \"${state2}\" }`;\n\n format = format.replace('{ \"opt1\": \"done\", \"opt2\": \"todo\" }', valueExample);\n }\n\n // For table fields, show actual column IDs if available\n if (fieldKind === 'table' && options.columnIds && options.columnIds.length > 0) {\n const colExample = options.columnIds.map((id) => `\"${id}\": \"...\"`).join(', ');\n format = format.replace('{ col1: \"val1\", col2: \"val2\" }', `{ ${colExample} }`);\n }\n\n return format;\n}\n\n/**\n * Instructions section for the context prompt.\n *\n * This explains the patch format for each field kind.\n * Generated from PATCH_FORMATS to ensure consistency.\n */\nexport const PATCH_FORMAT_INSTRUCTIONS = `# Instructions\n\nUse the fill_form tool to submit patches for the fields above.\nEach patch should match the field kind:\n${Object.entries(PATCH_FORMATS)\n .map(([kind, format]) => `- ${kind}: ${format}`)\n .join('\\n')}\n\nFor table fields, use the column IDs shown in the field schema. Each row is an object with column ID keys.\n\nIf you cannot find verifiable information for a field, skip it:\n- skip: { op: \"skip_field\", fieldId: \"...\", reason: \"Information not available\" }`;\n\n/**\n * Simplified general instructions for use with inline field instructions.\n *\n * When inline field instructions are shown after each issue, we only need\n * general guidance about using the fill_form tool.\n */\nexport const GENERAL_INSTRUCTIONS = `# General Instructions\n\nUse the fill_form tool to submit patches for the fields above.\nFor table fields, each row is an object with column ID keys.`;\n\n// =============================================================================\n// Section Headers\n// =============================================================================\n\n/**\n * Section headers used when building the composed system prompt.\n */\nexport const SECTION_HEADERS = {\n formInstructions: '# Form Instructions',\n roleInstructions: (role: string) => `# Instructions for ${role} role`,\n roleGuidance: '# Role guidance',\n fieldInstructions: '# Field-specific instructions',\n additionalContext: '# Additional Context',\n} as const;\n","/**\n * Tool API Definitions\n *\n * Single source of truth for all LLM tool names, descriptions, and schemas.\n * This file defines the contract between markform and LLM agents.\n */\n\n// =============================================================================\n// Tool Names\n// =============================================================================\n\n/** The primary tool for filling form fields */\nexport const FILL_FORM_TOOL_NAME = 'fill_form';\n\n// =============================================================================\n// Tool Descriptions\n// =============================================================================\n\n/** Description shown to LLMs for the fill_form tool */\nexport const FILL_FORM_TOOL_DESCRIPTION =\n 'Fill form fields by submitting patches. Each patch sets a value for one field. ' +\n 'Use the field IDs from the issues list. Return patches for all issues you can address.';\n\n// =============================================================================\n// Patch Operations\n// =============================================================================\n\n/** All valid patch operation names */\nexport const PATCH_OPERATIONS = [\n 'set_string',\n 'set_number',\n 'set_string_list',\n 'set_checkboxes',\n 'set_single_select',\n 'set_multi_select',\n 'set_url',\n 'set_url_list',\n 'set_date',\n 'set_year',\n 'set_table',\n 'clear_field',\n 'skip_field',\n 'abort_field',\n] as const;\n\nexport type PatchOperation = (typeof PATCH_OPERATIONS)[number];\n","/**\n * Live Agent - LLM-powered agent for form filling.\n *\n * Uses AI SDK to call an LLM that fills forms autonomously\n * by analyzing issues and generating appropriate patches.\n */\n\nimport type { LanguageModel, Tool } from 'ai';\nimport { generateText, stepCountIs, zodSchema } from 'ai';\nimport { z } from 'zod';\nimport { openai } from '@ai-sdk/openai';\nimport { anthropic } from '@ai-sdk/anthropic';\nimport { google } from '@ai-sdk/google';\nimport { xai } from '@ai-sdk/xai';\n\nimport type {\n DocumentationBlock,\n InspectIssue,\n ParsedForm,\n Patch,\n PatchRejection,\n WireFormat,\n WireResponseStep,\n} from '../engine/coreTypes.js';\nimport { PatchSchema } from '../engine/coreTypes.js';\nimport { serializeForm } from '../engine/serialize.js';\nimport { DEFAULT_ROLE_INSTRUCTIONS, AGENT_ROLE, DEFAULT_MAX_STEPS_PER_TURN } from '../settings.js';\nimport { getWebSearchConfig } from '../llms.js';\nimport type {\n Agent,\n AgentResponse,\n FillCallbacks,\n LiveAgentConfig,\n TurnStats,\n} from './harnessTypes.js';\nimport {\n DEFAULT_SYSTEM_PROMPT,\n WEB_SEARCH_INSTRUCTIONS,\n ISSUES_HEADER,\n getIssuesIntro,\n GENERAL_INSTRUCTIONS,\n SECTION_HEADERS,\n getPatchFormatHint,\n} from './prompts.js';\nimport { FILL_FORM_TOOL_NAME, FILL_FORM_TOOL_DESCRIPTION } from './toolApi.js';\n\n// Re-export types for backwards compatibility\nexport type { LiveAgentConfig } from './harnessTypes.js';\n\n// =============================================================================\n// Live Agent Implementation\n// =============================================================================\n\n/**\n * Live agent that uses an LLM to generate patches.\n */\nexport class LiveAgent implements Agent {\n private model: LanguageModel;\n private maxStepsPerTurn: number;\n private systemPromptAddition?: string;\n private targetRole: string;\n private provider?: string;\n private enableWebSearch: boolean;\n private webSearchTools: Record<string, Tool> | null = null;\n private additionalTools: Record<string, Tool>;\n private callbacks?: FillCallbacks;\n private executionId: string;\n private toolChoice: 'auto' | 'required';\n\n constructor(config: LiveAgentConfig) {\n this.model = config.model;\n this.maxStepsPerTurn = config.maxStepsPerTurn ?? DEFAULT_MAX_STEPS_PER_TURN;\n this.systemPromptAddition = config.systemPromptAddition;\n this.targetRole = config.targetRole ?? AGENT_ROLE;\n this.provider = config.provider;\n this.enableWebSearch = config.enableWebSearch;\n this.additionalTools = config.additionalTools ?? {};\n this.callbacks = config.callbacks;\n this.executionId = config.executionId ?? '0-serial';\n // TODO: Make toolChoice configurable per-model or per-form in the future.\n // For now, 'required' is always safe since Markform agents must use tools.\n // Some models (e.g., gpt-5-mini) don't reliably call tools with 'auto'.\n this.toolChoice = config.toolChoice ?? 'required';\n\n // Eagerly load web search tools to enable early logging\n if (this.enableWebSearch && this.provider) {\n this.webSearchTools = loadWebSearchTools(this.provider);\n }\n }\n\n /**\n * Get list of available tool names for this agent.\n * Useful for logging what capabilities the agent has.\n */\n getAvailableToolNames(): string[] {\n const tools = [FILL_FORM_TOOL_NAME];\n if (this.webSearchTools) {\n tools.push(...Object.keys(this.webSearchTools));\n }\n // Add custom tool names (may overlap with web search if replacing)\n tools.push(...Object.keys(this.additionalTools));\n // Dedupe in case custom tools replace built-in\n return [...new Set(tools)];\n }\n\n /**\n * Invoke the fill_form tool using the LLM.\n *\n * Each call is stateless - the full form context is provided fresh each turn.\n * The form itself carries all state (filled values, remaining issues).\n * Returns patches and per-turn stats for observability.\n *\n * @param issues - Current issues to address\n * @param form - Current form state\n * @param maxPatches - Maximum patches to generate\n * @param previousRejections - Rejections from previous turn (helps LLM learn from mistakes)\n */\n async fillFormTool(\n issues: InspectIssue[],\n form: ParsedForm,\n maxPatches: number,\n previousRejections?: PatchRejection[],\n ): Promise<AgentResponse> {\n // Build context prompt with issues and form schema (include previous rejections if any)\n const contextPrompt = buildContextPrompt(issues, form, maxPatches, previousRejections);\n\n // Build composed system prompt from form instructions\n let systemPrompt = buildSystemPrompt(form, this.targetRole, issues);\n\n // Append additional context if provided (never overrides form instructions)\n if (this.systemPromptAddition) {\n systemPrompt += '\\n\\n# Additional Context\\n' + this.systemPromptAddition;\n }\n\n // Web search tools are loaded in constructor, but check again for runtime changes\n if (this.enableWebSearch && this.provider && !this.webSearchTools) {\n this.webSearchTools = loadWebSearchTools(this.provider);\n }\n\n // If web search is available, add instructions to use it\n if (this.webSearchTools && Object.keys(this.webSearchTools).length > 0) {\n systemPrompt += '\\n\\n' + WEB_SEARCH_INSTRUCTIONS;\n }\n\n // Define the patch tool with properly typed parameters\n const patchesSchema = z.object({\n patches: z\n .array(PatchSchema)\n .max(maxPatches)\n .describe('Array of patches. Each patch sets a value for one field.'),\n });\n\n // Create tool using zodSchema wrapper for AI SDK v6 compatibility\n const fillFormToolDef: Tool = {\n description: FILL_FORM_TOOL_DESCRIPTION,\n inputSchema: zodSchema(patchesSchema),\n };\n\n // Combine all tools (custom tools win on name collision)\n const rawTools: Record<string, Tool> = {\n [FILL_FORM_TOOL_NAME]: fillFormToolDef,\n ...this.webSearchTools,\n ...this.additionalTools,\n };\n\n // Wrap tools with callbacks for observability\n const tools = wrapToolsWithCallbacks(rawTools, this.callbacks, this.provider, this.executionId);\n\n // Get model ID for callbacks (may not be available on all model types)\n const modelId = (this.model as { modelId?: string }).modelId ?? 'unknown';\n\n // Call onLlmCallStart callback (errors don't abort)\n if (this.callbacks?.onLlmCallStart) {\n try {\n this.callbacks.onLlmCallStart({\n model: modelId,\n executionId: this.executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Call the model (stateless - full context provided each turn)\n const result = await generateText({\n model: this.model,\n system: systemPrompt,\n prompt: contextPrompt,\n tools,\n toolChoice: this.toolChoice,\n stopWhen: stepCountIs(this.maxStepsPerTurn),\n });\n\n // Call onLlmCallEnd callback (errors don't abort)\n if (this.callbacks?.onLlmCallEnd) {\n try {\n this.callbacks.onLlmCallEnd({\n model: modelId,\n inputTokens: result.usage?.inputTokens ?? 0,\n outputTokens: result.usage?.outputTokens ?? 0,\n executionId: this.executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Extract patches from tool calls and count tool usage\n const patches: Patch[] = [];\n const toolCallCounts = new Map<string, number>();\n\n for (const step of result.steps) {\n for (const toolCall of step.toolCalls) {\n // Count tool calls\n const count = toolCallCounts.get(toolCall.toolName) ?? 0;\n toolCallCounts.set(toolCall.toolName, count + 1);\n\n // Extract patches from fill_form calls and emit tool events\n // (fill_form is declarative so doesn't go through wrapToolsWithCallbacks)\n if (toolCall.toolName === FILL_FORM_TOOL_NAME && 'input' in toolCall) {\n const input = toolCall.input as { patches: Patch[] };\n const startTime = Date.now();\n\n // Emit onToolStart for fill_form\n if (this.callbacks?.onToolStart) {\n try {\n this.callbacks.onToolStart({\n name: FILL_FORM_TOOL_NAME,\n input,\n executionId: this.executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n patches.push(...input.patches);\n\n // Emit onToolEnd for fill_form\n if (this.callbacks?.onToolEnd) {\n try {\n this.callbacks.onToolEnd({\n name: FILL_FORM_TOOL_NAME,\n output: { patchCount: input.patches.length },\n durationMs: Date.now() - startTime,\n executionId: this.executionId,\n error: undefined,\n });\n } catch {\n // Ignore callback errors\n }\n }\n }\n }\n }\n\n // Build tool call stats\n const toolCalls: TurnStats['toolCalls'] = [];\n for (const [name, count] of toolCallCounts) {\n toolCalls.push({ name, count });\n }\n\n // Count remaining issues by severity\n const requiredRemaining = issues.filter((i) => i.severity === 'required').length;\n const optionalRemaining = issues.filter((i) => i.severity === 'recommended').length;\n\n // Build wire format for session logging (captures complete request/response)\n const wire = buildWireFormat(systemPrompt, contextPrompt, rawTools, result);\n\n // Build stats\n const stats: TurnStats = {\n inputTokens: result.usage?.inputTokens,\n outputTokens: result.usage?.outputTokens,\n toolCalls,\n formProgress: {\n // Note: these are the counts BEFORE this turn's patches are applied\n // The caller will update these after applying patches\n answeredFields: Object.values(form.responsesByFieldId).filter(\n (response) => response?.state === 'answered',\n ).length,\n skippedFields: Object.values(form.responsesByFieldId).filter(\n (response) => response?.state === 'skipped',\n ).length,\n requiredRemaining,\n optionalRemaining,\n },\n prompts: {\n system: systemPrompt,\n context: contextPrompt,\n },\n wire,\n };\n\n // Limit to maxPatches and return with stats\n return {\n patches: patches.slice(0, maxPatches),\n stats,\n };\n }\n}\n\n// =============================================================================\n// Wire Format Capture Helpers\n// =============================================================================\n\n/**\n * Extract tool schemas from tools object for wire format logging.\n * Captures description and inputSchema for each tool.\n */\nfunction extractToolSchemas(\n tools: Record<string, Tool>,\n): Record<string, { description: string; inputSchema: unknown }> {\n const schemas: Record<string, { description: string; inputSchema: unknown }> = {};\n\n // Sort tool names for deterministic ordering\n const sortedNames = Object.keys(tools).sort();\n for (const name of sortedNames) {\n const tool = tools[name];\n if (tool) {\n schemas[name] = {\n description: tool.description ?? '',\n // Extract the JSON schema from the tool's inputSchema\n // The AI SDK Tool type has inputSchema as a JsonSchema object\n inputSchema: sortObjectKeys(tool.inputSchema ?? {}),\n };\n }\n }\n return schemas;\n}\n\n/**\n * Sort object keys recursively for deterministic serialization.\n * This ensures wire format is stable across runs for diffing.\n */\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') return obj;\n if (Array.isArray(obj)) return obj.map(sortObjectKeys);\n\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj as Record<string, unknown>).sort()) {\n sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n/**\n * Build wire format from generateText result.\n * Captures complete request/response for session logging.\n *\n * Uses loose typing to handle AI SDK's complex result structure.\n */\nfunction buildWireFormat(\n systemPrompt: string,\n contextPrompt: string,\n tools: Record<string, Tool>,\n result: {\n steps: {\n toolCalls: { toolName: string; input?: unknown }[];\n toolResults?: { toolName: string; result?: unknown }[];\n text?: string | null;\n }[];\n usage?: { inputTokens?: number; outputTokens?: number };\n },\n): WireFormat {\n // Build response steps (omit toolCallId for stability)\n const steps: WireResponseStep[] = result.steps.map((step) => ({\n toolCalls: step.toolCalls.map((tc) => ({\n toolName: tc.toolName,\n input: sortObjectKeys(tc.input),\n })),\n toolResults: (step.toolResults ?? []).map((tr) => ({\n toolName: tr.toolName,\n result: sortObjectKeys(tr.result),\n })),\n text: step.text ?? null,\n }));\n\n return {\n request: {\n system: systemPrompt,\n prompt: contextPrompt,\n tools: extractToolSchemas(tools),\n },\n response: {\n steps,\n usage: {\n inputTokens: result.usage?.inputTokens ?? 0,\n outputTokens: result.usage?.outputTokens ?? 0,\n },\n },\n };\n}\n\n// =============================================================================\n// Context Building\n// =============================================================================\n\n/**\n * Extract doc blocks of a specific tag type for a given ref.\n */\nfunction getDocBlocks(docs: DocumentationBlock[], ref: string, tag: string): DocumentationBlock[] {\n return docs.filter((d) => d.ref === ref && d.tag === tag);\n}\n\n/**\n * Build a composed system prompt from form instructions.\n *\n * Instruction sources (later ones augment earlier):\n * 1. Base form instructions - Doc blocks with ref=formId and tag=\"instructions\"\n * 2. Role-specific instructions - From form.metadata.roleInstructions[targetRole]\n * 3. Per-field instructions - Doc blocks with ref=fieldId and tag=\"instructions\"\n * 4. System defaults - DEFAULT_ROLE_INSTRUCTIONS[targetRole] or DEFAULT_SYSTEM_PROMPT\n */\nfunction buildSystemPrompt(form: ParsedForm, targetRole: string, issues: InspectIssue[]): string {\n const sections: string[] = [];\n\n // Start with base system prompt guidelines\n sections.push(DEFAULT_SYSTEM_PROMPT);\n\n // 1. Form-level instructions (doc blocks with kind=\"instructions\" for the form)\n const formInstructions = getDocBlocks(form.docs, form.schema.id, 'instructions');\n if (formInstructions.length > 0) {\n sections.push('');\n sections.push(SECTION_HEADERS.formInstructions);\n for (const doc of formInstructions) {\n sections.push(doc.bodyMarkdown.trim());\n }\n }\n\n // 2. Role-specific instructions from frontmatter\n const roleInstructions = form.metadata?.roleInstructions?.[targetRole];\n if (roleInstructions) {\n sections.push('');\n sections.push(SECTION_HEADERS.roleInstructions(targetRole));\n sections.push(roleInstructions);\n } else {\n // Fallback to default role instructions\n const defaultRoleInstr = DEFAULT_ROLE_INSTRUCTIONS[targetRole];\n if (defaultRoleInstr) {\n sections.push('');\n sections.push(SECTION_HEADERS.roleGuidance);\n sections.push(defaultRoleInstr);\n }\n }\n\n // 3. Per-field instructions for fields being addressed\n const fieldIds = new Set(issues.filter((i) => i.scope === 'field').map((i) => i.ref));\n const fieldInstructions: string[] = [];\n\n for (const fieldId of fieldIds) {\n const fieldDocs = getDocBlocks(form.docs, fieldId, 'instructions');\n if (fieldDocs.length > 0) {\n for (const doc of fieldDocs) {\n fieldInstructions.push(`**${fieldId}:** ${doc.bodyMarkdown.trim()}`);\n }\n }\n }\n\n if (fieldInstructions.length > 0) {\n sections.push('');\n sections.push(SECTION_HEADERS.fieldInstructions);\n sections.push(...fieldInstructions);\n }\n\n return sections.join('\\n');\n}\n\n/**\n * Build a context prompt with full form state and remaining issues.\n *\n * The form markdown shows the agent exactly what's been filled so far,\n * making each turn stateless - all state is in the form itself.\n *\n * @param issues - Current issues to address\n * @param form - Current form state\n * @param maxPatches - Maximum patches to generate\n * @param previousRejections - Rejections from previous turn (helps LLM learn from mistakes)\n */\nfunction buildContextPrompt(\n issues: InspectIssue[],\n form: ParsedForm,\n maxPatches: number,\n previousRejections?: PatchRejection[],\n): string {\n const lines: string[] = [];\n\n // If there were rejections from previous turn, show them first so the model learns\n if (previousRejections && previousRejections.length > 0) {\n lines.push('# Previous Patch Errors');\n lines.push('');\n lines.push(\n 'Your previous patches were rejected due to the following errors. Please fix these issues:',\n );\n lines.push('');\n for (const rejection of previousRejections) {\n lines.push(`- **Error:** ${rejection.message}`);\n // If we have field info, explain the type mismatch and show correct format\n if (rejection.fieldKind) {\n lines.push(\n ` **Correction:** This field is type \"${rejection.fieldKind}\". Use set_${rejection.fieldKind} instead.`,\n );\n const hint = getPatchFormatHint(\n rejection.fieldKind,\n rejection.fieldId,\n rejection.columnIds,\n );\n lines.push(` **Correct format:** ${hint}`);\n }\n }\n lines.push('');\n }\n\n // Include full form markdown so agent sees current state\n lines.push('# Current Form State');\n lines.push('');\n lines.push('Below is the complete form with all currently filled values.');\n lines.push('Fields marked with `[ ]` or empty values still need to be filled.');\n lines.push('');\n lines.push('```markdown');\n lines.push(serializeForm(form));\n lines.push('```');\n lines.push('');\n\n // List remaining issues\n lines.push(ISSUES_HEADER);\n lines.push('');\n lines.push(getIssuesIntro(issues.length));\n lines.push('');\n\n for (const issue of issues) {\n lines.push(`- **${issue.ref}** (${issue.scope}): ${issue.message}`);\n lines.push(` Severity: ${issue.severity}, Priority: P${issue.priority}`);\n\n // If it's a field issue, include field schema info and inline instructions\n if (issue.scope === 'field') {\n const field = findField(form, issue.ref);\n if (field) {\n lines.push(` Type: ${field.kind}`);\n\n // Collect option IDs for fields with options\n let optionIds: string[] | undefined;\n if ('options' in field && field.options) {\n optionIds = field.options.map((o) => o.id);\n lines.push(` Options: ${optionIds.join(', ')}`);\n }\n\n // Show checkbox mode\n let checkboxMode: 'simple' | 'multi' | 'explicit' | undefined;\n if (field.kind === 'checkboxes' && 'checkboxMode' in field) {\n checkboxMode = (field.checkboxMode as 'simple' | 'multi' | 'explicit') ?? 'multi';\n lines.push(` Mode: ${checkboxMode}`);\n }\n\n // For table fields, show column IDs so the model knows the expected row structure\n let columnIds: string[] | undefined;\n if (field.kind === 'table' && 'columns' in field && field.columns) {\n columnIds = field.columns.map((c) => c.id);\n const columnInfo = field.columns\n .map((c) => `${c.id}${c.required ? ' (required)' : ''}`)\n .join(', ');\n lines.push(` Columns: ${columnInfo}`);\n if (field.minRows !== undefined || field.maxRows !== undefined) {\n const constraints = [];\n if (field.minRows !== undefined) constraints.push(`min: ${field.minRows}`);\n if (field.maxRows !== undefined) constraints.push(`max: ${field.maxRows}`);\n lines.push(` Rows: ${constraints.join(', ')}`);\n }\n }\n\n // Add inline instructions for this field with concrete examples\n const patchHint = getPatchFormatHint(field.kind, {\n fieldId: field.id,\n columnIds,\n checkboxMode,\n optionIds,\n });\n lines.push(` Set: ${patchHint}`);\n\n // Show skip instruction for optional fields, or required notice\n if (issue.severity === 'required') {\n lines.push(` This field is required.`);\n } else {\n lines.push(` Skip: { op: \"skip_field\", fieldId: \"${field.id}\", reason: \"...\" }`);\n }\n }\n }\n lines.push('');\n }\n\n lines.push(GENERAL_INSTRUCTIONS);\n\n return lines.join('\\n');\n}\n\n/**\n * Find a field by ID in the form.\n */\nfunction findField(form: ParsedForm, fieldId: string) {\n for (const group of form.schema.groups) {\n for (const field of group.children) {\n if (field.id === fieldId) {\n return field;\n }\n }\n }\n return null;\n}\n\n// =============================================================================\n// Tool Wrapping for Callbacks\n// =============================================================================\n\n/**\n * Wrap tools with callbacks for observability.\n *\n * Only wraps tools that have an execute function.\n * Declarative tools (schema only) are passed through unchanged.\n */\nfunction wrapToolsWithCallbacks(\n tools: Record<string, Tool>,\n callbacks?: FillCallbacks,\n provider?: string,\n executionId = '0-serial',\n): Record<string, Tool> {\n // Skip wrapping if no tool callbacks\n if (!callbacks?.onToolStart && !callbacks?.onToolEnd && !callbacks?.onWebSearch) {\n return tools;\n }\n\n const wrapped: Record<string, Tool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n // Check if tool has an execute function we can wrap\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment\n const execute = (tool as any).execute;\n if (typeof execute === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n wrapped[name] = wrapTool(name, tool, execute, callbacks, provider, executionId);\n } else {\n // Pass through declarative tools unchanged\n wrapped[name] = tool;\n }\n }\n return wrapped;\n}\n\n/**\n * Wrap a single tool with callbacks.\n */\nfunction wrapTool(\n name: string,\n tool: Tool,\n originalExecute: (input: unknown) => Promise<unknown>,\n callbacks: FillCallbacks,\n provider: string | undefined,\n executionId: string,\n): Tool {\n return {\n ...tool,\n execute: async (input: unknown) => {\n const startTime = Date.now();\n\n // Call onToolStart (errors don't abort)\n if (callbacks.onToolStart) {\n try {\n callbacks.onToolStart({ name, input, executionId });\n } catch {\n // Ignore callback errors\n }\n }\n\n try {\n const output = await originalExecute(input);\n\n // Call onToolEnd on success (errors don't abort)\n if (callbacks.onToolEnd) {\n try {\n callbacks.onToolEnd({\n name,\n output,\n durationMs: Date.now() - startTime,\n executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Check if this is a web search tool and call onWebSearch\n if (callbacks.onWebSearch && isWebSearchTool(name)) {\n try {\n const webSearchInfo = extractWebSearchInfo(input, output, provider ?? 'unknown');\n if (webSearchInfo) {\n callbacks.onWebSearch({ ...webSearchInfo, executionId });\n }\n } catch {\n // Ignore callback errors\n }\n }\n\n return output;\n } catch (error) {\n // Call onToolEnd on error (errors don't abort)\n if (callbacks.onToolEnd) {\n try {\n callbacks.onToolEnd({\n name,\n output: null,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n throw error;\n }\n },\n };\n}\n\n/**\n * Check if a tool name indicates a web search tool.\n */\nfunction isWebSearchTool(name: string): boolean {\n return name === 'web_search' || name === 'google_search' || name.includes('search');\n}\n\n/**\n * Extract web search info from tool input/output.\n * Different providers may have different structures.\n */\nfunction extractWebSearchInfo(\n input: unknown,\n output: unknown,\n provider: string,\n): { query: string; resultCount: number; provider: string } | undefined {\n // Try to extract query from input\n let query: string | undefined;\n if (input && typeof input === 'object') {\n const inputObj = input as Record<string, unknown>;\n if (typeof inputObj.query === 'string') {\n query = inputObj.query;\n } else if (typeof inputObj.q === 'string') {\n query = inputObj.q;\n }\n }\n\n if (!query) {\n return undefined;\n }\n\n // Try to extract result count from output\n let resultCount = 0;\n if (output && typeof output === 'object') {\n const outputObj = output as Record<string, unknown>;\n // Common patterns for result count\n if (Array.isArray(outputObj.results)) {\n resultCount = outputObj.results.length;\n } else if (Array.isArray(outputObj.searchResults)) {\n resultCount = outputObj.searchResults.length;\n } else if (typeof outputObj.resultCount === 'number') {\n resultCount = outputObj.resultCount;\n } else if (typeof outputObj.totalResults === 'number') {\n resultCount = outputObj.totalResults;\n }\n }\n\n return { query, resultCount, provider };\n}\n\n// =============================================================================\n// Web Search Tools\n// =============================================================================\n\n/**\n * Load web search tools for a provider.\n * Uses centralized config from llms.ts.\n */\nfunction loadWebSearchTools(provider: string): Record<string, Tool> {\n const config = getWebSearchConfig(provider);\n if (!config?.toolName) return {};\n\n switch (provider) {\n case 'openai': {\n const tool = openai.tools?.webSearch?.({}) ?? openai.tools?.webSearchPreview?.({});\n if (tool) return { web_search: tool as Tool };\n return {};\n }\n case 'anthropic': {\n const tool = anthropic.tools?.webSearch_20250305?.({});\n if (tool) return { web_search: tool as Tool };\n return {};\n }\n case 'google': {\n const tool = google.tools?.googleSearch?.({});\n if (tool) return { google_search: tool as Tool };\n return {};\n }\n case 'xai': {\n const tool = xai.tools?.webSearch?.({});\n if (tool) return { web_search: tool as Tool };\n return {};\n }\n default:\n return {};\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a live agent with the given configuration.\n */\nexport function createLiveAgent(config: LiveAgentConfig): LiveAgent {\n return new LiveAgent(config);\n}\n\n// =============================================================================\n// Mock Wire Format Support\n// =============================================================================\n\n/**\n * Build wire format for mock sessions.\n *\n * This captures what WOULD be sent to the LLM in a mock session,\n * enabling git-based testing where prompt changes are visible in diffs.\n *\n * @param form - Current form state\n * @param issues - Issues being addressed\n * @param patches - Patches generated by mock agent\n * @param maxPatches - Max patches per turn\n * @param targetRole - Target role for instructions\n * @param previousRejections - Rejections from previous turn\n */\nexport function buildMockWireFormat(\n form: ParsedForm,\n issues: InspectIssue[],\n patches: Patch[],\n maxPatches: number,\n targetRole: string = AGENT_ROLE,\n previousRejections?: PatchRejection[],\n): WireFormat {\n // Build prompts exactly as LiveAgent would\n const systemPrompt = buildSystemPrompt(form, targetRole, issues);\n const contextPrompt = buildContextPrompt(issues, form, maxPatches, previousRejections);\n\n // Build tool schema for fill_form\n // Note: Using lowercase 'patch' in $defs to avoid case conversion issues in YAML serialization\n // (uppercase 'Patch' would become '_patch' in snake_case, breaking the $ref)\n const tools: Record<string, { description: string; inputSchema: unknown }> = {\n [FILL_FORM_TOOL_NAME]: {\n description: FILL_FORM_TOOL_DESCRIPTION,\n inputSchema: sortObjectKeys({\n type: 'object',\n properties: {\n patches: {\n type: 'array',\n items: { $ref: '#/$defs/patch' },\n description: 'Array of patches to apply to the form',\n },\n },\n required: ['patches'],\n $defs: {\n patch: { description: 'A patch operation (see tool description for full schema)' },\n },\n }),\n },\n };\n\n // Build simulated response from mock patches\n const steps: WireResponseStep[] = [\n {\n toolCalls: [\n {\n toolName: FILL_FORM_TOOL_NAME,\n input: sortObjectKeys({ patches }),\n },\n ],\n toolResults: [],\n text: null,\n },\n ];\n\n return {\n request: {\n system: systemPrompt,\n prompt: contextPrompt,\n tools,\n },\n response: {\n steps,\n usage: {\n inputTokens: 0, // Mock doesn't use LLM\n outputTokens: 0,\n },\n },\n };\n}\n","/**\n * Model Resolver - Parse and resolve AI SDK model identifiers.\n *\n * Parses model IDs in the format `provider/model-id` and dynamically\n * imports the corresponding AI SDK provider.\n */\n\nimport type { LanguageModel } from 'ai';\n\nimport { MarkformConfigError } from '../errors.js';\nimport type { ParsedModelId, ProviderInfo, ProviderName, ResolvedModel } from './harnessTypes.js';\n\n// Re-export types for backwards compatibility\nexport type { ParsedModelId, ProviderInfo, ProviderName, ResolvedModel } from './harnessTypes.js';\n\n/**\n * Map of provider names to their npm package and env var.\n */\nconst PROVIDERS: Record<ProviderName, { package: string; envVar: string; createFn: string }> = {\n anthropic: {\n package: '@ai-sdk/anthropic',\n envVar: 'ANTHROPIC_API_KEY',\n createFn: 'createAnthropic',\n },\n openai: {\n package: '@ai-sdk/openai',\n envVar: 'OPENAI_API_KEY',\n createFn: 'createOpenAI',\n },\n google: {\n package: '@ai-sdk/google',\n envVar: 'GOOGLE_GENERATIVE_AI_API_KEY',\n createFn: 'createGoogleGenerativeAI',\n },\n xai: {\n package: '@ai-sdk/xai',\n envVar: 'XAI_API_KEY',\n createFn: 'createXai',\n },\n deepseek: {\n package: '@ai-sdk/deepseek',\n envVar: 'DEEPSEEK_API_KEY',\n createFn: 'createDeepSeek',\n },\n};\n\n// =============================================================================\n// Model Resolution\n// =============================================================================\n\n/**\n * Parse a model ID string into provider and model components.\n *\n * @param modelIdString - Model ID in format `provider/model-id`\n * @returns Parsed model identifier\n * @throws Error if format is invalid\n */\nexport function parseModelId(modelIdString: string): ParsedModelId {\n const slashIndex = modelIdString.indexOf('/');\n if (slashIndex === -1) {\n throw new MarkformConfigError(\n `Invalid model ID format: \"${modelIdString}\". Expected format: provider/model-id (e.g., anthropic/claude-sonnet-4-5)`,\n { option: 'model', expectedType: 'provider/model-id format', receivedValue: modelIdString },\n );\n }\n\n const provider = modelIdString.slice(0, slashIndex);\n const modelId = modelIdString.slice(slashIndex + 1);\n\n if (!provider || !modelId) {\n throw new MarkformConfigError(\n `Invalid model ID format: \"${modelIdString}\". Both provider and model ID are required.`,\n {\n option: 'model',\n expectedType: 'non-empty provider and model-id',\n receivedValue: modelIdString,\n },\n );\n }\n\n const supportedProviders = Object.keys(PROVIDERS);\n if (!supportedProviders.includes(provider)) {\n throw new MarkformConfigError(\n `Unknown provider: \"${provider}\". Supported providers: ${supportedProviders.join(', ')}`,\n {\n option: 'model',\n expectedType: `one of: ${supportedProviders.join(', ')}`,\n receivedValue: provider,\n },\n );\n }\n\n return {\n provider: provider as ProviderName,\n modelId,\n };\n}\n\n/**\n * Resolve a model ID string to an AI SDK language model.\n *\n * Dynamically imports the provider package and creates the model instance.\n *\n * @param modelIdString - Model ID in format `provider/model-id`\n * @returns Resolved model with provider info\n * @throws Error if provider not installed or API key missing\n */\nexport async function resolveModel(modelIdString: string): Promise<ResolvedModel> {\n const { provider, modelId } = parseModelId(modelIdString);\n const providerConfig = PROVIDERS[provider];\n\n // Check for API key\n const apiKey = process.env[providerConfig.envVar];\n if (!apiKey) {\n throw new MarkformConfigError(\n `Missing API key for \"${provider}\" provider (model: ${modelIdString}).\\n` +\n `Set the ${providerConfig.envVar} environment variable or add it to your .env file.`,\n { option: providerConfig.envVar, expectedType: 'API key string', receivedValue: undefined },\n );\n }\n\n // Dynamically import the provider\n let providerModule: Record<string, (modelId: string) => LanguageModel>;\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n providerModule = await import(providerConfig.package);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes('Cannot find module') || message.includes('ERR_MODULE_NOT_FOUND')) {\n throw new MarkformConfigError(\n `Provider package not installed for model \"${modelIdString}\".\\n` +\n `Install with: pnpm add ${providerConfig.package}`,\n {\n option: 'model',\n expectedType: 'installed provider package',\n receivedValue: providerConfig.package,\n },\n );\n }\n throw error;\n }\n\n // Get the createProvider function (e.g., createAnthropic, createOpenAI, createGoogleGenerativeAI)\n const createFn = providerModule[providerConfig.createFn] as // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | ((options: { apiKey: string }) => any)\n | undefined;\n\n let model: LanguageModel;\n\n if (createFn && typeof createFn === 'function') {\n // Use the factory function with explicit API key\n // The provider instance is callable: providerInstance(modelId) returns a LanguageModel\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call\n model = createFn({ apiKey })(modelId);\n } else {\n // Fallback: try the simple provider function (for backwards compatibility)\n const providerFn = providerModule[provider] as ((modelId: string) => LanguageModel) | undefined;\n if (typeof providerFn !== 'function') {\n throw new MarkformConfigError(\n `Provider package \"${providerConfig.package}\" does not export expected function \"${provider}\" or \"${providerConfig.createFn}\"`,\n {\n option: 'model',\n expectedType: 'valid provider export',\n receivedValue: Object.keys(providerModule).join(', '),\n },\n );\n }\n model = providerFn(modelId);\n }\n\n return {\n model,\n provider,\n modelId,\n };\n}\n\n/**\n * Get list of supported provider names.\n */\nexport function getProviderNames(): ProviderName[] {\n return Object.keys(PROVIDERS) as ProviderName[];\n}\n\n/**\n * Get provider info for display purposes.\n */\nexport function getProviderInfo(provider: ProviderName): ProviderInfo {\n const config = PROVIDERS[provider];\n return {\n package: config.package,\n envVar: config.envVar,\n };\n}\n","/**\n * Parallel Harness - Orchestrates concurrent agent execution for parallel form filling.\n *\n * Uses the execution plan to identify parallel batches and order levels,\n * spawns concurrent agents for batch items, merges patches, and applies them.\n */\n\nimport { applyPatches } from '../engine/apply.js';\nimport type {\n ExecutionPlan,\n ExecutionPlanItem,\n InspectIssue,\n ParsedForm,\n Patch,\n} from '../engine/coreTypes.js';\nimport { computeExecutionPlan } from '../engine/executionPlan.js';\nimport { inspect } from '../engine/inspect.js';\nimport { DEFAULT_MAX_PARALLEL_AGENTS } from '../settings.js';\nimport type { Agent, AgentResponse } from './harnessTypes.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Scoped fill request for a parallel agent.\n * Provides the full form for context but limits the agent to specific fields.\n */\nexport interface ScopedFillRequest {\n /** Full form for read-only context */\n form: ParsedForm;\n /** Field IDs this agent should fill */\n targetFieldIds: string[];\n /** Group IDs this agent is responsible for */\n targetGroupIds: string[];\n /** Issues scoped to target fields */\n issues: InspectIssue[];\n}\n\n/**\n * Result of running a single order level.\n */\nexport interface ParallelStepResult {\n /** Total patches applied in this order level */\n patchesApplied: number;\n /** Whether any errors occurred */\n errors: string[];\n}\n\n/**\n * Result of running all order levels.\n */\nexport interface ParallelRunResult {\n /** Whether the form is complete */\n isComplete: boolean;\n /** Total patches applied across all levels */\n totalPatchesApplied: number;\n /** Order levels processed */\n orderLevelsProcessed: number[];\n /** Errors from any level */\n errors: string[];\n}\n\n/**\n * Configuration for the parallel harness.\n */\nexport interface ParallelHarnessConfig {\n /** Maximum concurrent agents for parallel batches (default: DEFAULT_MAX_PARALLEL_AGENTS) */\n maxParallelAgents?: number;\n /** Factory to create scoped agents for parallel batch items */\n agentFactory?: (request: ScopedFillRequest) => Agent;\n /** Callback when a parallel batch starts */\n onBatchStart?: (batchId: string) => void;\n /** Callback when a parallel batch completes */\n onBatchComplete?: (batchId: string) => void;\n /** Callback when an order level starts processing */\n onOrderLevelStart?: (order: number) => void;\n /** Callback when an order level completes */\n onOrderLevelComplete?: (order: number) => void;\n /** Target roles (default: ['agent']) */\n targetRoles?: string[];\n /** Max patches per agent turn */\n maxPatchesPerTurn?: number;\n}\n\n// =============================================================================\n// Scope Filtering\n// =============================================================================\n\n/**\n * Get field IDs that belong to an execution plan item.\n */\nexport function getFieldIdsForItem(form: ParsedForm, item: ExecutionPlanItem): string[] {\n if (item.itemType === 'field') {\n return [item.itemId];\n }\n const group = form.schema.groups.find((g) => g.id === item.itemId);\n if (!group) return [];\n return group.children.map((f) => f.id);\n}\n\n/**\n * Filter issues to only those relevant to an execution plan item's fields.\n * Form-scoped issues are excluded (they don't belong to individual agents).\n */\nexport function scopeIssuesForItem(\n form: ParsedForm,\n item: ExecutionPlanItem,\n allIssues: InspectIssue[],\n): InspectIssue[] {\n const targetFieldIds = new Set(getFieldIdsForItem(form, item));\n\n return allIssues.filter((issue) => {\n if (issue.scope === 'form') return false;\n if (issue.scope === 'field') return targetFieldIds.has(issue.ref);\n if (issue.scope === 'option') {\n // Option refs are \"fieldId.optionId\"\n const dotIndex = issue.ref.indexOf('.');\n const fieldId = dotIndex > 0 ? issue.ref.slice(0, dotIndex) : issue.ref;\n return targetFieldIds.has(fieldId);\n }\n if (issue.scope === 'cell') {\n // Cell refs are \"fieldId.columnId[rowIndex]\"\n const dotIndex = issue.ref.indexOf('.');\n const fieldId = dotIndex > 0 ? issue.ref.slice(0, dotIndex) : issue.ref;\n return targetFieldIds.has(fieldId);\n }\n return false;\n });\n}\n\n// =============================================================================\n// Parallel Harness\n// =============================================================================\n\n/**\n * Parallel harness that orchestrates concurrent agent execution.\n */\nexport class ParallelHarness {\n private form: ParsedForm;\n private plan: ExecutionPlan;\n private config: ParallelHarnessConfig;\n\n constructor(form: ParsedForm, config: ParallelHarnessConfig = {}) {\n this.form = form;\n this.plan = computeExecutionPlan(form);\n this.config = config;\n }\n\n /**\n * Get the execution plan.\n */\n getExecutionPlan(): ExecutionPlan {\n return this.plan;\n }\n\n /**\n * Run a single order level: execute loose serial items with the primary agent,\n * and parallel batch items concurrently.\n */\n async runOrderLevel(order: number, primaryAgent: Agent): Promise<ParallelStepResult> {\n const maxPatches = this.config.maxPatchesPerTurn ?? 20;\n let totalPatchesApplied = 0;\n const errors: string[] = [];\n\n // Get current issues for this form state\n const inspectResult = inspect(this.form);\n const allIssues = inspectResult.issues;\n\n // 1. Run loose serial items with primary agent\n const looseItems = this.plan.looseSerial.filter((i) => i.order === order);\n for (const item of looseItems) {\n const scopedIssues = scopeIssuesForItem(this.form, item, allIssues);\n if (scopedIssues.length === 0) continue;\n\n try {\n const response = await primaryAgent.fillFormTool(scopedIssues, this.form, maxPatches);\n if (response.patches.length > 0) {\n const result = applyPatches(this.form, response.patches);\n totalPatchesApplied += result.appliedPatches.length;\n }\n } catch (err) {\n errors.push(`Loose serial item ${item.itemId}: ${String(err)}`);\n }\n }\n\n // 2. Run parallel batch items concurrently\n for (const batch of this.plan.parallelBatches) {\n const batchItems = batch.items.filter((i) => i.order === order);\n if (batchItems.length === 0) continue;\n\n this.config.onBatchStart?.(batch.batchId);\n\n // Re-inspect after loose serial to get updated issues\n const batchInspect = inspect(this.form);\n const batchIssues = batchInspect.issues;\n\n const maxConcurrent = this.config.maxParallelAgents ?? DEFAULT_MAX_PARALLEL_AGENTS;\n\n // Create promise factories for each batch item (for true concurrency limiting)\n const agentFactories: (() => Promise<AgentResponse>)[] = [];\n const itemFieldIds = new Map<number, string[]>();\n\n for (let i = 0; i < batchItems.length; i++) {\n const item = batchItems[i]!;\n const scopedIssues = scopeIssuesForItem(this.form, item, batchIssues);\n const targetFieldIds = getFieldIdsForItem(this.form, item);\n itemFieldIds.set(i, targetFieldIds);\n\n if (scopedIssues.length === 0) {\n agentFactories.push(() => Promise.resolve({ patches: [] }));\n continue;\n }\n\n const request: ScopedFillRequest = {\n form: this.form,\n targetFieldIds,\n targetGroupIds: item.itemType === 'group' ? [item.itemId] : [],\n issues: scopedIssues,\n };\n\n // Use agentFactory if provided, otherwise use primary agent\n const agent = this.config.agentFactory ? this.config.agentFactory(request) : primaryAgent;\n\n // Wrap in factory so promise starts when slot is available\n agentFactories.push(() => agent.fillFormTool(scopedIssues, this.form, maxPatches));\n }\n\n // Run with concurrency limit (factories are called lazily)\n const results = await runWithConcurrency(agentFactories, maxConcurrent);\n\n // Merge all patches from parallel agents\n const allPatches: Patch[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n allPatches.push(...result.value.patches);\n } else {\n errors.push(`Parallel agent error: ${result.reason}`);\n }\n }\n\n // Apply merged patches in one call\n if (allPatches.length > 0) {\n const applyResult = applyPatches(this.form, allPatches);\n totalPatchesApplied += applyResult.appliedPatches.length;\n }\n\n this.config.onBatchComplete?.(batch.batchId);\n }\n\n return { patchesApplied: totalPatchesApplied, errors };\n }\n\n /**\n * Run all order levels sequentially, filling the entire form.\n */\n async runAll(primaryAgent: Agent): Promise<ParallelRunResult> {\n let totalPatchesApplied = 0;\n const orderLevelsProcessed: number[] = [];\n const allErrors: string[] = [];\n\n for (const order of this.plan.orderLevels) {\n this.config.onOrderLevelStart?.(order);\n\n const result = await this.runOrderLevel(order, primaryAgent);\n totalPatchesApplied += result.patchesApplied;\n orderLevelsProcessed.push(order);\n allErrors.push(...result.errors);\n\n this.config.onOrderLevelComplete?.(order);\n }\n\n // Check final form state\n const finalInspect = inspect(this.form);\n\n return {\n isComplete: finalInspect.isComplete,\n totalPatchesApplied,\n orderLevelsProcessed,\n errors: allErrors,\n };\n }\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Run promise factories with a concurrency limit.\n * Takes an array of functions that create promises (factories), not already-started promises.\n * This ensures concurrency limiting actually works - promises are started lazily.\n * Returns results in the same order as input.\n */\nexport async function runWithConcurrency<T>(\n factories: (() => Promise<T>)[],\n maxConcurrent: number,\n): Promise<PromiseSettledResult<T>[]> {\n if (factories.length === 0) {\n return [];\n }\n\n if (maxConcurrent >= factories.length) {\n // Start all and await - no limiting needed\n // Use async wrapper to convert sync throws to rejected promises\n return Promise.allSettled(factories.map(async (f) => f()));\n }\n\n // Semaphore-based concurrency limiter with lazy promise creation\n const results: PromiseSettledResult<T>[] = new Array<PromiseSettledResult<T>>(factories.length);\n let nextIndex = 0;\n\n async function runNext(): Promise<void> {\n while (nextIndex < factories.length) {\n const idx = nextIndex++;\n const factory = factories[idx];\n if (!factory) continue;\n try {\n const value = await factory(); // Create promise here, when slot is available\n results[idx] = { status: 'fulfilled', value };\n } catch (reason) {\n results[idx] = { status: 'rejected', reason };\n }\n }\n }\n\n const workers = Array.from({ length: Math.min(maxConcurrent, factories.length) }, () =>\n runNext(),\n );\n await Promise.all(workers);\n\n return results;\n}\n\n// =============================================================================\n// Factory\n// =============================================================================\n\n/**\n * Create a parallel harness for the given form.\n */\nexport function createParallelHarness(\n form: ParsedForm,\n config?: ParallelHarnessConfig,\n): ParallelHarness {\n return new ParallelHarness(form, config);\n}\n","/**\n * Programmatic Fill API - High-level entry point for form filling.\n *\n * Provides a single-function API for external agentic systems to execute\n * form-filling sessions with a single function call.\n */\n\nimport type { LanguageModel } from 'ai';\n\nimport { applyPatches } from '../engine/apply.js';\nimport type {\n ExecutionPlanItem,\n FieldValue,\n InspectIssue,\n ParsedForm,\n Patch,\n PatchRejection,\n SessionTurnContext,\n SessionTurnStats,\n} from '../engine/coreTypes.js';\nimport { computeExecutionPlan } from '../engine/executionPlan.js';\nimport { inspect } from '../engine/inspect.js';\nimport { parseForm } from '../engine/parse.js';\nimport { serializeForm } from '../engine/serialize.js';\nimport { coerceInputContext } from '../engine/valueCoercion.js';\nimport {\n AGENT_ROLE,\n DEFAULT_MAX_ISSUES_PER_TURN,\n DEFAULT_MAX_PARALLEL_AGENTS,\n DEFAULT_MAX_PATCHES_PER_TURN,\n DEFAULT_MAX_TURNS,\n} from '../settings.js';\nimport { computeProgressSummary, computeStructureSummary } from '../engine/summaries.js';\nimport type { ProgressCounts } from '../engine/coreTypes.js';\nimport type { FillRecord } from './fillRecord.js';\nimport { FillRecordCollector } from './fillRecordCollector.js';\nimport { createHarness } from './harness.js';\nimport { createLiveAgent } from './liveAgent.js';\nimport { resolveModel } from './modelResolver.js';\nimport { runWithConcurrency, scopeIssuesForItem } from './parallelHarness.js';\nimport type { Agent, FillOptions, FillResult, FillStatus, TurnStats } from './harnessTypes.js';\n\n// Re-export types for backwards compatibility\nexport type { FillOptions, FillResult, FillStatus, TurnProgress } from './harnessTypes.js';\n\n// =============================================================================\n// Execution ID Helpers\n// =============================================================================\n\n/**\n * Execution ID format for tracking parallel and serial execution threads.\n *\n * Format: `eid:{type}:o{order}[:{batchId}:i{index}]`\n *\n * Components:\n * - `eid:` - Prefix identifying this as an execution ID\n * - `{type}` - Either `serial` or `batch`\n * - `o{order}` - Order level (e.g., `o0`, `o10`)\n * - For batch only: `:{batchId}:i{index}` - Batch name and item index\n *\n * Examples:\n * - `eid:serial:o0` - Serial execution at order level 0\n * - `eid:batch:o0:research:i0` - First item in \"research\" batch at order 0\n * - `eid:batch:o0:research:i3` - Fourth item in \"research\" batch at order 0\n * - `eid:serial:o10` - Serial execution at order level 10\n *\n * Design principles:\n * - Self-identifying: Clear `eid:` prefix\n * - Structured: Type comes first for easy filtering\n * - Explicit: Each component has a prefix (`o` for order, `i` for index)\n * - Parseable: Can be split on `:` to extract components\n */\n\n/** Prefix for all execution IDs */\nconst EXECUTION_ID_PREFIX = 'eid';\n\n/**\n * Create an execution ID for serial execution at an order level.\n */\nexport function serialExecutionId(order: number): string {\n return `${EXECUTION_ID_PREFIX}:serial:o${order}`;\n}\n\n/**\n * Create an execution ID for a batch item at an order level.\n */\nexport function batchExecutionId(order: number, batchId: string, itemIndex: number): string {\n return `${EXECUTION_ID_PREFIX}:batch:o${order}:${batchId}:i${itemIndex}`;\n}\n\n/**\n * Parse an execution ID into its components.\n * Returns null if the ID doesn't match the expected format.\n */\nexport function parseExecutionId(\n id: string,\n):\n | { type: 'serial'; order: number }\n | { type: 'batch'; order: number; batchId: string; itemIndex: number }\n | null {\n if (!id.startsWith(`${EXECUTION_ID_PREFIX}:`)) return null;\n\n const parts = id.split(':');\n if (parts.length < 3) return null;\n\n const type = parts[1];\n const orderPart = parts[2];\n\n if (!orderPart?.startsWith('o')) return null;\n const order = parseInt(orderPart.slice(1), 10);\n if (isNaN(order)) return null;\n\n if (type === 'serial') {\n return { type: 'serial', order };\n } else if (type === 'batch' && parts.length >= 5) {\n const batchId = parts[3];\n const indexPart = parts[4];\n if (!indexPart?.startsWith('i') || !batchId) return null;\n const itemIndex = parseInt(indexPart.slice(1), 10);\n if (isNaN(itemIndex)) return null;\n return { type: 'batch', order, batchId, itemIndex };\n }\n\n return null;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Get current progress counts for a form.\n * Runs inspect to get issues, then computes progress summary.\n */\nfunction getProgressCounts(form: ParsedForm, targetRoles?: string[]): ProgressCounts {\n const inspectResult = inspect(form, { targetRoles });\n const progressSummary = computeProgressSummary(\n form.schema,\n form.responsesByFieldId,\n form.notes,\n inspectResult.issues,\n );\n return progressSummary.counts;\n}\n\n/**\n * Create a FillRecordCollector if recordFill is enabled.\n */\nfunction createCollectorIfNeeded(\n options: FillOptions,\n form: ParsedForm,\n provider: string,\n model: string,\n): FillRecordCollector | undefined {\n if (!options.recordFill) return undefined;\n\n const structureSummary = computeStructureSummary(form.schema);\n return new FillRecordCollector({\n form: {\n id: form.schema.id,\n title: form.schema.title,\n description: form.schema.description,\n structure: structureSummary,\n },\n provider,\n model,\n parallelEnabled: options.enableParallel,\n maxParallelAgents: options.maxParallelAgents,\n });\n}\n\n/**\n * Log a warning when a user callback throws.\n */\nfunction warnCallbackError(name: string, error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[markform] User callback ${name} threw: ${message}`);\n}\n\n/**\n * Merge user callbacks with collector callbacks.\n * Returns a new callbacks object that forwards to both.\n *\n * Error handling:\n * - Collector callbacks: errors propagate (bugs in our code should surface)\n * - User callbacks: errors are caught and logged as warnings\n */\nfunction mergeCallbacks(\n userCallbacks: FillOptions['callbacks'],\n collector: FillRecordCollector | undefined,\n): FillOptions['callbacks'] {\n if (!collector) return userCallbacks;\n if (!userCallbacks) return collector;\n\n // Create wrapper that forwards to both collector (directly) and user (safely)\n return {\n onTurnStart: (turn) => {\n collector.onTurnStart(turn);\n try {\n userCallbacks.onTurnStart?.(turn);\n } catch (e) {\n warnCallbackError('onTurnStart', e);\n }\n },\n onTurnComplete: (progress) => {\n collector.onTurnComplete(progress);\n try {\n userCallbacks.onTurnComplete?.(progress);\n } catch (e) {\n warnCallbackError('onTurnComplete', e);\n }\n },\n onLlmCallStart: (call) => {\n collector.onLlmCallStart(call);\n try {\n userCallbacks.onLlmCallStart?.(call);\n } catch (e) {\n warnCallbackError('onLlmCallStart', e);\n }\n },\n onLlmCallEnd: (call) => {\n collector.onLlmCallEnd(call);\n try {\n userCallbacks.onLlmCallEnd?.(call);\n } catch (e) {\n warnCallbackError('onLlmCallEnd', e);\n }\n },\n onToolStart: (call) => {\n collector.onToolStart(call);\n try {\n userCallbacks.onToolStart?.(call);\n } catch (e) {\n warnCallbackError('onToolStart', e);\n }\n },\n onToolEnd: (call) => {\n collector.onToolEnd(call);\n try {\n userCallbacks.onToolEnd?.(call);\n } catch (e) {\n warnCallbackError('onToolEnd', e);\n }\n },\n // Forward other callbacks to user only (collector doesn't handle these)\n onIssuesIdentified: userCallbacks.onIssuesIdentified\n ? (info) => {\n try {\n userCallbacks.onIssuesIdentified?.(info);\n } catch (e) {\n warnCallbackError('onIssuesIdentified', e);\n }\n }\n : undefined,\n onPatchesGenerated: userCallbacks.onPatchesGenerated\n ? (info) => {\n try {\n userCallbacks.onPatchesGenerated?.(info);\n } catch (e) {\n warnCallbackError('onPatchesGenerated', e);\n }\n }\n : undefined,\n onOrderLevelStart: userCallbacks.onOrderLevelStart\n ? (info) => {\n try {\n userCallbacks.onOrderLevelStart?.(info);\n } catch (e) {\n warnCallbackError('onOrderLevelStart', e);\n }\n }\n : undefined,\n onOrderLevelComplete: userCallbacks.onOrderLevelComplete\n ? (info) => {\n try {\n userCallbacks.onOrderLevelComplete?.(info);\n } catch (e) {\n warnCallbackError('onOrderLevelComplete', e);\n }\n }\n : undefined,\n onBatchStart: userCallbacks.onBatchStart\n ? (info) => {\n try {\n userCallbacks.onBatchStart?.(info);\n } catch (e) {\n warnCallbackError('onBatchStart', e);\n }\n }\n : undefined,\n onBatchComplete: userCallbacks.onBatchComplete\n ? (info) => {\n try {\n userCallbacks.onBatchComplete?.(info);\n } catch (e) {\n warnCallbackError('onBatchComplete', e);\n }\n }\n : undefined,\n // Forward onWebSearch to both collector (directly) and user (safely)\n onWebSearch: (info) => {\n collector.onWebSearch(info);\n try {\n userCallbacks.onWebSearch?.(info);\n } catch (e) {\n warnCallbackError('onWebSearch', e);\n }\n },\n };\n}\n\nfunction buildErrorResult(\n form: ParsedForm,\n errors: string[],\n warnings: string[],\n record?: FillRecord,\n): FillResult {\n // Extract values from responses\n const values: Record<string, FieldValue> = {};\n for (const [fieldId, response] of Object.entries(form.responsesByFieldId)) {\n if (response.state === 'answered' && response.value) {\n values[fieldId] = response.value;\n }\n }\n\n const result: FillResult = {\n status: {\n ok: false,\n reason: 'error',\n message: errors.join('; '),\n },\n markdown: serializeForm(form),\n values,\n form,\n turns: 0,\n totalPatches: 0,\n inputContextWarnings: warnings.length > 0 ? warnings : undefined,\n };\n\n if (record) {\n result.record = record;\n }\n\n return result;\n}\n\nfunction buildResult(\n form: ParsedForm,\n turns: number,\n totalPatches: number,\n status: FillStatus,\n inputContextWarnings?: string[],\n remainingIssues?: InspectIssue[],\n record?: FillRecord,\n): FillResult {\n // Extract values from responses\n const values: Record<string, FieldValue> = {};\n for (const [fieldId, response] of Object.entries(form.responsesByFieldId)) {\n if (response.state === 'answered' && response.value) {\n values[fieldId] = response.value;\n }\n }\n\n const result: FillResult = {\n status,\n markdown: serializeForm(form),\n values,\n form,\n turns,\n totalPatches,\n };\n\n if (inputContextWarnings && inputContextWarnings.length > 0) {\n result.inputContextWarnings = inputContextWarnings;\n }\n\n if (remainingIssues && remainingIssues.length > 0) {\n result.remainingIssues = remainingIssues.map((issue) => ({\n ref: issue.ref,\n message: issue.message,\n severity: issue.severity,\n priority: issue.priority,\n }));\n }\n\n if (record) {\n result.record = record;\n }\n\n return result;\n}\n\n// =============================================================================\n// Main API\n// =============================================================================\n\n/**\n * Fill a form using an LLM agent.\n *\n * This is the primary programmatic entry point for markform. It encapsulates\n * the harness loop with LiveAgent and provides a single-function call for\n * form filling.\n *\n * @param options - Fill options\n * @returns Fill result with status, values, and markdown\n *\n * @example\n * ```typescript\n * import { fillForm } from 'markform';\n *\n * const result = await fillForm({\n * form: formMarkdown,\n * model: 'anthropic/claude-sonnet-4-5',\n * enableWebSearch: true,\n * inputContext: {\n * company_name: 'Apple Inc.',\n * },\n * systemPromptAddition: `\n * ## Additional Context\n * ${backgroundInfo}\n * `,\n * callbacks: {\n * onTurnComplete: (progress) => {\n * console.log(`Turn ${progress.turnNumber}: ${progress.requiredIssuesRemaining} remaining`);\n * },\n * },\n * });\n *\n * if (result.status.ok) {\n * console.log('Values:', result.values);\n * }\n * ```\n */\nexport async function fillForm(options: FillOptions): Promise<FillResult> {\n // 1. Parse form if string\n let form: ParsedForm;\n try {\n form =\n typeof options.form === 'string' ? parseForm(options.form) : structuredClone(options.form);\n } catch (error) {\n // Return error result for parse failures\n const message = error instanceof Error ? error.message : String(error);\n return {\n status: { ok: false, reason: 'error', message: `Form parse error: ${message}` },\n markdown: typeof options.form === 'string' ? options.form : '',\n values: {},\n form: {\n schema: { id: '', groups: [] },\n responsesByFieldId: {},\n notes: [],\n docs: [],\n orderIndex: [],\n idIndex: new Map(),\n },\n turns: 0,\n totalPatches: 0,\n };\n }\n\n // 2. Resolve model if string (skip if _testAgent provided)\n let model: LanguageModel | undefined;\n let provider: string | undefined;\n if (!options._testAgent) {\n try {\n if (typeof options.model === 'string') {\n const resolved = await resolveModel(options.model);\n model = resolved.model;\n provider = resolved.provider;\n } else {\n model = options.model;\n // When a LanguageModel is passed directly, we can't determine provider\n // Web search will be disabled in this case\n }\n } catch (error) {\n // Model resolution is a pre-fill configuration error - fail fast without FillRecord\n const message = error instanceof Error ? error.message : String(error);\n return buildErrorResult(form, [`Model resolution error: ${message}`], []);\n }\n } else if (typeof options.model === 'string' && options.model.includes('/')) {\n // For test agent, extract provider from model string (e.g., \"mock/model\" -> \"mock\")\n provider = options.model.split('/')[0];\n }\n\n // 3. Create collector if recordFill is enabled\n const modelString = typeof options.model === 'string' ? options.model : 'custom';\n const collector = createCollectorIfNeeded(options, form, provider ?? 'unknown', modelString);\n const mergedCallbacks = mergeCallbacks(options.callbacks, collector);\n\n // 4. Apply input context using coercion layer\n let totalPatches = 0;\n let inputContextWarnings: string[] = [];\n\n if (options.inputContext) {\n const coercionResult = coerceInputContext(form, options.inputContext);\n\n // Input context errors are pre-fill configuration errors - fail fast without FillRecord\n if (coercionResult.errors.length > 0) {\n return buildErrorResult(form, coercionResult.errors, coercionResult.warnings);\n }\n\n // Apply coerced patches\n if (coercionResult.patches.length > 0) {\n applyPatches(form, coercionResult.patches);\n totalPatches = coercionResult.patches.length;\n }\n inputContextWarnings = coercionResult.warnings;\n }\n\n // 5. Check for parallel execution path\n if (options.enableParallel) {\n const plan = computeExecutionPlan(form);\n if (plan.parallelBatches.length > 0) {\n return fillFormParallel(\n form,\n model,\n provider,\n options,\n totalPatches,\n inputContextWarnings,\n collector,\n mergedCallbacks,\n );\n }\n // No parallel batches — fall through to serial path\n }\n\n // 6. Create harness + agent (serial path)\n const maxTurnsTotal = options.maxTurnsTotal ?? DEFAULT_MAX_TURNS;\n const startingTurnNumber = options.startingTurnNumber ?? 0;\n const maxPatchesPerTurn = options.maxPatchesPerTurn ?? DEFAULT_MAX_PATCHES_PER_TURN;\n const maxIssuesPerTurn = options.maxIssuesPerTurn ?? DEFAULT_MAX_ISSUES_PER_TURN;\n const targetRoles = options.targetRoles ?? [AGENT_ROLE];\n\n // Pass remaining turns to harness (accounts for turns already executed in previous calls)\n const remainingTurns = Math.max(0, maxTurnsTotal - startingTurnNumber);\n const harness = createHarness(form, {\n maxTurns: remainingTurns,\n maxPatchesPerTurn,\n maxIssuesPerTurn,\n targetRoles,\n fillMode: options.fillMode,\n });\n\n // Use test agent if provided, otherwise create LiveAgent\n const agent: Agent =\n options._testAgent ??\n createLiveAgent({\n model: model!,\n systemPromptAddition: options.systemPromptAddition,\n targetRole: targetRoles[0] ?? AGENT_ROLE,\n provider,\n enableWebSearch: options.enableWebSearch,\n additionalTools: options.additionalTools,\n callbacks: mergedCallbacks,\n maxStepsPerTurn: options.maxStepsPerTurn,\n toolChoice: options.toolChoice,\n });\n\n // 7. Run harness loop\n let turnCount = startingTurnNumber;\n let turnsThisCall = 0;\n let stepResult = harness.step();\n // Track rejections from previous turn to provide feedback to the LLM\n let previousRejections: PatchRejection[] | undefined;\n\n while (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n // Check per-call limit (before executing any work this turn)\n if (options.maxTurnsThisCall !== undefined && turnsThisCall >= options.maxTurnsThisCall) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'batch_limit');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n {\n ok: false,\n reason: 'batch_limit',\n message: `Reached per-call limit (${options.maxTurnsThisCall} turns)`,\n },\n inputContextWarnings,\n stepResult.issues,\n record,\n );\n }\n // Check for cancellation\n if (options.signal?.aborted) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('cancelled');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n stepResult.issues,\n record,\n );\n }\n\n // Call turn start callback (errors don't abort fill)\n if (mergedCallbacks?.onTurnStart) {\n try {\n mergedCallbacks.onTurnStart({\n turnNumber: turnCount + 1,\n issuesCount: stepResult.issues.length,\n // Default to order 0, serial execution for non-parallel fills\n // Parallel harness will override these values\n order: 0,\n executionId: '0-serial',\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Store issues shown this turn (before agent generates patches)\n const turnIssues = stepResult.issues;\n\n // Call onIssuesIdentified callback (before agent generates patches)\n if (mergedCallbacks?.onIssuesIdentified) {\n try {\n mergedCallbacks.onIssuesIdentified({\n turnNumber: turnCount + 1,\n issues: turnIssues,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Generate patches using agent (pass previous rejections so LLM can learn from mistakes)\n let response: { patches: Patch[]; stats?: TurnStats };\n try {\n response = await agent.fillFormTool(turnIssues, form, maxPatchesPerTurn, previousRejections);\n } catch (error) {\n // Agent threw an error - capture it in fill record and return\n const errorMessage = error instanceof Error ? error.message : String(error);\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('failed', errorMessage);\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'error', message: errorMessage },\n inputContextWarnings,\n turnIssues,\n record,\n );\n }\n const { patches, stats } = response;\n\n // Call onPatchesGenerated callback (after agent, before applying)\n if (mergedCallbacks?.onPatchesGenerated) {\n try {\n mergedCallbacks.onPatchesGenerated({\n turnNumber: turnCount + 1,\n patches,\n stats,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Re-check for cancellation after agent call (signal may have fired during LLM call)\n if (options.signal?.aborted) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('cancelled');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n turnIssues,\n record,\n );\n }\n\n // Convert TurnStats to SessionTurnStats (only include fields relevant for session logs)\n let llmStats: SessionTurnStats | undefined;\n let context: SessionTurnContext | undefined;\n if (stats) {\n llmStats = {\n inputTokens: stats.inputTokens,\n outputTokens: stats.outputTokens,\n toolCalls: stats.toolCalls && stats.toolCalls.length > 0 ? stats.toolCalls : undefined,\n };\n // Capture prompts sent to LLM for session logging (helps debug prompt issues)\n if (stats.prompts) {\n context = {\n systemPrompt: stats.prompts.system,\n contextPrompt: stats.prompts.context,\n };\n }\n }\n\n // Apply patches (pass wire format only if captureWireFormat is enabled)\n const wireFormat = options.captureWireFormat ? stats?.wire : undefined;\n stepResult = harness.apply(patches, turnIssues, llmStats, context, wireFormat);\n // Use actual applied count from harness (0 if patches were rejected)\n const actualPatchesApplied = stepResult.patchesApplied ?? patches.length;\n totalPatches += actualPatchesApplied;\n turnCount++;\n turnsThisCall++;\n\n // Store rejections to provide feedback to LLM in next turn\n previousRejections = stepResult.rejectedPatches;\n\n // Call progress callback (errors don't abort fill)\n if (mergedCallbacks?.onTurnComplete) {\n try {\n const requiredIssues = stepResult.issues.filter((i) => i.severity === 'required');\n mergedCallbacks.onTurnComplete({\n turnNumber: turnCount,\n issuesShown: turnIssues.length,\n patchesApplied: actualPatchesApplied,\n requiredIssuesRemaining: requiredIssues.length,\n isComplete: stepResult.isComplete,\n stats,\n issues: turnIssues,\n patches,\n rejectedPatches: stepResult.rejectedPatches ?? [],\n executionId: '0-serial',\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // If not complete and not at max turns, step again\n if (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n stepResult = harness.step();\n }\n }\n\n // 8. Determine final status and finalize record\n const finalProgressCounts = getProgressCounts(form, targetRoles);\n\n if (stepResult.isComplete) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('completed');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: true },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n // Hit max turns without completing\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'max_turns');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'max_turns', message: `Reached maximum total turns (${maxTurnsTotal})` },\n inputContextWarnings,\n stepResult.issues,\n record,\n );\n}\n\n// =============================================================================\n// Parallel Execution Path\n// =============================================================================\n\n/**\n * Fill a form using parallel execution.\n *\n * For each order level, runs serial items with the primary agent (multi-turn),\n * then runs parallel batch items concurrently (multi-turn per agent).\n */\nasync function fillFormParallel(\n form: ParsedForm,\n model: LanguageModel | undefined,\n provider: string | undefined,\n options: FillOptions,\n initialPatches: number,\n inputContextWarnings: string[],\n collector: FillRecordCollector | undefined,\n mergedCallbacks: FillOptions['callbacks'],\n): Promise<FillResult> {\n const plan = computeExecutionPlan(form);\n const maxTurnsTotal = options.maxTurnsTotal ?? DEFAULT_MAX_TURNS;\n const startingTurnNumber = options.startingTurnNumber ?? 0;\n const maxPatchesPerTurn = options.maxPatchesPerTurn ?? DEFAULT_MAX_PATCHES_PER_TURN;\n const maxIssuesPerTurn = options.maxIssuesPerTurn ?? DEFAULT_MAX_ISSUES_PER_TURN;\n const maxParallelAgents = options.maxParallelAgents ?? DEFAULT_MAX_PARALLEL_AGENTS;\n const targetRoles = options.targetRoles ?? [AGENT_ROLE];\n\n let totalPatches = initialPatches;\n let turnCount = startingTurnNumber;\n\n // Helper to create an agent with the correct executionId\n const createAgentForExecution = (executionId: string): Agent => {\n return (\n options._testAgent ??\n createLiveAgent({\n model: model!,\n systemPromptAddition: options.systemPromptAddition,\n targetRole: targetRoles[0] ?? AGENT_ROLE,\n provider,\n enableWebSearch: options.enableWebSearch,\n additionalTools: options.additionalTools,\n callbacks: mergedCallbacks,\n maxStepsPerTurn: options.maxStepsPerTurn,\n executionId,\n toolChoice: options.toolChoice,\n })\n );\n };\n\n for (const order of plan.orderLevels) {\n // Check cancellation\n if (options.signal?.aborted) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('cancelled');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n // Check turn limit\n if (turnCount >= maxTurnsTotal) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'max_turns');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n {\n ok: false,\n reason: 'max_turns',\n message: `Reached maximum total turns (${maxTurnsTotal})`,\n },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n // Fire order level callback\n try {\n mergedCallbacks?.onOrderLevelStart?.({ order });\n } catch {\n /* ignore */\n }\n\n // --- Serial items at this order level (multi-turn) ---\n const serialItems = plan.looseSerial.filter((i) => i.order === order);\n if (serialItems.length > 0) {\n const serialExecId = serialExecutionId(order);\n const serialAgent = createAgentForExecution(serialExecId);\n const result = await runMultiTurnForItems(\n form,\n serialAgent,\n serialItems,\n targetRoles,\n maxPatchesPerTurn,\n maxIssuesPerTurn,\n maxTurnsTotal,\n turnCount,\n options,\n order,\n serialExecId,\n mergedCallbacks,\n );\n totalPatches += result.patchesApplied;\n turnCount += result.turnsUsed;\n\n if (result.aborted && result.status) {\n let record: FillRecord | undefined;\n if (collector) {\n // Set status based on abort reason\n const status = result.status;\n if (!status.ok) {\n if (status.reason === 'cancelled') {\n collector.setStatus('cancelled');\n } else if (status.reason === 'error') {\n collector.setStatus('failed', status.message);\n } else {\n collector.setStatus('partial', status.reason);\n }\n }\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n result.status,\n inputContextWarnings,\n undefined,\n record,\n );\n }\n }\n\n // --- Parallel batch items at this order level ---\n for (const batch of plan.parallelBatches) {\n const batchItems = batch.items.filter((i) => i.order === order);\n if (batchItems.length === 0) continue;\n\n try {\n mergedCallbacks?.onBatchStart?.({ batchId: batch.batchId, itemCount: batchItems.length });\n } catch {\n /* ignore */\n }\n\n // Create promise factories for each batch item (for true concurrency limiting)\n // Factories are called lazily when a slot becomes available\n const itemFactories = batchItems.map((item, itemIndex) => {\n return () => {\n const batchExecId = batchExecutionId(order, batch.batchId, itemIndex);\n // Create a scoped agent for this batch item with correct executionId\n const scopedAgent = createAgentForExecution(batchExecId);\n\n return runMultiTurnForItems(\n form,\n scopedAgent,\n [item],\n targetRoles,\n maxPatchesPerTurn,\n maxIssuesPerTurn,\n maxTurnsTotal,\n turnCount,\n options,\n order,\n batchExecId,\n mergedCallbacks,\n );\n };\n });\n\n // Run with concurrency limit (factories are called lazily)\n const results = await runWithConcurrency(itemFactories, maxParallelAgents);\n\n let batchPatches = 0;\n const batchErrors: string[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n totalPatches += result.value.patchesApplied;\n batchPatches += result.value.patchesApplied;\n turnCount += result.value.turnsUsed;\n // Track errors from aborted items (agent threw an error)\n const itemStatus = result.value.status;\n if (result.value.aborted && itemStatus && !itemStatus.ok && itemStatus.message) {\n batchErrors.push(itemStatus.message);\n }\n } else {\n // Promise itself was rejected (shouldn't happen with new error handling, but defensive)\n const reason: unknown = result.reason;\n const errorMsg = reason instanceof Error ? reason.message : String(reason);\n batchErrors.push(`Parallel agent error: ${errorMsg}`);\n }\n }\n\n // If any batch items had errors, record them (but continue processing)\n // The form may still be partially filled even with some errors\n if (batchErrors.length > 0 && collector) {\n // Don't set failed status yet - we may still complete. Just log the errors.\n // The final status will be set at the end based on form completeness.\n console.warn(`[markform] Parallel batch ${batch.batchId} had errors:`, batchErrors);\n }\n\n try {\n mergedCallbacks?.onBatchComplete?.({\n batchId: batch.batchId,\n patchesApplied: batchPatches,\n });\n } catch {\n /* ignore */\n }\n }\n\n // Fire order level complete callback\n const levelInspect = inspect(form);\n try {\n mergedCallbacks?.onOrderLevelComplete?.({ order, patchesApplied: totalPatches });\n } catch {\n /* ignore */\n }\n\n // If form is already complete, stop early\n if (levelInspect.isComplete) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('completed');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: true },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n }\n\n // Check final form state\n const finalInspect = inspect(form);\n const finalProgressCounts = getProgressCounts(form, targetRoles);\n\n if (finalInspect.isComplete) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('completed');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: true },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'max_turns');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'max_turns', message: `Reached maximum total turns (${maxTurnsTotal})` },\n inputContextWarnings,\n finalInspect.issues,\n record,\n );\n}\n\n/**\n * Result from a multi-turn run for a set of items.\n */\ninterface MultiTurnResult {\n patchesApplied: number;\n turnsUsed: number;\n aborted: boolean;\n status?: FillStatus;\n}\n\n/**\n * Run a multi-turn loop for a set of execution plan items.\n * Scoped issues are filtered to only the target items' fields.\n * Retries with rejection feedback, same as the serial fillForm path.\n */\nasync function runMultiTurnForItems(\n form: ParsedForm,\n agent: Agent,\n items: ExecutionPlanItem[],\n targetRoles: string[],\n maxPatchesPerTurn: number,\n _maxIssuesPerTurn: number,\n maxTurnsTotal: number,\n startTurn: number,\n options: FillOptions,\n order: number,\n executionId: string,\n mergedCallbacks: FillOptions['callbacks'],\n): Promise<MultiTurnResult> {\n let turnsUsed = 0;\n let patchesApplied = 0;\n let previousRejections: PatchRejection[] | undefined;\n const maxTurnsForItems = Math.min(\n maxTurnsTotal - startTurn,\n options.maxTurnsThisCall ?? Infinity,\n );\n\n for (let turn = 0; turn < maxTurnsForItems; turn++) {\n // Check cancellation\n if (options.signal?.aborted) {\n return {\n patchesApplied,\n turnsUsed,\n aborted: true,\n status: { ok: false, reason: 'cancelled' },\n };\n }\n\n // Inspect form to get current issues, scoped to our items\n const inspectResult = inspect(form, { targetRoles });\n const allIssues = inspectResult.issues;\n\n // Scope issues to our items\n let scopedIssues: InspectIssue[] = [];\n for (const item of items) {\n scopedIssues.push(...scopeIssuesForItem(form, item, allIssues));\n }\n\n // Deduplicate issues (same issue could appear via multiple items)\n const seen = new Set<string>();\n scopedIssues = scopedIssues.filter((issue) => {\n const key = `${issue.scope}:${issue.ref}:${issue.message}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n\n if (scopedIssues.length === 0) break; // All items filled\n\n // Fire turn callback\n try {\n mergedCallbacks?.onTurnStart?.({\n turnNumber: startTurn + turnsUsed + 1,\n issuesCount: scopedIssues.length,\n order,\n executionId,\n });\n } catch {\n /* ignore */\n }\n\n // Call agent (catch errors to avoid rejecting the parallel promise)\n let response: { patches: Patch[]; stats?: TurnStats };\n try {\n response = await agent.fillFormTool(\n scopedIssues,\n form,\n maxPatchesPerTurn,\n previousRejections,\n );\n } catch (error) {\n // Return early with error result so it can be tracked by the parallel harness\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n patchesApplied,\n turnsUsed,\n aborted: true,\n status: { ok: false, reason: 'error', message: errorMessage },\n };\n }\n\n // Apply patches\n if (response.patches.length > 0) {\n const applyResult = applyPatches(form, response.patches);\n patchesApplied += applyResult.appliedPatches.length;\n previousRejections = applyResult.rejectedPatches;\n } else {\n previousRejections = undefined;\n }\n\n turnsUsed++;\n\n // Fire turn complete callback\n try {\n const postInspect = inspect(form, { targetRoles });\n const requiredIssues = postInspect.issues.filter((i) => i.severity === 'required');\n mergedCallbacks?.onTurnComplete?.({\n turnNumber: startTurn + turnsUsed,\n issuesShown: scopedIssues.length,\n patchesApplied: response.patches.length,\n requiredIssuesRemaining: requiredIssues.length,\n isComplete: postInspect.isComplete,\n stats: response.stats,\n issues: scopedIssues,\n patches: response.patches,\n rejectedPatches: previousRejections ?? [],\n executionId,\n });\n } catch {\n /* ignore */\n }\n }\n\n return { patchesApplied, turnsUsed, aborted: false };\n}\n","/**\n * Harness configuration resolver.\n *\n * Merges configuration from multiple sources with defined precedence:\n * 1. API-provided options (highest priority)\n * 2. Form frontmatter defaults\n * 3. Global defaults (lowest priority)\n */\n\nimport type { HarnessConfig, ParsedForm } from '../engine/coreTypes.js';\nimport type { FillOptions } from './harnessTypes.js';\nimport {\n DEFAULT_MAX_ISSUES_PER_TURN,\n DEFAULT_MAX_PARALLEL_AGENTS,\n DEFAULT_MAX_PATCHES_PER_TURN,\n DEFAULT_MAX_TURNS,\n} from '../settings.js';\n\n/**\n * Resolve harness configuration by merging options from multiple sources.\n *\n * Precedence (highest to lowest):\n * 1. options parameter (API-provided)\n * 2. form.metadata.harnessConfig (from frontmatter)\n * 3. Default constants\n *\n * @param form The parsed form (may contain frontmatter harness config)\n * @param options API-provided options to override defaults\n * @returns Resolved harness configuration\n */\nexport function resolveHarnessConfig(\n form: ParsedForm,\n options?: Partial<FillOptions>,\n): HarnessConfig {\n // Get frontmatter config (if present)\n const frontmatterConfig = form.metadata?.harnessConfig;\n\n // Merge with precedence: options > frontmatter > defaults\n return {\n maxTurns: options?.maxTurnsTotal ?? frontmatterConfig?.maxTurns ?? DEFAULT_MAX_TURNS,\n maxPatchesPerTurn:\n options?.maxPatchesPerTurn ??\n frontmatterConfig?.maxPatchesPerTurn ??\n DEFAULT_MAX_PATCHES_PER_TURN,\n maxIssuesPerTurn:\n options?.maxIssuesPerTurn ??\n frontmatterConfig?.maxIssuesPerTurn ??\n DEFAULT_MAX_ISSUES_PER_TURN,\n maxParallelAgents:\n options?.maxParallelAgents ??\n frontmatterConfig?.maxParallelAgents ??\n DEFAULT_MAX_PARALLEL_AGENTS,\n targetRoles: options?.targetRoles,\n fillMode: options?.fillMode,\n };\n}\n","/**\n * Format FillRecord as a human-readable summary.\n *\n * Produces a concise text summary of a fill operation, suitable for\n * CLI output or logging. Shows key metrics at a glance:\n * - Duration and turns\n * - Token usage\n * - Tool call summary\n * - Timing breakdown (verbose mode)\n * - Form progress\n */\n\nimport type { FillRecord } from './fillRecord.js';\n\n/**\n * Options for formatting the summary.\n */\nexport interface FormatFillRecordSummaryOptions {\n /** Show detailed breakdown including per-tool stats */\n verbose?: boolean;\n}\n\n/**\n * Format a number with thousands separators.\n */\nfunction formatNumber(n: number): string {\n return n.toLocaleString('en-US');\n}\n\n/**\n * Format milliseconds as a human-readable duration.\n */\nfunction formatDuration(ms: number): string {\n if (ms < 1000) {\n return `${ms}ms`;\n }\n const seconds = ms / 1000;\n if (seconds < 60) {\n // Show one decimal place\n return `${seconds.toFixed(1)}s`;\n }\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = seconds % 60;\n return `${minutes}m ${remainingSeconds.toFixed(0)}s`;\n}\n\n/**\n * Format a percentage.\n */\nfunction formatPercent(value: number, total: number): string {\n if (total === 0) return '0%';\n const pct = Math.round((value / total) * 100);\n return `${pct}%`;\n}\n\n/**\n * Format FillRecord as a human-readable text summary.\n *\n * @param record - The FillRecord to format\n * @param options - Formatting options (verbose mode for more detail)\n * @returns Multi-line text summary\n *\n * @example\n * ```typescript\n * const result = await fillForm({ form, model, recordFill: true });\n * if (result.record) {\n * console.log(formatFillRecordSummary(result.record));\n * }\n * ```\n */\nexport function formatFillRecordSummary(\n record: FillRecord,\n options: FormatFillRecordSummaryOptions = {},\n): string {\n const { verbose = false } = options;\n const lines: string[] = [];\n\n // Status line\n const statusText = record.status === 'completed' ? 'Fill completed' : 'Fill incomplete';\n const turnsText = `${record.execution.totalTurns} turn${record.execution.totalTurns !== 1 ? 's' : ''}`;\n let statusLine = `${statusText} in ${formatDuration(record.durationMs)} (${turnsText})`;\n if (record.status !== 'completed' && record.statusDetail) {\n statusLine += ` - ${record.statusDetail}`;\n }\n lines.push(statusLine);\n\n // Warn if timeline is empty but work was done (indicates callback wiring bug)\n // This catches the mf-mgxo bug where CLI was missing onTurnStart/onTurnComplete wiring\n const timelineEmpty = record.timeline.length === 0;\n const hadTurns = record.execution.totalTurns > 0;\n const hadFieldsFilled = record.formProgress.filledFields > 0;\n if (timelineEmpty && (hadTurns || hadFieldsFilled)) {\n lines.push('Warning: timeline is empty but work was recorded (possible callback wiring issue)');\n }\n\n lines.push('');\n\n // Token usage\n const tokenLine = `Tokens: ${formatNumber(record.llm.inputTokens)} input / ${formatNumber(record.llm.outputTokens)} output (${record.llm.provider}/${record.llm.model})`;\n lines.push(tokenLine);\n\n // Tool summary\n const { toolSummary } = record;\n let toolLine = `Tools: ${formatNumber(toolSummary.totalCalls)} calls`;\n if (toolSummary.totalCalls > 0) {\n toolLine += ` (${formatNumber(toolSummary.successfulCalls)} succeeded`;\n if (toolSummary.failedCalls > 0) {\n toolLine += `, ${formatNumber(toolSummary.failedCalls)} failed`;\n }\n toolLine += ')';\n }\n lines.push(toolLine);\n\n // Per-tool breakdown (verbose mode)\n if (verbose && toolSummary.byTool.length > 0) {\n for (const tool of toolSummary.byTool) {\n const avgDuration = formatDuration(tool.timing.avgMs);\n let toolDetail = ` - ${tool.toolName}: ${tool.callCount} calls, avg ${avgDuration}`;\n if (tool.timing.p95Ms !== undefined && tool.callCount > 1) {\n toolDetail += `, p95 ${formatDuration(tool.timing.p95Ms)}`;\n }\n lines.push(toolDetail);\n }\n }\n\n // Timing breakdown (verbose mode)\n if (verbose) {\n lines.push('');\n const { timingBreakdown } = record;\n const llmPct = timingBreakdown.breakdown.find((b) => b.category === 'llm')?.percentage ?? 0;\n const toolPct = timingBreakdown.breakdown.find((b) => b.category === 'tools')?.percentage ?? 0;\n const overheadPct =\n timingBreakdown.breakdown.find((b) => b.category === 'overhead')?.percentage ?? 0;\n\n const timingLine = `Timing: ${llmPct}% LLM (${formatDuration(timingBreakdown.llmTimeMs)}) | ${toolPct}% tools (${formatDuration(timingBreakdown.toolTimeMs)}) | ${overheadPct}% overhead (${formatDuration(timingBreakdown.overheadMs)})`;\n lines.push(timingLine);\n }\n\n // Progress\n lines.push('');\n const { formProgress } = record;\n const progressPct = formatPercent(formProgress.answeredFields, formProgress.totalFields);\n const progressLine = `Progress: ${formProgress.answeredFields}/${formProgress.totalFields} fields filled (${progressPct})`;\n lines.push(progressLine);\n\n return lines.join('\\n');\n}\n","/**\n * FillRecord types - Captures complete records of form fill operations.\n *\n * Provides detailed tracking of:\n * - LLM usage (tokens per turn and totals)\n * - Tool invocations with timing and results\n * - Turn-by-turn timeline with execution context\n * - Form progress and completion status\n *\n * @see docs/project/specs/active/plan-2026-01-29-fill-record.md\n */\n\nimport { z } from 'zod';\n\nimport { ProgressCountsSchema, StructureSummarySchema } from '../engine/coreTypes.js';\n\n// =============================================================================\n// Tool Statistics Schema\n// =============================================================================\n\n/**\n * Per-tool statistics with timing percentiles.\n * Enables analysis like \"web_search p95 is 2.5s\" or \"fill_form has 98% success rate\"\n */\nexport const ToolStatsSchema = z.object({\n /** Tool name identifier (e.g., \"web_search\", \"fill_form\") */\n toolName: z.string(),\n\n /** Number of times this tool was called */\n callCount: z.number().int().nonnegative(),\n /** Number of successful calls */\n successCount: z.number().int().nonnegative(),\n /** Number of failed calls */\n failureCount: z.number().int().nonnegative(),\n /** Success rate as percentage (0-100) */\n successRate: z.number().nonnegative(),\n\n /** For tools that return results (web_search), track result counts */\n results: z\n .object({\n /** Total results returned across all calls */\n totalResults: z.number().int().nonnegative(),\n /** Average results per call */\n avgResultsPerCall: z.number().nonnegative(),\n /** Calls that returned zero results */\n zeroResultCalls: z.number().int().nonnegative(),\n })\n .optional(),\n\n /** Timing statistics (all values in milliseconds) */\n timing: z.object({\n /** Total time spent in this tool */\n totalMs: z.number().int().nonnegative(),\n /** Average call duration */\n avgMs: z.number().nonnegative(),\n /** Minimum call duration */\n minMs: z.number().int().nonnegative(),\n /** Maximum call duration */\n maxMs: z.number().int().nonnegative(),\n /** 50th percentile (median) */\n p50Ms: z.number().int().nonnegative(),\n /** 95th percentile - useful for identifying slow outliers */\n p95Ms: z.number().int().nonnegative(),\n }),\n});\n\nexport type ToolStats = z.infer<typeof ToolStatsSchema>;\n\n// =============================================================================\n// Tool Call Schema (for timeline)\n// =============================================================================\n\n/**\n * Individual tool call in the timeline.\n */\nexport const ToolCallRecordSchema = z.object({\n /** Tool name */\n tool: z.string(),\n /** When the tool started */\n startedAt: z.string().datetime(),\n /** When the tool completed */\n completedAt: z.string().datetime(),\n /** Start time relative to fill start (milliseconds) */\n startMs: z.number().int().nonnegative(),\n /** Duration in milliseconds */\n durationMs: z.number().int().nonnegative(),\n /** Whether the call succeeded */\n success: z.boolean(),\n /** Tool input parameters (e.g., { query: \"...\" } for web_search) */\n input: z.record(z.string(), z.unknown()),\n /** Result summary */\n result: z\n .object({\n /** Number of results returned (e.g., web search results, patches applied) */\n resultCount: z.number().int().nonnegative().optional(),\n /** Error message if success=false */\n error: z.string().optional(),\n })\n .optional(),\n});\n\nexport type ToolCallRecord = z.infer<typeof ToolCallRecordSchema>;\n\n// =============================================================================\n// Timeline Entry Schema\n// =============================================================================\n\n/**\n * Single turn in the fill timeline.\n */\nexport const TimelineEntrySchema = z.object({\n /** Turn number (1-based) */\n turnNumber: z.number().int().positive(),\n\n /** Order level this turn belongs to (0, 1, 2, etc.) */\n order: z.number().int().nonnegative(),\n\n /**\n * Execution thread identifier.\n * Pattern: \"{order}-{context}\" where context is:\n * - \"serial\" for loose serial items\n * - \"batch-{batchId}-{itemIndex}\" for parallel batch items\n */\n executionId: z.string(),\n\n /** When the turn started */\n startedAt: z.string().datetime(),\n /** When the turn completed */\n completedAt: z.string().datetime(),\n /** Start time relative to fill start (milliseconds) */\n startMs: z.number().int().nonnegative(),\n /** Duration in milliseconds */\n durationMs: z.number().int().nonnegative(),\n\n /** Number of issues addressed this turn */\n issuesAddressed: z.number().int().nonnegative(),\n /** Number of patches successfully applied */\n patchesApplied: z.number().int().nonnegative(),\n /** Number of patches rejected */\n patchesRejected: z.number().int().nonnegative(),\n\n /** Per-turn token usage (from AI SDK result.usage) */\n tokens: z.object({\n input: z.number().int().nonnegative(),\n output: z.number().int().nonnegative(),\n }),\n\n /** Tool calls made during this turn */\n toolCalls: z.array(ToolCallRecordSchema),\n});\n\nexport type TimelineEntry = z.infer<typeof TimelineEntrySchema>;\n\n// =============================================================================\n// Timing Breakdown Schema\n// =============================================================================\n\n/**\n * Breakdown item for visualization.\n */\nexport const TimingBreakdownItemSchema = z.object({\n category: z.enum(['llm', 'tools', 'overhead']),\n label: z.string(),\n ms: z.number().int().nonnegative(),\n percentage: z.number().nonnegative(), // 0-100\n});\n\nexport type TimingBreakdownItem = z.infer<typeof TimingBreakdownItemSchema>;\n\n/**\n * Timing breakdown showing where time was spent.\n */\nexport const TimingBreakdownSchema = z.object({\n /** Total wall-clock time for the fill (ms) */\n totalMs: z.number().int().nonnegative(),\n /** Time spent in LLM API calls (ms) */\n llmTimeMs: z.number().int().nonnegative(),\n /** Time spent executing tools (ms) */\n toolTimeMs: z.number().int().nonnegative(),\n /** Overhead time (total - llm - tools) */\n overheadMs: z.number().int().nonnegative(),\n /** Percentage breakdown for visualization */\n breakdown: z.array(TimingBreakdownItemSchema),\n});\n\nexport type TimingBreakdown = z.infer<typeof TimingBreakdownSchema>;\n\n// =============================================================================\n// Tool Summary Schema\n// =============================================================================\n\n/**\n * Aggregated tool usage statistics.\n */\nexport const ToolSummarySchema = z.object({\n /** Total tool calls across all turns */\n totalCalls: z.number().int().nonnegative(),\n /** Successful tool calls */\n successfulCalls: z.number().int().nonnegative(),\n /** Failed tool calls */\n failedCalls: z.number().int().nonnegative(),\n /** Success rate as percentage (0-100) */\n successRate: z.number().nonnegative(),\n /** Total time spent in tool execution (ms) */\n totalDurationMs: z.number().int().nonnegative(),\n /** Per-tool statistics */\n byTool: z.array(ToolStatsSchema),\n});\n\nexport type ToolSummary = z.infer<typeof ToolSummarySchema>;\n\n// =============================================================================\n// Execution Metadata Schema\n// =============================================================================\n\n/**\n * Execution metadata for the fill.\n */\nexport const ExecutionMetadataSchema = z.object({\n /** Total number of turns executed */\n totalTurns: z.number().int().nonnegative(),\n /** Whether parallel execution was enabled */\n parallelEnabled: z.boolean(),\n /** Maximum parallel agents (if parallel enabled) */\n maxParallelAgents: z.number().int().positive().optional(),\n /** Order levels processed (e.g., [0, 1, 2]) */\n orderLevels: z.array(z.number().int().nonnegative()),\n /** Unique execution threads seen */\n executionThreads: z.array(z.string()),\n});\n\nexport type ExecutionMetadata = z.infer<typeof ExecutionMetadataSchema>;\n\n// =============================================================================\n// Fill Record Schema\n// =============================================================================\n\n/**\n * Fill status enum.\n */\nexport const FillRecordStatusSchema = z.enum(['completed', 'partial', 'failed', 'cancelled']);\n\nexport type FillRecordStatus = z.infer<typeof FillRecordStatusSchema>;\n\n/**\n * Complete record of a form fill operation.\n *\n * Captures everything that happened during the fill for:\n * - Provenance/corroboration\n * - Cost analysis\n * - Debugging\n * - Analytics\n */\nexport const FillRecordSchema = z.object({\n // =========================================================================\n // Session Identity\n // =========================================================================\n\n /** Unique session identifier */\n sessionId: z.string().uuid(),\n /** When the fill started */\n startedAt: z.string().datetime(),\n /** When the fill completed */\n completedAt: z.string().datetime(),\n /** Total duration in milliseconds */\n durationMs: z.number().int().nonnegative(),\n\n // =========================================================================\n // Form Metadata\n // =========================================================================\n\n /** Form identification and structure */\n form: z.object({\n /** Form ID from the form schema */\n id: z.string(),\n /** Form title if specified */\n title: z.string().optional(),\n /** Form description if specified */\n description: z.string().optional(),\n /** Structure summary (field counts, etc.) */\n structure: StructureSummarySchema,\n }),\n\n // =========================================================================\n // Outcome\n // =========================================================================\n\n /** Fill status */\n status: FillRecordStatusSchema,\n /** Additional status detail (e.g., error message) */\n statusDetail: z.string().optional(),\n\n /** Form progress at completion */\n formProgress: ProgressCountsSchema,\n\n // =========================================================================\n // LLM Usage\n // =========================================================================\n\n /** LLM usage totals (tokens only - clients calculate costs) */\n llm: z.object({\n /** Provider name (e.g., \"anthropic\", \"openai\") */\n provider: z.string(),\n /** Model identifier */\n model: z.string(),\n /** Total LLM calls */\n totalCalls: z.number().int().nonnegative(),\n /** Total input tokens */\n inputTokens: z.number().int().nonnegative(),\n /** Total output tokens */\n outputTokens: z.number().int().nonnegative(),\n }),\n\n // =========================================================================\n // Tool Usage\n // =========================================================================\n\n /** Aggregated tool statistics */\n toolSummary: ToolSummarySchema,\n\n /** Timing breakdown */\n timingBreakdown: TimingBreakdownSchema,\n\n // =========================================================================\n // Timeline\n // =========================================================================\n\n /** Turn-by-turn timeline (full history, no size limits) */\n timeline: z.array(TimelineEntrySchema),\n\n // =========================================================================\n // Execution Metadata\n // =========================================================================\n\n /** Execution configuration and thread info */\n execution: ExecutionMetadataSchema,\n\n // =========================================================================\n // Custom Data\n // =========================================================================\n\n /** Client-defined custom data */\n customData: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type FillRecord = z.infer<typeof FillRecordSchema>;\n\n// =============================================================================\n// Stable FillRecord (for golden tests)\n// =============================================================================\n\n/**\n * Stripped ToolStats without timing information.\n */\nexport type StableToolStats = Omit<ToolStats, 'timing'>;\n\n/**\n * Stripped ToolSummary without timing information.\n */\nexport type StableToolSummary = Omit<ToolSummary, 'totalDurationMs' | 'byTool'> & {\n byTool: StableToolStats[];\n};\n\n/**\n * FillRecord with unstable fields removed for deterministic golden tests.\n *\n * Removes:\n * - sessionId, startedAt, completedAt, durationMs (top-level timing)\n * - timeline (contains per-turn timestamps and durations)\n * - timingBreakdown (all timing values)\n * - toolSummary.totalDurationMs and toolSummary.byTool[].timing\n */\nexport type StableFillRecord = Omit<\n FillRecord,\n | 'sessionId'\n | 'startedAt'\n | 'completedAt'\n | 'durationMs'\n | 'timeline'\n | 'timingBreakdown'\n | 'toolSummary'\n> & {\n toolSummary: StableToolSummary;\n};\n\n/**\n * Strip unstable fields from FillRecord for golden test comparisons.\n *\n * In mock mode, all remaining fields should be deterministic:\n * - status, statusDetail: based on completion logic\n * - form: form metadata (static)\n * - formProgress: counts of filled fields (deterministic from mock source)\n * - llm: provider/model/tokens (tokens are 0 in mock mode)\n * - toolSummary: call counts and success rates (without timing)\n * - execution: turn counts, parallel settings (deterministic)\n */\nexport function stripUnstableFillRecordFields(record: FillRecord): StableFillRecord {\n // Strip timing from each tool's stats\n const stableByTool: StableToolStats[] = record.toolSummary.byTool.map((toolStats) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { timing, ...rest } = toolStats;\n return rest;\n });\n\n // Build stable tool summary without timing\n const stableToolSummary: StableToolSummary = {\n totalCalls: record.toolSummary.totalCalls,\n successfulCalls: record.toolSummary.successfulCalls,\n failedCalls: record.toolSummary.failedCalls,\n successRate: record.toolSummary.successRate,\n byTool: stableByTool,\n };\n\n return {\n // Keep form metadata (stable)\n form: record.form,\n\n // Keep outcome (stable in mock mode)\n status: record.status,\n statusDetail: record.statusDetail,\n formProgress: record.formProgress,\n\n // Keep LLM info (tokens are 0 in mock mode)\n llm: record.llm,\n\n // Use stable tool summary\n toolSummary: stableToolSummary,\n\n // Keep execution metadata (stable)\n execution: record.execution,\n\n // Keep custom data if present\n customData: record.customData,\n };\n}\n","/**\n * Research API - Form filling with web search capabilities.\n *\n * The runResearch() function is the main entry point for research-mode filling.\n * It uses web-search-enabled models to fill forms with information from the web.\n */\n\nimport type { ParsedForm, SessionTranscript } from '../engine/coreTypes.js';\nimport { createHarness } from '../harness/harness.js';\nimport { createLiveAgent } from '../harness/liveAgent.js';\nimport { resolveModel } from '../harness/modelResolver.js';\nimport { resolveHarnessConfig } from '../harness/harnessConfigResolver.js';\nimport type { FillOptions } from '../harness/harnessTypes.js';\nimport {\n AGENT_ROLE,\n DEFAULT_MAX_TURNS,\n DEFAULT_RESEARCH_MAX_ISSUES_PER_TURN,\n DEFAULT_RESEARCH_MAX_PATCHES_PER_TURN,\n} from '../settings.js';\nimport type { ResearchResult, ResearchStatus } from './researchTypes.js';\n\n/**\n * Options for runResearch (FillOptions without form, since form is a separate parameter).\n */\nexport type ResearchOptions = Omit<FillOptions, 'form'>;\n\n/**\n * Run research fill on a form.\n *\n * This function fills a form using an LLM with optional web search capabilities.\n * It resolves configuration from multiple sources (options > frontmatter > defaults)\n * and executes the harness loop until completion or max turns.\n *\n * @param form The parsed form to fill\n * @param options Fill options including model specification\n * @returns Research result with filled form and statistics\n */\nexport async function runResearch(\n form: ParsedForm,\n options: ResearchOptions,\n): Promise<ResearchResult> {\n // Validate model is provided\n if (!options.model) {\n throw new Error('model is required for runResearch()');\n }\n\n // Resolve the model - model is string | LanguageModel, but resolveModel only accepts string\n const modelSpec = options.model;\n if (typeof modelSpec !== 'string') {\n throw new Error(\n 'runResearch requires a model string identifier (e.g., \"openai/gpt-4o-search-preview\")',\n );\n }\n const { model, provider } = await resolveModel(modelSpec);\n\n // Resolve harness config with research defaults\n const baseConfig = resolveHarnessConfig(form, options);\n const config = {\n ...baseConfig,\n // Apply research-specific defaults if not overridden\n maxTurns: options.maxTurnsTotal ?? form.metadata?.harnessConfig?.maxTurns ?? DEFAULT_MAX_TURNS,\n maxIssuesPerTurn:\n options.maxIssuesPerTurn ??\n form.metadata?.harnessConfig?.maxIssuesPerTurn ??\n DEFAULT_RESEARCH_MAX_ISSUES_PER_TURN,\n maxPatchesPerTurn:\n options.maxPatchesPerTurn ??\n form.metadata?.harnessConfig?.maxPatchesPerTurn ??\n DEFAULT_RESEARCH_MAX_PATCHES_PER_TURN,\n targetRoles: options.targetRoles ?? [AGENT_ROLE],\n fillMode: options.fillMode ?? 'continue',\n };\n\n // Create harness and agent\n const harness = createHarness(form, config);\n const agent = createLiveAgent({\n model,\n provider,\n targetRole: config.targetRoles?.[0] ?? AGENT_ROLE,\n enableWebSearch: options.enableWebSearch,\n additionalTools: options.additionalTools,\n });\n\n // Get available tools for logging\n const availableTools = agent.getAvailableToolNames();\n\n // Track stats\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n\n // Run harness loop\n let stepResult = harness.step();\n\n while (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n // Generate patches from agent\n const response = await agent.fillFormTool(\n stepResult.issues,\n harness.getForm(),\n config.maxPatchesPerTurn,\n );\n\n // Track token usage if available\n if (response.stats?.inputTokens) {\n totalInputTokens += response.stats.inputTokens;\n }\n if (response.stats?.outputTokens) {\n totalOutputTokens += response.stats.outputTokens;\n }\n\n // Apply patches\n stepResult = harness.apply(response.patches, stepResult.issues);\n\n // Continue if not complete\n if (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n stepResult = harness.step();\n }\n }\n\n // Determine final status\n let status: ResearchStatus;\n if (stepResult.isComplete) {\n status = 'completed';\n } else if (harness.hasReachedMaxTurns()) {\n status = 'max_turns_reached';\n } else {\n status = 'incomplete';\n }\n\n // Build transcript if available\n const transcript: SessionTranscript = {\n sessionVersion: '0.1.0',\n mode: 'live',\n form: { path: '' },\n harness: {\n maxTurns: config.maxTurns,\n maxPatchesPerTurn: config.maxPatchesPerTurn,\n maxIssuesPerTurn: config.maxIssuesPerTurn,\n targetRoles: config.targetRoles,\n fillMode: config.fillMode,\n },\n turns: harness.getTurns(),\n final: {\n expectComplete: true,\n expectedCompletedForm: '',\n },\n };\n\n // Return result\n return {\n status,\n form: harness.getForm(),\n transcript,\n totalTurns: harness.getTurnNumber(),\n inputTokens: totalInputTokens > 0 ? totalInputTokens : undefined,\n outputTokens: totalOutputTokens > 0 ? totalOutputTokens : undefined,\n availableTools,\n };\n}\n","/**\n * Research form validation.\n *\n * Utilities for detecting and validating research-enabled forms.\n */\n\nimport type { ParsedForm } from '../engine/coreTypes.js';\n\n/**\n * Check if a form is configured for research mode.\n *\n * A form is considered a research form if it has web search configuration\n * in its frontmatter metadata, indicated by:\n * - webSearchModel: model ID for web search capability\n * - enableWebSearch: boolean flag to enable web search\n *\n * @param form The parsed form to check\n * @returns true if the form is configured for research\n */\nexport function isResearchForm(form: ParsedForm): boolean {\n const metadata = form.metadata;\n if (!metadata) {\n return false;\n }\n\n // Check for research configuration in metadata\n // These would be set in the frontmatter's markform section\n const extendedMetadata = metadata as unknown as Record<string, unknown>;\n\n // Check for webSearchModel or enableWebSearch\n if (extendedMetadata.webSearchModel) {\n return true;\n }\n\n if (extendedMetadata.enableWebSearch === true) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Validate that a form is suitable for research fill.\n *\n * Research forms should:\n * 1. Have agent-role fields to fill\n * 2. Not be already complete\n *\n * @param form The parsed form to validate\n * @returns Object with isValid and optional error message\n */\nexport function validateResearchForm(form: ParsedForm): { isValid: boolean; error?: string } {\n // Check if form has any fields\n const fieldCount =\n Object.keys(form.responsesByFieldId).length +\n form.schema.groups.reduce((sum, g) => sum + g.children.length, 0);\n\n if (fieldCount === 0) {\n return { isValid: false, error: 'Form has no fields to fill' };\n }\n\n // Form is valid for research\n return { isValid: true };\n}\n","/**\n * Markform - Agent-friendly, human-readable, editable forms.\n *\n * This is the main library entry point that exports the core engine,\n * types, and utilities for working with .form.md files.\n */\n\n// Build-time injected by tsdown (see tsdown.config.ts)\ndeclare const __MARKFORM_VERSION__: string;\n\n/** Markform version (injected at build time). */\nexport const VERSION: string =\n typeof __MARKFORM_VERSION__ !== 'undefined' ? __MARKFORM_VERSION__ : 'development';\n\n// =============================================================================\n// Type Exports\n// =============================================================================\n\nexport type {\n // Basic types\n Id,\n OptionId,\n QualifiedOptionRef,\n QualifiedColumnRef,\n ValidatorRef,\n // Checkbox types\n MultiCheckboxState,\n SimpleCheckboxState,\n ExplicitCheckboxValue,\n CheckboxValue,\n CheckboxMode,\n // Field kinds\n FieldKind,\n FieldBase,\n StringField,\n NumberField,\n StringListField,\n Option,\n CheckboxesField,\n SingleSelectField,\n MultiSelectField,\n UrlField,\n UrlListField,\n DateField,\n YearField,\n // Table field definitions\n ColumnTypeName,\n TableColumn,\n TableField,\n CellResponse,\n TableRowResponse,\n Field,\n // Form structure\n FieldGroup,\n FormSchema,\n // Field values\n StringValue,\n NumberValue,\n StringListValue,\n CheckboxesValue,\n SingleSelectValue,\n MultiSelectValue,\n UrlValue,\n UrlListValue,\n DateValue,\n YearValue,\n TableValue,\n FieldValue,\n // Documentation\n DocumentationTag,\n DocumentationBlock,\n // Answer state and field response\n AnswerState,\n FieldResponse,\n // Parsed form\n NodeType,\n IdIndexEntry,\n ParsedForm,\n // Validation\n Severity,\n SourcePosition,\n SourceRange,\n ValidationIssue,\n // Inspect\n IssueReason,\n IssueScope,\n InspectIssue,\n // Summaries\n StructureSummary,\n ProgressState,\n CheckboxProgressCounts,\n FieldProgress,\n ProgressCounts,\n ProgressSummary,\n // Results\n InspectResult,\n ApplyResult,\n PatchRejection,\n // Patches\n SetStringPatch,\n SetNumberPatch,\n SetStringListPatch,\n SetCheckboxesPatch,\n SetSingleSelectPatch,\n SetMultiSelectPatch,\n SetUrlPatch,\n SetUrlListPatch,\n SetDatePatch,\n SetYearPatch,\n TableRowPatch,\n SetTablePatch,\n ClearFieldPatch,\n Patch,\n // Harness\n StepResult,\n HarnessConfig,\n SessionTurn,\n SessionTurnStats,\n SessionFinal,\n SessionTranscript,\n // Wire format (for session logging)\n WireFormat,\n WireRequestFormat,\n WireResponseFormat,\n WireResponseStep,\n WireToolCall,\n WireToolResult,\n // Frontmatter\n MarkformFrontmatter,\n FrontmatterHarnessConfig,\n // Run mode\n RunMode,\n // Validators\n ValidatorContext,\n ValidatorFn,\n ValidatorRegistry,\n} from './engine/coreTypes.js';\n\n// =============================================================================\n// Schema Exports\n// =============================================================================\n\nexport {\n // Basic schemas\n IdSchema,\n OptionIdSchema,\n ValidatorRefSchema,\n // Checkbox schemas\n MultiCheckboxStateSchema,\n SimpleCheckboxStateSchema,\n ExplicitCheckboxValueSchema,\n CheckboxValueSchema,\n CheckboxModeSchema,\n // Field schemas\n FieldKindSchema,\n OptionSchema,\n StringFieldSchema,\n NumberFieldSchema,\n StringListFieldSchema,\n CheckboxesFieldSchema,\n SingleSelectFieldSchema,\n MultiSelectFieldSchema,\n UrlFieldSchema,\n UrlListFieldSchema,\n DateFieldSchema,\n YearFieldSchema,\n // Table field schemas\n ColumnTypeNameSchema,\n TableColumnSchema,\n TableFieldSchema,\n CellResponseSchema,\n TableRowResponseSchema,\n FieldSchema,\n // Form schemas\n FieldGroupSchema,\n FormSchemaSchema,\n // Value schemas\n StringValueSchema,\n NumberValueSchema,\n StringListValueSchema,\n CheckboxesValueSchema,\n SingleSelectValueSchema,\n MultiSelectValueSchema,\n UrlValueSchema,\n UrlListValueSchema,\n DateValueSchema,\n YearValueSchema,\n TableValueSchema,\n FieldValueSchema,\n // Documentation schemas\n DocumentationTagSchema,\n DocumentationBlockSchema,\n // Validation schemas\n SeveritySchema,\n SourcePositionSchema,\n SourceRangeSchema,\n ValidationIssueSchema,\n // Inspect schemas\n IssueReasonSchema,\n IssueScopeSchema,\n InspectIssueSchema,\n // Answer state and field response schemas\n AnswerStateSchema,\n FieldResponseSchema,\n // Summary schemas\n ProgressStateSchema,\n CheckboxProgressCountsSchema,\n FieldProgressSchema,\n ProgressCountsSchema,\n ProgressSummarySchema,\n StructureSummarySchema,\n // Result schemas\n InspectResultSchema,\n ApplyResultSchema,\n // Patch schemas\n SetStringPatchSchema,\n SetNumberPatchSchema,\n SetStringListPatchSchema,\n SetCheckboxesPatchSchema,\n SetSingleSelectPatchSchema,\n SetMultiSelectPatchSchema,\n SetUrlPatchSchema,\n SetUrlListPatchSchema,\n SetDatePatchSchema,\n SetYearPatchSchema,\n TableRowPatchSchema,\n SetTablePatchSchema,\n ClearFieldPatchSchema,\n PatchSchema,\n // Harness schemas\n StepResultSchema,\n HarnessConfigSchema,\n SessionTurnSchema,\n SessionFinalSchema,\n SessionTranscriptSchema,\n // Wire format schemas\n WireFormatSchema,\n WireRequestFormatSchema,\n WireResponseFormatSchema,\n WireResponseStepSchema,\n WireToolCallSchema,\n WireToolResultSchema,\n // Frontmatter schemas\n MarkformFrontmatterSchema,\n MarkformSectionInputSchema,\n // Run mode schema\n RunModeSchema,\n} from './engine/coreTypes.js';\n\n// =============================================================================\n// Engine Exports\n// =============================================================================\n\nexport { parseForm } from './engine/parse.js';\nexport { serializeForm, serializeReport } from './engine/serialize.js';\nexport type { SerializeOptions } from './engine/serialize.js';\nexport {\n computeStructureSummary,\n computeProgressSummary,\n computeFormState,\n isFormComplete,\n computeAllSummaries,\n} from './engine/summaries.js';\nexport type { ComputedSummaries } from './engine/summaries.js';\nexport { validate } from './engine/validate.js';\nexport type { ValidateOptions, ValidateResult } from './engine/validate.js';\nexport { inspect } from './engine/inspect.js';\nexport type { InspectOptions } from './engine/inspect.js';\nexport { parseSession, serializeSession } from './engine/session.js';\nexport { applyPatches } from './engine/apply.js';\n\n// =============================================================================\n// Markdown Utilities\n// =============================================================================\n\nexport { findAllHeadings, findEnclosingHeadings } from './markdown/markdownHeaders.js';\nexport type { HeadingInfo } from './markdown/markdownHeaders.js';\n\n// =============================================================================\n// ID Injection\n// =============================================================================\n\nexport { findAllCheckboxes, injectCheckboxIds, injectHeaderIds } from './engine/injectIds.js';\nexport type {\n CheckboxInfo,\n InjectCheckboxIdsOptions,\n InjectHeaderIdsOptions,\n InjectIdsResult,\n} from './engine/injectIds.js';\n\n// =============================================================================\n// JSON Schema Export\n// =============================================================================\n\nexport { formToJsonSchema, fieldToJsonSchema } from './engine/jsonSchema.js';\nexport type {\n JsonSchemaOptions,\n JsonSchemaResult,\n JsonSchemaDraft,\n MarkformSchemaExtension,\n MarkformFieldExtension,\n} from './engine/jsonSchema.js';\n\n// =============================================================================\n// Table Parsing Exports\n// =============================================================================\n\nexport { parseMarkdownTable, parseCellValue, parseRawTable } from './engine/table/index.js';\nexport type { ParseTableResult, ParsedRawTable } from './engine/table/index.js';\n\n// =============================================================================\n// Scope Reference Exports\n// =============================================================================\n\nexport {\n parseScopeRef,\n serializeScopeRef,\n isCellRef,\n isQualifiedRef,\n isFieldRef,\n getFieldId,\n} from './engine/scopeRef.js';\nexport type {\n FieldScopeRef,\n QualifiedScopeRef,\n CellScopeRef,\n ParsedScopeRef,\n ParseScopeRefResult,\n} from './engine/scopeRef.js';\n\n// =============================================================================\n// Value Coercion Exports\n// =============================================================================\n\nexport { findFieldById, coerceToFieldPatch, coerceInputContext } from './engine/valueCoercion.js';\nexport type {\n RawFieldValue,\n InputContext,\n CoercionResult,\n CoerceInputContextResult,\n} from './engine/valueCoercion.js';\n\n// =============================================================================\n// Harness Exports\n// =============================================================================\n\nexport { FormHarness, createHarness } from './harness/harness.js';\nexport { MockAgent, createMockAgent } from './harness/mockAgent.js';\nexport { fillForm } from './harness/programmaticFill.js';\nexport { resolveHarnessConfig } from './harness/harnessConfigResolver.js';\nexport {\n ParallelHarness,\n createParallelHarness,\n scopeIssuesForItem,\n} from './harness/parallelHarness.js';\nexport type {\n ScopedFillRequest,\n ParallelHarnessConfig,\n ParallelStepResult,\n ParallelRunResult,\n} from './harness/parallelHarness.js';\nexport type {\n FillCallbacks,\n FillOptions,\n FillResult,\n FillStatus,\n TurnProgress,\n TurnStats,\n AgentResponse,\n} from './harness/harnessTypes.js';\n\n// =============================================================================\n// FillRecord Exports\n// =============================================================================\n\nexport { FillRecordCollector } from './harness/fillRecordCollector.js';\nexport type { FillRecordCollectorOptions } from './harness/fillRecordCollector.js';\nexport { formatFillRecordSummary } from './harness/formatFillRecordSummary.js';\nexport type { FormatFillRecordSummaryOptions } from './harness/formatFillRecordSummary.js';\nexport type {\n FillRecord,\n FillRecordStatus,\n TimelineEntry,\n ToolCallRecord,\n ToolStats,\n ToolSummary,\n TimingBreakdown,\n TimingBreakdownItem,\n ExecutionMetadata,\n} from './harness/fillRecord.js';\nexport {\n FillRecordSchema,\n FillRecordStatusSchema,\n TimelineEntrySchema,\n ToolCallRecordSchema,\n ToolStatsSchema,\n ToolSummarySchema,\n TimingBreakdownSchema,\n TimingBreakdownItemSchema,\n ExecutionMetadataSchema,\n} from './harness/fillRecord.js';\n\n// =============================================================================\n// Research Exports\n// =============================================================================\n\nexport { runResearch } from './research/runResearch.js';\nexport type { ResearchOptions } from './research/runResearch.js';\nexport { isResearchForm, validateResearchForm } from './research/researchFormValidation.js';\nexport type { ResearchResult, ResearchStatus } from './research/researchTypes.js';\n\n// =============================================================================\n// Error Exports\n// =============================================================================\n\nexport {\n // Error classes\n MarkformError,\n MarkformParseError,\n MarkformPatchError,\n MarkformValidationError,\n MarkformLlmError,\n MarkformConfigError,\n MarkformAbortError,\n // Backward compatibility alias (deprecated - use MarkformParseError)\n ParseError,\n // Type guards\n isMarkformError,\n isParseError,\n isPatchError,\n isValidationError,\n isLlmError,\n isConfigError,\n isAbortError,\n isRetryableError,\n} from './errors.js';\n"],"x_google_ignoreList":[14,15,16,17,18],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;ACTD,MAAM,eAAe;;AAGrB,MAAM,gBAAgB;;AAGtB,MAAM,wBAAwB;;;;;AAM9B,SAAS,2BAA2B,OAAuB;CACzD,MAAM,QAAQ,sBAAsB,KAAK,MAAM;AAC/C,KAAI,MACF,QAAO,MAAM;AAEf,QAAO;;;;;AAMT,SAAS,cAAc,OAAmE;CACxF,MAAM,UAAU,MAAM,MAAM;CAE5B,MAAM,YAAY,aAAa,KAAK,QAAQ;AAC5C,KAAI,UACF,QAAO;EAAE,MAAM;EAAQ,QAAQ,UAAU;EAAI;CAG/C,MAAM,aAAa,cAAc,KAAK,QAAQ;AAC9C,KAAI,WACF,QAAO;EAAE,MAAM;EAAS,QAAQ,WAAW;EAAI;AAGjD,QAAO;;;;;;AAWT,SAAgB,eAAe,UAAkB,YAA0C;CACzF,MAAM,UAA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PartyTypeKind2","ZodFirstPartyTypeKind3","zodSchema","TypeValidationError2","TypeValidationError3","InvalidArgumentError2","APICallError3","APICallError4","VERSION","zodSchema","z","lazySchema2","zodSchema2","z2","z3","lazySchema3","zodSchema3","z4","lazySchema4","zodSchema4","z5","lazySchema5","zodSchema5","z6","createProviderToolFactoryWithOutputSchema2","lazySchema6","zodSchema6","z7","createProviderToolFactoryWithOutputSchema3","lazySchema7","zodSchema7","z8","createProviderToolFactoryWithOutputSchema4","lazySchema8","zodSchema8","z9","createProviderToolFactoryWithOutputSchema5","UnsupportedFunctionalityError2","validateTypes2","parseProviderOptions2","createProviderToolFactory2","lazySchema9","zodSchema9","z10","createProviderToolFactory3","lazySchema10","zodSchema10","z11","createProviderToolFactory4","lazySchema11","zodSchema11","z12","createProviderToolFactory5","lazySchema12","zodSchema12","z13","createProviderToolFactory6","lazySchema13","zodSchema13","z14","createProviderToolFactory7","lazySchema14","zodSchema14","z15","createProviderToolFactory8","lazySchema15","zodSchema15","z16","createProviderToolFactory9","lazySchema16","zodSchema16","z17","createProviderToolFactory10","lazySchema17","zodSchema17","z18","lazySchema18","zodSchema18","z19","createProviderToolFactoryWithOutputSchema6","generateId2"],"sources":["../src/engine/fieldRegistry.ts","../src/engine/table/parseTable.ts","../src/engine/parseFields.ts","../src/markdown/markdownHeaders.ts","../src/engine/injectIds.ts","../src/engine/parse.ts","../src/engine/jsonSchema.ts","../src/engine/scopeRef.ts","../src/engine/valueCoercion.ts","../src/harness/harness.ts","../src/harness/mockAgent.ts","../src/engine/executionPlan.ts","../src/harness/timeUtils.ts","../src/harness/fillRecordCollector.ts","../../../node_modules/.pnpm/@ai-sdk+provider@3.0.6/node_modules/@ai-sdk/provider/dist/index.mjs","../../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js","../../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js","../../../node_modules/.pnpm/@ai-sdk+provider-utils@4.0.12_zod@4.3.6/node_modules/@ai-sdk/provider-utils/dist/index.mjs","../../../node_modules/.pnpm/@ai-sdk+anthropic@3.0.34_zod@4.3.6/node_modules/@ai-sdk/anthropic/dist/index.mjs","../src/harness/prompts.ts","../src/harness/toolApi.ts","../src/harness/liveAgent.ts","../src/harness/modelResolver.ts","../src/harness/parallelHarness.ts","../src/harness/programmaticFill.ts","../src/harness/harnessConfigResolver.ts","../src/harness/formatFillRecordSummary.ts","../src/harness/fillRecord.ts","../src/research/runResearch.ts","../src/research/researchFormValidation.ts","../src/index.ts"],"sourcesContent":["/**\n * Field Kind Registry - Single source of truth for field kind relationships.\n *\n * Note: This registry maps field *kinds* (e.g., 'string', 'checkboxes') to their\n * corresponding TypeScript types. The name \"FieldTypeMap\" is retained for stability\n * but conceptually maps kinds → types.\n *\n * This module defines the relationships between FieldKind, Field, FieldValue,\n * and Patch types in a type-safe way. Adding a new field kind requires:\n *\n * - Add the kind to FIELD_KINDS tuple below\n * - Add entry to FieldTypeMap interface\n * - Define the Field interface (extends FieldBase)\n * - Define the Value interface\n * - Define the SetPatch interface\n * - Add Zod schemas in the schemas section\n *\n * TypeScript will error if any of these are missing or inconsistent.\n */\n\nimport type { z } from 'zod';\n\n// =============================================================================\n// Field kinds (tuple for type inference)\n// =============================================================================\n\n/**\n * All field kinds as a const tuple - the single source of truth.\n * Adding a new kind here will cause TypeScript errors until all\n * corresponding types and handlers are added.\n */\nexport const FIELD_KINDS = [\n 'string',\n 'number',\n 'string_list',\n 'checkboxes',\n 'single_select',\n 'multi_select',\n 'url',\n 'url_list',\n 'date',\n 'year',\n 'table',\n] as const;\n\n/** Field kind discriminant - derived from the tuple */\nexport type FieldKind = (typeof FIELD_KINDS)[number];\n\n// =============================================================================\n// Type map - links kind to Field, Value, and Patch\n// =============================================================================\n\nimport type {\n StringField,\n NumberField,\n StringListField,\n CheckboxesField,\n SingleSelectField,\n MultiSelectField,\n UrlField,\n UrlListField,\n DateField,\n YearField,\n TableField,\n StringValue,\n NumberValue,\n StringListValue,\n CheckboxesValue,\n SingleSelectValue,\n MultiSelectValue,\n UrlValue,\n UrlListValue,\n DateValue,\n YearValue,\n TableValue,\n SetStringPatch,\n SetNumberPatch,\n SetStringListPatch,\n SetCheckboxesPatch,\n SetSingleSelectPatch,\n SetMultiSelectPatch,\n SetUrlPatch,\n SetUrlListPatch,\n SetDatePatch,\n SetYearPatch,\n SetTablePatch,\n} from './coreTypes.js';\n\n/**\n * Type map linking each field kind to its corresponding types.\n * TypeScript will error if any kind is missing from this map.\n */\nexport interface FieldTypeMap {\n string: {\n field: StringField;\n value: StringValue;\n patch: SetStringPatch;\n emptyValue: { kind: 'string'; value: null };\n };\n number: {\n field: NumberField;\n value: NumberValue;\n patch: SetNumberPatch;\n emptyValue: { kind: 'number'; value: null };\n };\n string_list: {\n field: StringListField;\n value: StringListValue;\n patch: SetStringListPatch;\n emptyValue: { kind: 'string_list'; items: [] };\n };\n checkboxes: {\n field: CheckboxesField;\n value: CheckboxesValue;\n patch: SetCheckboxesPatch;\n emptyValue: { kind: 'checkboxes'; values: Record<string, never> };\n };\n single_select: {\n field: SingleSelectField;\n value: SingleSelectValue;\n patch: SetSingleSelectPatch;\n emptyValue: { kind: 'single_select'; selected: null };\n };\n multi_select: {\n field: MultiSelectField;\n value: MultiSelectValue;\n patch: SetMultiSelectPatch;\n emptyValue: { kind: 'multi_select'; selected: [] };\n };\n url: {\n field: UrlField;\n value: UrlValue;\n patch: SetUrlPatch;\n emptyValue: { kind: 'url'; value: null };\n };\n url_list: {\n field: UrlListField;\n value: UrlListValue;\n patch: SetUrlListPatch;\n emptyValue: { kind: 'url_list'; items: [] };\n };\n date: {\n field: DateField;\n value: DateValue;\n patch: SetDatePatch;\n emptyValue: { kind: 'date'; value: null };\n };\n year: {\n field: YearField;\n value: YearValue;\n patch: SetYearPatch;\n emptyValue: { kind: 'year'; value: null };\n };\n table: {\n field: TableField;\n value: TableValue;\n patch: SetTablePatch;\n emptyValue: { kind: 'table'; rows: [] };\n };\n}\n\n// =============================================================================\n// Compile-time assertions - error if FieldTypeMap is incomplete\n// =============================================================================\n\n/**\n * Asserts that T has all keys from K.\n * Used to ensure FieldTypeMap covers all FieldKind values.\n */\ntype AssertAllKeys<K extends string, T extends Record<K, unknown>> = T;\n\n/** Compile-time check: FieldTypeMap must have entry for every FieldKind */\ntype _AssertMapComplete = AssertAllKeys<FieldKind, FieldTypeMap>;\n\n/** Compile-time check: FieldTypeMap keys must exactly match FieldKind */\ntype _AssertMapExact = keyof FieldTypeMap extends FieldKind\n ? FieldKind extends keyof FieldTypeMap\n ? true\n : never\n : never;\n\n// If either assertion fails, you'll get a type error here:\nconst _typeCheck: _AssertMapComplete = {} as FieldTypeMap;\nconst _exactCheck: _AssertMapExact = true;\n\n// =============================================================================\n// Derived union types - automatically include all registered types\n// =============================================================================\n\n/** Union of all Field kinds - derived from the registry */\nexport type Field = FieldTypeMap[FieldKind]['field'];\n\n/** Union of all FieldValue types - derived from the registry */\nexport type FieldValue = FieldTypeMap[FieldKind]['value'];\n\n/** Union of all set patch types - derived from the registry */\nexport type SetValuePatch = FieldTypeMap[FieldKind]['patch'];\n\n// =============================================================================\n// Exhaustiveness check helper\n// =============================================================================\n\n/**\n * Exhaustiveness check helper for switch statements.\n * If you add a new FieldKind but forget to handle it in a switch,\n * TypeScript will error because the kind won't be assignable to never.\n *\n * Usage:\n * ```ts\n * switch (field.kind) {\n * case \"string\": ...\n * case \"number\": ...\n * // ... all cases ...\n * default:\n * return assertNever(field.kind);\n * }\n * ```\n */\nexport function assertNever(x: never, message?: string): never {\n throw new Error(message ?? `Unexpected value: ${JSON.stringify(x)}`);\n}\n\n// =============================================================================\n// Empty value factory - type-safe way to create empty values\n// =============================================================================\n\n/**\n * Create an empty/default value for a field.\n * Exhaustiveness is checked at compile time.\n */\nexport function createEmptyValue(kind: FieldKind): FieldValue {\n switch (kind) {\n case 'string':\n return { kind: 'string', value: null };\n case 'number':\n return { kind: 'number', value: null };\n case 'string_list':\n return { kind: 'string_list', items: [] };\n case 'checkboxes':\n return { kind: 'checkboxes', values: {} };\n case 'single_select':\n return { kind: 'single_select', selected: null };\n case 'multi_select':\n return { kind: 'multi_select', selected: [] };\n case 'url':\n return { kind: 'url', value: null };\n case 'url_list':\n return { kind: 'url_list', items: [] };\n case 'date':\n return { kind: 'date', value: null };\n case 'year':\n return { kind: 'year', value: null };\n case 'table':\n return { kind: 'table', rows: [] };\n default:\n return assertNever(kind);\n }\n}\n\n// =============================================================================\n// Zod schema registry - ensures schemas match types\n// =============================================================================\n\nimport {\n StringFieldSchema,\n NumberFieldSchema,\n StringListFieldSchema,\n CheckboxesFieldSchema,\n SingleSelectFieldSchema,\n MultiSelectFieldSchema,\n UrlFieldSchema,\n UrlListFieldSchema,\n DateFieldSchema,\n YearFieldSchema,\n TableFieldSchema,\n StringValueSchema,\n NumberValueSchema,\n StringListValueSchema,\n CheckboxesValueSchema,\n SingleSelectValueSchema,\n MultiSelectValueSchema,\n UrlValueSchema,\n UrlListValueSchema,\n DateValueSchema,\n YearValueSchema,\n TableValueSchema,\n SetStringPatchSchema,\n SetNumberPatchSchema,\n SetStringListPatchSchema,\n SetCheckboxesPatchSchema,\n SetSingleSelectPatchSchema,\n SetMultiSelectPatchSchema,\n SetUrlPatchSchema,\n SetUrlListPatchSchema,\n SetDatePatchSchema,\n SetYearPatchSchema,\n SetTablePatchSchema,\n} from './coreTypes.js';\n\n/**\n * Zod schema registry - maps each kind to its schemas.\n * This ensures schemas are defined for every field kind.\n */\nexport const FIELD_SCHEMAS = {\n string: {\n field: StringFieldSchema,\n value: StringValueSchema,\n patch: SetStringPatchSchema,\n },\n number: {\n field: NumberFieldSchema,\n value: NumberValueSchema,\n patch: SetNumberPatchSchema,\n },\n string_list: {\n field: StringListFieldSchema,\n value: StringListValueSchema,\n patch: SetStringListPatchSchema,\n },\n checkboxes: {\n field: CheckboxesFieldSchema,\n value: CheckboxesValueSchema,\n patch: SetCheckboxesPatchSchema,\n },\n single_select: {\n field: SingleSelectFieldSchema,\n value: SingleSelectValueSchema,\n patch: SetSingleSelectPatchSchema,\n },\n multi_select: {\n field: MultiSelectFieldSchema,\n value: MultiSelectValueSchema,\n patch: SetMultiSelectPatchSchema,\n },\n url: {\n field: UrlFieldSchema,\n value: UrlValueSchema,\n patch: SetUrlPatchSchema,\n },\n url_list: {\n field: UrlListFieldSchema,\n value: UrlListValueSchema,\n patch: SetUrlListPatchSchema,\n },\n date: {\n field: DateFieldSchema,\n value: DateValueSchema,\n patch: SetDatePatchSchema,\n },\n year: {\n field: YearFieldSchema,\n value: YearValueSchema,\n patch: SetYearPatchSchema,\n },\n table: {\n field: TableFieldSchema,\n value: TableValueSchema,\n patch: SetTablePatchSchema,\n },\n} as const satisfies Record<\n FieldKind,\n {\n field: z.ZodType;\n value: z.ZodType;\n patch: z.ZodType;\n }\n>;\n\n/** Type-safe schema lookup by kind */\nexport function getFieldSchemas<K extends FieldKind>(kind: K) {\n return FIELD_SCHEMAS[kind];\n}\n","/**\n * Markdown Table Parsing for Table Fields.\n *\n * Parses GFM-style pipe tables from markdown content within table-field tags.\n * Handles cell value parsing with type coercion and sentinel detection.\n */\n\nimport type {\n TableColumn,\n ColumnTypeName,\n CellResponse,\n TableRowResponse,\n TableValue,\n Id,\n} from '../coreTypes.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Result of parsing a markdown table */\nexport type ParseTableResult = { ok: true; value: TableValue } | { ok: false; error: string };\n\n/** Parsed raw table structure before type coercion */\nexport interface ParsedRawTable {\n headers: string[];\n rows: string[][];\n}\n\n// =============================================================================\n// Sentinel Detection\n// =============================================================================\n\n/** Sentinel pattern: %SKIP% or %SKIP:reason% or %SKIP(reason)% */\nconst SKIP_PATTERN = /^%SKIP(?:[:(](.*))?[)]?%$/i;\n\n/** Sentinel pattern: %ABORT% or %ABORT:reason% or %ABORT(reason)% */\nconst ABORT_PATTERN = /^%ABORT(?:[:(](.*))?[)]?%$/i;\n\n/** Markdown link pattern: [text](url) */\nconst MARKDOWN_LINK_PATTERN = /^\\[([^\\]]*)\\]\\(([^)]+)\\)$/;\n\n/**\n * Extract URL from markdown link format if present.\n * Returns the URL part from [text](url) format, or the original value if not a markdown link.\n */\nfunction extractUrlFromMarkdownLink(value: string): string {\n const match = MARKDOWN_LINK_PATTERN.exec(value);\n if (match) {\n return match[2]!; // Return the URL part\n }\n return value;\n}\n\n/**\n * Detect if a cell value is a sentinel.\n */\nfunction parseSentinel(value: string): { type: 'skip' | 'abort'; reason?: string } | null {\n const trimmed = value.trim();\n\n const skipMatch = SKIP_PATTERN.exec(trimmed);\n if (skipMatch) {\n return { type: 'skip', reason: skipMatch[1] };\n }\n\n const abortMatch = ABORT_PATTERN.exec(trimmed);\n if (abortMatch) {\n return { type: 'abort', reason: abortMatch[1] };\n }\n\n return null;\n}\n\n// =============================================================================\n// Cell Value Parsing\n// =============================================================================\n\n/**\n * Parse a cell value according to its column type.\n * Returns a CellResponse with appropriate state.\n */\nexport function parseCellValue(rawValue: string, columnType: ColumnTypeName): CellResponse {\n const trimmed = rawValue.trim();\n\n // Check for empty cell\n if (!trimmed) {\n return { state: 'skipped' };\n }\n\n // Check for sentinels\n const sentinel = parseSentinel(trimmed);\n if (sentinel) {\n return {\n state: sentinel.type === 'skip' ? 'skipped' : 'aborted',\n reason: sentinel.reason,\n };\n }\n\n // Parse based on column type\n switch (columnType) {\n case 'string':\n return { state: 'answered', value: trimmed };\n\n case 'number': {\n const num = parseFloat(trimmed);\n if (isNaN(num)) {\n // Invalid number - treat as string but this will fail validation\n return { state: 'answered', value: trimmed };\n }\n return { state: 'answered', value: num };\n }\n\n case 'url': {\n // Extract URL from markdown link format if present (e.g., [text](url) -> url)\n // This handles round-trip where URLs are serialized as markdown links\n const url = extractUrlFromMarkdownLink(trimmed);\n return { state: 'answered', value: url };\n }\n\n case 'date':\n // Date format validation - more thorough validation happens in validate.ts\n return { state: 'answered', value: trimmed };\n\n case 'year': {\n const year = parseInt(trimmed, 10);\n if (isNaN(year) || !Number.isInteger(year)) {\n // Invalid year - treat as string but this will fail validation\n return { state: 'answered', value: trimmed };\n }\n return { state: 'answered', value: year };\n }\n }\n}\n\n// =============================================================================\n// Raw Table Parsing\n// =============================================================================\n\n/**\n * Parse markdown table structure without type coercion.\n * Handles GFM pipe table format.\n */\nexport function parseRawMarkdownTable(content: string): ParseTableResult {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length < 2) {\n // Empty table or just header is ok\n if (lines.length === 0) {\n return { ok: true, value: { kind: 'table', rows: [] } };\n }\n // Just header row without separator\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n // Parse header row\n const headerLine = lines[0]!;\n const headers = parseTableRow(headerLine);\n if (headers.length === 0) {\n return { ok: false, error: 'Invalid table header row' };\n }\n\n // Validate separator row\n const separatorLine = lines[1]!;\n if (!isValidSeparator(separatorLine, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n\n // Parse data rows\n const dataRows: string[][] = [];\n for (let i = 2; i < lines.length; i++) {\n const row = parseTableRow(lines[i]!);\n // Normalize row length to match headers\n while (row.length < headers.length) {\n row.push('');\n }\n if (row.length > headers.length) {\n row.length = headers.length;\n }\n dataRows.push(row);\n }\n\n return {\n ok: true,\n value: { kind: 'table', rows: [] }, // Placeholder - actual rows are built with column context\n };\n}\n\n/**\n * Parse a table row into cell values.\n * Handles leading/trailing pipes and cell trimming.\n */\nfunction parseTableRow(line: string): string[] {\n let trimmed = line.trim();\n\n // Remove leading pipe\n if (trimmed.startsWith('|')) {\n trimmed = trimmed.slice(1);\n }\n\n // Remove trailing pipe\n if (trimmed.endsWith('|')) {\n trimmed = trimmed.slice(0, -1);\n }\n\n // Split by pipe and trim each cell\n return trimmed.split('|').map((cell) => cell.trim());\n}\n\n/**\n * Extract header labels from table content.\n * Returns array of header labels from the first row, or empty array if no valid header.\n */\nexport function extractTableHeaderLabels(content: string | null): string[] {\n if (!content || content.trim() === '') {\n return [];\n }\n\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length === 0) {\n return [];\n }\n\n return parseTableRow(lines[0]!);\n}\n\n/**\n * Check if a line is a valid table separator row.\n * Each cell should contain only dashes and optional colons for alignment.\n */\nfunction isValidSeparator(line: string, expectedCols: number): boolean {\n const cells = parseTableRow(line);\n\n // Must have same number of columns as header\n if (cells.length !== expectedCols) {\n return false;\n }\n\n // Each cell must match the separator pattern\n const separatorPattern = /^:?-+:?$/;\n return cells.every((cell) => separatorPattern.test(cell.trim()));\n}\n\n// =============================================================================\n// Full Table Parsing with Schema\n// =============================================================================\n\n/**\n * Parse a markdown table with column schema for type coercion.\n *\n * @param content - The markdown table content\n * @param columns - Column definitions from the table field schema\n * @param dataStartLine - Optional line index where data rows start (skips header validation)\n * @returns Parsed table value with typed cells\n */\nexport function parseMarkdownTable(\n content: string,\n columns: TableColumn[],\n dataStartLine?: number,\n): ParseTableResult {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n // Empty content - return empty table\n if (lines.length === 0) {\n return { ok: true, value: { kind: 'table', rows: [] } };\n }\n\n // Need at least header and separator (unless empty)\n if (lines.length < 2) {\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n // Parse header row\n const headerLine = lines[0]!;\n const headers = parseTableRow(headerLine);\n\n // Validate separator row\n const separatorLine = lines[1]!;\n if (!isValidSeparator(separatorLine, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n\n // When dataStartLine is provided, parse data positionally based on columns\n // (attribute-based column definitions)\n if (dataStartLine !== undefined) {\n const rows: TableRowResponse[] = [];\n\n for (let i = dataStartLine; i < lines.length; i++) {\n const rawCells = parseTableRow(lines[i]!);\n const row: TableRowResponse = {};\n\n for (let j = 0; j < columns.length; j++) {\n const column = columns[j]!;\n const rawValue = rawCells[j] ?? '';\n row[column.id] = parseCellValue(rawValue, column.type);\n }\n\n rows.push(row);\n }\n\n return { ok: true, value: { kind: 'table', rows } };\n }\n\n // Build column ID to index mapping from headers (for inline column parsing)\n // Headers should match column IDs or labels\n const columnIdToIndex = new Map<Id, number>();\n\n for (let i = 0; i < headers.length; i++) {\n const header = headers[i]!;\n // Find column by ID or label\n const column = columns.find((c) => c.id === header || c.label === header);\n if (column) {\n columnIdToIndex.set(column.id, i);\n }\n }\n\n // Parse data rows\n const rows: TableRowResponse[] = [];\n\n for (let i = 2; i < lines.length; i++) {\n const rawCells = parseTableRow(lines[i]!);\n const row: TableRowResponse = {};\n\n // Process each column\n for (const column of columns) {\n const cellIndex = columnIdToIndex.get(column.id);\n const rawValue = cellIndex !== undefined ? (rawCells[cellIndex] ?? '') : '';\n row[column.id] = parseCellValue(rawValue, column.type);\n }\n\n rows.push(row);\n }\n\n return { ok: true, value: { kind: 'table', rows } };\n}\n\n/**\n * Parse just the raw table structure without schema.\n * Useful for validation and error reporting.\n */\nexport function parseRawTable(\n content: string,\n): { ok: true; headers: string[]; rows: string[][] } | { ok: false; error: string } {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length === 0) {\n return { ok: true, headers: [], rows: [] };\n }\n\n if (lines.length < 2) {\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n const headers = parseTableRow(lines[0]!);\n const separatorLine = lines[1]!;\n\n if (!isValidSeparator(separatorLine, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n\n const rows: string[][] = [];\n for (let i = 2; i < lines.length; i++) {\n const row = parseTableRow(lines[i]!);\n // Normalize row length\n while (row.length < headers.length) {\n row.push('');\n }\n if (row.length > headers.length) {\n row.length = headers.length;\n }\n rows.push(row);\n }\n\n return { ok: true, headers, rows };\n}\n\n// =============================================================================\n// Column Extraction from Inline Table\n// =============================================================================\n\n/**\n * Result of extracting column definitions from inline table format.\n */\nexport type ExtractColumnsResult =\n | {\n ok: true;\n columns: TableColumn[];\n dataStartLine: number; // Line index where data rows start (after separator)\n }\n | {\n ok: false;\n error: string;\n };\n\n/**\n * Slugify a label to create a valid column ID.\n * Converts \"Start Date\" -> \"start_date\", \"Name\" -> \"name\", etc.\n */\nfunction slugify(label: string): string {\n return label\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '');\n}\n\n/**\n * Check if a cell value looks like a column type definition.\n * Valid formats: \"string\", \"number\", \"url\", \"date\", \"year\"\n * With optional \",required\" suffix.\n */\nfunction isTypeDefinition(cell: string): boolean {\n const typePattern = /^(string|number|url|date|year)(,required)?$/i;\n return typePattern.test(cell.trim());\n}\n\n/**\n * Parse a column type definition cell.\n * Format: \"type\" or \"type,required\"\n */\nfunction parseTypeCell(cell: string): { type: ColumnTypeName; required: boolean } {\n const trimmed = cell.trim().toLowerCase();\n const parts = trimmed.split(',');\n const type = parts[0] as ColumnTypeName;\n const required = parts.length > 1 && parts[1] === 'required';\n return { type, required };\n}\n\n/**\n * Extract column definitions from inline table format.\n *\n * Supports two formats:\n * 1. Simple format (header + separator + data):\n * | Name | Age |\n * |------|-----|\n * | Alice | 30 |\n * -> Columns default to type=string, required=false\n *\n * 2. Full format (header + type row + separator + data):\n * | Name | Age |\n * | string,required | number |\n * |------|-----|\n * | Alice | 30 |\n */\nexport function extractColumnsFromTable(content: string): ExtractColumnsResult {\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n if (lines.length < 2) {\n return { ok: false, error: 'Table must have at least a header and separator row' };\n }\n\n // Parse header row\n const headers = parseTableRow(lines[0]!);\n if (headers.length === 0) {\n return { ok: false, error: 'Invalid table header row' };\n }\n\n // Check second row - is it a type row or separator?\n const secondRow = parseTableRow(lines[1]!);\n const isSecondRowTypes =\n secondRow.length > 0 && secondRow.every((cell) => isTypeDefinition(cell));\n\n let typeRow: { type: ColumnTypeName; required: boolean }[] | undefined;\n let separatorLineIndex: number;\n\n if (isSecondRowTypes) {\n // Second row is type definitions\n if (secondRow.length !== headers.length) {\n return { ok: false, error: 'Type row must have same number of columns as header' };\n }\n typeRow = secondRow.map((cell) => parseTypeCell(cell));\n separatorLineIndex = 2;\n\n // Validate we have a separator row\n if (lines.length < 3) {\n return { ok: false, error: 'Table with type row must have a separator row' };\n }\n if (!isValidSeparator(lines[2]!, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n } else {\n // Second row should be separator\n if (!isValidSeparator(lines[1]!, headers.length)) {\n return { ok: false, error: 'Invalid table separator row' };\n }\n separatorLineIndex = 1;\n }\n\n // Build columns\n const columns: TableColumn[] = headers.map((header, i) => {\n const id = slugify(header) || `col${i}`;\n const label = header;\n const typeDef = typeRow?.[i] ?? { type: 'string' as ColumnTypeName, required: false };\n return {\n id,\n label,\n type: typeDef.type,\n required: typeDef.required,\n };\n });\n\n return {\n ok: true,\n columns,\n dataStartLine: separatorLineIndex + 1,\n };\n}\n\n/**\n * Parse a markdown table with columns extracted from inline format.\n * Used when columnIds attribute is not provided.\n */\nexport function parseInlineTable(content: string): ParseTableResult {\n const extractResult = extractColumnsFromTable(content);\n if (!extractResult.ok) {\n return { ok: false, error: extractResult.error };\n }\n\n const { columns, dataStartLine } = extractResult;\n const lines = content\n .trim()\n .split('\\n')\n .filter((line) => line.trim());\n\n // Parse data rows\n const rows: TableRowResponse[] = [];\n for (let i = dataStartLine; i < lines.length; i++) {\n const rawCells = parseTableRow(lines[i]!);\n const row: TableRowResponse = {};\n\n for (let j = 0; j < columns.length; j++) {\n const column = columns[j]!;\n const rawValue = rawCells[j] ?? '';\n row[column.id] = parseCellValue(rawValue, column.type);\n }\n\n rows.push(row);\n }\n\n return { ok: true, value: { kind: 'table', rows } };\n}\n","/**\n * Field kind parsers for Markform.\n *\n * This module contains the parsing logic for each field kind:\n * string, number, string-list, single-select, multi-select, checkboxes,\n * url, url-list, date, and year.\n */\n\nimport type { Node } from '@markdoc/markdoc';\n\nimport { AGENT_ROLE, DEFAULT_PRIORITY } from '../settings.js';\nimport { FIELD_KINDS, type FieldKind } from './fieldRegistry.js';\nimport type {\n ApprovalMode,\n CheckboxesField,\n CheckboxesValue,\n CheckboxMode,\n CheckboxValue,\n ColumnTypeName,\n ColumnTypeSpec,\n DateField,\n DateValue,\n Field,\n FieldResponse,\n FieldValue,\n MultiSelectField,\n MultiSelectValue,\n NumberField,\n NumberValue,\n Option,\n SingleSelectField,\n SingleSelectValue,\n StringField,\n StringListField,\n StringListValue,\n StringValue,\n TableColumn,\n TableField,\n TableValue,\n UrlField,\n UrlListField,\n UrlListValue,\n UrlValue,\n ValidatorRef,\n YearField,\n YearValue,\n} from './coreTypes.js';\nimport {\n CHECKBOX_MARKERS,\n extractFenceValue,\n extractTableContent,\n extractOptionItems,\n getBooleanAttr,\n getNumberAttr,\n getStringArrayAttr,\n getStringAttr,\n getValidateAttr,\n isTagNode,\n parseOptionText,\n} from './parseHelpers.js';\nimport { MarkformParseError } from '../errors.js';\nimport { tryParseSentinelResponse } from './parseSentinels.js';\nimport { parseMarkdownTable, extractTableHeaderLabels } from './table/parseTable.js';\n\n// =============================================================================\n// Field Response Helpers\n// =============================================================================\n\n/**\n * Determine if a field value is empty.\n * For old forms without state attributes, this infers whether the field has been filled.\n */\nexport function isValueEmpty(value: FieldValue): boolean {\n switch (value.kind) {\n case 'string':\n case 'number':\n case 'url':\n case 'date':\n case 'year':\n return value.value === null;\n case 'string_list':\n case 'url_list':\n return value.items.length === 0;\n case 'single_select':\n return value.selected === null;\n case 'multi_select':\n return value.selected.length === 0;\n case 'checkboxes': {\n // Empty if all checkboxes are in default unchecked state (todo/unfilled)\n const values = Object.values(value.values);\n return values.every((v) => v === 'todo' || v === 'unfilled');\n }\n case 'table':\n return (value.rows?.length ?? 0) === 0;\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = value;\n throw new Error(`Unhandled field value kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n}\n\n/**\n * Create a FieldResponse from a FieldValue.\n * For old forms without state attributes, infers state from value content.\n */\nfunction createFieldResponse(value: FieldValue): FieldResponse {\n if (isValueEmpty(value)) {\n return { state: 'unanswered' };\n }\n return { state: 'answered', value };\n}\n\n/**\n * Parse state attribute from field node and validate consistency.\n * Returns a FieldResponse based on state attribute, sentinel values, or value content.\n */\nexport function parseFieldResponse(\n node: Node,\n value: FieldValue,\n fieldId: string,\n required: boolean,\n): FieldResponse {\n const stateAttr = getStringAttr(node, 'state');\n const isFilled = !isValueEmpty(value);\n\n // Validate state attribute value if present\n if (stateAttr !== undefined) {\n if (\n stateAttr !== 'empty' &&\n stateAttr !== 'answered' &&\n stateAttr !== 'skipped' &&\n stateAttr !== 'aborted'\n ) {\n throw new MarkformParseError(\n `Invalid state attribute '${stateAttr}' on field '${fieldId}'. Must be empty, answered, skipped, or aborted`,\n );\n }\n\n // Validate state vs filled consistency\n if (stateAttr === 'skipped' || stateAttr === 'aborted') {\n if (isFilled) {\n throw new MarkformParseError(\n `Field '${fieldId}' has state='${stateAttr}' but contains a value. ${stateAttr} fields cannot have values.`,\n );\n }\n }\n\n // Validate skipped on required fields\n if (stateAttr === 'skipped' && required) {\n throw new MarkformParseError(\n `Field '${fieldId}' is required but has state='skipped'. Cannot skip required fields.`,\n );\n }\n\n // Return response based on explicit state attribute\n if (stateAttr === 'skipped') {\n return { state: 'skipped' };\n }\n if (stateAttr === 'aborted') {\n return { state: 'aborted' };\n }\n if (stateAttr === 'empty') {\n return { state: 'unanswered' };\n }\n if (stateAttr === 'answered') {\n if (!isFilled) {\n throw new MarkformParseError(`Field '${fieldId}' has state='answered' but has no value`);\n }\n return { state: 'answered', value };\n }\n }\n\n // No state attribute - infer from value content (backward compatibility)\n return createFieldResponse(value);\n}\n\n/**\n * Get priority attribute value or default to DEFAULT_PRIORITY.\n */\nfunction getPriorityAttr(node: Node): 'high' | 'medium' | 'low' {\n const value = getStringAttr(node, 'priority');\n if (value === 'high' || value === 'medium' || value === 'low') {\n return value;\n }\n return DEFAULT_PRIORITY;\n}\n\n// =============================================================================\n// Common Field Attribute Helpers\n// =============================================================================\n\ninterface BaseFieldAttrs {\n id: string;\n label: string;\n required: boolean;\n}\n\n/**\n * Parse and validate base field attributes (id, label, required).\n * Throws ParseError if id or label is missing.\n */\nfunction parseBaseFieldAttrs(node: Node, kind: FieldKind): BaseFieldAttrs {\n const id = getStringAttr(node, 'id');\n const label = getStringAttr(node, 'label');\n\n if (!id) {\n throw new MarkformParseError(`field kind=\"${kind}\" missing required 'id' attribute`);\n }\n if (!label) {\n throw new MarkformParseError(`field '${id}' missing required 'label' attribute`);\n }\n\n const required = getBooleanAttr(node, 'required') ?? false;\n return { id, label, required };\n}\n\ninterface CommonFieldAttrs {\n priority: 'high' | 'medium' | 'low';\n role: string;\n validate?: ValidatorRef[];\n report?: boolean;\n parallel?: string;\n order?: number;\n}\n\n/**\n * Get common field attributes (priority, role, validate, report, parallel, order).\n */\nfunction getCommonFieldAttrs(node: Node): CommonFieldAttrs {\n return {\n priority: getPriorityAttr(node),\n role: getStringAttr(node, 'role') ?? AGENT_ROLE,\n validate: getValidateAttr(node),\n report: getBooleanAttr(node, 'report'),\n parallel: getStringAttr(node, 'parallel'),\n order: getNumberAttr(node, 'order'),\n };\n}\n\n// =============================================================================\n// Placeholder/Examples Validation Helpers\n// =============================================================================\n\n/**\n * Validate that placeholder/examples are not used on chooser fields.\n * Throws ParseError if either attribute is present.\n */\nfunction validateNoPlaceholderExamples(node: Node, fieldType: string, fieldId: string): void {\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n if (placeholder !== undefined) {\n throw new MarkformParseError(\n `${fieldType} '${fieldId}' has 'placeholder' attribute, but placeholder is only valid on text-entry fields (string, number, string-list, url, url-list)`,\n );\n }\n if (examples !== undefined) {\n throw new MarkformParseError(\n `${fieldType} '${fieldId}' has 'examples' attribute, but examples is only valid on text-entry fields (string, number, string-list, url, url-list)`,\n );\n }\n}\n\n/**\n * Check if a string is a valid URL.\n */\nfunction isValidUrl(str: string): boolean {\n try {\n new URL(str);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Validate examples for number fields - all must parse as numbers.\n */\nfunction validateNumberExamples(examples: string[] | undefined, fieldId: string): void {\n if (!examples) return;\n for (const example of examples) {\n const parsed = Number(example);\n if (Number.isNaN(parsed)) {\n throw new MarkformParseError(\n `number-field '${fieldId}' has invalid example '${example}' - must be a valid number`,\n );\n }\n }\n}\n\n/**\n * Validate examples for URL fields - all must be valid URLs.\n */\nfunction validateUrlExamples(examples: string[] | undefined, fieldId: string): void {\n if (!examples) return;\n for (const example of examples) {\n if (!isValidUrl(example)) {\n throw new MarkformParseError(\n `url-field '${fieldId}' has invalid example '${example}' - must be a valid URL`,\n );\n }\n }\n}\n\n/**\n * Warn if placeholder doesn't match the expected type.\n * Returns a warning message or undefined.\n * Note: Currently unused as the warning system is not yet implemented.\n */\nfunction _warnPlaceholderTypeMismatch(\n placeholder: string | undefined,\n fieldType: 'number' | 'url',\n fieldId: string,\n): string | undefined {\n if (!placeholder) return undefined;\n\n if (fieldType === 'number') {\n const parsed = Number(placeholder);\n if (Number.isNaN(parsed)) {\n return `number-field '${fieldId}' has placeholder '${placeholder}' that doesn't parse as a number`;\n }\n } else if (fieldType === 'url') {\n if (!isValidUrl(placeholder)) {\n return `url-field '${fieldId}' has placeholder '${placeholder}' that doesn't look like a valid URL`;\n }\n }\n return undefined;\n}\n\n// =============================================================================\n// String Field Parser\n// =============================================================================\n\n/**\n * Parse a string-field tag.\n */\nexport function parseStringField(node: Node): { field: StringField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'string');\n\n const field: StringField = {\n kind: 'string',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n multiline: getBooleanAttr(node, 'multiline'),\n pattern: getStringAttr(node, 'pattern'),\n minLength: getNumberAttr(node, 'minLength'),\n maxLength: getNumberAttr(node, 'maxLength'),\n placeholder: getStringAttr(node, 'placeholder'),\n examples: getStringArrayAttr(node, 'examples'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : null;\n const value: StringValue = {\n kind: 'string',\n value: trimmedContent,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Number Field Parser\n// =============================================================================\n\n/**\n * Parse a number-field tag.\n */\nexport function parseNumberField(node: Node): { field: NumberField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'number');\n\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n // Validate examples are valid numbers\n validateNumberExamples(examples, id);\n\n // Note: Placeholder type mismatch is a warning, not an error\n // The warnPlaceholderTypeMismatch function is available but warnings are not yet surfaced\n\n const field: NumberField = {\n kind: 'number',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n min: getNumberAttr(node, 'min'),\n max: getNumberAttr(node, 'max'),\n integer: getBooleanAttr(node, 'integer'),\n placeholder,\n examples,\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse number normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : '';\n let numValue: number | null = null;\n if (trimmedContent) {\n const parsed = Number(trimmedContent);\n if (!Number.isNaN(parsed)) {\n numValue = parsed;\n }\n }\n\n const value: NumberValue = {\n kind: 'number',\n value: numValue,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// String List Field Parser\n// =============================================================================\n\n/**\n * Parse a string-list tag.\n */\nexport function parseStringListField(node: Node): {\n field: StringListField;\n response: FieldResponse;\n} {\n const { id, label, required } = parseBaseFieldAttrs(node, 'string_list');\n\n const field: StringListField = {\n kind: 'string_list',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n minItems: getNumberAttr(node, 'minItems'),\n maxItems: getNumberAttr(node, 'maxItems'),\n itemMinLength: getNumberAttr(node, 'itemMinLength'),\n itemMaxLength: getNumberAttr(node, 'itemMaxLength'),\n uniqueItems: getBooleanAttr(node, 'uniqueItems'),\n placeholder: getStringAttr(node, 'placeholder'),\n examples: getStringArrayAttr(node, 'examples'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse list normally\n const fenceContent = extractFenceValue(node);\n const items: string[] = [];\n if (fenceContent !== null) {\n const lines = fenceContent.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n items.push(trimmed);\n }\n }\n }\n\n const value: StringListValue = {\n kind: 'string_list',\n items,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Option Parsing (for Select/Checkbox fields)\n// =============================================================================\n\n/**\n * Parse options from a select/checkbox field.\n */\nfunction parseOptions(\n node: Node,\n fieldId: string,\n): { options: Option[]; selected: Record<string, CheckboxValue> } {\n const items = extractOptionItems(node);\n const options: Option[] = [];\n const selected: Record<string, CheckboxValue> = {};\n const seenIds = new Set<string>();\n\n for (const item of items) {\n const parsed = parseOptionText(item.text);\n if (!parsed) {\n continue;\n }\n\n if (!item.id) {\n throw new MarkformParseError(\n `Option in field '${fieldId}' missing ID annotation. Use {% #option_id %}`,\n );\n }\n\n if (seenIds.has(item.id)) {\n throw new MarkformParseError(`Duplicate option ID '${item.id}' in field '${fieldId}'`);\n }\n seenIds.add(item.id);\n\n options.push({ id: item.id, label: parsed.label });\n\n const state = CHECKBOX_MARKERS[parsed.marker];\n if (state !== undefined) {\n selected[item.id] = state;\n }\n }\n\n return { options, selected };\n}\n\n// =============================================================================\n// Single Select Field Parser\n// =============================================================================\n\n/**\n * Parse a single-select tag.\n */\nexport function parseSingleSelectField(node: Node): {\n field: SingleSelectField;\n response: FieldResponse;\n} {\n const { id, label, required } = parseBaseFieldAttrs(node, 'single_select');\n\n // Validate that placeholder/examples are not used on chooser fields\n validateNoPlaceholderExamples(node, 'single-select', id);\n\n const { options, selected } = parseOptions(node, id);\n\n const field: SingleSelectField = {\n kind: 'single_select',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n options,\n };\n\n // Find the selected option (exactly one with done/[x] state)\n let selectedOption: string | null = null;\n for (const [optId, state] of Object.entries(selected)) {\n if (state === 'done') {\n selectedOption = optId;\n break;\n }\n }\n\n const value: SingleSelectValue = {\n kind: 'single_select',\n selected: selectedOption,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Multi Select Field Parser\n// =============================================================================\n\n/**\n * Parse a multi-select tag.\n */\nexport function parseMultiSelectField(node: Node): {\n field: MultiSelectField;\n response: FieldResponse;\n} {\n const { id, label, required } = parseBaseFieldAttrs(node, 'multi_select');\n\n // Validate that placeholder/examples are not used on chooser fields\n validateNoPlaceholderExamples(node, 'multi-select', id);\n\n const { options, selected } = parseOptions(node, id);\n\n const field: MultiSelectField = {\n kind: 'multi_select',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n options,\n minSelections: getNumberAttr(node, 'minSelections'),\n maxSelections: getNumberAttr(node, 'maxSelections'),\n };\n\n // Collect all selected options (those with done/[x] state)\n const selectedOptions: string[] = [];\n for (const [optId, state] of Object.entries(selected)) {\n if (state === 'done') {\n selectedOptions.push(optId);\n }\n }\n\n const value: MultiSelectValue = {\n kind: 'multi_select',\n selected: selectedOptions,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Checkboxes Field Parser\n// =============================================================================\n\n/**\n * Parse a checkboxes tag.\n */\nexport function parseCheckboxesField(node: Node): {\n field: CheckboxesField;\n response: FieldResponse;\n} {\n // Checkboxes has special id/label handling (can't use parseBaseFieldAttrs due to required logic)\n const id = getStringAttr(node, 'id');\n const label = getStringAttr(node, 'label');\n\n if (!id) {\n throw new MarkformParseError('field kind=\"checkboxes\" missing required \\'id\\' attribute');\n }\n if (!label) {\n throw new MarkformParseError(`field '${id}' missing required 'label' attribute`);\n }\n\n // Validate that placeholder/examples are not used on chooser fields\n validateNoPlaceholderExamples(node, 'checkboxes', id);\n\n const { options, selected } = parseOptions(node, id);\n\n const checkboxModeStr = getStringAttr(node, 'checkboxMode');\n let checkboxMode: CheckboxMode = 'multi'; // default\n if (\n checkboxModeStr === 'multi' ||\n checkboxModeStr === 'simple' ||\n checkboxModeStr === 'explicit'\n ) {\n checkboxMode = checkboxModeStr;\n }\n\n const approvalModeStr = getStringAttr(node, 'approvalMode');\n let approvalMode: ApprovalMode = 'none'; // default\n if (approvalModeStr === 'blocking') {\n approvalMode = 'blocking';\n }\n\n // Handle required attribute based on checkboxMode:\n // - explicit mode is inherently required (cannot be set to false)\n // - multi/simple modes default to optional (false)\n const explicitRequired = getBooleanAttr(node, 'required');\n let required: boolean;\n if (checkboxMode === 'explicit') {\n if (explicitRequired === false) {\n throw new MarkformParseError(\n `Checkbox field \"${label}\" has checkboxMode=\"explicit\" which is inherently required. ` +\n `Cannot set required=false. Remove required attribute or change checkboxMode.`,\n );\n }\n required = true; // explicit mode is always required\n } else {\n required = explicitRequired ?? false; // multi/simple default to optional\n }\n\n const field: CheckboxesField = {\n kind: 'checkboxes',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n checkboxMode,\n minDone: getNumberAttr(node, 'minDone'),\n options,\n approvalMode,\n };\n\n // Initialize all options to their default state based on mode\n const values: Record<string, CheckboxValue> = {};\n\n for (const opt of options) {\n const state = selected[opt.id];\n if (state === undefined || state === 'todo') {\n // For explicit mode, \"todo\" (from [ ]) means \"unfilled\"\n values[opt.id] = checkboxMode === 'explicit' ? 'unfilled' : 'todo';\n } else {\n values[opt.id] = state;\n }\n }\n\n const value: CheckboxesValue = {\n kind: 'checkboxes',\n values,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// URL Field Parser\n// =============================================================================\n\n/**\n * Parse a url-field tag.\n */\nexport function parseUrlField(node: Node): { field: UrlField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'url');\n\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n // Validate examples are valid URLs\n validateUrlExamples(examples, id);\n\n // Note: Placeholder type mismatch is a warning, not an error\n\n const field: UrlField = {\n kind: 'url',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n placeholder,\n examples,\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : null;\n const value: UrlValue = {\n kind: 'url',\n value: trimmedContent,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// URL List Field Parser\n// =============================================================================\n\n/**\n * Parse a url-list tag.\n */\nexport function parseUrlListField(node: Node): { field: UrlListField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'url_list');\n\n const placeholder = getStringAttr(node, 'placeholder');\n const examples = getStringArrayAttr(node, 'examples');\n\n // Validate examples are valid URLs\n validateUrlExamples(examples, id);\n\n // Note: Placeholder type mismatch is a warning, not an error\n\n const field: UrlListField = {\n kind: 'url_list',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n minItems: getNumberAttr(node, 'minItems'),\n maxItems: getNumberAttr(node, 'maxItems'),\n uniqueItems: getBooleanAttr(node, 'uniqueItems'),\n placeholder,\n examples,\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse list normally\n const fenceContent = extractFenceValue(node);\n const items: string[] = [];\n if (fenceContent !== null) {\n const lines = fenceContent.split('\\n');\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n items.push(trimmed);\n }\n }\n }\n\n const value: UrlListValue = {\n kind: 'url_list',\n items,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Date Field Parser\n// =============================================================================\n\n/**\n * Parse a date-field tag.\n */\nexport function parseDateField(node: Node): { field: DateField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'date');\n\n const field: DateField = {\n kind: 'date',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n min: getStringAttr(node, 'min'),\n max: getStringAttr(node, 'max'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse normally\n // Convert empty strings to null explicitly (nullish coalescing doesn't work for empty strings)\n const fenceContent = extractFenceValue(node);\n let dateValue: string | null = null;\n if (fenceContent !== null) {\n const trimmed = fenceContent.trim();\n if (trimmed.length > 0) {\n dateValue = trimmed;\n }\n }\n const value: DateValue = {\n kind: 'date',\n value: dateValue,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Year Field Parser\n// =============================================================================\n\n/**\n * Parse a year-field tag.\n */\nexport function parseYearField(node: Node): { field: YearField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'year');\n\n const field: YearField = {\n kind: 'year',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n min: getNumberAttr(node, 'min'),\n max: getNumberAttr(node, 'max'),\n };\n\n // Check for sentinel values first\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n // No sentinel - parse year normally\n const fenceContent = extractFenceValue(node);\n const trimmedContent = fenceContent !== null ? fenceContent.trim() : '';\n let yearValue: number | null = null;\n if (trimmedContent) {\n const parsed = Number.parseInt(trimmedContent, 10);\n if (!Number.isNaN(parsed)) {\n yearValue = parsed;\n }\n }\n\n const value: YearValue = {\n kind: 'year',\n value: yearValue,\n };\n\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Table Field Parser\n// =============================================================================\n\n/**\n * Validate column type string.\n */\nfunction isValidColumnType(type: unknown): type is ColumnTypeName {\n return (\n type === 'string' || type === 'number' || type === 'url' || type === 'date' || type === 'year'\n );\n}\n\n/**\n * Parse column definitions from attributes.\n * columnIds is required. columnLabels is optional (backfilled from tableHeaderLabels if provided).\n */\nfunction parseColumnsFromAttributes(\n node: Node,\n fieldId: string,\n tableHeaderLabels?: string[],\n): TableColumn[] {\n const columnIds = getStringArrayAttr(node, 'columnIds');\n const columnLabels = getStringArrayAttr(node, 'columnLabels');\n const columnTypesRaw = node.attributes?.columnTypes as ColumnTypeSpec[] | undefined;\n\n if (!columnIds || columnIds.length === 0) {\n throw new MarkformParseError(\n `table-field '${fieldId}' requires 'columnIds' attribute. ` +\n `Example: columnIds=[\"name\", \"title\", \"department\"]`,\n );\n }\n\n // Validate unique column IDs\n const seenIds = new Set<string>();\n for (const id of columnIds) {\n if (seenIds.has(id)) {\n throw new MarkformParseError(`table-field '${fieldId}' has duplicate column ID '${id}'`);\n }\n seenIds.add(id);\n }\n\n const columns: TableColumn[] = [];\n for (let i = 0; i < columnIds.length; i++) {\n const id = columnIds[i]!;\n // Priority: explicit columnLabels > table header labels > column ID\n const label = columnLabels?.[i] ?? tableHeaderLabels?.[i] ?? id;\n\n // Parse column type - can be string or { type, required }\n const typeSpec = columnTypesRaw?.[i];\n let type: ColumnTypeName = 'string'; // default\n let required = false;\n\n if (typeSpec !== undefined) {\n if (typeof typeSpec === 'string') {\n if (!isValidColumnType(typeSpec)) {\n throw new MarkformParseError(\n `table-field '${fieldId}' has invalid column type '${String(typeSpec)}' for column '${id}'. ` +\n `Valid types: string, number, url, date, year`,\n );\n }\n type = typeSpec;\n } else if (typeof typeSpec === 'object' && typeSpec !== null) {\n const typeObj = typeSpec as { type?: unknown; required?: boolean };\n if (!isValidColumnType(typeObj.type)) {\n throw new MarkformParseError(\n `table-field '${fieldId}' has invalid column type '${String(typeObj.type)}' for column '${id}'. ` +\n `Valid types: string, number, url, date, year`,\n );\n }\n type = typeObj.type;\n required = typeObj.required ?? false;\n }\n }\n\n columns.push({ id, label, type, required });\n }\n\n return columns;\n}\n\n/**\n * Parse a table-field tag.\n *\n * Column definitions come from attributes:\n * - columnIds (required): array of snake_case column identifiers\n * - columnLabels (optional): array of display labels (backfilled from table header row if omitted)\n * - columnTypes (optional): array of column types (defaults to all 'string')\n *\n * Table content is a raw markdown table inside the tag (NOT a value fence).\n */\nexport function parseTableField(node: Node): { field: TableField; response: FieldResponse } {\n const { id, label, required } = parseBaseFieldAttrs(node, 'table');\n\n // Check for sentinel values first (entire field can be skipped/aborted)\n const sentinelResponse = tryParseSentinelResponse(node, id, required);\n\n // Get table content - raw markdown table inside the tag\n const tableContent = extractTableContent(node);\n\n // Extract header labels from table content for label backfilling\n const tableHeaderLabels = extractTableHeaderLabels(tableContent);\n\n // Parse columns from attributes (columnIds is required)\n const columns = parseColumnsFromAttributes(node, id, tableHeaderLabels);\n const dataStartLine = 2; // header + separator\n\n const field: TableField = {\n kind: 'table',\n id,\n label,\n required,\n ...getCommonFieldAttrs(node),\n columns,\n minRows: getNumberAttr(node, 'minRows'),\n maxRows: getNumberAttr(node, 'maxRows'),\n };\n\n if (sentinelResponse) {\n return { field, response: sentinelResponse };\n }\n\n if (tableContent === null || tableContent.trim() === '') {\n // Empty table\n const value: TableValue = { kind: 'table', rows: [] };\n const response = parseFieldResponse(node, value, id, required);\n return { field, response };\n }\n\n // Parse the markdown table with column schema\n // dataStartLine = 2 to skip header + separator rows\n const parseResult = parseMarkdownTable(tableContent, columns, dataStartLine);\n if (!parseResult.ok) {\n throw new MarkformParseError(`table-field '${id}': ${parseResult.error}`);\n }\n\n const response = parseFieldResponse(node, parseResult.value, id, required);\n return { field, response };\n}\n\n// =============================================================================\n// Unified Field Parser\n// =============================================================================\n\n/**\n * Map legacy tag names to field kinds for error messages.\n */\nconst LEGACY_TAG_TO_KIND: Record<string, FieldKind> = {\n 'string-field': 'string',\n 'number-field': 'number',\n 'string-list': 'string_list',\n 'single-select': 'single_select',\n 'multi-select': 'multi_select',\n checkboxes: 'checkboxes',\n 'url-field': 'url',\n 'url-list': 'url_list',\n 'date-field': 'date',\n 'year-field': 'year',\n 'table-field': 'table',\n};\n\n/**\n * Recursively check if any children of a node are field tags.\n * Throws MarkformParseError if a nested field is found.\n */\nfunction validateNoNestedFields(node: Node, outerFieldId: string): void {\n if (!node.children || !Array.isArray(node.children)) {\n return;\n }\n\n for (const child of node.children) {\n if (isTagNode(child, 'field')) {\n const innerId = getStringAttr(child, 'id') ?? 'unknown';\n throw new MarkformParseError(\n `Field tags cannot be nested. Found '${innerId}' inside '${outerFieldId}'`,\n );\n }\n // Recursively check grandchildren\n validateNoNestedFields(child, outerFieldId);\n }\n}\n\n/**\n * Parse a unified field tag: {% field kind=\"...\" ... %}\n */\nfunction parseUnifiedField(node: Node): { field: Field; response: FieldResponse } {\n const kind = getStringAttr(node, 'kind');\n\n if (!kind) {\n throw new MarkformParseError(\"field tag missing required 'kind' attribute\");\n }\n\n // Validate no nested field tags before processing\n const fieldId = getStringAttr(node, 'id') ?? 'unknown';\n validateNoNestedFields(node, fieldId);\n\n // Validate kind is a known field kind\n if (!FIELD_KINDS.includes(kind as FieldKind)) {\n throw new MarkformParseError(\n `field tag has invalid kind '${kind}'. Valid kinds: ${FIELD_KINDS.join(', ')}`,\n );\n }\n\n // Dispatch to specific parsers based on kind\n switch (kind as FieldKind) {\n case 'string':\n return parseStringField(node);\n case 'number':\n return parseNumberField(node);\n case 'string_list':\n return parseStringListField(node);\n case 'single_select':\n return parseSingleSelectField(node);\n case 'multi_select':\n return parseMultiSelectField(node);\n case 'checkboxes':\n return parseCheckboxesField(node);\n case 'url':\n return parseUrlField(node);\n case 'url_list':\n return parseUrlListField(node);\n case 'date':\n return parseDateField(node);\n case 'year':\n return parseYearField(node);\n case 'table':\n return parseTableField(node);\n }\n}\n\n// =============================================================================\n// Field Dispatcher\n// =============================================================================\n\n/**\n * Parse a field tag and return field schema and response.\n * Accepts both unified field syntax {% field kind=\"...\" %} and legacy tags.\n */\nexport function parseField(node: Node): { field: Field; response: FieldResponse } | null {\n if (!isTagNode(node)) {\n return null;\n }\n\n // Handle unified field tag\n if (node.tag === 'field') {\n return parseUnifiedField(node);\n }\n\n // Reject legacy tags with clear error messages\n if (node.tag) {\n const kind = LEGACY_TAG_TO_KIND[node.tag];\n if (kind !== undefined) {\n throw new MarkformParseError(\n `Legacy field tag '${node.tag}' is no longer supported. Use {% field kind=\"${kind}\" %} instead`,\n );\n }\n }\n\n return null;\n}\n","/**\n * Low-level utilities for extracting heading information from markdown.\n *\n * This module provides functions to find headings and determine which headings\n * enclose a given position. Used by plan documents and ID injection.\n */\n\nimport type { SourceRange } from '../engine/coreTypes.js';\n\n/**\n * Information about a markdown heading.\n */\nexport interface HeadingInfo {\n /** Heading level (1-6 for h1-h6) */\n level: number;\n\n /** Heading text content (without # prefix) */\n title: string;\n\n /** Line number (1-indexed) where heading starts */\n line: number;\n\n /** Full source position */\n position: SourceRange;\n}\n\n// ATX heading pattern: 1-6 # chars, space, then title\nconst ATX_HEADING_PATTERN = /^(#{1,6})\\s+(.*)$/;\n\n/**\n * Find all headings in a markdown document.\n * Returns headings in document order.\n *\n * Only ATX-style headings (# Title) are recognized.\n * Headings inside fenced code blocks are ignored.\n */\nexport function findAllHeadings(markdown: string): HeadingInfo[] {\n const lines = markdown.split('\\n');\n const headings: HeadingInfo[] = [];\n let inCodeBlock = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const lineNumber = i + 1; // 1-indexed\n\n // Track code block state\n if (line.startsWith('```') || line.startsWith('~~~')) {\n inCodeBlock = !inCodeBlock;\n continue;\n }\n\n // Skip if inside code block\n if (inCodeBlock) {\n continue;\n }\n\n // Check for ATX heading\n const match = ATX_HEADING_PATTERN.exec(line);\n if (match) {\n const hashes = match[1] ?? '';\n const title = (match[2] ?? '').trim();\n\n headings.push({\n level: hashes.length,\n title,\n line: lineNumber,\n position: {\n start: { line: lineNumber, col: 1 },\n end: { line: lineNumber, col: line.length + 1 },\n },\n });\n }\n }\n\n return headings;\n}\n\n/**\n * Find all headings that enclose a given line position.\n * Returns headings from innermost (most specific) to outermost (least specific).\n *\n * A heading \"encloses\" a line if:\n * 1. The heading appears before the line\n * 2. No heading of equal or higher level appears between them\n *\n * @param markdown - The markdown source text\n * @param line - The line number (1-indexed)\n * @returns Array of enclosing headings, innermost first\n */\nexport function findEnclosingHeadings(markdown: string, line: number): HeadingInfo[] {\n if (line <= 0) {\n return [];\n }\n\n const allHeadings = findAllHeadings(markdown);\n\n // Filter to headings that appear before this line (not on the line)\n const precedingHeadings = allHeadings.filter((h) => h.line < line);\n\n if (precedingHeadings.length === 0) {\n return [];\n }\n\n // Build the enclosing headings list\n // Walk backwards through preceding headings and collect those that aren't\n // \"shadowed\" by a heading of equal or higher level\n const result: HeadingInfo[] = [];\n let minLevelSeen = Infinity;\n\n for (let i = precedingHeadings.length - 1; i >= 0; i--) {\n const heading = precedingHeadings[i];\n if (!heading) continue;\n\n // If this heading is at a higher level (smaller number) than any we've seen,\n // it encloses the position\n if (heading.level < minLevelSeen) {\n result.push(heading);\n minLevelSeen = heading.level;\n }\n }\n\n return result;\n}\n","/**\n * ID injection utilities for checkboxes and headers.\n *\n * Provides functions to find checkboxes in markdown and inject ID annotations\n * using generator functions. Used by plan documents and programmatic ID generation.\n */\n\nimport type { CheckboxValue, SourceRange } from './coreTypes.js';\nimport { CHECKBOX_MARKERS } from './parseHelpers.js';\nimport { findAllHeadings, findEnclosingHeadings } from '../markdown/markdownHeaders.js';\nimport type { HeadingInfo } from '../markdown/markdownHeaders.js';\nimport { MarkformParseError } from '../errors.js';\n\n// Re-export HeadingInfo for convenience\nexport type { HeadingInfo };\n\n/**\n * Information about a checkbox found in markdown.\n */\nexport interface CheckboxInfo {\n /** Existing ID, if any (from {% #id %} annotation) */\n id?: string;\n\n /** Checkbox label text */\n label: string;\n\n /** Current checkbox state from marker */\n state: CheckboxValue;\n\n /** Line number (1-indexed) where checkbox appears */\n line: number;\n\n /** Source position of the checkbox line */\n position: SourceRange;\n\n /** Enclosing headings, innermost first */\n enclosingHeadings: HeadingInfo[];\n}\n\n// Pattern to match checkbox list items: optional indent, -, [marker], text\n// Captures: 1=indent, 2=marker (including brackets), 3=rest of line\nconst CHECKBOX_PATTERN = /^(\\s*)-\\s+(\\[[^\\]]\\])\\s+(.*)$/;\n\n// Pattern to extract Markdoc ID annotation: {% #id %}\nconst MARKDOC_ID_PATTERN = /\\{%\\s*#(\\w+)\\s*%\\}/;\n\n// Pattern to extract HTML comment ID annotation: <!-- #id -->\nconst HTML_COMMENT_ID_PATTERN = /<!--\\s*#(\\w+)\\s*-->/;\n\n/**\n * Find all checkboxes in a markdown document.\n * Returns checkboxes in document order with enclosing heading info.\n */\nexport function findAllCheckboxes(markdown: string): CheckboxInfo[] {\n const lines = markdown.split('\\n');\n const checkboxes: CheckboxInfo[] = [];\n let inCodeBlock = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n const lineNumber = i + 1; // 1-indexed\n\n // Track code block state\n if (line.trimStart().startsWith('```') || line.trimStart().startsWith('~~~')) {\n inCodeBlock = !inCodeBlock;\n continue;\n }\n\n // Skip if inside code block\n if (inCodeBlock) {\n continue;\n }\n\n // Check for checkbox pattern\n const match = CHECKBOX_PATTERN.exec(line);\n if (!match) {\n continue;\n }\n\n const marker = match[2] ?? '';\n const rest = match[3] ?? '';\n\n // Get checkbox state from marker\n const state = CHECKBOX_MARKERS[marker];\n if (state === undefined) {\n continue; // Invalid marker\n }\n\n // Extract label and ID\n let label = rest;\n let id: string | undefined;\n\n // Check for Markdoc ID annotation\n const markdocMatch = MARKDOC_ID_PATTERN.exec(rest);\n if (markdocMatch) {\n id = markdocMatch[1];\n label = rest.replace(MARKDOC_ID_PATTERN, '').trim();\n } else {\n // Check for HTML comment ID annotation\n const htmlMatch = HTML_COMMENT_ID_PATTERN.exec(rest);\n if (htmlMatch) {\n id = htmlMatch[1];\n label = rest.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n }\n\n // Get enclosing headings for this line\n const enclosingHeadings = findEnclosingHeadings(markdown, lineNumber);\n\n checkboxes.push({\n id,\n label,\n state,\n line: lineNumber,\n position: {\n start: { line: lineNumber, col: 1 },\n end: { line: lineNumber, col: line.length + 1 },\n },\n enclosingHeadings,\n });\n }\n\n return checkboxes;\n}\n\n/**\n * Options for ID injection.\n */\nexport interface InjectCheckboxIdsOptions {\n /**\n * Generator function to create IDs for checkboxes.\n * Receives checkbox info and 0-based index of checkboxes needing IDs.\n */\n generator: (info: CheckboxInfo, index: number) => string;\n\n /**\n * If true (default), only inject IDs for checkboxes missing them.\n * If false, replace all IDs.\n */\n onlyMissing?: boolean;\n}\n\n/**\n * Result of ID injection.\n */\nexport interface InjectIdsResult {\n /** Updated markdown with injected IDs */\n markdown: string;\n\n /** Number of IDs that were injected */\n injectedCount: number;\n\n /** Map of checkbox label to injected ID */\n injectedIds: Map<string, string>;\n}\n\n/**\n * Inject IDs into checkboxes in a markdown document.\n *\n * Uses a generator function to create unique IDs for each checkbox.\n * Throws if duplicate IDs are generated or if generated IDs conflict\n * with existing ones.\n */\nexport function injectCheckboxIds(\n markdown: string,\n options: InjectCheckboxIdsOptions,\n): InjectIdsResult {\n const { generator, onlyMissing = true } = options;\n const checkboxes = findAllCheckboxes(markdown);\n\n // Collect existing IDs (to check for conflicts)\n const existingIds = new Set<string>();\n for (const checkbox of checkboxes) {\n if (checkbox.id && onlyMissing) {\n existingIds.add(checkbox.id);\n }\n }\n\n // Determine which checkboxes need IDs\n const needsId = checkboxes.filter((cb) => (onlyMissing ? !cb.id : true));\n\n // Generate IDs and check for duplicates/conflicts\n const generatedIds = new Map<string, string>(); // label -> id\n const allGeneratedIds = new Set<string>();\n\n for (let i = 0; i < needsId.length; i++) {\n const checkbox = needsId[i]!;\n const newId = generator(checkbox, i);\n\n // Check for duplicate generated IDs\n if (allGeneratedIds.has(newId)) {\n throw new MarkformParseError(\n `Duplicate generated ID '${newId}' for checkbox '${checkbox.label}'`,\n { line: checkbox.line },\n );\n }\n\n // Check for conflict with existing IDs (only when onlyMissing=true)\n if (onlyMissing && existingIds.has(newId)) {\n throw new MarkformParseError(`Generated ID '${newId}' conflicts with existing ID`, {\n line: checkbox.line,\n });\n }\n\n allGeneratedIds.add(newId);\n generatedIds.set(checkbox.label, newId);\n }\n\n // If no changes needed, return original markdown\n if (needsId.length === 0) {\n return {\n markdown,\n injectedCount: 0,\n injectedIds: new Map(),\n };\n }\n\n // Apply changes to markdown (process in reverse order to preserve line numbers)\n const lines = markdown.split('\\n');\n const sortedByLine = [...needsId].sort((a, b) => b.line - a.line);\n\n for (const checkbox of sortedByLine) {\n const lineIndex = checkbox.line - 1;\n const line = lines[lineIndex]!;\n const newId = generatedIds.get(checkbox.label)!;\n\n // Remove existing ID annotation if replacing\n let updatedLine = line;\n if (!onlyMissing || checkbox.id) {\n // Remove existing Markdoc ID\n updatedLine = updatedLine.replace(MARKDOC_ID_PATTERN, '').trim();\n // Remove existing HTML comment ID\n updatedLine = updatedLine.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n\n // Append new ID annotation\n lines[lineIndex] = `${updatedLine} {% #${newId} %}`;\n }\n\n return {\n markdown: lines.join('\\n'),\n injectedCount: needsId.length,\n injectedIds: generatedIds,\n };\n}\n\n/**\n * Options for header ID injection.\n */\nexport interface InjectHeaderIdsOptions {\n /**\n * Generator function to create IDs for headings.\n * Receives heading info and 0-based index of headings needing IDs.\n */\n generator: (info: HeadingInfo, index: number) => string;\n\n /**\n * If true (default), only inject IDs for headings missing them.\n * If false, replace all IDs.\n */\n onlyMissing?: boolean;\n\n /**\n * Heading levels to process. Defaults to all levels [1, 2, 3, 4, 5, 6].\n */\n levels?: number[];\n}\n\n/**\n * Extended HeadingInfo that includes existing ID if present.\n */\ninterface HeadingWithId extends HeadingInfo {\n id?: string;\n}\n\n/**\n * Find all headings with their existing IDs.\n * Strips ID annotations from title for clean generator input.\n */\nfunction findAllHeadingsWithIds(markdown: string): HeadingWithId[] {\n const headings = findAllHeadings(markdown);\n const lines = markdown.split('\\n');\n\n return headings.map((heading) => {\n const line = lines[heading.line - 1] ?? '';\n\n // Check for existing ID annotation\n let id: string | undefined;\n let cleanTitle = heading.title;\n\n const markdocMatch = MARKDOC_ID_PATTERN.exec(line);\n if (markdocMatch) {\n id = markdocMatch[1];\n // Strip ID annotation from title\n cleanTitle = heading.title.replace(MARKDOC_ID_PATTERN, '').trim();\n } else {\n const htmlMatch = HTML_COMMENT_ID_PATTERN.exec(line);\n if (htmlMatch) {\n id = htmlMatch[1];\n // Strip ID annotation from title\n cleanTitle = heading.title.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n }\n\n return { ...heading, title: cleanTitle, id };\n });\n}\n\n/**\n * Inject IDs into headings in a markdown document.\n *\n * Uses a generator function to create unique IDs for each heading.\n * Throws if duplicate IDs are generated or if generated IDs conflict\n * with existing ones.\n */\nexport function injectHeaderIds(\n markdown: string,\n options: InjectHeaderIdsOptions,\n): InjectIdsResult {\n const { generator, onlyMissing = true, levels = [1, 2, 3, 4, 5, 6] } = options;\n const allHeadings = findAllHeadingsWithIds(markdown);\n\n // Filter by levels\n const levelSet = new Set(levels);\n const headings = allHeadings.filter((h) => levelSet.has(h.level));\n\n // Collect existing IDs (to check for conflicts)\n const existingIds = new Set<string>();\n for (const heading of headings) {\n if (heading.id && onlyMissing) {\n existingIds.add(heading.id);\n }\n }\n\n // Determine which headings need IDs\n const needsId = headings.filter((h) => (onlyMissing ? !h.id : true));\n\n // Generate IDs and check for duplicates/conflicts\n const generatedIds = new Map<string, string>(); // title -> id\n const allGeneratedIds = new Set<string>();\n\n for (let i = 0; i < needsId.length; i++) {\n const heading = needsId[i]!;\n const newId = generator(heading, i);\n\n // Check for duplicate generated IDs\n if (allGeneratedIds.has(newId)) {\n throw new MarkformParseError(\n `Duplicate generated ID '${newId}' for heading '${heading.title}'`,\n { line: heading.line },\n );\n }\n\n // Check for conflict with existing IDs (only when onlyMissing=true)\n if (onlyMissing && existingIds.has(newId)) {\n throw new MarkformParseError(`Generated ID '${newId}' conflicts with existing ID`, {\n line: heading.line,\n });\n }\n\n allGeneratedIds.add(newId);\n generatedIds.set(heading.title, newId);\n }\n\n // If no changes needed, return original markdown\n if (needsId.length === 0) {\n return {\n markdown,\n injectedCount: 0,\n injectedIds: new Map(),\n };\n }\n\n // Apply changes to markdown (process in reverse order to preserve line numbers)\n const lines = markdown.split('\\n');\n const sortedByLine = [...needsId].sort((a, b) => b.line - a.line);\n\n for (const heading of sortedByLine) {\n const lineIndex = heading.line - 1;\n const line = lines[lineIndex]!;\n const newId = generatedIds.get(heading.title)!;\n\n // Remove existing ID annotation if replacing\n let updatedLine = line;\n if (!onlyMissing || heading.id) {\n // Remove existing Markdoc ID\n updatedLine = updatedLine.replace(MARKDOC_ID_PATTERN, '').trim();\n // Remove existing HTML comment ID\n updatedLine = updatedLine.replace(HTML_COMMENT_ID_PATTERN, '').trim();\n }\n\n // Append new ID annotation\n lines[lineIndex] = `${updatedLine} {% #${newId} %}`;\n }\n\n return {\n markdown: lines.join('\\n'),\n injectedCount: needsId.length,\n injectedIds: generatedIds,\n };\n}\n","/**\n * Markdoc parser for .form.md files.\n *\n * Parses Markdoc documents and extracts form schema, values, and documentation blocks.\n */\n\nimport Markdoc from '@markdoc/markdoc';\nimport type { Node } from '@markdoc/markdoc';\nimport YAML from 'yaml';\n\nimport type {\n CheckboxesField,\n CheckboxesValue,\n DocumentationBlock,\n DocumentationTag,\n FieldGroup,\n FieldResponse,\n FormMetadata,\n FormSchema,\n Id,\n IdIndexEntry,\n Note,\n ParsedForm,\n SyntaxStyle,\n TagRegion,\n TagType,\n} from './coreTypes.js';\nimport { MarkformSectionInputSchema } from './coreTypes.js';\nimport type { ZodError } from 'zod';\nimport {\n AGENT_ROLE,\n DEFAULT_PRIORITY,\n DEFAULT_ROLES,\n DEFAULT_ROLE_INSTRUCTIONS,\n transformHarnessConfigToTs,\n} from '../settings.js';\nimport { parseField } from './parseFields.js';\nimport {\n getBooleanAttr,\n getNumberAttr,\n getStringAttr,\n getValidateAttr,\n isTagNode,\n} from './parseHelpers.js';\nimport { MarkformParseError } from '../errors.js';\nimport { detectSyntaxStyle, preprocessCommentSyntax } from './preprocess.js';\nimport { findAllCheckboxes } from './injectIds.js';\n\n// Re-export ParseError for backward compatibility\nexport { ParseError } from '../errors.js';\n\n/**\n * Valid tag names inside a form.\n * Any other tag will produce a ParseError.\n */\nconst VALID_FORM_TAGS = new Set([\n 'group',\n 'field',\n 'note',\n 'description',\n 'instructions',\n 'documentation',\n]);\n\n// =============================================================================\n// Frontmatter Parsing\n// =============================================================================\n\ninterface FrontmatterResult {\n frontmatter: Record<string, unknown>;\n metadata?: FormMetadata;\n /** Description from markform.description in frontmatter */\n description?: string;\n}\n\n/**\n * Format Zod validation errors for user-friendly display.\n */\nfunction formatZodError(error: ZodError): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.map(String).join('.');\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join('; ');\n}\n\n/**\n * Extract YAML frontmatter from Markdoc AST.\n * Uses Markdoc's native frontmatter extraction and parses the YAML.\n * Validates the markform section using Zod schema.\n */\nfunction extractFrontmatter(ast: Node): FrontmatterResult {\n const rawFrontmatter = ast.attributes.frontmatter as string | undefined;\n if (!rawFrontmatter) {\n return { frontmatter: {} };\n }\n\n try {\n const parsed = YAML.parse(rawFrontmatter) as Record<string, unknown> | null;\n const frontmatter = parsed ?? {};\n\n // Extract metadata from markform section\n const rawMarkformSection = frontmatter.markform;\n if (!rawMarkformSection) {\n return { frontmatter };\n }\n\n // Validate markform section with Zod schema\n const validationResult = MarkformSectionInputSchema.safeParse(rawMarkformSection);\n if (!validationResult.success) {\n throw new MarkformParseError(\n `Invalid markform frontmatter: ${formatZodError(validationResult.error)}`,\n );\n }\n const markformSection = validationResult.data;\n\n // Transform harness config from snake_case to camelCase\n const harnessConfig =\n markformSection.harness && Object.keys(markformSection.harness).length > 0\n ? transformHarnessConfigToTs(markformSection.harness)\n : undefined;\n\n // Build metadata\n // Note: roles and role_instructions can be either inside markform: or at top-level\n // Prefer markform section, fall back to top-level for backwards compatibility\n const metadata: FormMetadata = {\n markformVersion: markformSection.spec ?? 'MF/0.1',\n ...(markformSection.title && { title: markformSection.title }),\n ...(markformSection.description && { description: markformSection.description }),\n roles: markformSection.roles ??\n (frontmatter.roles as string[] | undefined) ?? [...DEFAULT_ROLES],\n roleInstructions:\n markformSection.role_instructions ??\n (frontmatter.role_instructions as Record<string, string> | undefined) ??\n DEFAULT_ROLE_INSTRUCTIONS,\n ...(harnessConfig && { harnessConfig }),\n ...(markformSection.run_mode && { runMode: markformSection.run_mode }),\n };\n\n return { frontmatter, metadata, description: markformSection.description };\n } catch (error) {\n // Re-throw ParseError as-is, wrap other errors\n if (error instanceof MarkformParseError) {\n throw error;\n }\n throw new MarkformParseError('Failed to parse frontmatter YAML');\n }\n}\n\n/**\n * Extract the raw source content minus frontmatter.\n * This is the content that will be used for splice-based serialization.\n */\nfunction extractRawSource(preprocessed: string): string {\n // YAML frontmatter is delimited by --- at start and end\n const frontmatterRegex = /^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/;\n const frontmatterMatch = frontmatterRegex.exec(preprocessed);\n if (frontmatterMatch) {\n return preprocessed.slice(frontmatterMatch[0].length);\n }\n return preprocessed;\n}\n\n/**\n * Build a line-to-offset mapping for converting Markdoc line numbers to byte offsets.\n * Returns an array where lineOffsets[lineNumber] = byte offset of line start.\n * Line numbers are 0-indexed (Markdoc uses 0-indexed lines).\n */\nfunction buildLineOffsets(source: string): number[] {\n const offsets: number[] = [0]; // Line 0 starts at offset 0\n for (let i = 0; i < source.length; i++) {\n if (source[i] === '\\n') {\n offsets.push(i + 1); // Next line starts after the newline\n }\n }\n return offsets;\n}\n\n/**\n * Extract tag region from a Markdoc AST node.\n * Uses the node's location property (line numbers) and converts to byte offsets.\n */\nfunction extractTagRegion(\n node: Node,\n tagType: TagType,\n tagId: Id,\n lineOffsets: number[],\n frontmatterLineCount: number,\n sourceLength: number,\n hasValue?: boolean,\n): TagRegion | null {\n // Markdoc nodes have location with start/end line numbers (0-indexed)\n const location = node.location;\n if (!location?.start || !location?.end) {\n return null;\n }\n\n // Adjust line numbers for frontmatter removal\n // rawSource starts after frontmatter, so we need to adjust the line numbers\n const startLine = location.start.line - frontmatterLineCount;\n const endLine = location.end.line - frontmatterLineCount;\n\n // Skip if the tag is in the frontmatter area (shouldn't happen, but be safe)\n if (startLine < 0 || endLine < 0) {\n return null;\n }\n\n // Convert line numbers to byte offsets\n // Markdoc's end line is the line containing the closing tag\n // We need to find the end of that line\n const startOffset = lineOffsets[startLine] ?? 0;\n let endOffset: number;\n\n // For end offset, we want the end of the end line (start of next line or end of source)\n if (endLine + 1 < lineOffsets.length) {\n endOffset = lineOffsets[endLine + 1] ?? sourceLength;\n } else {\n endOffset = sourceLength;\n }\n\n // Sanity check: make sure offsets are valid\n if (startOffset >= endOffset || startOffset < 0 || endOffset > sourceLength) {\n return null;\n }\n\n return {\n tagId,\n tagType,\n startOffset,\n endOffset,\n ...(hasValue !== undefined && { includesValue: hasValue }),\n };\n}\n\n/**\n * Collect all tag regions from the AST for content preservation.\n * Traverses the AST and extracts positions of all Markform tags.\n */\nfunction collectTagRegions(\n ast: Node,\n rawSource: string,\n frontmatterLineCount: number,\n responsesByFieldId: Record<Id, FieldResponse>,\n): TagRegion[] {\n const regions: TagRegion[] = [];\n const lineOffsets = buildLineOffsets(rawSource);\n const sourceLength = rawSource.length;\n\n function traverse(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n // Check for form tag\n if (isTagNode(node, 'form')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n const region = extractTagRegion(\n node,\n 'form',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for group tag\n if (isTagNode(node, 'group')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n const region = extractTagRegion(\n node,\n 'group',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for field tag\n if (isTagNode(node, 'field')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n // Check if field has a value by looking at responsesByFieldId\n const hasValue = responsesByFieldId[id]?.value !== undefined;\n const region = extractTagRegion(\n node,\n 'field',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n hasValue,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for note tag\n if (isTagNode(node, 'note')) {\n const id = getStringAttr(node, 'id');\n if (id) {\n const region = extractTagRegion(\n node,\n 'note',\n id,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n }\n\n // Check for documentation tags (instructions, description, etc.)\n const DOC_TAGS = ['instructions', 'description', 'documentation'];\n if (node.type === 'tag' && node.tag && DOC_TAGS.includes(node.tag)) {\n const ref = getStringAttr(node, 'ref');\n // Use ref as the ID for doc blocks, or generate one\n const docId = ref ?? `doc_${regions.length}`;\n const region = extractTagRegion(\n node,\n 'documentation',\n docId,\n lineOffsets,\n frontmatterLineCount,\n sourceLength,\n );\n if (region) regions.push(region);\n }\n\n // Recurse into children\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n traverse(child);\n }\n }\n }\n\n traverse(ast);\n\n // Sort by startOffset to ensure document order\n regions.sort((a, b) => a.startOffset - b.startOffset);\n\n return regions;\n}\n\n// =============================================================================\n// Group and Form Parsing\n// =============================================================================\n\n/**\n * Parse a group tag.\n */\nfunction parseFieldGroup(\n node: Node,\n responsesByFieldId: Record<Id, FieldResponse>,\n orderIndex: Id[],\n idIndex: Map<Id, IdIndexEntry>,\n parentId?: Id,\n): FieldGroup {\n const id = getStringAttr(node, 'id');\n const title = getStringAttr(node, 'title');\n\n if (!id) {\n throw new MarkformParseError(\"group missing required 'id' attribute\");\n }\n\n if (idIndex.has(id)) {\n throw new MarkformParseError(`Duplicate ID '${id}'`);\n }\n\n // Validate that state attribute is not on group\n const stateAttr = getStringAttr(node, 'state');\n if (stateAttr !== undefined) {\n throw new MarkformParseError(\n `Field-group '${id}' has state attribute. state attribute is not allowed on groups.`,\n );\n }\n\n idIndex.set(id, { nodeType: 'group', parentId });\n\n const children: FieldGroup['children'] = [];\n\n // Traverse children to find fields\n function processChildren(child: Node): void {\n if (!child || typeof child !== 'object') {\n return;\n }\n\n const result = parseField(child);\n if (result) {\n if (idIndex.has(result.field.id)) {\n throw new MarkformParseError(`Duplicate ID '${result.field.id}'`);\n }\n\n idIndex.set(result.field.id, { nodeType: 'field', parentId: id });\n children.push(result.field);\n responsesByFieldId[result.field.id] = result.response;\n orderIndex.push(result.field.id);\n\n // Add options to idIndex for select/checkbox fields\n if ('options' in result.field) {\n for (const opt of result.field.options) {\n const qualifiedRef = `${result.field.id}.${opt.id}`;\n if (idIndex.has(qualifiedRef)) {\n throw new MarkformParseError(`Duplicate option ref '${qualifiedRef}'`);\n }\n idIndex.set(qualifiedRef, {\n nodeType: 'option',\n parentId: id,\n fieldId: result.field.id,\n });\n }\n }\n }\n\n if (child.children && Array.isArray(child.children)) {\n for (const c of child.children) {\n processChildren(c);\n }\n }\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n processChildren(child);\n }\n }\n\n const parallel = getStringAttr(node, 'parallel');\n const order = getNumberAttr(node, 'order');\n\n // Validate: fields inside a group must not have `parallel`\n // Validate: fields inside a group must not explicitly specify a different `order`\n const groupEffectiveOrder = order ?? 0;\n for (const child of children) {\n if (child.parallel) {\n throw new MarkformParseError(\n `Field '${child.id}' has parallel='${child.parallel}' but is inside ` +\n `group '${id}'. The parallel attribute is only allowed on ` +\n `top-level fields and groups.`,\n );\n }\n // Only error if the child *explicitly* sets order to a different value.\n // Unset order on a child is fine — it inherits the group's order.\n if (child.order !== undefined) {\n const childEffectiveOrder = child.order;\n if (childEffectiveOrder !== groupEffectiveOrder) {\n throw new MarkformParseError(\n `Field '${child.id}' has order=${child.order} but is inside ` +\n `group '${id}' with order=${groupEffectiveOrder}. ` +\n `A field inside a group must not specify a different order.`,\n );\n }\n }\n }\n\n return {\n id,\n title,\n validate: getValidateAttr(node),\n children,\n report: getBooleanAttr(node, 'report'),\n parallel,\n order,\n };\n}\n\n/**\n * Parse a form tag.\n * Handles both explicit groups and fields placed directly under the form.\n * Also handles implicit checkboxes when form has no explicit fields.\n */\nfunction parseFormTag(\n node: Node,\n responsesByFieldId: Record<Id, FieldResponse>,\n orderIndex: Id[],\n idIndex: Map<Id, IdIndexEntry>,\n markdown: string,\n): FormSchema {\n const id = getStringAttr(node, 'id');\n const title = getStringAttr(node, 'title');\n\n if (!id) {\n throw new MarkformParseError(\"form missing required 'id' attribute\");\n }\n\n if (idIndex.has(id)) {\n throw new MarkformParseError(`Duplicate ID '${id}'`);\n }\n\n idIndex.set(id, { nodeType: 'form' });\n\n const groups: FieldGroup[] = [];\n const ungroupedFields: FieldGroup['children'] = [];\n\n // Process children to find groups and ungrouped fields\n function processContent(child: Node): void {\n if (!child || typeof child !== 'object') {\n return;\n }\n\n // Check for unknown tags inside form\n if (isTagNode(child) && !VALID_FORM_TAGS.has((child as { tag: string }).tag)) {\n throw new MarkformParseError(`Unknown tag '${(child as { tag: string }).tag}' inside form`);\n }\n\n if (isTagNode(child, 'group')) {\n const group = parseFieldGroup(child, responsesByFieldId, orderIndex, idIndex, id);\n groups.push(group);\n return; // parseFieldGroup already processed the children\n }\n\n // Check for field tags directly under the form (not in a group)\n const result = parseField(child);\n if (result) {\n if (idIndex.has(result.field.id)) {\n throw new MarkformParseError(`Duplicate ID '${result.field.id}'`);\n }\n\n idIndex.set(result.field.id, { nodeType: 'field', parentId: id });\n ungroupedFields.push(result.field);\n responsesByFieldId[result.field.id] = result.response;\n orderIndex.push(result.field.id);\n\n // Add options to idIndex for select/checkbox fields\n if ('options' in result.field) {\n for (const opt of result.field.options) {\n const qualifiedRef = `${result.field.id}.${opt.id}`;\n if (idIndex.has(qualifiedRef)) {\n throw new MarkformParseError(`Duplicate option ref '${qualifiedRef}'`);\n }\n idIndex.set(qualifiedRef, {\n nodeType: 'option',\n parentId: id,\n fieldId: result.field.id,\n });\n }\n }\n return; // Don't recurse into field children\n }\n\n // Recurse into children for non-group, non-field nodes\n if (child.children && Array.isArray(child.children)) {\n for (const c of child.children) {\n processContent(c);\n }\n }\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n processContent(child);\n }\n }\n\n // If there are ungrouped fields, create an implicit group to hold them\n // The 'default' ID is a special name for implicit groups, but can also be used explicitly\n if (ungroupedFields.length > 0) {\n const implicitGroupId = 'default';\n // Check if 'default' was already used explicitly - if so, merge fields into it\n const existingDefault = groups.find((g) => g.id === implicitGroupId);\n if (existingDefault) {\n // Merge ungrouped fields into the existing explicit 'default' group\n existingDefault.children = [...(existingDefault.children ?? []), ...ungroupedFields];\n } else {\n idIndex.set(implicitGroupId, { nodeType: 'group', parentId: id });\n groups.push({\n id: implicitGroupId,\n children: ungroupedFields,\n implicit: true,\n });\n }\n }\n\n // Count all explicit fields\n const hasExplicitFields =\n ungroupedFields.length > 0 || groups.some((g) => g.children && g.children.length > 0);\n\n // Check if there are explicit fields that use checkbox syntax\n // (checkboxes, single_select, multi_select all use checkbox-like list items)\n const hasExplicitCheckboxStyleFields = groups.some((g) =>\n g.children?.some(\n (f) => f.kind === 'checkboxes' || f.kind === 'single_select' || f.kind === 'multi_select',\n ),\n );\n\n // Find all checkboxes in the markdown\n const allCheckboxes = findAllCheckboxes(markdown);\n\n if (allCheckboxes.length > 0) {\n if (hasExplicitFields) {\n // If there are explicit fields that use checkbox syntax, checkboxes are inside them\n // But if there are only non-checkbox-style fields, the checkboxes are orphans\n if (!hasExplicitCheckboxStyleFields) {\n throw new MarkformParseError(\n 'Checkboxes found outside of field tags. Either wrap all checkboxes in ' +\n 'fields or remove all explicit fields for implicit checkboxes mode.',\n );\n }\n // If there are explicit checkboxes fields, the checkboxes are inside them (OK)\n } else {\n // No explicit fields - create implicit checkboxes field\n const seenIds = new Set<string>();\n const options: { id: string; label: string }[] = [];\n const values: CheckboxesValue['values'] = {};\n\n for (const checkbox of allCheckboxes) {\n if (!checkbox.id) {\n throw new MarkformParseError(\n `Option in implicit field 'checkboxes' missing ID annotation. Use {% #option_id %}`,\n { line: checkbox.line },\n );\n }\n\n if (seenIds.has(checkbox.id)) {\n throw new MarkformParseError(\n `Duplicate option ID '${checkbox.id}' in field 'checkboxes'`,\n { line: checkbox.line },\n );\n }\n\n seenIds.add(checkbox.id);\n options.push({\n id: checkbox.id,\n label: checkbox.label,\n });\n values[checkbox.id] = checkbox.state;\n }\n\n // Create implicit checkboxes field\n // The 'checkboxes' ID is a special name for implicit checkboxes, but can also be used explicitly\n const implicitField: CheckboxesField = {\n kind: 'checkboxes',\n id: 'checkboxes',\n label: 'Checkboxes',\n checkboxMode: 'multi',\n implicit: true,\n options,\n required: false,\n priority: DEFAULT_PRIORITY,\n role: AGENT_ROLE,\n approvalMode: 'none',\n };\n\n // Add to idIndex\n idIndex.set('checkboxes', { nodeType: 'field', parentId: id });\n orderIndex.push('checkboxes');\n\n // Add options to idIndex\n for (const opt of options) {\n const qualifiedRef = `checkboxes.${opt.id}`;\n idIndex.set(qualifiedRef, {\n nodeType: 'option',\n parentId: id,\n fieldId: 'checkboxes',\n });\n }\n\n // Create response for the implicit field\n const checkboxesValue: CheckboxesValue = {\n kind: 'checkboxes',\n values,\n };\n responsesByFieldId.checkboxes = {\n state: 'answered',\n value: checkboxesValue,\n };\n\n // Create or get default group for implicit field\n let defaultGroup = groups.find((g) => g.id === 'default');\n if (!defaultGroup) {\n defaultGroup = {\n id: 'default',\n children: [],\n implicit: true,\n };\n idIndex.set('default', { nodeType: 'group', parentId: id });\n groups.push(defaultGroup);\n }\n defaultGroup.children = defaultGroup.children || [];\n defaultGroup.children.push(implicitField);\n }\n }\n\n // Validate parallel batch consistency: same order and same role within each batch.\n // Collect all top-level items that have parallel set.\n // For explicit groups, the group itself is the item.\n // For implicit groups, each child field is a top-level item.\n validateParallelBatches(groups);\n\n return { id, title, groups };\n}\n\n/**\n * Validate that parallel batches have consistent order and role values.\n */\nfunction validateParallelBatches(groups: FieldGroup[]): void {\n // Collect batch membership: batchId → array of { order, role, itemId }\n const batches = new Map<string, { order: number; role: string; itemId: string }[]>();\n\n for (const group of groups) {\n if (group.implicit) {\n // Implicit group: each child field is a top-level item\n for (const field of group.children) {\n if (field.parallel) {\n const list = batches.get(field.parallel) ?? [];\n list.push({\n order: field.order ?? 0,\n role: field.role,\n itemId: field.id,\n });\n batches.set(field.parallel, list);\n }\n }\n } else {\n // Explicit group: the group is the item\n if (group.parallel) {\n // For a group's role, use the role of the first child (they should all match\n // since fields inside a group share the group's execution context).\n // If the group has no children, use AGENT_ROLE as default.\n const groupRole = group.children[0]?.role ?? AGENT_ROLE;\n const list = batches.get(group.parallel) ?? [];\n list.push({\n order: group.order ?? 0,\n role: groupRole,\n itemId: group.id,\n });\n batches.set(group.parallel, list);\n }\n }\n }\n\n // Validate each batch\n for (const [batchId, items] of batches) {\n if (items.length < 2) continue;\n\n const firstOrder = items[0]!.order;\n const firstRole = items[0]!.role;\n\n const differentOrders = items.filter((i) => i.order !== firstOrder);\n if (differentOrders.length > 0) {\n const orderValues = [...new Set(items.map((i) => i.order))].join(', ');\n throw new MarkformParseError(\n `Parallel batch '${batchId}' has items with different order values (${orderValues}). ` +\n `All items in a parallel batch must have the same order.`,\n );\n }\n\n const differentRoles = items.filter((i) => i.role !== firstRole);\n if (differentRoles.length > 0) {\n const roles = [...new Set(items.map((i) => i.role))].join(', ');\n throw new MarkformParseError(\n `Parallel batch '${batchId}' has items with different roles (${roles}). ` +\n `All items in a parallel batch must have the same role.`,\n );\n }\n }\n}\n\n// =============================================================================\n// Note Parsing\n// =============================================================================\n\n/**\n * Extract all notes from AST.\n * Looks for {% note %} tags with id, ref, role, and optional state.\n */\nfunction extractNotes(ast: Node, idIndex: Map<Id, IdIndexEntry>): Note[] {\n const notes: Note[] = [];\n const seenIds = new Set<string>();\n\n function traverse(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n // Check for note tags\n if (isTagNode(node, 'note')) {\n const id = getStringAttr(node, 'id');\n const ref = getStringAttr(node, 'ref');\n const role = getStringAttr(node, 'role');\n const stateAttr = getStringAttr(node, 'state');\n\n // Validate required attributes\n if (!id) {\n throw new MarkformParseError(\"note missing required 'id' attribute\");\n }\n if (!ref) {\n throw new MarkformParseError(`note '${id}' missing required 'ref' attribute`);\n }\n if (!role) {\n throw new MarkformParseError(`note '${id}' missing required 'role' attribute`);\n }\n\n // Reject state attribute on notes (markform-254: notes are general-purpose only)\n if (stateAttr !== undefined) {\n throw new MarkformParseError(\n `note '${id}' has 'state' attribute. Notes no longer support state linking; use FieldResponse.reason for skip/abort reasons.`,\n );\n }\n\n // Validate ref exists in idIndex\n if (!idIndex.has(ref)) {\n throw new MarkformParseError(`note '${id}' references unknown ID '${ref}'`);\n }\n\n // Validate duplicate note IDs\n if (seenIds.has(id)) {\n throw new MarkformParseError(`Duplicate note ID '${id}'`);\n }\n seenIds.add(id);\n\n // Extract text content\n let text = '';\n function extractText(n: Node): void {\n if (n.type === 'text' && typeof n.attributes?.content === 'string') {\n text += n.attributes.content;\n }\n if (n.children && Array.isArray(n.children)) {\n for (const c of n.children) {\n extractText(c);\n }\n }\n }\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n extractText(child);\n }\n }\n\n notes.push({\n id,\n ref,\n role,\n text: text.trim(),\n });\n }\n\n // Recurse into children\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n traverse(child);\n }\n }\n }\n\n traverse(ast);\n return notes;\n}\n\n// =============================================================================\n// Documentation Block Parsing\n// =============================================================================\n\n/** Valid documentation tag names */\nconst DOC_TAG_NAMES = ['description', 'instructions', 'documentation'] as const;\n\n/**\n * Extract all documentation blocks from AST.\n * Looks for {% description %}, {% instructions %}, and {% documentation %} tags.\n */\nfunction extractDocBlocks(ast: Node, idIndex: Map<Id, IdIndexEntry>): DocumentationBlock[] {\n const docs: DocumentationBlock[] = [];\n const seenRefs = new Set<string>();\n\n function traverse(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n // Check for description, instructions, or documentation tags\n const nodeTag = node.type === 'tag' && node.tag ? node.tag : null;\n if (nodeTag && (DOC_TAG_NAMES as readonly string[]).includes(nodeTag)) {\n const tag = nodeTag as DocumentationTag;\n const ref = getStringAttr(node, 'ref');\n\n if (!ref) {\n throw new MarkformParseError(`${tag} block missing required 'ref' attribute`);\n }\n\n // Validate ref exists\n if (!idIndex.has(ref)) {\n throw new MarkformParseError(`${tag} block references unknown ID '${ref}'`);\n }\n\n const uniqueKey = `${ref}:${tag}`;\n\n if (seenRefs.has(uniqueKey)) {\n throw new MarkformParseError(`Duplicate ${tag} block for ref='${ref}'`);\n }\n seenRefs.add(uniqueKey);\n\n // Extract body content - collect all text from children\n let bodyMarkdown = '';\n function extractText(n: Node): void {\n if (n.type === 'text' && typeof n.attributes?.content === 'string') {\n bodyMarkdown += n.attributes.content;\n } else if (n.type === 'softbreak' || n.type === 'hardbreak') {\n // Preserve line breaks from markdown - softbreak is a single newline,\n // hardbreak is an explicit break (e.g., two spaces at end of line)\n bodyMarkdown += '\\n';\n }\n if (n.children && Array.isArray(n.children)) {\n for (const c of n.children) {\n extractText(c);\n }\n }\n }\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n extractText(child);\n }\n }\n\n docs.push({\n tag,\n ref,\n bodyMarkdown: bodyMarkdown.trim(),\n report: getBooleanAttr(node, 'report'),\n });\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n traverse(child);\n }\n }\n }\n\n traverse(ast);\n return docs;\n}\n\n// =============================================================================\n// Main Parser\n// =============================================================================\n\n/**\n * Parse a Markform .form.md document.\n *\n * Supports both Markdoc syntax (`{% tag %}`) and HTML comment syntax (`<!-- f:tag -->`).\n * The original syntax style is detected and preserved for round-trip serialization.\n *\n * @param markdown - The full markdown content including frontmatter\n * @returns The parsed form representation\n * @throws ParseError if the document is invalid\n */\nexport function parseForm(markdown: string): ParsedForm {\n // Step 0: Detect syntax style and preprocess HTML comment syntax to Markdoc\n const syntaxStyle: SyntaxStyle = detectSyntaxStyle(markdown);\n const preprocessed = preprocessCommentSyntax(markdown);\n\n // Step 0.5: Extract raw source (content minus frontmatter) for content preservation\n const rawSource = extractRawSource(preprocessed);\n // Calculate the number of lines in frontmatter for line number adjustment\n const frontmatter = preprocessed.slice(0, preprocessed.length - rawSource.length);\n const frontmatterLineCount = (frontmatter.match(/\\n/g) ?? []).length;\n\n // Step 1: Parse Markdoc AST (raw AST, not transformed)\n // Markdoc natively handles frontmatter extraction and stores it in ast.attributes.frontmatter\n const ast = Markdoc.parse(preprocessed);\n\n // Step 2: Extract frontmatter and metadata from AST\n const { metadata, description } = extractFrontmatter(ast);\n\n // Step 3: Find the form tag in the raw AST\n let formSchema: FormSchema | null = null;\n const responsesByFieldId: Record<Id, FieldResponse> = {};\n const orderIndex: Id[] = [];\n const idIndex = new Map<Id, IdIndexEntry>();\n\n function findFormTag(node: Node): void {\n if (!node || typeof node !== 'object') {\n return;\n }\n\n if (isTagNode(node, 'form')) {\n if (formSchema) {\n throw new MarkformParseError('Multiple form tags found - only one allowed');\n }\n formSchema = parseFormTag(node, responsesByFieldId, orderIndex, idIndex, preprocessed);\n return;\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n findFormTag(child);\n }\n }\n }\n\n findFormTag(ast);\n\n if (!formSchema) {\n throw new MarkformParseError('No form tag found in document');\n }\n\n // Build final schema with description from frontmatter\n // Type assertion needed because TypeScript doesn't track closure assignments well\n const parsedSchema = formSchema as FormSchema;\n const schema: FormSchema = {\n ...parsedSchema,\n ...(description && { description }),\n };\n\n // Step 4: Extract notes (needs idIndex to validate refs)\n const notes = extractNotes(ast, idIndex);\n\n // Step 5: Extract doc blocks (needs idIndex to validate refs)\n const docs = extractDocBlocks(ast, idIndex);\n\n // Step 6: Collect tag regions for content preservation\n const tagRegions = collectTagRegions(ast, rawSource, frontmatterLineCount, responsesByFieldId);\n\n return {\n schema,\n responsesByFieldId,\n notes,\n docs,\n orderIndex,\n idIndex,\n ...(metadata && { metadata }),\n syntaxStyle,\n rawSource,\n tagRegions,\n };\n}\n","/**\n * JSON Schema export for Markform forms.\n *\n * Converts parsed forms to JSON Schema format (draft 2020-12).\n * Includes x-markform extension properties for Markform-specific metadata.\n */\n\nimport type {\n CheckboxesField,\n CheckboxMode,\n ApprovalMode,\n DateField,\n DocumentationBlock,\n Field,\n FieldPriorityLevel,\n MultiSelectField,\n NumberField,\n ParsedForm,\n SingleSelectField,\n StringField,\n StringListField,\n TableColumn,\n TableField,\n UrlField,\n UrlListField,\n YearField,\n} from './coreTypes.js';\n\n// =============================================================================\n// JSON Schema Types (subset we use)\n// =============================================================================\n\n/** JSON Schema type values */\ntype JsonSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';\n\n/** JSON Schema format values */\ntype JsonSchemaFormat = 'date' | 'uri' | 'email' | 'uri-reference';\n\n/** JSON Schema property definition */\ninterface JsonSchemaProperty {\n type?: JsonSchemaType | JsonSchemaType[];\n title?: string;\n description?: string;\n enum?: (string | number | boolean | null)[];\n const?: string | number | boolean | null;\n format?: JsonSchemaFormat;\n pattern?: string;\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n // JSON Schema 2019-09/2020-12 format validation keywords\n formatMinimum?: string;\n formatMaximum?: string;\n items?: JsonSchemaProperty;\n properties?: Record<string, JsonSchemaProperty>;\n required?: string[];\n minItems?: number;\n maxItems?: number;\n uniqueItems?: boolean;\n additionalProperties?: boolean | JsonSchemaProperty;\n // Composition keywords\n anyOf?: JsonSchemaProperty[];\n oneOf?: JsonSchemaProperty[];\n 'x-markform'?: MarkformFieldExtension;\n}\n\n/** Root JSON Schema object (does not extend JsonSchemaProperty to allow different x-markform type) */\ninterface JsonSchemaRoot {\n $schema: string;\n $id?: string;\n type: 'object';\n title?: string;\n description?: string;\n properties?: Record<string, JsonSchemaProperty>;\n required?: string[];\n 'x-markform'?: MarkformSchemaExtension;\n}\n\n// =============================================================================\n// Markform Extension Types\n// =============================================================================\n\n/** Form-level Markform extension data */\nexport interface MarkformSchemaExtension {\n spec: string;\n roles?: string[];\n roleInstructions?: Record<string, string>;\n groups?: { id: string; title?: string }[];\n}\n\n/** Field-level Markform extension data */\nexport interface MarkformFieldExtension {\n role?: string;\n priority?: FieldPriorityLevel;\n group?: string;\n checkboxMode?: CheckboxMode;\n approvalMode?: ApprovalMode;\n minDone?: number;\n placeholder?: string;\n examples?: string[];\n}\n\n// =============================================================================\n// Options and Result Types\n// =============================================================================\n\n/** JSON Schema draft version */\nexport type JsonSchemaDraft = '2020-12' | '2019-09' | 'draft-07';\n\n/** Options for JSON Schema generation */\nexport interface JsonSchemaOptions {\n /** Include x-markform extension properties (default: true) */\n includeExtensions?: boolean;\n /** JSON Schema draft version (default: '2020-12') */\n draft?: JsonSchemaDraft;\n}\n\n/** Result from JSON Schema generation */\nexport interface JsonSchemaResult {\n /** The generated JSON Schema */\n schema: JsonSchemaRoot;\n}\n\n// =============================================================================\n// Schema URL Map\n// =============================================================================\n\nconst SCHEMA_URLS: Record<JsonSchemaDraft, string> = {\n '2020-12': 'https://json-schema.org/draft/2020-12/schema',\n '2019-09': 'https://json-schema.org/draft/2019-09/schema',\n 'draft-07': 'http://json-schema.org/draft-07/schema#',\n};\n\n// =============================================================================\n// Documentation Helpers\n// =============================================================================\n\n/**\n * Find description for a field from doc blocks.\n */\nfunction findDescription(docs: DocumentationBlock[], fieldId: string): string | undefined {\n // Look for 'description' or 'documentation' tags that reference this field\n for (const doc of docs) {\n if (doc.ref === fieldId && (doc.tag === 'description' || doc.tag === 'documentation')) {\n return doc.bodyMarkdown.trim();\n }\n }\n return undefined;\n}\n\n// =============================================================================\n// Field Type Converters\n// =============================================================================\n\nfunction stringFieldToJsonSchema(\n field: StringField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minLength !== undefined) {\n schema.minLength = field.minLength;\n }\n if (field.maxLength !== undefined) {\n schema.maxLength = field.maxLength;\n }\n if (field.pattern !== undefined) {\n schema.pattern = field.pattern;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction numberFieldToJsonSchema(\n field: NumberField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: field.integer ? 'integer' : 'number',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.min !== undefined) {\n schema.minimum = field.min;\n }\n if (field.max !== undefined) {\n schema.maximum = field.max;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction dateFieldToJsonSchema(\n field: DateField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n format: 'date',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n // Use formatMinimum/formatMaximum for date constraints (JSON Schema 2019-09/2020-12 only)\n // These keywords don't exist in draft-07, so we skip them for that draft\n if (options.draft !== 'draft-07') {\n if (field.min) {\n schema.formatMinimum = field.min;\n }\n if (field.max) {\n schema.formatMaximum = field.max;\n }\n }\n\n // Also include in x-markform extension for backward compatibility\n if (options.includeExtensions) {\n const ext = buildFieldExtension(field, groupId);\n if (field.min) {\n (ext as MarkformFieldExtension & { minDate?: string }).minDate = field.min;\n }\n if (field.max) {\n (ext as MarkformFieldExtension & { maxDate?: string }).maxDate = field.max;\n }\n schema['x-markform'] = ext;\n }\n\n return schema;\n}\n\nfunction yearFieldToJsonSchema(\n field: YearField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'integer',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.min !== undefined) {\n schema.minimum = field.min;\n }\n if (field.max !== undefined) {\n schema.maximum = field.max;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction urlFieldToJsonSchema(\n field: UrlField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n format: 'uri',\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction stringListFieldToJsonSchema(\n field: StringListField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const itemSchema: JsonSchemaProperty = { type: 'string' };\n if (field.itemMinLength !== undefined) {\n itemSchema.minLength = field.itemMinLength;\n }\n if (field.itemMaxLength !== undefined) {\n itemSchema.maxLength = field.itemMaxLength;\n }\n\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: itemSchema,\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minItems !== undefined) {\n schema.minItems = field.minItems;\n }\n if (field.maxItems !== undefined) {\n schema.maxItems = field.maxItems;\n }\n if (field.uniqueItems) {\n schema.uniqueItems = true;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction urlListFieldToJsonSchema(\n field: UrlListField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: { type: 'string', format: 'uri' },\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minItems !== undefined) {\n schema.minItems = field.minItems;\n }\n if (field.maxItems !== undefined) {\n schema.maxItems = field.maxItems;\n }\n if (field.uniqueItems) {\n schema.uniqueItems = true;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction singleSelectFieldToJsonSchema(\n field: SingleSelectField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'string',\n enum: field.options.map((opt) => opt.id),\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction multiSelectFieldToJsonSchema(\n field: MultiSelectField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: {\n type: 'string',\n enum: field.options.map((opt) => opt.id),\n },\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minSelections !== undefined) {\n schema.minItems = field.minSelections;\n }\n if (field.maxSelections !== undefined) {\n schema.maxItems = field.maxSelections;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction checkboxesFieldToJsonSchema(\n field: CheckboxesField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n // Checkboxes are represented as an object with each option as a property\n // The value for each property depends on the checkbox mode\n // Boolean values are also accepted and coerced: true→done/yes, false→todo/no\n const validStates = getValidCheckboxStates(field.checkboxMode);\n\n const properties: Record<string, JsonSchemaProperty> = {};\n for (const opt of field.options) {\n properties[opt.id] = {\n anyOf: [{ type: 'string', enum: validStates }, { type: 'boolean' }],\n title: opt.label,\n };\n }\n\n const schema: JsonSchemaProperty = {\n type: 'object',\n properties,\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (options.includeExtensions) {\n const ext = buildFieldExtension(field, groupId);\n ext.checkboxMode = field.checkboxMode;\n if (field.minDone !== undefined) {\n ext.minDone = field.minDone;\n }\n if (field.approvalMode !== 'none') {\n ext.approvalMode = field.approvalMode;\n }\n schema['x-markform'] = ext;\n }\n\n return schema;\n}\n\nfunction getValidCheckboxStates(mode: CheckboxMode): string[] {\n switch (mode) {\n case 'multi':\n return ['todo', 'done', 'incomplete', 'active', 'na'];\n case 'simple':\n return ['todo', 'done'];\n case 'explicit':\n return ['unfilled', 'yes', 'no'];\n }\n}\n\nfunction tableFieldToJsonSchema(\n field: TableField,\n docs: DocumentationBlock[],\n options: Required<JsonSchemaOptions>,\n groupId?: string,\n): JsonSchemaProperty {\n const rowProperties: Record<string, JsonSchemaProperty> = {};\n const requiredColumns: string[] = [];\n\n for (const col of field.columns) {\n rowProperties[col.id] = columnToJsonSchema(col);\n if (col.required) {\n requiredColumns.push(col.id);\n }\n }\n\n const rowSchema: JsonSchemaProperty = {\n type: 'object',\n properties: rowProperties,\n };\n\n if (requiredColumns.length > 0) {\n rowSchema.required = requiredColumns;\n }\n\n const schema: JsonSchemaProperty = {\n type: 'array',\n items: rowSchema,\n title: field.label,\n };\n\n const description = findDescription(docs, field.id);\n if (description) {\n schema.description = description;\n }\n\n if (field.minRows !== undefined) {\n schema.minItems = field.minRows;\n }\n if (field.maxRows !== undefined) {\n schema.maxItems = field.maxRows;\n }\n\n if (options.includeExtensions) {\n schema['x-markform'] = buildFieldExtension(field, groupId);\n }\n\n return schema;\n}\n\nfunction columnToJsonSchema(col: TableColumn): JsonSchemaProperty {\n const schema: JsonSchemaProperty = {\n title: col.label,\n };\n\n switch (col.type) {\n case 'string':\n schema.type = 'string';\n break;\n case 'number':\n schema.type = 'number';\n break;\n case 'url':\n schema.type = 'string';\n schema.format = 'uri';\n break;\n case 'date':\n schema.type = 'string';\n schema.format = 'date';\n break;\n case 'year':\n schema.type = 'integer';\n break;\n }\n\n return schema;\n}\n\n// =============================================================================\n// Extension Builders\n// =============================================================================\n\nfunction buildFieldExtension(field: Field, groupId?: string): MarkformFieldExtension {\n const ext: MarkformFieldExtension = {};\n\n if (field.role) {\n ext.role = field.role;\n }\n\n if (field.priority && field.priority !== 'medium') {\n ext.priority = field.priority;\n }\n\n if (groupId) {\n ext.group = groupId;\n }\n\n if (field.placeholder) {\n ext.placeholder = field.placeholder;\n }\n\n if (field.examples && field.examples.length > 0) {\n ext.examples = field.examples;\n }\n\n return ext;\n}\n\nfunction buildSchemaExtension(form: ParsedForm): MarkformSchemaExtension {\n const ext: MarkformSchemaExtension = {\n spec: form.metadata?.markformVersion ?? 'MF/0.1',\n };\n\n if (form.metadata?.roles && form.metadata.roles.length > 0) {\n ext.roles = form.metadata.roles;\n }\n\n if (form.metadata?.roleInstructions && Object.keys(form.metadata.roleInstructions).length > 0) {\n ext.roleInstructions = form.metadata.roleInstructions;\n }\n\n // Build groups list (excluding implicit groups)\n const groups: { id: string; title?: string }[] = [];\n for (const group of form.schema.groups) {\n if (!group.implicit) {\n groups.push({\n id: group.id,\n ...(group.title ? { title: group.title } : {}),\n });\n }\n }\n if (groups.length > 0) {\n ext.groups = groups;\n }\n\n return ext;\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Convert a single field to its JSON Schema representation.\n */\nexport function fieldToJsonSchema(\n field: Field,\n docs: DocumentationBlock[],\n options?: JsonSchemaOptions,\n groupId?: string,\n): JsonSchemaProperty {\n const opts: Required<JsonSchemaOptions> = {\n includeExtensions: options?.includeExtensions ?? true,\n draft: options?.draft ?? '2020-12',\n };\n\n switch (field.kind) {\n case 'string':\n return stringFieldToJsonSchema(field, docs, opts, groupId);\n case 'number':\n return numberFieldToJsonSchema(field, docs, opts, groupId);\n case 'date':\n return dateFieldToJsonSchema(field, docs, opts, groupId);\n case 'year':\n return yearFieldToJsonSchema(field, docs, opts, groupId);\n case 'url':\n return urlFieldToJsonSchema(field, docs, opts, groupId);\n case 'string_list':\n return stringListFieldToJsonSchema(field, docs, opts, groupId);\n case 'url_list':\n return urlListFieldToJsonSchema(field, docs, opts, groupId);\n case 'single_select':\n return singleSelectFieldToJsonSchema(field, docs, opts, groupId);\n case 'multi_select':\n return multiSelectFieldToJsonSchema(field, docs, opts, groupId);\n case 'checkboxes':\n return checkboxesFieldToJsonSchema(field, docs, opts, groupId);\n case 'table':\n return tableFieldToJsonSchema(field, docs, opts, groupId);\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = field;\n throw new Error(`Unhandled field kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n}\n\n/**\n * Convert a parsed form to JSON Schema.\n *\n * Main API for JSON Schema generation. Use from libraries or CLI.\n */\nexport function formToJsonSchema(form: ParsedForm, options?: JsonSchemaOptions): JsonSchemaResult {\n const opts: Required<JsonSchemaOptions> = {\n includeExtensions: options?.includeExtensions ?? true,\n draft: options?.draft ?? '2020-12',\n };\n\n const properties: Record<string, JsonSchemaProperty> = {};\n const requiredFields: string[] = [];\n\n // Process all fields from all groups\n for (const group of form.schema.groups) {\n const groupId = group.implicit ? undefined : group.id;\n for (const field of group.children) {\n properties[field.id] = fieldToJsonSchema(field, form.docs, opts, groupId);\n if (field.required) {\n requiredFields.push(field.id);\n }\n }\n }\n\n // Build root schema\n const schema: JsonSchemaRoot = {\n $schema: SCHEMA_URLS[opts.draft],\n $id: form.schema.id,\n type: 'object',\n properties,\n };\n\n if (form.schema.title) {\n schema.title = form.schema.title;\n }\n\n // Find form-level description\n const formDescription = findDescription(form.docs, form.schema.id);\n if (formDescription) {\n schema.description = formDescription;\n }\n\n if (requiredFields.length > 0) {\n schema.required = requiredFields;\n }\n\n if (opts.includeExtensions) {\n schema['x-markform'] = buildSchemaExtension(form);\n }\n\n return { schema };\n}\n","/**\n * Scope Reference Parsing and Serialization.\n *\n * Handles parsing and serialization of scope reference strings used in issues and validation.\n *\n * Scope reference formats:\n * - `fieldId` - simple field reference\n * - `fieldId.optionId` - qualified option/column reference (context-dependent)\n * - `fieldId[row].columnId` - cell reference (tables only)\n *\n * The distinction between option and column references is made during resolution\n * with schema context (see scopeRefValidation.ts).\n */\n\nimport type { Id } from './coreTypes.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Simple field reference */\nexport interface FieldScopeRef {\n type: 'field';\n fieldId: Id;\n}\n\n/**\n * Qualified reference - could be option or column.\n * Disambiguation happens during resolution with schema context.\n */\nexport interface QualifiedScopeRef {\n type: 'qualified';\n fieldId: Id;\n qualifierId: Id; // optionId or columnId\n}\n\n/** Cell reference - table field specific */\nexport interface CellScopeRef {\n type: 'cell';\n fieldId: Id;\n row: number; // 0-indexed row number\n columnId: Id;\n}\n\n/** Union of all parsed scope reference types */\nexport type ParsedScopeRef = FieldScopeRef | QualifiedScopeRef | CellScopeRef;\n\n/** Result of parsing a scope reference */\nexport type ParseScopeRefResult = { ok: true; ref: ParsedScopeRef } | { ok: false; error: string };\n\n// =============================================================================\n// Regex Patterns\n// =============================================================================\n\n/**\n * Pattern for cell reference: fieldId[row].columnId\n * - fieldId: identifier (letters, digits, underscores, hyphens)\n * - row: non-negative integer\n * - columnId: identifier\n */\nconst CELL_REF_PATTERN = /^([a-zA-Z_][a-zA-Z0-9_-]*)\\[(\\d+)\\]\\.([a-zA-Z_][a-zA-Z0-9_-]*)$/;\n\n/**\n * Pattern for qualified reference: fieldId.qualifierId\n * - fieldId: identifier\n * - qualifierId: identifier (optionId or columnId)\n */\nconst QUALIFIED_REF_PATTERN = /^([a-zA-Z_][a-zA-Z0-9_-]*)\\.([a-zA-Z_][a-zA-Z0-9_-]*)$/;\n\n/**\n * Pattern for simple field reference: fieldId\n * - fieldId: identifier\n */\nconst FIELD_REF_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_-]*$/;\n\n// =============================================================================\n// Parsing\n// =============================================================================\n\n/**\n * Parse a scope reference string into a structured format.\n *\n * @param refStr - The scope reference string to parse\n * @returns Parsed scope reference or error\n *\n * @example\n * parseScopeRef('myField')\n * // => { ok: true, ref: { type: 'field', fieldId: 'myField' } }\n *\n * parseScopeRef('myField.optA')\n * // => { ok: true, ref: { type: 'qualified', fieldId: 'myField', qualifierId: 'optA' } }\n *\n * parseScopeRef('myTable[2].name')\n * // => { ok: true, ref: { type: 'cell', fieldId: 'myTable', row: 2, columnId: 'name' } }\n */\nexport function parseScopeRef(refStr: string): ParseScopeRefResult {\n // Trim whitespace\n const trimmed = refStr.trim();\n\n if (!trimmed) {\n return { ok: false, error: 'Empty scope reference' };\n }\n\n // Try cell reference first (most specific pattern)\n const cellMatch = CELL_REF_PATTERN.exec(trimmed);\n if (cellMatch) {\n const fieldId = cellMatch[1]!;\n const rowStr = cellMatch[2]!;\n const columnId = cellMatch[3]!;\n const row = parseInt(rowStr, 10);\n if (row < 0 || !Number.isInteger(row)) {\n return { ok: false, error: `Invalid row index: ${rowStr}` };\n }\n return {\n ok: true,\n ref: { type: 'cell', fieldId, row, columnId },\n };\n }\n\n // Try qualified reference\n const qualifiedMatch = QUALIFIED_REF_PATTERN.exec(trimmed);\n if (qualifiedMatch) {\n const fieldId = qualifiedMatch[1]!;\n const qualifierId = qualifiedMatch[2]!;\n return {\n ok: true,\n ref: { type: 'qualified', fieldId, qualifierId },\n };\n }\n\n // Try simple field reference\n if (FIELD_REF_PATTERN.test(trimmed)) {\n return {\n ok: true,\n ref: { type: 'field', fieldId: trimmed },\n };\n }\n\n return { ok: false, error: `Invalid scope reference format: ${refStr}` };\n}\n\n// =============================================================================\n// Serialization\n// =============================================================================\n\n/**\n * Serialize a parsed scope reference back to a string.\n *\n * @param ref - The parsed scope reference\n * @returns Serialized string\n *\n * @example\n * serializeScopeRef({ type: 'field', fieldId: 'myField' })\n * // => 'myField'\n *\n * serializeScopeRef({ type: 'qualified', fieldId: 'myField', qualifierId: 'optA' })\n * // => 'myField.optA'\n *\n * serializeScopeRef({ type: 'cell', fieldId: 'myTable', row: 2, columnId: 'name' })\n * // => 'myTable[2].name'\n */\nexport function serializeScopeRef(ref: ParsedScopeRef): string {\n switch (ref.type) {\n case 'field':\n return ref.fieldId;\n case 'qualified':\n return `${ref.fieldId}.${ref.qualifierId}`;\n case 'cell':\n return `${ref.fieldId}[${ref.row}].${ref.columnId}`;\n }\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Check if a scope reference is a cell reference.\n */\nexport function isCellRef(ref: ParsedScopeRef): ref is CellScopeRef {\n return ref.type === 'cell';\n}\n\n/**\n * Check if a scope reference is a qualified reference.\n */\nexport function isQualifiedRef(ref: ParsedScopeRef): ref is QualifiedScopeRef {\n return ref.type === 'qualified';\n}\n\n/**\n * Check if a scope reference is a simple field reference.\n */\nexport function isFieldRef(ref: ParsedScopeRef): ref is FieldScopeRef {\n return ref.type === 'field';\n}\n\n/**\n * Extract the field ID from any scope reference.\n */\nexport function getFieldId(ref: ParsedScopeRef): Id {\n return ref.fieldId;\n}\n","/**\n * Unified value coercion layer for converting raw input values to typed Patches.\n *\n * This module provides the single source of truth for:\n * - Field lookup by ID (using idIndex for O(1) lookups)\n * - Coercing raw values to typed Patches with validation\n * - Batch coercion of InputContext with warnings/errors\n */\n\nimport type {\n CheckboxValue,\n Field,\n OptionId,\n ParsedForm,\n Patch,\n TableRowPatch,\n} from './coreTypes.js';\n\n// =============================================================================\n// Raw Input Types\n// =============================================================================\n\n/** Raw value that can be coerced to a field value. */\nexport type RawFieldValue = string | number | boolean | string[] | Record<string, unknown> | null;\n\n/** Input context is a map of field IDs to raw values. */\nexport type InputContext = Record<string, RawFieldValue>;\n\n// =============================================================================\n// Coercion Results\n// =============================================================================\n\nexport type CoercionResult =\n | { ok: true; patch: Patch }\n | { ok: true; patch: Patch; warning: string }\n | { ok: false; error: string };\n\nexport interface CoerceInputContextResult {\n patches: Patch[];\n /** Non-fatal warnings (e.g., \"coerced '123' to number for field X\") */\n warnings: string[];\n /** Fatal errors (e.g., \"field 'foo' not found\") */\n errors: string[];\n}\n\n// =============================================================================\n// Field Lookup\n// =============================================================================\n\n/**\n * Find a field by ID.\n *\n * Uses idIndex for O(1) validation that the ID exists and is a field,\n * then retrieves the Field object from the schema.\n */\nexport function findFieldById(form: ParsedForm, fieldId: string): Field | undefined {\n // O(1) check: verify the ID exists and is a field\n const entry = form.idIndex.get(fieldId);\n if (entry?.nodeType !== 'field') {\n return undefined;\n }\n\n // Retrieve the Field object from the schema\n for (const group of form.schema.groups) {\n for (const field of group.children) {\n if (field.id === fieldId) {\n return field;\n }\n }\n }\n\n return undefined;\n}\n\n// =============================================================================\n// Coercion Helpers\n// =============================================================================\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\n// =============================================================================\n// Field-Specific Coercion\n// =============================================================================\n\nfunction coerceToString(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'number') {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: String(rawValue) },\n warning: `Coerced number ${rawValue} to string for field '${fieldId}'`,\n };\n }\n\n if (typeof rawValue === 'boolean') {\n return {\n ok: true,\n patch: { op: 'set_string', fieldId, value: String(rawValue) },\n warning: `Coerced boolean ${rawValue} to string for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to string for field '${fieldId}'`,\n };\n}\n\nfunction coerceToNumber(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_number', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'number') {\n return {\n ok: true,\n patch: { op: 'set_number', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n const parsed = Number(rawValue);\n if (!Number.isNaN(parsed)) {\n return {\n ok: true,\n patch: { op: 'set_number', fieldId, value: parsed },\n warning: `Coerced string '${rawValue}' to number for field '${fieldId}'`,\n };\n }\n return {\n ok: false,\n error: `Cannot coerce non-numeric string '${rawValue}' to number for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to number for field '${fieldId}'`,\n };\n}\n\nfunction coerceToStringList(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: [] },\n };\n }\n\n if (isStringArray(rawValue)) {\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: [rawValue] },\n warning: `Coerced single string to array for field '${fieldId}'`,\n };\n }\n\n if (Array.isArray(rawValue)) {\n // Try to coerce non-string items\n const items: string[] = [];\n for (const item of rawValue) {\n if (typeof item === 'string') {\n items.push(item);\n } else if (typeof item === 'number' || typeof item === 'boolean') {\n items.push(String(item));\n } else {\n return {\n ok: false,\n error: `Cannot coerce array with non-string items to string_list for field '${fieldId}'`,\n };\n }\n }\n return {\n ok: true,\n patch: { op: 'set_string_list', fieldId, value: items },\n warning: `Coerced array items to strings for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to string_list for field '${fieldId}'`,\n };\n}\n\nfunction coerceToSingleSelect(field: Field, rawValue: RawFieldValue): CoercionResult {\n if (field.kind !== 'single_select') {\n return { ok: false, error: `Field '${field.id}' is not a single_select field` };\n }\n\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_single_select', fieldId: field.id, value: null },\n };\n }\n\n if (typeof rawValue !== 'string') {\n return {\n ok: false,\n error: `single_select field '${field.id}' requires a string option ID, got ${typeof rawValue}`,\n };\n }\n\n const validOptions = new Set(field.options.map((o) => o.id));\n if (!validOptions.has(rawValue)) {\n return {\n ok: false,\n error: `Invalid option '${rawValue}' for single_select field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n\n return {\n ok: true,\n patch: { op: 'set_single_select', fieldId: field.id, value: rawValue },\n };\n}\n\nfunction coerceToMultiSelect(field: Field, rawValue: RawFieldValue): CoercionResult {\n if (field.kind !== 'multi_select') {\n return { ok: false, error: `Field '${field.id}' is not a multi_select field` };\n }\n\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_multi_select', fieldId: field.id, value: [] },\n };\n }\n\n const validOptions = new Set(field.options.map((o) => o.id));\n let selected: string[];\n let warning: string | undefined;\n\n if (typeof rawValue === 'string') {\n selected = [rawValue];\n warning = `Coerced single string to array for multi_select field '${field.id}'`;\n } else if (isStringArray(rawValue)) {\n selected = rawValue;\n } else {\n return {\n ok: false,\n error: `multi_select field '${field.id}' requires a string or string array, got ${typeof rawValue}`,\n };\n }\n\n // Validate all options\n for (const optId of selected) {\n if (!validOptions.has(optId)) {\n return {\n ok: false,\n error: `Invalid option '${optId}' for multi_select field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n }\n\n const patch: Patch = { op: 'set_multi_select', fieldId: field.id, value: selected };\n return warning ? { ok: true, patch, warning } : { ok: true, patch };\n}\n\nfunction coerceToCheckboxes(field: Field, rawValue: RawFieldValue): CoercionResult {\n if (field.kind !== 'checkboxes') {\n return { ok: false, error: `Field '${field.id}' is not a checkboxes field` };\n }\n\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_checkboxes', fieldId: field.id, value: {} },\n };\n }\n\n const validOptions = new Set(field.options.map((o) => o.id));\n const checkboxMode = field.checkboxMode;\n\n // Coerce array of option IDs to checkbox object with default state\n if (Array.isArray(rawValue)) {\n const defaultState = checkboxMode === 'explicit' ? 'yes' : 'done';\n const values: Record<string, CheckboxValue> = {};\n\n for (const item of rawValue) {\n if (typeof item !== 'string') {\n return {\n ok: false,\n error: `Array items for checkboxes field '${field.id}' must be strings (option IDs), got ${typeof item}`,\n };\n }\n if (!validOptions.has(item)) {\n return {\n ok: false,\n error: `Invalid option '${item}' for checkboxes field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n values[item] = defaultState;\n }\n\n const patch: Patch = { op: 'set_checkboxes', fieldId: field.id, value: values };\n\n // Empty array: no warning needed\n if (rawValue.length === 0) {\n return { ok: true, patch };\n }\n\n return {\n ok: true,\n patch,\n warning: `Coerced array to checkboxes object with '${defaultState}' state for field '${field.id}'`,\n };\n }\n\n if (!isPlainObject(rawValue)) {\n return {\n ok: false,\n error: `checkboxes field '${field.id}' requires a Record<string, CheckboxValue> or array of option IDs, got ${typeof rawValue}`,\n };\n }\n\n const values: Record<OptionId, CheckboxValue> = {};\n let hadBooleanCoercion = false;\n\n // Valid checkbox values based on mode\n const validValues = new Set<string>(\n checkboxMode === 'explicit'\n ? ['unfilled', 'yes', 'no']\n : checkboxMode === 'simple'\n ? ['todo', 'done']\n : ['todo', 'done', 'incomplete', 'active', 'na'],\n );\n\n for (const [optId, value] of Object.entries(rawValue)) {\n if (!validOptions.has(optId)) {\n return {\n ok: false,\n error: `Invalid option '${optId}' for checkboxes field '${field.id}'. Valid options: ${Array.from(validOptions).join(', ')}`,\n };\n }\n\n // Coerce boolean values to appropriate checkbox strings\n if (typeof value === 'boolean') {\n hadBooleanCoercion = true;\n if (checkboxMode === 'explicit') {\n values[optId] = value ? 'yes' : 'no';\n } else {\n values[optId] = value ? 'done' : 'todo';\n }\n continue;\n }\n\n if (typeof value !== 'string' || !validValues.has(value)) {\n return {\n ok: false,\n error: `Invalid checkbox value '${String(value)}' for option '${optId}' in field '${field.id}'. Valid values for ${checkboxMode} mode: ${Array.from(validValues).join(', ')} (or use true/false)`,\n };\n }\n\n values[optId] = value as CheckboxValue;\n }\n\n const patch: Patch = { op: 'set_checkboxes', fieldId: field.id, value: values };\n if (hadBooleanCoercion) {\n return {\n ok: true,\n patch,\n warning: `Coerced boolean values to checkbox strings for field '${field.id}'`,\n };\n }\n return { ok: true, patch };\n}\n\nfunction coerceToUrl(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_url', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_url', fieldId, value: rawValue },\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to url for field '${fieldId}'`,\n };\n}\n\nfunction coerceToUrlList(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: [] },\n };\n }\n\n if (isStringArray(rawValue)) {\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: [rawValue] },\n warning: `Coerced single string to array for field '${fieldId}'`,\n };\n }\n\n if (Array.isArray(rawValue)) {\n // Try to coerce non-string items\n const items: string[] = [];\n for (const item of rawValue) {\n if (typeof item === 'string') {\n items.push(item);\n } else {\n return {\n ok: false,\n error: `Cannot coerce array with non-string items to url_list for field '${fieldId}'`,\n };\n }\n }\n return {\n ok: true,\n patch: { op: 'set_url_list', fieldId, value: items },\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to url_list for field '${fieldId}'`,\n };\n}\n\nfunction coerceToDate(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_date', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'string') {\n return {\n ok: true,\n patch: { op: 'set_date', fieldId, value: rawValue },\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to date for field '${fieldId}'`,\n };\n}\n\nfunction coerceToYear(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_year', fieldId, value: null },\n };\n }\n\n if (typeof rawValue === 'number') {\n if (!Number.isInteger(rawValue)) {\n return {\n ok: false,\n error: `Year must be an integer for field '${fieldId}', got ${rawValue}`,\n };\n }\n return {\n ok: true,\n patch: { op: 'set_year', fieldId, value: rawValue },\n };\n }\n\n if (typeof rawValue === 'string') {\n const parsed = Number.parseInt(rawValue, 10);\n if (Number.isNaN(parsed)) {\n return {\n ok: false,\n error: `Cannot coerce non-numeric string '${rawValue}' to year for field '${fieldId}'`,\n };\n }\n return {\n ok: true,\n patch: { op: 'set_year', fieldId, value: parsed },\n warning: `Coerced string '${rawValue}' to year for field '${fieldId}'`,\n };\n }\n\n return {\n ok: false,\n error: `Cannot coerce ${typeof rawValue} to year for field '${fieldId}'`,\n };\n}\n\n/**\n * Coerce raw value to SetTablePatch.\n * Accepts:\n * - Array of row objects: [{ col1: value1, col2: value2 }, ...]\n * - Empty array: [] (valid for optional tables or minRows=0)\n */\nfunction coerceToTable(fieldId: string, rawValue: RawFieldValue): CoercionResult {\n // Handle null as clear\n if (rawValue === null) {\n return {\n ok: true,\n patch: { op: 'set_table', fieldId, value: [] },\n };\n }\n\n // Must be an array\n if (!Array.isArray(rawValue)) {\n return {\n ok: false,\n error: `Table value for field '${fieldId}' must be an array of rows, got ${typeof rawValue}`,\n };\n }\n\n // Empty array is valid\n if (rawValue.length === 0) {\n return {\n ok: true,\n patch: { op: 'set_table', fieldId, value: [] },\n };\n }\n\n // Process each row\n const rows: TableRowPatch[] = [];\n for (let i = 0; i < rawValue.length; i++) {\n const row = rawValue[i];\n if (typeof row !== 'object' || row === null || Array.isArray(row)) {\n return {\n ok: false,\n error: `Row ${i} for table field '${fieldId}' must be an object, got ${Array.isArray(row) ? 'array' : typeof row}`,\n };\n }\n rows.push(row as TableRowPatch);\n }\n\n return {\n ok: true,\n patch: { op: 'set_table', fieldId, value: rows },\n };\n}\n\n// =============================================================================\n// Main Coercion Functions\n// =============================================================================\n\n/**\n * Coerce a raw value to a Patch for a specific field.\n */\nexport function coerceToFieldPatch(\n form: ParsedForm,\n fieldId: string,\n rawValue: RawFieldValue,\n): CoercionResult {\n const field = findFieldById(form, fieldId);\n if (!field) {\n return { ok: false, error: `Field '${fieldId}' not found` };\n }\n\n switch (field.kind) {\n case 'string':\n return coerceToString(fieldId, rawValue);\n case 'number':\n return coerceToNumber(fieldId, rawValue);\n case 'string_list':\n return coerceToStringList(fieldId, rawValue);\n case 'single_select':\n return coerceToSingleSelect(field, rawValue);\n case 'multi_select':\n return coerceToMultiSelect(field, rawValue);\n case 'checkboxes':\n return coerceToCheckboxes(field, rawValue);\n case 'url':\n return coerceToUrl(fieldId, rawValue);\n case 'url_list':\n return coerceToUrlList(fieldId, rawValue);\n case 'date':\n return coerceToDate(fieldId, rawValue);\n case 'year':\n return coerceToYear(fieldId, rawValue);\n case 'table':\n return coerceToTable(fieldId, rawValue);\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = field;\n throw new Error(`Unhandled field kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n}\n\n/**\n * Coerce an entire InputContext to patches.\n *\n * Returns patches for valid entries, collects warnings for coercions,\n * and errors for invalid entries.\n */\nexport function coerceInputContext(\n form: ParsedForm,\n inputContext: InputContext,\n): CoerceInputContextResult {\n const patches: Patch[] = [];\n const warnings: string[] = [];\n const errors: string[] = [];\n\n for (const [fieldId, rawValue] of Object.entries(inputContext)) {\n // Skip null values (no-op, field unchanged)\n if (rawValue === null) {\n continue;\n }\n\n const result = coerceToFieldPatch(form, fieldId, rawValue);\n\n if (result.ok) {\n patches.push(result.patch);\n if ('warning' in result && result.warning) {\n warnings.push(result.warning);\n }\n } else {\n errors.push(result.error);\n }\n }\n\n return { patches, warnings, errors };\n}\n","/**\n * Form Harness - Execution harness for form filling.\n *\n * Manages the step protocol for agent-driven form completion:\n * INIT -> STEP -> WAIT -> APPLY -> (repeat) -> COMPLETE\n */\n\n// Use pure JS sha256 to avoid node:crypto dependency, enabling use in\n// browsers, edge runtimes (Cloudflare Workers, Convex), and other non-Node environments.\nimport { sha256 } from 'js-sha256';\n\nimport { applyPatches } from '../engine/apply.js';\nimport { inspect, getFieldsForRoles } from '../engine/inspect.js';\nimport { serializeForm } from '../engine/serialize.js';\nimport type {\n ClearFieldPatch,\n HarnessConfig,\n InspectIssue,\n ParsedForm,\n Patch,\n PatchRejection,\n PatchWarning,\n SessionTurn,\n SessionTurnContext,\n SessionTurnStats,\n StepResult,\n WireFormat,\n} from '../engine/coreTypes.js';\nimport {\n DEFAULT_MAX_ISSUES_PER_TURN,\n DEFAULT_MAX_PATCHES_PER_TURN,\n DEFAULT_MAX_TURNS,\n AGENT_ROLE,\n} from '../settings.js';\n\n// =============================================================================\n// Default Configuration\n// =============================================================================\n\nconst DEFAULT_CONFIG: HarnessConfig = {\n maxIssuesPerTurn: DEFAULT_MAX_ISSUES_PER_TURN,\n maxPatchesPerTurn: DEFAULT_MAX_PATCHES_PER_TURN,\n maxTurns: DEFAULT_MAX_TURNS,\n};\n\n// =============================================================================\n// Harness State\n// =============================================================================\n\ntype HarnessState = 'init' | 'step' | 'wait' | 'complete';\n\n// =============================================================================\n// Form Harness Class\n// =============================================================================\n\n/**\n * Form harness for managing agent-driven form filling.\n */\nexport class FormHarness {\n private form: ParsedForm;\n private config: HarnessConfig;\n private state: HarnessState = 'init';\n private turnNumber = 0;\n private turns: SessionTurn[] = [];\n\n constructor(form: ParsedForm, config: Partial<HarnessConfig> = {}) {\n this.form = form;\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Get the current harness state.\n */\n getState(): HarnessState {\n return this.state;\n }\n\n /**\n * Get the current turn number.\n */\n getTurnNumber(): number {\n return this.turnNumber;\n }\n\n /**\n * Get the recorded session turns.\n */\n getTurns(): SessionTurn[] {\n return [...this.turns];\n }\n\n /**\n * Get the current form.\n */\n getForm(): ParsedForm {\n return this.form;\n }\n\n /**\n * Check if the harness has reached max turns.\n *\n * Returns true when we've completed all allowed turns. This happens when:\n * - turnNumber >= maxTurns AND we've already applied (state is \"complete\")\n * - OR turnNumber > maxTurns (we've exceeded the limit)\n *\n * This allows the harness loop to run N times when maxTurns=N by returning\n * false when we're at turn N but haven't applied yet (state is \"wait\").\n */\n hasReachedMaxTurns(): boolean {\n // If we've exceeded the limit, always return true\n if (this.turnNumber > this.config.maxTurns) {\n return true;\n }\n // At the last turn, check if we've completed it (state transitioned to \"complete\")\n if (this.turnNumber === this.config.maxTurns && this.state === 'complete') {\n return true;\n }\n return false;\n }\n\n /**\n * Perform a step - inspect the form and return current state.\n *\n * This transitions from INIT/WAIT -> STEP state.\n * Returns the current form state with prioritized issues.\n *\n * On first step with fillMode='overwrite', clears all target role fields\n * so they will be reported as needing to be filled.\n */\n step(): StepResult {\n if (this.state === 'complete') {\n throw new Error('Harness is complete - cannot step');\n }\n\n // On first step with fillMode='overwrite', clear all target role fields\n if (this.state === 'init' && this.config.fillMode === 'overwrite') {\n this.clearTargetRoleFields();\n }\n\n // Increment turn number\n this.turnNumber++;\n\n // Check max turns\n if (this.turnNumber > this.config.maxTurns) {\n this.state = 'complete';\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n return {\n structureSummary: result.structureSummary,\n progressSummary: result.progressSummary,\n issues: [],\n stepBudget: 0,\n isComplete: result.isComplete,\n turnNumber: this.turnNumber,\n };\n }\n\n this.state = 'step';\n\n // Inspect form and compute step result\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n const stepResult = this.computeStepResult(result);\n\n // Transition state based on whether there's more work\n this.state = stepResult.issues.length === 0 ? 'complete' : 'wait';\n\n return stepResult;\n }\n\n /**\n * Apply patches to the form.\n *\n * This transitions from WAIT -> STEP/COMPLETE state.\n * Records the turn in the session transcript.\n *\n * @param patches - Patches to apply\n * @param issues - Issues that were shown to the agent (for recording)\n * @param llmStats - Optional LLM stats for session logging\n * @param context - Optional context prompts sent to LLM (for session logging)\n * @param wire - Optional wire format for comprehensive session logging\n * @returns StepResult after applying patches\n */\n apply(\n patches: Patch[],\n issues: InspectIssue[],\n llmStats?: SessionTurnStats,\n context?: SessionTurnContext,\n wire?: WireFormat,\n ): StepResult {\n if (this.state !== 'wait') {\n throw new Error(`Cannot apply in state: ${this.state}`);\n }\n\n if (patches.length > this.config.maxPatchesPerTurn) {\n throw new Error(`Too many patches: ${patches.length} > ${this.config.maxPatchesPerTurn}`);\n }\n\n // Apply patches with best-effort semantics - valid patches are applied even when some fail\n const applyResult = applyPatches(this.form, patches);\n const patchesActuallyApplied = applyResult.appliedPatches.length;\n\n // Re-inspect after applying patches to get full issue list including optional_unanswered\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n const stepResult = this.computeStepResult(result);\n\n // Add actual patch count and rejection details to step result\n stepResult.patchesApplied = patchesActuallyApplied;\n stepResult.rejectedPatches = applyResult.rejectedPatches;\n\n // Record turn in session transcript (include rejections, warnings, and wire format)\n this.recordTurn(\n issues,\n patches,\n result,\n llmStats,\n context,\n applyResult.rejectedPatches,\n applyResult.warnings,\n wire,\n );\n\n // Transition state: complete if no more work OR max turns reached\n const noMoreWork = stepResult.issues.length === 0;\n if (noMoreWork || this.turnNumber >= this.config.maxTurns) {\n this.state = 'complete';\n } else {\n this.state = 'wait';\n }\n\n return stepResult;\n }\n\n /**\n * Compute step result from inspect result.\n * Applies issue filtering and computes step budget.\n */\n private computeStepResult(result: ReturnType<typeof inspect>): StepResult {\n // Issue filtering pipeline (order matters):\n // 0. Filter by order level - only surface issues for the current (lowest incomplete) order\n // 1. Filter by maxGroupsPerTurn/maxFieldsPerTurn - limits scope diversity\n // 2. Cap by maxIssuesPerTurn - limits total count shown to agent\n const orderFiltered = this.filterIssuesByOrder(result.issues);\n const filteredIssues = this.filterIssuesByScope(orderFiltered);\n const limitedIssues = filteredIssues.slice(0, this.config.maxIssuesPerTurn);\n\n // Step budget = min of max patches per turn and issues to address\n const stepBudget = Math.min(this.config.maxPatchesPerTurn, limitedIssues.length);\n\n return {\n structureSummary: result.structureSummary,\n progressSummary: result.progressSummary,\n issues: limitedIssues,\n stepBudget,\n isComplete: result.isComplete,\n turnNumber: this.turnNumber,\n };\n }\n\n /**\n * Record a turn in the session transcript.\n */\n private recordTurn(\n issues: InspectIssue[],\n patches: Patch[],\n result: ReturnType<typeof inspect>,\n llmStats?: SessionTurnStats,\n context?: SessionTurnContext,\n rejectedPatches?: PatchRejection[],\n warnings?: PatchWarning[],\n wire?: WireFormat,\n ): void {\n const markdown = serializeForm(this.form);\n const hash = sha256(markdown);\n\n const requiredIssueCount = result.issues.filter((i) => i.severity === 'required').length;\n\n const turn: SessionTurn = {\n turn: this.turnNumber,\n inspect: { issues },\n apply: {\n patches,\n ...(rejectedPatches && rejectedPatches.length > 0 && { rejectedPatches }),\n ...(warnings && warnings.length > 0 && { warnings }),\n },\n after: {\n requiredIssueCount,\n markdownSha256: hash,\n answeredFieldCount: result.progressSummary.counts.answeredFields,\n skippedFieldCount: result.progressSummary.counts.skippedFields,\n },\n };\n\n if (context) {\n turn.context = context;\n }\n\n if (llmStats) {\n turn.llm = llmStats;\n }\n\n if (wire) {\n turn.wire = wire;\n }\n\n this.turns.push(turn);\n }\n\n /**\n * Check if the form is complete.\n */\n isComplete(): boolean {\n const result = inspect(this.form, { targetRoles: this.config.targetRoles });\n return result.isComplete;\n }\n\n /**\n * Get the current markdown content of the form.\n */\n getMarkdown(): string {\n return serializeForm(this.form);\n }\n\n /**\n * Get the SHA256 hash of the current form markdown.\n */\n getMarkdownHash(): string {\n const markdown = serializeForm(this.form);\n return sha256(markdown);\n }\n\n /**\n * Filter issues based on maxFieldsPerTurn and maxGroupsPerTurn limits.\n *\n * Issues are processed in priority order. An issue is included if:\n * - Adding it doesn't exceed the field limit (for field/option scoped issues)\n * - Adding it doesn't exceed the group limit\n *\n * Form-level issues are always included.\n */\n private filterIssuesByScope(issues: InspectIssue[]): InspectIssue[] {\n const maxFields = this.config.maxFieldsPerTurn;\n const maxGroups = this.config.maxGroupsPerTurn;\n\n // If no limits configured, return all issues\n if (maxFields === undefined && maxGroups === undefined) {\n return issues;\n }\n\n const result: InspectIssue[] = [];\n const seenFields = new Set<string>();\n const seenGroups = new Set<string>();\n\n for (const issue of issues) {\n // Form-level issues always pass\n if (issue.scope === 'form') {\n result.push(issue);\n continue;\n }\n\n // Extract field ID from ref (for options, it's \"fieldId.optionId\")\n const fieldId = this.getFieldIdFromRef(issue.ref, issue.scope);\n\n // Get the parent group for the field (if any)\n const groupId = fieldId ? this.getGroupForField(fieldId) : undefined;\n\n // Check field limit\n if (maxFields !== undefined && fieldId) {\n if (!seenFields.has(fieldId) && seenFields.size >= maxFields) {\n continue; // Would exceed field limit\n }\n }\n\n // Check group limit\n if (maxGroups !== undefined && groupId) {\n if (!seenGroups.has(groupId) && seenGroups.size >= maxGroups) {\n continue; // Would exceed group limit\n }\n }\n\n // Include the issue and track the field/group\n result.push(issue);\n if (fieldId) {\n seenFields.add(fieldId);\n }\n if (groupId) {\n seenGroups.add(groupId);\n }\n }\n\n return result;\n }\n\n /**\n * Filter issues by order level.\n *\n * Only includes issues for fields at the current (lowest incomplete) order level.\n * Fields at higher order levels are deferred until all lower-order fields are complete.\n * If no order attributes are used, all issues pass through (all at order 0).\n */\n private filterIssuesByOrder(issues: InspectIssue[]): InspectIssue[] {\n // Build a map: fieldId → effective order\n const fieldOrderMap = new Map<string, number>();\n for (const group of this.form.schema.groups) {\n const groupOrder = group.order ?? 0;\n for (const field of group.children) {\n // If field has explicit order, use it; otherwise inherit group's order\n fieldOrderMap.set(field.id, field.order ?? groupOrder);\n }\n }\n\n // Find all distinct order levels that still have open issues\n const openOrderLevels = new Set<number>();\n for (const issue of issues) {\n const fieldId = this.getFieldIdFromRef(issue.ref, issue.scope);\n if (fieldId) {\n const order = fieldOrderMap.get(fieldId) ?? 0;\n openOrderLevels.add(order);\n } else if (issue.scope === 'form') {\n // Form-level issues are always at order 0\n openOrderLevels.add(0);\n }\n }\n\n if (openOrderLevels.size <= 1) {\n // All issues are at the same order level (or no issues) — no filtering needed\n return issues;\n }\n\n // Find the lowest order level with open issues\n const currentOrder = Math.min(...openOrderLevels);\n\n // Only include issues at the current order level\n return issues.filter((issue) => {\n if (issue.scope === 'form') {\n return true; // Form-level issues always pass\n }\n const fieldId = this.getFieldIdFromRef(issue.ref, issue.scope);\n if (!fieldId) {\n return true; // Can't determine order — include\n }\n const order = fieldOrderMap.get(fieldId) ?? 0;\n return order === currentOrder;\n });\n }\n\n /**\n * Extract field ID from an issue ref.\n */\n private getFieldIdFromRef(ref: string, scope: InspectIssue['scope']): string | undefined {\n if (scope === 'field') {\n return ref;\n }\n if (scope === 'option') {\n // Option refs are \"fieldId.optionId\"\n const dotIndex = ref.indexOf('.');\n return dotIndex > 0 ? ref.slice(0, dotIndex) : undefined;\n }\n // Group-level issues don't have a field\n return undefined;\n }\n\n /**\n * Get the parent group ID for a field.\n */\n private getGroupForField(fieldId: string): string | undefined {\n const entry = this.form.idIndex.get(fieldId);\n if (!entry) {\n return undefined;\n }\n\n // If the field has a parent and that parent is a group, return it\n if (entry.parentId) {\n const parentEntry = this.form.idIndex.get(entry.parentId);\n if (parentEntry?.nodeType === 'group') {\n return entry.parentId;\n }\n }\n\n return undefined;\n }\n\n /**\n * Clear all fields that match the target roles.\n * Used when fillMode='overwrite' to re-fill already-filled fields.\n */\n private clearTargetRoleFields(): void {\n const targetRoles = this.config.targetRoles ?? [AGENT_ROLE];\n const targetFields = getFieldsForRoles(this.form, targetRoles);\n\n // Create clear patches for all target role fields\n const clearPatches: ClearFieldPatch[] = targetFields.map((field) => ({\n op: 'clear_field' as const,\n fieldId: field.id,\n }));\n\n // Apply clear patches (this modifies the form in place)\n if (clearPatches.length > 0) {\n applyPatches(this.form, clearPatches);\n }\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a new form harness.\n *\n * @param form - The parsed form to fill\n * @param config - Optional harness configuration\n * @returns A new FormHarness instance\n */\nexport function createHarness(form: ParsedForm, config?: Partial<HarnessConfig>): FormHarness {\n return new FormHarness(form, config);\n}\n","/**\n * Mock Agent - Deterministic agent for testing harness execution.\n *\n * Uses a pre-filled \"completed mock\" form to generate patches\n * that fill the form deterministically.\n */\n\nimport type {\n CheckboxesValue,\n DateValue,\n Field,\n FieldValue,\n Id,\n InspectIssue,\n MultiSelectValue,\n NumberValue,\n Patch,\n ParsedForm,\n SingleSelectValue,\n StringListValue,\n StringValue,\n TableRowPatch,\n TableValue,\n UrlListValue,\n UrlValue,\n YearValue,\n} from '../engine/coreTypes.js';\nimport type { Agent, AgentResponse } from './harnessTypes.js';\n\n// Re-export Agent type for backwards compatibility\nexport type { Agent, AgentResponse } from './harnessTypes.js';\n\n// =============================================================================\n// Mock Agent Implementation\n// =============================================================================\n\n/**\n * Mock agent that generates patches from a pre-filled form.\n */\nexport class MockAgent implements Agent {\n private completedValues: Record<Id, FieldValue>;\n private fieldMap: Map<Id, Field>;\n\n /**\n * Create a mock agent from a completed form.\n *\n * @param completedForm - A fully-filled form to use as source of values\n */\n constructor(completedForm: ParsedForm) {\n // Extract values from responses\n this.completedValues = {};\n for (const [fieldId, response] of Object.entries(completedForm.responsesByFieldId)) {\n if (response.state === 'answered' && response.value) {\n this.completedValues[fieldId] = response.value;\n }\n }\n\n // Build field map for quick lookup\n this.fieldMap = new Map();\n for (const group of completedForm.schema.groups) {\n for (const field of group.children) {\n this.fieldMap.set(field.id, field);\n }\n }\n }\n\n /**\n * Invoke the fill_form tool using the completed mock to address issues.\n *\n * Processes issues in priority order, generating patches for\n * fields that have values in the completed mock. For fields with no\n * value (empty optional fields), generates skip_field patches.\n * Returns AgentResponse with patches but no stats (mock doesn't track LLM usage).\n */\n async fillFormTool(\n issues: InspectIssue[],\n _form: ParsedForm,\n maxPatches: number,\n ): Promise<AgentResponse> {\n const patches: Patch[] = [];\n const addressedFields = new Set<Id>();\n\n // Process issues in priority order\n for (const issue of issues) {\n if (patches.length >= maxPatches) {\n break;\n }\n\n // Skip non-field issues\n if (issue.scope !== 'field') {\n continue;\n }\n\n const fieldId = issue.ref;\n\n // Skip if we've already addressed this field\n if (addressedFields.has(fieldId)) {\n continue;\n }\n\n // Get field schema\n const field = this.fieldMap.get(fieldId);\n if (!field) {\n continue;\n }\n\n // Get the completed value for this field\n const completedValue = this.completedValues[fieldId];\n\n // If no value exists, generate skip_field patch for optional fields\n if (!completedValue || !this.hasValue(completedValue)) {\n if (!field.required) {\n patches.push({\n op: 'skip_field',\n fieldId,\n role: 'agent',\n reason: 'No value in mock form',\n });\n addressedFields.add(fieldId);\n }\n continue;\n }\n\n // Generate patch based on field kind\n const patch = this.createPatch(fieldId, field, completedValue);\n if (patch) {\n patches.push(patch);\n addressedFields.add(fieldId);\n }\n }\n\n // Return AgentResponse (no stats for mock agent)\n return Promise.resolve({ patches });\n }\n\n /**\n * Check if a field value actually has content (not null/empty).\n */\n private hasValue(value: FieldValue): boolean {\n switch (value.kind) {\n case 'string':\n return value.value !== null && value.value !== '';\n case 'number':\n return value.value !== null;\n case 'string_list':\n return value.items.length > 0;\n case 'single_select':\n return value.selected !== null;\n case 'multi_select':\n return value.selected.length > 0;\n case 'checkboxes':\n return true; // Checkboxes always have some state\n case 'url':\n return value.value !== null && value.value !== '';\n case 'url_list':\n return value.items.length > 0;\n case 'date':\n return value.value !== null;\n case 'year':\n return value.value !== null;\n case 'table':\n return (value.rows?.length ?? 0) > 0;\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = value;\n throw new Error(`Unhandled field value kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n }\n\n /**\n * Create a patch for a field based on its kind and completed value.\n */\n private createPatch(fieldId: Id, field: Field, value: FieldValue): Patch | null {\n switch (field.kind) {\n case 'string': {\n const v = value as StringValue;\n return {\n op: 'set_string',\n fieldId,\n value: v.value,\n };\n }\n\n case 'number': {\n const v = value as NumberValue;\n return {\n op: 'set_number',\n fieldId,\n value: v.value,\n };\n }\n\n case 'string_list': {\n const v = value as StringListValue;\n return {\n op: 'set_string_list',\n fieldId,\n value: v.items,\n };\n }\n\n case 'single_select': {\n const v = value as SingleSelectValue;\n return {\n op: 'set_single_select',\n fieldId,\n value: v.selected,\n };\n }\n\n case 'multi_select': {\n const v = value as MultiSelectValue;\n return {\n op: 'set_multi_select',\n fieldId,\n value: v.selected,\n };\n }\n\n case 'checkboxes': {\n const v = value as CheckboxesValue;\n return {\n op: 'set_checkboxes',\n fieldId,\n value: v.values,\n };\n }\n\n case 'url': {\n const v = value as UrlValue;\n return {\n op: 'set_url',\n fieldId,\n value: v.value,\n };\n }\n\n case 'url_list': {\n const v = value as UrlListValue;\n return {\n op: 'set_url_list',\n fieldId,\n value: v.items,\n };\n }\n\n case 'date': {\n const v = value as DateValue;\n return {\n op: 'set_date',\n fieldId,\n value: v.value,\n };\n }\n\n case 'year': {\n const v = value as YearValue;\n return {\n op: 'set_year',\n fieldId,\n value: v.value,\n };\n }\n\n case 'table': {\n const v = value as TableValue;\n // Convert TableRowResponse[] to TableRowPatch[]\n // TableRowResponse has CellResponse {state, value}, but patch needs just the value\n const patchRows: TableRowPatch[] = v.rows.map((row) => {\n const patchRow: TableRowPatch = {};\n for (const [colId, cellResponse] of Object.entries(row)) {\n // Use null for undefined values (skipped/empty cells)\n patchRow[colId] = cellResponse.value ?? null;\n }\n return patchRow;\n });\n return {\n op: 'set_table',\n fieldId,\n value: patchRows,\n };\n }\n\n default: {\n // Exhaustiveness check - TypeScript will error if a case is missing\n const _exhaustive: never = field;\n throw new Error(`Unhandled field kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a mock agent from a completed form.\n *\n * @param completedForm - A fully-filled form to use as source of values\n * @returns A new MockAgent instance\n */\nexport function createMockAgent(completedForm: ParsedForm): MockAgent {\n return new MockAgent(completedForm);\n}\n","/**\n * Execution plan computation for parallel form filling.\n *\n * Partitions a form's top-level items into a loose-serial pool and\n * zero or more parallel batches, grouped by order level.\n */\n\nimport type { ExecutionPlan, ExecutionPlanItem, ParallelBatch, ParsedForm } from './coreTypes.js';\n\n/**\n * Compute an execution plan from a parsed form.\n *\n * Walks top-level items (groups, or individual fields in implicit groups)\n * in document order and partitions them by their `parallel` attribute:\n * - Items without `parallel` go to the loose-serial pool.\n * - Items with the same `parallel` value form a parallel batch.\n *\n * Also computes distinct order levels across all items.\n */\nexport function computeExecutionPlan(form: ParsedForm): ExecutionPlan {\n const looseSerial: ExecutionPlanItem[] = [];\n const batchMap = new Map<string, ExecutionPlanItem[]>();\n const orderSet = new Set<number>();\n\n for (const group of form.schema.groups) {\n if (group.implicit) {\n // Implicit group: each child field is a top-level item\n for (const field of group.children) {\n const order = field.order ?? 0;\n orderSet.add(order);\n const item: ExecutionPlanItem = {\n itemId: field.id,\n itemType: 'field',\n order,\n };\n if (field.parallel) {\n const list = batchMap.get(field.parallel) ?? [];\n list.push(item);\n batchMap.set(field.parallel, list);\n } else {\n looseSerial.push(item);\n }\n }\n } else {\n // Explicit group: the group is the item\n const order = group.order ?? 0;\n orderSet.add(order);\n const item: ExecutionPlanItem = {\n itemId: group.id,\n itemType: 'group',\n order,\n };\n if (group.parallel) {\n const list = batchMap.get(group.parallel) ?? [];\n list.push(item);\n batchMap.set(group.parallel, list);\n } else {\n looseSerial.push(item);\n }\n }\n }\n\n const parallelBatches: ParallelBatch[] = [];\n for (const [batchId, items] of batchMap) {\n parallelBatches.push({ batchId, items });\n }\n\n const orderLevels = [...orderSet].sort((a, b) => a - b);\n\n return { looseSerial, parallelBatches, orderLevels };\n}\n","/**\n * Time utilities - Shared helpers for time and ID generation.\n *\n * Centralizes time-related operations for:\n * - Consistent behavior across the codebase\n * - Easy mocking in tests\n * - Clear audit of time-dependent code\n */\n\nimport { ulid } from 'ulid';\n\n/**\n * Get the current time as an ISO 8601 string.\n *\n * All code that needs \"now\" should call this function instead of\n * `new Date()` directly. This allows:\n * - Consistent timestamp format (ISO 8601)\n * - Clear visibility into time-dependent code\n * - Future support for clock mocking in tests\n *\n * @returns ISO 8601 timestamp string\n *\n * @example\n * ```typescript\n * const startedAt = currentTime();\n * // ... do work ...\n * const completedAt = currentTime();\n * ```\n */\nexport function currentTime(): string {\n return new Date().toISOString();\n}\n\n/**\n * Get the current time in milliseconds since Unix epoch.\n *\n * Use this when you need numeric timestamps for duration calculations.\n *\n * @returns Milliseconds since Unix epoch\n */\nexport function currentTimeMs(): number {\n return Date.now();\n}\n\n/**\n * Generate a unique session ID using ULID with a \"sess-\" prefix.\n *\n * ULIDs are:\n * - Lexicographically sortable by time\n * - 128-bit compatible with UUID\n * - URL-safe (no special characters)\n * - Monotonically increasing within the same millisecond\n *\n * The \"sess-\" prefix makes IDs self-identifying, following the policy\n * that all IDs should indicate their type at a glance. The ULID is\n * lowercased for consistency and readability.\n *\n * @returns Prefixed lowercase ULID string (31 characters: \"sess-\" + 26-char ULID)\n *\n * @example\n * ```typescript\n * const sessionId = generateSessionId();\n * // => \"sess-01arz3ndektsv4rrffq69g5fav\"\n * ```\n */\nexport function generateSessionId(): string {\n return `sess-${ulid().toLowerCase()}`;\n}\n","/**\n * FillRecordCollector - Append-only collector for fill records.\n *\n * Implements FillCallbacks to capture all events during a form fill operation\n * and assembles them into a FillRecord at the end.\n *\n * Concurrency model: Uses an append-only event log pattern that safely handles\n * interleaved async operations. JavaScript's single-threaded event loop ensures\n * that synchronous array pushes are atomic, so concurrent async callbacks can\n * safely append events without data races.\n *\n * @see docs/project/specs/active/plan-2026-01-29-fill-record.md\n */\n\nimport type { ProgressCounts, StructureSummary } from '../engine/coreTypes.js';\nimport type { FillCallbacks, TurnProgress } from './harnessTypes.js';\nimport type {\n FillRecord,\n FillRecordStatus,\n TimelineEntry,\n ToolCallRecord,\n ToolStats,\n ToolSummary,\n TimingBreakdown,\n TimingBreakdownItem,\n ExecutionMetadata,\n} from './fillRecord.js';\nimport { currentTime, generateSessionId } from './timeUtils.js';\n\n// =============================================================================\n// Internal Event Types\n// =============================================================================\n\ninterface TurnStartEvent {\n type: 'turn_start';\n timestamp: string;\n turnNumber: number;\n issuesCount: number;\n order: number;\n executionId: string;\n}\n\ninterface TurnCompleteEvent {\n type: 'turn_complete';\n timestamp: string;\n turnNumber: number;\n patchesApplied: number;\n patchesRejected: number;\n issuesAddressed: number;\n executionId?: string;\n}\n\ninterface LlmCallStartEvent {\n type: 'llm_call_start';\n timestamp: string;\n model: string;\n executionId: string;\n}\n\ninterface LlmCallEndEvent {\n type: 'llm_call_end';\n timestamp: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n executionId: string;\n}\n\ninterface ToolStartEvent {\n type: 'tool_start';\n timestamp: string;\n name: string;\n input: unknown;\n executionId: string;\n}\n\ninterface ToolEndEvent {\n type: 'tool_end';\n timestamp: string;\n name: string;\n output: unknown;\n durationMs: number;\n error?: string;\n executionId: string;\n}\n\ninterface WebSearchEvent {\n type: 'web_search';\n timestamp: string;\n query: string;\n resultCount: number;\n provider: string;\n executionId: string;\n}\n\ntype CollectorEvent =\n | TurnStartEvent\n | TurnCompleteEvent\n | LlmCallStartEvent\n | LlmCallEndEvent\n | ToolStartEvent\n | ToolEndEvent\n | WebSearchEvent;\n\n// =============================================================================\n// Options Interface\n// =============================================================================\n\nexport interface FillRecordCollectorOptions {\n /** Form metadata */\n form: {\n id: string;\n title?: string;\n description?: string;\n structure: StructureSummary;\n };\n /** LLM provider name */\n provider: string;\n /** Model identifier */\n model: string;\n /** Whether parallel execution is enabled */\n parallelEnabled?: boolean;\n /** Maximum parallel agents */\n maxParallelAgents?: number;\n /** Custom data to include in record */\n customData?: Record<string, unknown>;\n}\n\n// =============================================================================\n// FillRecordCollector Implementation\n// =============================================================================\n\n/**\n * Collector for FillRecord data from async form fill operations.\n *\n * Uses an append-only event log pattern that safely handles interleaved\n * async callbacks from parallel execution. Events are aggregated when\n * getRecord() is called.\n */\nexport class FillRecordCollector implements FillCallbacks {\n private readonly startedAt: string;\n private readonly sessionId: string;\n private readonly form: FillRecordCollectorOptions['form'];\n private readonly provider: string;\n private readonly model: string;\n private readonly parallelEnabled: boolean;\n private readonly maxParallelAgents?: number;\n private customData: Record<string, unknown>;\n\n // Append-only event log - safe for interleaved async operations\n private events: CollectorEvent[] = [];\n\n // Explicit status override\n private explicitStatus?: FillRecordStatus;\n private explicitStatusDetail?: string;\n\n // Track pending tool calls by name (for matching start/end)\n private pendingToolCalls = new Map<string, ToolStartEvent>();\n\n // Track pending LLM calls by executionId\n private pendingLlmCalls = new Map<string, LlmCallStartEvent>();\n\n constructor(options: FillRecordCollectorOptions) {\n this.startedAt = currentTime();\n this.sessionId = generateSessionId();\n this.form = options.form;\n this.provider = options.provider;\n this.model = options.model;\n this.parallelEnabled = options.parallelEnabled ?? false;\n this.maxParallelAgents = options.maxParallelAgents;\n this.customData = options.customData ?? {};\n }\n\n // ===========================================================================\n // FillCallbacks Implementation\n // ===========================================================================\n\n onTurnStart(turn: {\n turnNumber: number;\n issuesCount: number;\n order: number;\n executionId: string;\n }): void {\n this.events.push({\n type: 'turn_start',\n timestamp: currentTime(),\n turnNumber: turn.turnNumber,\n issuesCount: turn.issuesCount,\n order: turn.order,\n executionId: turn.executionId,\n });\n }\n\n onTurnComplete(progress: TurnProgress): void {\n this.events.push({\n type: 'turn_complete',\n timestamp: currentTime(),\n turnNumber: progress.turnNumber,\n patchesApplied: progress.patchesApplied,\n patchesRejected: progress.rejectedPatches?.length ?? 0,\n issuesAddressed: progress.issuesShown,\n executionId: progress.executionId,\n });\n }\n\n onLlmCallStart(call: { model: string; executionId: string }): void {\n const event: LlmCallStartEvent = {\n type: 'llm_call_start',\n timestamp: currentTime(),\n model: call.model,\n executionId: call.executionId,\n };\n this.events.push(event);\n this.pendingLlmCalls.set(call.executionId, event);\n }\n\n onLlmCallEnd(call: {\n model: string;\n inputTokens: number;\n outputTokens: number;\n executionId: string;\n }): void {\n this.events.push({\n type: 'llm_call_end',\n timestamp: currentTime(),\n model: call.model,\n inputTokens: call.inputTokens,\n outputTokens: call.outputTokens,\n executionId: call.executionId,\n });\n this.pendingLlmCalls.delete(call.executionId);\n }\n\n onToolStart(call: { name: string; input: unknown; executionId: string }): void {\n const event: ToolStartEvent = {\n type: 'tool_start',\n timestamp: currentTime(),\n name: call.name,\n input: call.input,\n executionId: call.executionId,\n };\n this.events.push(event);\n // Use composite key for parallel tool calls\n const key = `${call.executionId}:${call.name}`;\n this.pendingToolCalls.set(key, event);\n }\n\n onToolEnd(call: {\n name: string;\n output: unknown;\n durationMs: number;\n error?: string;\n executionId: string;\n }): void {\n this.events.push({\n type: 'tool_end',\n timestamp: currentTime(),\n name: call.name,\n output: call.output,\n durationMs: call.durationMs,\n error: call.error,\n executionId: call.executionId,\n });\n const key = `${call.executionId}:${call.name}`;\n this.pendingToolCalls.delete(key);\n }\n\n onWebSearch(info: {\n query: string;\n resultCount: number;\n provider: string;\n executionId: string;\n }): void {\n this.events.push({\n type: 'web_search',\n timestamp: currentTime(),\n query: info.query,\n resultCount: info.resultCount,\n provider: info.provider,\n executionId: info.executionId,\n });\n }\n\n // ===========================================================================\n // Public Methods\n // ===========================================================================\n\n /**\n * Add custom data during execution.\n */\n addCustomData(key: string, value: unknown): void {\n this.customData[key] = value;\n }\n\n /**\n * Set explicit status (overrides auto-detection from progress).\n */\n setStatus(status: FillRecordStatus, detail?: string): void {\n this.explicitStatus = status;\n this.explicitStatusDetail = detail;\n }\n\n /**\n * Assemble the complete FillRecord from collected events.\n */\n getRecord(formProgress: ProgressCounts): FillRecord {\n const completedAt = currentTime();\n const durationMs = new Date(completedAt).getTime() - new Date(this.startedAt).getTime();\n\n // Build timeline from events\n const timeline = this.buildTimeline();\n\n // Calculate LLM totals\n const llmTotals = this.calculateLlmTotals();\n\n // Calculate tool summary\n const toolSummary = this.calculateToolSummary();\n\n // Calculate timing breakdown\n const timingBreakdown = this.calculateTimingBreakdown(\n durationMs,\n llmTotals.llmTimeMs,\n toolSummary.totalDurationMs,\n );\n\n // Build execution metadata\n const execution = this.buildExecutionMetadata(timeline);\n\n // Determine status\n const status = this.determineStatus(formProgress);\n\n return {\n sessionId: this.sessionId,\n startedAt: this.startedAt,\n completedAt,\n durationMs,\n form: this.form,\n status,\n statusDetail: this.explicitStatusDetail,\n formProgress,\n llm: {\n provider: this.provider,\n model: this.model,\n totalCalls: llmTotals.totalCalls,\n inputTokens: llmTotals.inputTokens,\n outputTokens: llmTotals.outputTokens,\n },\n toolSummary,\n timingBreakdown,\n timeline,\n execution,\n customData: Object.keys(this.customData).length > 0 ? this.customData : undefined,\n };\n }\n\n // ===========================================================================\n // Private Aggregation Methods\n // ===========================================================================\n\n private buildTimeline(): TimelineEntry[] {\n // Use composite key (executionId:turnNumber) to properly track parallel turns\n const turnKey = (execId: string, turnNum: number) => `${execId}:${turnNum}`;\n\n // Fill start time for calculating relative offsets\n const fillStartMs = new Date(this.startedAt).getTime();\n\n const turns = new Map<string, TimelineEntry>();\n const turnStartEvents = new Map<string, TurnStartEvent>();\n const turnToolCalls = new Map<string, ToolCallRecord[]>();\n const turnTokens = new Map<string, { input: number; output: number }>();\n\n // First pass: collect turn start events and tool calls\n for (const event of this.events) {\n if (event.type === 'turn_start') {\n const key = turnKey(event.executionId, event.turnNumber);\n turnStartEvents.set(key, event);\n turnToolCalls.set(key, []);\n turnTokens.set(key, { input: 0, output: 0 });\n }\n }\n\n // Track active tool calls per turn (keyed by composite key)\n const activeToolsByTurn = new Map<\n string,\n Map<string, { start: ToolStartEvent; turnKey: string }>\n >();\n // Track current turn key for each executionId (for proper sequential turn tracking)\n const currentTurnKeyByExecutionId = new Map<string, string>();\n\n // Second pass: match tool start/end events and LLM tokens\n for (const event of this.events) {\n if (event.type === 'turn_start') {\n const key = turnKey(event.executionId, event.turnNumber);\n currentTurnKeyByExecutionId.set(event.executionId, key);\n activeToolsByTurn.set(key, new Map());\n } else if (event.type === 'tool_start') {\n // Use the current turn for this executionId (not the most recent globally)\n const activeTurnKey = currentTurnKeyByExecutionId.get(event.executionId);\n if (activeTurnKey) {\n const activeTools = activeToolsByTurn.get(activeTurnKey);\n if (activeTools) {\n const toolKey = `${event.executionId}:${event.name}`;\n activeTools.set(toolKey, { start: event, turnKey: activeTurnKey });\n }\n }\n } else if (event.type === 'tool_end') {\n const toolKey = `${event.executionId}:${event.name}`;\n // Find which turn this tool call belongs to\n let foundTurnKey: string | undefined;\n for (const [tk, activeTools] of activeToolsByTurn) {\n if (activeTools.has(toolKey)) {\n foundTurnKey = tk;\n break;\n }\n }\n\n if (foundTurnKey !== undefined) {\n const activeTools = activeToolsByTurn.get(foundTurnKey)!;\n const startInfo = activeTools.get(toolKey);\n if (startInfo) {\n const toolCall: ToolCallRecord = {\n tool: event.name,\n startedAt: startInfo.start.timestamp,\n completedAt: event.timestamp,\n startMs: new Date(startInfo.start.timestamp).getTime() - fillStartMs,\n durationMs: event.durationMs,\n success: !event.error,\n input: this.normalizeInput(startInfo.start.input),\n result: event.error ? { error: event.error } : this.extractResultCount(event.output),\n };\n turnToolCalls.get(foundTurnKey)?.push(toolCall);\n activeTools.delete(toolKey);\n }\n }\n } else if (event.type === 'llm_call_end') {\n // Use the current turn for this executionId\n const tk = currentTurnKeyByExecutionId.get(event.executionId);\n if (tk) {\n const tokens = turnTokens.get(tk);\n if (tokens) {\n tokens.input += event.inputTokens;\n tokens.output += event.outputTokens;\n }\n }\n }\n }\n\n // Third pass: build timeline entries from turn complete events\n // Match turn_complete events to their start events by executionId + turnNumber\n const turnCompleteByKey = new Map<string, TurnCompleteEvent>();\n for (const event of this.events) {\n if (event.type === 'turn_complete') {\n // Use executionId if available (parallel execution), otherwise fall back to matching by turnNumber\n if (event.executionId) {\n const key = turnKey(event.executionId, event.turnNumber);\n turnCompleteByKey.set(key, event);\n } else {\n // Legacy fallback: find first unmatched start event with same turnNumber\n for (const [key, startEvent] of turnStartEvents) {\n if (startEvent.turnNumber === event.turnNumber && !turnCompleteByKey.has(key)) {\n turnCompleteByKey.set(key, event);\n break;\n }\n }\n }\n }\n }\n\n for (const [key, startEvent] of turnStartEvents) {\n const completeEvent = turnCompleteByKey.get(key);\n if (completeEvent) {\n const tokens = turnTokens.get(key) ?? { input: 0, output: 0 };\n const toolCalls = turnToolCalls.get(key) ?? [];\n\n const turnStartMs = new Date(startEvent.timestamp).getTime();\n const entry: TimelineEntry = {\n turnNumber: startEvent.turnNumber,\n order: startEvent.order,\n executionId: startEvent.executionId,\n startedAt: startEvent.timestamp,\n completedAt: completeEvent.timestamp,\n startMs: turnStartMs - fillStartMs,\n durationMs: new Date(completeEvent.timestamp).getTime() - turnStartMs,\n issuesAddressed: completeEvent.issuesAddressed,\n patchesApplied: completeEvent.patchesApplied,\n patchesRejected: completeEvent.patchesRejected,\n tokens,\n toolCalls,\n };\n turns.set(key, entry);\n }\n }\n\n // Sort by startedAt timestamp (proper chronological order for parallel execution)\n return Array.from(turns.values()).sort(\n (a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime(),\n );\n }\n\n private findTurnKeyForExecutionId(\n executionId: string,\n turnStartEvents: Map<string, TurnStartEvent>,\n ): string | undefined {\n // Find the most recent turn for this executionId\n let latestKey: string | undefined;\n let latestTime = '';\n for (const [key, event] of turnStartEvents) {\n if (event.executionId === executionId && event.timestamp > latestTime) {\n latestKey = key;\n latestTime = event.timestamp;\n }\n }\n return latestKey;\n }\n\n private normalizeInput(input: unknown): Record<string, unknown> {\n if (input && typeof input === 'object' && !Array.isArray(input)) {\n return input as Record<string, unknown>;\n }\n return { value: input };\n }\n\n private extractResultCount(output: unknown): { resultCount?: number } | undefined {\n if (output && typeof output === 'object') {\n const obj = output as Record<string, unknown>;\n // Check for common patterns\n if (Array.isArray(obj.results)) {\n return { resultCount: obj.results.length };\n }\n if (typeof obj.applied === 'number') {\n return { resultCount: obj.applied };\n }\n if (typeof obj.resultCount === 'number') {\n return { resultCount: obj.resultCount };\n }\n }\n return undefined;\n }\n\n private calculateLlmTotals(): {\n totalCalls: number;\n inputTokens: number;\n outputTokens: number;\n llmTimeMs: number;\n } {\n let totalCalls = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let llmTimeMs = 0;\n\n const llmStartTimes = new Map<string, string>();\n\n for (const event of this.events) {\n if (event.type === 'llm_call_start') {\n llmStartTimes.set(event.executionId, event.timestamp);\n } else if (event.type === 'llm_call_end') {\n totalCalls++;\n inputTokens += event.inputTokens;\n outputTokens += event.outputTokens;\n\n const startTime = llmStartTimes.get(event.executionId);\n if (startTime) {\n llmTimeMs += new Date(event.timestamp).getTime() - new Date(startTime).getTime();\n llmStartTimes.delete(event.executionId);\n }\n }\n }\n\n return { totalCalls, inputTokens, outputTokens, llmTimeMs };\n }\n\n private calculateToolSummary(): ToolSummary {\n const toolCalls = new Map<\n string,\n { durations: number[]; successes: number; failures: number; resultCounts: number[] }\n >();\n\n let totalCalls = 0;\n let successfulCalls = 0;\n let failedCalls = 0;\n let totalDurationMs = 0;\n\n for (const event of this.events) {\n if (event.type === 'tool_end') {\n totalCalls++;\n totalDurationMs += event.durationMs;\n\n if (event.error) {\n failedCalls++;\n } else {\n successfulCalls++;\n }\n\n let stats = toolCalls.get(event.name);\n if (!stats) {\n stats = { durations: [], successes: 0, failures: 0, resultCounts: [] };\n toolCalls.set(event.name, stats);\n }\n\n stats.durations.push(event.durationMs);\n if (event.error) {\n stats.failures++;\n } else {\n stats.successes++;\n }\n\n // Extract result count if available\n const resultCount = this.extractResultCountFromOutput(event.output);\n if (resultCount !== undefined) {\n stats.resultCounts.push(resultCount);\n }\n }\n }\n\n const byTool: ToolStats[] = [];\n for (const [toolName, stats] of toolCalls) {\n const callCount = stats.durations.length;\n const sortedDurations = [...stats.durations].sort((a, b) => a - b);\n\n byTool.push({\n toolName,\n callCount,\n successCount: stats.successes,\n failureCount: stats.failures,\n successRate: callCount > 0 ? (stats.successes / callCount) * 100 : 0,\n results:\n stats.resultCounts.length > 0\n ? {\n totalResults: stats.resultCounts.reduce((a, b) => a + b, 0),\n avgResultsPerCall:\n stats.resultCounts.reduce((a, b) => a + b, 0) / stats.resultCounts.length,\n zeroResultCalls: stats.resultCounts.filter((c) => c === 0).length,\n }\n : undefined,\n timing: {\n totalMs: stats.durations.reduce((a, b) => a + b, 0),\n avgMs: callCount > 0 ? stats.durations.reduce((a, b) => a + b, 0) / callCount : 0,\n minMs: sortedDurations[0] ?? 0,\n maxMs: sortedDurations[sortedDurations.length - 1] ?? 0,\n p50Ms: this.percentile(sortedDurations, 50),\n p95Ms: this.percentile(sortedDurations, 95),\n },\n });\n }\n\n return {\n totalCalls,\n successfulCalls,\n failedCalls,\n successRate: totalCalls > 0 ? (successfulCalls / totalCalls) * 100 : 0,\n totalDurationMs,\n byTool,\n };\n }\n\n private extractResultCountFromOutput(output: unknown): number | undefined {\n if (output && typeof output === 'object') {\n const obj = output as Record<string, unknown>;\n if (Array.isArray(obj.results)) {\n return obj.results.length;\n }\n if (typeof obj.resultCount === 'number') {\n return obj.resultCount;\n }\n }\n return undefined;\n }\n\n private percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0;\n if (sorted.length === 1) return sorted[0]!;\n\n const index = (p / 100) * (sorted.length - 1);\n const lower = Math.floor(index);\n const upper = Math.ceil(index);\n\n if (lower === upper) {\n return Math.round(sorted[lower]!);\n }\n\n const weight = index - lower;\n return Math.round(sorted[lower]! * (1 - weight) + sorted[upper]! * weight);\n }\n\n private calculateTimingBreakdown(\n totalMs: number,\n llmTimeMs: number,\n toolTimeMs: number,\n ): TimingBreakdown {\n const overheadMs = Math.max(0, totalMs - llmTimeMs - toolTimeMs);\n\n const breakdown: TimingBreakdownItem[] = [\n {\n category: 'llm',\n label: 'LLM API calls',\n ms: llmTimeMs,\n percentage: totalMs > 0 ? (llmTimeMs / totalMs) * 100 : 0,\n },\n {\n category: 'tools',\n label: 'Tool execution',\n ms: toolTimeMs,\n percentage: totalMs > 0 ? (toolTimeMs / totalMs) * 100 : 0,\n },\n {\n category: 'overhead',\n label: 'Overhead',\n ms: overheadMs,\n percentage: totalMs > 0 ? (overheadMs / totalMs) * 100 : 0,\n },\n ];\n\n return {\n totalMs,\n llmTimeMs,\n toolTimeMs,\n overheadMs,\n breakdown,\n };\n }\n\n private buildExecutionMetadata(timeline: TimelineEntry[]): ExecutionMetadata {\n const orderLevels = new Set<number>();\n const executionThreads = new Set<string>();\n\n for (const entry of timeline) {\n orderLevels.add(entry.order);\n executionThreads.add(entry.executionId);\n }\n\n return {\n totalTurns: timeline.length,\n parallelEnabled: this.parallelEnabled,\n maxParallelAgents: this.parallelEnabled ? this.maxParallelAgents : undefined,\n orderLevels: Array.from(orderLevels).sort((a, b) => a - b),\n executionThreads: Array.from(executionThreads),\n };\n }\n\n private determineStatus(formProgress: ProgressCounts): FillRecordStatus {\n // Explicit status takes precedence\n if (this.explicitStatus) {\n return this.explicitStatus;\n }\n\n // Determine from form progress\n const hasUnanswered = formProgress.unansweredFields > 0;\n const allRequiredFilled = formProgress.answeredFields >= formProgress.requiredFields;\n\n if (!hasUnanswered) {\n return 'completed';\n }\n\n if (allRequiredFilled) {\n return 'completed';\n }\n\n return 'partial';\n }\n}\n","// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\n }\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n 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)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\n if (typeof callbacks == \"function\")\n throw new TypeError(\n \"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;\n let incompleteLine = \"\", isFirstChunk = !0, id, data = \"\", eventType = \"\";\n function feed(newChunk) {\n const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, \"\") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);\n for (const line of complete)\n parseLine(line);\n incompleteLine = incomplete, isFirstChunk = !1;\n }\n function parseLine(line) {\n if (line === \"\") {\n dispatchEvent();\n return;\n }\n if (line.startsWith(\":\")) {\n onComment && onComment(line.slice(line.startsWith(\": \") ? 2 : 1));\n return;\n }\n const fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex !== -1) {\n const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === \" \" ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n return;\n }\n processField(line, \"\", line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value;\n break;\n case \"data\":\n data = `${data}${value}\n`;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n data.length > 0 && onEvent({\n id,\n event: eventType || void 0,\n // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n // then remove the last character from the data buffer.\n data: data.endsWith(`\n`) ? data.slice(0, -1) : data\n }), id = void 0, data = \"\", eventType = \"\";\n }\n function reset(options = {}) {\n incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = \"\", eventType = \"\", incompleteLine = \"\";\n }\n return { feed, reset };\n}\nfunction splitLines(chunk) {\n const lines = [];\n let incompleteLine = \"\", searchIndex = 0;\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {\n incompleteLine = chunk.slice(searchIndex);\n break;\n } else {\n const line = chunk.slice(searchIndex, lineEnd);\n lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === \"\\r\" && chunk[searchIndex] === `\n` && searchIndex++;\n }\n }\n return [lines, incompleteLine];\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n },\n onRetry,\n onComment\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","// src/combine-headers.ts\nfunction combineHeaders(...headers) {\n return headers.reduce(\n (combinedHeaders, currentHeaders) => ({\n ...combinedHeaders,\n ...currentHeaders != null ? currentHeaders : {}\n }),\n {}\n );\n}\n\n// src/convert-async-iterator-to-readable-stream.ts\nfunction convertAsyncIteratorToReadableStream(iterator) {\n let cancelled = false;\n return new ReadableStream({\n /**\n * Called when the consumer wants to pull more data from the stream.\n *\n * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n * @returns {Promise<void>}\n */\n async pull(controller) {\n if (cancelled) return;\n try {\n const { value, done } = await iterator.next();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n },\n /**\n * Called when the consumer cancels the stream.\n */\n async cancel(reason) {\n cancelled = true;\n if (iterator.return) {\n try {\n await iterator.return(reason);\n } catch (e) {\n }\n }\n }\n });\n}\n\n// src/create-tool-name-mapping.ts\nfunction createToolNameMapping({\n tools = [],\n providerToolNames\n}) {\n const customToolNameToProviderToolName = {};\n const providerToolNameToCustomToolName = {};\n for (const tool2 of tools) {\n if (tool2.type === \"provider\" && tool2.id in providerToolNames) {\n const providerToolName = providerToolNames[tool2.id];\n customToolNameToProviderToolName[tool2.name] = providerToolName;\n providerToolNameToCustomToolName[providerToolName] = tool2.name;\n }\n }\n return {\n toProviderToolName: (customToolName) => {\n var _a2;\n return (_a2 = customToolNameToProviderToolName[customToolName]) != null ? _a2 : customToolName;\n },\n toCustomToolName: (providerToolName) => {\n var _a2;\n return (_a2 = providerToolNameToCustomToolName[providerToolName]) != null ? _a2 : providerToolName;\n }\n };\n}\n\n// src/delay.ts\nasync function delay(delayInMs, options) {\n if (delayInMs == null) {\n return Promise.resolve();\n }\n const signal = options == null ? void 0 : options.abortSignal;\n return new Promise((resolve2, reject) => {\n if (signal == null ? void 0 : signal.aborted) {\n reject(createAbortError());\n return;\n }\n const timeoutId = setTimeout(() => {\n cleanup();\n resolve2();\n }, delayInMs);\n const cleanup = () => {\n clearTimeout(timeoutId);\n signal == null ? void 0 : signal.removeEventListener(\"abort\", onAbort);\n };\n const onAbort = () => {\n cleanup();\n reject(createAbortError());\n };\n signal == null ? void 0 : signal.addEventListener(\"abort\", onAbort);\n });\n}\nfunction createAbortError() {\n return new DOMException(\"Delay was aborted\", \"AbortError\");\n}\n\n// src/delayed-promise.ts\nvar DelayedPromise = class {\n constructor() {\n this.status = { type: \"pending\" };\n this._resolve = void 0;\n this._reject = void 0;\n }\n get promise() {\n if (this._promise) {\n return this._promise;\n }\n this._promise = new Promise((resolve2, reject) => {\n if (this.status.type === \"resolved\") {\n resolve2(this.status.value);\n } else if (this.status.type === \"rejected\") {\n reject(this.status.error);\n }\n this._resolve = resolve2;\n this._reject = reject;\n });\n return this._promise;\n }\n resolve(value) {\n var _a2;\n this.status = { type: \"resolved\", value };\n if (this._promise) {\n (_a2 = this._resolve) == null ? void 0 : _a2.call(this, value);\n }\n }\n reject(error) {\n var _a2;\n this.status = { type: \"rejected\", error };\n if (this._promise) {\n (_a2 = this._reject) == null ? void 0 : _a2.call(this, error);\n }\n }\n isResolved() {\n return this.status.type === \"resolved\";\n }\n isRejected() {\n return this.status.type === \"rejected\";\n }\n isPending() {\n return this.status.type === \"pending\";\n }\n};\n\n// src/extract-response-headers.ts\nfunction extractResponseHeaders(response) {\n return Object.fromEntries([...response.headers]);\n}\n\n// src/uint8-utils.ts\nvar { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n const base64Url = base64String.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const latin1string = atob(base64Url);\n return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n let latin1string = \"\";\n for (let i = 0; i < array.length; i++) {\n latin1string += String.fromCodePoint(array[i]);\n }\n return btoa(latin1string);\n}\nfunction convertToBase64(value) {\n return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n\n// src/convert-image-model-file-to-data-uri.ts\nfunction convertImageModelFileToDataUri(file) {\n if (file.type === \"url\") return file.url;\n return `data:${file.mediaType};base64,${typeof file.data === \"string\" ? file.data : convertUint8ArrayToBase64(file.data)}`;\n}\n\n// src/convert-to-form-data.ts\nfunction convertToFormData(input, options = {}) {\n const { useArrayBrackets = true } = options;\n const formData = new FormData();\n for (const [key, value] of Object.entries(input)) {\n if (value == null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 1) {\n formData.append(key, value[0]);\n continue;\n }\n const arrayKey = useArrayBrackets ? `${key}[]` : key;\n for (const item of value) {\n formData.append(arrayKey, item);\n }\n continue;\n }\n formData.append(key, value);\n }\n return formData;\n}\n\n// src/download-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_DownloadError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {\n constructor({\n url,\n statusCode,\n statusText,\n cause,\n message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`\n }) {\n super({ name, message, cause });\n this[_a] = true;\n this.url = url;\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker);\n }\n};\n\n// src/download-blob.ts\nasync function downloadBlob(url) {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n throw new DownloadError({\n url,\n statusCode: response.status,\n statusText: response.statusText\n });\n }\n return await response.blob();\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n throw new DownloadError({ url, cause: error });\n }\n}\n\n// src/generate-id.ts\nimport { InvalidArgumentError } from \"@ai-sdk/provider\";\nvar createIdGenerator = ({\n prefix,\n size = 16,\n alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n separator = \"-\"\n} = {}) => {\n const generator = () => {\n const alphabetLength = alphabet.length;\n const chars = new Array(size);\n for (let i = 0; i < size; i++) {\n chars[i] = alphabet[Math.random() * alphabetLength | 0];\n }\n return chars.join(\"\");\n };\n if (prefix == null) {\n return generator;\n }\n if (alphabet.includes(separator)) {\n throw new InvalidArgumentError({\n argument: \"separator\",\n message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n });\n }\n return () => `${prefix}${separator}${generator()}`;\n};\nvar generateId = createIdGenerator();\n\n// src/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/get-from-api.ts\nimport { APICallError as APICallError2 } from \"@ai-sdk/provider\";\n\n// src/handle-fetch-error.ts\nimport { APICallError } from \"@ai-sdk/provider\";\n\n// src/is-abort-error.ts\nfunction isAbortError(error) {\n return (error instanceof Error || error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || // Next.js\n error.name === \"TimeoutError\");\n}\n\n// src/handle-fetch-error.ts\nvar FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nvar BUN_ERROR_CODES = [\n \"ConnectionRefused\",\n \"ConnectionClosed\",\n \"FailedToOpenSocket\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ETIMEDOUT\",\n \"EPIPE\"\n];\nfunction isBunNetworkError(error) {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = error.code;\n if (typeof code === \"string\" && BUN_ERROR_CODES.includes(code)) {\n return true;\n }\n return false;\n}\nfunction handleFetchError({\n error,\n url,\n requestBodyValues\n}) {\n if (isAbortError(error)) {\n return error;\n }\n if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n const cause = error.cause;\n if (cause != null) {\n return new APICallError({\n message: `Cannot connect to API: ${cause.message}`,\n cause,\n url,\n requestBodyValues,\n isRetryable: true\n // retry when network error\n });\n }\n }\n if (isBunNetworkError(error)) {\n return new APICallError({\n message: `Cannot connect to API: ${error.message}`,\n cause: error,\n url,\n requestBodyValues,\n isRetryable: true\n });\n }\n return error;\n}\n\n// src/get-runtime-environment-user-agent.ts\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n var _a2, _b2, _c;\n if (globalThisAny.window) {\n return `runtime/browser`;\n }\n if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) {\n return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n }\n if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) {\n return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n }\n if (globalThisAny.EdgeRuntime) {\n return `runtime/vercel-edge`;\n }\n return \"runtime/unknown\";\n}\n\n// src/normalize-headers.ts\nfunction normalizeHeaders(headers) {\n if (headers == null) {\n return {};\n }\n const normalized = {};\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n normalized[key.toLowerCase()] = value;\n });\n } else {\n if (!Array.isArray(headers)) {\n headers = Object.entries(headers);\n }\n for (const [key, value] of headers) {\n if (value != null) {\n normalized[key.toLowerCase()] = value;\n }\n }\n }\n return normalized;\n}\n\n// src/with-user-agent-suffix.ts\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n const normalizedHeaders = new Headers(normalizeHeaders(headers));\n const currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n normalizedHeaders.set(\n \"user-agent\",\n [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \")\n );\n return Object.fromEntries(normalizedHeaders.entries());\n}\n\n// src/version.ts\nvar VERSION = true ? \"4.0.12\" : \"0.0.0-test\";\n\n// src/get-from-api.ts\nvar getOriginalFetch = () => globalThis.fetch;\nvar getFromApi = async ({\n url,\n headers = {},\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch: fetch2 = getOriginalFetch()\n}) => {\n try {\n const response = await fetch2(url, {\n method: \"GET\",\n headers: withUserAgentSuffix(\n headers,\n `ai-sdk/provider-utils/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n signal: abortSignal\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!response.ok) {\n let errorInformation;\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: {}\n });\n } catch (error) {\n if (isAbortError(error) || APICallError2.isInstance(error)) {\n throw error;\n }\n throw new APICallError2({\n message: \"Failed to process error response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {}\n });\n }\n throw errorInformation.value;\n }\n try {\n return await successfulResponseHandler({\n response,\n url,\n requestBodyValues: {}\n });\n } catch (error) {\n if (error instanceof Error) {\n if (isAbortError(error) || APICallError2.isInstance(error)) {\n throw error;\n }\n }\n throw new APICallError2({\n message: \"Failed to process successful response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {}\n });\n }\n } catch (error) {\n throw handleFetchError({ error, url, requestBodyValues: {} });\n }\n};\n\n// src/inject-json-instruction.ts\nvar DEFAULT_SCHEMA_PREFIX = \"JSON schema:\";\nvar DEFAULT_SCHEMA_SUFFIX = \"You MUST answer with a JSON object that matches the JSON schema above.\";\nvar DEFAULT_GENERIC_SUFFIX = \"You MUST answer with JSON.\";\nfunction injectJsonInstruction({\n prompt,\n schema,\n schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,\n schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX\n}) {\n return [\n prompt != null && prompt.length > 0 ? prompt : void 0,\n prompt != null && prompt.length > 0 ? \"\" : void 0,\n // add a newline if prompt is not null\n schemaPrefix,\n schema != null ? JSON.stringify(schema) : void 0,\n schemaSuffix\n ].filter((line) => line != null).join(\"\\n\");\n}\nfunction injectJsonInstructionIntoMessages({\n messages,\n schema,\n schemaPrefix,\n schemaSuffix\n}) {\n var _a2, _b2;\n const systemMessage = ((_a2 = messages[0]) == null ? void 0 : _a2.role) === \"system\" ? { ...messages[0] } : { role: \"system\", content: \"\" };\n systemMessage.content = injectJsonInstruction({\n prompt: systemMessage.content,\n schema,\n schemaPrefix,\n schemaSuffix\n });\n return [\n systemMessage,\n ...((_b2 = messages[0]) == null ? void 0 : _b2.role) === \"system\" ? messages.slice(1) : messages\n ];\n}\n\n// src/is-non-nullable.ts\nfunction isNonNullable(value) {\n return value != null;\n}\n\n// src/is-url-supported.ts\nfunction isUrlSupported({\n mediaType,\n url,\n supportedUrls\n}) {\n url = url.toLowerCase();\n mediaType = mediaType.toLowerCase();\n return Object.entries(supportedUrls).map(([key, value]) => {\n const mediaType2 = key.toLowerCase();\n return mediaType2 === \"*\" || mediaType2 === \"*/*\" ? { mediaTypePrefix: \"\", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\\*/, \"\"), regexes: value };\n }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));\n}\n\n// src/load-api-key.ts\nimport { LoadAPIKeyError } from \"@ai-sdk/provider\";\nfunction loadApiKey({\n apiKey,\n environmentVariableName,\n apiKeyParameterName = \"apiKey\",\n description\n}) {\n if (typeof apiKey === \"string\") {\n return apiKey;\n }\n if (apiKey != null) {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string.`\n });\n }\n if (typeof process === \"undefined\") {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`\n });\n }\n apiKey = process.env[environmentVariableName];\n if (apiKey == null) {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`\n });\n }\n if (typeof apiKey !== \"string\") {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n });\n }\n return apiKey;\n}\n\n// src/load-optional-setting.ts\nfunction loadOptionalSetting({\n settingValue,\n environmentVariableName\n}) {\n if (typeof settingValue === \"string\") {\n return settingValue;\n }\n if (settingValue != null || typeof process === \"undefined\") {\n return void 0;\n }\n settingValue = process.env[environmentVariableName];\n if (settingValue == null || typeof settingValue !== \"string\") {\n return void 0;\n }\n return settingValue;\n}\n\n// src/load-setting.ts\nimport { LoadSettingError } from \"@ai-sdk/provider\";\nfunction loadSetting({\n settingValue,\n environmentVariableName,\n settingName,\n description\n}) {\n if (typeof settingValue === \"string\") {\n return settingValue;\n }\n if (settingValue != null) {\n throw new LoadSettingError({\n message: `${description} setting must be a string.`\n });\n }\n if (typeof process === \"undefined\") {\n throw new LoadSettingError({\n message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`\n });\n }\n settingValue = process.env[environmentVariableName];\n if (settingValue == null) {\n throw new LoadSettingError({\n message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`\n });\n }\n if (typeof settingValue !== \"string\") {\n throw new LoadSettingError({\n message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n });\n }\n return settingValue;\n}\n\n// src/media-type-to-extension.ts\nfunction mediaTypeToExtension(mediaType) {\n var _a2;\n const [_type, subtype = \"\"] = mediaType.toLowerCase().split(\"/\");\n return (_a2 = {\n mpeg: \"mp3\",\n \"x-wav\": \"wav\",\n opus: \"ogg\",\n mp4: \"m4a\",\n \"x-m4a\": \"m4a\"\n }[subtype]) != null ? _a2 : subtype;\n}\n\n// src/parse-json.ts\nimport {\n JSONParseError,\n TypeValidationError as TypeValidationError3\n} from \"@ai-sdk/provider\";\n\n// src/secure-json-parse.ts\nvar suspectProtoRx = /\"__proto__\"\\s*:/;\nvar suspectConstructorRx = /\"constructor\"\\s*:/;\nfunction _parse(text) {\n const obj = JSON.parse(text);\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {\n return obj;\n }\n return filter(obj);\n}\nfunction filter(obj) {\n let next = [obj];\n while (next.length) {\n const nodes = next;\n next = [];\n for (const node of nodes) {\n if (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n if (Object.prototype.hasOwnProperty.call(node, \"constructor\") && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === \"object\") {\n next.push(value);\n }\n }\n }\n }\n return obj;\n}\nfunction secureJsonParse(text) {\n const { stackTraceLimit } = Error;\n try {\n Error.stackTraceLimit = 0;\n } catch (e) {\n return _parse(text);\n }\n try {\n return _parse(text);\n } finally {\n Error.stackTraceLimit = stackTraceLimit;\n }\n}\n\n// src/validate-types.ts\nimport { TypeValidationError as TypeValidationError2 } from \"@ai-sdk/provider\";\n\n// src/schema.ts\nimport { TypeValidationError } from \"@ai-sdk/provider\";\nimport * as z4 from \"zod/v4\";\n\n// src/add-additional-properties-to-json-schema.ts\nfunction addAdditionalPropertiesToJsonSchema(jsonSchema2) {\n if (jsonSchema2.type === \"object\" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes(\"object\")) {\n jsonSchema2.additionalProperties = false;\n const { properties } = jsonSchema2;\n if (properties != null) {\n for (const key of Object.keys(properties)) {\n properties[key] = visit(properties[key]);\n }\n }\n }\n if (jsonSchema2.items != null) {\n jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);\n }\n if (jsonSchema2.anyOf != null) {\n jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);\n }\n if (jsonSchema2.allOf != null) {\n jsonSchema2.allOf = jsonSchema2.allOf.map(visit);\n }\n if (jsonSchema2.oneOf != null) {\n jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);\n }\n const { definitions } = jsonSchema2;\n if (definitions != null) {\n for (const key of Object.keys(definitions)) {\n definitions[key] = visit(definitions[key]);\n }\n }\n return jsonSchema2;\n}\nfunction visit(def) {\n if (typeof def === \"boolean\") return def;\n return addAdditionalPropertiesToJsonSchema(def);\n}\n\n// src/to-json-schema/zod3-to-json-schema/options.ts\nvar ignoreOverride = Symbol(\n \"Let zodToJsonSchema decide on which parser to use\"\n);\nvar defaultOptions = {\n name: void 0,\n $refStrategy: \"root\",\n basePath: [\"#\"],\n effectStrategy: \"input\",\n pipeStrategy: \"all\",\n dateStrategy: \"format:date-time\",\n mapStrategy: \"entries\",\n removeAdditionalStrategy: \"passthrough\",\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: \"definitions\",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n patternStrategy: \"escape\",\n applyRegexFlags: false,\n emailStrategy: \"format:email\",\n base64Strategy: \"contentEncoding:base64\",\n nameStrategy: \"ref\"\n};\nvar getDefaultOptions = (options) => typeof options === \"string\" ? {\n ...defaultOptions,\n name: options\n} : {\n ...defaultOptions,\n ...options\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nimport { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/any.ts\nfunction parseAnyDef() {\n return {};\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/array.ts\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\nfunction parseArrayDef(def, refs) {\n var _a2, _b2, _c;\n const res = {\n type: \"array\"\n };\n 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) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"]\n });\n }\n if (def.minLength) {\n res.minItems = def.minLength.value;\n }\n if (def.maxLength) {\n res.maxItems = def.maxLength.value;\n }\n if (def.exactLength) {\n res.minItems = def.exactLength.value;\n res.maxItems = def.exactLength.value;\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts\nfunction parseBigintDef(def) {\n const res = {\n type: \"integer\",\n format: \"int64\"\n };\n if (!def.checks) return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case \"max\":\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n break;\n case \"multipleOf\":\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts\nfunction parseBooleanDef() {\n return { type: \"boolean\" };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/branded.ts\nfunction parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/catch.ts\nvar parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/date.ts\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))\n };\n }\n switch (strategy) {\n case \"string\":\n case \"format:date-time\":\n return {\n type: \"string\",\n format: \"date-time\"\n };\n case \"format:date\":\n return {\n type: \"string\",\n format: \"date\"\n };\n case \"integer\":\n return integerDateParser(def);\n }\n}\nvar integerDateParser = (def) => {\n const res = {\n type: \"integer\",\n format: \"unix-time\"\n };\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n res.minimum = check.value;\n break;\n case \"max\":\n res.maximum = check.value;\n break;\n }\n }\n return res;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/default.ts\nfunction parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue()\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/effects.ts\nfunction parseEffectsDef(_def, refs) {\n return refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/enum.ts\nfunction parseEnumDef(def) {\n return {\n type: \"string\",\n enum: Array.from(def.values)\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts\nvar isJsonSchema7AllOfType = (type) => {\n if (\"type\" in type && type.type === \"string\") return false;\n return \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"1\"]\n })\n ].filter((x) => !!x);\n const mergedAllOf = [];\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n } else {\n let nestedSchema = schema;\n if (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/literal.ts\nfunction parseLiteralDef(def) {\n const parsedType = typeof def.value;\n if (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") {\n return {\n type: Array.isArray(def.value) ? \"array\" : \"object\"\n };\n }\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n const: def.value\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nimport {\n ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2\n} from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/string.ts\nvar emojiRegex = void 0;\nvar zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === void 0) {\n emojiRegex = RegExp(\n \"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\",\n \"u\"\n );\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n const res = {\n type: \"string\"\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n break;\n case \"max\":\n res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(\n res,\n RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n check.message,\n refs\n );\n break;\n case \"endsWith\":\n addPattern(\n res,\n RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n check.message,\n refs\n );\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n break;\n case \"includes\": {\n addPattern(\n res,\n RegExp(escapeLiteralCheckValue(check.value, refs)),\n check.message,\n refs\n );\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n res.contentEncoding = \"base64\";\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n /* @__PURE__ */ ((_) => {\n })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nvar ALPHA_NUMERIC = new Set(\n \"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\"\n);\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\nfunction addFormat(schema, value, message, refs) {\n var _a2;\n if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format\n });\n delete schema.format;\n }\n schema.anyOf.push({\n format: value,\n ...message && refs.errorMessages && { errorMessage: { format: message } }\n });\n } else {\n schema.format = value;\n }\n}\nfunction addPattern(schema, regex, message, refs) {\n var _a2;\n if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern\n });\n delete schema.pattern;\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...message && refs.errorMessages && { errorMessage: { pattern: message } }\n });\n } else {\n schema.pattern = stringifyRegExpWithFlags(regex, refs);\n }\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n var _a2;\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n const flags = {\n i: regex.flags.includes(\"i\"),\n // Case-insensitive\n m: regex.flags.includes(\"m\"),\n // `^` and `$` matches adjacent to newline characters\n s: regex.flags.includes(\"s\")\n // `.` matches newlines\n };\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n } else if (source[i + 1] === \"-\" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {\n pattern += source[i];\n inCharRange = true;\n } else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n } else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\n]))`;\n continue;\n } else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\n` : `[${source[i]}\\r\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n } else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n } else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n } catch (e) {\n console.warn(\n `Could not convert regex pattern at ${refs.currentPath.join(\n \"/\"\n )} to a flag-independent form! Falling back to the flag-ignorant source`\n );\n return regex.source;\n }\n return pattern;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nfunction parseRecordDef(def, refs) {\n var _a2, _b2, _c, _d, _e, _f;\n const schema = {\n type: \"object\",\n additionalProperties: (_a2 = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"]\n })) != null ? _a2 : refs.allowedAdditionalProperties\n };\n if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType\n };\n } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values\n }\n };\n } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {\n const { type, ...keyType } = parseBrandedDef(\n def.keyType._def,\n refs\n );\n return {\n ...schema,\n propertyNames: keyType\n };\n }\n return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/map.ts\nfunction parseMapDef(def, refs) {\n if (refs.mapStrategy === \"record\") {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"]\n }) || parseAnyDef();\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"]\n }) || parseAnyDef();\n return {\n type: \"array\",\n maxItems: 125,\n items: {\n type: \"array\",\n items: [keys, values],\n minItems: 2,\n maxItems: 2\n }\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts\nfunction parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== \"number\";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(\n new Set(actualValues.map((values) => typeof values))\n );\n return {\n type: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n enum: actualValues\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/never.ts\nfunction parseNeverDef() {\n return { not: parseAnyDef() };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/null.ts\nfunction parseNullDef() {\n return {\n type: \"null\"\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/union.ts\nvar primitiveMappings = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"integer\",\n ZodBoolean: \"boolean\",\n ZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n if (options.every(\n (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)\n )) {\n const types = options.reduce((types2, x) => {\n const type = primitiveMappings[x._def.typeName];\n return type && !types2.includes(type) ? [...types2, type] : types2;\n }, []);\n return {\n type: types.length > 1 ? types : types[0]\n };\n } else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n const types = options.reduce(\n (acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return [...acc, type];\n case \"bigint\":\n return [...acc, \"integer\"];\n case \"object\":\n if (x._def.value === null) return [...acc, \"null\"];\n case \"symbol\":\n case \"undefined\":\n case \"function\":\n default:\n return acc;\n }\n },\n []\n );\n if (types.length === options.length) {\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce(\n (acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n },\n []\n )\n };\n }\n } else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n return {\n type: \"string\",\n enum: options.reduce(\n (acc, x) => [\n ...acc,\n ...x._def.values.filter((x2) => !acc.includes(x2))\n ],\n []\n )\n };\n }\n return asAnyOf(def, refs);\n}\nvar asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", `${i}`]\n })\n ).filter(\n (x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0)\n );\n return anyOf.length ? { anyOf } : void 0;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts\nfunction parseNullableDef(def, refs) {\n if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(\n def.innerType._def.typeName\n ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n return {\n type: [\n primitiveMappings[def.innerType._def.typeName],\n \"null\"\n ]\n };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"0\"]\n });\n return base && { anyOf: [base, { type: \"null\" }] };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/number.ts\nfunction parseNumberDef(def) {\n const res = {\n type: \"number\"\n };\n if (!def.checks) return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"int\":\n res.type = \"integer\";\n break;\n case \"min\":\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case \"max\":\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n break;\n case \"multipleOf\":\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/object.ts\nfunction parseObjectDef(def, refs) {\n const result = {\n type: \"object\",\n properties: {}\n };\n const required = [];\n const shape = def.shape();\n for (const propName in shape) {\n let propDef = shape[propName];\n if (propDef === void 0 || propDef._def === void 0) {\n continue;\n }\n const propOptional = safeIsOptional(propDef);\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", propName],\n propertyPath: [...refs.currentPath, \"properties\", propName]\n });\n if (parsedDef === void 0) {\n continue;\n }\n result.properties[propName] = parsedDef;\n if (!propOptional) {\n required.push(propName);\n }\n }\n if (required.length) {\n result.required = required;\n }\n const additionalProperties = decideAdditionalProperties(def, refs);\n if (additionalProperties !== void 0) {\n result.additionalProperties = additionalProperties;\n }\n return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n if (def.catchall._def.typeName !== \"ZodNever\") {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"]\n });\n }\n switch (def.unknownKeys) {\n case \"passthrough\":\n return refs.allowedAdditionalProperties;\n case \"strict\":\n return refs.rejectedAdditionalProperties;\n case \"strip\":\n return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n }\n}\nfunction safeIsOptional(schema) {\n try {\n return schema.isOptional();\n } catch (e) {\n return true;\n }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/optional.ts\nvar parseOptionalDef = (def, refs) => {\n var _a2;\n if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"1\"]\n });\n return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts\nvar parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === \"input\") {\n return parseDef(def.in._def, refs);\n } else if (refs.pipeStrategy === \"output\") {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", a ? \"1\" : \"0\"]\n });\n return {\n allOf: [a, b].filter((x) => x !== void 0)\n };\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/promise.ts\nfunction parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/set.ts\nfunction parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"]\n });\n const schema = {\n type: \"array\",\n uniqueItems: true,\n items\n };\n if (def.minSize) {\n schema.minItems = def.minSize.value;\n }\n if (def.maxSize) {\n schema.maxItems = def.maxSize.value;\n }\n return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts\nfunction parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: \"array\",\n minItems: def.items.length,\n items: def.items.map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`]\n })\n ).reduce(\n (acc, x) => x === void 0 ? acc : [...acc, x],\n []\n ),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalItems\"]\n })\n };\n } else {\n return {\n type: \"array\",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items.map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`]\n })\n ).reduce(\n (acc, x) => x === void 0 ? acc : [...acc, x],\n []\n )\n };\n }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts\nfunction parseUndefinedDef() {\n return {\n not: parseAnyDef()\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts\nfunction parseUnknownDef() {\n return parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts\nvar parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nvar selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind3.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodNumber:\n return parseNumberDef(def);\n case ZodFirstPartyTypeKind3.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodBigInt:\n return parseBigintDef(def);\n case ZodFirstPartyTypeKind3.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind3.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodUndefined:\n return parseUndefinedDef();\n case ZodFirstPartyTypeKind3.ZodNull:\n return parseNullDef();\n case ZodFirstPartyTypeKind3.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodUnion:\n case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodLiteral:\n return parseLiteralDef(def);\n case ZodFirstPartyTypeKind3.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind3.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind3.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodLazy:\n return () => def.getter()._def;\n case ZodFirstPartyTypeKind3.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodNaN:\n case ZodFirstPartyTypeKind3.ZodNever:\n return parseNeverDef();\n case ZodFirstPartyTypeKind3.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodAny:\n return parseAnyDef();\n case ZodFirstPartyTypeKind3.ZodUnknown:\n return parseUnknownDef();\n case ZodFirstPartyTypeKind3.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodFunction:\n case ZodFirstPartyTypeKind3.ZodVoid:\n case ZodFirstPartyTypeKind3.ZodSymbol:\n return void 0;\n default:\n return /* @__PURE__ */ ((_) => void 0)(typeName);\n }\n};\n\n// src/to-json-schema/zod3-to-json-schema/get-relative-path.ts\nvar getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i]) break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n\n// src/to-json-schema/zod3-to-json-schema/parse-def.ts\nfunction parseDef(def, refs, forceResolution = false) {\n var _a2;\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(\n refs,\n def,\n refs,\n seenItem,\n forceResolution\n );\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== void 0) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };\n refs.seen.set(def, newItem);\n const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n const jsonSchema2 = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n if (jsonSchema2) {\n addMeta(def, refs, jsonSchema2);\n }\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema2, def, refs);\n newItem.jsonSchema = jsonSchema2;\n return postProcessResult;\n }\n newItem.jsonSchema = jsonSchema2;\n return jsonSchema2;\n}\nvar get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case \"root\":\n return { $ref: item.path.join(\"/\") };\n case \"relative\":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case \"none\":\n case \"seen\": {\n if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(\n `Recursive reference detected at ${refs.currentPath.join(\n \"/\"\n )}! Defaulting to any`\n );\n return parseAnyDef();\n }\n return refs.$refStrategy === \"seen\" ? parseAnyDef() : void 0;\n }\n }\n};\nvar addMeta = (def, refs, jsonSchema2) => {\n if (def.description) {\n jsonSchema2.description = def.description;\n }\n return jsonSchema2;\n};\n\n// src/to-json-schema/zod3-to-json-schema/refs.ts\nvar getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;\n return {\n ..._options,\n currentPath,\n propertyPath: void 0,\n seen: new Map(\n Object.entries(_options.definitions).map(([name2, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name2],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: void 0\n }\n ])\n )\n };\n};\n\n// src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts\nvar zod3ToJsonSchema = (schema, options) => {\n var _a2;\n const refs = getRefs(options);\n let definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce(\n (acc, [name3, schema2]) => {\n var _a3;\n return {\n ...acc,\n [name3]: (_a3 = parseDef(\n schema2._def,\n {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name3]\n },\n true\n )) != null ? _a3 : parseAnyDef()\n };\n },\n {}\n ) : void 0;\n const name2 = typeof options === \"string\" ? options : (options == null ? void 0 : options.nameStrategy) === \"title\" ? void 0 : options == null ? void 0 : options.name;\n const main = (_a2 = parseDef(\n schema._def,\n name2 === void 0 ? refs : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name2]\n },\n false\n )) != null ? _a2 : parseAnyDef();\n const title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n if (title !== void 0) {\n main.title = title;\n }\n const combined = name2 === void 0 ? definitions ? {\n ...main,\n [refs.definitionPath]: definitions\n } : main : {\n $ref: [\n ...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n refs.definitionPath,\n name2\n ].join(\"/\"),\n [refs.definitionPath]: {\n ...definitions,\n [name2]: main\n }\n };\n combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n return combined;\n};\n\n// src/schema.ts\nvar schemaSymbol = Symbol.for(\"vercel.ai.schema\");\nfunction lazySchema(createSchema) {\n let schema;\n return () => {\n if (schema == null) {\n schema = createSchema();\n }\n return schema;\n };\n}\nfunction jsonSchema(jsonSchema2, {\n validate\n} = {}) {\n return {\n [schemaSymbol]: true,\n _type: void 0,\n // should never be used directly\n get jsonSchema() {\n if (typeof jsonSchema2 === \"function\") {\n jsonSchema2 = jsonSchema2();\n }\n return jsonSchema2;\n },\n validate\n };\n}\nfunction isSchema(value) {\n return typeof value === \"object\" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && \"jsonSchema\" in value && \"validate\" in value;\n}\nfunction asSchema(schema) {\n return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : \"~standard\" in schema ? schema[\"~standard\"].vendor === \"zod\" ? zodSchema(schema) : standardSchema(schema) : schema();\n}\nfunction standardSchema(standardSchema2) {\n return jsonSchema(\n () => addAdditionalPropertiesToJsonSchema(\n standardSchema2[\"~standard\"].jsonSchema.input({\n target: \"draft-07\"\n })\n ),\n {\n validate: async (value) => {\n const result = await standardSchema2[\"~standard\"].validate(value);\n return \"value\" in result ? { success: true, value: result.value } : {\n success: false,\n error: new TypeValidationError({\n value,\n cause: result.issues\n })\n };\n }\n }\n );\n}\nfunction zod3Schema(zodSchema2, options) {\n var _a2;\n const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () => zod3ToJsonSchema(zodSchema2, {\n $refStrategy: useReferences ? \"root\" : \"none\"\n }),\n {\n validate: async (value) => {\n const result = await zodSchema2.safeParseAsync(value);\n return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n }\n }\n );\n}\nfunction zod4Schema(zodSchema2, options) {\n var _a2;\n const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () => addAdditionalPropertiesToJsonSchema(\n z4.toJSONSchema(zodSchema2, {\n target: \"draft-7\",\n io: \"input\",\n reused: useReferences ? \"ref\" : \"inline\"\n })\n ),\n {\n validate: async (value) => {\n const result = await z4.safeParseAsync(zodSchema2, value);\n return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n }\n }\n );\n}\nfunction isZod4Schema(zodSchema2) {\n return \"_zod\" in zodSchema2;\n}\nfunction zodSchema(zodSchema2, options) {\n if (isZod4Schema(zodSchema2)) {\n return zod4Schema(zodSchema2, options);\n } else {\n return zod3Schema(zodSchema2, options);\n }\n}\n\n// src/validate-types.ts\nasync function validateTypes({\n value,\n schema,\n context\n}) {\n const result = await safeValidateTypes({ value, schema, context });\n if (!result.success) {\n throw TypeValidationError2.wrap({ value, cause: result.error, context });\n }\n return result.value;\n}\nasync function safeValidateTypes({\n value,\n schema,\n context\n}) {\n const actualSchema = asSchema(schema);\n try {\n if (actualSchema.validate == null) {\n return { success: true, value, rawValue: value };\n }\n const result = await actualSchema.validate(value);\n if (result.success) {\n return { success: true, value: result.value, rawValue: value };\n }\n return {\n success: false,\n error: TypeValidationError2.wrap({ value, cause: result.error, context }),\n rawValue: value\n };\n } catch (error) {\n return {\n success: false,\n error: TypeValidationError2.wrap({ value, cause: error, context }),\n rawValue: value\n };\n }\n}\n\n// src/parse-json.ts\nasync function parseJSON({\n text,\n schema\n}) {\n try {\n const value = secureJsonParse(text);\n if (schema == null) {\n return value;\n }\n return validateTypes({ value, schema });\n } catch (error) {\n if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {\n throw error;\n }\n throw new JSONParseError({ text, cause: error });\n }\n}\nasync function safeParseJSON({\n text,\n schema\n}) {\n try {\n const value = secureJsonParse(text);\n if (schema == null) {\n return { success: true, value, rawValue: value };\n }\n return await safeValidateTypes({ value, schema });\n } catch (error) {\n return {\n success: false,\n error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),\n rawValue: void 0\n };\n }\n}\nfunction isParsableJson(input) {\n try {\n secureJsonParse(input);\n return true;\n } catch (e) {\n return false;\n }\n}\n\n// src/parse-json-event-stream.ts\nimport {\n EventSourceParserStream\n} from \"eventsource-parser/stream\";\nfunction parseJsonEventStream({\n stream,\n schema\n}) {\n return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(\n new TransformStream({\n async transform({ data }, controller) {\n if (data === \"[DONE]\") {\n return;\n }\n controller.enqueue(await safeParseJSON({ text: data, schema }));\n }\n })\n );\n}\n\n// src/parse-provider-options.ts\nimport { InvalidArgumentError as InvalidArgumentError2 } from \"@ai-sdk/provider\";\nasync function parseProviderOptions({\n provider,\n providerOptions,\n schema\n}) {\n if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {\n return void 0;\n }\n const parsedProviderOptions = await safeValidateTypes({\n value: providerOptions[provider],\n schema\n });\n if (!parsedProviderOptions.success) {\n throw new InvalidArgumentError2({\n argument: \"providerOptions\",\n message: `invalid ${provider} provider options`,\n cause: parsedProviderOptions.error\n });\n }\n return parsedProviderOptions.value;\n}\n\n// src/post-to-api.ts\nimport { APICallError as APICallError3 } from \"@ai-sdk/provider\";\nvar getOriginalFetch2 = () => globalThis.fetch;\nvar postJsonToApi = async ({\n url,\n headers,\n body,\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n}) => postToApi({\n url,\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers\n },\n body: {\n content: JSON.stringify(body),\n values: body\n },\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n});\nvar postFormDataToApi = async ({\n url,\n headers,\n formData,\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n}) => postToApi({\n url,\n headers,\n body: {\n content: formData,\n values: Object.fromEntries(formData.entries())\n },\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n});\nvar postToApi = async ({\n url,\n headers = {},\n body,\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch: fetch2 = getOriginalFetch2()\n}) => {\n try {\n const response = await fetch2(url, {\n method: \"POST\",\n headers: withUserAgentSuffix(\n headers,\n `ai-sdk/provider-utils/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n body: body.content,\n signal: abortSignal\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!response.ok) {\n let errorInformation;\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: body.values\n });\n } catch (error) {\n if (isAbortError(error) || APICallError3.isInstance(error)) {\n throw error;\n }\n throw new APICallError3({\n message: \"Failed to process error response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: body.values\n });\n }\n throw errorInformation.value;\n }\n try {\n return await successfulResponseHandler({\n response,\n url,\n requestBodyValues: body.values\n });\n } catch (error) {\n if (error instanceof Error) {\n if (isAbortError(error) || APICallError3.isInstance(error)) {\n throw error;\n }\n }\n throw new APICallError3({\n message: \"Failed to process successful response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: body.values\n });\n }\n } catch (error) {\n throw handleFetchError({ error, url, requestBodyValues: body.values });\n }\n};\n\n// src/types/tool.ts\nfunction tool(tool2) {\n return tool2;\n}\nfunction dynamicTool(tool2) {\n return { ...tool2, type: \"dynamic\" };\n}\n\n// src/provider-tool-factory.ts\nfunction createProviderToolFactory({\n id,\n inputSchema\n}) {\n return ({\n execute,\n outputSchema,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n ...args\n }) => tool({\n type: \"provider\",\n id,\n args,\n inputSchema,\n outputSchema,\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable\n });\n}\nfunction createProviderToolFactoryWithOutputSchema({\n id,\n inputSchema,\n outputSchema,\n supportsDeferredResults\n}) {\n return ({\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n ...args\n }) => tool({\n type: \"provider\",\n id,\n args,\n inputSchema,\n outputSchema,\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n supportsDeferredResults\n });\n}\n\n// src/remove-undefined-entries.ts\nfunction removeUndefinedEntries(record) {\n return Object.fromEntries(\n Object.entries(record).filter(([_key, value]) => value != null)\n );\n}\n\n// src/resolve.ts\nasync function resolve(value) {\n if (typeof value === \"function\") {\n value = value();\n }\n return Promise.resolve(value);\n}\n\n// src/response-handler.ts\nimport { APICallError as APICallError4, EmptyResponseBodyError } from \"@ai-sdk/provider\";\nvar createJsonErrorResponseHandler = ({\n errorSchema,\n errorToMessage,\n isRetryable\n}) => async ({ response, url, requestBodyValues }) => {\n const responseBody = await response.text();\n const responseHeaders = extractResponseHeaders(response);\n if (responseBody.trim() === \"\") {\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n })\n };\n }\n try {\n const parsedError = await parseJSON({\n text: responseBody,\n schema: errorSchema\n });\n return {\n responseHeaders,\n value: new APICallError4({\n message: errorToMessage(parsedError),\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n data: parsedError,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)\n })\n };\n } catch (parseError) {\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n })\n };\n }\n};\nvar createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {\n const responseHeaders = extractResponseHeaders(response);\n if (response.body == null) {\n throw new EmptyResponseBodyError({});\n }\n return {\n responseHeaders,\n value: parseJsonEventStream({\n stream: response.body,\n schema: chunkSchema\n })\n };\n};\nvar createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {\n const responseBody = await response.text();\n const parsedResult = await safeParseJSON({\n text: responseBody,\n schema: responseSchema\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!parsedResult.success) {\n throw new APICallError4({\n message: \"Invalid JSON response\",\n cause: parsedResult.error,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n url,\n requestBodyValues\n });\n }\n return {\n responseHeaders,\n value: parsedResult.value,\n rawValue: parsedResult.rawValue\n };\n};\nvar createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n const responseHeaders = extractResponseHeaders(response);\n if (!response.body) {\n throw new APICallError4({\n message: \"Response body is empty\",\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody: void 0\n });\n }\n try {\n const buffer = await response.arrayBuffer();\n return {\n responseHeaders,\n value: new Uint8Array(buffer)\n };\n } catch (error) {\n throw new APICallError4({\n message: \"Failed to read response as array buffer\",\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody: void 0,\n cause: error\n });\n }\n};\nvar createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n const responseHeaders = extractResponseHeaders(response);\n const responseBody = await response.text();\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody\n })\n };\n};\n\n// src/without-trailing-slash.ts\nfunction withoutTrailingSlash(url) {\n return url == null ? void 0 : url.replace(/\\/$/, \"\");\n}\n\n// src/is-async-iterable.ts\nfunction isAsyncIterable(obj) {\n return obj != null && typeof obj[Symbol.asyncIterator] === \"function\";\n}\n\n// src/types/execute-tool.ts\nasync function* executeTool({\n execute,\n input,\n options\n}) {\n const result = execute(input, options);\n if (isAsyncIterable(result)) {\n let lastOutput;\n for await (const output of result) {\n lastOutput = output;\n yield { type: \"preliminary\", output };\n }\n yield { type: \"final\", output: lastOutput };\n } else {\n yield { type: \"final\", output: await result };\n }\n}\n\n// src/index.ts\nimport {\n EventSourceParserStream as EventSourceParserStream2\n} from \"eventsource-parser/stream\";\nexport {\n DelayedPromise,\n DownloadError,\n EventSourceParserStream2 as EventSourceParserStream,\n VERSION,\n asSchema,\n combineHeaders,\n convertAsyncIteratorToReadableStream,\n convertBase64ToUint8Array,\n convertImageModelFileToDataUri,\n convertToBase64,\n convertToFormData,\n convertUint8ArrayToBase64,\n createBinaryResponseHandler,\n createEventSourceResponseHandler,\n createIdGenerator,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n createProviderToolFactory,\n createProviderToolFactoryWithOutputSchema,\n createStatusCodeErrorResponseHandler,\n createToolNameMapping,\n delay,\n downloadBlob,\n dynamicTool,\n executeTool,\n extractResponseHeaders,\n generateId,\n getErrorMessage,\n getFromApi,\n getRuntimeEnvironmentUserAgent,\n injectJsonInstructionIntoMessages,\n isAbortError,\n isNonNullable,\n isParsableJson,\n isUrlSupported,\n jsonSchema,\n lazySchema,\n loadApiKey,\n loadOptionalSetting,\n loadSetting,\n mediaTypeToExtension,\n normalizeHeaders,\n parseJSON,\n parseJsonEventStream,\n parseProviderOptions,\n postFormDataToApi,\n postJsonToApi,\n postToApi,\n removeUndefinedEntries,\n resolve,\n safeParseJSON,\n safeValidateTypes,\n tool,\n validateTypes,\n withUserAgentSuffix,\n withoutTrailingSlash,\n zodSchema\n};\n//# sourceMappingURL=index.mjs.map","// src/anthropic-provider.ts\nimport {\n InvalidArgumentError,\n NoSuchModelError\n} from \"@ai-sdk/provider\";\nimport {\n generateId as generateId2,\n loadApiKey,\n loadOptionalSetting,\n withoutTrailingSlash,\n withUserAgentSuffix\n} from \"@ai-sdk/provider-utils\";\n\n// src/version.ts\nvar VERSION = true ? \"3.0.34\" : \"0.0.0-test\";\n\n// src/anthropic-messages-language-model.ts\nimport {\n APICallError\n} from \"@ai-sdk/provider\";\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n createToolNameMapping,\n generateId,\n parseProviderOptions as parseProviderOptions2,\n postJsonToApi,\n resolve\n} from \"@ai-sdk/provider-utils\";\n\n// src/anthropic-error.ts\nimport {\n createJsonErrorResponseHandler,\n lazySchema,\n zodSchema\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\nvar anthropicErrorDataSchema = lazySchema(\n () => zodSchema(\n z.object({\n type: z.literal(\"error\"),\n error: z.object({\n type: z.string(),\n message: z.string()\n })\n })\n )\n);\nvar anthropicFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: anthropicErrorDataSchema,\n errorToMessage: (data) => data.error.message\n});\n\n// src/anthropic-messages-api.ts\nimport { lazySchema as lazySchema2, zodSchema as zodSchema2 } from \"@ai-sdk/provider-utils\";\nimport { z as z2 } from \"zod/v4\";\nvar anthropicMessagesResponseSchema = lazySchema2(\n () => zodSchema2(\n z2.object({\n type: z2.literal(\"message\"),\n id: z2.string().nullish(),\n model: z2.string().nullish(),\n content: z2.array(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text\"),\n text: z2.string(),\n citations: z2.array(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"web_search_result_location\"),\n cited_text: z2.string(),\n url: z2.string(),\n title: z2.string(),\n encrypted_index: z2.string()\n }),\n z2.object({\n type: z2.literal(\"page_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_page_number: z2.number(),\n end_page_number: z2.number()\n }),\n z2.object({\n type: z2.literal(\"char_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_char_index: z2.number(),\n end_char_index: z2.number()\n })\n ])\n ).optional()\n }),\n z2.object({\n type: z2.literal(\"thinking\"),\n thinking: z2.string(),\n signature: z2.string()\n }),\n z2.object({\n type: z2.literal(\"redacted_thinking\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n // Programmatic tool calling: caller info when triggered from code execution\n caller: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_20250825\"),\n tool_id: z2.string()\n }),\n z2.object({\n type: z2.literal(\"direct\")\n })\n ]).optional()\n }),\n z2.object({\n type: z2.literal(\"server_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.record(z2.string(), z2.unknown()).nullish()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n server_name: z2.string()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_result\"),\n tool_use_id: z2.string(),\n is_error: z2.boolean(),\n content: z2.array(\n z2.union([\n z2.string(),\n z2.object({ type: z2.literal(\"text\"), text: z2.string() })\n ])\n )\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"web_fetch_result\"),\n url: z2.string(),\n retrieved_at: z2.string(),\n content: z2.object({\n type: z2.literal(\"document\"),\n title: z2.string().nullable(),\n citations: z2.object({ enabled: z2.boolean() }).optional(),\n source: z2.union([\n z2.object({\n type: z2.literal(\"base64\"),\n media_type: z2.literal(\"application/pdf\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text\"),\n media_type: z2.literal(\"text/plain\"),\n data: z2.string()\n })\n ])\n })\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"web_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.array(\n z2.object({\n type: z2.literal(\"web_search_result\"),\n url: z2.string(),\n title: z2.string(),\n encrypted_content: z2.string(),\n page_age: z2.string().nullish()\n })\n ),\n z2.object({\n type: z2.literal(\"web_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // code execution results for code_execution_20250522 tool:\n z2.object({\n type: z2.literal(\"code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_result\"),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number(),\n content: z2.array(\n z2.object({\n type: z2.literal(\"code_execution_output\"),\n file_id: z2.string()\n })\n ).optional().default([])\n }),\n z2.object({\n type: z2.literal(\"code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // bash code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"bash_code_execution_result\"),\n content: z2.array(\n z2.object({\n type: z2.literal(\"bash_code_execution_output\"),\n file_id: z2.string()\n })\n ),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number()\n }),\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // text editor code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result_error\"),\n error_code: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_view_result\"),\n content: z2.string(),\n file_type: z2.string(),\n num_lines: z2.number().nullable(),\n start_line: z2.number().nullable(),\n total_lines: z2.number().nullable()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_create_result\"),\n is_file_update: z2.boolean()\n }),\n z2.object({\n type: z2.literal(\n \"text_editor_code_execution_str_replace_result\"\n ),\n lines: z2.array(z2.string()).nullable(),\n new_lines: z2.number().nullable(),\n new_start: z2.number().nullable(),\n old_lines: z2.number().nullable(),\n old_start: z2.number().nullable()\n })\n ])\n }),\n // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119:\n z2.object({\n type: z2.literal(\"tool_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"tool_search_tool_search_result\"),\n tool_references: z2.array(\n z2.object({\n type: z2.literal(\"tool_reference\"),\n tool_name: z2.string()\n })\n )\n }),\n z2.object({\n type: z2.literal(\"tool_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n })\n ])\n ),\n stop_reason: z2.string().nullish(),\n stop_sequence: z2.string().nullish(),\n usage: z2.looseObject({\n input_tokens: z2.number(),\n output_tokens: z2.number(),\n cache_creation_input_tokens: z2.number().nullish(),\n cache_read_input_tokens: z2.number().nullish()\n }),\n container: z2.object({\n expires_at: z2.string(),\n id: z2.string(),\n skills: z2.array(\n z2.object({\n type: z2.union([z2.literal(\"anthropic\"), z2.literal(\"custom\")]),\n skill_id: z2.string(),\n version: z2.string()\n })\n ).nullish()\n }).nullish(),\n context_management: z2.object({\n applied_edits: z2.array(\n z2.union([\n z2.object({\n type: z2.literal(\"clear_tool_uses_20250919\"),\n cleared_tool_uses: z2.number(),\n cleared_input_tokens: z2.number()\n }),\n z2.object({\n type: z2.literal(\"clear_thinking_20251015\"),\n cleared_thinking_turns: z2.number(),\n cleared_input_tokens: z2.number()\n })\n ])\n )\n }).nullish()\n })\n )\n);\nvar anthropicMessagesChunkSchema = lazySchema2(\n () => zodSchema2(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"message_start\"),\n message: z2.object({\n id: z2.string().nullish(),\n model: z2.string().nullish(),\n role: z2.string().nullish(),\n usage: z2.looseObject({\n input_tokens: z2.number(),\n cache_creation_input_tokens: z2.number().nullish(),\n cache_read_input_tokens: z2.number().nullish()\n }),\n // Programmatic tool calling: content may be pre-populated for deferred tool calls\n content: z2.array(\n z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n caller: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_20250825\"),\n tool_id: z2.string()\n }),\n z2.object({\n type: z2.literal(\"direct\")\n })\n ]).optional()\n })\n ])\n ).nullish(),\n stop_reason: z2.string().nullish(),\n container: z2.object({\n expires_at: z2.string(),\n id: z2.string()\n }).nullish()\n })\n }),\n z2.object({\n type: z2.literal(\"content_block_start\"),\n index: z2.number(),\n content_block: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text\"),\n text: z2.string()\n }),\n z2.object({\n type: z2.literal(\"thinking\"),\n thinking: z2.string()\n }),\n z2.object({\n type: z2.literal(\"tool_use\"),\n id: z2.string(),\n name: z2.string(),\n // Programmatic tool calling: input may be present directly for deferred tool calls\n input: z2.record(z2.string(), z2.unknown()).optional(),\n // Programmatic tool calling: caller info when triggered from code execution\n caller: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_20250825\"),\n tool_id: z2.string()\n }),\n z2.object({\n type: z2.literal(\"direct\")\n })\n ]).optional()\n }),\n z2.object({\n type: z2.literal(\"redacted_thinking\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"server_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.record(z2.string(), z2.unknown()).nullish()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_use\"),\n id: z2.string(),\n name: z2.string(),\n input: z2.unknown(),\n server_name: z2.string()\n }),\n z2.object({\n type: z2.literal(\"mcp_tool_result\"),\n tool_use_id: z2.string(),\n is_error: z2.boolean(),\n content: z2.array(\n z2.union([\n z2.string(),\n z2.object({ type: z2.literal(\"text\"), text: z2.string() })\n ])\n )\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"web_fetch_result\"),\n url: z2.string(),\n retrieved_at: z2.string(),\n content: z2.object({\n type: z2.literal(\"document\"),\n title: z2.string().nullable(),\n citations: z2.object({ enabled: z2.boolean() }).optional(),\n source: z2.union([\n z2.object({\n type: z2.literal(\"base64\"),\n media_type: z2.literal(\"application/pdf\"),\n data: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text\"),\n media_type: z2.literal(\"text/plain\"),\n data: z2.string()\n })\n ])\n })\n }),\n z2.object({\n type: z2.literal(\"web_fetch_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"web_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.array(\n z2.object({\n type: z2.literal(\"web_search_result\"),\n url: z2.string(),\n title: z2.string(),\n encrypted_content: z2.string(),\n page_age: z2.string().nullish()\n })\n ),\n z2.object({\n type: z2.literal(\"web_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // code execution results for code_execution_20250522 tool:\n z2.object({\n type: z2.literal(\"code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"code_execution_result\"),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number(),\n content: z2.array(\n z2.object({\n type: z2.literal(\"code_execution_output\"),\n file_id: z2.string()\n })\n ).optional().default([])\n }),\n z2.object({\n type: z2.literal(\"code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // bash code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"bash_code_execution_result\"),\n content: z2.array(\n z2.object({\n type: z2.literal(\"bash_code_execution_output\"),\n file_id: z2.string()\n })\n ),\n stdout: z2.string(),\n stderr: z2.string(),\n return_code: z2.number()\n }),\n z2.object({\n type: z2.literal(\"bash_code_execution_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n }),\n // text editor code execution results for code_execution_20250825 tool:\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"text_editor_code_execution_tool_result_error\"),\n error_code: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_view_result\"),\n content: z2.string(),\n file_type: z2.string(),\n num_lines: z2.number().nullable(),\n start_line: z2.number().nullable(),\n total_lines: z2.number().nullable()\n }),\n z2.object({\n type: z2.literal(\"text_editor_code_execution_create_result\"),\n is_file_update: z2.boolean()\n }),\n z2.object({\n type: z2.literal(\n \"text_editor_code_execution_str_replace_result\"\n ),\n lines: z2.array(z2.string()).nullable(),\n new_lines: z2.number().nullable(),\n new_start: z2.number().nullable(),\n old_lines: z2.number().nullable(),\n old_start: z2.number().nullable()\n })\n ])\n }),\n // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119:\n z2.object({\n type: z2.literal(\"tool_search_tool_result\"),\n tool_use_id: z2.string(),\n content: z2.union([\n z2.object({\n type: z2.literal(\"tool_search_tool_search_result\"),\n tool_references: z2.array(\n z2.object({\n type: z2.literal(\"tool_reference\"),\n tool_name: z2.string()\n })\n )\n }),\n z2.object({\n type: z2.literal(\"tool_search_tool_result_error\"),\n error_code: z2.string()\n })\n ])\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"content_block_delta\"),\n index: z2.number(),\n delta: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"input_json_delta\"),\n partial_json: z2.string()\n }),\n z2.object({\n type: z2.literal(\"text_delta\"),\n text: z2.string()\n }),\n z2.object({\n type: z2.literal(\"thinking_delta\"),\n thinking: z2.string()\n }),\n z2.object({\n type: z2.literal(\"signature_delta\"),\n signature: z2.string()\n }),\n z2.object({\n type: z2.literal(\"citations_delta\"),\n citation: z2.discriminatedUnion(\"type\", [\n z2.object({\n type: z2.literal(\"web_search_result_location\"),\n cited_text: z2.string(),\n url: z2.string(),\n title: z2.string(),\n encrypted_index: z2.string()\n }),\n z2.object({\n type: z2.literal(\"page_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_page_number: z2.number(),\n end_page_number: z2.number()\n }),\n z2.object({\n type: z2.literal(\"char_location\"),\n cited_text: z2.string(),\n document_index: z2.number(),\n document_title: z2.string().nullable(),\n start_char_index: z2.number(),\n end_char_index: z2.number()\n })\n ])\n })\n ])\n }),\n z2.object({\n type: z2.literal(\"content_block_stop\"),\n index: z2.number()\n }),\n z2.object({\n type: z2.literal(\"error\"),\n error: z2.object({\n type: z2.string(),\n message: z2.string()\n })\n }),\n z2.object({\n type: z2.literal(\"message_delta\"),\n delta: z2.object({\n stop_reason: z2.string().nullish(),\n stop_sequence: z2.string().nullish(),\n container: z2.object({\n expires_at: z2.string(),\n id: z2.string(),\n skills: z2.array(\n z2.object({\n type: z2.union([\n z2.literal(\"anthropic\"),\n z2.literal(\"custom\")\n ]),\n skill_id: z2.string(),\n version: z2.string()\n })\n ).nullish()\n }).nullish()\n }),\n usage: z2.looseObject({\n input_tokens: z2.number().nullish(),\n output_tokens: z2.number(),\n cache_creation_input_tokens: z2.number().nullish(),\n cache_read_input_tokens: z2.number().nullish()\n }),\n context_management: z2.object({\n applied_edits: z2.array(\n z2.union([\n z2.object({\n type: z2.literal(\"clear_tool_uses_20250919\"),\n cleared_tool_uses: z2.number(),\n cleared_input_tokens: z2.number()\n }),\n z2.object({\n type: z2.literal(\"clear_thinking_20251015\"),\n cleared_thinking_turns: z2.number(),\n cleared_input_tokens: z2.number()\n })\n ])\n )\n }).nullish()\n }),\n z2.object({\n type: z2.literal(\"message_stop\")\n }),\n z2.object({\n type: z2.literal(\"ping\")\n })\n ])\n )\n);\nvar anthropicReasoningMetadataSchema = lazySchema2(\n () => zodSchema2(\n z2.object({\n signature: z2.string().optional(),\n redactedData: z2.string().optional()\n })\n )\n);\n\n// src/anthropic-messages-options.ts\nimport { z as z3 } from \"zod/v4\";\nvar anthropicFilePartProviderOptions = z3.object({\n /**\n * Citation configuration for this document.\n * When enabled, this document will generate citations in the response.\n */\n citations: z3.object({\n /**\n * Enable citations for this document\n */\n enabled: z3.boolean()\n }).optional(),\n /**\n * Custom title for the document.\n * If not provided, the filename will be used.\n */\n title: z3.string().optional(),\n /**\n * Context about the document that will be passed to the model\n * but not used towards cited content.\n * Useful for storing document metadata as text or stringified JSON.\n */\n context: z3.string().optional()\n});\nvar anthropicProviderOptions = z3.object({\n /**\n * Whether to send reasoning to the model.\n *\n * This allows you to deactivate reasoning inputs for models that do not support them.\n */\n sendReasoning: z3.boolean().optional(),\n /**\n * Determines how structured outputs are generated.\n *\n * - `outputFormat`: Use the `output_format` parameter to specify the structured output format.\n * - `jsonTool`: Use a special 'json' tool to specify the structured output format.\n * - `auto`: Use 'outputFormat' when supported, otherwise use 'jsonTool' (default).\n */\n structuredOutputMode: z3.enum([\"outputFormat\", \"jsonTool\", \"auto\"]).optional(),\n /**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include thinking content blocks showing Claude's thinking process before the final answer.\n * Requires a minimum budget of 1,024 tokens and counts towards the `max_tokens` limit.\n */\n thinking: z3.object({\n type: z3.union([z3.literal(\"enabled\"), z3.literal(\"disabled\")]),\n budgetTokens: z3.number().optional()\n }).optional(),\n /**\n * Whether to disable parallel function calling during tool use. Default is false.\n * When set to true, Claude will use at most one tool per response.\n */\n disableParallelToolUse: z3.boolean().optional(),\n /**\n * Cache control settings for this message.\n * See https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n cacheControl: z3.object({\n type: z3.literal(\"ephemeral\"),\n ttl: z3.union([z3.literal(\"5m\"), z3.literal(\"1h\")]).optional()\n }).optional(),\n /**\n * MCP servers to be utilized in this request.\n */\n mcpServers: z3.array(\n z3.object({\n type: z3.literal(\"url\"),\n name: z3.string(),\n url: z3.string(),\n authorizationToken: z3.string().nullish(),\n toolConfiguration: z3.object({\n enabled: z3.boolean().nullish(),\n allowedTools: z3.array(z3.string()).nullish()\n }).nullish()\n })\n ).optional(),\n /**\n * Agent Skills configuration. Skills enable Claude to perform specialized tasks\n * like document processing (PPTX, DOCX, PDF, XLSX) and data analysis.\n * Requires code execution tool to be enabled.\n */\n container: z3.object({\n id: z3.string().optional(),\n skills: z3.array(\n z3.object({\n type: z3.union([z3.literal(\"anthropic\"), z3.literal(\"custom\")]),\n skillId: z3.string(),\n version: z3.string().optional()\n })\n ).optional()\n }).optional(),\n /**\n * Whether to enable tool streaming (and structured output streaming).\n *\n * When set to false, the model will return all tool calls and results\n * at once after a delay.\n *\n * @default true\n */\n toolStreaming: z3.boolean().optional(),\n /**\n * @default 'high'\n */\n effort: z3.enum([\"low\", \"medium\", \"high\"]).optional(),\n contextManagement: z3.object({\n edits: z3.array(\n z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"clear_tool_uses_20250919\"),\n trigger: z3.discriminatedUnion(\"type\", [\n z3.object({\n type: z3.literal(\"input_tokens\"),\n value: z3.number()\n }),\n z3.object({\n type: z3.literal(\"tool_uses\"),\n value: z3.number()\n })\n ]).optional(),\n keep: z3.object({\n type: z3.literal(\"tool_uses\"),\n value: z3.number()\n }).optional(),\n clearAtLeast: z3.object({\n type: z3.literal(\"input_tokens\"),\n value: z3.number()\n }).optional(),\n clearToolInputs: z3.boolean().optional(),\n excludeTools: z3.array(z3.string()).optional()\n }),\n z3.object({\n type: z3.literal(\"clear_thinking_20251015\"),\n keep: z3.union([\n z3.literal(\"all\"),\n z3.object({\n type: z3.literal(\"thinking_turns\"),\n value: z3.number()\n })\n ]).optional()\n })\n ])\n )\n }).optional()\n});\n\n// src/anthropic-prepare-tools.ts\nimport {\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\n\n// src/get-cache-control.ts\nvar MAX_CACHE_BREAKPOINTS = 4;\nfunction getCacheControl(providerMetadata) {\n var _a;\n const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;\n const cacheControlValue = (_a = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a : anthropic2 == null ? void 0 : anthropic2.cache_control;\n return cacheControlValue;\n}\nvar CacheControlValidator = class {\n constructor() {\n this.breakpointCount = 0;\n this.warnings = [];\n }\n getCacheControl(providerMetadata, context) {\n const cacheControlValue = getCacheControl(providerMetadata);\n if (!cacheControlValue) {\n return void 0;\n }\n if (!context.canCache) {\n this.warnings.push({\n type: \"unsupported\",\n feature: \"cache_control on non-cacheable context\",\n details: `cache_control cannot be set on ${context.type}. It will be ignored.`\n });\n return void 0;\n }\n this.breakpointCount++;\n if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) {\n this.warnings.push({\n type: \"unsupported\",\n feature: \"cacheControl breakpoint limit\",\n details: `Maximum ${MAX_CACHE_BREAKPOINTS} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`\n });\n return void 0;\n }\n return cacheControlValue;\n }\n getWarnings() {\n return this.warnings;\n }\n};\n\n// src/tool/text-editor_20250728.ts\nimport { createProviderToolFactory } from \"@ai-sdk/provider-utils\";\nimport { z as z4 } from \"zod/v4\";\nimport { lazySchema as lazySchema3, zodSchema as zodSchema3 } from \"@ai-sdk/provider-utils\";\nvar textEditor_20250728ArgsSchema = lazySchema3(\n () => zodSchema3(\n z4.object({\n maxCharacters: z4.number().optional()\n })\n )\n);\nvar textEditor_20250728InputSchema = lazySchema3(\n () => zodSchema3(\n z4.object({\n command: z4.enum([\"view\", \"create\", \"str_replace\", \"insert\"]),\n path: z4.string(),\n file_text: z4.string().optional(),\n insert_line: z4.number().int().optional(),\n new_str: z4.string().optional(),\n insert_text: z4.string().optional(),\n old_str: z4.string().optional(),\n view_range: z4.array(z4.number().int()).optional()\n })\n )\n);\nvar factory = createProviderToolFactory({\n id: \"anthropic.text_editor_20250728\",\n inputSchema: textEditor_20250728InputSchema\n});\nvar textEditor_20250728 = (args = {}) => {\n return factory(args);\n};\n\n// src/tool/web-search_20250305.ts\nimport {\n createProviderToolFactoryWithOutputSchema,\n lazySchema as lazySchema4,\n zodSchema as zodSchema4\n} from \"@ai-sdk/provider-utils\";\nimport { z as z5 } from \"zod/v4\";\nvar webSearch_20250305ArgsSchema = lazySchema4(\n () => zodSchema4(\n z5.object({\n maxUses: z5.number().optional(),\n allowedDomains: z5.array(z5.string()).optional(),\n blockedDomains: z5.array(z5.string()).optional(),\n userLocation: z5.object({\n type: z5.literal(\"approximate\"),\n city: z5.string().optional(),\n region: z5.string().optional(),\n country: z5.string().optional(),\n timezone: z5.string().optional()\n }).optional()\n })\n )\n);\nvar webSearch_20250305OutputSchema = lazySchema4(\n () => zodSchema4(\n z5.array(\n z5.object({\n url: z5.string(),\n title: z5.string().nullable(),\n pageAge: z5.string().nullable(),\n encryptedContent: z5.string(),\n type: z5.literal(\"web_search_result\")\n })\n )\n )\n);\nvar webSearch_20250305InputSchema = lazySchema4(\n () => zodSchema4(\n z5.object({\n query: z5.string()\n })\n )\n);\nvar factory2 = createProviderToolFactoryWithOutputSchema({\n id: \"anthropic.web_search_20250305\",\n inputSchema: webSearch_20250305InputSchema,\n outputSchema: webSearch_20250305OutputSchema,\n supportsDeferredResults: true\n});\nvar webSearch_20250305 = (args = {}) => {\n return factory2(args);\n};\n\n// src/tool/web-fetch-20250910.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema2,\n lazySchema as lazySchema5,\n zodSchema as zodSchema5\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\nvar webFetch_20250910ArgsSchema = lazySchema5(\n () => zodSchema5(\n z6.object({\n maxUses: z6.number().optional(),\n allowedDomains: z6.array(z6.string()).optional(),\n blockedDomains: z6.array(z6.string()).optional(),\n citations: z6.object({ enabled: z6.boolean() }).optional(),\n maxContentTokens: z6.number().optional()\n })\n )\n);\nvar webFetch_20250910OutputSchema = lazySchema5(\n () => zodSchema5(\n z6.object({\n type: z6.literal(\"web_fetch_result\"),\n url: z6.string(),\n content: z6.object({\n type: z6.literal(\"document\"),\n title: z6.string().nullable(),\n citations: z6.object({ enabled: z6.boolean() }).optional(),\n source: z6.union([\n z6.object({\n type: z6.literal(\"base64\"),\n mediaType: z6.literal(\"application/pdf\"),\n data: z6.string()\n }),\n z6.object({\n type: z6.literal(\"text\"),\n mediaType: z6.literal(\"text/plain\"),\n data: z6.string()\n })\n ])\n }),\n retrievedAt: z6.string().nullable()\n })\n )\n);\nvar webFetch_20250910InputSchema = lazySchema5(\n () => zodSchema5(\n z6.object({\n url: z6.string()\n })\n )\n);\nvar factory3 = createProviderToolFactoryWithOutputSchema2({\n id: \"anthropic.web_fetch_20250910\",\n inputSchema: webFetch_20250910InputSchema,\n outputSchema: webFetch_20250910OutputSchema,\n supportsDeferredResults: true\n});\nvar webFetch_20250910 = (args = {}) => {\n return factory3(args);\n};\n\n// src/anthropic-prepare-tools.ts\nimport { validateTypes } from \"@ai-sdk/provider-utils\";\nasync function prepareTools({\n tools,\n toolChoice,\n disableParallelToolUse,\n cacheControlValidator,\n supportsStructuredOutput\n}) {\n var _a;\n tools = (tools == null ? void 0 : tools.length) ? tools : void 0;\n const toolWarnings = [];\n const betas = /* @__PURE__ */ new Set();\n const validator = cacheControlValidator || new CacheControlValidator();\n if (tools == null) {\n return { tools: void 0, toolChoice: void 0, toolWarnings, betas };\n }\n const anthropicTools2 = [];\n for (const tool of tools) {\n switch (tool.type) {\n case \"function\": {\n const cacheControl = validator.getCacheControl(tool.providerOptions, {\n type: \"tool definition\",\n canCache: true\n });\n const anthropicOptions = (_a = tool.providerOptions) == null ? void 0 : _a.anthropic;\n const deferLoading = anthropicOptions == null ? void 0 : anthropicOptions.deferLoading;\n const allowedCallers = anthropicOptions == null ? void 0 : anthropicOptions.allowedCallers;\n anthropicTools2.push({\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n cache_control: cacheControl,\n ...supportsStructuredOutput === true && tool.strict != null ? { strict: tool.strict } : {},\n ...deferLoading != null ? { defer_loading: deferLoading } : {},\n ...allowedCallers != null ? { allowed_callers: allowedCallers } : {},\n ...tool.inputExamples != null ? {\n input_examples: tool.inputExamples.map(\n (example) => example.input\n )\n } : {}\n });\n if (supportsStructuredOutput === true) {\n betas.add(\"structured-outputs-2025-11-13\");\n }\n if (tool.inputExamples != null || allowedCallers != null) {\n betas.add(\"advanced-tool-use-2025-11-20\");\n }\n break;\n }\n case \"provider\": {\n switch (tool.id) {\n case \"anthropic.code_execution_20250522\": {\n betas.add(\"code-execution-2025-05-22\");\n anthropicTools2.push({\n type: \"code_execution_20250522\",\n name: \"code_execution\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.code_execution_20250825\": {\n betas.add(\"code-execution-2025-08-25\");\n anthropicTools2.push({\n type: \"code_execution_20250825\",\n name: \"code_execution\"\n });\n break;\n }\n case \"anthropic.computer_20250124\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"computer\",\n type: \"computer_20250124\",\n display_width_px: tool.args.displayWidthPx,\n display_height_px: tool.args.displayHeightPx,\n display_number: tool.args.displayNumber,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.computer_20251124\": {\n betas.add(\"computer-use-2025-11-24\");\n anthropicTools2.push({\n name: \"computer\",\n type: \"computer_20251124\",\n display_width_px: tool.args.displayWidthPx,\n display_height_px: tool.args.displayHeightPx,\n display_number: tool.args.displayNumber,\n enable_zoom: tool.args.enableZoom,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.computer_20241022\": {\n betas.add(\"computer-use-2024-10-22\");\n anthropicTools2.push({\n name: \"computer\",\n type: \"computer_20241022\",\n display_width_px: tool.args.displayWidthPx,\n display_height_px: tool.args.displayHeightPx,\n display_number: tool.args.displayNumber,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20250124\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"str_replace_editor\",\n type: \"text_editor_20250124\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20241022\": {\n betas.add(\"computer-use-2024-10-22\");\n anthropicTools2.push({\n name: \"str_replace_editor\",\n type: \"text_editor_20241022\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20250429\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"str_replace_based_edit_tool\",\n type: \"text_editor_20250429\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.text_editor_20250728\": {\n const args = await validateTypes({\n value: tool.args,\n schema: textEditor_20250728ArgsSchema\n });\n anthropicTools2.push({\n name: \"str_replace_based_edit_tool\",\n type: \"text_editor_20250728\",\n max_characters: args.maxCharacters,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.bash_20250124\": {\n betas.add(\"computer-use-2025-01-24\");\n anthropicTools2.push({\n name: \"bash\",\n type: \"bash_20250124\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.bash_20241022\": {\n betas.add(\"computer-use-2024-10-22\");\n anthropicTools2.push({\n name: \"bash\",\n type: \"bash_20241022\",\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.memory_20250818\": {\n betas.add(\"context-management-2025-06-27\");\n anthropicTools2.push({\n name: \"memory\",\n type: \"memory_20250818\"\n });\n break;\n }\n case \"anthropic.web_fetch_20250910\": {\n betas.add(\"web-fetch-2025-09-10\");\n const args = await validateTypes({\n value: tool.args,\n schema: webFetch_20250910ArgsSchema\n });\n anthropicTools2.push({\n type: \"web_fetch_20250910\",\n name: \"web_fetch\",\n max_uses: args.maxUses,\n allowed_domains: args.allowedDomains,\n blocked_domains: args.blockedDomains,\n citations: args.citations,\n max_content_tokens: args.maxContentTokens,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.web_search_20250305\": {\n const args = await validateTypes({\n value: tool.args,\n schema: webSearch_20250305ArgsSchema\n });\n anthropicTools2.push({\n type: \"web_search_20250305\",\n name: \"web_search\",\n max_uses: args.maxUses,\n allowed_domains: args.allowedDomains,\n blocked_domains: args.blockedDomains,\n user_location: args.userLocation,\n cache_control: void 0\n });\n break;\n }\n case \"anthropic.tool_search_regex_20251119\": {\n betas.add(\"advanced-tool-use-2025-11-20\");\n anthropicTools2.push({\n type: \"tool_search_tool_regex_20251119\",\n name: \"tool_search_tool_regex\"\n });\n break;\n }\n case \"anthropic.tool_search_bm25_20251119\": {\n betas.add(\"advanced-tool-use-2025-11-20\");\n anthropicTools2.push({\n type: \"tool_search_tool_bm25_20251119\",\n name: \"tool_search_tool_bm25\"\n });\n break;\n }\n default: {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `provider-defined tool ${tool.id}`\n });\n break;\n }\n }\n break;\n }\n default: {\n toolWarnings.push({\n type: \"unsupported\",\n feature: `tool ${tool}`\n });\n break;\n }\n }\n }\n if (toolChoice == null) {\n return {\n tools: anthropicTools2,\n toolChoice: disableParallelToolUse ? { type: \"auto\", disable_parallel_tool_use: disableParallelToolUse } : void 0,\n toolWarnings,\n betas\n };\n }\n const type = toolChoice.type;\n switch (type) {\n case \"auto\":\n return {\n tools: anthropicTools2,\n toolChoice: {\n type: \"auto\",\n disable_parallel_tool_use: disableParallelToolUse\n },\n toolWarnings,\n betas\n };\n case \"required\":\n return {\n tools: anthropicTools2,\n toolChoice: {\n type: \"any\",\n disable_parallel_tool_use: disableParallelToolUse\n },\n toolWarnings,\n betas\n };\n case \"none\":\n return { tools: void 0, toolChoice: void 0, toolWarnings, betas };\n case \"tool\":\n return {\n tools: anthropicTools2,\n toolChoice: {\n type: \"tool\",\n name: toolChoice.toolName,\n disable_parallel_tool_use: disableParallelToolUse\n },\n toolWarnings,\n betas\n };\n default: {\n const _exhaustiveCheck = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`\n });\n }\n }\n}\n\n// src/convert-anthropic-messages-usage.ts\nfunction convertAnthropicMessagesUsage(usage) {\n var _a, _b;\n const inputTokens = usage.input_tokens;\n const outputTokens = usage.output_tokens;\n const cacheCreationTokens = (_a = usage.cache_creation_input_tokens) != null ? _a : 0;\n const cacheReadTokens = (_b = usage.cache_read_input_tokens) != null ? _b : 0;\n return {\n inputTokens: {\n total: inputTokens + cacheCreationTokens + cacheReadTokens,\n noCache: inputTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: cacheCreationTokens\n },\n outputTokens: {\n total: outputTokens,\n text: void 0,\n reasoning: void 0\n },\n raw: usage\n };\n}\n\n// src/convert-to-anthropic-messages-prompt.ts\nimport {\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nimport {\n convertToBase64,\n parseProviderOptions,\n validateTypes as validateTypes2,\n isNonNullable\n} from \"@ai-sdk/provider-utils\";\n\n// src/tool/code-execution_20250522.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema3,\n lazySchema as lazySchema6,\n zodSchema as zodSchema6\n} from \"@ai-sdk/provider-utils\";\nimport { z as z7 } from \"zod/v4\";\nvar codeExecution_20250522OutputSchema = lazySchema6(\n () => zodSchema6(\n z7.object({\n type: z7.literal(\"code_execution_result\"),\n stdout: z7.string(),\n stderr: z7.string(),\n return_code: z7.number(),\n content: z7.array(\n z7.object({\n type: z7.literal(\"code_execution_output\"),\n file_id: z7.string()\n })\n ).optional().default([])\n })\n )\n);\nvar codeExecution_20250522InputSchema = lazySchema6(\n () => zodSchema6(\n z7.object({\n code: z7.string()\n })\n )\n);\nvar factory4 = createProviderToolFactoryWithOutputSchema3({\n id: \"anthropic.code_execution_20250522\",\n inputSchema: codeExecution_20250522InputSchema,\n outputSchema: codeExecution_20250522OutputSchema\n});\nvar codeExecution_20250522 = (args = {}) => {\n return factory4(args);\n};\n\n// src/tool/code-execution_20250825.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema4,\n lazySchema as lazySchema7,\n zodSchema as zodSchema7\n} from \"@ai-sdk/provider-utils\";\nimport { z as z8 } from \"zod/v4\";\nvar codeExecution_20250825OutputSchema = lazySchema7(\n () => zodSchema7(\n z8.discriminatedUnion(\"type\", [\n z8.object({\n type: z8.literal(\"code_execution_result\"),\n stdout: z8.string(),\n stderr: z8.string(),\n return_code: z8.number(),\n content: z8.array(\n z8.object({\n type: z8.literal(\"code_execution_output\"),\n file_id: z8.string()\n })\n ).optional().default([])\n }),\n z8.object({\n type: z8.literal(\"bash_code_execution_result\"),\n content: z8.array(\n z8.object({\n type: z8.literal(\"bash_code_execution_output\"),\n file_id: z8.string()\n })\n ),\n stdout: z8.string(),\n stderr: z8.string(),\n return_code: z8.number()\n }),\n z8.object({\n type: z8.literal(\"bash_code_execution_tool_result_error\"),\n error_code: z8.string()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_tool_result_error\"),\n error_code: z8.string()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_view_result\"),\n content: z8.string(),\n file_type: z8.string(),\n num_lines: z8.number().nullable(),\n start_line: z8.number().nullable(),\n total_lines: z8.number().nullable()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_create_result\"),\n is_file_update: z8.boolean()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution_str_replace_result\"),\n lines: z8.array(z8.string()).nullable(),\n new_lines: z8.number().nullable(),\n new_start: z8.number().nullable(),\n old_lines: z8.number().nullable(),\n old_start: z8.number().nullable()\n })\n ])\n )\n);\nvar codeExecution_20250825InputSchema = lazySchema7(\n () => zodSchema7(\n z8.discriminatedUnion(\"type\", [\n // Programmatic tool calling format (mapped from { code } by AI SDK)\n z8.object({\n type: z8.literal(\"programmatic-tool-call\"),\n code: z8.string()\n }),\n z8.object({\n type: z8.literal(\"bash_code_execution\"),\n command: z8.string()\n }),\n z8.discriminatedUnion(\"command\", [\n z8.object({\n type: z8.literal(\"text_editor_code_execution\"),\n command: z8.literal(\"view\"),\n path: z8.string()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution\"),\n command: z8.literal(\"create\"),\n path: z8.string(),\n file_text: z8.string().nullish()\n }),\n z8.object({\n type: z8.literal(\"text_editor_code_execution\"),\n command: z8.literal(\"str_replace\"),\n path: z8.string(),\n old_str: z8.string(),\n new_str: z8.string()\n })\n ])\n ])\n )\n);\nvar factory5 = createProviderToolFactoryWithOutputSchema4({\n id: \"anthropic.code_execution_20250825\",\n inputSchema: codeExecution_20250825InputSchema,\n outputSchema: codeExecution_20250825OutputSchema,\n // Programmatic tool calling: tool results may be deferred to a later turn\n // when code execution triggers a client-executed tool that needs to be\n // resolved before the code execution result can be returned.\n supportsDeferredResults: true\n});\nvar codeExecution_20250825 = (args = {}) => {\n return factory5(args);\n};\n\n// src/tool/tool-search-regex_20251119.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema5,\n lazySchema as lazySchema8,\n zodSchema as zodSchema8\n} from \"@ai-sdk/provider-utils\";\nimport { z as z9 } from \"zod/v4\";\nvar toolSearchRegex_20251119OutputSchema = lazySchema8(\n () => zodSchema8(\n z9.array(\n z9.object({\n type: z9.literal(\"tool_reference\"),\n toolName: z9.string()\n })\n )\n )\n);\nvar toolSearchRegex_20251119InputSchema = lazySchema8(\n () => zodSchema8(\n z9.object({\n /**\n * A regex pattern to search for tools.\n * Uses Python re.search() syntax. Maximum 200 characters.\n *\n * Examples:\n * - \"weather\" - matches tool names/descriptions containing \"weather\"\n * - \"get_.*_data\" - matches tools like get_user_data, get_weather_data\n * - \"database.*query|query.*database\" - OR patterns for flexibility\n * - \"(?i)slack\" - case-insensitive search\n */\n pattern: z9.string(),\n /**\n * Maximum number of tools to return. Optional.\n */\n limit: z9.number().optional()\n })\n )\n);\nvar factory6 = createProviderToolFactoryWithOutputSchema5({\n id: \"anthropic.tool_search_regex_20251119\",\n inputSchema: toolSearchRegex_20251119InputSchema,\n outputSchema: toolSearchRegex_20251119OutputSchema,\n supportsDeferredResults: true\n});\nvar toolSearchRegex_20251119 = (args = {}) => {\n return factory6(args);\n};\n\n// src/convert-to-anthropic-messages-prompt.ts\nfunction convertToString(data) {\n if (typeof data === \"string\") {\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n }\n if (data instanceof Uint8Array) {\n return new TextDecoder().decode(data);\n }\n if (data instanceof URL) {\n throw new UnsupportedFunctionalityError2({\n functionality: \"URL-based text documents are not supported for citations\"\n });\n }\n throw new UnsupportedFunctionalityError2({\n functionality: `unsupported data type for text documents: ${typeof data}`\n });\n}\nfunction isUrlData(data) {\n return data instanceof URL || isUrlString(data);\n}\nfunction isUrlString(data) {\n return typeof data === \"string\" && /^https?:\\/\\//i.test(data);\n}\nfunction getUrlString(data) {\n return data instanceof URL ? data.toString() : data;\n}\nasync function convertToAnthropicMessagesPrompt({\n prompt,\n sendReasoning,\n warnings,\n cacheControlValidator,\n toolNameMapping\n}) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;\n const betas = /* @__PURE__ */ new Set();\n const blocks = groupIntoBlocks(prompt);\n const validator = cacheControlValidator || new CacheControlValidator();\n let system = void 0;\n const messages = [];\n async function shouldEnableCitations(providerMetadata) {\n var _a2, _b2;\n const anthropicOptions = await parseProviderOptions({\n provider: \"anthropic\",\n providerOptions: providerMetadata,\n schema: anthropicFilePartProviderOptions\n });\n return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;\n }\n async function getDocumentMetadata(providerMetadata) {\n const anthropicOptions = await parseProviderOptions({\n provider: \"anthropic\",\n providerOptions: providerMetadata,\n schema: anthropicFilePartProviderOptions\n });\n return {\n title: anthropicOptions == null ? void 0 : anthropicOptions.title,\n context: anthropicOptions == null ? void 0 : anthropicOptions.context\n };\n }\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n const isLastBlock = i === blocks.length - 1;\n const type = block.type;\n switch (type) {\n case \"system\": {\n if (system != null) {\n throw new UnsupportedFunctionalityError2({\n functionality: \"Multiple system messages that are separated by user/assistant messages\"\n });\n }\n system = block.messages.map(({ content, providerOptions }) => ({\n type: \"text\",\n text: content,\n cache_control: validator.getCacheControl(providerOptions, {\n type: \"system message\",\n canCache: true\n })\n }));\n break;\n }\n case \"user\": {\n const anthropicContent = [];\n for (const message of block.messages) {\n const { role, content } = message;\n switch (role) {\n case \"user\": {\n for (let j = 0; j < content.length; j++) {\n const part = content[j];\n const isLastPart = j === content.length - 1;\n const cacheControl = (_a = validator.getCacheControl(part.providerOptions, {\n type: \"user message part\",\n canCache: true\n })) != null ? _a : isLastPart ? validator.getCacheControl(message.providerOptions, {\n type: \"user message\",\n canCache: true\n }) : void 0;\n switch (part.type) {\n case \"text\": {\n anthropicContent.push({\n type: \"text\",\n text: part.text,\n cache_control: cacheControl\n });\n break;\n }\n case \"file\": {\n if (part.mediaType.startsWith(\"image/\")) {\n anthropicContent.push({\n type: \"image\",\n source: isUrlData(part.data) ? {\n type: \"url\",\n url: getUrlString(part.data)\n } : {\n type: \"base64\",\n media_type: part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType,\n data: convertToBase64(part.data)\n },\n cache_control: cacheControl\n });\n } else if (part.mediaType === \"application/pdf\") {\n betas.add(\"pdfs-2024-09-25\");\n const enableCitations = await shouldEnableCitations(\n part.providerOptions\n );\n const metadata = await getDocumentMetadata(\n part.providerOptions\n );\n anthropicContent.push({\n type: \"document\",\n source: isUrlData(part.data) ? {\n type: \"url\",\n url: getUrlString(part.data)\n } : {\n type: \"base64\",\n media_type: \"application/pdf\",\n data: convertToBase64(part.data)\n },\n title: (_b = metadata.title) != null ? _b : part.filename,\n ...metadata.context && { context: metadata.context },\n ...enableCitations && {\n citations: { enabled: true }\n },\n cache_control: cacheControl\n });\n } else if (part.mediaType === \"text/plain\") {\n const enableCitations = await shouldEnableCitations(\n part.providerOptions\n );\n const metadata = await getDocumentMetadata(\n part.providerOptions\n );\n anthropicContent.push({\n type: \"document\",\n source: isUrlData(part.data) ? {\n type: \"url\",\n url: getUrlString(part.data)\n } : {\n type: \"text\",\n media_type: \"text/plain\",\n data: convertToString(part.data)\n },\n title: (_c = metadata.title) != null ? _c : part.filename,\n ...metadata.context && { context: metadata.context },\n ...enableCitations && {\n citations: { enabled: true }\n },\n cache_control: cacheControl\n });\n } else {\n throw new UnsupportedFunctionalityError2({\n functionality: `media type: ${part.mediaType}`\n });\n }\n break;\n }\n }\n }\n break;\n }\n case \"tool\": {\n for (let i2 = 0; i2 < content.length; i2++) {\n const part = content[i2];\n if (part.type === \"tool-approval-response\") {\n continue;\n }\n const isLastPart = i2 === content.length - 1;\n const cacheControl = (_d = validator.getCacheControl(part.providerOptions, {\n type: \"tool result part\",\n canCache: true\n })) != null ? _d : isLastPart ? validator.getCacheControl(message.providerOptions, {\n type: \"tool result message\",\n canCache: true\n }) : void 0;\n const output = part.output;\n let contentValue;\n switch (output.type) {\n case \"content\":\n contentValue = output.value.map((contentPart) => {\n switch (contentPart.type) {\n case \"text\":\n return {\n type: \"text\",\n text: contentPart.text\n };\n case \"image-data\": {\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: contentPart.mediaType,\n data: contentPart.data\n }\n };\n }\n case \"image-url\": {\n return {\n type: \"image\",\n source: {\n type: \"url\",\n url: contentPart.url\n }\n };\n }\n case \"file-url\": {\n return {\n type: \"document\",\n source: {\n type: \"url\",\n url: contentPart.url\n }\n };\n }\n case \"file-data\": {\n if (contentPart.mediaType === \"application/pdf\") {\n betas.add(\"pdfs-2024-09-25\");\n return {\n type: \"document\",\n source: {\n type: \"base64\",\n media_type: contentPart.mediaType,\n data: contentPart.data\n }\n };\n }\n warnings.push({\n type: \"other\",\n message: `unsupported tool content part type: ${contentPart.type} with media type: ${contentPart.mediaType}`\n });\n return void 0;\n }\n default: {\n warnings.push({\n type: \"other\",\n message: `unsupported tool content part type: ${contentPart.type}`\n });\n return void 0;\n }\n }\n }).filter(isNonNullable);\n break;\n case \"text\":\n case \"error-text\":\n contentValue = output.value;\n break;\n case \"execution-denied\":\n contentValue = (_e = output.reason) != null ? _e : \"Tool execution denied.\";\n break;\n case \"json\":\n case \"error-json\":\n default:\n contentValue = JSON.stringify(output.value);\n break;\n }\n anthropicContent.push({\n type: \"tool_result\",\n tool_use_id: part.toolCallId,\n content: contentValue,\n is_error: output.type === \"error-text\" || output.type === \"error-json\" ? true : void 0,\n cache_control: cacheControl\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n messages.push({ role: \"user\", content: anthropicContent });\n break;\n }\n case \"assistant\": {\n const anthropicContent = [];\n const mcpToolUseIds = /* @__PURE__ */ new Set();\n for (let j = 0; j < block.messages.length; j++) {\n const message = block.messages[j];\n const isLastMessage = j === block.messages.length - 1;\n const { content } = message;\n for (let k = 0; k < content.length; k++) {\n const part = content[k];\n const isLastContentPart = k === content.length - 1;\n const cacheControl = (_f = validator.getCacheControl(part.providerOptions, {\n type: \"assistant message part\",\n canCache: true\n })) != null ? _f : isLastContentPart ? validator.getCacheControl(message.providerOptions, {\n type: \"assistant message\",\n canCache: true\n }) : void 0;\n switch (part.type) {\n case \"text\": {\n anthropicContent.push({\n type: \"text\",\n text: (\n // trim the last text part if it's the last message in the block\n // because Anthropic does not allow trailing whitespace\n // in pre-filled assistant responses\n isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text\n ),\n cache_control: cacheControl\n });\n break;\n }\n case \"reasoning\": {\n if (sendReasoning) {\n const reasoningMetadata = await parseProviderOptions({\n provider: \"anthropic\",\n providerOptions: part.providerOptions,\n schema: anthropicReasoningMetadataSchema\n });\n if (reasoningMetadata != null) {\n if (reasoningMetadata.signature != null) {\n validator.getCacheControl(part.providerOptions, {\n type: \"thinking block\",\n canCache: false\n });\n anthropicContent.push({\n type: \"thinking\",\n thinking: part.text,\n signature: reasoningMetadata.signature\n });\n } else if (reasoningMetadata.redactedData != null) {\n validator.getCacheControl(part.providerOptions, {\n type: \"redacted thinking block\",\n canCache: false\n });\n anthropicContent.push({\n type: \"redacted_thinking\",\n data: reasoningMetadata.redactedData\n });\n } else {\n warnings.push({\n type: \"other\",\n message: \"unsupported reasoning metadata\"\n });\n }\n } else {\n warnings.push({\n type: \"other\",\n message: \"unsupported reasoning metadata\"\n });\n }\n } else {\n warnings.push({\n type: \"other\",\n message: \"sending reasoning content is disabled for this model\"\n });\n }\n break;\n }\n case \"tool-call\": {\n if (part.providerExecuted) {\n const providerToolName = toolNameMapping.toProviderToolName(\n part.toolName\n );\n const isMcpToolUse = ((_h = (_g = part.providerOptions) == null ? void 0 : _g.anthropic) == null ? void 0 : _h.type) === \"mcp-tool-use\";\n if (isMcpToolUse) {\n mcpToolUseIds.add(part.toolCallId);\n const serverName = (_j = (_i = part.providerOptions) == null ? void 0 : _i.anthropic) == null ? void 0 : _j.serverName;\n if (serverName == null || typeof serverName !== \"string\") {\n warnings.push({\n type: \"other\",\n message: \"mcp tool use server name is required and must be a string\"\n });\n break;\n }\n anthropicContent.push({\n type: \"mcp_tool_use\",\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n server_name: serverName,\n cache_control: cacheControl\n });\n } else if (\n // code execution 20250825:\n providerToolName === \"code_execution\" && part.input != null && typeof part.input === \"object\" && \"type\" in part.input && typeof part.input.type === \"string\" && (part.input.type === \"bash_code_execution\" || part.input.type === \"text_editor_code_execution\")\n ) {\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: part.input.type,\n // map back to subtool name\n input: part.input,\n cache_control: cacheControl\n });\n } else if (\n // code execution 20250825 programmatic tool calling:\n // Strip the fake 'programmatic-tool-call' type before sending to Anthropic\n providerToolName === \"code_execution\" && part.input != null && typeof part.input === \"object\" && \"type\" in part.input && part.input.type === \"programmatic-tool-call\"\n ) {\n const { type: _, ...inputWithoutType } = part.input;\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: \"code_execution\",\n input: inputWithoutType,\n cache_control: cacheControl\n });\n } else {\n if (providerToolName === \"code_execution\" || // code execution 20250522\n providerToolName === \"web_fetch\" || providerToolName === \"web_search\") {\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: providerToolName,\n input: part.input,\n cache_control: cacheControl\n });\n } else if (providerToolName === \"tool_search_tool_regex\" || providerToolName === \"tool_search_tool_bm25\") {\n anthropicContent.push({\n type: \"server_tool_use\",\n id: part.toolCallId,\n name: providerToolName,\n input: part.input,\n cache_control: cacheControl\n });\n } else {\n warnings.push({\n type: \"other\",\n message: `provider executed tool call for tool ${part.toolName} is not supported`\n });\n }\n }\n break;\n }\n const callerOptions = (_k = part.providerOptions) == null ? void 0 : _k.anthropic;\n const caller = (callerOptions == null ? void 0 : callerOptions.caller) ? callerOptions.caller.type === \"code_execution_20250825\" && callerOptions.caller.toolId ? {\n type: \"code_execution_20250825\",\n tool_id: callerOptions.caller.toolId\n } : callerOptions.caller.type === \"direct\" ? { type: \"direct\" } : void 0 : void 0;\n anthropicContent.push({\n type: \"tool_use\",\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n ...caller && { caller },\n cache_control: cacheControl\n });\n break;\n }\n case \"tool-result\": {\n const providerToolName = toolNameMapping.toProviderToolName(\n part.toolName\n );\n if (mcpToolUseIds.has(part.toolCallId)) {\n const output = part.output;\n if (output.type !== \"json\" && output.type !== \"error-json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n anthropicContent.push({\n type: \"mcp_tool_result\",\n tool_use_id: part.toolCallId,\n is_error: output.type === \"error-json\",\n content: output.value,\n cache_control: cacheControl\n });\n } else if (providerToolName === \"code_execution\") {\n const output = part.output;\n if (output.type === \"error-text\" || output.type === \"error-json\") {\n let errorInfo = {};\n try {\n if (typeof output.value === \"string\") {\n errorInfo = JSON.parse(output.value);\n } else if (typeof output.value === \"object\" && output.value !== null) {\n errorInfo = output.value;\n }\n } catch (e) {\n }\n if (errorInfo.type === \"code_execution_tool_result_error\") {\n anthropicContent.push({\n type: \"code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"code_execution_tool_result_error\",\n error_code: (_l = errorInfo.errorCode) != null ? _l : \"unknown\"\n },\n cache_control: cacheControl\n });\n } else {\n anthropicContent.push({\n type: \"bash_code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n cache_control: cacheControl,\n content: {\n type: \"bash_code_execution_tool_result_error\",\n error_code: (_m = errorInfo.errorCode) != null ? _m : \"unknown\"\n }\n });\n }\n break;\n }\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n if (output.value == null || typeof output.value !== \"object\" || !(\"type\" in output.value) || typeof output.value.type !== \"string\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output value is not a valid code execution result for tool ${part.toolName}`\n });\n break;\n }\n if (output.value.type === \"code_execution_result\") {\n const codeExecutionOutput = await validateTypes2({\n value: output.value,\n schema: codeExecution_20250522OutputSchema\n });\n anthropicContent.push({\n type: \"code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: codeExecutionOutput.type,\n stdout: codeExecutionOutput.stdout,\n stderr: codeExecutionOutput.stderr,\n return_code: codeExecutionOutput.return_code,\n content: (_n = codeExecutionOutput.content) != null ? _n : []\n },\n cache_control: cacheControl\n });\n } else {\n const codeExecutionOutput = await validateTypes2({\n value: output.value,\n schema: codeExecution_20250825OutputSchema\n });\n if (codeExecutionOutput.type === \"code_execution_result\") {\n anthropicContent.push({\n type: \"code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: codeExecutionOutput.type,\n stdout: codeExecutionOutput.stdout,\n stderr: codeExecutionOutput.stderr,\n return_code: codeExecutionOutput.return_code,\n content: (_o = codeExecutionOutput.content) != null ? _o : []\n },\n cache_control: cacheControl\n });\n } else if (codeExecutionOutput.type === \"bash_code_execution_result\" || codeExecutionOutput.type === \"bash_code_execution_tool_result_error\") {\n anthropicContent.push({\n type: \"bash_code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n cache_control: cacheControl,\n content: codeExecutionOutput\n });\n } else {\n anthropicContent.push({\n type: \"text_editor_code_execution_tool_result\",\n tool_use_id: part.toolCallId,\n cache_control: cacheControl,\n content: codeExecutionOutput\n });\n }\n }\n break;\n }\n if (providerToolName === \"web_fetch\") {\n const output = part.output;\n if (output.type === \"error-json\") {\n let errorValue = {};\n try {\n if (typeof output.value === \"string\") {\n errorValue = JSON.parse(output.value);\n } else if (typeof output.value === \"object\" && output.value !== null) {\n errorValue = output.value;\n }\n } catch (e) {\n const extractedErrorCode = (_p = output.value) == null ? void 0 : _p.errorCode;\n errorValue = {\n errorCode: typeof extractedErrorCode === \"string\" ? extractedErrorCode : \"unknown\"\n };\n }\n anthropicContent.push({\n type: \"web_fetch_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"web_fetch_tool_result_error\",\n error_code: (_q = errorValue.errorCode) != null ? _q : \"unknown\"\n },\n cache_control: cacheControl\n });\n break;\n }\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n const webFetchOutput = await validateTypes2({\n value: output.value,\n schema: webFetch_20250910OutputSchema\n });\n anthropicContent.push({\n type: \"web_fetch_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"web_fetch_result\",\n url: webFetchOutput.url,\n retrieved_at: webFetchOutput.retrievedAt,\n content: {\n type: \"document\",\n title: webFetchOutput.content.title,\n citations: webFetchOutput.content.citations,\n source: {\n type: webFetchOutput.content.source.type,\n media_type: webFetchOutput.content.source.mediaType,\n data: webFetchOutput.content.source.data\n }\n }\n },\n cache_control: cacheControl\n });\n break;\n }\n if (providerToolName === \"web_search\") {\n const output = part.output;\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n const webSearchOutput = await validateTypes2({\n value: output.value,\n schema: webSearch_20250305OutputSchema\n });\n anthropicContent.push({\n type: \"web_search_tool_result\",\n tool_use_id: part.toolCallId,\n content: webSearchOutput.map((result) => ({\n url: result.url,\n title: result.title,\n page_age: result.pageAge,\n encrypted_content: result.encryptedContent,\n type: result.type\n })),\n cache_control: cacheControl\n });\n break;\n }\n if (providerToolName === \"tool_search_tool_regex\" || providerToolName === \"tool_search_tool_bm25\") {\n const output = part.output;\n if (output.type !== \"json\") {\n warnings.push({\n type: \"other\",\n message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`\n });\n break;\n }\n const toolSearchOutput = await validateTypes2({\n value: output.value,\n schema: toolSearchRegex_20251119OutputSchema\n });\n const toolReferences = toolSearchOutput.map((ref) => ({\n type: \"tool_reference\",\n tool_name: ref.toolName\n }));\n anthropicContent.push({\n type: \"tool_search_tool_result\",\n tool_use_id: part.toolCallId,\n content: {\n type: \"tool_search_tool_search_result\",\n tool_references: toolReferences\n },\n cache_control: cacheControl\n });\n break;\n }\n warnings.push({\n type: \"other\",\n message: `provider executed tool result for tool ${part.toolName} is not supported`\n });\n break;\n }\n }\n }\n }\n messages.push({ role: \"assistant\", content: anthropicContent });\n break;\n }\n default: {\n const _exhaustiveCheck = type;\n throw new Error(`content type: ${_exhaustiveCheck}`);\n }\n }\n }\n return {\n prompt: { system, messages },\n betas\n };\n}\nfunction groupIntoBlocks(prompt) {\n const blocks = [];\n let currentBlock = void 0;\n for (const message of prompt) {\n const { role } = message;\n switch (role) {\n case \"system\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"system\") {\n currentBlock = { type: \"system\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n case \"assistant\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"assistant\") {\n currentBlock = { type: \"assistant\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n case \"user\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"user\") {\n currentBlock = { type: \"user\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n case \"tool\": {\n if ((currentBlock == null ? void 0 : currentBlock.type) !== \"user\") {\n currentBlock = { type: \"user\", messages: [] };\n blocks.push(currentBlock);\n }\n currentBlock.messages.push(message);\n break;\n }\n default: {\n const _exhaustiveCheck = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n return blocks;\n}\n\n// src/map-anthropic-stop-reason.ts\nfunction mapAnthropicStopReason({\n finishReason,\n isJsonResponseFromTool\n}) {\n switch (finishReason) {\n case \"pause_turn\":\n case \"end_turn\":\n case \"stop_sequence\":\n return \"stop\";\n case \"refusal\":\n return \"content-filter\";\n case \"tool_use\":\n return isJsonResponseFromTool ? \"stop\" : \"tool-calls\";\n case \"max_tokens\":\n case \"model_context_window_exceeded\":\n return \"length\";\n default:\n return \"other\";\n }\n}\n\n// src/anthropic-messages-language-model.ts\nfunction createCitationSource(citation, citationDocuments, generateId3) {\n var _a;\n if (citation.type === \"web_search_result_location\") {\n return {\n type: \"source\",\n sourceType: \"url\",\n id: generateId3(),\n url: citation.url,\n title: citation.title,\n providerMetadata: {\n anthropic: {\n citedText: citation.cited_text,\n encryptedIndex: citation.encrypted_index\n }\n }\n };\n }\n if (citation.type !== \"page_location\" && citation.type !== \"char_location\") {\n return;\n }\n const documentInfo = citationDocuments[citation.document_index];\n if (!documentInfo) {\n return;\n }\n return {\n type: \"source\",\n sourceType: \"document\",\n id: generateId3(),\n mediaType: documentInfo.mediaType,\n title: (_a = citation.document_title) != null ? _a : documentInfo.title,\n filename: documentInfo.filename,\n providerMetadata: {\n anthropic: citation.type === \"page_location\" ? {\n citedText: citation.cited_text,\n startPageNumber: citation.start_page_number,\n endPageNumber: citation.end_page_number\n } : {\n citedText: citation.cited_text,\n startCharIndex: citation.start_char_index,\n endCharIndex: citation.end_char_index\n }\n }\n };\n}\nvar AnthropicMessagesLanguageModel = class {\n constructor(modelId, config) {\n this.specificationVersion = \"v3\";\n var _a;\n this.modelId = modelId;\n this.config = config;\n this.generateId = (_a = config.generateId) != null ? _a : generateId;\n }\n supportsUrl(url) {\n return url.protocol === \"https:\";\n }\n get provider() {\n return this.config.provider;\n }\n /**\n * Extracts the dynamic provider name from the config.provider string.\n * e.g., 'my-custom-anthropic.messages' -> 'my-custom-anthropic'\n */\n get providerOptionsName() {\n const provider = this.config.provider;\n const dotIndex = provider.indexOf(\".\");\n return dotIndex === -1 ? provider : provider.substring(0, dotIndex);\n }\n get supportedUrls() {\n var _a, _b, _c;\n return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};\n }\n async getArgs({\n userSuppliedBetas,\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n tools,\n toolChoice,\n providerOptions,\n stream\n }) {\n var _a, _b, _c, _d, _e, _f;\n const warnings = [];\n if (frequencyPenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"frequencyPenalty\" });\n }\n if (presencePenalty != null) {\n warnings.push({ type: \"unsupported\", feature: \"presencePenalty\" });\n }\n if (seed != null) {\n warnings.push({ type: \"unsupported\", feature: \"seed\" });\n }\n if (temperature != null && temperature > 1) {\n warnings.push({\n type: \"unsupported\",\n feature: \"temperature\",\n details: `${temperature} exceeds anthropic maximum of 1.0. clamped to 1.0`\n });\n temperature = 1;\n } else if (temperature != null && temperature < 0) {\n warnings.push({\n type: \"unsupported\",\n feature: \"temperature\",\n details: `${temperature} is below anthropic minimum of 0. clamped to 0`\n });\n temperature = 0;\n }\n if ((responseFormat == null ? void 0 : responseFormat.type) === \"json\") {\n if (responseFormat.schema == null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"responseFormat\",\n details: \"JSON response format requires a schema. The response format is ignored.\"\n });\n }\n }\n const providerOptionsName = this.providerOptionsName;\n const canonicalOptions = await parseProviderOptions2({\n provider: \"anthropic\",\n providerOptions,\n schema: anthropicProviderOptions\n });\n const customProviderOptions = providerOptionsName !== \"anthropic\" ? await parseProviderOptions2({\n provider: providerOptionsName,\n providerOptions,\n schema: anthropicProviderOptions\n }) : null;\n const usedCustomProviderKey = customProviderOptions != null;\n const anthropicOptions = Object.assign(\n {},\n canonicalOptions != null ? canonicalOptions : {},\n customProviderOptions != null ? customProviderOptions : {}\n );\n const {\n maxOutputTokens: maxOutputTokensForModel,\n supportsStructuredOutput: modelSupportsStructuredOutput,\n isKnownModel\n } = getModelCapabilities(this.modelId);\n const supportsStructuredOutput = ((_a = this.config.supportsNativeStructuredOutput) != null ? _a : true) && modelSupportsStructuredOutput;\n const structureOutputMode = (_b = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _b : \"auto\";\n const useStructuredOutput = structureOutputMode === \"outputFormat\" || structureOutputMode === \"auto\" && supportsStructuredOutput;\n const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null && !useStructuredOutput ? {\n type: \"function\",\n name: \"json\",\n description: \"Respond with a JSON object.\",\n inputSchema: responseFormat.schema\n } : void 0;\n const contextManagement = anthropicOptions == null ? void 0 : anthropicOptions.contextManagement;\n const cacheControlValidator = new CacheControlValidator();\n const toolNameMapping = createToolNameMapping({\n tools,\n providerToolNames: {\n \"anthropic.code_execution_20250522\": \"code_execution\",\n \"anthropic.code_execution_20250825\": \"code_execution\",\n \"anthropic.computer_20241022\": \"computer\",\n \"anthropic.computer_20250124\": \"computer\",\n \"anthropic.text_editor_20241022\": \"str_replace_editor\",\n \"anthropic.text_editor_20250124\": \"str_replace_editor\",\n \"anthropic.text_editor_20250429\": \"str_replace_based_edit_tool\",\n \"anthropic.text_editor_20250728\": \"str_replace_based_edit_tool\",\n \"anthropic.bash_20241022\": \"bash\",\n \"anthropic.bash_20250124\": \"bash\",\n \"anthropic.memory_20250818\": \"memory\",\n \"anthropic.web_search_20250305\": \"web_search\",\n \"anthropic.web_fetch_20250910\": \"web_fetch\",\n \"anthropic.tool_search_regex_20251119\": \"tool_search_tool_regex\",\n \"anthropic.tool_search_bm25_20251119\": \"tool_search_tool_bm25\"\n }\n });\n const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({\n prompt,\n sendReasoning: (_c = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _c : true,\n warnings,\n cacheControlValidator,\n toolNameMapping\n });\n const isThinking = ((_d = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _d.type) === \"enabled\";\n let thinkingBudget = (_e = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _e.budgetTokens;\n const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel;\n const baseArgs = {\n // model id:\n model: this.modelId,\n // standardized settings:\n max_tokens: maxTokens,\n temperature,\n top_k: topK,\n top_p: topP,\n stop_sequences: stopSequences,\n // provider specific settings:\n ...isThinking && {\n thinking: { type: \"enabled\", budget_tokens: thinkingBudget }\n },\n ...(anthropicOptions == null ? void 0 : anthropicOptions.effort) && {\n output_config: { effort: anthropicOptions.effort }\n },\n // structured output:\n ...useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null && {\n output_format: {\n type: \"json_schema\",\n schema: responseFormat.schema\n }\n },\n // mcp servers:\n ...(anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && {\n mcp_servers: anthropicOptions.mcpServers.map((server) => ({\n type: server.type,\n name: server.name,\n url: server.url,\n authorization_token: server.authorizationToken,\n tool_configuration: server.toolConfiguration ? {\n allowed_tools: server.toolConfiguration.allowedTools,\n enabled: server.toolConfiguration.enabled\n } : void 0\n }))\n },\n // container: For programmatic tool calling (just an ID string) or agent skills (object with id and skills)\n ...(anthropicOptions == null ? void 0 : anthropicOptions.container) && {\n container: anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0 ? (\n // Object format when skills are provided (agent skills feature)\n {\n id: anthropicOptions.container.id,\n skills: anthropicOptions.container.skills.map((skill) => ({\n type: skill.type,\n skill_id: skill.skillId,\n version: skill.version\n }))\n }\n ) : (\n // String format for container ID only (programmatic tool calling)\n anthropicOptions.container.id\n )\n },\n // prompt:\n system: messagesPrompt.system,\n messages: messagesPrompt.messages,\n ...contextManagement && {\n context_management: {\n edits: contextManagement.edits.map((edit) => {\n const strategy = edit.type;\n switch (strategy) {\n case \"clear_tool_uses_20250919\":\n return {\n type: edit.type,\n ...edit.trigger !== void 0 && {\n trigger: edit.trigger\n },\n ...edit.keep !== void 0 && { keep: edit.keep },\n ...edit.clearAtLeast !== void 0 && {\n clear_at_least: edit.clearAtLeast\n },\n ...edit.clearToolInputs !== void 0 && {\n clear_tool_inputs: edit.clearToolInputs\n },\n ...edit.excludeTools !== void 0 && {\n exclude_tools: edit.excludeTools\n }\n };\n case \"clear_thinking_20251015\":\n return {\n type: edit.type,\n ...edit.keep !== void 0 && { keep: edit.keep }\n };\n default:\n warnings.push({\n type: \"other\",\n message: `Unknown context management strategy: ${strategy}`\n });\n return void 0;\n }\n }).filter((edit) => edit !== void 0)\n }\n }\n };\n if (isThinking) {\n if (thinkingBudget == null) {\n warnings.push({\n type: \"compatibility\",\n feature: \"extended thinking\",\n details: \"thinking budget is required when thinking is enabled. using default budget of 1024 tokens.\"\n });\n baseArgs.thinking = {\n type: \"enabled\",\n budget_tokens: 1024\n };\n thinkingBudget = 1024;\n }\n if (baseArgs.temperature != null) {\n baseArgs.temperature = void 0;\n warnings.push({\n type: \"unsupported\",\n feature: \"temperature\",\n details: \"temperature is not supported when thinking is enabled\"\n });\n }\n if (topK != null) {\n baseArgs.top_k = void 0;\n warnings.push({\n type: \"unsupported\",\n feature: \"topK\",\n details: \"topK is not supported when thinking is enabled\"\n });\n }\n if (topP != null) {\n baseArgs.top_p = void 0;\n warnings.push({\n type: \"unsupported\",\n feature: \"topP\",\n details: \"topP is not supported when thinking is enabled\"\n });\n }\n baseArgs.max_tokens = maxTokens + (thinkingBudget != null ? thinkingBudget : 0);\n } else {\n if (topP != null && temperature != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"topP\",\n details: `topP is not supported when temperature is set. topP is ignored.`\n });\n baseArgs.top_p = void 0;\n }\n }\n if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) {\n if (maxOutputTokens != null) {\n warnings.push({\n type: \"unsupported\",\n feature: \"maxOutputTokens\",\n details: `${baseArgs.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${maxOutputTokensForModel} max output tokens. The max output tokens have been limited to ${maxOutputTokensForModel}.`\n });\n }\n baseArgs.max_tokens = maxOutputTokensForModel;\n }\n if ((anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0) {\n betas.add(\"mcp-client-2025-04-04\");\n }\n if (contextManagement) {\n betas.add(\"context-management-2025-06-27\");\n }\n if ((anthropicOptions == null ? void 0 : anthropicOptions.container) && anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0) {\n betas.add(\"code-execution-2025-08-25\");\n betas.add(\"skills-2025-10-02\");\n betas.add(\"files-api-2025-04-14\");\n if (!(tools == null ? void 0 : tools.some(\n (tool) => tool.type === \"provider\" && tool.id === \"anthropic.code_execution_20250825\"\n ))) {\n warnings.push({\n type: \"other\",\n message: \"code execution tool is required when using skills\"\n });\n }\n }\n if (anthropicOptions == null ? void 0 : anthropicOptions.effort) {\n betas.add(\"effort-2025-11-24\");\n }\n if (stream && ((_f = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _f : true)) {\n betas.add(\"fine-grained-tool-streaming-2025-05-14\");\n }\n const usingNativeOutputFormat = useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === \"json\" && responseFormat.schema != null;\n if (usingNativeOutputFormat) {\n betas.add(\"structured-outputs-2025-11-13\");\n }\n const {\n tools: anthropicTools2,\n toolChoice: anthropicToolChoice,\n toolWarnings,\n betas: toolsBetas\n } = await prepareTools(\n jsonResponseTool != null ? {\n tools: [...tools != null ? tools : [], jsonResponseTool],\n toolChoice: { type: \"required\" },\n disableParallelToolUse: true,\n cacheControlValidator,\n supportsStructuredOutput: false\n } : {\n tools: tools != null ? tools : [],\n toolChoice,\n disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,\n cacheControlValidator,\n supportsStructuredOutput\n }\n );\n const cacheWarnings = cacheControlValidator.getWarnings();\n return {\n args: {\n ...baseArgs,\n tools: anthropicTools2,\n tool_choice: anthropicToolChoice,\n stream: stream === true ? true : void 0\n // do not send when not streaming\n },\n warnings: [...warnings, ...toolWarnings, ...cacheWarnings],\n betas: /* @__PURE__ */ new Set([...betas, ...toolsBetas, ...userSuppliedBetas]),\n usesJsonResponseTool: jsonResponseTool != null,\n toolNameMapping,\n providerOptionsName,\n usedCustomProviderKey\n };\n }\n async getHeaders({\n betas,\n headers\n }) {\n return combineHeaders(\n await resolve(this.config.headers),\n headers,\n betas.size > 0 ? { \"anthropic-beta\": Array.from(betas).join(\",\") } : {}\n );\n }\n async getBetasFromHeaders(requestHeaders) {\n var _a, _b;\n const configHeaders = await resolve(this.config.headers);\n const configBetaHeader = (_a = configHeaders[\"anthropic-beta\"]) != null ? _a : \"\";\n const requestBetaHeader = (_b = requestHeaders == null ? void 0 : requestHeaders[\"anthropic-beta\"]) != null ? _b : \"\";\n return new Set(\n [\n ...configBetaHeader.toLowerCase().split(\",\"),\n ...requestBetaHeader.toLowerCase().split(\",\")\n ].map((beta) => beta.trim()).filter((beta) => beta !== \"\")\n );\n }\n buildRequestUrl(isStreaming) {\n var _a, _b, _c;\n return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;\n }\n transformRequestBody(args) {\n var _a, _b, _c;\n return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;\n }\n extractCitationDocuments(prompt) {\n const isCitationPart = (part) => {\n var _a, _b;\n if (part.type !== \"file\") {\n return false;\n }\n if (part.mediaType !== \"application/pdf\" && part.mediaType !== \"text/plain\") {\n return false;\n }\n const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;\n const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;\n return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;\n };\n return prompt.filter((message) => message.role === \"user\").flatMap((message) => message.content).filter(isCitationPart).map((part) => {\n var _a;\n const filePart = part;\n return {\n title: (_a = filePart.filename) != null ? _a : \"Untitled Document\",\n filename: filePart.filename,\n mediaType: filePart.mediaType\n };\n });\n }\n async doGenerate(options) {\n var _a, _b, _c, _d, _e, _f;\n const {\n args,\n warnings,\n betas,\n usesJsonResponseTool,\n toolNameMapping,\n providerOptionsName,\n usedCustomProviderKey\n } = await this.getArgs({\n ...options,\n stream: false,\n userSuppliedBetas: await this.getBetasFromHeaders(options.headers)\n });\n const citationDocuments = [\n ...this.extractCitationDocuments(options.prompt)\n ];\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse\n } = await postJsonToApi({\n url: this.buildRequestUrl(false),\n headers: await this.getHeaders({ betas, headers: options.headers }),\n body: this.transformRequestBody(args),\n failedResponseHandler: anthropicFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n anthropicMessagesResponseSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n const content = [];\n const mcpToolCalls = {};\n const serverToolCalls = {};\n let isJsonResponseFromTool = false;\n for (const part of response.content) {\n switch (part.type) {\n case \"text\": {\n if (!usesJsonResponseTool) {\n content.push({ type: \"text\", text: part.text });\n if (part.citations) {\n for (const citation of part.citations) {\n const source = createCitationSource(\n citation,\n citationDocuments,\n this.generateId\n );\n if (source) {\n content.push(source);\n }\n }\n }\n }\n break;\n }\n case \"thinking\": {\n content.push({\n type: \"reasoning\",\n text: part.thinking,\n providerMetadata: {\n anthropic: {\n signature: part.signature\n }\n }\n });\n break;\n }\n case \"redacted_thinking\": {\n content.push({\n type: \"reasoning\",\n text: \"\",\n providerMetadata: {\n anthropic: {\n redactedData: part.data\n }\n }\n });\n break;\n }\n case \"tool_use\": {\n const isJsonResponseTool = usesJsonResponseTool && part.name === \"json\";\n if (isJsonResponseTool) {\n isJsonResponseFromTool = true;\n content.push({\n type: \"text\",\n text: JSON.stringify(part.input)\n });\n } else {\n const caller = part.caller;\n const callerInfo = caller ? {\n type: caller.type,\n toolId: \"tool_id\" in caller ? caller.tool_id : void 0\n } : void 0;\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: JSON.stringify(part.input),\n ...callerInfo && {\n providerMetadata: {\n anthropic: {\n caller: callerInfo\n }\n }\n }\n });\n }\n break;\n }\n case \"server_tool_use\": {\n if (part.name === \"text_editor_code_execution\" || part.name === \"bash_code_execution\") {\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n input: JSON.stringify({ type: part.name, ...part.input }),\n providerExecuted: true\n });\n } else if (part.name === \"web_search\" || part.name === \"code_execution\" || part.name === \"web_fetch\") {\n const inputToSerialize = part.name === \"code_execution\" && part.input != null && typeof part.input === \"object\" && \"code\" in part.input && !(\"type\" in part.input) ? { type: \"programmatic-tool-call\", ...part.input } : part.input;\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: toolNameMapping.toCustomToolName(part.name),\n input: JSON.stringify(inputToSerialize),\n providerExecuted: true\n });\n } else if (part.name === \"tool_search_tool_regex\" || part.name === \"tool_search_tool_bm25\") {\n serverToolCalls[part.id] = part.name;\n content.push({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: toolNameMapping.toCustomToolName(part.name),\n input: JSON.stringify(part.input),\n providerExecuted: true\n });\n }\n break;\n }\n case \"mcp_tool_use\": {\n mcpToolCalls[part.id] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: JSON.stringify(part.input),\n providerExecuted: true,\n dynamic: true,\n providerMetadata: {\n anthropic: {\n type: \"mcp-tool-use\",\n serverName: part.server_name\n }\n }\n };\n content.push(mcpToolCalls[part.id]);\n break;\n }\n case \"mcp_tool_result\": {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: mcpToolCalls[part.tool_use_id].toolName,\n isError: part.is_error,\n result: part.content,\n dynamic: true,\n providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata\n });\n break;\n }\n case \"web_fetch_tool_result\": {\n if (part.content.type === \"web_fetch_result\") {\n citationDocuments.push({\n title: (_a = part.content.content.title) != null ? _a : part.content.url,\n mediaType: part.content.content.source.media_type\n });\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n result: {\n type: \"web_fetch_result\",\n url: part.content.url,\n retrievedAt: part.content.retrieved_at,\n content: {\n type: part.content.content.type,\n title: part.content.content.title,\n citations: part.content.content.citations,\n source: {\n type: part.content.content.source.type,\n mediaType: part.content.content.source.media_type,\n data: part.content.content.source.data\n }\n }\n }\n });\n } else if (part.content.type === \"web_fetch_tool_result_error\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n isError: true,\n result: {\n type: \"web_fetch_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n case \"web_search_tool_result\": {\n if (Array.isArray(part.content)) {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n result: part.content.map((result) => {\n var _a2;\n return {\n url: result.url,\n title: result.title,\n pageAge: (_a2 = result.page_age) != null ? _a2 : null,\n encryptedContent: result.encrypted_content,\n type: result.type\n };\n })\n });\n for (const result of part.content) {\n content.push({\n type: \"source\",\n sourceType: \"url\",\n id: this.generateId(),\n url: result.url,\n title: result.title,\n providerMetadata: {\n anthropic: {\n pageAge: (_b = result.page_age) != null ? _b : null\n }\n }\n });\n }\n } else {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n isError: true,\n result: {\n type: \"web_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n // code execution 20250522:\n case \"code_execution_tool_result\": {\n if (part.content.type === \"code_execution_result\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: {\n type: part.content.type,\n stdout: part.content.stdout,\n stderr: part.content.stderr,\n return_code: part.content.return_code,\n content: (_c = part.content.content) != null ? _c : []\n }\n });\n } else if (part.content.type === \"code_execution_tool_result_error\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n isError: true,\n result: {\n type: \"code_execution_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n // code execution 20250825:\n case \"bash_code_execution_tool_result\":\n case \"text_editor_code_execution_tool_result\": {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: part.content\n });\n break;\n }\n // tool search tool results:\n case \"tool_search_tool_result\": {\n let providerToolName = serverToolCalls[part.tool_use_id];\n if (providerToolName == null) {\n const bm25CustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_bm25\"\n );\n const regexCustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_regex\"\n );\n if (bm25CustomName !== \"tool_search_tool_bm25\") {\n providerToolName = \"tool_search_tool_bm25\";\n } else if (regexCustomName !== \"tool_search_tool_regex\") {\n providerToolName = \"tool_search_tool_regex\";\n } else {\n providerToolName = \"tool_search_tool_regex\";\n }\n }\n if (part.content.type === \"tool_search_tool_search_result\") {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n result: part.content.tool_references.map((ref) => ({\n type: ref.type,\n toolName: ref.tool_name\n }))\n });\n } else {\n content.push({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n isError: true,\n result: {\n type: \"tool_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n break;\n }\n }\n }\n return {\n content,\n finishReason: {\n unified: mapAnthropicStopReason({\n finishReason: response.stop_reason,\n isJsonResponseFromTool\n }),\n raw: (_d = response.stop_reason) != null ? _d : void 0\n },\n usage: convertAnthropicMessagesUsage(response.usage),\n request: { body: args },\n response: {\n id: (_e = response.id) != null ? _e : void 0,\n modelId: (_f = response.model) != null ? _f : void 0,\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n providerMetadata: (() => {\n var _a2, _b2, _c2, _d2, _e2;\n const anthropicMetadata = {\n usage: response.usage,\n cacheCreationInputTokens: (_a2 = response.usage.cache_creation_input_tokens) != null ? _a2 : null,\n stopSequence: (_b2 = response.stop_sequence) != null ? _b2 : null,\n container: response.container ? {\n expiresAt: response.container.expires_at,\n id: response.container.id,\n skills: (_d2 = (_c2 = response.container.skills) == null ? void 0 : _c2.map((skill) => ({\n type: skill.type,\n skillId: skill.skill_id,\n version: skill.version\n }))) != null ? _d2 : null\n } : null,\n contextManagement: (_e2 = mapAnthropicResponseContextManagement(\n response.context_management\n )) != null ? _e2 : null\n };\n const providerMetadata = {\n anthropic: anthropicMetadata\n };\n if (usedCustomProviderKey && providerOptionsName !== \"anthropic\") {\n providerMetadata[providerOptionsName] = anthropicMetadata;\n }\n return providerMetadata;\n })()\n };\n }\n async doStream(options) {\n var _a, _b;\n const {\n args: body,\n warnings,\n betas,\n usesJsonResponseTool,\n toolNameMapping,\n providerOptionsName,\n usedCustomProviderKey\n } = await this.getArgs({\n ...options,\n stream: true,\n userSuppliedBetas: await this.getBetasFromHeaders(options.headers)\n });\n const citationDocuments = [\n ...this.extractCitationDocuments(options.prompt)\n ];\n const url = this.buildRequestUrl(true);\n const { responseHeaders, value: response } = await postJsonToApi({\n url,\n headers: await this.getHeaders({ betas, headers: options.headers }),\n body: this.transformRequestBody(body),\n failedResponseHandler: anthropicFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n anthropicMessagesChunkSchema\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch\n });\n let finishReason = {\n unified: \"other\",\n raw: void 0\n };\n const usage = {\n input_tokens: 0,\n output_tokens: 0,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0\n };\n const contentBlocks = {};\n const mcpToolCalls = {};\n const serverToolCalls = {};\n let contextManagement = null;\n let rawUsage = void 0;\n let cacheCreationInputTokens = null;\n let stopSequence = null;\n let container = null;\n let isJsonResponseFromTool = false;\n let blockType = void 0;\n const generateId3 = this.generateId;\n const transformedStream = response.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings });\n },\n transform(chunk, controller) {\n var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;\n if (options.includeRawChunks) {\n controller.enqueue({ type: \"raw\", rawValue: chunk.rawValue });\n }\n if (!chunk.success) {\n controller.enqueue({ type: \"error\", error: chunk.error });\n return;\n }\n const value = chunk.value;\n switch (value.type) {\n case \"ping\": {\n return;\n }\n case \"content_block_start\": {\n const part = value.content_block;\n const contentBlockType = part.type;\n blockType = contentBlockType;\n switch (contentBlockType) {\n case \"text\": {\n if (usesJsonResponseTool) {\n return;\n }\n contentBlocks[value.index] = { type: \"text\" };\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n return;\n }\n case \"thinking\": {\n contentBlocks[value.index] = { type: \"reasoning\" };\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index)\n });\n return;\n }\n case \"redacted_thinking\": {\n contentBlocks[value.index] = { type: \"reasoning\" };\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(value.index),\n providerMetadata: {\n anthropic: {\n redactedData: part.data\n }\n }\n });\n return;\n }\n case \"tool_use\": {\n const isJsonResponseTool = usesJsonResponseTool && part.name === \"json\";\n if (isJsonResponseTool) {\n isJsonResponseFromTool = true;\n contentBlocks[value.index] = { type: \"text\" };\n controller.enqueue({\n type: \"text-start\",\n id: String(value.index)\n });\n } else {\n const caller = part.caller;\n const callerInfo = caller ? {\n type: caller.type,\n toolId: \"tool_id\" in caller ? caller.tool_id : void 0\n } : void 0;\n const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0;\n const initialInput = hasNonEmptyInput ? JSON.stringify(part.input) : \"\";\n contentBlocks[value.index] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: initialInput,\n firstDelta: initialInput.length === 0,\n ...callerInfo && { caller: callerInfo }\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: part.name\n });\n }\n return;\n }\n case \"server_tool_use\": {\n if ([\n \"web_fetch\",\n \"web_search\",\n // code execution 20250825:\n \"code_execution\",\n // code execution 20250825 text editor:\n \"text_editor_code_execution\",\n // code execution 20250825 bash:\n \"bash_code_execution\"\n ].includes(part.name)) {\n const providerToolName = part.name === \"text_editor_code_execution\" || part.name === \"bash_code_execution\" ? \"code_execution\" : part.name;\n const customToolName = toolNameMapping.toCustomToolName(providerToolName);\n contentBlocks[value.index] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: customToolName,\n input: \"\",\n providerExecuted: true,\n firstDelta: true,\n providerToolName: part.name\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: customToolName,\n providerExecuted: true\n });\n } else if (part.name === \"tool_search_tool_regex\" || part.name === \"tool_search_tool_bm25\") {\n serverToolCalls[part.id] = part.name;\n const customToolName = toolNameMapping.toCustomToolName(\n part.name\n );\n contentBlocks[value.index] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: customToolName,\n input: \"\",\n providerExecuted: true,\n firstDelta: true,\n providerToolName: part.name\n };\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: customToolName,\n providerExecuted: true\n });\n }\n return;\n }\n case \"web_fetch_tool_result\": {\n if (part.content.type === \"web_fetch_result\") {\n citationDocuments.push({\n title: (_a2 = part.content.content.title) != null ? _a2 : part.content.url,\n mediaType: part.content.content.source.media_type\n });\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n result: {\n type: \"web_fetch_result\",\n url: part.content.url,\n retrievedAt: part.content.retrieved_at,\n content: {\n type: part.content.content.type,\n title: part.content.content.title,\n citations: part.content.content.citations,\n source: {\n type: part.content.content.source.type,\n mediaType: part.content.content.source.media_type,\n data: part.content.content.source.data\n }\n }\n }\n });\n } else if (part.content.type === \"web_fetch_tool_result_error\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_fetch\"),\n isError: true,\n result: {\n type: \"web_fetch_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n case \"web_search_tool_result\": {\n if (Array.isArray(part.content)) {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n result: part.content.map((result) => {\n var _a3;\n return {\n url: result.url,\n title: result.title,\n pageAge: (_a3 = result.page_age) != null ? _a3 : null,\n encryptedContent: result.encrypted_content,\n type: result.type\n };\n })\n });\n for (const result of part.content) {\n controller.enqueue({\n type: \"source\",\n sourceType: \"url\",\n id: generateId3(),\n url: result.url,\n title: result.title,\n providerMetadata: {\n anthropic: {\n pageAge: (_b2 = result.page_age) != null ? _b2 : null\n }\n }\n });\n }\n } else {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"web_search\"),\n isError: true,\n result: {\n type: \"web_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n // code execution 20250522:\n case \"code_execution_tool_result\": {\n if (part.content.type === \"code_execution_result\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: {\n type: part.content.type,\n stdout: part.content.stdout,\n stderr: part.content.stderr,\n return_code: part.content.return_code,\n content: (_c = part.content.content) != null ? _c : []\n }\n });\n } else if (part.content.type === \"code_execution_tool_result_error\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n isError: true,\n result: {\n type: \"code_execution_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n // code execution 20250825:\n case \"bash_code_execution_tool_result\":\n case \"text_editor_code_execution_tool_result\": {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(\"code_execution\"),\n result: part.content\n });\n return;\n }\n // tool search tool results:\n case \"tool_search_tool_result\": {\n let providerToolName = serverToolCalls[part.tool_use_id];\n if (providerToolName == null) {\n const bm25CustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_bm25\"\n );\n const regexCustomName = toolNameMapping.toCustomToolName(\n \"tool_search_tool_regex\"\n );\n if (bm25CustomName !== \"tool_search_tool_bm25\") {\n providerToolName = \"tool_search_tool_bm25\";\n } else if (regexCustomName !== \"tool_search_tool_regex\") {\n providerToolName = \"tool_search_tool_regex\";\n } else {\n providerToolName = \"tool_search_tool_regex\";\n }\n }\n if (part.content.type === \"tool_search_tool_search_result\") {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n result: part.content.tool_references.map((ref) => ({\n type: ref.type,\n toolName: ref.tool_name\n }))\n });\n } else {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: toolNameMapping.toCustomToolName(providerToolName),\n isError: true,\n result: {\n type: \"tool_search_tool_result_error\",\n errorCode: part.content.error_code\n }\n });\n }\n return;\n }\n case \"mcp_tool_use\": {\n mcpToolCalls[part.id] = {\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: JSON.stringify(part.input),\n providerExecuted: true,\n dynamic: true,\n providerMetadata: {\n anthropic: {\n type: \"mcp-tool-use\",\n serverName: part.server_name\n }\n }\n };\n controller.enqueue(mcpToolCalls[part.id]);\n return;\n }\n case \"mcp_tool_result\": {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: part.tool_use_id,\n toolName: mcpToolCalls[part.tool_use_id].toolName,\n isError: part.is_error,\n result: part.content,\n dynamic: true,\n providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata\n });\n return;\n }\n default: {\n const _exhaustiveCheck = contentBlockType;\n throw new Error(\n `Unsupported content block type: ${_exhaustiveCheck}`\n );\n }\n }\n }\n case \"content_block_stop\": {\n if (contentBlocks[value.index] != null) {\n const contentBlock = contentBlocks[value.index];\n switch (contentBlock.type) {\n case \"text\": {\n controller.enqueue({\n type: \"text-end\",\n id: String(value.index)\n });\n break;\n }\n case \"reasoning\": {\n controller.enqueue({\n type: \"reasoning-end\",\n id: String(value.index)\n });\n break;\n }\n case \"tool-call\":\n const isJsonResponseTool = usesJsonResponseTool && contentBlock.toolName === \"json\";\n if (!isJsonResponseTool) {\n controller.enqueue({\n type: \"tool-input-end\",\n id: contentBlock.toolCallId\n });\n let finalInput = contentBlock.input === \"\" ? \"{}\" : contentBlock.input;\n if (contentBlock.providerToolName === \"code_execution\") {\n try {\n const parsed = JSON.parse(finalInput);\n if (parsed != null && typeof parsed === \"object\" && \"code\" in parsed && !(\"type\" in parsed)) {\n finalInput = JSON.stringify({\n type: \"programmatic-tool-call\",\n ...parsed\n });\n }\n } catch (e) {\n }\n }\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: contentBlock.toolCallId,\n toolName: contentBlock.toolName,\n input: finalInput,\n providerExecuted: contentBlock.providerExecuted,\n ...contentBlock.caller && {\n providerMetadata: {\n anthropic: {\n caller: contentBlock.caller\n }\n }\n }\n });\n }\n break;\n }\n delete contentBlocks[value.index];\n }\n blockType = void 0;\n return;\n }\n case \"content_block_delta\": {\n const deltaType = value.delta.type;\n switch (deltaType) {\n case \"text_delta\": {\n if (usesJsonResponseTool) {\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta: value.delta.text\n });\n return;\n }\n case \"thinking_delta\": {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: value.delta.thinking\n });\n return;\n }\n case \"signature_delta\": {\n if (blockType === \"thinking\") {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(value.index),\n delta: \"\",\n providerMetadata: {\n anthropic: {\n signature: value.delta.signature\n }\n }\n });\n }\n return;\n }\n case \"input_json_delta\": {\n const contentBlock = contentBlocks[value.index];\n let delta = value.delta.partial_json;\n if (delta.length === 0) {\n return;\n }\n if (isJsonResponseFromTool) {\n if ((contentBlock == null ? void 0 : contentBlock.type) !== \"text\") {\n return;\n }\n controller.enqueue({\n type: \"text-delta\",\n id: String(value.index),\n delta\n });\n } else {\n if ((contentBlock == null ? void 0 : contentBlock.type) !== \"tool-call\") {\n return;\n }\n if (contentBlock.firstDelta && (contentBlock.providerToolName === \"bash_code_execution\" || contentBlock.providerToolName === \"text_editor_code_execution\")) {\n delta = `{\"type\": \"${contentBlock.providerToolName}\",${delta.substring(1)}`;\n }\n controller.enqueue({\n type: \"tool-input-delta\",\n id: contentBlock.toolCallId,\n delta\n });\n contentBlock.input += delta;\n contentBlock.firstDelta = false;\n }\n return;\n }\n case \"citations_delta\": {\n const citation = value.delta.citation;\n const source = createCitationSource(\n citation,\n citationDocuments,\n generateId3\n );\n if (source) {\n controller.enqueue(source);\n }\n return;\n }\n default: {\n const _exhaustiveCheck = deltaType;\n throw new Error(\n `Unsupported delta type: ${_exhaustiveCheck}`\n );\n }\n }\n }\n case \"message_start\": {\n usage.input_tokens = value.message.usage.input_tokens;\n usage.cache_read_input_tokens = (_d = value.message.usage.cache_read_input_tokens) != null ? _d : 0;\n usage.cache_creation_input_tokens = (_e = value.message.usage.cache_creation_input_tokens) != null ? _e : 0;\n rawUsage = {\n ...value.message.usage\n };\n cacheCreationInputTokens = (_f = value.message.usage.cache_creation_input_tokens) != null ? _f : null;\n if (value.message.container != null) {\n container = {\n expiresAt: value.message.container.expires_at,\n id: value.message.container.id,\n skills: null\n };\n }\n if (value.message.stop_reason != null) {\n finishReason = {\n unified: mapAnthropicStopReason({\n finishReason: value.message.stop_reason,\n isJsonResponseFromTool\n }),\n raw: value.message.stop_reason\n };\n }\n controller.enqueue({\n type: \"response-metadata\",\n id: (_g = value.message.id) != null ? _g : void 0,\n modelId: (_h = value.message.model) != null ? _h : void 0\n });\n if (value.message.content != null) {\n for (let contentIndex = 0; contentIndex < value.message.content.length; contentIndex++) {\n const part = value.message.content[contentIndex];\n if (part.type === \"tool_use\") {\n const caller = part.caller;\n const callerInfo = caller ? {\n type: caller.type,\n toolId: \"tool_id\" in caller ? caller.tool_id : void 0\n } : void 0;\n controller.enqueue({\n type: \"tool-input-start\",\n id: part.id,\n toolName: part.name\n });\n const inputStr = JSON.stringify((_i = part.input) != null ? _i : {});\n controller.enqueue({\n type: \"tool-input-delta\",\n id: part.id,\n delta: inputStr\n });\n controller.enqueue({\n type: \"tool-input-end\",\n id: part.id\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: part.id,\n toolName: part.name,\n input: inputStr,\n ...callerInfo && {\n providerMetadata: {\n anthropic: {\n caller: callerInfo\n }\n }\n }\n });\n }\n }\n }\n return;\n }\n case \"message_delta\": {\n if (value.usage.input_tokens != null && usage.input_tokens !== value.usage.input_tokens) {\n usage.input_tokens = value.usage.input_tokens;\n }\n usage.output_tokens = value.usage.output_tokens;\n if (value.usage.cache_read_input_tokens != null) {\n usage.cache_read_input_tokens = value.usage.cache_read_input_tokens;\n }\n if (value.usage.cache_creation_input_tokens != null) {\n usage.cache_creation_input_tokens = value.usage.cache_creation_input_tokens;\n cacheCreationInputTokens = value.usage.cache_creation_input_tokens;\n }\n finishReason = {\n unified: mapAnthropicStopReason({\n finishReason: value.delta.stop_reason,\n isJsonResponseFromTool\n }),\n raw: (_j = value.delta.stop_reason) != null ? _j : void 0\n };\n stopSequence = (_k = value.delta.stop_sequence) != null ? _k : null;\n container = value.delta.container != null ? {\n expiresAt: value.delta.container.expires_at,\n id: value.delta.container.id,\n skills: (_m = (_l = value.delta.container.skills) == null ? void 0 : _l.map((skill) => ({\n type: skill.type,\n skillId: skill.skill_id,\n version: skill.version\n }))) != null ? _m : null\n } : null;\n if (value.context_management) {\n contextManagement = mapAnthropicResponseContextManagement(\n value.context_management\n );\n }\n rawUsage = {\n ...rawUsage,\n ...value.usage\n };\n return;\n }\n case \"message_stop\": {\n const anthropicMetadata = {\n usage: rawUsage != null ? rawUsage : null,\n cacheCreationInputTokens,\n stopSequence,\n container,\n contextManagement\n };\n const providerMetadata = {\n anthropic: anthropicMetadata\n };\n if (usedCustomProviderKey && providerOptionsName !== \"anthropic\") {\n providerMetadata[providerOptionsName] = anthropicMetadata;\n }\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertAnthropicMessagesUsage(usage),\n providerMetadata\n });\n return;\n }\n case \"error\": {\n controller.enqueue({ type: \"error\", error: value.error });\n return;\n }\n default: {\n const _exhaustiveCheck = value;\n throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n }\n }\n }\n })\n );\n const [streamForFirstChunk, streamForConsumer] = transformedStream.tee();\n const firstChunkReader = streamForFirstChunk.getReader();\n try {\n await firstChunkReader.read();\n let result = await firstChunkReader.read();\n if (((_a = result.value) == null ? void 0 : _a.type) === \"raw\") {\n result = await firstChunkReader.read();\n }\n if (((_b = result.value) == null ? void 0 : _b.type) === \"error\") {\n const error = result.value.error;\n throw new APICallError({\n message: error.message,\n url,\n requestBodyValues: body,\n statusCode: error.type === \"overloaded_error\" ? 529 : 500,\n responseHeaders,\n responseBody: JSON.stringify(error),\n isRetryable: error.type === \"overloaded_error\"\n });\n }\n } finally {\n firstChunkReader.cancel().catch(() => {\n });\n firstChunkReader.releaseLock();\n }\n return {\n stream: streamForConsumer,\n request: { body },\n response: { headers: responseHeaders }\n };\n }\n};\nfunction getModelCapabilities(modelId) {\n if (modelId.includes(\"claude-sonnet-4-5\") || modelId.includes(\"claude-opus-4-5\") || modelId.includes(\"claude-haiku-4-5\")) {\n return {\n maxOutputTokens: 64e3,\n supportsStructuredOutput: true,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-opus-4-1\")) {\n return {\n maxOutputTokens: 32e3,\n supportsStructuredOutput: true,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-sonnet-4-\") || modelId.includes(\"claude-3-7-sonnet\")) {\n return {\n maxOutputTokens: 64e3,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-opus-4-\")) {\n return {\n maxOutputTokens: 32e3,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-3-5-haiku\")) {\n return {\n maxOutputTokens: 8192,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else if (modelId.includes(\"claude-3-haiku\")) {\n return {\n maxOutputTokens: 4096,\n supportsStructuredOutput: false,\n isKnownModel: true\n };\n } else {\n return {\n maxOutputTokens: 4096,\n supportsStructuredOutput: false,\n isKnownModel: false\n };\n }\n}\nfunction mapAnthropicResponseContextManagement(contextManagement) {\n return contextManagement ? {\n appliedEdits: contextManagement.applied_edits.map((edit) => {\n const strategy = edit.type;\n switch (strategy) {\n case \"clear_tool_uses_20250919\":\n return {\n type: edit.type,\n clearedToolUses: edit.cleared_tool_uses,\n clearedInputTokens: edit.cleared_input_tokens\n };\n case \"clear_thinking_20251015\":\n return {\n type: edit.type,\n clearedThinkingTurns: edit.cleared_thinking_turns,\n clearedInputTokens: edit.cleared_input_tokens\n };\n }\n }).filter((edit) => edit !== void 0)\n } : null;\n}\n\n// src/tool/bash_20241022.ts\nimport {\n createProviderToolFactory as createProviderToolFactory2,\n lazySchema as lazySchema9,\n zodSchema as zodSchema9\n} from \"@ai-sdk/provider-utils\";\nimport { z as z10 } from \"zod/v4\";\nvar bash_20241022InputSchema = lazySchema9(\n () => zodSchema9(\n z10.object({\n command: z10.string(),\n restart: z10.boolean().optional()\n })\n )\n);\nvar bash_20241022 = createProviderToolFactory2({\n id: \"anthropic.bash_20241022\",\n inputSchema: bash_20241022InputSchema\n});\n\n// src/tool/bash_20250124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory3,\n lazySchema as lazySchema10,\n zodSchema as zodSchema10\n} from \"@ai-sdk/provider-utils\";\nimport { z as z11 } from \"zod/v4\";\nvar bash_20250124InputSchema = lazySchema10(\n () => zodSchema10(\n z11.object({\n command: z11.string(),\n restart: z11.boolean().optional()\n })\n )\n);\nvar bash_20250124 = createProviderToolFactory3({\n id: \"anthropic.bash_20250124\",\n inputSchema: bash_20250124InputSchema\n});\n\n// src/tool/computer_20241022.ts\nimport {\n createProviderToolFactory as createProviderToolFactory4,\n lazySchema as lazySchema11,\n zodSchema as zodSchema11\n} from \"@ai-sdk/provider-utils\";\nimport { z as z12 } from \"zod/v4\";\nvar computer_20241022InputSchema = lazySchema11(\n () => zodSchema11(\n z12.object({\n action: z12.enum([\n \"key\",\n \"type\",\n \"mouse_move\",\n \"left_click\",\n \"left_click_drag\",\n \"right_click\",\n \"middle_click\",\n \"double_click\",\n \"screenshot\",\n \"cursor_position\"\n ]),\n coordinate: z12.array(z12.number().int()).optional(),\n text: z12.string().optional()\n })\n )\n);\nvar computer_20241022 = createProviderToolFactory4({\n id: \"anthropic.computer_20241022\",\n inputSchema: computer_20241022InputSchema\n});\n\n// src/tool/computer_20250124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory5,\n lazySchema as lazySchema12,\n zodSchema as zodSchema12\n} from \"@ai-sdk/provider-utils\";\nimport { z as z13 } from \"zod/v4\";\nvar computer_20250124InputSchema = lazySchema12(\n () => zodSchema12(\n z13.object({\n action: z13.enum([\n \"key\",\n \"hold_key\",\n \"type\",\n \"cursor_position\",\n \"mouse_move\",\n \"left_mouse_down\",\n \"left_mouse_up\",\n \"left_click\",\n \"left_click_drag\",\n \"right_click\",\n \"middle_click\",\n \"double_click\",\n \"triple_click\",\n \"scroll\",\n \"wait\",\n \"screenshot\"\n ]),\n coordinate: z13.tuple([z13.number().int(), z13.number().int()]).optional(),\n duration: z13.number().optional(),\n scroll_amount: z13.number().optional(),\n scroll_direction: z13.enum([\"up\", \"down\", \"left\", \"right\"]).optional(),\n start_coordinate: z13.tuple([z13.number().int(), z13.number().int()]).optional(),\n text: z13.string().optional()\n })\n )\n);\nvar computer_20250124 = createProviderToolFactory5({\n id: \"anthropic.computer_20250124\",\n inputSchema: computer_20250124InputSchema\n});\n\n// src/tool/computer_20251124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory6,\n lazySchema as lazySchema13,\n zodSchema as zodSchema13\n} from \"@ai-sdk/provider-utils\";\nimport { z as z14 } from \"zod/v4\";\nvar computer_20251124InputSchema = lazySchema13(\n () => zodSchema13(\n z14.object({\n action: z14.enum([\n \"key\",\n \"hold_key\",\n \"type\",\n \"cursor_position\",\n \"mouse_move\",\n \"left_mouse_down\",\n \"left_mouse_up\",\n \"left_click\",\n \"left_click_drag\",\n \"right_click\",\n \"middle_click\",\n \"double_click\",\n \"triple_click\",\n \"scroll\",\n \"wait\",\n \"screenshot\",\n \"zoom\"\n ]),\n coordinate: z14.tuple([z14.number().int(), z14.number().int()]).optional(),\n duration: z14.number().optional(),\n region: z14.tuple([\n z14.number().int(),\n z14.number().int(),\n z14.number().int(),\n z14.number().int()\n ]).optional(),\n scroll_amount: z14.number().optional(),\n scroll_direction: z14.enum([\"up\", \"down\", \"left\", \"right\"]).optional(),\n start_coordinate: z14.tuple([z14.number().int(), z14.number().int()]).optional(),\n text: z14.string().optional()\n })\n )\n);\nvar computer_20251124 = createProviderToolFactory6({\n id: \"anthropic.computer_20251124\",\n inputSchema: computer_20251124InputSchema\n});\n\n// src/tool/memory_20250818.ts\nimport {\n createProviderToolFactory as createProviderToolFactory7,\n lazySchema as lazySchema14,\n zodSchema as zodSchema14\n} from \"@ai-sdk/provider-utils\";\nimport { z as z15 } from \"zod/v4\";\nvar memory_20250818InputSchema = lazySchema14(\n () => zodSchema14(\n z15.discriminatedUnion(\"command\", [\n z15.object({\n command: z15.literal(\"view\"),\n path: z15.string(),\n view_range: z15.tuple([z15.number(), z15.number()]).optional()\n }),\n z15.object({\n command: z15.literal(\"create\"),\n path: z15.string(),\n file_text: z15.string()\n }),\n z15.object({\n command: z15.literal(\"str_replace\"),\n path: z15.string(),\n old_str: z15.string(),\n new_str: z15.string()\n }),\n z15.object({\n command: z15.literal(\"insert\"),\n path: z15.string(),\n insert_line: z15.number(),\n insert_text: z15.string()\n }),\n z15.object({\n command: z15.literal(\"delete\"),\n path: z15.string()\n }),\n z15.object({\n command: z15.literal(\"rename\"),\n old_path: z15.string(),\n new_path: z15.string()\n })\n ])\n )\n);\nvar memory_20250818 = createProviderToolFactory7({\n id: \"anthropic.memory_20250818\",\n inputSchema: memory_20250818InputSchema\n});\n\n// src/tool/text-editor_20241022.ts\nimport {\n createProviderToolFactory as createProviderToolFactory8,\n lazySchema as lazySchema15,\n zodSchema as zodSchema15\n} from \"@ai-sdk/provider-utils\";\nimport { z as z16 } from \"zod/v4\";\nvar textEditor_20241022InputSchema = lazySchema15(\n () => zodSchema15(\n z16.object({\n command: z16.enum([\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"]),\n path: z16.string(),\n file_text: z16.string().optional(),\n insert_line: z16.number().int().optional(),\n new_str: z16.string().optional(),\n insert_text: z16.string().optional(),\n old_str: z16.string().optional(),\n view_range: z16.array(z16.number().int()).optional()\n })\n )\n);\nvar textEditor_20241022 = createProviderToolFactory8({\n id: \"anthropic.text_editor_20241022\",\n inputSchema: textEditor_20241022InputSchema\n});\n\n// src/tool/text-editor_20250124.ts\nimport {\n createProviderToolFactory as createProviderToolFactory9,\n lazySchema as lazySchema16,\n zodSchema as zodSchema16\n} from \"@ai-sdk/provider-utils\";\nimport { z as z17 } from \"zod/v4\";\nvar textEditor_20250124InputSchema = lazySchema16(\n () => zodSchema16(\n z17.object({\n command: z17.enum([\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"]),\n path: z17.string(),\n file_text: z17.string().optional(),\n insert_line: z17.number().int().optional(),\n new_str: z17.string().optional(),\n insert_text: z17.string().optional(),\n old_str: z17.string().optional(),\n view_range: z17.array(z17.number().int()).optional()\n })\n )\n);\nvar textEditor_20250124 = createProviderToolFactory9({\n id: \"anthropic.text_editor_20250124\",\n inputSchema: textEditor_20250124InputSchema\n});\n\n// src/tool/text-editor_20250429.ts\nimport {\n createProviderToolFactory as createProviderToolFactory10,\n lazySchema as lazySchema17,\n zodSchema as zodSchema17\n} from \"@ai-sdk/provider-utils\";\nimport { z as z18 } from \"zod/v4\";\nvar textEditor_20250429InputSchema = lazySchema17(\n () => zodSchema17(\n z18.object({\n command: z18.enum([\"view\", \"create\", \"str_replace\", \"insert\"]),\n path: z18.string(),\n file_text: z18.string().optional(),\n insert_line: z18.number().int().optional(),\n new_str: z18.string().optional(),\n insert_text: z18.string().optional(),\n old_str: z18.string().optional(),\n view_range: z18.array(z18.number().int()).optional()\n })\n )\n);\nvar textEditor_20250429 = createProviderToolFactory10({\n id: \"anthropic.text_editor_20250429\",\n inputSchema: textEditor_20250429InputSchema\n});\n\n// src/tool/tool-search-bm25_20251119.ts\nimport {\n createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema6,\n lazySchema as lazySchema18,\n zodSchema as zodSchema18\n} from \"@ai-sdk/provider-utils\";\nimport { z as z19 } from \"zod/v4\";\nvar toolSearchBm25_20251119OutputSchema = lazySchema18(\n () => zodSchema18(\n z19.array(\n z19.object({\n type: z19.literal(\"tool_reference\"),\n toolName: z19.string()\n })\n )\n )\n);\nvar toolSearchBm25_20251119InputSchema = lazySchema18(\n () => zodSchema18(\n z19.object({\n /**\n * A natural language query to search for tools.\n * Claude will use BM25 text search to find relevant tools.\n */\n query: z19.string(),\n /**\n * Maximum number of tools to return. Optional.\n */\n limit: z19.number().optional()\n })\n )\n);\nvar factory7 = createProviderToolFactoryWithOutputSchema6({\n id: \"anthropic.tool_search_bm25_20251119\",\n inputSchema: toolSearchBm25_20251119InputSchema,\n outputSchema: toolSearchBm25_20251119OutputSchema,\n supportsDeferredResults: true\n});\nvar toolSearchBm25_20251119 = (args = {}) => {\n return factory7(args);\n};\n\n// src/anthropic-tools.ts\nvar anthropicTools = {\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20241022,\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20250124,\n /**\n * Claude can analyze data, create visualizations, perform complex calculations,\n * run system commands, create and edit files, and process uploaded files directly within\n * the API conversation.\n *\n * The code execution tool allows Claude to run Bash commands and manipulate files,\n * including writing code, in a secure, sandboxed environment.\n */\n codeExecution_20250522,\n /**\n * Claude can analyze data, create visualizations, perform complex calculations,\n * run system commands, create and edit files, and process uploaded files directly within\n * the API conversation.\n *\n * The code execution tool allows Claude to run both Python and Bash commands and manipulate files,\n * including writing code, in a secure, sandboxed environment.\n *\n * This is the latest version with enhanced Bash support and file operations.\n */\n codeExecution_20250825,\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * Image results are supported.\n *\n * @param displayWidthPx - The width of the display being controlled by the model in pixels.\n * @param displayHeightPx - The height of the display being controlled by the model in pixels.\n * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.\n */\n computer_20241022,\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * Image results are supported.\n *\n * @param displayWidthPx - The width of the display being controlled by the model in pixels.\n * @param displayHeightPx - The height of the display being controlled by the model in pixels.\n * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.\n */\n computer_20250124,\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * This version adds the zoom action for detailed screen region inspection.\n *\n * Image results are supported.\n *\n * Supported models: Claude Opus 4.5\n *\n * @param displayWidthPx - The width of the display being controlled by the model in pixels.\n * @param displayHeightPx - The height of the display being controlled by the model in pixels.\n * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.\n * @param enableZoom - Enable zoom action. Set to true to allow Claude to zoom into specific screen regions. Default: false.\n */\n computer_20251124,\n /**\n * The memory tool enables Claude to store and retrieve information across conversations through a memory file directory.\n * Claude can create, read, update, and delete files that persist between sessions,\n * allowing it to build knowledge over time without keeping everything in the context window.\n * The memory tool operates client-side—you control where and how the data is stored through your own infrastructure.\n *\n * Supported models: Claude Sonnet 4.5, Claude Sonnet 4, Claude Opus 4.1, Claude Opus 4.\n */\n memory_20250818,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Supported models: Claude Sonnet 3.5\n */\n textEditor_20241022,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Supported models: Claude Sonnet 3.7\n */\n textEditor_20250124,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Note: This version does not support the \"undo_edit\" command.\n *\n * @deprecated Use textEditor_20250728 instead\n */\n textEditor_20250429,\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents. This allows Claude\n * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.\n *\n * Note: This version does not support the \"undo_edit\" command and adds optional max_characters parameter.\n *\n * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1\n *\n * @param maxCharacters - Optional maximum number of characters to view in the file\n */\n textEditor_20250728,\n /**\n * Creates a web fetch tool that gives Claude direct access to real-time web content.\n *\n * @param maxUses - The max_uses parameter limits the number of web fetches performed\n * @param allowedDomains - Only fetch from these domains\n * @param blockedDomains - Never fetch from these domains\n * @param citations - Unlike web search where citations are always enabled, citations are optional for web fetch. Set \"citations\": {\"enabled\": true} to enable Claude to cite specific passages from fetched documents.\n * @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context.\n */\n webFetch_20250910,\n /**\n * Creates a web search tool that gives Claude direct access to real-time web content.\n *\n * @param maxUses - Maximum number of web searches Claude can perform during the conversation.\n * @param allowedDomains - Optional list of domains that Claude is allowed to search.\n * @param blockedDomains - Optional list of domains that Claude should avoid when searching.\n * @param userLocation - Optional user location information to provide geographically relevant search results.\n */\n webSearch_20250305,\n /**\n * Creates a tool search tool that uses regex patterns to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand. Instead of loading all\n * tool definitions into the context window upfront, Claude searches your tool\n * catalog and loads only the tools it needs.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n *\n * Supported models: Claude Opus 4.5, Claude Sonnet 4.5\n */\n toolSearchRegex_20251119,\n /**\n * Creates a tool search tool that uses BM25 (natural language) to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand. Instead of loading all\n * tool definitions into the context window upfront, Claude searches your tool\n * catalog and loads only the tools it needs.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n *\n * Supported models: Claude Opus 4.5, Claude Sonnet 4.5\n */\n toolSearchBm25_20251119\n};\n\n// src/anthropic-provider.ts\nfunction createAnthropic(options = {}) {\n var _a, _b;\n const baseURL = (_a = withoutTrailingSlash(\n loadOptionalSetting({\n settingValue: options.baseURL,\n environmentVariableName: \"ANTHROPIC_BASE_URL\"\n })\n )) != null ? _a : \"https://api.anthropic.com/v1\";\n const providerName = (_b = options.name) != null ? _b : \"anthropic.messages\";\n if (options.apiKey && options.authToken) {\n throw new InvalidArgumentError({\n argument: \"apiKey/authToken\",\n message: \"Both apiKey and authToken were provided. Please use only one authentication method.\"\n });\n }\n const getHeaders = () => {\n const authHeaders = options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {\n \"x-api-key\": loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"ANTHROPIC_API_KEY\",\n description: \"Anthropic\"\n })\n };\n return withUserAgentSuffix(\n {\n \"anthropic-version\": \"2023-06-01\",\n ...authHeaders,\n ...options.headers\n },\n `ai-sdk/anthropic/${VERSION}`\n );\n };\n const createChatModel = (modelId) => {\n var _a2;\n return new AnthropicMessagesLanguageModel(modelId, {\n provider: providerName,\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: (_a2 = options.generateId) != null ? _a2 : generateId2,\n supportedUrls: () => ({\n \"image/*\": [/^https?:\\/\\/.*$/],\n \"application/pdf\": [/^https?:\\/\\/.*$/]\n })\n });\n };\n const provider = function(modelId) {\n if (new.target) {\n throw new Error(\n \"The Anthropic model function cannot be called with the new keyword.\"\n );\n }\n return createChatModel(modelId);\n };\n provider.specificationVersion = \"v3\";\n provider.languageModel = createChatModel;\n provider.chat = createChatModel;\n provider.messages = createChatModel;\n provider.embeddingModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"embeddingModel\" });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId) => {\n throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n };\n provider.tools = anthropicTools;\n return provider;\n}\nvar anthropic = createAnthropic();\n\n// src/forward-anthropic-container-id-from-last-step.ts\nfunction forwardAnthropicContainerIdFromLastStep({\n steps\n}) {\n var _a, _b, _c;\n for (let i = steps.length - 1; i >= 0; i--) {\n const containerId = (_c = (_b = (_a = steps[i].providerMetadata) == null ? void 0 : _a.anthropic) == null ? void 0 : _b.container) == null ? void 0 : _c.id;\n if (containerId) {\n return {\n providerOptions: {\n anthropic: {\n container: { id: containerId }\n }\n }\n };\n }\n }\n return void 0;\n}\nexport {\n VERSION,\n anthropic,\n createAnthropic,\n forwardAnthropicContainerIdFromLastStep\n};\n//# sourceMappingURL=index.mjs.map","/**\n * Agent Prompts - Centralized prompt definitions for the live agent.\n *\n * All hardcoded prompts are defined here for easy review, modification,\n * and future configurability. This file serves as the single source of\n * truth for agent behavior instructions.\n */\n\n// =============================================================================\n// System Prompts\n// =============================================================================\n\n/**\n * Default system prompt for the live agent.\n *\n * This is the base instruction set that defines the agent's core behavior\n * for form filling. It emphasizes accuracy over completeness and prohibits\n * fabrication of data.\n */\nexport const DEFAULT_SYSTEM_PROMPT = `# Form Instructions\n\nResearch and fill the form fields using all available tools. Focus on accuracy over completeness.\n\n## Guidelines\n1. Address required fields first (severity: \"required\"), then optional fields (severity: \"recommended\")\n2. NEVER fabricate or guess information - only use data you can verify\n3. If you cannot find verifiable information, use skip_field with a reason\n\n## Patch Format Examples\n\nUse the fill_form tool with patches in these formats:\n\n| Type | Example |\n|------|---------|\n| string | \\`{ op: \"set_string\", fieldId: \"name\", value: \"Acme Corp\" }\\` |\n| number | \\`{ op: \"set_number\", fieldId: \"age\", value: 32 }\\` |\n| string_list | \\`{ op: \"set_string_list\", fieldId: \"tags\", value: [\"ai\", \"ml\"] }\\` |\n| url | \\`{ op: \"set_url\", fieldId: \"website\", value: \"https://example.com\" }\\` |\n| url_list | \\`{ op: \"set_url_list\", fieldId: \"sources\", value: [\"https://a.com\", \"https://b.com\"] }\\` |\n| date | \\`{ op: \"set_date\", fieldId: \"event_date\", value: \"2024-06-15\" }\\` |\n| year | \\`{ op: \"set_year\", fieldId: \"founded\", value: 2024 }\\` |\n| single_select | \\`{ op: \"set_single_select\", fieldId: \"priority\", value: \"high\" }\\` |\n| multi_select | \\`{ op: \"set_multi_select\", fieldId: \"categories\", value: [\"frontend\", \"backend\"] }\\` |\n| checkboxes | \\`{ op: \"set_checkboxes\", fieldId: \"tasks\", value: { \"task1\": \"done\", \"task2\": \"todo\" } }\\` |\n| table | \\`{ op: \"set_table\", fieldId: \"team\", value: [{ \"name\": \"Alice\", \"role\": \"Engineer\" }] }\\` |\n\n## Important: checkboxes vs multi_select\n\nThese two types look similar but have DIFFERENT value formats:\n\n- **multi_select** → array of option IDs: \\`[\"opt1\", \"opt2\"]\\`\n- **checkboxes** → object mapping IDs to states: \\`{ \"opt1\": \"done\", \"opt2\": \"todo\" }\\`\n\n**Checkbox states by mode:**\n- Mode \"simple\": \\`\"done\"\\` or \\`\"todo\"\\`\n- Mode \"multi\": \\`\"done\"\\`, \\`\"todo\"\\`, \\`\"incomplete\"\\`, \\`\"active\"\\`, or \\`\"na\"\\`\n- Mode \"explicit\": \\`\"yes\"\\` or \\`\"no\"\\` (if unknown, use abort_field)\n\n**WRONG:** \\`{ op: \"set_checkboxes\", value: [\"task1\", \"task2\"] }\\`\n**RIGHT:** \\`{ op: \"set_checkboxes\", value: { \"task1\": \"done\", \"task2\": \"done\" } }\\`\n\n## Skipping Fields\n\nIf you cannot find verifiable information:\n\\`{ op: \"skip_field\", fieldId: \"...\", reason: \"Could not find verified data\" }\\`\n`;\n\n/**\n * Web search instructions appended when web search tools are available.\n *\n * These instructions enforce that the agent must verify all information\n * through web search before filling fields.\n */\nexport const WEB_SEARCH_INSTRUCTIONS = `# Web Search\nYou have access to web search tools. You MUST use them to verify ALL information before filling fields.\n\nGuidelines:\n1. Search for official sources (company websites, Crunchbase, LinkedIn, press releases)\n2. Cross-reference information across multiple sources when possible\n3. Only fill fields with data you found and verified through search\n4. If a search returns no results or uncertain information, use skip_field with a reason explaining what you searched for\n5. NEVER fill fields with guessed or assumed information\n`;\n\n// =============================================================================\n// Context Prompt Templates\n// =============================================================================\n\n/**\n * Header for the issues section in the context prompt.\n */\nexport const ISSUES_HEADER = '# Current Form Issues';\n\n/**\n * Template for the issues intro text.\n * @param issueCount - Actual number of issues shown\n */\nexport function getIssuesIntro(issueCount: number): string {\n return `You need to address ${issueCount} issue${issueCount === 1 ? '' : 's'}. Here are the current issues:`;\n}\n\n/**\n * Patch format examples by field kind.\n *\n * This is the single source of truth for patch format documentation.\n * Used in PATCH_FORMAT_INSTRUCTIONS and rejection feedback hints.\n */\nexport const PATCH_FORMATS: Record<string, string> = {\n string: '{ op: \"set_string\", fieldId: \"...\", value: \"text here\" }',\n number: '{ op: \"set_number\", fieldId: \"...\", value: 42 }',\n string_list: '{ op: \"set_string_list\", fieldId: \"...\", value: [\"item1\", \"item2\"] }',\n single_select: '{ op: \"set_single_select\", fieldId: \"...\", value: \"option_id\" }',\n multi_select: '{ op: \"set_multi_select\", fieldId: \"...\", value: [\"opt1\", \"opt2\"] }',\n checkboxes: '{ op: \"set_checkboxes\", fieldId: \"...\", value: { \"opt1\": \"done\", \"opt2\": \"todo\" } }',\n url: '{ op: \"set_url\", fieldId: \"...\", value: \"https://example.com\" }',\n url_list: '{ op: \"set_url_list\", fieldId: \"...\", value: [\"https://a.com\", \"https://b.com\"] }',\n date: '{ op: \"set_date\", fieldId: \"...\", value: \"2024-06-15\" }',\n year: '{ op: \"set_year\", fieldId: \"...\", value: 2024 }',\n table: '{ op: \"set_table\", fieldId: \"...\", value: [{ col1: \"val1\", col2: \"val2\" }] }',\n};\n\n/**\n * Checkbox-mode-specific format hints.\n * Used to provide clearer examples based on the checkbox mode.\n */\nexport const CHECKBOX_MODE_HINTS: Record<string, string> = {\n simple: '{ \"opt1\": \"done\", \"opt2\": \"todo\" } // states: done, todo',\n multi:\n '{ \"opt1\": \"todo\", \"opt2\": \"todo\", \"opt3\": \"done\", \"opt4\": \"incomplete\", \"opt5\": \"active\", \"opt6\": \"na\" } // states: done, todo, incomplete, active, na',\n explicit: '{ \"opt1\": \"yes\", \"opt2\": \"no\" } // states: yes, no',\n};\n\n/**\n * Options for generating patch format hints.\n */\nexport interface PatchFormatHintOptions {\n fieldId?: string;\n columnIds?: string[];\n checkboxMode?: 'simple' | 'multi' | 'explicit';\n optionIds?: string[];\n}\n\n/**\n * Get the correct patch format for a field kind.\n *\n * @param fieldKind - The field kind (e.g., \"table\", \"string\")\n * @param options - Optional configuration for the hint\n * @returns The patch format example string\n */\nexport function getPatchFormatHint(\n fieldKind: string,\n fieldIdOrOptions?: string | PatchFormatHintOptions,\n columnIds?: string[],\n): string {\n // Handle legacy call signature: getPatchFormatHint(kind, fieldId, columnIds)\n let options: PatchFormatHintOptions = {};\n if (typeof fieldIdOrOptions === 'string') {\n options = { fieldId: fieldIdOrOptions, columnIds };\n } else if (fieldIdOrOptions) {\n options = fieldIdOrOptions;\n }\n\n let format = PATCH_FORMATS[fieldKind];\n if (!format) {\n return `Use the correct set_${fieldKind} operation for this field type.`;\n }\n\n // Substitute field ID if provided\n if (options.fieldId) {\n format = format.replace('fieldId: \"...\"', `fieldId: \"${options.fieldId}\"`);\n }\n\n // For checkboxes, use mode-specific hints with actual option IDs if available\n if (fieldKind === 'checkboxes') {\n const mode = options.checkboxMode ?? 'multi';\n const optIds = options.optionIds ?? ['opt1', 'opt2'];\n const stateMap: Record<string, [string, string]> = {\n simple: ['done', 'todo'],\n multi: ['done', 'todo'],\n explicit: ['yes', 'no'],\n };\n const [state1, state2] = stateMap[mode] ?? ['done', 'todo'];\n\n // Build concrete example with actual option IDs\n const valueExample =\n optIds.length >= 2\n ? `{ \"${optIds[0]}\": \"${state1}\", \"${optIds[1]}\": \"${state2}\" }`\n : optIds.length === 1\n ? `{ \"${optIds[0]}\": \"${state1}\" }`\n : `{ \"opt1\": \"${state1}\", \"opt2\": \"${state2}\" }`;\n\n format = format.replace('{ \"opt1\": \"done\", \"opt2\": \"todo\" }', valueExample);\n }\n\n // For table fields, show actual column IDs if available\n if (fieldKind === 'table' && options.columnIds && options.columnIds.length > 0) {\n const colExample = options.columnIds.map((id) => `\"${id}\": \"...\"`).join(', ');\n format = format.replace('{ col1: \"val1\", col2: \"val2\" }', `{ ${colExample} }`);\n }\n\n return format;\n}\n\n/**\n * Instructions section for the context prompt.\n *\n * This explains the patch format for each field kind.\n * Generated from PATCH_FORMATS to ensure consistency.\n */\nexport const PATCH_FORMAT_INSTRUCTIONS = `# Instructions\n\nUse the fill_form tool to submit patches for the fields above.\nEach patch should match the field kind:\n${Object.entries(PATCH_FORMATS)\n .map(([kind, format]) => `- ${kind}: ${format}`)\n .join('\\n')}\n\nFor table fields, use the column IDs shown in the field schema. Each row is an object with column ID keys.\n\nIf you cannot find verifiable information for a field, skip it:\n- skip: { op: \"skip_field\", fieldId: \"...\", reason: \"Information not available\" }`;\n\n/**\n * Simplified general instructions for use with inline field instructions.\n *\n * When inline field instructions are shown after each issue, we only need\n * general guidance about using the fill_form tool.\n */\nexport const GENERAL_INSTRUCTIONS = `# General Instructions\n\nUse the fill_form tool to submit patches for the fields above.\nFor table fields, each row is an object with column ID keys.`;\n\n// =============================================================================\n// Section Headers\n// =============================================================================\n\n/**\n * Section headers used when building the composed system prompt.\n */\nexport const SECTION_HEADERS = {\n formInstructions: '# Form Instructions',\n roleInstructions: (role: string) => `# Instructions for ${role} role`,\n roleGuidance: '# Role guidance',\n fieldInstructions: '# Field-specific instructions',\n additionalContext: '# Additional Context',\n} as const;\n","/**\n * Tool API Definitions\n *\n * Single source of truth for all LLM tool names, descriptions, and schemas.\n * This file defines the contract between markform and LLM agents.\n */\n\n// =============================================================================\n// Tool Names\n// =============================================================================\n\n/** The primary tool for filling form fields */\nexport const FILL_FORM_TOOL_NAME = 'fill_form';\n\n// =============================================================================\n// Tool Descriptions\n// =============================================================================\n\n/** Description shown to LLMs for the fill_form tool */\nexport const FILL_FORM_TOOL_DESCRIPTION =\n 'Fill form fields by submitting patches. Each patch sets a value for one field. ' +\n 'Use the field IDs from the issues list. Return patches for all issues you can address.';\n\n// =============================================================================\n// Patch Operations\n// =============================================================================\n\n/** All valid patch operation names */\nexport const PATCH_OPERATIONS = [\n 'set_string',\n 'set_number',\n 'set_string_list',\n 'set_checkboxes',\n 'set_single_select',\n 'set_multi_select',\n 'set_url',\n 'set_url_list',\n 'set_date',\n 'set_year',\n 'set_table',\n 'clear_field',\n 'skip_field',\n 'abort_field',\n] as const;\n\nexport type PatchOperation = (typeof PATCH_OPERATIONS)[number];\n","/**\n * Live Agent - LLM-powered agent for form filling.\n *\n * Uses AI SDK to call an LLM that fills forms autonomously\n * by analyzing issues and generating appropriate patches.\n */\n\nimport type { LanguageModel, Tool } from 'ai';\nimport { generateText, stepCountIs, zodSchema } from 'ai';\nimport { z } from 'zod';\nimport { openai } from '@ai-sdk/openai';\nimport { anthropic } from '@ai-sdk/anthropic';\nimport { google } from '@ai-sdk/google';\nimport { xai } from '@ai-sdk/xai';\n\nimport type {\n DocumentationBlock,\n InspectIssue,\n ParsedForm,\n Patch,\n PatchRejection,\n WireFormat,\n WireResponseStep,\n} from '../engine/coreTypes.js';\nimport { PatchSchema } from '../engine/coreTypes.js';\nimport { serializeForm } from '../engine/serialize.js';\nimport { DEFAULT_ROLE_INSTRUCTIONS, AGENT_ROLE, DEFAULT_MAX_STEPS_PER_TURN } from '../settings.js';\nimport { getWebSearchConfig } from '../llms.js';\nimport { wrapApiError } from '../errors.js';\nimport type {\n Agent,\n AgentResponse,\n FillCallbacks,\n LiveAgentConfig,\n TurnStats,\n} from './harnessTypes.js';\nimport {\n DEFAULT_SYSTEM_PROMPT,\n WEB_SEARCH_INSTRUCTIONS,\n ISSUES_HEADER,\n getIssuesIntro,\n GENERAL_INSTRUCTIONS,\n SECTION_HEADERS,\n getPatchFormatHint,\n} from './prompts.js';\nimport { FILL_FORM_TOOL_NAME, FILL_FORM_TOOL_DESCRIPTION } from './toolApi.js';\n\n// Re-export types for backwards compatibility\nexport type { LiveAgentConfig } from './harnessTypes.js';\n\n// =============================================================================\n// Live Agent Implementation\n// =============================================================================\n\n/**\n * Live agent that uses an LLM to generate patches.\n */\nexport class LiveAgent implements Agent {\n private model: LanguageModel;\n private maxStepsPerTurn: number;\n private systemPromptAddition?: string;\n private targetRole: string;\n private provider?: string;\n private enableWebSearch: boolean;\n private webSearchTools: Record<string, Tool> | null = null;\n private additionalTools: Record<string, Tool>;\n private callbacks?: FillCallbacks;\n private executionId: string;\n private toolChoice: 'auto' | 'required';\n\n constructor(config: LiveAgentConfig) {\n this.model = config.model;\n this.maxStepsPerTurn = config.maxStepsPerTurn ?? DEFAULT_MAX_STEPS_PER_TURN;\n this.systemPromptAddition = config.systemPromptAddition;\n this.targetRole = config.targetRole ?? AGENT_ROLE;\n this.provider = config.provider;\n this.enableWebSearch = config.enableWebSearch;\n this.additionalTools = config.additionalTools ?? {};\n this.callbacks = config.callbacks;\n this.executionId = config.executionId ?? '0-serial';\n // TODO: Make toolChoice configurable per-model or per-form in the future.\n // For now, 'required' is always safe since Markform agents must use tools.\n // Some models (e.g., gpt-5-mini) don't reliably call tools with 'auto'.\n this.toolChoice = config.toolChoice ?? 'required';\n\n // Eagerly load web search tools to enable early logging\n if (this.enableWebSearch && this.provider) {\n this.webSearchTools = loadWebSearchTools(this.provider);\n }\n }\n\n /**\n * Get list of available tool names for this agent.\n * Useful for logging what capabilities the agent has.\n */\n getAvailableToolNames(): string[] {\n const tools = [FILL_FORM_TOOL_NAME];\n if (this.webSearchTools) {\n tools.push(...Object.keys(this.webSearchTools));\n }\n // Add custom tool names (may overlap with web search if replacing)\n tools.push(...Object.keys(this.additionalTools));\n // Dedupe in case custom tools replace built-in\n return [...new Set(tools)];\n }\n\n /**\n * Invoke the fill_form tool using the LLM.\n *\n * Each call is stateless - the full form context is provided fresh each turn.\n * The form itself carries all state (filled values, remaining issues).\n * Returns patches and per-turn stats for observability.\n *\n * @param issues - Current issues to address\n * @param form - Current form state\n * @param maxPatches - Maximum patches to generate\n * @param previousRejections - Rejections from previous turn (helps LLM learn from mistakes)\n */\n async fillFormTool(\n issues: InspectIssue[],\n form: ParsedForm,\n maxPatches: number,\n previousRejections?: PatchRejection[],\n ): Promise<AgentResponse> {\n // Build context prompt with issues and form schema (include previous rejections if any)\n const contextPrompt = buildContextPrompt(issues, form, maxPatches, previousRejections);\n\n // Build composed system prompt from form instructions\n let systemPrompt = buildSystemPrompt(form, this.targetRole, issues);\n\n // Append additional context if provided (never overrides form instructions)\n if (this.systemPromptAddition) {\n systemPrompt += '\\n\\n# Additional Context\\n' + this.systemPromptAddition;\n }\n\n // Web search tools are loaded in constructor, but check again for runtime changes\n if (this.enableWebSearch && this.provider && !this.webSearchTools) {\n this.webSearchTools = loadWebSearchTools(this.provider);\n }\n\n // If web search is available, add instructions to use it\n if (this.webSearchTools && Object.keys(this.webSearchTools).length > 0) {\n systemPrompt += '\\n\\n' + WEB_SEARCH_INSTRUCTIONS;\n }\n\n // Define the patch tool with properly typed parameters\n const patchesSchema = z.object({\n patches: z\n .array(PatchSchema)\n .max(maxPatches)\n .describe('Array of patches. Each patch sets a value for one field.'),\n });\n\n // Create tool using zodSchema wrapper for AI SDK v6 compatibility\n const fillFormToolDef: Tool = {\n description: FILL_FORM_TOOL_DESCRIPTION,\n inputSchema: zodSchema(patchesSchema),\n };\n\n // Combine all tools (custom tools win on name collision)\n const rawTools: Record<string, Tool> = {\n [FILL_FORM_TOOL_NAME]: fillFormToolDef,\n ...this.webSearchTools,\n ...this.additionalTools,\n };\n\n // Wrap tools with callbacks for observability\n const tools = wrapToolsWithCallbacks(rawTools, this.callbacks, this.provider, this.executionId);\n\n // Get model ID for callbacks (may not be available on all model types)\n const modelId = (this.model as { modelId?: string }).modelId ?? 'unknown';\n\n // Call onLlmCallStart callback (errors don't abort)\n if (this.callbacks?.onLlmCallStart) {\n try {\n this.callbacks.onLlmCallStart({\n model: modelId,\n executionId: this.executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Call the model (stateless - full context provided each turn)\n let result;\n try {\n result = await generateText({\n model: this.model,\n system: systemPrompt,\n prompt: contextPrompt,\n tools,\n toolChoice: this.toolChoice,\n stopWhen: stepCountIs(this.maxStepsPerTurn),\n });\n } catch (error) {\n // Wrap API errors with rich context for debugging\n throw wrapApiError(error, this.provider ?? 'unknown', modelId);\n }\n\n // Call onLlmCallEnd callback (errors don't abort)\n if (this.callbacks?.onLlmCallEnd) {\n try {\n this.callbacks.onLlmCallEnd({\n model: modelId,\n inputTokens: result.usage?.inputTokens ?? 0,\n outputTokens: result.usage?.outputTokens ?? 0,\n executionId: this.executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Extract patches from tool calls and count tool usage\n const patches: Patch[] = [];\n const toolCallCounts = new Map<string, number>();\n\n for (const step of result.steps) {\n for (const toolCall of step.toolCalls) {\n // Count tool calls\n const count = toolCallCounts.get(toolCall.toolName) ?? 0;\n toolCallCounts.set(toolCall.toolName, count + 1);\n\n // Extract patches from fill_form calls and emit tool events\n // (fill_form is declarative so doesn't go through wrapToolsWithCallbacks)\n if (toolCall.toolName === FILL_FORM_TOOL_NAME && 'input' in toolCall) {\n const input = toolCall.input as { patches: Patch[] };\n const startTime = Date.now();\n\n // Emit onToolStart for fill_form\n if (this.callbacks?.onToolStart) {\n try {\n this.callbacks.onToolStart({\n name: FILL_FORM_TOOL_NAME,\n input,\n executionId: this.executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n patches.push(...input.patches);\n\n // Emit onToolEnd for fill_form\n if (this.callbacks?.onToolEnd) {\n try {\n this.callbacks.onToolEnd({\n name: FILL_FORM_TOOL_NAME,\n output: { patchCount: input.patches.length },\n durationMs: Date.now() - startTime,\n executionId: this.executionId,\n error: undefined,\n });\n } catch {\n // Ignore callback errors\n }\n }\n }\n }\n }\n\n // Build tool call stats\n const toolCalls: TurnStats['toolCalls'] = [];\n for (const [name, count] of toolCallCounts) {\n toolCalls.push({ name, count });\n }\n\n // Count remaining issues by severity\n const requiredRemaining = issues.filter((i) => i.severity === 'required').length;\n const optionalRemaining = issues.filter((i) => i.severity === 'recommended').length;\n\n // Build wire format for session logging (captures complete request/response)\n const wire = buildWireFormat(systemPrompt, contextPrompt, rawTools, result);\n\n // Build stats\n const stats: TurnStats = {\n inputTokens: result.usage?.inputTokens,\n outputTokens: result.usage?.outputTokens,\n toolCalls,\n formProgress: {\n // Note: these are the counts BEFORE this turn's patches are applied\n // The caller will update these after applying patches\n answeredFields: Object.values(form.responsesByFieldId).filter(\n (response) => response?.state === 'answered',\n ).length,\n skippedFields: Object.values(form.responsesByFieldId).filter(\n (response) => response?.state === 'skipped',\n ).length,\n requiredRemaining,\n optionalRemaining,\n },\n prompts: {\n system: systemPrompt,\n context: contextPrompt,\n },\n wire,\n };\n\n // Limit to maxPatches and return with stats\n return {\n patches: patches.slice(0, maxPatches),\n stats,\n };\n }\n}\n\n// =============================================================================\n// Wire Format Capture Helpers\n// =============================================================================\n\n/**\n * Extract tool schemas from tools object for wire format logging.\n * Captures description and inputSchema for each tool.\n */\nfunction extractToolSchemas(\n tools: Record<string, Tool>,\n): Record<string, { description: string; inputSchema: unknown }> {\n const schemas: Record<string, { description: string; inputSchema: unknown }> = {};\n\n // Sort tool names for deterministic ordering\n const sortedNames = Object.keys(tools).sort();\n for (const name of sortedNames) {\n const tool = tools[name];\n if (tool) {\n schemas[name] = {\n description: tool.description ?? '',\n // Extract the JSON schema from the tool's inputSchema\n // The AI SDK Tool type has inputSchema as a JsonSchema object\n inputSchema: sortObjectKeys(tool.inputSchema ?? {}),\n };\n }\n }\n return schemas;\n}\n\n/**\n * Sort object keys recursively for deterministic serialization.\n * This ensures wire format is stable across runs for diffing.\n */\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') return obj;\n if (Array.isArray(obj)) return obj.map(sortObjectKeys);\n\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj as Record<string, unknown>).sort()) {\n sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n/**\n * Build wire format from generateText result.\n * Captures complete request/response for session logging.\n *\n * Uses loose typing to handle AI SDK's complex result structure.\n */\nfunction buildWireFormat(\n systemPrompt: string,\n contextPrompt: string,\n tools: Record<string, Tool>,\n result: {\n steps: {\n toolCalls: { toolName: string; input?: unknown }[];\n toolResults?: { toolName: string; result?: unknown }[];\n text?: string | null;\n }[];\n usage?: { inputTokens?: number; outputTokens?: number };\n },\n): WireFormat {\n // Build response steps (omit toolCallId for stability)\n const steps: WireResponseStep[] = result.steps.map((step) => ({\n toolCalls: step.toolCalls.map((tc) => ({\n toolName: tc.toolName,\n input: sortObjectKeys(tc.input),\n })),\n toolResults: (step.toolResults ?? []).map((tr) => ({\n toolName: tr.toolName,\n result: sortObjectKeys(tr.result),\n })),\n text: step.text ?? null,\n }));\n\n return {\n request: {\n system: systemPrompt,\n prompt: contextPrompt,\n tools: extractToolSchemas(tools),\n },\n response: {\n steps,\n usage: {\n inputTokens: result.usage?.inputTokens ?? 0,\n outputTokens: result.usage?.outputTokens ?? 0,\n },\n },\n };\n}\n\n// =============================================================================\n// Context Building\n// =============================================================================\n\n/**\n * Extract doc blocks of a specific tag type for a given ref.\n */\nfunction getDocBlocks(docs: DocumentationBlock[], ref: string, tag: string): DocumentationBlock[] {\n return docs.filter((d) => d.ref === ref && d.tag === tag);\n}\n\n/**\n * Build a composed system prompt from form instructions.\n *\n * Instruction sources (later ones augment earlier):\n * 1. Base form instructions - Doc blocks with ref=formId and tag=\"instructions\"\n * 2. Role-specific instructions - From form.metadata.roleInstructions[targetRole]\n * 3. Per-field instructions - Doc blocks with ref=fieldId and tag=\"instructions\"\n * 4. System defaults - DEFAULT_ROLE_INSTRUCTIONS[targetRole] or DEFAULT_SYSTEM_PROMPT\n */\nfunction buildSystemPrompt(form: ParsedForm, targetRole: string, issues: InspectIssue[]): string {\n const sections: string[] = [];\n\n // Start with base system prompt guidelines\n sections.push(DEFAULT_SYSTEM_PROMPT);\n\n // 1. Form-level instructions (doc blocks with kind=\"instructions\" for the form)\n const formInstructions = getDocBlocks(form.docs, form.schema.id, 'instructions');\n if (formInstructions.length > 0) {\n sections.push('');\n sections.push(SECTION_HEADERS.formInstructions);\n for (const doc of formInstructions) {\n sections.push(doc.bodyMarkdown.trim());\n }\n }\n\n // 2. Role-specific instructions from frontmatter\n const roleInstructions = form.metadata?.roleInstructions?.[targetRole];\n if (roleInstructions) {\n sections.push('');\n sections.push(SECTION_HEADERS.roleInstructions(targetRole));\n sections.push(roleInstructions);\n } else {\n // Fallback to default role instructions\n const defaultRoleInstr = DEFAULT_ROLE_INSTRUCTIONS[targetRole];\n if (defaultRoleInstr) {\n sections.push('');\n sections.push(SECTION_HEADERS.roleGuidance);\n sections.push(defaultRoleInstr);\n }\n }\n\n // 3. Per-field instructions for fields being addressed\n const fieldIds = new Set(issues.filter((i) => i.scope === 'field').map((i) => i.ref));\n const fieldInstructions: string[] = [];\n\n for (const fieldId of fieldIds) {\n const fieldDocs = getDocBlocks(form.docs, fieldId, 'instructions');\n if (fieldDocs.length > 0) {\n for (const doc of fieldDocs) {\n fieldInstructions.push(`**${fieldId}:** ${doc.bodyMarkdown.trim()}`);\n }\n }\n }\n\n if (fieldInstructions.length > 0) {\n sections.push('');\n sections.push(SECTION_HEADERS.fieldInstructions);\n sections.push(...fieldInstructions);\n }\n\n return sections.join('\\n');\n}\n\n/**\n * Build a context prompt with full form state and remaining issues.\n *\n * The form markdown shows the agent exactly what's been filled so far,\n * making each turn stateless - all state is in the form itself.\n *\n * @param issues - Current issues to address\n * @param form - Current form state\n * @param maxPatches - Maximum patches to generate\n * @param previousRejections - Rejections from previous turn (helps LLM learn from mistakes)\n */\nfunction buildContextPrompt(\n issues: InspectIssue[],\n form: ParsedForm,\n maxPatches: number,\n previousRejections?: PatchRejection[],\n): string {\n const lines: string[] = [];\n\n // If there were rejections from previous turn, show them first so the model learns\n if (previousRejections && previousRejections.length > 0) {\n lines.push('# Previous Patch Errors');\n lines.push('');\n lines.push(\n 'Your previous patches were rejected due to the following errors. Please fix these issues:',\n );\n lines.push('');\n for (const rejection of previousRejections) {\n lines.push(`- **Error:** ${rejection.message}`);\n // If we have field info, explain the type mismatch and show correct format\n if (rejection.fieldKind) {\n lines.push(\n ` **Correction:** This field is type \"${rejection.fieldKind}\". Use set_${rejection.fieldKind} instead.`,\n );\n const hint = getPatchFormatHint(\n rejection.fieldKind,\n rejection.fieldId,\n rejection.columnIds,\n );\n lines.push(` **Correct format:** ${hint}`);\n }\n }\n lines.push('');\n }\n\n // Include full form markdown so agent sees current state\n lines.push('# Current Form State');\n lines.push('');\n lines.push('Below is the complete form with all currently filled values.');\n lines.push('Fields marked with `[ ]` or empty values still need to be filled.');\n lines.push('');\n lines.push('```markdown');\n lines.push(serializeForm(form));\n lines.push('```');\n lines.push('');\n\n // List remaining issues\n lines.push(ISSUES_HEADER);\n lines.push('');\n lines.push(getIssuesIntro(issues.length));\n lines.push('');\n\n for (const issue of issues) {\n lines.push(`- **${issue.ref}** (${issue.scope}): ${issue.message}`);\n lines.push(` Severity: ${issue.severity}, Priority: P${issue.priority}`);\n\n // If it's a field issue, include field schema info and inline instructions\n if (issue.scope === 'field') {\n const field = findField(form, issue.ref);\n if (field) {\n lines.push(` Type: ${field.kind}`);\n\n // Collect option IDs for fields with options\n let optionIds: string[] | undefined;\n if ('options' in field && field.options) {\n optionIds = field.options.map((o) => o.id);\n lines.push(` Options: ${optionIds.join(', ')}`);\n }\n\n // Show checkbox mode\n let checkboxMode: 'simple' | 'multi' | 'explicit' | undefined;\n if (field.kind === 'checkboxes' && 'checkboxMode' in field) {\n checkboxMode = (field.checkboxMode as 'simple' | 'multi' | 'explicit') ?? 'multi';\n lines.push(` Mode: ${checkboxMode}`);\n }\n\n // For table fields, show column IDs so the model knows the expected row structure\n let columnIds: string[] | undefined;\n if (field.kind === 'table' && 'columns' in field && field.columns) {\n columnIds = field.columns.map((c) => c.id);\n const columnInfo = field.columns\n .map((c) => `${c.id}${c.required ? ' (required)' : ''}`)\n .join(', ');\n lines.push(` Columns: ${columnInfo}`);\n if (field.minRows !== undefined || field.maxRows !== undefined) {\n const constraints = [];\n if (field.minRows !== undefined) constraints.push(`min: ${field.minRows}`);\n if (field.maxRows !== undefined) constraints.push(`max: ${field.maxRows}`);\n lines.push(` Rows: ${constraints.join(', ')}`);\n }\n }\n\n // Add inline instructions for this field with concrete examples\n const patchHint = getPatchFormatHint(field.kind, {\n fieldId: field.id,\n columnIds,\n checkboxMode,\n optionIds,\n });\n lines.push(` Set: ${patchHint}`);\n\n // Show skip instruction for optional fields, or required notice\n if (issue.severity === 'required') {\n lines.push(` This field is required.`);\n } else {\n lines.push(` Skip: { op: \"skip_field\", fieldId: \"${field.id}\", reason: \"...\" }`);\n }\n }\n }\n lines.push('');\n }\n\n lines.push(GENERAL_INSTRUCTIONS);\n\n return lines.join('\\n');\n}\n\n/**\n * Find a field by ID in the form.\n */\nfunction findField(form: ParsedForm, fieldId: string) {\n for (const group of form.schema.groups) {\n for (const field of group.children) {\n if (field.id === fieldId) {\n return field;\n }\n }\n }\n return null;\n}\n\n// =============================================================================\n// Tool Wrapping for Callbacks\n// =============================================================================\n\n/**\n * Wrap tools with callbacks for observability.\n *\n * Only wraps tools that have an execute function.\n * Declarative tools (schema only) are passed through unchanged.\n */\nfunction wrapToolsWithCallbacks(\n tools: Record<string, Tool>,\n callbacks?: FillCallbacks,\n provider?: string,\n executionId = '0-serial',\n): Record<string, Tool> {\n // Skip wrapping if no tool callbacks\n if (!callbacks?.onToolStart && !callbacks?.onToolEnd && !callbacks?.onWebSearch) {\n return tools;\n }\n\n const wrapped: Record<string, Tool> = {};\n for (const [name, tool] of Object.entries(tools)) {\n // Check if tool has an execute function we can wrap\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment\n const execute = (tool as any).execute;\n if (typeof execute === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n wrapped[name] = wrapTool(name, tool, execute, callbacks, provider, executionId);\n } else {\n // Pass through declarative tools unchanged\n wrapped[name] = tool;\n }\n }\n return wrapped;\n}\n\n/**\n * Wrap a single tool with callbacks.\n */\nfunction wrapTool(\n name: string,\n tool: Tool,\n originalExecute: (input: unknown) => Promise<unknown>,\n callbacks: FillCallbacks,\n provider: string | undefined,\n executionId: string,\n): Tool {\n return {\n ...tool,\n execute: async (input: unknown) => {\n const startTime = Date.now();\n\n // Call onToolStart (errors don't abort)\n if (callbacks.onToolStart) {\n try {\n callbacks.onToolStart({ name, input, executionId });\n } catch {\n // Ignore callback errors\n }\n }\n\n try {\n const output = await originalExecute(input);\n\n // Call onToolEnd on success (errors don't abort)\n if (callbacks.onToolEnd) {\n try {\n callbacks.onToolEnd({\n name,\n output,\n durationMs: Date.now() - startTime,\n executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Check if this is a web search tool and call onWebSearch\n if (callbacks.onWebSearch && isWebSearchTool(name)) {\n try {\n const webSearchInfo = extractWebSearchInfo(input, output, provider ?? 'unknown');\n if (webSearchInfo) {\n callbacks.onWebSearch({ ...webSearchInfo, executionId });\n }\n } catch {\n // Ignore callback errors\n }\n }\n\n return output;\n } catch (error) {\n // Call onToolEnd on error (errors don't abort)\n if (callbacks.onToolEnd) {\n try {\n callbacks.onToolEnd({\n name,\n output: null,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n executionId,\n });\n } catch {\n // Ignore callback errors\n }\n }\n throw error;\n }\n },\n };\n}\n\n/**\n * Check if a tool name indicates a web search tool.\n */\nfunction isWebSearchTool(name: string): boolean {\n return name === 'web_search' || name === 'google_search' || name.includes('search');\n}\n\n/**\n * Extract web search info from tool input/output.\n * Different providers may have different structures.\n */\nfunction extractWebSearchInfo(\n input: unknown,\n output: unknown,\n provider: string,\n): { query: string; resultCount: number; provider: string } | undefined {\n // Try to extract query from input\n let query: string | undefined;\n if (input && typeof input === 'object') {\n const inputObj = input as Record<string, unknown>;\n if (typeof inputObj.query === 'string') {\n query = inputObj.query;\n } else if (typeof inputObj.q === 'string') {\n query = inputObj.q;\n }\n }\n\n if (!query) {\n return undefined;\n }\n\n // Try to extract result count from output\n let resultCount = 0;\n if (output && typeof output === 'object') {\n const outputObj = output as Record<string, unknown>;\n // Common patterns for result count\n if (Array.isArray(outputObj.results)) {\n resultCount = outputObj.results.length;\n } else if (Array.isArray(outputObj.searchResults)) {\n resultCount = outputObj.searchResults.length;\n } else if (typeof outputObj.resultCount === 'number') {\n resultCount = outputObj.resultCount;\n } else if (typeof outputObj.totalResults === 'number') {\n resultCount = outputObj.totalResults;\n }\n }\n\n return { query, resultCount, provider };\n}\n\n// =============================================================================\n// Web Search Tools\n// =============================================================================\n\n/**\n * Load web search tools for a provider.\n * Uses centralized config from llms.ts.\n */\nfunction loadWebSearchTools(provider: string): Record<string, Tool> {\n const config = getWebSearchConfig(provider);\n if (!config?.toolName) return {};\n\n switch (provider) {\n case 'openai': {\n const tool = openai.tools?.webSearch?.({}) ?? openai.tools?.webSearchPreview?.({});\n if (tool) return { web_search: tool as Tool };\n return {};\n }\n case 'anthropic': {\n const tool = anthropic.tools?.webSearch_20250305?.({});\n if (tool) return { web_search: tool as Tool };\n return {};\n }\n case 'google': {\n const tool = google.tools?.googleSearch?.({});\n if (tool) return { google_search: tool as Tool };\n return {};\n }\n case 'xai': {\n const tool = xai.tools?.webSearch?.({});\n if (tool) return { web_search: tool as Tool };\n return {};\n }\n default:\n return {};\n }\n}\n\n// =============================================================================\n// Factory Function\n// =============================================================================\n\n/**\n * Create a live agent with the given configuration.\n */\nexport function createLiveAgent(config: LiveAgentConfig): LiveAgent {\n return new LiveAgent(config);\n}\n\n// =============================================================================\n// Mock Wire Format Support\n// =============================================================================\n\n/**\n * Build wire format for mock sessions.\n *\n * This captures what WOULD be sent to the LLM in a mock session,\n * enabling git-based testing where prompt changes are visible in diffs.\n *\n * @param form - Current form state\n * @param issues - Issues being addressed\n * @param patches - Patches generated by mock agent\n * @param maxPatches - Max patches per turn\n * @param targetRole - Target role for instructions\n * @param previousRejections - Rejections from previous turn\n */\nexport function buildMockWireFormat(\n form: ParsedForm,\n issues: InspectIssue[],\n patches: Patch[],\n maxPatches: number,\n targetRole: string = AGENT_ROLE,\n previousRejections?: PatchRejection[],\n): WireFormat {\n // Build prompts exactly as LiveAgent would\n const systemPrompt = buildSystemPrompt(form, targetRole, issues);\n const contextPrompt = buildContextPrompt(issues, form, maxPatches, previousRejections);\n\n // Build tool schema for fill_form\n // Note: Using lowercase 'patch' in $defs to avoid case conversion issues in YAML serialization\n // (uppercase 'Patch' would become '_patch' in snake_case, breaking the $ref)\n const tools: Record<string, { description: string; inputSchema: unknown }> = {\n [FILL_FORM_TOOL_NAME]: {\n description: FILL_FORM_TOOL_DESCRIPTION,\n inputSchema: sortObjectKeys({\n type: 'object',\n properties: {\n patches: {\n type: 'array',\n items: { $ref: '#/$defs/patch' },\n description: 'Array of patches to apply to the form',\n },\n },\n required: ['patches'],\n $defs: {\n patch: { description: 'A patch operation (see tool description for full schema)' },\n },\n }),\n },\n };\n\n // Build simulated response from mock patches\n const steps: WireResponseStep[] = [\n {\n toolCalls: [\n {\n toolName: FILL_FORM_TOOL_NAME,\n input: sortObjectKeys({ patches }),\n },\n ],\n toolResults: [],\n text: null,\n },\n ];\n\n return {\n request: {\n system: systemPrompt,\n prompt: contextPrompt,\n tools,\n },\n response: {\n steps,\n usage: {\n inputTokens: 0, // Mock doesn't use LLM\n outputTokens: 0,\n },\n },\n };\n}\n","/**\n * Model Resolver - Parse and resolve AI SDK model identifiers.\n *\n * Parses model IDs in the format `provider/model-id` and dynamically\n * imports the corresponding AI SDK provider.\n */\n\nimport type { LanguageModel } from 'ai';\n\nimport { MarkformConfigError } from '../errors.js';\nimport type { ParsedModelId, ProviderInfo, ProviderName, ResolvedModel } from './harnessTypes.js';\n\n// Re-export types for backwards compatibility\nexport type { ParsedModelId, ProviderInfo, ProviderName, ResolvedModel } from './harnessTypes.js';\n\n/**\n * Map of provider names to their npm package and env var.\n */\nconst PROVIDERS: Record<ProviderName, { package: string; envVar: string; createFn: string }> = {\n anthropic: {\n package: '@ai-sdk/anthropic',\n envVar: 'ANTHROPIC_API_KEY',\n createFn: 'createAnthropic',\n },\n openai: {\n package: '@ai-sdk/openai',\n envVar: 'OPENAI_API_KEY',\n createFn: 'createOpenAI',\n },\n google: {\n package: '@ai-sdk/google',\n envVar: 'GOOGLE_GENERATIVE_AI_API_KEY',\n createFn: 'createGoogleGenerativeAI',\n },\n xai: {\n package: '@ai-sdk/xai',\n envVar: 'XAI_API_KEY',\n createFn: 'createXai',\n },\n deepseek: {\n package: '@ai-sdk/deepseek',\n envVar: 'DEEPSEEK_API_KEY',\n createFn: 'createDeepSeek',\n },\n};\n\n// =============================================================================\n// Model Resolution\n// =============================================================================\n\n/**\n * Parse a model ID string into provider and model components.\n *\n * @param modelIdString - Model ID in format `provider/model-id`\n * @returns Parsed model identifier\n * @throws Error if format is invalid\n */\nexport function parseModelId(modelIdString: string): ParsedModelId {\n const slashIndex = modelIdString.indexOf('/');\n if (slashIndex === -1) {\n throw new MarkformConfigError(\n `Invalid model ID format: \"${modelIdString}\". Expected format: provider/model-id (e.g., anthropic/claude-sonnet-4-5)`,\n { option: 'model', expectedType: 'provider/model-id format', receivedValue: modelIdString },\n );\n }\n\n const provider = modelIdString.slice(0, slashIndex);\n const modelId = modelIdString.slice(slashIndex + 1);\n\n if (!provider || !modelId) {\n throw new MarkformConfigError(\n `Invalid model ID format: \"${modelIdString}\". Both provider and model ID are required.`,\n {\n option: 'model',\n expectedType: 'non-empty provider and model-id',\n receivedValue: modelIdString,\n },\n );\n }\n\n const supportedProviders = Object.keys(PROVIDERS);\n if (!supportedProviders.includes(provider)) {\n throw new MarkformConfigError(\n `Unknown provider: \"${provider}\". Supported providers: ${supportedProviders.join(', ')}`,\n {\n option: 'model',\n expectedType: `one of: ${supportedProviders.join(', ')}`,\n receivedValue: provider,\n },\n );\n }\n\n return {\n provider: provider as ProviderName,\n modelId,\n };\n}\n\n/**\n * Resolve a model ID string to an AI SDK language model.\n *\n * Dynamically imports the provider package and creates the model instance.\n *\n * @param modelIdString - Model ID in format `provider/model-id`\n * @returns Resolved model with provider info\n * @throws Error if provider not installed or API key missing\n */\nexport async function resolveModel(modelIdString: string): Promise<ResolvedModel> {\n const { provider, modelId } = parseModelId(modelIdString);\n const providerConfig = PROVIDERS[provider];\n\n // Check for API key\n const apiKey = process.env[providerConfig.envVar];\n if (!apiKey) {\n throw new MarkformConfigError(\n `Missing API key for \"${provider}\" provider (model: ${modelIdString}).\\n` +\n `Set the ${providerConfig.envVar} environment variable or add it to your .env file.`,\n { option: providerConfig.envVar, expectedType: 'API key string', receivedValue: undefined },\n );\n }\n\n // Dynamically import the provider\n let providerModule: Record<string, (modelId: string) => LanguageModel>;\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n providerModule = await import(providerConfig.package);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes('Cannot find module') || message.includes('ERR_MODULE_NOT_FOUND')) {\n throw new MarkformConfigError(\n `Provider package not installed for model \"${modelIdString}\".\\n` +\n `Install with: pnpm add ${providerConfig.package}`,\n {\n option: 'model',\n expectedType: 'installed provider package',\n receivedValue: providerConfig.package,\n },\n );\n }\n throw error;\n }\n\n // Get the createProvider function (e.g., createAnthropic, createOpenAI, createGoogleGenerativeAI)\n const createFn = providerModule[providerConfig.createFn] as // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | ((options: { apiKey: string }) => any)\n | undefined;\n\n let model: LanguageModel;\n\n if (createFn && typeof createFn === 'function') {\n // Use the factory function with explicit API key\n // The provider instance is callable: providerInstance(modelId) returns a LanguageModel\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call\n model = createFn({ apiKey })(modelId);\n } else {\n // Fallback: try the simple provider function (for backwards compatibility)\n const providerFn = providerModule[provider] as ((modelId: string) => LanguageModel) | undefined;\n if (typeof providerFn !== 'function') {\n throw new MarkformConfigError(\n `Provider package \"${providerConfig.package}\" does not export expected function \"${provider}\" or \"${providerConfig.createFn}\"`,\n {\n option: 'model',\n expectedType: 'valid provider export',\n receivedValue: Object.keys(providerModule).join(', '),\n },\n );\n }\n model = providerFn(modelId);\n }\n\n return {\n model,\n provider,\n modelId,\n };\n}\n\n/**\n * Get list of supported provider names.\n */\nexport function getProviderNames(): ProviderName[] {\n return Object.keys(PROVIDERS) as ProviderName[];\n}\n\n/**\n * Get provider info for display purposes.\n */\nexport function getProviderInfo(provider: ProviderName): ProviderInfo {\n const config = PROVIDERS[provider];\n return {\n package: config.package,\n envVar: config.envVar,\n };\n}\n","/**\n * Parallel Harness - Orchestrates concurrent agent execution for parallel form filling.\n *\n * Uses the execution plan to identify parallel batches and order levels,\n * spawns concurrent agents for batch items, merges patches, and applies them.\n */\n\nimport { applyPatches } from '../engine/apply.js';\nimport type {\n ExecutionPlan,\n ExecutionPlanItem,\n InspectIssue,\n ParsedForm,\n Patch,\n} from '../engine/coreTypes.js';\nimport { computeExecutionPlan } from '../engine/executionPlan.js';\nimport { inspect } from '../engine/inspect.js';\nimport { DEFAULT_MAX_PARALLEL_AGENTS } from '../settings.js';\nimport type { Agent, AgentResponse } from './harnessTypes.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Scoped fill request for a parallel agent.\n * Provides the full form for context but limits the agent to specific fields.\n */\nexport interface ScopedFillRequest {\n /** Full form for read-only context */\n form: ParsedForm;\n /** Field IDs this agent should fill */\n targetFieldIds: string[];\n /** Group IDs this agent is responsible for */\n targetGroupIds: string[];\n /** Issues scoped to target fields */\n issues: InspectIssue[];\n}\n\n/**\n * Result of running a single order level.\n */\nexport interface ParallelStepResult {\n /** Total patches applied in this order level */\n patchesApplied: number;\n /** Whether any errors occurred */\n errors: string[];\n}\n\n/**\n * Result of running all order levels.\n */\nexport interface ParallelRunResult {\n /** Whether the form is complete */\n isComplete: boolean;\n /** Total patches applied across all levels */\n totalPatchesApplied: number;\n /** Order levels processed */\n orderLevelsProcessed: number[];\n /** Errors from any level */\n errors: string[];\n}\n\n/**\n * Configuration for the parallel harness.\n */\nexport interface ParallelHarnessConfig {\n /** Maximum concurrent agents for parallel batches (default: DEFAULT_MAX_PARALLEL_AGENTS) */\n maxParallelAgents?: number;\n /** Factory to create scoped agents for parallel batch items */\n agentFactory?: (request: ScopedFillRequest) => Agent;\n /** Callback when a parallel batch starts */\n onBatchStart?: (batchId: string) => void;\n /** Callback when a parallel batch completes */\n onBatchComplete?: (batchId: string) => void;\n /** Callback when an order level starts processing */\n onOrderLevelStart?: (order: number) => void;\n /** Callback when an order level completes */\n onOrderLevelComplete?: (order: number) => void;\n /** Target roles (default: ['agent']) */\n targetRoles?: string[];\n /** Max patches per agent turn */\n maxPatchesPerTurn?: number;\n}\n\n// =============================================================================\n// Scope Filtering\n// =============================================================================\n\n/**\n * Get field IDs that belong to an execution plan item.\n */\nexport function getFieldIdsForItem(form: ParsedForm, item: ExecutionPlanItem): string[] {\n if (item.itemType === 'field') {\n return [item.itemId];\n }\n const group = form.schema.groups.find((g) => g.id === item.itemId);\n if (!group) return [];\n return group.children.map((f) => f.id);\n}\n\n/**\n * Filter issues to only those relevant to an execution plan item's fields.\n * Form-scoped issues are excluded (they don't belong to individual agents).\n */\nexport function scopeIssuesForItem(\n form: ParsedForm,\n item: ExecutionPlanItem,\n allIssues: InspectIssue[],\n): InspectIssue[] {\n const targetFieldIds = new Set(getFieldIdsForItem(form, item));\n\n return allIssues.filter((issue) => {\n if (issue.scope === 'form') return false;\n if (issue.scope === 'field') return targetFieldIds.has(issue.ref);\n if (issue.scope === 'option') {\n // Option refs are \"fieldId.optionId\"\n const dotIndex = issue.ref.indexOf('.');\n const fieldId = dotIndex > 0 ? issue.ref.slice(0, dotIndex) : issue.ref;\n return targetFieldIds.has(fieldId);\n }\n if (issue.scope === 'cell') {\n // Cell refs are \"fieldId.columnId[rowIndex]\"\n const dotIndex = issue.ref.indexOf('.');\n const fieldId = dotIndex > 0 ? issue.ref.slice(0, dotIndex) : issue.ref;\n return targetFieldIds.has(fieldId);\n }\n return false;\n });\n}\n\n// =============================================================================\n// Parallel Harness\n// =============================================================================\n\n/**\n * Parallel harness that orchestrates concurrent agent execution.\n */\nexport class ParallelHarness {\n private form: ParsedForm;\n private plan: ExecutionPlan;\n private config: ParallelHarnessConfig;\n\n constructor(form: ParsedForm, config: ParallelHarnessConfig = {}) {\n this.form = form;\n this.plan = computeExecutionPlan(form);\n this.config = config;\n }\n\n /**\n * Get the execution plan.\n */\n getExecutionPlan(): ExecutionPlan {\n return this.plan;\n }\n\n /**\n * Run a single order level: execute loose serial items with the primary agent,\n * and parallel batch items concurrently.\n */\n async runOrderLevel(order: number, primaryAgent: Agent): Promise<ParallelStepResult> {\n const maxPatches = this.config.maxPatchesPerTurn ?? 20;\n let totalPatchesApplied = 0;\n const errors: string[] = [];\n\n // Get current issues for this form state\n const inspectResult = inspect(this.form);\n const allIssues = inspectResult.issues;\n\n // 1. Run loose serial items with primary agent\n const looseItems = this.plan.looseSerial.filter((i) => i.order === order);\n for (const item of looseItems) {\n const scopedIssues = scopeIssuesForItem(this.form, item, allIssues);\n if (scopedIssues.length === 0) continue;\n\n try {\n const response = await primaryAgent.fillFormTool(scopedIssues, this.form, maxPatches);\n if (response.patches.length > 0) {\n const result = applyPatches(this.form, response.patches);\n totalPatchesApplied += result.appliedPatches.length;\n }\n } catch (err) {\n errors.push(`Loose serial item ${item.itemId}: ${String(err)}`);\n }\n }\n\n // 2. Run parallel batch items concurrently\n for (const batch of this.plan.parallelBatches) {\n const batchItems = batch.items.filter((i) => i.order === order);\n if (batchItems.length === 0) continue;\n\n this.config.onBatchStart?.(batch.batchId);\n\n // Re-inspect after loose serial to get updated issues\n const batchInspect = inspect(this.form);\n const batchIssues = batchInspect.issues;\n\n const maxConcurrent = this.config.maxParallelAgents ?? DEFAULT_MAX_PARALLEL_AGENTS;\n\n // Create promise factories for each batch item (for true concurrency limiting)\n const agentFactories: (() => Promise<AgentResponse>)[] = [];\n const itemFieldIds = new Map<number, string[]>();\n\n for (let i = 0; i < batchItems.length; i++) {\n const item = batchItems[i]!;\n const scopedIssues = scopeIssuesForItem(this.form, item, batchIssues);\n const targetFieldIds = getFieldIdsForItem(this.form, item);\n itemFieldIds.set(i, targetFieldIds);\n\n if (scopedIssues.length === 0) {\n agentFactories.push(() => Promise.resolve({ patches: [] }));\n continue;\n }\n\n const request: ScopedFillRequest = {\n form: this.form,\n targetFieldIds,\n targetGroupIds: item.itemType === 'group' ? [item.itemId] : [],\n issues: scopedIssues,\n };\n\n // Use agentFactory if provided, otherwise use primary agent\n const agent = this.config.agentFactory ? this.config.agentFactory(request) : primaryAgent;\n\n // Wrap in factory so promise starts when slot is available\n agentFactories.push(() => agent.fillFormTool(scopedIssues, this.form, maxPatches));\n }\n\n // Run with concurrency limit (factories are called lazily)\n const results = await runWithConcurrency(agentFactories, maxConcurrent);\n\n // Merge all patches from parallel agents\n const allPatches: Patch[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n allPatches.push(...result.value.patches);\n } else {\n errors.push(`Parallel agent error: ${result.reason}`);\n }\n }\n\n // Apply merged patches in one call\n if (allPatches.length > 0) {\n const applyResult = applyPatches(this.form, allPatches);\n totalPatchesApplied += applyResult.appliedPatches.length;\n }\n\n this.config.onBatchComplete?.(batch.batchId);\n }\n\n return { patchesApplied: totalPatchesApplied, errors };\n }\n\n /**\n * Run all order levels sequentially, filling the entire form.\n */\n async runAll(primaryAgent: Agent): Promise<ParallelRunResult> {\n let totalPatchesApplied = 0;\n const orderLevelsProcessed: number[] = [];\n const allErrors: string[] = [];\n\n for (const order of this.plan.orderLevels) {\n this.config.onOrderLevelStart?.(order);\n\n const result = await this.runOrderLevel(order, primaryAgent);\n totalPatchesApplied += result.patchesApplied;\n orderLevelsProcessed.push(order);\n allErrors.push(...result.errors);\n\n this.config.onOrderLevelComplete?.(order);\n }\n\n // Check final form state\n const finalInspect = inspect(this.form);\n\n return {\n isComplete: finalInspect.isComplete,\n totalPatchesApplied,\n orderLevelsProcessed,\n errors: allErrors,\n };\n }\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Run promise factories with a concurrency limit.\n * Takes an array of functions that create promises (factories), not already-started promises.\n * This ensures concurrency limiting actually works - promises are started lazily.\n * Returns results in the same order as input.\n */\nexport async function runWithConcurrency<T>(\n factories: (() => Promise<T>)[],\n maxConcurrent: number,\n): Promise<PromiseSettledResult<T>[]> {\n if (factories.length === 0) {\n return [];\n }\n\n if (maxConcurrent >= factories.length) {\n // Start all and await - no limiting needed\n // Use async wrapper to convert sync throws to rejected promises\n return Promise.allSettled(factories.map(async (f) => f()));\n }\n\n // Semaphore-based concurrency limiter with lazy promise creation\n const results: PromiseSettledResult<T>[] = new Array<PromiseSettledResult<T>>(factories.length);\n let nextIndex = 0;\n\n async function runNext(): Promise<void> {\n while (nextIndex < factories.length) {\n const idx = nextIndex++;\n const factory = factories[idx];\n if (!factory) continue;\n try {\n const value = await factory(); // Create promise here, when slot is available\n results[idx] = { status: 'fulfilled', value };\n } catch (reason) {\n results[idx] = { status: 'rejected', reason };\n }\n }\n }\n\n const workers = Array.from({ length: Math.min(maxConcurrent, factories.length) }, () =>\n runNext(),\n );\n await Promise.all(workers);\n\n return results;\n}\n\n// =============================================================================\n// Factory\n// =============================================================================\n\n/**\n * Create a parallel harness for the given form.\n */\nexport function createParallelHarness(\n form: ParsedForm,\n config?: ParallelHarnessConfig,\n): ParallelHarness {\n return new ParallelHarness(form, config);\n}\n","/**\n * Programmatic Fill API - High-level entry point for form filling.\n *\n * Provides a single-function API for external agentic systems to execute\n * form-filling sessions with a single function call.\n */\n\nimport type { LanguageModel } from 'ai';\n\nimport { applyPatches } from '../engine/apply.js';\nimport type {\n ExecutionPlanItem,\n FieldValue,\n InspectIssue,\n ParsedForm,\n Patch,\n PatchRejection,\n SessionTurnContext,\n SessionTurnStats,\n} from '../engine/coreTypes.js';\nimport { computeExecutionPlan } from '../engine/executionPlan.js';\nimport { inspect } from '../engine/inspect.js';\nimport { parseForm } from '../engine/parse.js';\nimport { serializeForm } from '../engine/serialize.js';\nimport { coerceInputContext } from '../engine/valueCoercion.js';\nimport {\n AGENT_ROLE,\n DEFAULT_MAX_ISSUES_PER_TURN,\n DEFAULT_MAX_PARALLEL_AGENTS,\n DEFAULT_MAX_PATCHES_PER_TURN,\n DEFAULT_MAX_TURNS,\n} from '../settings.js';\nimport { computeProgressSummary, computeStructureSummary } from '../engine/summaries.js';\nimport type { ProgressCounts } from '../engine/coreTypes.js';\nimport type { FillRecord } from './fillRecord.js';\nimport { FillRecordCollector } from './fillRecordCollector.js';\nimport { createHarness } from './harness.js';\nimport { createLiveAgent } from './liveAgent.js';\nimport { resolveModel } from './modelResolver.js';\nimport { runWithConcurrency, scopeIssuesForItem } from './parallelHarness.js';\nimport type { Agent, FillOptions, FillResult, FillStatus, TurnStats } from './harnessTypes.js';\n\n// Re-export types for backwards compatibility\nexport type { FillOptions, FillResult, FillStatus, TurnProgress } from './harnessTypes.js';\n\n// =============================================================================\n// Execution ID Helpers\n// =============================================================================\n\n/**\n * Execution ID format for tracking parallel and serial execution threads.\n *\n * Format: `eid:{type}:o{order}[:{batchId}:i{index}]`\n *\n * Components:\n * - `eid:` - Prefix identifying this as an execution ID\n * - `{type}` - Either `serial` or `batch`\n * - `o{order}` - Order level (e.g., `o0`, `o10`)\n * - For batch only: `:{batchId}:i{index}` - Batch name and item index\n *\n * Examples:\n * - `eid:serial:o0` - Serial execution at order level 0\n * - `eid:batch:o0:research:i0` - First item in \"research\" batch at order 0\n * - `eid:batch:o0:research:i3` - Fourth item in \"research\" batch at order 0\n * - `eid:serial:o10` - Serial execution at order level 10\n *\n * Design principles:\n * - Self-identifying: Clear `eid:` prefix\n * - Structured: Type comes first for easy filtering\n * - Explicit: Each component has a prefix (`o` for order, `i` for index)\n * - Parseable: Can be split on `:` to extract components\n */\n\n/** Prefix for all execution IDs */\nconst EXECUTION_ID_PREFIX = 'eid';\n\n/**\n * Create an execution ID for serial execution at an order level.\n */\nexport function serialExecutionId(order: number): string {\n return `${EXECUTION_ID_PREFIX}:serial:o${order}`;\n}\n\n/**\n * Create an execution ID for a batch item at an order level.\n */\nexport function batchExecutionId(order: number, batchId: string, itemIndex: number): string {\n return `${EXECUTION_ID_PREFIX}:batch:o${order}:${batchId}:i${itemIndex}`;\n}\n\n/**\n * Parse an execution ID into its components.\n * Returns null if the ID doesn't match the expected format.\n */\nexport function parseExecutionId(\n id: string,\n):\n | { type: 'serial'; order: number }\n | { type: 'batch'; order: number; batchId: string; itemIndex: number }\n | null {\n if (!id.startsWith(`${EXECUTION_ID_PREFIX}:`)) return null;\n\n const parts = id.split(':');\n if (parts.length < 3) return null;\n\n const type = parts[1];\n const orderPart = parts[2];\n\n if (!orderPart?.startsWith('o')) return null;\n const order = parseInt(orderPart.slice(1), 10);\n if (isNaN(order)) return null;\n\n if (type === 'serial') {\n return { type: 'serial', order };\n } else if (type === 'batch' && parts.length >= 5) {\n const batchId = parts[3];\n const indexPart = parts[4];\n if (!indexPart?.startsWith('i') || !batchId) return null;\n const itemIndex = parseInt(indexPart.slice(1), 10);\n if (isNaN(itemIndex)) return null;\n return { type: 'batch', order, batchId, itemIndex };\n }\n\n return null;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Get current progress counts for a form.\n * Runs inspect to get issues, then computes progress summary.\n */\nfunction getProgressCounts(form: ParsedForm, targetRoles?: string[]): ProgressCounts {\n const inspectResult = inspect(form, { targetRoles });\n const progressSummary = computeProgressSummary(\n form.schema,\n form.responsesByFieldId,\n form.notes,\n inspectResult.issues,\n );\n return progressSummary.counts;\n}\n\n/**\n * Create a FillRecordCollector if recordFill is enabled.\n */\nfunction createCollectorIfNeeded(\n options: FillOptions,\n form: ParsedForm,\n provider: string,\n model: string,\n): FillRecordCollector | undefined {\n if (!options.recordFill) return undefined;\n\n const structureSummary = computeStructureSummary(form.schema);\n return new FillRecordCollector({\n form: {\n id: form.schema.id,\n title: form.schema.title,\n description: form.schema.description,\n structure: structureSummary,\n },\n provider,\n model,\n parallelEnabled: options.enableParallel,\n maxParallelAgents: options.maxParallelAgents,\n });\n}\n\n/**\n * Log a warning when a user callback throws.\n */\nfunction warnCallbackError(name: string, error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[markform] User callback ${name} threw: ${message}`);\n}\n\n/**\n * Merge user callbacks with collector callbacks.\n * Returns a new callbacks object that forwards to both.\n *\n * Error handling:\n * - Collector callbacks: errors propagate (bugs in our code should surface)\n * - User callbacks: errors are caught and logged as warnings\n */\nfunction mergeCallbacks(\n userCallbacks: FillOptions['callbacks'],\n collector: FillRecordCollector | undefined,\n): FillOptions['callbacks'] {\n if (!collector) return userCallbacks;\n if (!userCallbacks) return collector;\n\n // Create wrapper that forwards to both collector (directly) and user (safely)\n return {\n onTurnStart: (turn) => {\n collector.onTurnStart(turn);\n try {\n userCallbacks.onTurnStart?.(turn);\n } catch (e) {\n warnCallbackError('onTurnStart', e);\n }\n },\n onTurnComplete: (progress) => {\n collector.onTurnComplete(progress);\n try {\n userCallbacks.onTurnComplete?.(progress);\n } catch (e) {\n warnCallbackError('onTurnComplete', e);\n }\n },\n onLlmCallStart: (call) => {\n collector.onLlmCallStart(call);\n try {\n userCallbacks.onLlmCallStart?.(call);\n } catch (e) {\n warnCallbackError('onLlmCallStart', e);\n }\n },\n onLlmCallEnd: (call) => {\n collector.onLlmCallEnd(call);\n try {\n userCallbacks.onLlmCallEnd?.(call);\n } catch (e) {\n warnCallbackError('onLlmCallEnd', e);\n }\n },\n onToolStart: (call) => {\n collector.onToolStart(call);\n try {\n userCallbacks.onToolStart?.(call);\n } catch (e) {\n warnCallbackError('onToolStart', e);\n }\n },\n onToolEnd: (call) => {\n collector.onToolEnd(call);\n try {\n userCallbacks.onToolEnd?.(call);\n } catch (e) {\n warnCallbackError('onToolEnd', e);\n }\n },\n // Forward other callbacks to user only (collector doesn't handle these)\n onIssuesIdentified: userCallbacks.onIssuesIdentified\n ? (info) => {\n try {\n userCallbacks.onIssuesIdentified?.(info);\n } catch (e) {\n warnCallbackError('onIssuesIdentified', e);\n }\n }\n : undefined,\n onPatchesGenerated: userCallbacks.onPatchesGenerated\n ? (info) => {\n try {\n userCallbacks.onPatchesGenerated?.(info);\n } catch (e) {\n warnCallbackError('onPatchesGenerated', e);\n }\n }\n : undefined,\n onOrderLevelStart: userCallbacks.onOrderLevelStart\n ? (info) => {\n try {\n userCallbacks.onOrderLevelStart?.(info);\n } catch (e) {\n warnCallbackError('onOrderLevelStart', e);\n }\n }\n : undefined,\n onOrderLevelComplete: userCallbacks.onOrderLevelComplete\n ? (info) => {\n try {\n userCallbacks.onOrderLevelComplete?.(info);\n } catch (e) {\n warnCallbackError('onOrderLevelComplete', e);\n }\n }\n : undefined,\n onBatchStart: userCallbacks.onBatchStart\n ? (info) => {\n try {\n userCallbacks.onBatchStart?.(info);\n } catch (e) {\n warnCallbackError('onBatchStart', e);\n }\n }\n : undefined,\n onBatchComplete: userCallbacks.onBatchComplete\n ? (info) => {\n try {\n userCallbacks.onBatchComplete?.(info);\n } catch (e) {\n warnCallbackError('onBatchComplete', e);\n }\n }\n : undefined,\n // Forward onWebSearch to both collector (directly) and user (safely)\n onWebSearch: (info) => {\n collector.onWebSearch(info);\n try {\n userCallbacks.onWebSearch?.(info);\n } catch (e) {\n warnCallbackError('onWebSearch', e);\n }\n },\n };\n}\n\nfunction buildErrorResult(\n form: ParsedForm,\n errors: string[],\n warnings: string[],\n record?: FillRecord,\n): FillResult {\n // Extract values from responses\n const values: Record<string, FieldValue> = {};\n for (const [fieldId, response] of Object.entries(form.responsesByFieldId)) {\n if (response.state === 'answered' && response.value) {\n values[fieldId] = response.value;\n }\n }\n\n const result: FillResult = {\n status: {\n ok: false,\n reason: 'error',\n message: errors.join('; '),\n },\n markdown: serializeForm(form),\n values,\n form,\n turns: 0,\n totalPatches: 0,\n inputContextWarnings: warnings.length > 0 ? warnings : undefined,\n };\n\n if (record) {\n result.record = record;\n }\n\n return result;\n}\n\nfunction buildResult(\n form: ParsedForm,\n turns: number,\n totalPatches: number,\n status: FillStatus,\n inputContextWarnings?: string[],\n remainingIssues?: InspectIssue[],\n record?: FillRecord,\n): FillResult {\n // Extract values from responses\n const values: Record<string, FieldValue> = {};\n for (const [fieldId, response] of Object.entries(form.responsesByFieldId)) {\n if (response.state === 'answered' && response.value) {\n values[fieldId] = response.value;\n }\n }\n\n const result: FillResult = {\n status,\n markdown: serializeForm(form),\n values,\n form,\n turns,\n totalPatches,\n };\n\n if (inputContextWarnings && inputContextWarnings.length > 0) {\n result.inputContextWarnings = inputContextWarnings;\n }\n\n if (remainingIssues && remainingIssues.length > 0) {\n result.remainingIssues = remainingIssues.map((issue) => ({\n ref: issue.ref,\n message: issue.message,\n severity: issue.severity,\n priority: issue.priority,\n }));\n }\n\n if (record) {\n result.record = record;\n }\n\n return result;\n}\n\n// =============================================================================\n// Main API\n// =============================================================================\n\n/**\n * Fill a form using an LLM agent.\n *\n * This is the primary programmatic entry point for markform. It encapsulates\n * the harness loop with LiveAgent and provides a single-function call for\n * form filling.\n *\n * @param options - Fill options\n * @returns Fill result with status, values, and markdown\n *\n * @example\n * ```typescript\n * import { fillForm } from 'markform';\n *\n * const result = await fillForm({\n * form: formMarkdown,\n * model: 'anthropic/claude-sonnet-4-5',\n * enableWebSearch: true,\n * inputContext: {\n * company_name: 'Apple Inc.',\n * },\n * systemPromptAddition: `\n * ## Additional Context\n * ${backgroundInfo}\n * `,\n * callbacks: {\n * onTurnComplete: (progress) => {\n * console.log(`Turn ${progress.turnNumber}: ${progress.requiredIssuesRemaining} remaining`);\n * },\n * },\n * });\n *\n * if (result.status.ok) {\n * console.log('Values:', result.values);\n * }\n * ```\n */\nexport async function fillForm(options: FillOptions): Promise<FillResult> {\n // 1. Parse form if string\n let form: ParsedForm;\n try {\n form =\n typeof options.form === 'string' ? parseForm(options.form) : structuredClone(options.form);\n } catch (error) {\n // Return error result for parse failures\n const message = error instanceof Error ? error.message : String(error);\n return {\n status: { ok: false, reason: 'error', message: `Form parse error: ${message}` },\n markdown: typeof options.form === 'string' ? options.form : '',\n values: {},\n form: {\n schema: { id: '', groups: [] },\n responsesByFieldId: {},\n notes: [],\n docs: [],\n orderIndex: [],\n idIndex: new Map(),\n },\n turns: 0,\n totalPatches: 0,\n };\n }\n\n // 2. Resolve model if string (skip if _testAgent provided)\n let model: LanguageModel | undefined;\n let provider: string | undefined;\n if (!options._testAgent) {\n try {\n if (typeof options.model === 'string') {\n const resolved = await resolveModel(options.model);\n model = resolved.model;\n provider = resolved.provider;\n } else {\n model = options.model;\n // When a LanguageModel is passed directly, we can't determine provider\n // Web search will be disabled in this case\n }\n } catch (error) {\n // Model resolution is a pre-fill configuration error - fail fast without FillRecord\n const message = error instanceof Error ? error.message : String(error);\n return buildErrorResult(form, [`Model resolution error: ${message}`], []);\n }\n } else if (typeof options.model === 'string' && options.model.includes('/')) {\n // For test agent, extract provider from model string (e.g., \"mock/model\" -> \"mock\")\n provider = options.model.split('/')[0];\n }\n\n // 3. Create collector if recordFill is enabled\n const modelString = typeof options.model === 'string' ? options.model : 'custom';\n const collector = createCollectorIfNeeded(options, form, provider ?? 'unknown', modelString);\n const mergedCallbacks = mergeCallbacks(options.callbacks, collector);\n\n // 4. Apply input context using coercion layer\n let totalPatches = 0;\n let inputContextWarnings: string[] = [];\n\n if (options.inputContext) {\n const coercionResult = coerceInputContext(form, options.inputContext);\n\n // Input context errors are pre-fill configuration errors - fail fast without FillRecord\n if (coercionResult.errors.length > 0) {\n return buildErrorResult(form, coercionResult.errors, coercionResult.warnings);\n }\n\n // Apply coerced patches\n if (coercionResult.patches.length > 0) {\n applyPatches(form, coercionResult.patches);\n totalPatches = coercionResult.patches.length;\n }\n inputContextWarnings = coercionResult.warnings;\n }\n\n // 5. Check for parallel execution path\n if (options.enableParallel) {\n const plan = computeExecutionPlan(form);\n if (plan.parallelBatches.length > 0) {\n return fillFormParallel(\n form,\n model,\n provider,\n options,\n totalPatches,\n inputContextWarnings,\n collector,\n mergedCallbacks,\n );\n }\n // No parallel batches — fall through to serial path\n }\n\n // 6. Create harness + agent (serial path)\n const maxTurnsTotal = options.maxTurnsTotal ?? DEFAULT_MAX_TURNS;\n const startingTurnNumber = options.startingTurnNumber ?? 0;\n const maxPatchesPerTurn = options.maxPatchesPerTurn ?? DEFAULT_MAX_PATCHES_PER_TURN;\n const maxIssuesPerTurn = options.maxIssuesPerTurn ?? DEFAULT_MAX_ISSUES_PER_TURN;\n const targetRoles = options.targetRoles ?? [AGENT_ROLE];\n\n // Pass remaining turns to harness (accounts for turns already executed in previous calls)\n const remainingTurns = Math.max(0, maxTurnsTotal - startingTurnNumber);\n const harness = createHarness(form, {\n maxTurns: remainingTurns,\n maxPatchesPerTurn,\n maxIssuesPerTurn,\n targetRoles,\n fillMode: options.fillMode,\n });\n\n // Use test agent if provided, otherwise create LiveAgent\n const agent: Agent =\n options._testAgent ??\n createLiveAgent({\n model: model!,\n systemPromptAddition: options.systemPromptAddition,\n targetRole: targetRoles[0] ?? AGENT_ROLE,\n provider,\n enableWebSearch: options.enableWebSearch,\n additionalTools: options.additionalTools,\n callbacks: mergedCallbacks,\n maxStepsPerTurn: options.maxStepsPerTurn,\n toolChoice: options.toolChoice,\n });\n\n // 7. Run harness loop\n let turnCount = startingTurnNumber;\n let turnsThisCall = 0;\n let stepResult = harness.step();\n // Track rejections from previous turn to provide feedback to the LLM\n let previousRejections: PatchRejection[] | undefined;\n\n while (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n // Check per-call limit (before executing any work this turn)\n if (options.maxTurnsThisCall !== undefined && turnsThisCall >= options.maxTurnsThisCall) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'batch_limit');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n {\n ok: false,\n reason: 'batch_limit',\n message: `Reached per-call limit (${options.maxTurnsThisCall} turns)`,\n },\n inputContextWarnings,\n stepResult.issues,\n record,\n );\n }\n // Check for cancellation\n if (options.signal?.aborted) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('cancelled');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n stepResult.issues,\n record,\n );\n }\n\n // Call turn start callback (errors don't abort fill)\n if (mergedCallbacks?.onTurnStart) {\n try {\n mergedCallbacks.onTurnStart({\n turnNumber: turnCount + 1,\n issuesCount: stepResult.issues.length,\n // Default to order 0, serial execution for non-parallel fills\n // Parallel harness will override these values\n order: 0,\n executionId: '0-serial',\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Store issues shown this turn (before agent generates patches)\n const turnIssues = stepResult.issues;\n\n // Call onIssuesIdentified callback (before agent generates patches)\n if (mergedCallbacks?.onIssuesIdentified) {\n try {\n mergedCallbacks.onIssuesIdentified({\n turnNumber: turnCount + 1,\n issues: turnIssues,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Generate patches using agent (pass previous rejections so LLM can learn from mistakes)\n let response: { patches: Patch[]; stats?: TurnStats };\n try {\n response = await agent.fillFormTool(turnIssues, form, maxPatchesPerTurn, previousRejections);\n } catch (error) {\n // Agent threw an error - capture it in fill record and return\n const errorMessage = error instanceof Error ? error.message : String(error);\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('failed', errorMessage);\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'error', message: errorMessage },\n inputContextWarnings,\n turnIssues,\n record,\n );\n }\n const { patches, stats } = response;\n\n // Call onPatchesGenerated callback (after agent, before applying)\n if (mergedCallbacks?.onPatchesGenerated) {\n try {\n mergedCallbacks.onPatchesGenerated({\n turnNumber: turnCount + 1,\n patches,\n stats,\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // Re-check for cancellation after agent call (signal may have fired during LLM call)\n if (options.signal?.aborted) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('cancelled');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n turnIssues,\n record,\n );\n }\n\n // Convert TurnStats to SessionTurnStats (only include fields relevant for session logs)\n let llmStats: SessionTurnStats | undefined;\n let context: SessionTurnContext | undefined;\n if (stats) {\n llmStats = {\n inputTokens: stats.inputTokens,\n outputTokens: stats.outputTokens,\n toolCalls: stats.toolCalls && stats.toolCalls.length > 0 ? stats.toolCalls : undefined,\n };\n // Capture prompts sent to LLM for session logging (helps debug prompt issues)\n if (stats.prompts) {\n context = {\n systemPrompt: stats.prompts.system,\n contextPrompt: stats.prompts.context,\n };\n }\n }\n\n // Apply patches (pass wire format only if captureWireFormat is enabled)\n const wireFormat = options.captureWireFormat ? stats?.wire : undefined;\n stepResult = harness.apply(patches, turnIssues, llmStats, context, wireFormat);\n // Use actual applied count from harness (0 if patches were rejected)\n const actualPatchesApplied = stepResult.patchesApplied ?? patches.length;\n totalPatches += actualPatchesApplied;\n turnCount++;\n turnsThisCall++;\n\n // Store rejections to provide feedback to LLM in next turn\n previousRejections = stepResult.rejectedPatches;\n\n // Call progress callback (errors don't abort fill)\n if (mergedCallbacks?.onTurnComplete) {\n try {\n const requiredIssues = stepResult.issues.filter((i) => i.severity === 'required');\n mergedCallbacks.onTurnComplete({\n turnNumber: turnCount,\n issuesShown: turnIssues.length,\n patchesApplied: actualPatchesApplied,\n requiredIssuesRemaining: requiredIssues.length,\n isComplete: stepResult.isComplete,\n stats,\n issues: turnIssues,\n patches,\n rejectedPatches: stepResult.rejectedPatches ?? [],\n executionId: '0-serial',\n });\n } catch {\n // Ignore callback errors\n }\n }\n\n // If not complete and not at max turns, step again\n if (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n stepResult = harness.step();\n }\n }\n\n // 8. Determine final status and finalize record\n const finalProgressCounts = getProgressCounts(form, targetRoles);\n\n if (stepResult.isComplete) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('completed');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: true },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n // Hit max turns without completing\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'max_turns');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'max_turns', message: `Reached maximum total turns (${maxTurnsTotal})` },\n inputContextWarnings,\n stepResult.issues,\n record,\n );\n}\n\n// =============================================================================\n// Parallel Execution Path\n// =============================================================================\n\n/**\n * Fill a form using parallel execution.\n *\n * For each order level, runs serial items with the primary agent (multi-turn),\n * then runs parallel batch items concurrently (multi-turn per agent).\n */\nasync function fillFormParallel(\n form: ParsedForm,\n model: LanguageModel | undefined,\n provider: string | undefined,\n options: FillOptions,\n initialPatches: number,\n inputContextWarnings: string[],\n collector: FillRecordCollector | undefined,\n mergedCallbacks: FillOptions['callbacks'],\n): Promise<FillResult> {\n const plan = computeExecutionPlan(form);\n const maxTurnsTotal = options.maxTurnsTotal ?? DEFAULT_MAX_TURNS;\n const startingTurnNumber = options.startingTurnNumber ?? 0;\n const maxPatchesPerTurn = options.maxPatchesPerTurn ?? DEFAULT_MAX_PATCHES_PER_TURN;\n const maxIssuesPerTurn = options.maxIssuesPerTurn ?? DEFAULT_MAX_ISSUES_PER_TURN;\n const maxParallelAgents = options.maxParallelAgents ?? DEFAULT_MAX_PARALLEL_AGENTS;\n const targetRoles = options.targetRoles ?? [AGENT_ROLE];\n\n let totalPatches = initialPatches;\n let turnCount = startingTurnNumber;\n\n // Helper to create an agent with the correct executionId\n const createAgentForExecution = (executionId: string): Agent => {\n return (\n options._testAgent ??\n createLiveAgent({\n model: model!,\n systemPromptAddition: options.systemPromptAddition,\n targetRole: targetRoles[0] ?? AGENT_ROLE,\n provider,\n enableWebSearch: options.enableWebSearch,\n additionalTools: options.additionalTools,\n callbacks: mergedCallbacks,\n maxStepsPerTurn: options.maxStepsPerTurn,\n executionId,\n toolChoice: options.toolChoice,\n })\n );\n };\n\n for (const order of plan.orderLevels) {\n // Check cancellation\n if (options.signal?.aborted) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('cancelled');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n // Check turn limit\n if (turnCount >= maxTurnsTotal) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'max_turns');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n {\n ok: false,\n reason: 'max_turns',\n message: `Reached maximum total turns (${maxTurnsTotal})`,\n },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n // Fire order level callback\n try {\n mergedCallbacks?.onOrderLevelStart?.({ order });\n } catch {\n /* ignore */\n }\n\n // --- Serial items at this order level (multi-turn) ---\n const serialItems = plan.looseSerial.filter((i) => i.order === order);\n if (serialItems.length > 0) {\n const serialExecId = serialExecutionId(order);\n const serialAgent = createAgentForExecution(serialExecId);\n const result = await runMultiTurnForItems(\n form,\n serialAgent,\n serialItems,\n targetRoles,\n maxPatchesPerTurn,\n maxIssuesPerTurn,\n maxTurnsTotal,\n turnCount,\n options,\n order,\n serialExecId,\n mergedCallbacks,\n );\n totalPatches += result.patchesApplied;\n turnCount += result.turnsUsed;\n\n if (result.aborted && result.status) {\n let record: FillRecord | undefined;\n if (collector) {\n // Set status based on abort reason\n const status = result.status;\n if (!status.ok) {\n if (status.reason === 'cancelled') {\n collector.setStatus('cancelled');\n } else if (status.reason === 'error') {\n collector.setStatus('failed', status.message);\n } else {\n collector.setStatus('partial', status.reason);\n }\n }\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n result.status,\n inputContextWarnings,\n undefined,\n record,\n );\n }\n }\n\n // --- Parallel batch items at this order level ---\n for (const batch of plan.parallelBatches) {\n const batchItems = batch.items.filter((i) => i.order === order);\n if (batchItems.length === 0) continue;\n\n try {\n mergedCallbacks?.onBatchStart?.({ batchId: batch.batchId, itemCount: batchItems.length });\n } catch {\n /* ignore */\n }\n\n // Create promise factories for each batch item (for true concurrency limiting)\n // Factories are called lazily when a slot becomes available\n const itemFactories = batchItems.map((item, itemIndex) => {\n return () => {\n const batchExecId = batchExecutionId(order, batch.batchId, itemIndex);\n // Create a scoped agent for this batch item with correct executionId\n const scopedAgent = createAgentForExecution(batchExecId);\n\n return runMultiTurnForItems(\n form,\n scopedAgent,\n [item],\n targetRoles,\n maxPatchesPerTurn,\n maxIssuesPerTurn,\n maxTurnsTotal,\n turnCount,\n options,\n order,\n batchExecId,\n mergedCallbacks,\n );\n };\n });\n\n // Run with concurrency limit (factories are called lazily)\n const results = await runWithConcurrency(itemFactories, maxParallelAgents);\n\n let batchPatches = 0;\n const batchErrors: string[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n totalPatches += result.value.patchesApplied;\n batchPatches += result.value.patchesApplied;\n turnCount += result.value.turnsUsed;\n // Track errors from aborted items (agent threw an error)\n const itemStatus = result.value.status;\n if (result.value.aborted && itemStatus && !itemStatus.ok && itemStatus.message) {\n batchErrors.push(itemStatus.message);\n }\n } else {\n // Promise itself was rejected (shouldn't happen with new error handling, but defensive)\n const reason: unknown = result.reason;\n const errorMsg = reason instanceof Error ? reason.message : String(reason);\n batchErrors.push(`Parallel agent error: ${errorMsg}`);\n }\n }\n\n // If any batch items had errors, record them (but continue processing)\n // The form may still be partially filled even with some errors\n if (batchErrors.length > 0 && collector) {\n // Don't set failed status yet - we may still complete. Just log the errors.\n // The final status will be set at the end based on form completeness.\n console.warn(`[markform] Parallel batch ${batch.batchId} had errors:`, batchErrors);\n }\n\n try {\n mergedCallbacks?.onBatchComplete?.({\n batchId: batch.batchId,\n patchesApplied: batchPatches,\n });\n } catch {\n /* ignore */\n }\n }\n\n // Fire order level complete callback\n const levelInspect = inspect(form);\n try {\n mergedCallbacks?.onOrderLevelComplete?.({ order, patchesApplied: totalPatches });\n } catch {\n /* ignore */\n }\n\n // If form is already complete, stop early\n if (levelInspect.isComplete) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('completed');\n record = collector.getRecord(getProgressCounts(form, targetRoles));\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: true },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n }\n\n // Check final form state\n const finalInspect = inspect(form);\n const finalProgressCounts = getProgressCounts(form, targetRoles);\n\n if (finalInspect.isComplete) {\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('completed');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: true },\n inputContextWarnings,\n undefined,\n record,\n );\n }\n\n let record: FillRecord | undefined;\n if (collector) {\n collector.setStatus('partial', 'max_turns');\n record = collector.getRecord(finalProgressCounts);\n }\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'max_turns', message: `Reached maximum total turns (${maxTurnsTotal})` },\n inputContextWarnings,\n finalInspect.issues,\n record,\n );\n}\n\n/**\n * Result from a multi-turn run for a set of items.\n */\ninterface MultiTurnResult {\n patchesApplied: number;\n turnsUsed: number;\n aborted: boolean;\n status?: FillStatus;\n}\n\n/**\n * Run a multi-turn loop for a set of execution plan items.\n * Scoped issues are filtered to only the target items' fields.\n * Retries with rejection feedback, same as the serial fillForm path.\n */\nasync function runMultiTurnForItems(\n form: ParsedForm,\n agent: Agent,\n items: ExecutionPlanItem[],\n targetRoles: string[],\n maxPatchesPerTurn: number,\n _maxIssuesPerTurn: number,\n maxTurnsTotal: number,\n startTurn: number,\n options: FillOptions,\n order: number,\n executionId: string,\n mergedCallbacks: FillOptions['callbacks'],\n): Promise<MultiTurnResult> {\n let turnsUsed = 0;\n let patchesApplied = 0;\n let previousRejections: PatchRejection[] | undefined;\n const maxTurnsForItems = Math.min(\n maxTurnsTotal - startTurn,\n options.maxTurnsThisCall ?? Infinity,\n );\n\n for (let turn = 0; turn < maxTurnsForItems; turn++) {\n // Check cancellation\n if (options.signal?.aborted) {\n return {\n patchesApplied,\n turnsUsed,\n aborted: true,\n status: { ok: false, reason: 'cancelled' },\n };\n }\n\n // Inspect form to get current issues, scoped to our items\n const inspectResult = inspect(form, { targetRoles });\n const allIssues = inspectResult.issues;\n\n // Scope issues to our items\n let scopedIssues: InspectIssue[] = [];\n for (const item of items) {\n scopedIssues.push(...scopeIssuesForItem(form, item, allIssues));\n }\n\n // Deduplicate issues (same issue could appear via multiple items)\n const seen = new Set<string>();\n scopedIssues = scopedIssues.filter((issue) => {\n const key = `${issue.scope}:${issue.ref}:${issue.message}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n\n if (scopedIssues.length === 0) break; // All items filled\n\n // Fire turn callback\n try {\n mergedCallbacks?.onTurnStart?.({\n turnNumber: startTurn + turnsUsed + 1,\n issuesCount: scopedIssues.length,\n order,\n executionId,\n });\n } catch {\n /* ignore */\n }\n\n // Call agent (catch errors to avoid rejecting the parallel promise)\n let response: { patches: Patch[]; stats?: TurnStats };\n try {\n response = await agent.fillFormTool(\n scopedIssues,\n form,\n maxPatchesPerTurn,\n previousRejections,\n );\n } catch (error) {\n // Return early with error result so it can be tracked by the parallel harness\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n patchesApplied,\n turnsUsed,\n aborted: true,\n status: { ok: false, reason: 'error', message: errorMessage },\n };\n }\n\n // Apply patches\n if (response.patches.length > 0) {\n const applyResult = applyPatches(form, response.patches);\n patchesApplied += applyResult.appliedPatches.length;\n previousRejections = applyResult.rejectedPatches;\n } else {\n previousRejections = undefined;\n }\n\n turnsUsed++;\n\n // Fire turn complete callback\n try {\n const postInspect = inspect(form, { targetRoles });\n const requiredIssues = postInspect.issues.filter((i) => i.severity === 'required');\n mergedCallbacks?.onTurnComplete?.({\n turnNumber: startTurn + turnsUsed,\n issuesShown: scopedIssues.length,\n patchesApplied: response.patches.length,\n requiredIssuesRemaining: requiredIssues.length,\n isComplete: postInspect.isComplete,\n stats: response.stats,\n issues: scopedIssues,\n patches: response.patches,\n rejectedPatches: previousRejections ?? [],\n executionId,\n });\n } catch {\n /* ignore */\n }\n }\n\n return { patchesApplied, turnsUsed, aborted: false };\n}\n","/**\n * Harness configuration resolver.\n *\n * Merges configuration from multiple sources with defined precedence:\n * 1. API-provided options (highest priority)\n * 2. Form frontmatter defaults\n * 3. Global defaults (lowest priority)\n */\n\nimport type { HarnessConfig, ParsedForm } from '../engine/coreTypes.js';\nimport type { FillOptions } from './harnessTypes.js';\nimport {\n DEFAULT_MAX_ISSUES_PER_TURN,\n DEFAULT_MAX_PARALLEL_AGENTS,\n DEFAULT_MAX_PATCHES_PER_TURN,\n DEFAULT_MAX_TURNS,\n} from '../settings.js';\n\n/**\n * Resolve harness configuration by merging options from multiple sources.\n *\n * Precedence (highest to lowest):\n * 1. options parameter (API-provided)\n * 2. form.metadata.harnessConfig (from frontmatter)\n * 3. Default constants\n *\n * @param form The parsed form (may contain frontmatter harness config)\n * @param options API-provided options to override defaults\n * @returns Resolved harness configuration\n */\nexport function resolveHarnessConfig(\n form: ParsedForm,\n options?: Partial<FillOptions>,\n): HarnessConfig {\n // Get frontmatter config (if present)\n const frontmatterConfig = form.metadata?.harnessConfig;\n\n // Merge with precedence: options > frontmatter > defaults\n return {\n maxTurns: options?.maxTurnsTotal ?? frontmatterConfig?.maxTurns ?? DEFAULT_MAX_TURNS,\n maxPatchesPerTurn:\n options?.maxPatchesPerTurn ??\n frontmatterConfig?.maxPatchesPerTurn ??\n DEFAULT_MAX_PATCHES_PER_TURN,\n maxIssuesPerTurn:\n options?.maxIssuesPerTurn ??\n frontmatterConfig?.maxIssuesPerTurn ??\n DEFAULT_MAX_ISSUES_PER_TURN,\n maxParallelAgents:\n options?.maxParallelAgents ??\n frontmatterConfig?.maxParallelAgents ??\n DEFAULT_MAX_PARALLEL_AGENTS,\n targetRoles: options?.targetRoles,\n fillMode: options?.fillMode,\n };\n}\n","/**\n * Format FillRecord as a human-readable summary.\n *\n * Produces a concise text summary of a fill operation, suitable for\n * CLI output or logging. Shows key metrics at a glance:\n * - Duration and turns\n * - Token usage\n * - Tool call summary\n * - Timing breakdown (verbose mode)\n * - Form progress\n */\n\nimport type { FillRecord } from './fillRecord.js';\n\n/**\n * Options for formatting the summary.\n */\nexport interface FormatFillRecordSummaryOptions {\n /** Show detailed breakdown including per-tool stats */\n verbose?: boolean;\n}\n\n/**\n * Format a number with thousands separators.\n */\nfunction formatNumber(n: number): string {\n return n.toLocaleString('en-US');\n}\n\n/**\n * Format milliseconds as a human-readable duration.\n */\nfunction formatDuration(ms: number): string {\n if (ms < 1000) {\n return `${ms}ms`;\n }\n const seconds = ms / 1000;\n if (seconds < 60) {\n // Show one decimal place\n return `${seconds.toFixed(1)}s`;\n }\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = seconds % 60;\n return `${minutes}m ${remainingSeconds.toFixed(0)}s`;\n}\n\n/**\n * Format a percentage.\n */\nfunction formatPercent(value: number, total: number): string {\n if (total === 0) return '0%';\n const pct = Math.round((value / total) * 100);\n return `${pct}%`;\n}\n\n/**\n * Format FillRecord as a human-readable text summary.\n *\n * @param record - The FillRecord to format\n * @param options - Formatting options (verbose mode for more detail)\n * @returns Multi-line text summary\n *\n * @example\n * ```typescript\n * const result = await fillForm({ form, model, recordFill: true });\n * if (result.record) {\n * console.log(formatFillRecordSummary(result.record));\n * }\n * ```\n */\nexport function formatFillRecordSummary(\n record: FillRecord,\n options: FormatFillRecordSummaryOptions = {},\n): string {\n const { verbose = false } = options;\n const lines: string[] = [];\n\n // Status line\n const statusText = record.status === 'completed' ? 'Fill completed' : 'Fill incomplete';\n const turnsText = `${record.execution.totalTurns} turn${record.execution.totalTurns !== 1 ? 's' : ''}`;\n let statusLine = `${statusText} in ${formatDuration(record.durationMs)} (${turnsText})`;\n if (record.status !== 'completed' && record.statusDetail) {\n statusLine += ` - ${record.statusDetail}`;\n }\n lines.push(statusLine);\n\n // Warn if timeline is empty but work was done (indicates callback wiring bug)\n // This catches the mf-mgxo bug where CLI was missing onTurnStart/onTurnComplete wiring\n const timelineEmpty = record.timeline.length === 0;\n const hadTurns = record.execution.totalTurns > 0;\n const hadFieldsFilled = record.formProgress.filledFields > 0;\n if (timelineEmpty && (hadTurns || hadFieldsFilled)) {\n lines.push('Warning: timeline is empty but work was recorded (possible callback wiring issue)');\n }\n\n lines.push('');\n\n // Token usage\n const tokenLine = `Tokens: ${formatNumber(record.llm.inputTokens)} input / ${formatNumber(record.llm.outputTokens)} output (${record.llm.provider}/${record.llm.model})`;\n lines.push(tokenLine);\n\n // Tool summary\n const { toolSummary } = record;\n let toolLine = `Tools: ${formatNumber(toolSummary.totalCalls)} calls`;\n if (toolSummary.totalCalls > 0) {\n toolLine += ` (${formatNumber(toolSummary.successfulCalls)} succeeded`;\n if (toolSummary.failedCalls > 0) {\n toolLine += `, ${formatNumber(toolSummary.failedCalls)} failed`;\n }\n toolLine += ')';\n }\n lines.push(toolLine);\n\n // Per-tool breakdown (verbose mode)\n if (verbose && toolSummary.byTool.length > 0) {\n for (const tool of toolSummary.byTool) {\n const avgDuration = formatDuration(tool.timing.avgMs);\n let toolDetail = ` - ${tool.toolName}: ${tool.callCount} calls, avg ${avgDuration}`;\n if (tool.timing.p95Ms !== undefined && tool.callCount > 1) {\n toolDetail += `, p95 ${formatDuration(tool.timing.p95Ms)}`;\n }\n lines.push(toolDetail);\n }\n }\n\n // Timing breakdown (verbose mode)\n if (verbose) {\n lines.push('');\n const { timingBreakdown } = record;\n const llmPct = timingBreakdown.breakdown.find((b) => b.category === 'llm')?.percentage ?? 0;\n const toolPct = timingBreakdown.breakdown.find((b) => b.category === 'tools')?.percentage ?? 0;\n const overheadPct =\n timingBreakdown.breakdown.find((b) => b.category === 'overhead')?.percentage ?? 0;\n\n const timingLine = `Timing: ${llmPct}% LLM (${formatDuration(timingBreakdown.llmTimeMs)}) | ${toolPct}% tools (${formatDuration(timingBreakdown.toolTimeMs)}) | ${overheadPct}% overhead (${formatDuration(timingBreakdown.overheadMs)})`;\n lines.push(timingLine);\n }\n\n // Progress\n lines.push('');\n const { formProgress } = record;\n const progressPct = formatPercent(formProgress.answeredFields, formProgress.totalFields);\n const progressLine = `Progress: ${formProgress.answeredFields}/${formProgress.totalFields} fields filled (${progressPct})`;\n lines.push(progressLine);\n\n return lines.join('\\n');\n}\n","/**\n * FillRecord types - Captures complete records of form fill operations.\n *\n * Provides detailed tracking of:\n * - LLM usage (tokens per turn and totals)\n * - Tool invocations with timing and results\n * - Turn-by-turn timeline with execution context\n * - Form progress and completion status\n *\n * @see docs/project/specs/active/plan-2026-01-29-fill-record.md\n */\n\nimport { z } from 'zod';\n\nimport { ProgressCountsSchema, StructureSummarySchema } from '../engine/coreTypes.js';\n\n// =============================================================================\n// Tool Statistics Schema\n// =============================================================================\n\n/**\n * Per-tool statistics with timing percentiles.\n * Enables analysis like \"web_search p95 is 2.5s\" or \"fill_form has 98% success rate\"\n */\nexport const ToolStatsSchema = z.object({\n /** Tool name identifier (e.g., \"web_search\", \"fill_form\") */\n toolName: z.string(),\n\n /** Number of times this tool was called */\n callCount: z.number().int().nonnegative(),\n /** Number of successful calls */\n successCount: z.number().int().nonnegative(),\n /** Number of failed calls */\n failureCount: z.number().int().nonnegative(),\n /** Success rate as percentage (0-100) */\n successRate: z.number().nonnegative(),\n\n /** For tools that return results (web_search), track result counts */\n results: z\n .object({\n /** Total results returned across all calls */\n totalResults: z.number().int().nonnegative(),\n /** Average results per call */\n avgResultsPerCall: z.number().nonnegative(),\n /** Calls that returned zero results */\n zeroResultCalls: z.number().int().nonnegative(),\n })\n .optional(),\n\n /** Timing statistics (all values in milliseconds) */\n timing: z.object({\n /** Total time spent in this tool */\n totalMs: z.number().int().nonnegative(),\n /** Average call duration */\n avgMs: z.number().nonnegative(),\n /** Minimum call duration */\n minMs: z.number().int().nonnegative(),\n /** Maximum call duration */\n maxMs: z.number().int().nonnegative(),\n /** 50th percentile (median) */\n p50Ms: z.number().int().nonnegative(),\n /** 95th percentile - useful for identifying slow outliers */\n p95Ms: z.number().int().nonnegative(),\n }),\n});\n\nexport type ToolStats = z.infer<typeof ToolStatsSchema>;\n\n// =============================================================================\n// Tool Call Schema (for timeline)\n// =============================================================================\n\n/**\n * Individual tool call in the timeline.\n */\nexport const ToolCallRecordSchema = z.object({\n /** Tool name */\n tool: z.string(),\n /** When the tool started */\n startedAt: z.string().datetime(),\n /** When the tool completed */\n completedAt: z.string().datetime(),\n /** Start time relative to fill start (milliseconds) */\n startMs: z.number().int().nonnegative(),\n /** Duration in milliseconds */\n durationMs: z.number().int().nonnegative(),\n /** Whether the call succeeded */\n success: z.boolean(),\n /** Tool input parameters (e.g., { query: \"...\" } for web_search) */\n input: z.record(z.string(), z.unknown()),\n /** Result summary */\n result: z\n .object({\n /** Number of results returned (e.g., web search results, patches applied) */\n resultCount: z.number().int().nonnegative().optional(),\n /** Error message if success=false */\n error: z.string().optional(),\n })\n .optional(),\n});\n\nexport type ToolCallRecord = z.infer<typeof ToolCallRecordSchema>;\n\n// =============================================================================\n// Timeline Entry Schema\n// =============================================================================\n\n/**\n * Single turn in the fill timeline.\n */\nexport const TimelineEntrySchema = z.object({\n /** Turn number (1-based) */\n turnNumber: z.number().int().positive(),\n\n /** Order level this turn belongs to (0, 1, 2, etc.) */\n order: z.number().int().nonnegative(),\n\n /**\n * Execution thread identifier.\n * Pattern: \"{order}-{context}\" where context is:\n * - \"serial\" for loose serial items\n * - \"batch-{batchId}-{itemIndex}\" for parallel batch items\n */\n executionId: z.string(),\n\n /** When the turn started */\n startedAt: z.string().datetime(),\n /** When the turn completed */\n completedAt: z.string().datetime(),\n /** Start time relative to fill start (milliseconds) */\n startMs: z.number().int().nonnegative(),\n /** Duration in milliseconds */\n durationMs: z.number().int().nonnegative(),\n\n /** Number of issues addressed this turn */\n issuesAddressed: z.number().int().nonnegative(),\n /** Number of patches successfully applied */\n patchesApplied: z.number().int().nonnegative(),\n /** Number of patches rejected */\n patchesRejected: z.number().int().nonnegative(),\n\n /** Per-turn token usage (from AI SDK result.usage) */\n tokens: z.object({\n input: z.number().int().nonnegative(),\n output: z.number().int().nonnegative(),\n }),\n\n /** Tool calls made during this turn */\n toolCalls: z.array(ToolCallRecordSchema),\n});\n\nexport type TimelineEntry = z.infer<typeof TimelineEntrySchema>;\n\n// =============================================================================\n// Timing Breakdown Schema\n// =============================================================================\n\n/**\n * Breakdown item for visualization.\n */\nexport const TimingBreakdownItemSchema = z.object({\n category: z.enum(['llm', 'tools', 'overhead']),\n label: z.string(),\n ms: z.number().int().nonnegative(),\n percentage: z.number().nonnegative(), // 0-100\n});\n\nexport type TimingBreakdownItem = z.infer<typeof TimingBreakdownItemSchema>;\n\n/**\n * Timing breakdown showing where time was spent.\n */\nexport const TimingBreakdownSchema = z.object({\n /** Total wall-clock time for the fill (ms) */\n totalMs: z.number().int().nonnegative(),\n /** Time spent in LLM API calls (ms) */\n llmTimeMs: z.number().int().nonnegative(),\n /** Time spent executing tools (ms) */\n toolTimeMs: z.number().int().nonnegative(),\n /** Overhead time (total - llm - tools) */\n overheadMs: z.number().int().nonnegative(),\n /** Percentage breakdown for visualization */\n breakdown: z.array(TimingBreakdownItemSchema),\n});\n\nexport type TimingBreakdown = z.infer<typeof TimingBreakdownSchema>;\n\n// =============================================================================\n// Tool Summary Schema\n// =============================================================================\n\n/**\n * Aggregated tool usage statistics.\n */\nexport const ToolSummarySchema = z.object({\n /** Total tool calls across all turns */\n totalCalls: z.number().int().nonnegative(),\n /** Successful tool calls */\n successfulCalls: z.number().int().nonnegative(),\n /** Failed tool calls */\n failedCalls: z.number().int().nonnegative(),\n /** Success rate as percentage (0-100) */\n successRate: z.number().nonnegative(),\n /** Total time spent in tool execution (ms) */\n totalDurationMs: z.number().int().nonnegative(),\n /** Per-tool statistics */\n byTool: z.array(ToolStatsSchema),\n});\n\nexport type ToolSummary = z.infer<typeof ToolSummarySchema>;\n\n// =============================================================================\n// Execution Metadata Schema\n// =============================================================================\n\n/**\n * Execution metadata for the fill.\n */\nexport const ExecutionMetadataSchema = z.object({\n /** Total number of turns executed */\n totalTurns: z.number().int().nonnegative(),\n /** Whether parallel execution was enabled */\n parallelEnabled: z.boolean(),\n /** Maximum parallel agents (if parallel enabled) */\n maxParallelAgents: z.number().int().positive().optional(),\n /** Order levels processed (e.g., [0, 1, 2]) */\n orderLevels: z.array(z.number().int().nonnegative()),\n /** Unique execution threads seen */\n executionThreads: z.array(z.string()),\n});\n\nexport type ExecutionMetadata = z.infer<typeof ExecutionMetadataSchema>;\n\n// =============================================================================\n// Fill Record Schema\n// =============================================================================\n\n/**\n * Fill status enum.\n */\nexport const FillRecordStatusSchema = z.enum(['completed', 'partial', 'failed', 'cancelled']);\n\nexport type FillRecordStatus = z.infer<typeof FillRecordStatusSchema>;\n\n/**\n * Complete record of a form fill operation.\n *\n * Captures everything that happened during the fill for:\n * - Provenance/corroboration\n * - Cost analysis\n * - Debugging\n * - Analytics\n */\nexport const FillRecordSchema = z.object({\n // =========================================================================\n // Session Identity\n // =========================================================================\n\n /** Unique session identifier */\n sessionId: z.string().uuid(),\n /** When the fill started */\n startedAt: z.string().datetime(),\n /** When the fill completed */\n completedAt: z.string().datetime(),\n /** Total duration in milliseconds */\n durationMs: z.number().int().nonnegative(),\n\n // =========================================================================\n // Form Metadata\n // =========================================================================\n\n /** Form identification and structure */\n form: z.object({\n /** Form ID from the form schema */\n id: z.string(),\n /** Form title if specified */\n title: z.string().optional(),\n /** Form description if specified */\n description: z.string().optional(),\n /** Structure summary (field counts, etc.) */\n structure: StructureSummarySchema,\n }),\n\n // =========================================================================\n // Outcome\n // =========================================================================\n\n /** Fill status */\n status: FillRecordStatusSchema,\n /** Additional status detail (e.g., error message) */\n statusDetail: z.string().optional(),\n\n /** Form progress at completion */\n formProgress: ProgressCountsSchema,\n\n // =========================================================================\n // LLM Usage\n // =========================================================================\n\n /** LLM usage totals (tokens only - clients calculate costs) */\n llm: z.object({\n /** Provider name (e.g., \"anthropic\", \"openai\") */\n provider: z.string(),\n /** Model identifier */\n model: z.string(),\n /** Total LLM calls */\n totalCalls: z.number().int().nonnegative(),\n /** Total input tokens */\n inputTokens: z.number().int().nonnegative(),\n /** Total output tokens */\n outputTokens: z.number().int().nonnegative(),\n }),\n\n // =========================================================================\n // Tool Usage\n // =========================================================================\n\n /** Aggregated tool statistics */\n toolSummary: ToolSummarySchema,\n\n /** Timing breakdown */\n timingBreakdown: TimingBreakdownSchema,\n\n // =========================================================================\n // Timeline\n // =========================================================================\n\n /** Turn-by-turn timeline (full history, no size limits) */\n timeline: z.array(TimelineEntrySchema),\n\n // =========================================================================\n // Execution Metadata\n // =========================================================================\n\n /** Execution configuration and thread info */\n execution: ExecutionMetadataSchema,\n\n // =========================================================================\n // Custom Data\n // =========================================================================\n\n /** Client-defined custom data */\n customData: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type FillRecord = z.infer<typeof FillRecordSchema>;\n\n// =============================================================================\n// Stable FillRecord (for golden tests)\n// =============================================================================\n\n/**\n * Stripped ToolStats without timing information.\n */\nexport type StableToolStats = Omit<ToolStats, 'timing'>;\n\n/**\n * Stripped ToolSummary without timing information.\n */\nexport type StableToolSummary = Omit<ToolSummary, 'totalDurationMs' | 'byTool'> & {\n byTool: StableToolStats[];\n};\n\n/**\n * FillRecord with unstable fields removed for deterministic golden tests.\n *\n * Removes:\n * - sessionId, startedAt, completedAt, durationMs (top-level timing)\n * - timeline (contains per-turn timestamps and durations)\n * - timingBreakdown (all timing values)\n * - toolSummary.totalDurationMs and toolSummary.byTool[].timing\n */\nexport type StableFillRecord = Omit<\n FillRecord,\n | 'sessionId'\n | 'startedAt'\n | 'completedAt'\n | 'durationMs'\n | 'timeline'\n | 'timingBreakdown'\n | 'toolSummary'\n> & {\n toolSummary: StableToolSummary;\n};\n\n/**\n * Strip unstable fields from FillRecord for golden test comparisons.\n *\n * In mock mode, all remaining fields should be deterministic:\n * - status, statusDetail: based on completion logic\n * - form: form metadata (static)\n * - formProgress: counts of filled fields (deterministic from mock source)\n * - llm: provider/model/tokens (tokens are 0 in mock mode)\n * - toolSummary: call counts and success rates (without timing)\n * - execution: turn counts, parallel settings (deterministic)\n */\nexport function stripUnstableFillRecordFields(record: FillRecord): StableFillRecord {\n // Strip timing from each tool's stats\n const stableByTool: StableToolStats[] = record.toolSummary.byTool.map((toolStats) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { timing, ...rest } = toolStats;\n return rest;\n });\n\n // Build stable tool summary without timing\n const stableToolSummary: StableToolSummary = {\n totalCalls: record.toolSummary.totalCalls,\n successfulCalls: record.toolSummary.successfulCalls,\n failedCalls: record.toolSummary.failedCalls,\n successRate: record.toolSummary.successRate,\n byTool: stableByTool,\n };\n\n return {\n // Keep form metadata (stable)\n form: record.form,\n\n // Keep outcome (stable in mock mode)\n status: record.status,\n statusDetail: record.statusDetail,\n formProgress: record.formProgress,\n\n // Keep LLM info (tokens are 0 in mock mode)\n llm: record.llm,\n\n // Use stable tool summary\n toolSummary: stableToolSummary,\n\n // Keep execution metadata (stable)\n execution: record.execution,\n\n // Keep custom data if present\n customData: record.customData,\n };\n}\n","/**\n * Research API - Form filling with web search capabilities.\n *\n * The runResearch() function is the main entry point for research-mode filling.\n * It uses web-search-enabled models to fill forms with information from the web.\n */\n\nimport type { ParsedForm, SessionTranscript } from '../engine/coreTypes.js';\nimport { createHarness } from '../harness/harness.js';\nimport { createLiveAgent } from '../harness/liveAgent.js';\nimport { resolveModel } from '../harness/modelResolver.js';\nimport { resolveHarnessConfig } from '../harness/harnessConfigResolver.js';\nimport type { FillOptions } from '../harness/harnessTypes.js';\nimport {\n AGENT_ROLE,\n DEFAULT_MAX_TURNS,\n DEFAULT_RESEARCH_MAX_ISSUES_PER_TURN,\n DEFAULT_RESEARCH_MAX_PATCHES_PER_TURN,\n} from '../settings.js';\nimport type { ResearchResult, ResearchStatus } from './researchTypes.js';\n\n/**\n * Options for runResearch (FillOptions without form, since form is a separate parameter).\n */\nexport type ResearchOptions = Omit<FillOptions, 'form'>;\n\n/**\n * Run research fill on a form.\n *\n * This function fills a form using an LLM with optional web search capabilities.\n * It resolves configuration from multiple sources (options > frontmatter > defaults)\n * and executes the harness loop until completion or max turns.\n *\n * @param form The parsed form to fill\n * @param options Fill options including model specification\n * @returns Research result with filled form and statistics\n */\nexport async function runResearch(\n form: ParsedForm,\n options: ResearchOptions,\n): Promise<ResearchResult> {\n // Validate model is provided\n if (!options.model) {\n throw new Error('model is required for runResearch()');\n }\n\n // Resolve the model - model is string | LanguageModel, but resolveModel only accepts string\n const modelSpec = options.model;\n if (typeof modelSpec !== 'string') {\n throw new Error(\n 'runResearch requires a model string identifier (e.g., \"openai/gpt-4o-search-preview\")',\n );\n }\n const { model, provider } = await resolveModel(modelSpec);\n\n // Resolve harness config with research defaults\n const baseConfig = resolveHarnessConfig(form, options);\n const config = {\n ...baseConfig,\n // Apply research-specific defaults if not overridden\n maxTurns: options.maxTurnsTotal ?? form.metadata?.harnessConfig?.maxTurns ?? DEFAULT_MAX_TURNS,\n maxIssuesPerTurn:\n options.maxIssuesPerTurn ??\n form.metadata?.harnessConfig?.maxIssuesPerTurn ??\n DEFAULT_RESEARCH_MAX_ISSUES_PER_TURN,\n maxPatchesPerTurn:\n options.maxPatchesPerTurn ??\n form.metadata?.harnessConfig?.maxPatchesPerTurn ??\n DEFAULT_RESEARCH_MAX_PATCHES_PER_TURN,\n targetRoles: options.targetRoles ?? [AGENT_ROLE],\n fillMode: options.fillMode ?? 'continue',\n };\n\n // Create harness and agent\n const harness = createHarness(form, config);\n const agent = createLiveAgent({\n model,\n provider,\n targetRole: config.targetRoles?.[0] ?? AGENT_ROLE,\n enableWebSearch: options.enableWebSearch,\n additionalTools: options.additionalTools,\n });\n\n // Get available tools for logging\n const availableTools = agent.getAvailableToolNames();\n\n // Track stats\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n\n // Run harness loop\n let stepResult = harness.step();\n\n while (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n // Generate patches from agent\n const response = await agent.fillFormTool(\n stepResult.issues,\n harness.getForm(),\n config.maxPatchesPerTurn,\n );\n\n // Track token usage if available\n if (response.stats?.inputTokens) {\n totalInputTokens += response.stats.inputTokens;\n }\n if (response.stats?.outputTokens) {\n totalOutputTokens += response.stats.outputTokens;\n }\n\n // Apply patches\n stepResult = harness.apply(response.patches, stepResult.issues);\n\n // Continue if not complete\n if (!stepResult.isComplete && !harness.hasReachedMaxTurns()) {\n stepResult = harness.step();\n }\n }\n\n // Determine final status\n let status: ResearchStatus;\n if (stepResult.isComplete) {\n status = 'completed';\n } else if (harness.hasReachedMaxTurns()) {\n status = 'max_turns_reached';\n } else {\n status = 'incomplete';\n }\n\n // Build transcript if available\n const transcript: SessionTranscript = {\n sessionVersion: '0.1.0',\n mode: 'live',\n form: { path: '' },\n harness: {\n maxTurns: config.maxTurns,\n maxPatchesPerTurn: config.maxPatchesPerTurn,\n maxIssuesPerTurn: config.maxIssuesPerTurn,\n targetRoles: config.targetRoles,\n fillMode: config.fillMode,\n },\n turns: harness.getTurns(),\n final: {\n expectComplete: true,\n expectedCompletedForm: '',\n },\n };\n\n // Return result\n return {\n status,\n form: harness.getForm(),\n transcript,\n totalTurns: harness.getTurnNumber(),\n inputTokens: totalInputTokens > 0 ? totalInputTokens : undefined,\n outputTokens: totalOutputTokens > 0 ? totalOutputTokens : undefined,\n availableTools,\n };\n}\n","/**\n * Research form validation.\n *\n * Utilities for detecting and validating research-enabled forms.\n */\n\nimport type { ParsedForm } from '../engine/coreTypes.js';\n\n/**\n * Check if a form is configured for research mode.\n *\n * A form is considered a research form if it has web search configuration\n * in its frontmatter metadata, indicated by:\n * - webSearchModel: model ID for web search capability\n * - enableWebSearch: boolean flag to enable web search\n *\n * @param form The parsed form to check\n * @returns true if the form is configured for research\n */\nexport function isResearchForm(form: ParsedForm): boolean {\n const metadata = form.metadata;\n if (!metadata) {\n return false;\n }\n\n // Check for research configuration in metadata\n // These would be set in the frontmatter's markform section\n const extendedMetadata = metadata as unknown as Record<string, unknown>;\n\n // Check for webSearchModel or enableWebSearch\n if (extendedMetadata.webSearchModel) {\n return true;\n }\n\n if (extendedMetadata.enableWebSearch === true) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Validate that a form is suitable for research fill.\n *\n * Research forms should:\n * 1. Have agent-role fields to fill\n * 2. Not be already complete\n *\n * @param form The parsed form to validate\n * @returns Object with isValid and optional error message\n */\nexport function validateResearchForm(form: ParsedForm): { isValid: boolean; error?: string } {\n // Check if form has any fields\n const fieldCount =\n Object.keys(form.responsesByFieldId).length +\n form.schema.groups.reduce((sum, g) => sum + g.children.length, 0);\n\n if (fieldCount === 0) {\n return { isValid: false, error: 'Form has no fields to fill' };\n }\n\n // Form is valid for research\n return { isValid: true };\n}\n","/**\n * Markform - Agent-friendly, human-readable, editable forms.\n *\n * This is the main library entry point that exports the core engine,\n * types, and utilities for working with .form.md files.\n */\n\n// Build-time injected by tsdown (see tsdown.config.ts)\ndeclare const __MARKFORM_VERSION__: string;\n\n/** Markform version (injected at build time). */\nexport const VERSION: string =\n typeof __MARKFORM_VERSION__ !== 'undefined' ? __MARKFORM_VERSION__ : 'development';\n\n// =============================================================================\n// Type Exports\n// =============================================================================\n\nexport type {\n // Basic types\n Id,\n OptionId,\n QualifiedOptionRef,\n QualifiedColumnRef,\n ValidatorRef,\n // Checkbox types\n MultiCheckboxState,\n SimpleCheckboxState,\n ExplicitCheckboxValue,\n CheckboxValue,\n CheckboxMode,\n // Field kinds\n FieldKind,\n FieldBase,\n StringField,\n NumberField,\n StringListField,\n Option,\n CheckboxesField,\n SingleSelectField,\n MultiSelectField,\n UrlField,\n UrlListField,\n DateField,\n YearField,\n // Table field definitions\n ColumnTypeName,\n TableColumn,\n TableField,\n CellResponse,\n TableRowResponse,\n Field,\n // Form structure\n FieldGroup,\n FormSchema,\n // Field values\n StringValue,\n NumberValue,\n StringListValue,\n CheckboxesValue,\n SingleSelectValue,\n MultiSelectValue,\n UrlValue,\n UrlListValue,\n DateValue,\n YearValue,\n TableValue,\n FieldValue,\n // Documentation\n DocumentationTag,\n DocumentationBlock,\n // Answer state and field response\n AnswerState,\n FieldResponse,\n // Parsed form\n NodeType,\n IdIndexEntry,\n ParsedForm,\n // Validation\n Severity,\n SourcePosition,\n SourceRange,\n ValidationIssue,\n // Inspect\n IssueReason,\n IssueScope,\n InspectIssue,\n // Summaries\n StructureSummary,\n ProgressState,\n CheckboxProgressCounts,\n FieldProgress,\n ProgressCounts,\n ProgressSummary,\n // Results\n InspectResult,\n ApplyResult,\n PatchRejection,\n // Patches\n SetStringPatch,\n SetNumberPatch,\n SetStringListPatch,\n SetCheckboxesPatch,\n SetSingleSelectPatch,\n SetMultiSelectPatch,\n SetUrlPatch,\n SetUrlListPatch,\n SetDatePatch,\n SetYearPatch,\n TableRowPatch,\n SetTablePatch,\n ClearFieldPatch,\n Patch,\n // Harness\n StepResult,\n HarnessConfig,\n SessionTurn,\n SessionTurnStats,\n SessionFinal,\n SessionTranscript,\n // Wire format (for session logging)\n WireFormat,\n WireRequestFormat,\n WireResponseFormat,\n WireResponseStep,\n WireToolCall,\n WireToolResult,\n // Frontmatter\n MarkformFrontmatter,\n FrontmatterHarnessConfig,\n // Run mode\n RunMode,\n // Validators\n ValidatorContext,\n ValidatorFn,\n ValidatorRegistry,\n} from './engine/coreTypes.js';\n\n// =============================================================================\n// Schema Exports\n// =============================================================================\n\nexport {\n // Basic schemas\n IdSchema,\n OptionIdSchema,\n ValidatorRefSchema,\n // Checkbox schemas\n MultiCheckboxStateSchema,\n SimpleCheckboxStateSchema,\n ExplicitCheckboxValueSchema,\n CheckboxValueSchema,\n CheckboxModeSchema,\n // Field schemas\n FieldKindSchema,\n OptionSchema,\n StringFieldSchema,\n NumberFieldSchema,\n StringListFieldSchema,\n CheckboxesFieldSchema,\n SingleSelectFieldSchema,\n MultiSelectFieldSchema,\n UrlFieldSchema,\n UrlListFieldSchema,\n DateFieldSchema,\n YearFieldSchema,\n // Table field schemas\n ColumnTypeNameSchema,\n TableColumnSchema,\n TableFieldSchema,\n CellResponseSchema,\n TableRowResponseSchema,\n FieldSchema,\n // Form schemas\n FieldGroupSchema,\n FormSchemaSchema,\n // Value schemas\n StringValueSchema,\n NumberValueSchema,\n StringListValueSchema,\n CheckboxesValueSchema,\n SingleSelectValueSchema,\n MultiSelectValueSchema,\n UrlValueSchema,\n UrlListValueSchema,\n DateValueSchema,\n YearValueSchema,\n TableValueSchema,\n FieldValueSchema,\n // Documentation schemas\n DocumentationTagSchema,\n DocumentationBlockSchema,\n // Validation schemas\n SeveritySchema,\n SourcePositionSchema,\n SourceRangeSchema,\n ValidationIssueSchema,\n // Inspect schemas\n IssueReasonSchema,\n IssueScopeSchema,\n InspectIssueSchema,\n // Answer state and field response schemas\n AnswerStateSchema,\n FieldResponseSchema,\n // Summary schemas\n ProgressStateSchema,\n CheckboxProgressCountsSchema,\n FieldProgressSchema,\n ProgressCountsSchema,\n ProgressSummarySchema,\n StructureSummarySchema,\n // Result schemas\n InspectResultSchema,\n ApplyResultSchema,\n // Patch schemas\n SetStringPatchSchema,\n SetNumberPatchSchema,\n SetStringListPatchSchema,\n SetCheckboxesPatchSchema,\n SetSingleSelectPatchSchema,\n SetMultiSelectPatchSchema,\n SetUrlPatchSchema,\n SetUrlListPatchSchema,\n SetDatePatchSchema,\n SetYearPatchSchema,\n TableRowPatchSchema,\n SetTablePatchSchema,\n ClearFieldPatchSchema,\n PatchSchema,\n // Harness schemas\n StepResultSchema,\n HarnessConfigSchema,\n SessionTurnSchema,\n SessionFinalSchema,\n SessionTranscriptSchema,\n // Wire format schemas\n WireFormatSchema,\n WireRequestFormatSchema,\n WireResponseFormatSchema,\n WireResponseStepSchema,\n WireToolCallSchema,\n WireToolResultSchema,\n // Frontmatter schemas\n MarkformFrontmatterSchema,\n MarkformSectionInputSchema,\n // Run mode schema\n RunModeSchema,\n} from './engine/coreTypes.js';\n\n// =============================================================================\n// Engine Exports\n// =============================================================================\n\nexport { parseForm } from './engine/parse.js';\nexport { serializeForm, serializeReport } from './engine/serialize.js';\nexport type { SerializeOptions } from './engine/serialize.js';\nexport {\n computeStructureSummary,\n computeProgressSummary,\n computeFormState,\n isFormComplete,\n computeAllSummaries,\n} from './engine/summaries.js';\nexport type { ComputedSummaries } from './engine/summaries.js';\nexport { validate } from './engine/validate.js';\nexport type { ValidateOptions, ValidateResult } from './engine/validate.js';\nexport { inspect } from './engine/inspect.js';\nexport type { InspectOptions } from './engine/inspect.js';\nexport { parseSession, serializeSession } from './engine/session.js';\nexport { applyPatches } from './engine/apply.js';\n\n// =============================================================================\n// Markdown Utilities\n// =============================================================================\n\nexport { findAllHeadings, findEnclosingHeadings } from './markdown/markdownHeaders.js';\nexport type { HeadingInfo } from './markdown/markdownHeaders.js';\n\n// =============================================================================\n// ID Injection\n// =============================================================================\n\nexport { findAllCheckboxes, injectCheckboxIds, injectHeaderIds } from './engine/injectIds.js';\nexport type {\n CheckboxInfo,\n InjectCheckboxIdsOptions,\n InjectHeaderIdsOptions,\n InjectIdsResult,\n} from './engine/injectIds.js';\n\n// =============================================================================\n// JSON Schema Export\n// =============================================================================\n\nexport { formToJsonSchema, fieldToJsonSchema } from './engine/jsonSchema.js';\nexport type {\n JsonSchemaOptions,\n JsonSchemaResult,\n JsonSchemaDraft,\n MarkformSchemaExtension,\n MarkformFieldExtension,\n} from './engine/jsonSchema.js';\n\n// =============================================================================\n// Table Parsing Exports\n// =============================================================================\n\nexport { parseMarkdownTable, parseCellValue, parseRawTable } from './engine/table/index.js';\nexport type { ParseTableResult, ParsedRawTable } from './engine/table/index.js';\n\n// =============================================================================\n// Scope Reference Exports\n// =============================================================================\n\nexport {\n parseScopeRef,\n serializeScopeRef,\n isCellRef,\n isQualifiedRef,\n isFieldRef,\n getFieldId,\n} from './engine/scopeRef.js';\nexport type {\n FieldScopeRef,\n QualifiedScopeRef,\n CellScopeRef,\n ParsedScopeRef,\n ParseScopeRefResult,\n} from './engine/scopeRef.js';\n\n// =============================================================================\n// Value Coercion Exports\n// =============================================================================\n\nexport { findFieldById, coerceToFieldPatch, coerceInputContext } from './engine/valueCoercion.js';\nexport type {\n RawFieldValue,\n InputContext,\n CoercionResult,\n CoerceInputContextResult,\n} from './engine/valueCoercion.js';\n\n// =============================================================================\n// Harness Exports\n// =============================================================================\n\nexport { FormHarness, createHarness } from './harness/harness.js';\nexport { MockAgent, createMockAgent } from './harness/mockAgent.js';\nexport { fillForm } from './harness/programmaticFill.js';\nexport { resolveHarnessConfig } from './harness/harnessConfigResolver.js';\nexport {\n ParallelHarness,\n createParallelHarness,\n scopeIssuesForItem,\n} from './harness/parallelHarness.js';\nexport type {\n ScopedFillRequest,\n ParallelHarnessConfig,\n ParallelStepResult,\n ParallelRunResult,\n} from './harness/parallelHarness.js';\nexport type {\n FillCallbacks,\n FillOptions,\n FillResult,\n FillStatus,\n TurnProgress,\n TurnStats,\n AgentResponse,\n} from './harness/harnessTypes.js';\n\n// =============================================================================\n// FillRecord Exports\n// =============================================================================\n\nexport { FillRecordCollector } from './harness/fillRecordCollector.js';\nexport type { FillRecordCollectorOptions } from './harness/fillRecordCollector.js';\nexport { formatFillRecordSummary } from './harness/formatFillRecordSummary.js';\nexport type { FormatFillRecordSummaryOptions } from './harness/formatFillRecordSummary.js';\nexport type {\n FillRecord,\n FillRecordStatus,\n TimelineEntry,\n ToolCallRecord,\n ToolStats,\n ToolSummary,\n TimingBreakdown,\n TimingBreakdownItem,\n ExecutionMetadata,\n} from './harness/fillRecord.js';\nexport {\n FillRecordSchema,\n FillRecordStatusSchema,\n TimelineEntrySchema,\n ToolCallRecordSchema,\n ToolStatsSchema,\n ToolSummarySchema,\n TimingBreakdownSchema,\n TimingBreakdownItemSchema,\n ExecutionMetadataSchema,\n} from './harness/fillRecord.js';\n\n// =============================================================================\n// Research Exports\n// =============================================================================\n\nexport { runResearch } from './research/runResearch.js';\nexport type { ResearchOptions } from './research/runResearch.js';\nexport { isResearchForm, validateResearchForm } from './research/researchFormValidation.js';\nexport type { ResearchResult, ResearchStatus } from './research/researchTypes.js';\n\n// =============================================================================\n// Error Exports\n// =============================================================================\n\nexport {\n // Error classes\n MarkformError,\n MarkformParseError,\n MarkformPatchError,\n MarkformValidationError,\n MarkformLlmError,\n MarkformConfigError,\n MarkformAbortError,\n // Backward compatibility alias (deprecated - use MarkformParseError)\n ParseError,\n // Type guards\n isMarkformError,\n isParseError,\n isPatchError,\n isValidationError,\n isLlmError,\n isConfigError,\n isAbortError,\n isRetryableError,\n} from './errors.js';\n"],"x_google_ignoreList":[14,15,16,17,18],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;ACTD,MAAM,eAAe;;AAGrB,MAAM,gBAAgB;;AAGtB,MAAM,wBAAwB;;;;;AAM9B,SAAS,2BAA2B,OAAuB;CACzD,MAAM,QAAQ,sBAAsB,KAAK,MAAM;AAC/C,KAAI,MACF,QAAO,MAAM;AAEf,QAAO;;;;;AAMT,SAAS,cAAc,OAAmE;CACxF,MAAM,UAAU,MAAM,MAAM;CAE5B,MAAM,YAAY,aAAa,KAAK,QAAQ;AAC5C,KAAI,UACF,QAAO;EAAE,MAAM;EAAQ,QAAQ,UAAU;EAAI;CAG/C,MAAM,aAAa,cAAc,KAAK,QAAQ;AAC9C,KAAI,WACF,QAAO;EAAE,MAAM;EAAS,QAAQ,WAAW;EAAI;AAGjD,QAAO;;;;;;AAWT,SAAgB,eAAe,UAAkB,YAA0C;CACzF,MAAM,UAAU,SAAS,MAAM;AAG/B,KAAI,CAAC,QACH,QAAO,EAAE,OAAO,WAAW;CAI7B,MAAM,WAAW,cAAc,QAAQ;AAC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