markform 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +48 -39
  2. package/dist/ai-sdk.d.mts +3 -2
  3. package/dist/ai-sdk.mjs +3 -2
  4. package/dist/ai-sdk.mjs.map +1 -0
  5. package/dist/{apply-CUH_16RD.mjs → apply-CXsI5N9x.mjs} +639 -9
  6. package/dist/apply-CXsI5N9x.mjs.map +1 -0
  7. package/dist/bin.mjs +3 -2
  8. package/dist/bin.mjs.map +1 -0
  9. package/dist/{cli-ixzNVirs.mjs → cli-BsFessUW.mjs} +713 -120
  10. package/dist/cli-BsFessUW.mjs.map +1 -0
  11. package/dist/cli.d.mts +2 -1
  12. package/dist/cli.mjs +1 -1
  13. package/dist/{coreTypes-CnKsB1H3.d.mts → coreTypes-DE6Giau5.d.mts} +10 -1
  14. package/dist/coreTypes-DiCddBKu.mjs +2 -1
  15. package/dist/coreTypes-DiCddBKu.mjs.map +1 -0
  16. package/dist/index.d.mts +15 -2
  17. package/dist/index.mjs +2 -2
  18. package/dist/session-XDrocA3j.mjs +2 -1
  19. package/dist/session-XDrocA3j.mjs.map +1 -0
  20. package/dist/{shared-D3dNi-Gn.mjs → shared-CCq4haEV.mjs} +9 -1
  21. package/dist/shared-CCq4haEV.mjs.map +1 -0
  22. package/dist/shared-fUKfJ1UA.mjs +4 -0
  23. package/dist/{src-BKRKMdgR.mjs → src-Dv3IZSQU.mjs} +15 -6
  24. package/dist/src-Dv3IZSQU.mjs.map +1 -0
  25. package/docs/markform-reference.md +58 -7
  26. package/docs/markform-spec.md +142 -0
  27. package/examples/movie-research/movie-deep-research-mock-filled.form.md +64 -40
  28. package/examples/movie-research/movie-deep-research.form.md +58 -37
  29. package/examples/movie-research/movie-research-demo.form.md +9 -6
  30. package/examples/rejection-test/rejection-test-mock-filled.form.md +5 -7
  31. package/examples/rejection-test/rejection-test-mock-filled.report.md +4 -2
  32. package/examples/rejection-test/rejection-test-mock-filled.schema.json +1 -1
  33. package/examples/rejection-test/rejection-test.form.md +5 -7
  34. package/examples/rejection-test/rejection-test.session.yaml +10 -10
  35. package/examples/simple/simple-comment-syntax.form.md +79 -0
  36. package/examples/simple/simple-mock-filled.form.md +20 -9
  37. package/examples/simple/simple-mock-filled.report.md +30 -7
  38. package/examples/simple/simple-skipped-filled.form.md +22 -10
  39. package/examples/simple/simple-skipped-filled.report.md +27 -4
  40. package/examples/simple/simple-skipped-filled.yml +1 -1
  41. package/examples/simple/simple-with-skips.session.yaml +35 -19
  42. package/examples/simple/simple.form.md +20 -9
  43. package/examples/simple/simple.raw.md +18 -25
  44. package/examples/simple/simple.session.yaml +35 -19
  45. package/examples/startup-deep-research/startup-deep-research.form.md +126 -103
  46. package/examples/startup-research/startup-research-mock-filled.form.md +19 -10
  47. package/examples/startup-research/startup-research.form.md +36 -29
  48. package/package.json +9 -3
  49. package/dist/shared-CNqwaxUt.mjs +0 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-Dv3IZSQU.mjs","names":["CHECKBOX_MARKERS: Record<string, CheckboxValue>","name","value: unknown","items: ParsedOptionItem[]","id: string | null","lines: string[]","parseSentinel","rows: TableRowResponse[]","row: TableRowResponse","rows: string[][]","_exhaustive: never","field: StringField","field: NumberField","numValue: number | null","field: StringListField","items: string[]","options: Option[]","selected: Record<string, CheckboxValue>","field: SingleSelectField","selectedOption: string | null","field: MultiSelectField","selectedOptions: string[]","checkboxMode: CheckboxMode","approvalMode: ApprovalMode","required: boolean","field: CheckboxesField","values: Record<string, CheckboxValue>","field: UrlField","field: UrlListField","field: DateField","dateValue: string | null","field: YearField","yearValue: number | null","columns: TableColumn[]","type: ColumnTypeName","field: TableField","LEGACY_TAG_TO_KIND: Record<string, FieldKind>","result: FrontmatterHarnessConfig","keyMap: Record<string, keyof FrontmatterHarnessConfig>","runMode: RunMode | undefined","children: FieldGroup['children']","groups: FieldGroup[]","ungroupedFields: FieldGroup['children']","notes: Note[]","docs: DocumentationBlock[]","syntaxStyle: SyntaxStyle","formSchema: FormSchema | null","responsesByFieldId: Record<Id, FieldResponse>","orderIndex: Id[]","SCHEMA_URLS: Record<JsonSchemaDraft, string>","schema: JsonSchemaProperty","itemSchema: JsonSchemaProperty","properties: Record<string, JsonSchemaProperty>","rowProperties: Record<string, JsonSchemaProperty>","requiredColumns: string[]","rowSchema: JsonSchemaProperty","ext: MarkformFieldExtension","ext: MarkformSchemaExtension","groups: { id: string; title?: string }[]","opts: Required<JsonSchemaOptions>","_exhaustive: never","requiredFields: string[]","schema: JsonSchemaRoot","items: string[]","selected: string[]","warning: string | undefined","patch: Patch","values: Record<string, CheckboxValue>","values","values: Record<OptionId, CheckboxValue>","rows: TableRowPatch[]","_exhaustive: never","patches: Patch[]","warnings: string[]","errors: string[]","DEFAULT_CONFIG: HarnessConfig","result","turn: SessionTurn","result: InspectIssue[]","clearPatches: ClearFieldPatch[]","patches: Patch[]","_exhaustive: never","patchRow: TableRowPatch","marker","symbol","name","_a2","_b2","VERSION","ZodFirstPartyTypeKind2","ZodFirstPartyTypeKind3","name2","name3","_a3","zodSchema","TypeValidationError2","TypeValidationError3","InvalidArgumentError2","APICallError3","APICallError4","VERSION","zodSchema","z","lazySchema2","zodSchema2","z2","z3","_a","lazySchema3","zodSchema3","z4","lazySchema4","zodSchema4","z5","lazySchema5","zodSchema5","z6","createProviderToolFactoryWithOutputSchema2","tool","_b","lazySchema6","zodSchema6","z7","createProviderToolFactoryWithOutputSchema3","lazySchema7","zodSchema7","z8","createProviderToolFactoryWithOutputSchema4","lazySchema8","zodSchema8","z9","createProviderToolFactoryWithOutputSchema5","UnsupportedFunctionalityError2","_a2","_b2","validateTypes2","parseProviderOptions2","_a3","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","lazySchema17","zodSchema17","z18","createProviderToolFactoryWithOutputSchema6","generateId2","PATCH_FORMATS: Record<string, string>","options: PatchFormatHintOptions","fillFormToolDef: Tool","rawTools: Record<string, Tool>","patches: Patch[]","toolCalls: TurnStats['toolCalls']","name","stats: TurnStats","schemas: Record<string, { description: string; inputSchema: unknown }>","tool","sorted: Record<string, unknown>","steps: WireResponseStep[]","sections: string[]","fieldInstructions: string[]","lines: string[]","optionIds: string[] | undefined","checkboxMode: 'simple' | 'multi' | 'explicit' | undefined","columnIds: string[] | undefined","wrapped: Record<string, Tool>","tools: Record<string, { description: string; inputSchema: unknown }>","PROVIDERS: Record<ProviderName, { package: string; envVar: string; createFn: string }>","providerModule: Record<string, (modelId: string) => LanguageModel>","model: LanguageModel","values: Record<string, FieldValue>","result: FillResult","form: ParsedForm","model: LanguageModel | undefined","provider: string | undefined","inputContextWarnings: string[]","agent: Agent","previousRejections: PatchRejection[] | undefined","llmStats: SessionTurnStats | undefined","context: SessionTurnContext | undefined","status: ResearchStatus","transcript: SessionTranscript","VERSION: string"],"sources":["../src/engine/fieldRegistry.ts","../src/engine/parseHelpers.ts","../src/engine/parseSentinels.ts","../src/engine/table/parseTable.ts","../src/engine/parseFields.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","../../../node_modules/.pnpm/@ai-sdk+provider@3.0.0/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.1_zod@4.2.1/node_modules/@ai-sdk/provider-utils/dist/index.mjs","../../../node_modules/.pnpm/@ai-sdk+anthropic@3.0.1_zod@4.2.1/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/programmaticFill.ts","../src/harness/harnessConfigResolver.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 * Low-level parsing utilities for Markdoc AST processing.\n *\n * This module provides helper functions for extracting attributes and content\n * from Markdoc AST nodes. These are used by the field parsers and form parser.\n */\n\nimport type { Node } from '@markdoc/markdoc';\n\nimport type { CheckboxValue, ValidatorRef } from './coreTypes.js';\n\n// =============================================================================\n// Checkbox Marker Parsing\n// =============================================================================\n\n/** Map checkbox marker to state value */\nexport const CHECKBOX_MARKERS: Record<string, CheckboxValue> = {\n '[ ]': 'todo',\n '[x]': 'done',\n '[X]': 'done',\n '[/]': 'incomplete',\n '[*]': 'active',\n '[-]': 'na',\n '[y]': 'yes',\n '[Y]': 'yes',\n '[n]': 'no',\n '[N]': 'no',\n};\n\n// Regex to extract checkbox marker and label from text content\n// Text is like \"[ ] Label\" or \"[x] Label\"\nconst OPTION_TEXT_PATTERN = /^(\\[[^\\]]\\])\\s*(.*?)\\s*$/;\n\nexport interface ParsedMarkerText {\n marker: string;\n label: string;\n}\n\n/**\n * Parse option text to extract marker and label.\n * Text is like \"[ ] Label\" or \"[x] Label\".\n */\nexport function parseOptionText(text: string): ParsedMarkerText | null {\n const match = OPTION_TEXT_PATTERN.exec(text);\n if (!match) {\n return null;\n }\n\n const marker = match[1] ?? '';\n const label = (match[2] ?? '').trim();\n\n return { marker, label };\n}\n\n// =============================================================================\n// Markdoc Tag Processing\n// =============================================================================\n\n/**\n * Check if a node is a tag node with specific name.\n * Works with raw AST nodes (not transformed Tags).\n */\nexport function isTagNode(node: Node, name?: string): boolean {\n if (typeof node !== 'object' || node === null) {\n return false;\n }\n if (node.type === 'tag' && node.tag) {\n return name === undefined || node.tag === name;\n }\n return false;\n}\n\n/**\n * Get string attribute value or undefined.\n */\nexport function getStringAttr(node: Node, name: string): string | undefined {\n const value: unknown = node.attributes?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Get number attribute value or undefined.\n */\nexport function getNumberAttr(node: Node, name: string): number | undefined {\n const value: unknown = node.attributes?.[name];\n return typeof value === 'number' ? value : undefined;\n}\n\n/**\n * Get boolean attribute value or undefined.\n */\nexport function getBooleanAttr(node: Node, name: string): boolean | undefined {\n const value: unknown = node.attributes?.[name];\n return typeof value === 'boolean' ? value : undefined;\n}\n\n/**\n * Get validator references from validate attribute.\n * Handles both single string and array formats.\n */\nexport function getValidateAttr(node: Node): ValidatorRef[] | undefined {\n const value: unknown = node.attributes?.validate;\n if (value === undefined || value === null) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value as ValidatorRef[];\n }\n if (typeof value === 'string') {\n return [value];\n }\n if (typeof value === 'object') {\n // Single object validator ref like { id: \"foo\", param: 1 }\n return [value as ValidatorRef];\n }\n return undefined;\n}\n\n/**\n * Get string array attribute value or undefined.\n * Handles both single string (converts to array) and array formats.\n */\nexport function getStringArrayAttr(node: Node, name: string): string[] | undefined {\n const value: unknown = node.attributes?.[name];\n if (value === undefined || value === null) {\n return undefined;\n }\n if (Array.isArray(value)) {\n // Filter to only strings\n const strings = value.filter((v): v is string => typeof v === 'string');\n return strings.length > 0 ? strings : undefined;\n }\n if (typeof value === 'string') {\n return [value];\n }\n return undefined;\n}\n\n/**\n * Parsed option item from AST.\n */\nexport interface ParsedOptionItem {\n /** ID from {% #id %} annotation */\n id: string | null;\n /** Text content (e.g., \"[ ] Label\" or \"[x] Label\") */\n text: string;\n}\n\n/**\n * Extract option items from node children (for option lists).\n * Works with raw AST nodes. Collects text and ID from list items.\n */\nexport function extractOptionItems(node: Node): ParsedOptionItem[] {\n const items: ParsedOptionItem[] = [];\n\n /**\n * Collect all text content from a node tree into a single string.\n */\n function collectText(n: Node): string {\n let text = '';\n\n // Text nodes have content in attributes\n if (n.type === 'text' && typeof n.attributes?.content === 'string') {\n text += n.attributes.content;\n }\n\n // Softbreak is a newline\n if (n.type === 'softbreak') {\n text += '\\n';\n }\n\n // Recurse into children\n if (n.children && Array.isArray(n.children)) {\n for (const c of n.children) {\n text += collectText(c);\n }\n }\n\n return text;\n }\n\n /**\n * Traverse to find list items and extract their content.\n */\n function traverse(child: Node): void {\n if (!child || typeof child !== 'object') {\n return;\n }\n\n // List items contain the option text and ID\n if (child.type === 'item') {\n const text = collectText(child);\n // Markdoc parses {% #id %} as an id attribute on the item (tight list)\n // or on the first child paragraph (loose list with blank lines between items)\n let id: string | null = null;\n if (typeof child.attributes?.id === 'string') {\n // Tight list: ID is directly on the item\n id = child.attributes.id;\n } else if (\n child.children &&\n Array.isArray(child.children) &&\n child.children.length > 0 &&\n typeof child.children[0]?.attributes?.id === 'string'\n ) {\n // Loose list: ID is on the first child (paragraph)\n id = child.children[0].attributes.id;\n }\n if (text.trim()) {\n items.push({ id, text: text.trim() });\n }\n return; // Don't recurse further into item children\n }\n\n // Recurse into children\n if (child.children && Array.isArray(child.children)) {\n for (const c of child.children) {\n traverse(c);\n }\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 return items;\n}\n\n/**\n * Extract fence value from node children.\n * Looks for ```value code blocks.\n */\nexport function extractFenceValue(node: Node): string | null {\n function traverse(child: Node): string | null {\n if (!child || typeof child !== 'object') {\n return null;\n }\n\n // Check if this is a fence node with language=\"value\"\n if (child.type === 'fence') {\n const lang = child.attributes?.language as string | undefined;\n if (lang === 'value') {\n return typeof child.attributes?.content === 'string' ? child.attributes.content : null;\n }\n }\n\n // Traverse children\n if (child.children && Array.isArray(child.children)) {\n for (const c of child.children) {\n const result = traverse(c);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n const result = traverse(child);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Extract table content from node children.\n * Handles both raw text and Markdoc-parsed table nodes.\n * Reconstructs markdown table format from the AST.\n */\nexport function extractTableContent(node: Node): string | null {\n const lines: string[] = [];\n\n function extractTextFromNode(n: Node): string {\n if (!n || typeof n !== 'object') return '';\n if (n.type === 'text' && typeof n.attributes?.content === 'string') {\n return n.attributes.content;\n }\n if (n.children && Array.isArray(n.children)) {\n return n.children.map(extractTextFromNode).join('');\n }\n return '';\n }\n\n function extractTableRow(trNode: Node): string {\n if (!trNode.children || !Array.isArray(trNode.children)) return '';\n const cells = trNode.children\n .filter((c: Node) => c.type === 'th' || c.type === 'td')\n .map((c: Node) => extractTextFromNode(c).trim());\n return `| ${cells.join(' | ')} |`;\n }\n\n function processNode(child: Node): void {\n if (!child || typeof child !== 'object') return;\n\n // Paragraph containing text (like \"| Name | Role |\")\n if (child.type === 'paragraph' || child.type === 'inline') {\n const text = extractTextFromNode(child).trim();\n if (text) {\n lines.push(text);\n }\n return;\n }\n\n // Text node directly\n if (child.type === 'text' && typeof child.attributes?.content === 'string') {\n const text = child.attributes.content.trim();\n if (text) {\n lines.push(text);\n }\n return;\n }\n\n // Markdoc table node - reconstruct as markdown\n if (child.type === 'table') {\n // Process thead\n const thead = child.children?.find((c: Node) => c.type === 'thead');\n if (thead?.children) {\n for (const tr of thead.children.filter((c: Node) => c.type === 'tr')) {\n lines.push(extractTableRow(tr));\n }\n }\n\n // If we have header rows, add separator\n if (thead?.children?.length) {\n const firstTr = thead.children.find((c: Node) => c.type === 'tr');\n if (firstTr?.children) {\n const colCount = firstTr.children.filter(\n (c: Node) => c.type === 'th' || c.type === 'td',\n ).length;\n const separatorCells = Array(colCount).fill('----');\n lines.push(`| ${separatorCells.join(' | ')} |`);\n }\n }\n\n // Process tbody\n const tbody = child.children?.find((c: Node) => c.type === 'tbody');\n if (tbody?.children) {\n for (const tr of tbody.children.filter((c: Node) => c.type === 'tr')) {\n lines.push(extractTableRow(tr));\n }\n }\n return;\n }\n\n // Traverse children for other node types\n if (child.children && Array.isArray(child.children)) {\n for (const c of child.children) {\n processNode(c);\n }\n }\n }\n\n if (node.children && Array.isArray(node.children)) {\n for (const child of node.children) {\n processNode(child);\n }\n }\n\n const result = lines.join('\\n').trim();\n return result || null;\n}\n","/**\n * Sentinel value parsing for Markform fields.\n *\n * Sentinel values (%SKIP% and %ABORT%) are special markers that indicate\n * a field was intentionally skipped or aborted rather than filled in.\n */\n\nimport type { Node } from '@markdoc/markdoc';\n\nimport type { FieldResponse } from './coreTypes.js';\nimport { extractFenceValue, getStringAttr } from './parseHelpers.js';\nimport { MarkformParseError } from '../errors.js';\n\n// =============================================================================\n// Sentinel Constants\n// =============================================================================\n\n/** Sentinel values for text fields */\nexport const SENTINEL_SKIP = '%SKIP%';\nexport const SENTINEL_ABORT = '%ABORT%';\n\n// =============================================================================\n// Sentinel Parsing\n// =============================================================================\n\n/**\n * Parsed sentinel value.\n */\nexport interface ParsedSentinel {\n type: 'skip' | 'abort';\n reason?: string;\n}\n\n/**\n * Parse a sentinel value with optional parenthesized reason.\n * Formats: `%SKIP%`, `%SKIP% (reason text)`, `%ABORT%`, `%ABORT% (reason text)`\n * Returns null if the content is not a sentinel.\n */\nexport function parseSentinel(content: string | null): ParsedSentinel | null {\n if (!content) {\n return null;\n }\n\n const trimmed = content.trim();\n const reasonPattern = /^\\((.+)\\)$/s;\n\n // Check for %SKIP% with optional reason\n if (trimmed.startsWith(SENTINEL_SKIP)) {\n const rest = trimmed.slice(SENTINEL_SKIP.length).trim();\n if (rest === '') {\n return { type: 'skip' };\n }\n // Extract reason from parentheses\n const match = reasonPattern.exec(rest);\n if (match?.[1]) {\n return { type: 'skip', reason: match[1].trim() };\n }\n // Invalid format - just %SKIP% with non-parenthesized content\n return null;\n }\n\n // Check for %ABORT% with optional reason\n if (trimmed.startsWith(SENTINEL_ABORT)) {\n const rest = trimmed.slice(SENTINEL_ABORT.length).trim();\n if (rest === '') {\n return { type: 'abort' };\n }\n // Extract reason from parentheses\n const match = reasonPattern.exec(rest);\n if (match?.[1]) {\n return { type: 'abort', reason: match[1].trim() };\n }\n // Invalid format - just %ABORT% with non-parenthesized content\n return null;\n }\n\n return null;\n}\n\n/**\n * Check for sentinel values in fence content and validate against state attribute.\n * Handles the common pattern of checking for %SKIP% and %ABORT% sentinels in field values.\n *\n * @param node - The field node to check\n * @param fieldId - The field ID for error messages\n * @param required - Whether the field is required (skip not allowed on required fields)\n * @returns A FieldResponse if a sentinel is found, null otherwise\n */\nexport function tryParseSentinelResponse(\n node: Node,\n fieldId: string,\n required: boolean,\n): FieldResponse | null {\n const fenceContent = extractFenceValue(node);\n const stateAttr = getStringAttr(node, 'state');\n\n const sentinel = parseSentinel(fenceContent);\n if (!sentinel) {\n return null;\n }\n\n if (sentinel.type === 'skip') {\n if (stateAttr !== undefined && stateAttr !== 'skipped') {\n throw new MarkformParseError(\n `Field '${fieldId}' has conflicting state='${stateAttr}' with %SKIP% sentinel`,\n );\n }\n if (required) {\n throw new MarkformParseError(\n `Field '${fieldId}' is required but has %SKIP% sentinel. Cannot skip required fields.`,\n );\n }\n return { state: 'skipped', ...(sentinel.reason && { reason: sentinel.reason }) };\n }\n\n if (sentinel.type === 'abort') {\n if (stateAttr !== undefined && stateAttr !== 'aborted') {\n throw new MarkformParseError(\n `Field '${fieldId}' has conflicting state='${stateAttr}' with %ABORT% sentinel`,\n );\n }\n return { state: 'aborted', ...(sentinel.reason && { reason: sentinel.reason }) };\n }\n\n return null;\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/**\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 // Basic URL validation - more thorough validation happens in validate.ts\n return { state: 'answered', value: trimmed };\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}\n\n/**\n * Get common field attributes (priority, role, validate, report).\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 };\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 * 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 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 * 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 DocumentationBlock,\n DocumentationTag,\n FieldGroup,\n FieldResponse,\n FormMetadata,\n FormSchema,\n FrontmatterHarnessConfig,\n Id,\n IdIndexEntry,\n Note,\n ParsedForm,\n RunMode,\n SyntaxStyle,\n} from './coreTypes.js';\nimport { RunModeSchema } from './coreTypes.js';\nimport { DEFAULT_ROLES, DEFAULT_ROLE_INSTRUCTIONS } from '../settings.js';\nimport { parseField } from './parseFields.js';\nimport { getBooleanAttr, getStringAttr, getValidateAttr, isTagNode } from './parseHelpers.js';\nimport { MarkformParseError } from '../errors.js';\nimport { detectSyntaxStyle, preprocessCommentSyntax } from './preprocess.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 * Parse harness configuration from frontmatter.\n * Converts snake_case keys to camelCase.\n */\nfunction parseHarnessConfig(raw: unknown): FrontmatterHarnessConfig | undefined {\n if (!raw || typeof raw !== 'object') {\n return undefined;\n }\n\n const config = raw as Record<string, unknown>;\n const result: FrontmatterHarnessConfig = {};\n\n // Map snake_case to camelCase\n const keyMap: Record<string, keyof FrontmatterHarnessConfig> = {\n max_turns: 'maxTurns',\n maxTurns: 'maxTurns',\n max_patches_per_turn: 'maxPatchesPerTurn',\n maxPatchesPerTurn: 'maxPatchesPerTurn',\n max_issues_per_turn: 'maxIssuesPerTurn',\n maxIssuesPerTurn: 'maxIssuesPerTurn',\n };\n\n for (const [key, value] of Object.entries(config)) {\n const camelKey = keyMap[key];\n if (camelKey && typeof value === 'number') {\n result[camelKey] = value;\n }\n }\n\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\n/**\n * Extract YAML frontmatter from Markdoc AST.\n * Uses Markdoc's native frontmatter extraction and parses the YAML.\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 markformSection = frontmatter.markform as Record<string, unknown> | undefined;\n if (!markformSection) {\n return { frontmatter };\n }\n\n // Parse harness config from markform.harness\n const harnessConfig = parseHarnessConfig(markformSection.harness);\n\n // Parse run_mode from markform.run_mode\n let runMode: RunMode | undefined;\n const rawRunMode = markformSection.run_mode;\n if (rawRunMode !== undefined) {\n const parsed = RunModeSchema.safeParse(rawRunMode);\n if (!parsed.success) {\n throw new MarkformParseError(\n `Invalid run_mode: '${typeof rawRunMode === 'string' ? rawRunMode : JSON.stringify(rawRunMode)}'. Must be one of: interactive, fill, research`,\n );\n }\n runMode = parsed.data;\n }\n\n // Extract description from markform.description\n const description =\n typeof markformSection.description === 'string' ? markformSection.description : undefined;\n\n // Build metadata\n const metadata: FormMetadata = {\n markformVersion: (markformSection.spec as string) ?? 'MF/0.1',\n roles: (frontmatter.roles as string[]) ?? [...DEFAULT_ROLES],\n roleInstructions:\n (frontmatter.role_instructions as Record<string, string>) ?? DEFAULT_ROLE_INSTRUCTIONS,\n ...(harnessConfig && { harnessConfig }),\n ...(runMode && { runMode }),\n };\n\n return { frontmatter, metadata, 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// 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 return {\n id,\n title,\n validate: getValidateAttr(node),\n children,\n report: getBooleanAttr(node, 'report'),\n };\n}\n\n/**\n * Parse a form tag.\n * Handles both explicit groups and fields placed directly under the form.\n */\nfunction parseFormTag(\n node: Node,\n responsesByFieldId: Record<Id, FieldResponse>,\n orderIndex: Id[],\n idIndex: Map<Id, IdIndexEntry>,\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 if (ungroupedFields.length > 0) {\n const implicitGroupId = `_default`;\n if (idIndex.has(implicitGroupId)) {\n throw new MarkformParseError(\n `ID '${implicitGroupId}' is reserved for implicit field groups. ` +\n `Please use a different ID for your field or group.`,\n );\n }\n idIndex.set(implicitGroupId, { nodeType: 'group', parentId: id });\n groups.push({\n id: implicitGroupId,\n children: ungroupedFields,\n implicit: true,\n });\n }\n\n return { id, title, groups };\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 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);\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 return {\n schema,\n responsesByFieldId,\n notes,\n docs,\n orderIndex,\n idIndex,\n ...(metadata && { metadata }),\n syntaxStyle,\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 // 1. Filter by maxGroupsPerTurn/maxFieldsPerTurn - limits scope diversity\n // 2. Cap by maxIssuesPerTurn - limits total count shown to agent\n const filteredIssues = this.filterIssuesByScope(result.issues);\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 * 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","// 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({ value, cause }) {\n super({\n name: name12,\n message: `Type validation failed: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\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, 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 * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause\n }) {\n return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });\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\"];\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 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.1\" : \"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\") {\n jsonSchema2.additionalProperties = false;\n const properties = jsonSchema2.properties;\n if (properties != null) {\n for (const property in properties) {\n properties[property] = addAdditionalPropertiesToJsonSchema(\n properties[property]\n );\n }\n }\n }\n if (jsonSchema2.type === \"array\" && jsonSchema2.items != null) {\n if (Array.isArray(jsonSchema2.items)) {\n jsonSchema2.items = jsonSchema2.items.map(\n (item) => addAdditionalPropertiesToJsonSchema(item)\n );\n } else {\n jsonSchema2.items = addAdditionalPropertiesToJsonSchema(\n jsonSchema2.items\n );\n }\n }\n return jsonSchema2;\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 () => standardSchema2[\"~standard\"].jsonSchema.input({\n target: \"draft-07\"\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}) {\n const result = await safeValidateTypes({ value, schema });\n if (!result.success) {\n throw TypeValidationError2.wrap({ value, cause: result.error });\n }\n return result.value;\n}\nasync function safeValidateTypes({\n value,\n schema\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 }),\n rawValue: value\n };\n } catch (error) {\n return {\n success: false,\n error: TypeValidationError2.wrap({ value, cause: error }),\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\nexport * from \"@standard-schema/spec\";\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 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.1\" : \"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 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 usage: z2.looseObject({\n output_tokens: z2.number(),\n cache_creation_input_tokens: z2.number().nullish()\n })\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 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});\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});\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_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});\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}\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;\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: part.data instanceof URL ? {\n type: \"url\",\n url: part.data.toString()\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: part.data instanceof URL ? {\n type: \"url\",\n url: part.data.toString()\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: part.data instanceof URL ? {\n type: \"url\",\n url: part.data.toString()\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 const errorValue = JSON.parse(output.value);\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: errorValue.errorCode\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 !== \"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 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 anthropicOptions = await parseProviderOptions2({\n provider: \"anthropic\",\n providerOptions,\n schema: anthropicProviderOptions\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 }\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\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 };\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, _g, _h, _i, _j;\n const { args, warnings, betas, usesJsonResponseTool, toolNameMapping } = await this.getArgs({\n ...options,\n stream: false,\n userSuppliedBetas: await this.getBetasFromHeaders(options.headers)\n });\n const citationDocuments = this.extractCitationDocuments(options.prompt);\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 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 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 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: (_a = result.page_age) != null ? _a : 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: (_b = part.content.content) != null ? _b : []\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 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(\"tool_search\"),\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(\"tool_search\"),\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: (_c = response.stop_reason) != null ? _c : void 0\n },\n usage: convertAnthropicMessagesUsage(response.usage),\n request: { body: args },\n response: {\n id: (_d = response.id) != null ? _d : void 0,\n modelId: (_e = response.model) != null ? _e : void 0,\n headers: responseHeaders,\n body: rawResponse\n },\n warnings,\n providerMetadata: {\n anthropic: {\n usage: response.usage,\n cacheCreationInputTokens: (_f = response.usage.cache_creation_input_tokens) != null ? _f : null,\n stopSequence: (_g = response.stop_sequence) != null ? _g : null,\n container: response.container ? {\n expiresAt: response.container.expires_at,\n id: response.container.id,\n skills: (_i = (_h = response.container.skills) == null ? void 0 : _h.map((skill) => ({\n type: skill.type,\n skillId: skill.skill_id,\n version: skill.version\n }))) != null ? _i : null\n } : null,\n contextManagement: (_j = mapAnthropicResponseContextManagement(\n response.context_management\n )) != null ? _j : null\n }\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 } = await this.getArgs({\n ...options,\n stream: true,\n userSuppliedBetas: await this.getBetasFromHeaders(options.headers)\n });\n const citationDocuments = this.extractCitationDocuments(options.prompt);\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 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;\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 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 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: (_a2 = result.page_age) != null ? _a2 : 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: (_b2 = part.content.content) != null ? _b2 : []\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 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(\"tool_search\"),\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(\"tool_search\"),\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 = (_c = value.message.usage.cache_read_input_tokens) != null ? _c : 0;\n usage.cache_creation_input_tokens = (_d = value.message.usage.cache_creation_input_tokens) != null ? _d : 0;\n rawUsage = {\n ...value.message.usage\n };\n cacheCreationInputTokens = (_e = value.message.usage.cache_creation_input_tokens) != null ? _e : 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: (_f = value.message.id) != null ? _f : void 0,\n modelId: (_g = value.message.model) != null ? _g : 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((_h = part.input) != null ? _h : {});\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 usage.output_tokens = value.usage.output_tokens;\n finishReason = {\n unified: mapAnthropicStopReason({\n finishReason: value.delta.stop_reason,\n isJsonResponseFromTool\n }),\n raw: (_i = value.delta.stop_reason) != null ? _i : void 0\n };\n stopSequence = (_j = value.delta.stop_sequence) != null ? _j : null;\n container = value.delta.container != null ? {\n expiresAt: value.delta.container.expires_at,\n id: value.delta.container.id,\n skills: (_l = (_k = value.delta.container.skills) == null ? void 0 : _k.map((skill) => ({\n type: skill.type,\n skillId: skill.skill_id,\n version: skill.version\n }))) != null ? _l : null\n } : null;\n if (value.delta.context_management) {\n contextManagement = mapAnthropicResponseContextManagement(\n value.delta.context_management\n );\n }\n rawUsage = {\n ...rawUsage,\n ...value.usage\n };\n return;\n }\n case \"message_stop\": {\n controller.enqueue({\n type: \"finish\",\n finishReason,\n usage: convertAnthropicMessagesUsage(usage),\n providerMetadata: {\n anthropic: {\n usage: rawUsage != null ? rawUsage : null,\n cacheCreationInputTokens,\n stopSequence,\n container,\n contextManagement\n }\n }\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\")) {\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\") || modelId.includes(\"claude-haiku-4-5\")) {\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/memory_20250818.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 memory_20250818InputSchema = lazySchema13(\n () => zodSchema13(\n z14.discriminatedUnion(\"command\", [\n z14.object({\n command: z14.literal(\"view\"),\n path: z14.string(),\n view_range: z14.tuple([z14.number(), z14.number()]).optional()\n }),\n z14.object({\n command: z14.literal(\"create\"),\n path: z14.string(),\n file_text: z14.string()\n }),\n z14.object({\n command: z14.literal(\"str_replace\"),\n path: z14.string(),\n old_str: z14.string(),\n new_str: z14.string()\n }),\n z14.object({\n command: z14.literal(\"insert\"),\n path: z14.string(),\n insert_line: z14.number(),\n insert_text: z14.string()\n }),\n z14.object({\n command: z14.literal(\"delete\"),\n path: z14.string()\n }),\n z14.object({\n command: z14.literal(\"rename\"),\n old_path: z14.string(),\n new_path: z14.string()\n })\n ])\n )\n);\nvar memory_20250818 = createProviderToolFactory6({\n id: \"anthropic.memory_20250818\",\n inputSchema: memory_20250818InputSchema\n});\n\n// src/tool/text-editor_20241022.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 textEditor_20241022InputSchema = lazySchema14(\n () => zodSchema14(\n z15.object({\n command: z15.enum([\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"]),\n path: z15.string(),\n file_text: z15.string().optional(),\n insert_line: z15.number().int().optional(),\n new_str: z15.string().optional(),\n old_str: z15.string().optional(),\n view_range: z15.array(z15.number().int()).optional()\n })\n )\n);\nvar textEditor_20241022 = createProviderToolFactory7({\n id: \"anthropic.text_editor_20241022\",\n inputSchema: textEditor_20241022InputSchema\n});\n\n// src/tool/text-editor_20250124.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_20250124InputSchema = 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 old_str: z16.string().optional(),\n view_range: z16.array(z16.number().int()).optional()\n })\n )\n);\nvar textEditor_20250124 = createProviderToolFactory8({\n id: \"anthropic.text_editor_20250124\",\n inputSchema: textEditor_20250124InputSchema\n});\n\n// src/tool/text-editor_20250429.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_20250429InputSchema = lazySchema16(\n () => zodSchema16(\n z17.object({\n command: z17.enum([\"view\", \"create\", \"str_replace\", \"insert\"]),\n path: z17.string(),\n file_text: z17.string().optional(),\n insert_line: z17.number().int().optional(),\n new_str: z17.string().optional(),\n old_str: z17.string().optional(),\n view_range: z17.array(z17.number().int()).optional()\n })\n )\n);\nvar textEditor_20250429 = createProviderToolFactory9({\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 lazySchema17,\n zodSchema as zodSchema17\n} from \"@ai-sdk/provider-utils\";\nimport { z as z18 } from \"zod/v4\";\nvar toolSearchBm25_20251119OutputSchema = lazySchema17(\n () => zodSchema17(\n z18.array(\n z18.object({\n type: z18.literal(\"tool_reference\"),\n toolName: z18.string()\n })\n )\n )\n);\nvar toolSearchBm25_20251119InputSchema = lazySchema17(\n () => zodSchema17(\n z18.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: z18.string(),\n /**\n * Maximum number of tools to return. Optional.\n */\n limit: z18.number().optional()\n })\n )\n);\nvar factory7 = createProviderToolFactoryWithOutputSchema6({\n id: \"anthropic.tool_search_bm25_20251119\",\n inputSchema: toolSearchBm25_20251119InputSchema,\n outputSchema: toolSearchBm25_20251119OutputSchema\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 * 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 const getHeaders = () => withUserAgentSuffix(\n {\n \"anthropic-version\": \"2023-06-01\",\n \"x-api-key\": loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: \"ANTHROPIC_API_KEY\",\n description: \"Anthropic\"\n }),\n ...options.headers\n },\n `ai-sdk/anthropic/${VERSION}`\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 })\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\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\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);\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({ model: modelId });\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 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 });\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\n if (toolCall.toolName === FILL_FORM_TOOL_NAME && 'input' in toolCall) {\n const input = toolCall.input as { patches: Patch[] };\n patches.push(...input.patches);\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): Record<string, Tool> {\n // Skip wrapping if no tool callbacks\n if (!callbacks?.onToolStart && !callbacks?.onToolEnd) {\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);\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): 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 });\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 });\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 });\n } catch {\n // Ignore callback errors\n }\n }\n throw error;\n }\n },\n };\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 * 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 { parseForm } from '../engine/parse.js';\nimport { serializeForm } from '../engine/serialize.js';\nimport type {\n FieldValue,\n InspectIssue,\n ParsedForm,\n PatchRejection,\n SessionTurnContext,\n SessionTurnStats,\n} from '../engine/coreTypes.js';\nimport { coerceInputContext } from '../engine/valueCoercion.js';\nimport {\n AGENT_ROLE,\n DEFAULT_MAX_ISSUES_PER_TURN,\n DEFAULT_MAX_PATCHES_PER_TURN,\n DEFAULT_MAX_TURNS,\n} from '../settings.js';\nimport { createHarness } from './harness.js';\nimport { createLiveAgent } from './liveAgent.js';\nimport { resolveModel } from './modelResolver.js';\nimport type { Agent, FillOptions, FillResult, FillStatus } from './harnessTypes.js';\n\n// Re-export types for backwards compatibility\nexport type { FillOptions, FillResult, FillStatus, TurnProgress } from './harnessTypes.js';\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\nfunction buildErrorResult(form: ParsedForm, errors: string[], warnings: string[]): 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 return {\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\nfunction buildResult(\n form: ParsedForm,\n turns: number,\n totalPatches: number,\n status: FillStatus,\n inputContextWarnings?: string[],\n remainingIssues?: InspectIssue[],\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 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 const message = error instanceof Error ? error.message : String(error);\n return buildErrorResult(form, [`Model resolution error: ${message}`], []);\n }\n }\n\n // 3. 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 // Fail fast on input context errors\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 // 4. Create harness + agent\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: options.callbacks,\n maxStepsPerTurn: options.maxStepsPerTurn,\n });\n\n // 5. 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 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 );\n }\n // Check for cancellation\n if (options.signal?.aborted) {\n return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n stepResult.issues,\n );\n }\n\n // Call turn start callback (errors don't abort fill)\n if (options.callbacks?.onTurnStart) {\n try {\n options.callbacks.onTurnStart({\n turnNumber: turnCount + 1,\n issuesCount: stepResult.issues.length,\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 (options.callbacks?.onIssuesIdentified) {\n try {\n options.callbacks.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 const response = await agent.fillFormTool(\n turnIssues,\n form,\n maxPatchesPerTurn,\n previousRejections,\n );\n const { patches, stats } = response;\n\n // Call onPatchesGenerated callback (after agent, before applying)\n if (options.callbacks?.onPatchesGenerated) {\n try {\n options.callbacks.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 return buildResult(\n form,\n turnCount,\n totalPatches,\n { ok: false, reason: 'cancelled' },\n inputContextWarnings,\n turnIssues,\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 (options.callbacks?.onTurnComplete) {\n try {\n const requiredIssues = stepResult.issues.filter((i) => i.severity === 'required');\n options.callbacks.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 });\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 // 6. Determine final status\n if (stepResult.isComplete) {\n return buildResult(form, turnCount, totalPatches, { ok: true }, inputContextWarnings);\n }\n\n // Hit max turns without completing\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 );\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_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 // These don't have frontmatter equivalents\n targetRoles: options?.targetRoles,\n fillMode: options?.fillMode,\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 schema\n MarkformFrontmatterSchema,\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// 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 type {\n FillCallbacks,\n FillOptions,\n FillResult,\n FillStatus,\n TurnProgress,\n TurnStats,\n AgentResponse,\n} from './harness/harnessTypes.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":[11,12,13,14,15],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,cAAc;CACzB;CACA;CACA;C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