@claritylabs/cl-sdk 4.2.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1060,7 +1060,8 @@ var InsurerInfoSchema = z9.object({
1060
1060
  amBestRating: z9.string().optional(),
1061
1061
  amBestNumber: z9.string().optional(),
1062
1062
  admittedStatus: AdmittedStatusSchema.optional(),
1063
- stateOfDomicile: z9.string().optional()
1063
+ stateOfDomicile: z9.string().optional(),
1064
+ address: AddressSchema.optional()
1064
1065
  }).merge(SourceProvenanceSchema);
1065
1066
  var ProducerInfoSchema = z9.object({
1066
1067
  agencyName: z9.string(),
@@ -1617,251 +1618,541 @@ var DeclarationsSchema = z16.discriminatedUnion("line", [
1617
1618
  ]);
1618
1619
 
1619
1620
  // src/schemas/document.ts
1621
+ import { z as z18 } from "zod";
1622
+
1623
+ // src/source/schemas.ts
1620
1624
  import { z as z17 } from "zod";
1621
- var SubsectionSchema = z17.object({
1622
- title: z17.string(),
1623
- sectionNumber: z17.string().optional(),
1624
- pageNumber: z17.number().optional(),
1625
- excerpt: z17.string().optional(),
1626
- content: z17.string().optional(),
1627
- documentNodeId: z17.string().optional(),
1628
- sourceSpanIds: z17.array(z17.string()).optional(),
1629
- sourceTextHash: z17.string().optional()
1630
- });
1631
- var SectionSchema = z17.object({
1625
+ var SourceSpanKindSchema = z17.enum([
1626
+ "pdf_text",
1627
+ "pdf_image",
1628
+ "html",
1629
+ "markdown",
1630
+ "plain_text",
1631
+ "structured_field"
1632
+ ]);
1633
+ var SourceSpanUnitSchema = z17.enum([
1634
+ "page",
1635
+ "section",
1636
+ "table",
1637
+ "table_row",
1638
+ "table_cell",
1639
+ "key_value",
1640
+ "text"
1641
+ ]);
1642
+ var SourceKindSchema = z17.enum([
1643
+ "policy_pdf",
1644
+ "application_pdf",
1645
+ "email",
1646
+ "attachment",
1647
+ "manual_note"
1648
+ ]);
1649
+ var SourceSpanBBoxSchema = z17.object({
1650
+ page: z17.number().int().positive(),
1651
+ x: z17.number(),
1652
+ y: z17.number(),
1653
+ width: z17.number(),
1654
+ height: z17.number()
1655
+ });
1656
+ var SourceSpanLocationSchema = z17.object({
1657
+ page: z17.number().int().positive().optional(),
1658
+ startPage: z17.number().int().positive().optional(),
1659
+ endPage: z17.number().int().positive().optional(),
1660
+ charStart: z17.number().int().nonnegative().optional(),
1661
+ charEnd: z17.number().int().nonnegative().optional(),
1662
+ lineStart: z17.number().int().positive().optional(),
1663
+ lineEnd: z17.number().int().positive().optional(),
1664
+ fieldPath: z17.string().optional()
1665
+ });
1666
+ var SourceSpanTableLocationSchema = z17.object({
1667
+ tableId: z17.string().optional(),
1668
+ rowIndex: z17.number().int().nonnegative().optional(),
1669
+ columnIndex: z17.number().int().nonnegative().optional(),
1670
+ columnName: z17.string().optional(),
1671
+ rowSpanId: z17.string().optional(),
1672
+ tableSpanId: z17.string().optional(),
1673
+ isHeader: z17.boolean().optional()
1674
+ });
1675
+ var SourceSpanSchema = z17.object({
1676
+ id: z17.string().min(1),
1677
+ documentId: z17.string().min(1),
1678
+ sourceKind: SourceKindSchema.optional(),
1679
+ chunkId: z17.string().optional(),
1680
+ kind: SourceSpanKindSchema,
1681
+ text: z17.string(),
1682
+ hash: z17.string().min(1),
1683
+ textHash: z17.string().optional(),
1684
+ pageStart: z17.number().int().positive().optional(),
1685
+ pageEnd: z17.number().int().positive().optional(),
1686
+ sectionId: z17.string().optional(),
1687
+ formNumber: z17.string().optional(),
1688
+ sourceUnit: SourceSpanUnitSchema.optional(),
1689
+ parentSpanId: z17.string().optional(),
1690
+ table: SourceSpanTableLocationSchema.optional(),
1691
+ bbox: z17.array(SourceSpanBBoxSchema).optional(),
1692
+ location: SourceSpanLocationSchema.optional(),
1693
+ metadata: z17.record(z17.string(), z17.string()).optional()
1694
+ });
1695
+ var SourceSpanRefSchema = z17.object({
1696
+ sourceSpanId: z17.string().min(1),
1697
+ documentId: z17.string().min(1).optional(),
1698
+ chunkId: z17.string().optional(),
1699
+ quote: z17.string().optional(),
1700
+ hash: z17.string().optional(),
1701
+ location: SourceSpanLocationSchema.optional()
1702
+ });
1703
+ var SourceChunkSchema = z17.object({
1704
+ id: z17.string().min(1),
1705
+ documentId: z17.string().min(1),
1706
+ sourceSpanIds: z17.array(z17.string().min(1)),
1707
+ text: z17.string(),
1708
+ textHash: z17.string().min(1),
1709
+ pageStart: z17.number().int().positive().optional(),
1710
+ pageEnd: z17.number().int().positive().optional(),
1711
+ metadata: z17.record(z17.string(), z17.string()).default({})
1712
+ });
1713
+ var DocumentSourceNodeKindSchema = z17.enum([
1714
+ "document",
1715
+ "page_group",
1716
+ "page",
1717
+ "form",
1718
+ "endorsement",
1719
+ "section",
1720
+ "schedule",
1721
+ "clause",
1722
+ "table",
1723
+ "table_row",
1724
+ "table_cell",
1725
+ "text"
1726
+ ]);
1727
+ var DocumentSourceNodeSchema = z17.object({
1728
+ id: z17.string().min(1),
1729
+ documentId: z17.string().min(1),
1730
+ parentId: z17.string().optional(),
1731
+ kind: DocumentSourceNodeKindSchema,
1632
1732
  title: z17.string(),
1633
- sectionNumber: z17.string().optional(),
1634
- pageStart: z17.number(),
1635
- pageEnd: z17.number().optional(),
1636
- type: z17.string(),
1637
- coverageType: z17.string().optional(),
1638
- excerpt: z17.string().optional(),
1639
- content: z17.string().optional(),
1640
- subsections: z17.array(SubsectionSchema).optional(),
1641
- recordId: z17.string().optional(),
1642
- documentNodeId: z17.string().optional(),
1643
- sourceSpanIds: z17.array(z17.string()).optional(),
1644
- sourceTextHash: z17.string().optional()
1645
- });
1646
- var SubjectivitySchema = z17.object({
1647
1733
  description: z17.string(),
1648
- category: z17.string().optional()
1734
+ textExcerpt: z17.string().optional(),
1735
+ sourceSpanIds: z17.array(z17.string().min(1)),
1736
+ pageStart: z17.number().int().positive().optional(),
1737
+ pageEnd: z17.number().int().positive().optional(),
1738
+ bbox: z17.array(SourceSpanBBoxSchema).optional(),
1739
+ order: z17.number().int().nonnegative(),
1740
+ path: z17.string(),
1741
+ metadata: z17.record(z17.string(), z17.unknown()).optional()
1742
+ });
1743
+ var SourceBackedValueSchema = z17.object({
1744
+ value: z17.string(),
1745
+ normalizedValue: z17.string().optional(),
1746
+ confidence: z17.enum(["low", "medium", "high"]).default("medium"),
1747
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1748
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1749
+ });
1750
+ var OperationalAddressSchema = z17.object({
1751
+ street1: z17.string().optional(),
1752
+ street2: z17.string().optional(),
1753
+ city: z17.string().optional(),
1754
+ state: z17.string().optional(),
1755
+ zip: z17.string().optional(),
1756
+ country: z17.string().optional(),
1757
+ formatted: z17.string().optional()
1758
+ });
1759
+ var OperationalDeclarationFactSchema = z17.object({
1760
+ field: z17.enum([
1761
+ "namedInsured",
1762
+ "mailingAddress",
1763
+ "dba",
1764
+ "entityType",
1765
+ "taxId",
1766
+ "additionalNamedInsured",
1767
+ "policyNumber",
1768
+ "insurer",
1769
+ "broker",
1770
+ "effectiveDate",
1771
+ "expirationDate",
1772
+ "premium",
1773
+ "other"
1774
+ ]),
1775
+ label: z17.string().optional(),
1776
+ value: z17.string(),
1777
+ normalizedValue: z17.string().optional(),
1778
+ valueKind: z17.enum(["string", "number", "date", "money", "address", "list", "unknown"]).default("string"),
1779
+ address: OperationalAddressSchema.optional(),
1780
+ confidence: z17.enum(["low", "medium", "high"]).default("medium"),
1781
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1782
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1649
1783
  });
1650
- var UnderwritingConditionSchema = z17.object({
1651
- description: z17.string()
1784
+ var OperationalCoverageTermSchema = z17.object({
1785
+ kind: z17.enum([
1786
+ "each_claim_limit",
1787
+ "each_occurrence_limit",
1788
+ "each_loss_limit",
1789
+ "aggregate_limit",
1790
+ "sublimit",
1791
+ "retention",
1792
+ "deductible",
1793
+ "retroactive_date",
1794
+ "premium",
1795
+ "other"
1796
+ ]).default("other"),
1797
+ label: z17.string(),
1798
+ value: z17.string(),
1799
+ amount: z17.number().optional(),
1800
+ appliesTo: z17.string().optional(),
1801
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1802
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1652
1803
  });
1653
- var PremiumLineSchema = z17.object({
1804
+ var OperationalCoverageLineSchema = z17.object({
1805
+ name: z17.string(),
1806
+ lineOfBusiness: AcordLobCodeSchema.optional(),
1807
+ coverageCode: z17.string().optional(),
1808
+ limit: z17.string().optional(),
1809
+ deductible: z17.string().optional(),
1810
+ premium: z17.string().optional(),
1811
+ retroactiveDate: z17.string().optional(),
1812
+ formNumber: z17.string().optional(),
1813
+ sectionRef: z17.string().optional(),
1814
+ endorsementNumber: z17.string().optional(),
1815
+ limits: z17.array(OperationalCoverageTermSchema).default([]),
1816
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1817
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1818
+ });
1819
+ var OperationalCoverageScheduleValueSchema = z17.object({
1820
+ label: z17.string(),
1821
+ value: z17.string()
1822
+ });
1823
+ var OperationalCoverageScheduleItemSchema = z17.object({
1824
+ label: z17.string(),
1825
+ description: z17.string().optional(),
1826
+ values: z17.array(OperationalCoverageScheduleValueSchema).default([]),
1827
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1828
+ });
1829
+ var OperationalCoverageScheduleSchema = z17.object({
1830
+ name: z17.string(),
1831
+ kind: z17.enum(["vehicle", "property", "location", "other"]),
1832
+ description: z17.string().optional(),
1833
+ items: z17.array(OperationalCoverageScheduleItemSchema).default([]),
1834
+ sourceSpanIds: z17.array(z17.string().min(1)).default([]),
1835
+ pageStart: z17.number().int().positive().optional(),
1836
+ pageEnd: z17.number().int().positive().optional()
1837
+ });
1838
+ var OperationalPremiumLineSchema = z17.object({
1654
1839
  line: z17.string(),
1655
1840
  amount: z17.string(),
1656
1841
  amountValue: z17.number().optional(),
1657
- documentNodeId: z17.string().optional(),
1658
- sourceSpanIds: z17.array(z17.string()).optional(),
1659
- sourceTextHash: z17.string().optional()
1842
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1843
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1660
1844
  });
1661
- var AuxiliaryFactSchema = z17.object({
1662
- key: z17.string(),
1663
- value: z17.string(),
1664
- subject: z17.string().optional(),
1665
- context: z17.string().optional(),
1666
- documentNodeId: z17.string().optional(),
1667
- sourceSpanIds: z17.array(z17.string()).optional(),
1668
- sourceTextHash: z17.string().optional()
1669
- });
1670
- var DefinitionSchema = z17.object({
1671
- term: z17.string(),
1672
- definition: z17.string(),
1673
- pageNumber: z17.number().optional(),
1674
- formNumber: z17.string().optional(),
1675
- formTitle: z17.string().optional(),
1676
- sectionRef: z17.string().optional(),
1677
- originalContent: z17.string().optional(),
1678
- recordId: z17.string().optional(),
1679
- documentNodeId: z17.string().optional(),
1680
- sourceSpanIds: z17.array(z17.string()).optional(),
1681
- sourceTextHash: z17.string().optional()
1682
- });
1683
- var CoveredReasonSchema = z17.object({
1684
- coverageName: z17.string(),
1685
- reasonNumber: z17.string().optional(),
1686
- title: z17.string().optional(),
1687
- content: z17.string(),
1688
- conditions: z17.array(z17.string()).optional(),
1689
- exceptions: z17.array(z17.string()).optional(),
1690
- appliesTo: z17.array(z17.string()).optional(),
1691
- pageNumber: z17.number().optional(),
1692
- formNumber: z17.string().optional(),
1693
- formTitle: z17.string().optional(),
1694
- sectionRef: z17.string().optional(),
1695
- originalContent: z17.string().optional(),
1696
- recordId: z17.string().optional(),
1697
- documentNodeId: z17.string().optional(),
1698
- sourceSpanIds: z17.array(z17.string()).optional(),
1699
- sourceTextHash: z17.string().optional()
1700
- });
1701
- var DocumentTableOfContentsEntrySchema = z17.object({
1702
- title: z17.string(),
1703
- level: z17.number().int().positive().optional(),
1704
- pageStart: z17.number().optional(),
1705
- pageEnd: z17.number().optional(),
1706
- documentNodeId: z17.string().optional(),
1707
- sourceSpanIds: z17.array(z17.string()).optional()
1708
- });
1709
- var DocumentPageMapEntrySchema = z17.object({
1710
- page: z17.number().int().positive(),
1711
- label: z17.string().optional(),
1712
- formNumber: z17.string().optional(),
1713
- formTitle: z17.string().optional(),
1714
- sectionTitle: z17.string().optional(),
1715
- extractorNames: z17.array(z17.string()).optional(),
1716
- sourceSpanIds: z17.array(z17.string()).optional()
1845
+ var OperationalTaxFeeItemSchema = z17.object({
1846
+ name: z17.string(),
1847
+ amount: z17.string(),
1848
+ amountValue: z17.number().optional(),
1849
+ type: z17.string().optional(),
1850
+ description: z17.string().optional(),
1851
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1852
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1853
+ });
1854
+ var OperationalPartySchema = z17.object({
1855
+ role: z17.string(),
1856
+ name: z17.string(),
1857
+ address: OperationalAddressSchema.optional(),
1858
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1859
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1717
1860
  });
1718
- var DocumentAgentGuidanceSchema = z17.object({
1861
+ var OperationalEndorsementSupportSchema = z17.object({
1719
1862
  kind: z17.string(),
1720
- title: z17.string(),
1721
- detail: z17.string(),
1722
- sourceSpanIds: z17.array(z17.string()).optional()
1723
- });
1724
- var DocumentMetadataSchema = z17.object({
1725
- sourceTreeVersion: z17.string().optional(),
1726
- sourceTreeCanonical: z17.boolean().optional(),
1727
- formInventory: z17.array(FormReferenceSchema).optional(),
1728
- tableOfContents: z17.array(DocumentTableOfContentsEntrySchema).optional(),
1729
- pageMap: z17.array(DocumentPageMapEntrySchema).optional(),
1730
- agentGuidance: z17.array(DocumentAgentGuidanceSchema).optional()
1731
- });
1732
- var DocumentNodeSchema = z17.lazy(
1733
- () => z17.object({
1734
- id: z17.string(),
1735
- title: z17.string(),
1736
- originalTitle: z17.string().optional(),
1737
- type: z17.string().optional(),
1738
- label: z17.string().optional(),
1739
- level: z17.number().int().positive().optional(),
1740
- sectionNumber: z17.string().optional(),
1741
- pageStart: z17.number().optional(),
1742
- pageEnd: z17.number().optional(),
1743
- formNumber: z17.string().optional(),
1744
- formTitle: z17.string().optional(),
1745
- excerpt: z17.string().optional(),
1746
- content: z17.string().optional(),
1747
- interpretationLabels: z17.array(z17.string()).optional(),
1748
- sourceSpanIds: z17.array(z17.string()).optional(),
1749
- sourceTextHash: z17.string().optional(),
1750
- children: z17.array(DocumentNodeSchema).optional()
1863
+ status: z17.enum(["supported", "excluded", "requires_review"]),
1864
+ summary: z17.string(),
1865
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1866
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1867
+ });
1868
+ function legacyOperationalProfileInput(value) {
1869
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
1870
+ const record = value;
1871
+ if ("linesOfBusiness" in record) return value;
1872
+ if (!("policyTypes" in record)) return value;
1873
+ return {
1874
+ ...record,
1875
+ linesOfBusiness: record.policyTypes
1876
+ };
1877
+ }
1878
+ var OperationalLinesOfBusinessSchema = z17.preprocess(
1879
+ (value) => Array.isArray(value) ? toLobCodes(value.filter((item) => typeof item === "string")) : void 0,
1880
+ z17.array(AcordLobCodeSchema).default(["UN"])
1881
+ );
1882
+ var PolicyOperationalProfileSchema = z17.preprocess(
1883
+ legacyOperationalProfileInput,
1884
+ z17.object({
1885
+ documentType: z17.enum(["policy", "quote"]).default("policy"),
1886
+ linesOfBusiness: OperationalLinesOfBusinessSchema,
1887
+ policyNumber: SourceBackedValueSchema.optional(),
1888
+ namedInsured: SourceBackedValueSchema.optional(),
1889
+ insurer: SourceBackedValueSchema.optional(),
1890
+ broker: SourceBackedValueSchema.optional(),
1891
+ effectiveDate: SourceBackedValueSchema.optional(),
1892
+ expirationDate: SourceBackedValueSchema.optional(),
1893
+ retroactiveDate: SourceBackedValueSchema.optional(),
1894
+ premium: SourceBackedValueSchema.optional(),
1895
+ operationsDescription: SourceBackedValueSchema.optional(),
1896
+ declarationFacts: z17.array(OperationalDeclarationFactSchema).default([]),
1897
+ coverages: z17.array(OperationalCoverageLineSchema).default([]),
1898
+ coverageSchedules: z17.array(OperationalCoverageScheduleSchema).optional(),
1899
+ premiumBreakdown: z17.array(OperationalPremiumLineSchema).optional(),
1900
+ taxesAndFees: z17.array(OperationalTaxFeeItemSchema).optional(),
1901
+ totalCost: SourceBackedValueSchema.optional(),
1902
+ parties: z17.array(OperationalPartySchema).default([]),
1903
+ endorsementSupport: z17.array(OperationalEndorsementSupportSchema).default([]),
1904
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1905
+ sourceSpanIds: z17.array(z17.string().min(1)).default([]),
1906
+ warnings: z17.array(z17.string()).default([])
1907
+ })
1908
+ );
1909
+
1910
+ // src/schemas/document.ts
1911
+ var SubsectionSchema = z18.object({
1912
+ title: z18.string(),
1913
+ sectionNumber: z18.string().optional(),
1914
+ pageNumber: z18.number().optional(),
1915
+ excerpt: z18.string().optional(),
1916
+ content: z18.string().optional(),
1917
+ documentNodeId: z18.string().optional(),
1918
+ sourceSpanIds: z18.array(z18.string()).optional(),
1919
+ sourceTextHash: z18.string().optional()
1920
+ });
1921
+ var SectionSchema = z18.object({
1922
+ title: z18.string(),
1923
+ sectionNumber: z18.string().optional(),
1924
+ pageStart: z18.number(),
1925
+ pageEnd: z18.number().optional(),
1926
+ type: z18.string(),
1927
+ coverageType: z18.string().optional(),
1928
+ excerpt: z18.string().optional(),
1929
+ content: z18.string().optional(),
1930
+ subsections: z18.array(SubsectionSchema).optional(),
1931
+ recordId: z18.string().optional(),
1932
+ documentNodeId: z18.string().optional(),
1933
+ sourceSpanIds: z18.array(z18.string()).optional(),
1934
+ sourceTextHash: z18.string().optional()
1935
+ });
1936
+ var SubjectivitySchema = z18.object({
1937
+ description: z18.string(),
1938
+ category: z18.string().optional()
1939
+ });
1940
+ var UnderwritingConditionSchema = z18.object({
1941
+ description: z18.string()
1942
+ });
1943
+ var PremiumLineSchema = z18.object({
1944
+ line: z18.string(),
1945
+ amount: z18.string(),
1946
+ amountValue: z18.number().optional(),
1947
+ documentNodeId: z18.string().optional(),
1948
+ sourceSpanIds: z18.array(z18.string()).optional(),
1949
+ sourceTextHash: z18.string().optional()
1950
+ });
1951
+ var AuxiliaryFactSchema = z18.object({
1952
+ key: z18.string(),
1953
+ value: z18.string(),
1954
+ subject: z18.string().optional(),
1955
+ context: z18.string().optional(),
1956
+ documentNodeId: z18.string().optional(),
1957
+ sourceSpanIds: z18.array(z18.string()).optional(),
1958
+ sourceTextHash: z18.string().optional()
1959
+ });
1960
+ var DefinitionSchema = z18.object({
1961
+ term: z18.string(),
1962
+ definition: z18.string(),
1963
+ pageNumber: z18.number().optional(),
1964
+ formNumber: z18.string().optional(),
1965
+ formTitle: z18.string().optional(),
1966
+ sectionRef: z18.string().optional(),
1967
+ originalContent: z18.string().optional(),
1968
+ recordId: z18.string().optional(),
1969
+ documentNodeId: z18.string().optional(),
1970
+ sourceSpanIds: z18.array(z18.string()).optional(),
1971
+ sourceTextHash: z18.string().optional()
1972
+ });
1973
+ var CoveredReasonSchema = z18.object({
1974
+ coverageName: z18.string(),
1975
+ reasonNumber: z18.string().optional(),
1976
+ title: z18.string().optional(),
1977
+ content: z18.string(),
1978
+ conditions: z18.array(z18.string()).optional(),
1979
+ exceptions: z18.array(z18.string()).optional(),
1980
+ appliesTo: z18.array(z18.string()).optional(),
1981
+ pageNumber: z18.number().optional(),
1982
+ formNumber: z18.string().optional(),
1983
+ formTitle: z18.string().optional(),
1984
+ sectionRef: z18.string().optional(),
1985
+ originalContent: z18.string().optional(),
1986
+ recordId: z18.string().optional(),
1987
+ documentNodeId: z18.string().optional(),
1988
+ sourceSpanIds: z18.array(z18.string()).optional(),
1989
+ sourceTextHash: z18.string().optional()
1990
+ });
1991
+ var DocumentTableOfContentsEntrySchema = z18.object({
1992
+ title: z18.string(),
1993
+ level: z18.number().int().positive().optional(),
1994
+ pageStart: z18.number().optional(),
1995
+ pageEnd: z18.number().optional(),
1996
+ documentNodeId: z18.string().optional(),
1997
+ sourceSpanIds: z18.array(z18.string()).optional()
1998
+ });
1999
+ var DocumentPageMapEntrySchema = z18.object({
2000
+ page: z18.number().int().positive(),
2001
+ label: z18.string().optional(),
2002
+ formNumber: z18.string().optional(),
2003
+ formTitle: z18.string().optional(),
2004
+ sectionTitle: z18.string().optional(),
2005
+ extractorNames: z18.array(z18.string()).optional(),
2006
+ sourceSpanIds: z18.array(z18.string()).optional()
2007
+ });
2008
+ var DocumentAgentGuidanceSchema = z18.object({
2009
+ kind: z18.string(),
2010
+ title: z18.string(),
2011
+ detail: z18.string(),
2012
+ sourceSpanIds: z18.array(z18.string()).optional()
2013
+ });
2014
+ var DocumentMetadataSchema = z18.object({
2015
+ sourceTreeVersion: z18.string().optional(),
2016
+ sourceTreeCanonical: z18.boolean().optional(),
2017
+ formInventory: z18.array(FormReferenceSchema).optional(),
2018
+ tableOfContents: z18.array(DocumentTableOfContentsEntrySchema).optional(),
2019
+ pageMap: z18.array(DocumentPageMapEntrySchema).optional(),
2020
+ agentGuidance: z18.array(DocumentAgentGuidanceSchema).optional()
2021
+ });
2022
+ var DocumentNodeSchema = z18.lazy(
2023
+ () => z18.object({
2024
+ id: z18.string(),
2025
+ title: z18.string(),
2026
+ originalTitle: z18.string().optional(),
2027
+ type: z18.string().optional(),
2028
+ label: z18.string().optional(),
2029
+ level: z18.number().int().positive().optional(),
2030
+ sectionNumber: z18.string().optional(),
2031
+ pageStart: z18.number().optional(),
2032
+ pageEnd: z18.number().optional(),
2033
+ formNumber: z18.string().optional(),
2034
+ formTitle: z18.string().optional(),
2035
+ excerpt: z18.string().optional(),
2036
+ content: z18.string().optional(),
2037
+ interpretationLabels: z18.array(z18.string()).optional(),
2038
+ sourceSpanIds: z18.array(z18.string()).optional(),
2039
+ sourceTextHash: z18.string().optional(),
2040
+ children: z18.array(DocumentNodeSchema).optional()
1751
2041
  })
1752
2042
  );
1753
2043
  var BaseDocumentFields = {
1754
- id: z17.string(),
1755
- carrier: z17.string(),
1756
- security: z17.string().optional(),
1757
- insuredName: z17.string(),
1758
- premium: z17.string().optional(),
1759
- premiumAmount: z17.number().optional(),
1760
- summary: z17.string().optional(),
1761
- linesOfBusiness: z17.array(z17.string()).optional(),
1762
- coverages: z17.array(CoverageSchema),
2044
+ id: z18.string(),
2045
+ carrier: z18.string(),
2046
+ security: z18.string().optional(),
2047
+ insuredName: z18.string(),
2048
+ premium: z18.string().optional(),
2049
+ premiumAmount: z18.number().optional(),
2050
+ premiumBreakdown: z18.array(PremiumLineSchema).optional(),
2051
+ summary: z18.string().optional(),
2052
+ linesOfBusiness: z18.array(z18.string()).optional(),
2053
+ coverages: z18.array(CoverageSchema),
1763
2054
  documentMetadata: DocumentMetadataSchema,
1764
- documentOutline: z17.array(DocumentNodeSchema),
1765
- sections: z17.array(SectionSchema).optional(),
1766
- definitions: z17.array(DefinitionSchema).optional(),
1767
- coveredReasons: z17.array(CoveredReasonSchema).optional(),
2055
+ documentOutline: z18.array(DocumentNodeSchema),
2056
+ sections: z18.array(SectionSchema).optional(),
2057
+ definitions: z18.array(DefinitionSchema).optional(),
2058
+ coveredReasons: z18.array(CoveredReasonSchema).optional(),
1768
2059
  // Enriched fields (v1.2+)
1769
- carrierLegalName: z17.string().optional(),
1770
- carrierNaicNumber: z17.string().optional(),
1771
- carrierAmBestRating: z17.string().optional(),
1772
- carrierAdmittedStatus: z17.string().optional(),
1773
- mga: z17.string().optional(),
1774
- underwriter: z17.string().optional(),
1775
- brokerAgency: z17.string().optional(),
1776
- brokerContactName: z17.string().optional(),
1777
- brokerLicenseNumber: z17.string().optional(),
1778
- priorPolicyNumber: z17.string().optional(),
1779
- programName: z17.string().optional(),
1780
- isRenewal: z17.boolean().optional(),
1781
- isPackage: z17.boolean().optional(),
1782
- insuredDba: z17.string().optional(),
2060
+ carrierLegalName: z18.string().optional(),
2061
+ carrierNaicNumber: z18.string().optional(),
2062
+ carrierAmBestRating: z18.string().optional(),
2063
+ carrierAdmittedStatus: z18.string().optional(),
2064
+ mga: z18.string().optional(),
2065
+ underwriter: z18.string().optional(),
2066
+ brokerAgency: z18.string().optional(),
2067
+ brokerContactName: z18.string().optional(),
2068
+ brokerLicenseNumber: z18.string().optional(),
2069
+ priorPolicyNumber: z18.string().optional(),
2070
+ programName: z18.string().optional(),
2071
+ isRenewal: z18.boolean().optional(),
2072
+ isPackage: z18.boolean().optional(),
2073
+ insuredDba: z18.string().optional(),
1783
2074
  insuredAddress: SourceBackedAddressSchema.optional(),
1784
2075
  insuredEntityType: EntityTypeSchema.optional(),
1785
- additionalNamedInsureds: z17.array(NamedInsuredSchema).optional(),
1786
- insuredSicCode: z17.string().optional(),
1787
- insuredNaicsCode: z17.string().optional(),
1788
- insuredFein: z17.string().optional(),
1789
- enrichedCoverages: z17.array(EnrichedCoverageSchema).optional(),
1790
- endorsements: z17.array(EndorsementSchema).optional(),
1791
- exclusions: z17.array(ExclusionSchema).optional(),
1792
- conditions: z17.array(PolicyConditionSchema).optional(),
2076
+ additionalNamedInsureds: z18.array(NamedInsuredSchema).optional(),
2077
+ insuredSicCode: z18.string().optional(),
2078
+ insuredNaicsCode: z18.string().optional(),
2079
+ insuredFein: z18.string().optional(),
2080
+ enrichedCoverages: z18.array(EnrichedCoverageSchema).optional(),
2081
+ endorsements: z18.array(EndorsementSchema).optional(),
2082
+ exclusions: z18.array(ExclusionSchema).optional(),
2083
+ conditions: z18.array(PolicyConditionSchema).optional(),
1793
2084
  limits: LimitScheduleSchema.optional(),
1794
2085
  deductibles: DeductibleScheduleSchema.optional(),
1795
- locations: z17.array(InsuredLocationSchema).optional(),
1796
- vehicles: z17.array(InsuredVehicleSchema).optional(),
1797
- classifications: z17.array(ClassificationCodeSchema).optional(),
1798
- formInventory: z17.array(FormReferenceSchema).optional(),
2086
+ locations: z18.array(InsuredLocationSchema).optional(),
2087
+ vehicles: z18.array(InsuredVehicleSchema).optional(),
2088
+ classifications: z18.array(ClassificationCodeSchema).optional(),
2089
+ coverageSchedules: z18.array(OperationalCoverageScheduleSchema).optional(),
2090
+ formInventory: z18.array(FormReferenceSchema).optional(),
1799
2091
  declarations: DeclarationsSchema.optional(),
1800
2092
  coverageForm: CoverageFormSchema.optional(),
1801
- retroactiveDate: z17.string().optional(),
2093
+ retroactiveDate: z18.string().optional(),
1802
2094
  extendedReportingPeriod: ExtendedReportingPeriodSchema.optional(),
1803
2095
  insurer: InsurerInfoSchema.optional(),
1804
2096
  producer: ProducerInfoSchema.optional(),
1805
- claimsContacts: z17.array(ContactSchema).optional(),
1806
- regulatoryContacts: z17.array(ContactSchema).optional(),
1807
- thirdPartyAdministrators: z17.array(ContactSchema).optional(),
1808
- additionalInsureds: z17.array(EndorsementPartySchema).optional(),
1809
- lossPayees: z17.array(EndorsementPartySchema).optional(),
1810
- mortgageHolders: z17.array(EndorsementPartySchema).optional(),
1811
- taxesAndFees: z17.array(TaxFeeItemSchema).optional(),
1812
- totalCost: z17.string().optional(),
1813
- totalCostAmount: z17.number().optional(),
1814
- minimumPremium: z17.string().optional(),
1815
- minimumPremiumAmount: z17.number().optional(),
1816
- depositPremium: z17.string().optional(),
1817
- depositPremiumAmount: z17.number().optional(),
2097
+ claimsContacts: z18.array(ContactSchema).optional(),
2098
+ regulatoryContacts: z18.array(ContactSchema).optional(),
2099
+ thirdPartyAdministrators: z18.array(ContactSchema).optional(),
2100
+ additionalInsureds: z18.array(EndorsementPartySchema).optional(),
2101
+ lossPayees: z18.array(EndorsementPartySchema).optional(),
2102
+ mortgageHolders: z18.array(EndorsementPartySchema).optional(),
2103
+ taxesAndFees: z18.array(TaxFeeItemSchema).optional(),
2104
+ totalCost: z18.string().optional(),
2105
+ totalCostAmount: z18.number().optional(),
2106
+ minimumPremium: z18.string().optional(),
2107
+ minimumPremiumAmount: z18.number().optional(),
2108
+ depositPremium: z18.string().optional(),
2109
+ depositPremiumAmount: z18.number().optional(),
1818
2110
  paymentPlan: PaymentPlanSchema.optional(),
1819
2111
  auditType: AuditTypeSchema.optional(),
1820
- ratingBasis: z17.array(RatingBasisSchema).optional(),
1821
- premiumByLocation: z17.array(LocationPremiumSchema).optional(),
2112
+ ratingBasis: z18.array(RatingBasisSchema).optional(),
2113
+ premiumByLocation: z18.array(LocationPremiumSchema).optional(),
1822
2114
  lossSummary: LossSummarySchema.optional(),
1823
- individualClaims: z17.array(ClaimRecordSchema).optional(),
2115
+ individualClaims: z18.array(ClaimRecordSchema).optional(),
1824
2116
  experienceMod: ExperienceModSchema.optional(),
1825
- cancellationNoticeDays: z17.number().optional(),
1826
- nonrenewalNoticeDays: z17.number().optional(),
1827
- supplementaryFacts: z17.array(AuxiliaryFactSchema).optional()
2117
+ cancellationNoticeDays: z18.number().optional(),
2118
+ nonrenewalNoticeDays: z18.number().optional(),
2119
+ supplementaryFacts: z18.array(AuxiliaryFactSchema).optional()
1828
2120
  };
1829
- var PolicyDocumentSchema = z17.object({
2121
+ var PolicyDocumentSchema = z18.object({
1830
2122
  ...BaseDocumentFields,
1831
- type: z17.literal("policy"),
1832
- policyNumber: z17.string(),
1833
- effectiveDate: z17.string(),
1834
- expirationDate: z17.string().optional(),
2123
+ type: z18.literal("policy"),
2124
+ policyNumber: z18.string(),
2125
+ effectiveDate: z18.string(),
2126
+ expirationDate: z18.string().optional(),
1835
2127
  policyTermType: PolicyTermTypeSchema.optional(),
1836
- nextReviewDate: z17.string().optional(),
1837
- effectiveTime: z17.string().optional()
2128
+ nextReviewDate: z18.string().optional(),
2129
+ effectiveTime: z18.string().optional()
1838
2130
  });
1839
- var QuoteDocumentSchema = z17.object({
2131
+ var QuoteDocumentSchema = z18.object({
1840
2132
  ...BaseDocumentFields,
1841
- type: z17.literal("quote"),
1842
- quoteNumber: z17.string(),
1843
- proposedEffectiveDate: z17.string().optional(),
1844
- proposedExpirationDate: z17.string().optional(),
1845
- quoteExpirationDate: z17.string().optional(),
1846
- subjectivities: z17.array(SubjectivitySchema).optional(),
1847
- underwritingConditions: z17.array(UnderwritingConditionSchema).optional(),
1848
- premiumBreakdown: z17.array(PremiumLineSchema).optional(),
2133
+ type: z18.literal("quote"),
2134
+ quoteNumber: z18.string(),
2135
+ proposedEffectiveDate: z18.string().optional(),
2136
+ proposedExpirationDate: z18.string().optional(),
2137
+ quoteExpirationDate: z18.string().optional(),
2138
+ subjectivities: z18.array(SubjectivitySchema).optional(),
2139
+ underwritingConditions: z18.array(UnderwritingConditionSchema).optional(),
1849
2140
  // Enriched quote fields (v1.2+)
1850
- enrichedSubjectivities: z17.array(EnrichedSubjectivitySchema).optional(),
1851
- enrichedUnderwritingConditions: z17.array(EnrichedUnderwritingConditionSchema).optional(),
1852
- warrantyRequirements: z17.array(z17.string()).optional(),
1853
- lossControlRecommendations: z17.array(z17.string()).optional(),
2141
+ enrichedSubjectivities: z18.array(EnrichedSubjectivitySchema).optional(),
2142
+ enrichedUnderwritingConditions: z18.array(EnrichedUnderwritingConditionSchema).optional(),
2143
+ warrantyRequirements: z18.array(z18.string()).optional(),
2144
+ lossControlRecommendations: z18.array(z18.string()).optional(),
1854
2145
  bindingAuthority: BindingAuthoritySchema.optional()
1855
2146
  });
1856
- var InsuranceDocumentSchema = z17.discriminatedUnion("type", [
2147
+ var InsuranceDocumentSchema = z18.discriminatedUnion("type", [
1857
2148
  PolicyDocumentSchema,
1858
2149
  QuoteDocumentSchema
1859
2150
  ]);
1860
2151
 
1861
2152
  // src/schemas/platform.ts
1862
- import { z as z18 } from "zod";
1863
- var PlatformSchema = z18.enum(["email", "chat", "sms", "slack", "discord"]);
1864
- var CommunicationIntentSchema = z18.enum(["direct", "mediated", "observed"]);
2153
+ import { z as z19 } from "zod";
2154
+ var PlatformSchema = z19.enum(["email", "chat", "sms", "slack", "discord"]);
2155
+ var CommunicationIntentSchema = z19.enum(["direct", "mediated", "observed"]);
1865
2156
  var PLATFORM_CONFIGS = {
1866
2157
  email: {
1867
2158
  supportsMarkdown: false,
@@ -1894,65 +2185,65 @@ var PLATFORM_CONFIGS = {
1894
2185
  };
1895
2186
 
1896
2187
  // src/schemas/pce.ts
1897
- import { z as z20 } from "zod";
2188
+ import { z as z21 } from "zod";
1898
2189
 
1899
2190
  // src/case/index.ts
1900
- import { z as z19 } from "zod";
1901
- var CaseEvidenceSourceSchema = z19.object({
1902
- id: z19.string(),
1903
- label: z19.string().optional(),
1904
- documentId: z19.string().optional(),
1905
- page: z19.number().optional(),
1906
- fieldPath: z19.string().optional(),
1907
- text: z19.string().describe("Source text available for span validation and citation"),
1908
- metadata: z19.record(z19.string(), z19.string()).optional()
1909
- });
1910
- var CaseCitationSchema = z19.object({
1911
- sourceId: z19.string(),
1912
- quote: z19.string(),
1913
- page: z19.number().optional(),
1914
- fieldPath: z19.string().optional()
1915
- });
1916
- var ValidationIssueSeveritySchema = z19.enum(["info", "warning", "blocking"]);
1917
- var CaseValidationIssueSchema = z19.object({
1918
- code: z19.string(),
2191
+ import { z as z20 } from "zod";
2192
+ var CaseEvidenceSourceSchema = z20.object({
2193
+ id: z20.string(),
2194
+ label: z20.string().optional(),
2195
+ documentId: z20.string().optional(),
2196
+ page: z20.number().optional(),
2197
+ fieldPath: z20.string().optional(),
2198
+ text: z20.string().describe("Source text available for span validation and citation"),
2199
+ metadata: z20.record(z20.string(), z20.string()).optional()
2200
+ });
2201
+ var CaseCitationSchema = z20.object({
2202
+ sourceId: z20.string(),
2203
+ quote: z20.string(),
2204
+ page: z20.number().optional(),
2205
+ fieldPath: z20.string().optional()
2206
+ });
2207
+ var ValidationIssueSeveritySchema = z20.enum(["info", "warning", "blocking"]);
2208
+ var CaseValidationIssueSchema = z20.object({
2209
+ code: z20.string(),
1919
2210
  severity: ValidationIssueSeveritySchema,
1920
- message: z19.string(),
1921
- itemId: z19.string().optional(),
1922
- fieldPath: z19.string().optional(),
1923
- sourceId: z19.string().optional()
1924
- });
1925
- var MissingInfoQuestionSchema = z19.object({
1926
- id: z19.string(),
1927
- itemId: z19.string().optional(),
1928
- fieldPath: z19.string().optional(),
1929
- question: z19.string(),
1930
- reason: z19.string(),
1931
- answer: z19.string().optional()
1932
- });
1933
- var CasePacketArtifactKindSchema = z19.enum([
2211
+ message: z20.string(),
2212
+ itemId: z20.string().optional(),
2213
+ fieldPath: z20.string().optional(),
2214
+ sourceId: z20.string().optional()
2215
+ });
2216
+ var MissingInfoQuestionSchema = z20.object({
2217
+ id: z20.string(),
2218
+ itemId: z20.string().optional(),
2219
+ fieldPath: z20.string().optional(),
2220
+ question: z20.string(),
2221
+ reason: z20.string(),
2222
+ answer: z20.string().optional()
2223
+ });
2224
+ var CasePacketArtifactKindSchema = z20.enum([
1934
2225
  "underwriter_summary",
1935
2226
  "carrier_email",
1936
2227
  "missing_info_request",
1937
2228
  "json_packet",
1938
2229
  "validation_report"
1939
2230
  ]);
1940
- var CasePacketArtifactSchema = z19.object({
1941
- id: z19.string(),
2231
+ var CasePacketArtifactSchema = z20.object({
2232
+ id: z20.string(),
1942
2233
  kind: CasePacketArtifactKindSchema,
1943
- title: z19.string(),
1944
- content: z19.string(),
1945
- citations: z19.array(CaseCitationSchema).default([])
1946
- });
1947
- var CaseSubmissionPacketSchema = z19.object({
1948
- id: z19.string(),
1949
- caseId: z19.string(),
1950
- artifacts: z19.array(CasePacketArtifactSchema),
1951
- validationIssues: z19.array(CaseValidationIssueSchema),
1952
- missingInfoQuestions: z19.array(MissingInfoQuestionSchema),
1953
- createdAt: z19.number()
1954
- });
1955
- var CaseActionSchema = z19.enum([
2234
+ title: z20.string(),
2235
+ content: z20.string(),
2236
+ citations: z20.array(CaseCitationSchema).default([])
2237
+ });
2238
+ var CaseSubmissionPacketSchema = z20.object({
2239
+ id: z20.string(),
2240
+ caseId: z20.string(),
2241
+ artifacts: z20.array(CasePacketArtifactSchema),
2242
+ validationIssues: z20.array(CaseValidationIssueSchema),
2243
+ missingInfoQuestions: z20.array(MissingInfoQuestionSchema),
2244
+ createdAt: z20.number()
2245
+ });
2246
+ var CaseActionSchema = z20.enum([
1956
2247
  "inspect_attachments",
1957
2248
  "retrieve_policy_evidence",
1958
2249
  "retrieve_prior_applications",
@@ -1965,23 +2256,23 @@ var CaseActionSchema = z19.enum([
1965
2256
  "generate_packet",
1966
2257
  "answer_field_or_case_question"
1967
2258
  ]);
1968
- var AgenticExecutionModeSchema = z19.enum(["deterministic_tree", "market_eval", "hybrid"]);
1969
- var CaseProposalScoreSchema = z19.object({
1970
- grounding: z19.number().min(0).max(1),
1971
- completeness: z19.number().min(0).max(1),
1972
- consistency: z19.number().min(0).max(1),
1973
- determinism: z19.number().min(0).max(1),
1974
- risk: z19.number().min(0).max(1),
1975
- cost: z19.number().min(0).max(1)
1976
- });
1977
- var CaseProposalSchema = z19.object({
1978
- id: z19.string(),
1979
- sourceSpanIds: z19.array(z19.string()).default([]),
1980
- confidence: z19.number().min(0).max(1),
1981
- missingInfo: z19.array(z19.string()).default([]),
1982
- validationIssues: z19.array(CaseValidationIssueSchema).default([]),
1983
- estimatedRisk: z19.number().min(0).max(1).default(0.5),
1984
- estimatedCost: z19.number().min(0).max(1).default(0.5),
2259
+ var AgenticExecutionModeSchema = z20.enum(["deterministic_tree", "market_eval", "hybrid"]);
2260
+ var CaseProposalScoreSchema = z20.object({
2261
+ grounding: z20.number().min(0).max(1),
2262
+ completeness: z20.number().min(0).max(1),
2263
+ consistency: z20.number().min(0).max(1),
2264
+ determinism: z20.number().min(0).max(1),
2265
+ risk: z20.number().min(0).max(1),
2266
+ cost: z20.number().min(0).max(1)
2267
+ });
2268
+ var CaseProposalSchema = z20.object({
2269
+ id: z20.string(),
2270
+ sourceSpanIds: z20.array(z20.string()).default([]),
2271
+ confidence: z20.number().min(0).max(1),
2272
+ missingInfo: z20.array(z20.string()).default([]),
2273
+ validationIssues: z20.array(CaseValidationIssueSchema).default([]),
2274
+ estimatedRisk: z20.number().min(0).max(1).default(0.5),
2275
+ estimatedCost: z20.number().min(0).max(1).default(0.5),
1985
2276
  score: CaseProposalScoreSchema.optional()
1986
2277
  });
1987
2278
  function stableCaseId(prefix, parts) {
@@ -2100,8 +2391,8 @@ function totalProposalScore(score) {
2100
2391
  }
2101
2392
 
2102
2393
  // src/schemas/pce.ts
2103
- var PolicyChangeActionSchema = z20.enum(["add", "remove", "update", "replace", "clarify"]);
2104
- var PolicyChangeKindSchema = z20.enum([
2394
+ var PolicyChangeActionSchema = z21.enum(["add", "remove", "update", "replace", "clarify"]);
2395
+ var PolicyChangeKindSchema = z21.enum([
2105
2396
  "named_insured_change",
2106
2397
  "additional_insured_change",
2107
2398
  "coverage_change",
@@ -2115,70 +2406,70 @@ var PolicyChangeKindSchema = z20.enum([
2115
2406
  "renewal_submission_update",
2116
2407
  "general_endorsement"
2117
2408
  ]);
2118
- var PolicyChangeConfidenceSchema = z20.enum(["high", "medium", "low"]);
2119
- var PolicyChangeStatusSchema = z20.enum(["draft", "needs_info", "ready", "blocked"]);
2120
- var PolicyChangeItemSchema = z20.object({
2121
- id: z20.string(),
2409
+ var PolicyChangeConfidenceSchema = z21.enum(["high", "medium", "low"]);
2410
+ var PolicyChangeStatusSchema = z21.enum(["draft", "needs_info", "ready", "blocked"]);
2411
+ var PolicyChangeItemSchema = z21.object({
2412
+ id: z21.string(),
2122
2413
  kind: PolicyChangeKindSchema.default("general_endorsement"),
2123
2414
  action: PolicyChangeActionSchema,
2124
- affectedPolicyId: z20.string().default("unknown"),
2125
- fieldPath: z20.string().describe("Stable policy field path or business field name"),
2126
- label: z20.string(),
2127
- beforeValue: z20.string().optional().describe("Existing policy value, when cited from policy evidence"),
2128
- afterValue: z20.string().optional().describe("Requested new value"),
2129
- requestedValue: z20.string().optional().describe("Alias for afterValue used by policy-change workflows"),
2130
- effectiveDate: z20.string().optional(),
2131
- reason: z20.string().optional(),
2132
- sourceIds: z20.array(z20.string()).default([]),
2133
- sourceSpanIds: z20.array(z20.string()).default([]),
2134
- userSourceSpanIds: z20.array(z20.string()).optional(),
2135
- citations: z20.array(CaseCitationSchema).default([]),
2415
+ affectedPolicyId: z21.string().default("unknown"),
2416
+ fieldPath: z21.string().describe("Stable policy field path or business field name"),
2417
+ label: z21.string(),
2418
+ beforeValue: z21.string().optional().describe("Existing policy value, when cited from policy evidence"),
2419
+ afterValue: z21.string().optional().describe("Requested new value"),
2420
+ requestedValue: z21.string().optional().describe("Alias for afterValue used by policy-change workflows"),
2421
+ effectiveDate: z21.string().optional(),
2422
+ reason: z21.string().optional(),
2423
+ sourceIds: z21.array(z21.string()).default([]),
2424
+ sourceSpanIds: z21.array(z21.string()).default([]),
2425
+ userSourceSpanIds: z21.array(z21.string()).optional(),
2426
+ citations: z21.array(CaseCitationSchema).default([]),
2136
2427
  confidence: PolicyChangeConfidenceSchema.default("medium"),
2137
- confidenceScore: z20.number().min(0).max(1).optional(),
2428
+ confidenceScore: z21.number().min(0).max(1).optional(),
2138
2429
  status: PolicyChangeStatusSchema.default("ready")
2139
2430
  });
2140
- var PceNormalizationResultSchema = z20.object({
2141
- summary: z20.string(),
2142
- items: z20.array(PolicyChangeItemSchema.omit({ id: true, status: true }).extend({
2143
- id: z20.string().optional(),
2431
+ var PceNormalizationResultSchema = z21.object({
2432
+ summary: z21.string(),
2433
+ items: z21.array(PolicyChangeItemSchema.omit({ id: true, status: true }).extend({
2434
+ id: z21.string().optional(),
2144
2435
  status: PolicyChangeStatusSchema.optional()
2145
2436
  })),
2146
- missingInfoQuestions: z20.array(MissingInfoQuestionSchema.omit({ id: true }).extend({
2147
- id: z20.string().optional()
2437
+ missingInfoQuestions: z21.array(MissingInfoQuestionSchema.omit({ id: true }).extend({
2438
+ id: z21.string().optional()
2148
2439
  })).default([])
2149
2440
  });
2150
- var PolicyChangeImpactSchema = z20.object({
2151
- itemId: z20.string(),
2152
- beforeValue: z20.string().optional(),
2153
- requestedValue: z20.string().optional(),
2154
- likelyEndorsementRequired: z20.boolean().default(true),
2155
- carrierApprovalLikelyRequired: z20.boolean().default(true),
2156
- affectedCoverageForms: z20.array(z20.string()).default([]),
2157
- sourceSpanIds: z20.array(z20.string()).default([])
2158
- });
2159
- var PceCaseStateSchema = z20.object({
2160
- id: z20.string(),
2161
- requestText: z20.string(),
2162
- summary: z20.string(),
2441
+ var PolicyChangeImpactSchema = z21.object({
2442
+ itemId: z21.string(),
2443
+ beforeValue: z21.string().optional(),
2444
+ requestedValue: z21.string().optional(),
2445
+ likelyEndorsementRequired: z21.boolean().default(true),
2446
+ carrierApprovalLikelyRequired: z21.boolean().default(true),
2447
+ affectedCoverageForms: z21.array(z21.string()).default([]),
2448
+ sourceSpanIds: z21.array(z21.string()).default([])
2449
+ });
2450
+ var PceCaseStateSchema = z21.object({
2451
+ id: z21.string(),
2452
+ requestText: z21.string(),
2453
+ summary: z21.string(),
2163
2454
  executionMode: AgenticExecutionModeSchema.default("deterministic_tree"),
2164
- items: z20.array(PolicyChangeItemSchema),
2165
- impacts: z20.array(PolicyChangeImpactSchema),
2166
- evidenceSources: z20.array(CaseEvidenceSourceSchema),
2167
- validationIssues: z20.array(CaseValidationIssueSchema),
2168
- missingInfoQuestions: z20.array(MissingInfoQuestionSchema),
2169
- createdAt: z20.number(),
2170
- updatedAt: z20.number()
2171
- });
2172
- var PolicyChangeRequestSchema = z20.object({
2173
- id: z20.string(),
2174
- text: z20.string(),
2455
+ items: z21.array(PolicyChangeItemSchema),
2456
+ impacts: z21.array(PolicyChangeImpactSchema),
2457
+ evidenceSources: z21.array(CaseEvidenceSourceSchema),
2458
+ validationIssues: z21.array(CaseValidationIssueSchema),
2459
+ missingInfoQuestions: z21.array(MissingInfoQuestionSchema),
2460
+ createdAt: z21.number(),
2461
+ updatedAt: z21.number()
2462
+ });
2463
+ var PolicyChangeRequestSchema = z21.object({
2464
+ id: z21.string(),
2465
+ text: z21.string(),
2175
2466
  executionMode: AgenticExecutionModeSchema.optional(),
2176
- userSourceSpanIds: z20.array(z20.string()).optional(),
2177
- createdAt: z20.number().optional()
2467
+ userSourceSpanIds: z21.array(z21.string()).optional(),
2468
+ createdAt: z21.number().optional()
2178
2469
  });
2179
2470
  var PceSubmissionPacketSchema = CaseSubmissionPacketSchema.extend({
2180
2471
  pceCase: PceCaseStateSchema,
2181
- artifacts: z20.array(CasePacketArtifactSchema)
2472
+ artifacts: z21.array(CasePacketArtifactSchema)
2182
2473
  });
2183
2474
 
2184
2475
  // src/schemas/context-keys.ts
@@ -2233,252 +2524,6 @@ var CONTEXT_KEY_MAP = [
2233
2524
  { extractedField: "declarations.breed", category: "pet_info", contextKey: "pet_breed", description: "Pet breed" }
2234
2525
  ];
2235
2526
 
2236
- // src/source/schemas.ts
2237
- import { z as z21 } from "zod";
2238
- var SourceSpanKindSchema = z21.enum([
2239
- "pdf_text",
2240
- "pdf_image",
2241
- "html",
2242
- "markdown",
2243
- "plain_text",
2244
- "structured_field"
2245
- ]);
2246
- var SourceSpanUnitSchema = z21.enum([
2247
- "page",
2248
- "section",
2249
- "table",
2250
- "table_row",
2251
- "table_cell",
2252
- "key_value",
2253
- "text"
2254
- ]);
2255
- var SourceKindSchema = z21.enum([
2256
- "policy_pdf",
2257
- "application_pdf",
2258
- "email",
2259
- "attachment",
2260
- "manual_note"
2261
- ]);
2262
- var SourceSpanBBoxSchema = z21.object({
2263
- page: z21.number().int().positive(),
2264
- x: z21.number(),
2265
- y: z21.number(),
2266
- width: z21.number(),
2267
- height: z21.number()
2268
- });
2269
- var SourceSpanLocationSchema = z21.object({
2270
- page: z21.number().int().positive().optional(),
2271
- startPage: z21.number().int().positive().optional(),
2272
- endPage: z21.number().int().positive().optional(),
2273
- charStart: z21.number().int().nonnegative().optional(),
2274
- charEnd: z21.number().int().nonnegative().optional(),
2275
- lineStart: z21.number().int().positive().optional(),
2276
- lineEnd: z21.number().int().positive().optional(),
2277
- fieldPath: z21.string().optional()
2278
- });
2279
- var SourceSpanTableLocationSchema = z21.object({
2280
- tableId: z21.string().optional(),
2281
- rowIndex: z21.number().int().nonnegative().optional(),
2282
- columnIndex: z21.number().int().nonnegative().optional(),
2283
- columnName: z21.string().optional(),
2284
- rowSpanId: z21.string().optional(),
2285
- tableSpanId: z21.string().optional(),
2286
- isHeader: z21.boolean().optional()
2287
- });
2288
- var SourceSpanSchema = z21.object({
2289
- id: z21.string().min(1),
2290
- documentId: z21.string().min(1),
2291
- sourceKind: SourceKindSchema.optional(),
2292
- chunkId: z21.string().optional(),
2293
- kind: SourceSpanKindSchema,
2294
- text: z21.string(),
2295
- hash: z21.string().min(1),
2296
- textHash: z21.string().optional(),
2297
- pageStart: z21.number().int().positive().optional(),
2298
- pageEnd: z21.number().int().positive().optional(),
2299
- sectionId: z21.string().optional(),
2300
- formNumber: z21.string().optional(),
2301
- sourceUnit: SourceSpanUnitSchema.optional(),
2302
- parentSpanId: z21.string().optional(),
2303
- table: SourceSpanTableLocationSchema.optional(),
2304
- bbox: z21.array(SourceSpanBBoxSchema).optional(),
2305
- location: SourceSpanLocationSchema.optional(),
2306
- metadata: z21.record(z21.string(), z21.string()).optional()
2307
- });
2308
- var SourceSpanRefSchema = z21.object({
2309
- sourceSpanId: z21.string().min(1),
2310
- documentId: z21.string().min(1).optional(),
2311
- chunkId: z21.string().optional(),
2312
- quote: z21.string().optional(),
2313
- hash: z21.string().optional(),
2314
- location: SourceSpanLocationSchema.optional()
2315
- });
2316
- var SourceChunkSchema = z21.object({
2317
- id: z21.string().min(1),
2318
- documentId: z21.string().min(1),
2319
- sourceSpanIds: z21.array(z21.string().min(1)),
2320
- text: z21.string(),
2321
- textHash: z21.string().min(1),
2322
- pageStart: z21.number().int().positive().optional(),
2323
- pageEnd: z21.number().int().positive().optional(),
2324
- metadata: z21.record(z21.string(), z21.string()).default({})
2325
- });
2326
- var DocumentSourceNodeKindSchema = z21.enum([
2327
- "document",
2328
- "page_group",
2329
- "page",
2330
- "form",
2331
- "endorsement",
2332
- "section",
2333
- "schedule",
2334
- "clause",
2335
- "table",
2336
- "table_row",
2337
- "table_cell",
2338
- "text"
2339
- ]);
2340
- var DocumentSourceNodeSchema = z21.object({
2341
- id: z21.string().min(1),
2342
- documentId: z21.string().min(1),
2343
- parentId: z21.string().optional(),
2344
- kind: DocumentSourceNodeKindSchema,
2345
- title: z21.string(),
2346
- description: z21.string(),
2347
- textExcerpt: z21.string().optional(),
2348
- sourceSpanIds: z21.array(z21.string().min(1)),
2349
- pageStart: z21.number().int().positive().optional(),
2350
- pageEnd: z21.number().int().positive().optional(),
2351
- bbox: z21.array(SourceSpanBBoxSchema).optional(),
2352
- order: z21.number().int().nonnegative(),
2353
- path: z21.string(),
2354
- metadata: z21.record(z21.string(), z21.unknown()).optional()
2355
- });
2356
- var SourceBackedValueSchema = z21.object({
2357
- value: z21.string(),
2358
- normalizedValue: z21.string().optional(),
2359
- confidence: z21.enum(["low", "medium", "high"]).default("medium"),
2360
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2361
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2362
- });
2363
- var OperationalAddressSchema = z21.object({
2364
- street1: z21.string().optional(),
2365
- street2: z21.string().optional(),
2366
- city: z21.string().optional(),
2367
- state: z21.string().optional(),
2368
- zip: z21.string().optional(),
2369
- country: z21.string().optional(),
2370
- formatted: z21.string().optional()
2371
- });
2372
- var OperationalDeclarationFactSchema = z21.object({
2373
- field: z21.enum([
2374
- "namedInsured",
2375
- "mailingAddress",
2376
- "dba",
2377
- "entityType",
2378
- "taxId",
2379
- "additionalNamedInsured",
2380
- "policyNumber",
2381
- "insurer",
2382
- "broker",
2383
- "effectiveDate",
2384
- "expirationDate",
2385
- "premium",
2386
- "other"
2387
- ]),
2388
- label: z21.string().optional(),
2389
- value: z21.string(),
2390
- normalizedValue: z21.string().optional(),
2391
- valueKind: z21.enum(["string", "number", "date", "money", "address", "list", "unknown"]).default("string"),
2392
- address: OperationalAddressSchema.optional(),
2393
- confidence: z21.enum(["low", "medium", "high"]).default("medium"),
2394
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2395
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2396
- });
2397
- var OperationalCoverageTermSchema = z21.object({
2398
- kind: z21.enum([
2399
- "each_claim_limit",
2400
- "each_occurrence_limit",
2401
- "each_loss_limit",
2402
- "aggregate_limit",
2403
- "sublimit",
2404
- "retention",
2405
- "deductible",
2406
- "retroactive_date",
2407
- "premium",
2408
- "other"
2409
- ]).default("other"),
2410
- label: z21.string(),
2411
- value: z21.string(),
2412
- amount: z21.number().optional(),
2413
- appliesTo: z21.string().optional(),
2414
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2415
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2416
- });
2417
- var OperationalCoverageLineSchema = z21.object({
2418
- name: z21.string(),
2419
- lineOfBusiness: AcordLobCodeSchema.optional(),
2420
- coverageCode: z21.string().optional(),
2421
- limit: z21.string().optional(),
2422
- deductible: z21.string().optional(),
2423
- premium: z21.string().optional(),
2424
- retroactiveDate: z21.string().optional(),
2425
- formNumber: z21.string().optional(),
2426
- sectionRef: z21.string().optional(),
2427
- endorsementNumber: z21.string().optional(),
2428
- limits: z21.array(OperationalCoverageTermSchema).default([]),
2429
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2430
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2431
- });
2432
- var OperationalPartySchema = z21.object({
2433
- role: z21.string(),
2434
- name: z21.string(),
2435
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2436
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2437
- });
2438
- var OperationalEndorsementSupportSchema = z21.object({
2439
- kind: z21.string(),
2440
- status: z21.enum(["supported", "excluded", "requires_review"]),
2441
- summary: z21.string(),
2442
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2443
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2444
- });
2445
- function legacyOperationalProfileInput(value) {
2446
- if (!value || typeof value !== "object" || Array.isArray(value)) return value;
2447
- const record = value;
2448
- if ("linesOfBusiness" in record) return value;
2449
- if (!("policyTypes" in record)) return value;
2450
- return {
2451
- ...record,
2452
- linesOfBusiness: record.policyTypes
2453
- };
2454
- }
2455
- var OperationalLinesOfBusinessSchema = z21.preprocess(
2456
- (value) => Array.isArray(value) ? toLobCodes(value.filter((item) => typeof item === "string")) : void 0,
2457
- z21.array(AcordLobCodeSchema).default(["UN"])
2458
- );
2459
- var PolicyOperationalProfileSchema = z21.preprocess(
2460
- legacyOperationalProfileInput,
2461
- z21.object({
2462
- documentType: z21.enum(["policy", "quote"]).default("policy"),
2463
- linesOfBusiness: OperationalLinesOfBusinessSchema,
2464
- policyNumber: SourceBackedValueSchema.optional(),
2465
- namedInsured: SourceBackedValueSchema.optional(),
2466
- insurer: SourceBackedValueSchema.optional(),
2467
- broker: SourceBackedValueSchema.optional(),
2468
- effectiveDate: SourceBackedValueSchema.optional(),
2469
- expirationDate: SourceBackedValueSchema.optional(),
2470
- retroactiveDate: SourceBackedValueSchema.optional(),
2471
- premium: SourceBackedValueSchema.optional(),
2472
- declarationFacts: z21.array(OperationalDeclarationFactSchema).default([]),
2473
- coverages: z21.array(OperationalCoverageLineSchema).default([]),
2474
- parties: z21.array(OperationalPartySchema).default([]),
2475
- endorsementSupport: z21.array(OperationalEndorsementSupportSchema).default([]),
2476
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2477
- sourceSpanIds: z21.array(z21.string().min(1)).default([]),
2478
- warnings: z21.array(z21.string()).default([])
2479
- })
2480
- );
2481
-
2482
2527
  // src/source/policy-types.ts
2483
2528
  var LOB_TEXT_PATTERNS = [
2484
2529
  { codes: ["CGL"], pattern: /\b(?:commercial\s+)?general\s+liability\b|\bcgl\b/i },
@@ -3829,7 +3874,7 @@ function shouldFailQualityGate(mode, status) {
3829
3874
  }
3830
3875
 
3831
3876
  // src/extraction/source-tree-extractor.ts
3832
- import { z as z23 } from "zod";
3877
+ import { z as z24 } from "zod";
3833
3878
 
3834
3879
  // src/source/operational-profile.ts
3835
3880
  function normalizeWhitespace4(value) {
@@ -3847,6 +3892,34 @@ function cleanCoverageLineOfBusiness(value) {
3847
3892
  function normalizedFactValue(value) {
3848
3893
  return value.toLowerCase().replace(/&/g, " and ").replace(/[.,#]/g, " ").replace(/\s+/g, " ").trim();
3849
3894
  }
3895
+ var OPERATIONAL_ADDRESS_FIELDS = [
3896
+ "street1",
3897
+ "street2",
3898
+ "city",
3899
+ "state",
3900
+ "zip",
3901
+ "country",
3902
+ "formatted"
3903
+ ];
3904
+ function normalizeOperationalAddress(value) {
3905
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
3906
+ const record = value;
3907
+ const address = Object.fromEntries(
3908
+ OPERATIONAL_ADDRESS_FIELDS.flatMap((field) => {
3909
+ const cleaned = typeof record[field] === "string" ? cleanValue(record[field]) : void 0;
3910
+ return cleaned ? [[field, cleaned]] : [];
3911
+ })
3912
+ );
3913
+ return Object.keys(address).length > 0 ? address : void 0;
3914
+ }
3915
+ function normalizeOperationalPartyRole(value) {
3916
+ const normalized = value.toLowerCase().replace(/[\s-]+/g, "_");
3917
+ if (normalized === "namedinsured" || normalized === "insured") return "named_insured";
3918
+ if (normalized === "managing_general_agent") return "mga";
3919
+ if (normalized === "managing_general_underwriter") return "mga";
3920
+ if (normalized === "third_party_administrator") return "administrator";
3921
+ return normalized;
3922
+ }
3850
3923
  var OPERATIONAL_COVERAGE_TERM_KINDS = /* @__PURE__ */ new Set([
3851
3924
  "each_claim_limit",
3852
3925
  "each_occurrence_limit",
@@ -3945,6 +4018,7 @@ function mergeOperationalProfile(base, candidate, validNodeIds, validSpanIds) {
3945
4018
  const expirationDate = mergeValue(base.expirationDate, candidate.expirationDate);
3946
4019
  const retroactiveDate = mergeValue(base.retroactiveDate, candidate.retroactiveDate);
3947
4020
  const premium = mergeValue(base.premium, candidate.premium);
4021
+ const operationsDescription = mergeValue(base.operationsDescription, candidate.operationsDescription);
3948
4022
  const candidateDeclarationFacts = Array.isArray(candidate.declarationFacts) ? candidate.declarationFacts.map(mergeDeclarationFact).filter((fact) => Boolean(fact)) : [];
3949
4023
  const declarationFacts = [
3950
4024
  ...base.declarationFacts,
@@ -3969,7 +4043,8 @@ function mergeOperationalProfile(base, candidate, validNodeIds, validSpanIds) {
3969
4043
  effectiveDate,
3970
4044
  expirationDate,
3971
4045
  retroactiveDate,
3972
- premium
4046
+ premium,
4047
+ operationsDescription
3973
4048
  ].filter((value) => Boolean(value));
3974
4049
  const coverages = base.coverages.length > 0 ? base.coverages : Array.isArray(candidate.coverages) ? candidate.coverages.map((coverage) => {
3975
4050
  const record = coverage;
@@ -4028,14 +4103,21 @@ function mergeOperationalProfile(base, candidate, validNodeIds, validSpanIds) {
4028
4103
  const record = party;
4029
4104
  const role = typeof record.role === "string" ? cleanValue(record.role) : void 0;
4030
4105
  const name = typeof record.name === "string" ? cleanValue(record.name) : void 0;
4106
+ const address = normalizeOperationalAddress(record.address);
4031
4107
  const sourceNodeIds2 = keepIds(record.sourceNodeIds, validNodeIds);
4032
4108
  const sourceSpanIds2 = keepIds(record.sourceSpanIds, validSpanIds);
4033
4109
  if (!role || !name || sourceNodeIds2.length === 0 && sourceSpanIds2.length === 0) return [];
4034
- return [{ role, name, sourceNodeIds: sourceNodeIds2, sourceSpanIds: sourceSpanIds2 }];
4110
+ return [{
4111
+ role: normalizeOperationalPartyRole(role),
4112
+ name,
4113
+ address,
4114
+ sourceNodeIds: sourceNodeIds2,
4115
+ sourceSpanIds: sourceSpanIds2
4116
+ }];
4035
4117
  }) : [];
4036
4118
  const parties = [
4037
- ...base.parties,
4038
4119
  ...candidateParties,
4120
+ ...base.parties,
4039
4121
  sourceBackedParty("named_insured", namedInsured),
4040
4122
  sourceBackedParty("insurer", insurer),
4041
4123
  sourceBackedParty("broker", broker)
@@ -4109,6 +4191,7 @@ function mergeOperationalProfile(base, candidate, validNodeIds, validSpanIds) {
4109
4191
  expirationDate,
4110
4192
  retroactiveDate,
4111
4193
  premium,
4194
+ operationsDescription,
4112
4195
  declarationFacts,
4113
4196
  coverages: annotatedCoverages,
4114
4197
  parties,
@@ -4553,96 +4636,812 @@ function applyCoverageCleanupDecision(coverage, decision, validNodeIds, validSpa
4553
4636
  if (value) next.premium = value;
4554
4637
  else delete next.premium;
4555
4638
  }
4556
- if (decision.retroactiveDate == null && termDecisionsTouch(coverage, termDecisions, isRetroactiveDateTerm)) {
4557
- const value = retroactiveDateFromTerms(next.limits);
4558
- if (value) next.retroactiveDate = value;
4559
- else delete next.retroactiveDate;
4639
+ if (decision.retroactiveDate == null && termDecisionsTouch(coverage, termDecisions, isRetroactiveDateTerm)) {
4640
+ const value = retroactiveDateFromTerms(next.limits);
4641
+ if (value) next.retroactiveDate = value;
4642
+ else delete next.retroactiveDate;
4643
+ }
4644
+ }
4645
+ const termLimit = primaryLimitFromTerms(next.limits);
4646
+ if (termLimit && shouldUseTermLimitDisplay(next.limit, termLimit)) {
4647
+ next.limit = termLimit;
4648
+ }
4649
+ next.sourceNodeIds = uniqueStrings([
4650
+ ...next.sourceNodeIds,
4651
+ ...next.limits.flatMap((term) => term.sourceNodeIds)
4652
+ ]);
4653
+ next.sourceSpanIds = uniqueStrings([
4654
+ ...next.sourceSpanIds,
4655
+ ...next.limits.flatMap((term) => term.sourceSpanIds)
4656
+ ]);
4657
+ return next.name ? next : coverage;
4658
+ }
4659
+ function sourceIdsFromOperationalProfile(profile) {
4660
+ const backedValues = [
4661
+ profile.policyNumber,
4662
+ profile.namedInsured,
4663
+ profile.insurer,
4664
+ profile.broker,
4665
+ profile.effectiveDate,
4666
+ profile.expirationDate,
4667
+ profile.retroactiveDate,
4668
+ profile.premium,
4669
+ profile.totalCost,
4670
+ profile.operationsDescription
4671
+ ].filter(Boolean);
4672
+ return {
4673
+ sourceNodeIds: uniqueStrings([
4674
+ ...backedValues.flatMap((value) => value?.sourceNodeIds ?? []),
4675
+ ...profile.coverages.flatMap((coverage) => coverage.sourceNodeIds),
4676
+ ...profile.coverages.flatMap((coverage) => coverage.limits.flatMap((term) => term.sourceNodeIds)),
4677
+ ...(profile.premiumBreakdown ?? []).flatMap((row) => row.sourceNodeIds),
4678
+ ...(profile.taxesAndFees ?? []).flatMap((row) => row.sourceNodeIds),
4679
+ ...profile.parties.flatMap((party) => party.sourceNodeIds),
4680
+ ...profile.endorsementSupport.flatMap((support) => support.sourceNodeIds)
4681
+ ]),
4682
+ sourceSpanIds: uniqueStrings([
4683
+ ...backedValues.flatMap((value) => value?.sourceSpanIds ?? []),
4684
+ ...profile.coverages.flatMap((coverage) => coverage.sourceSpanIds),
4685
+ ...profile.coverages.flatMap((coverage) => coverage.limits.flatMap((term) => term.sourceSpanIds)),
4686
+ ...(profile.coverageSchedules ?? []).flatMap((schedule) => [
4687
+ ...schedule.sourceSpanIds,
4688
+ ...schedule.items.flatMap((item) => item.sourceSpanIds)
4689
+ ]),
4690
+ ...(profile.premiumBreakdown ?? []).flatMap((row) => row.sourceSpanIds),
4691
+ ...(profile.taxesAndFees ?? []).flatMap((row) => row.sourceSpanIds),
4692
+ ...profile.parties.flatMap((party) => party.sourceSpanIds),
4693
+ ...profile.endorsementSupport.flatMap((support) => support.sourceSpanIds)
4694
+ ])
4695
+ };
4696
+ }
4697
+ function applyOperationalProfileCleanup(profile, cleanup, validNodeIds, validSpanIds) {
4698
+ const coverageDecisionByIndex = /* @__PURE__ */ new Map();
4699
+ for (const decision of cleanup.coverageDecisions) {
4700
+ if (decision.coverageIndex < profile.coverages.length) coverageDecisionByIndex.set(decision.coverageIndex, decision);
4701
+ }
4702
+ const coverages = profile.coverages.map(
4703
+ (coverage, index) => applyCoverageCleanupDecision(coverage, coverageDecisionByIndex.get(index), validNodeIds, validSpanIds)
4704
+ ).filter((coverage) => Boolean(coverage));
4705
+ const cleanupWarnings = cleanup.warnings.map((warning) => cleanProfileValue(warning)).filter((warning) => Boolean(warning));
4706
+ const nextProfile = {
4707
+ ...profile,
4708
+ coverages,
4709
+ warnings: uniqueStrings([
4710
+ ...profile.warnings,
4711
+ ...cleanupWarnings.map((warning) => `Operational profile cleanup warning: ${warning}`)
4712
+ ])
4713
+ };
4714
+ return PolicyOperationalProfileSchema.parse({
4715
+ ...nextProfile,
4716
+ ...sourceIdsFromOperationalProfile(nextProfile)
4717
+ });
4718
+ }
4719
+
4720
+ // src/extraction/coverage-recovery.ts
4721
+ import { z as z23 } from "zod";
4722
+ var COVERAGE_RECOVERY_VERSION = "coverage-recovery-v2";
4723
+ var DISCOVERY_PAGE_BATCH_SIZE = 32;
4724
+ var REGION_PAGE_BATCH_SIZE = 4;
4725
+ var RECOVERY_EVIDENCE_CHAR_LIMIT = 42e3;
4726
+ var RecoveryRegionSchema = z23.object({
4727
+ pageStart: z23.number().int().positive(),
4728
+ pageEnd: z23.number().int().positive(),
4729
+ reason: z23.string(),
4730
+ priorContext: z23.string().optional(),
4731
+ sourceNodeIds: z23.array(z23.string()).default([]),
4732
+ sourceSpanIds: z23.array(z23.string()).default([])
4733
+ });
4734
+ var RecoveryRegionDiscoverySchema = z23.object({
4735
+ regions: z23.array(RecoveryRegionSchema).default([]),
4736
+ warnings: z23.array(z23.string()).default([])
4737
+ });
4738
+ var CoverageRecoveryCandidateSchema = z23.object({
4739
+ coverages: z23.array(OperationalCoverageLineSchema).default([]),
4740
+ coverageSchedules: z23.array(OperationalCoverageScheduleSchema).default([]),
4741
+ premiumBreakdown: z23.array(OperationalPremiumLineSchema).default([]),
4742
+ taxesAndFees: z23.array(OperationalTaxFeeItemSchema).default([]),
4743
+ totalCost: SourceBackedValueSchema.optional(),
4744
+ warnings: z23.array(z23.string()).default([])
4745
+ });
4746
+ function cleanText(value) {
4747
+ if (typeof value !== "string") return void 0;
4748
+ const text = value.replace(/\s+/g, " ").trim();
4749
+ return text || void 0;
4750
+ }
4751
+ function uniqueStrings2(values) {
4752
+ return [...new Set(values.filter((value) => Boolean(value)))];
4753
+ }
4754
+ function spanPageStart(span) {
4755
+ return span.pageStart ?? span.location?.startPage ?? span.location?.page;
4756
+ }
4757
+ function spanPageEnd(span) {
4758
+ return span.pageEnd ?? span.location?.endPage ?? span.location?.page ?? spanPageStart(span);
4759
+ }
4760
+ function spanSourceUnit(span) {
4761
+ return span.sourceUnit ?? span.metadata?.sourceUnit;
4762
+ }
4763
+ function overlapsPageRange(value, pageStart2, pageEnd2) {
4764
+ const start = value.pageStart ?? value.pageEnd;
4765
+ const end = value.pageEnd ?? value.pageStart;
4766
+ return typeof start === "number" && typeof end === "number" && start <= pageEnd2 && end >= pageStart2;
4767
+ }
4768
+ function chunkValues(values, size) {
4769
+ const chunks = [];
4770
+ for (let index = 0; index < values.length; index += size) {
4771
+ chunks.push(values.slice(index, index + size));
4772
+ }
4773
+ return chunks;
4774
+ }
4775
+ function evenlySample(values, limit) {
4776
+ if (values.length <= limit) return values;
4777
+ if (limit <= 1) return [values[0]];
4778
+ return Array.from(
4779
+ { length: limit },
4780
+ (_, index) => values[Math.round(index * (values.length - 1) / (limit - 1))]
4781
+ );
4782
+ }
4783
+ function sourceNodeIdsBySpanId(sourceTree) {
4784
+ const result = /* @__PURE__ */ new Map();
4785
+ for (const node of sourceTree) {
4786
+ for (const sourceSpanId of node.sourceSpanIds) {
4787
+ const ids = result.get(sourceSpanId) ?? [];
4788
+ ids.push(node.id);
4789
+ result.set(sourceSpanId, ids);
4790
+ }
4791
+ }
4792
+ return result;
4793
+ }
4794
+ function documentPages(sourceTree, sourceSpans) {
4795
+ const pages = /* @__PURE__ */ new Set();
4796
+ for (const span of sourceSpans) {
4797
+ const start = spanPageStart(span);
4798
+ const end = spanPageEnd(span) ?? start;
4799
+ if (!start || !end) continue;
4800
+ for (let page = start; page <= end; page += 1) pages.add(page);
4801
+ }
4802
+ for (const node of sourceTree) {
4803
+ if (node.pageStart) pages.add(node.pageStart);
4804
+ if (node.pageEnd) pages.add(node.pageEnd);
4805
+ }
4806
+ return [...pages].sort((left, right) => left - right);
4807
+ }
4808
+ function pageSketch(page, sourceTree, sourceSpans) {
4809
+ const pageNodes = sourceTree.filter((node) => node.kind !== "document" && overlapsPageRange(node, page, page)).sort((left, right) => left.order - right.order || left.id.localeCompare(right.id));
4810
+ const pageSpans = sourceSpans.filter((span) => overlapsPageRange({ pageStart: spanPageStart(span), pageEnd: spanPageEnd(span) }, page, page)).sort(
4811
+ (left, right) => (left.location?.charStart ?? Number.MAX_SAFE_INTEGER) - (right.location?.charStart ?? Number.MAX_SAFE_INTEGER) || left.id.localeCompare(right.id)
4812
+ );
4813
+ const tableIds = uniqueStrings2(pageSpans.map((span) => span.table?.tableId ?? span.metadata?.tableId));
4814
+ const units = pageSpans.reduce((counts, span) => {
4815
+ const unit = spanSourceUnit(span) ?? "unknown";
4816
+ counts[unit] = (counts[unit] ?? 0) + 1;
4817
+ return counts;
4818
+ }, {});
4819
+ const textSamples = evenlySample(
4820
+ pageSpans.filter((span) => cleanText(span.text)).map((span) => ({
4821
+ sourceSpanId: span.id,
4822
+ sourceUnit: spanSourceUnit(span),
4823
+ tableId: span.table?.tableId ?? span.metadata?.tableId,
4824
+ rowIndex: span.table?.rowIndex,
4825
+ columnIndex: span.table?.columnIndex,
4826
+ columnName: span.table?.columnName,
4827
+ bbox: span.bbox?.[0],
4828
+ text: cleanText(span.text)?.slice(0, 280)
4829
+ })),
4830
+ 18
4831
+ );
4832
+ return {
4833
+ page,
4834
+ forms: uniqueStrings2(pageSpans.map((span) => span.formNumber)),
4835
+ structure: evenlySample(pageNodes.map((node) => ({
4836
+ id: node.id,
4837
+ kind: node.kind,
4838
+ title: node.title,
4839
+ path: node.path,
4840
+ sourceSpanIds: node.sourceSpanIds.slice(0, 6)
4841
+ })), 20),
4842
+ layout: {
4843
+ units,
4844
+ tableCount: tableIds.length,
4845
+ rowCount: pageSpans.filter((span) => spanSourceUnit(span) === "table_row").length,
4846
+ cellCount: pageSpans.filter((span) => spanSourceUnit(span) === "table_cell").length
4847
+ },
4848
+ textSamples
4849
+ };
4850
+ }
4851
+ function discoveryPrompt(sketches) {
4852
+ return `Discover every document region that may contain policy-specific coverage facts, asset schedules, or financial facts.
4853
+
4854
+ This is semantic region discovery, not keyword or heading matching. Inspect the layout and source-tree sketch for every supplied page, including unusual terminology and late-document schedules.
4855
+
4856
+ Select regions containing or continuing any of:
4857
+ - coverage, benefit, insuring-agreement, limit, sublimit, deductible, retention, or per-asset terms
4858
+ - covered-auto, vehicle, property, location, building, equipment, or similar asset schedules
4859
+ - premium breakdowns, taxes, fees, surcharges, assessments, or total payable
4860
+ - declarations, forms, endorsements, options, exclusions, or cross-references that establish the status or scope of those facts
4861
+
4862
+ Continuation rules:
4863
+ - A repeated heading is not required. Carry prior section and table-header context onto continuation pages.
4864
+ - Continue through compatible row numbering, column geometry, form identity, and table shape.
4865
+ - Stop at a new form, incompatible table structure, terminal language, or unrelated section.
4866
+ - Include declined, excluded, and unselected-option regions so the extraction pass can keep them out of active coverage rows.
4867
+
4868
+ Use only page numbers and source IDs from the sketches. Return no region for pages that contain no relevant policy-specific evidence.
4869
+
4870
+ Page sketches:
4871
+ ${JSON.stringify(sketches, null, 2)}`;
4872
+ }
4873
+ function normalizeRegions(regions, pages) {
4874
+ if (pages.length === 0) return [];
4875
+ const minPage = pages[0];
4876
+ const maxPage = pages[pages.length - 1];
4877
+ const normalized = regions.flatMap((region) => {
4878
+ const start = Math.max(minPage, Math.min(maxPage, region.pageStart));
4879
+ const end = Math.max(start, Math.min(maxPage, region.pageEnd));
4880
+ if (!pages.some((page) => page >= start && page <= end)) return [];
4881
+ return [{ ...region, pageStart: start, pageEnd: end }];
4882
+ });
4883
+ normalized.sort((left, right) => left.pageStart - right.pageStart || left.pageEnd - right.pageEnd);
4884
+ return normalized.reduce((rows, region) => {
4885
+ const previous = rows[rows.length - 1];
4886
+ if (!previous || region.pageStart > previous.pageEnd + 1) {
4887
+ rows.push(region);
4888
+ return rows;
4889
+ }
4890
+ previous.pageEnd = Math.max(previous.pageEnd, region.pageEnd);
4891
+ previous.reason = uniqueStrings2([previous.reason, region.reason]).join("; ");
4892
+ previous.priorContext = uniqueStrings2([previous.priorContext, region.priorContext]).join("; ") || void 0;
4893
+ previous.sourceNodeIds = uniqueStrings2([...previous.sourceNodeIds, ...region.sourceNodeIds]);
4894
+ previous.sourceSpanIds = uniqueStrings2([...previous.sourceSpanIds, ...region.sourceSpanIds]);
4895
+ return rows;
4896
+ }, []);
4897
+ }
4898
+ function splitRegions(regions) {
4899
+ return regions.flatMap((region) => {
4900
+ const result = [];
4901
+ for (let page = region.pageStart; page <= region.pageEnd; page += REGION_PAGE_BATCH_SIZE) {
4902
+ result.push({
4903
+ ...region,
4904
+ pageStart: page,
4905
+ pageEnd: Math.min(region.pageEnd, page + REGION_PAGE_BATCH_SIZE - 1)
4906
+ });
4907
+ }
4908
+ return result;
4909
+ });
4910
+ }
4911
+ function priorStructuralContext(region, sourceTree, sourceSpans) {
4912
+ const precedingNodes = sourceTree.filter((node) => node.kind !== "document" && (node.pageStart ?? 0) <= region.pageStart).filter((node) => ["page_group", "form", "endorsement", "section", "schedule", "table"].includes(node.kind)).sort(
4913
+ (left, right) => (right.pageStart ?? 0) - (left.pageStart ?? 0) || right.order - left.order
4914
+ ).slice(0, 12).map((node) => ({
4915
+ id: node.id,
4916
+ kind: node.kind,
4917
+ title: node.title,
4918
+ path: node.path,
4919
+ pageStart: node.pageStart,
4920
+ pageEnd: node.pageEnd,
4921
+ sourceSpanIds: node.sourceSpanIds.slice(0, 8)
4922
+ }));
4923
+ const headerSpans = sourceSpans.filter((span) => {
4924
+ const page = spanPageStart(span);
4925
+ return typeof page === "number" && page >= Math.max(1, region.pageStart - 2) && page <= region.pageStart && (span.table?.isHeader || span.table?.columnName || span.metadata?.isHeader === "true");
4926
+ }).map((span) => ({
4927
+ sourceSpanId: span.id,
4928
+ pageStart: spanPageStart(span),
4929
+ table: span.table,
4930
+ text: cleanText(span.text)?.slice(0, 600)
4931
+ }));
4932
+ return { priorContext: region.priorContext, precedingNodes, tableHeaders: headerSpans };
4933
+ }
4934
+ function regionEvidence(region, sourceTree, sourceSpans) {
4935
+ const nodeIdsBySpanId = sourceNodeIdsBySpanId(sourceTree);
4936
+ const spans = sourceSpans.filter((span) => overlapsPageRange(
4937
+ { pageStart: spanPageStart(span), pageEnd: spanPageEnd(span) },
4938
+ region.pageStart,
4939
+ region.pageEnd
4940
+ )).sort(
4941
+ (left, right) => (spanPageStart(left) ?? Number.MAX_SAFE_INTEGER) - (spanPageStart(right) ?? Number.MAX_SAFE_INTEGER) || (left.location?.charStart ?? Number.MAX_SAFE_INTEGER) - (right.location?.charStart ?? Number.MAX_SAFE_INTEGER) || left.id.localeCompare(right.id)
4942
+ );
4943
+ return spans.flatMap((span) => {
4944
+ const text = cleanText(span.text);
4945
+ if (!text) return [];
4946
+ const parts = text.match(/[\s\S]{1,1400}/g) ?? [text];
4947
+ return parts.map((part) => ({
4948
+ sourceSpanId: span.id,
4949
+ sourceNodeIds: (nodeIdsBySpanId.get(span.id) ?? []).slice(0, 6),
4950
+ pageStart: spanPageStart(span),
4951
+ pageEnd: spanPageEnd(span),
4952
+ sourceUnit: spanSourceUnit(span),
4953
+ formNumber: span.formNumber,
4954
+ table: span.table,
4955
+ text: part
4956
+ }));
4957
+ });
4958
+ }
4959
+ function evidenceBatches(entries) {
4960
+ const batches = [];
4961
+ let current = [];
4962
+ let chars = 0;
4963
+ for (const entry of entries) {
4964
+ const size = entry.text.length + 260;
4965
+ if (current.length > 0 && chars + size > RECOVERY_EVIDENCE_CHAR_LIMIT) {
4966
+ batches.push(current);
4967
+ current = [];
4968
+ chars = 0;
4969
+ }
4970
+ current.push(entry);
4971
+ chars += size;
4972
+ }
4973
+ if (current.length > 0) batches.push(current);
4974
+ return batches;
4975
+ }
4976
+ function recoveryPrompt(params) {
4977
+ return `Recover missing source-backed policy coverage, schedule, and financial facts from one semantically selected document region.
4978
+
4979
+ Region: pages ${params.region.pageStart}-${params.region.pageEnd}
4980
+ Reason: ${params.region.reason}
4981
+ Evidence batch: ${params.batchIndex}/${params.batchCount}
4982
+
4983
+ Rules:
4984
+ - Preserve the source's coverage terminology as coverages[].name. ACORD lineOfBusiness and coverageCode may supplement it but may not replace it with unsupported wording.
4985
+ - A repeated heading is not required. Use the prior section and table-header context to interpret compatible continuation rows.
4986
+ - Keep declaration/core-form and endorsement facts separate when their source scopes differ, even if names match.
4987
+ - Put per occurrence, per claim, aggregate, per vehicle, per location, retention, deductible, sublimit, and similar values in coverages[].limits with the source label preserved.
4988
+ - Do not emit premium, taxes, fees, surcharges, assessments, rating bases, insured values, or exposures as coverage rows or coverage terms.
4989
+ - Do not emit declined, excluded, not-covered, or optional-unselected entries as active coverages.
4990
+ - Store covered-auto, vehicle, property, location, building, and equipment listings in coverageSchedules. Partial or redacted items are allowed there.
4991
+ - Put premium rows in premiumBreakdown, taxes/fees/surcharges/assessments in taxesAndFees, and total payable in totalCost.
4992
+ - Every returned fact must cite existing sourceSpanIds or sourceNodeIds from the supplied evidence. Prefer exact row/cell sourceSpanIds.
4993
+ - Numeric, monetary, percentage, date, VIN, form, and policy identifiers must be copied exactly enough to appear in their cited evidence after punctuation and spacing normalization.
4994
+ - Omit ambiguous or unsupported facts. Do not replace or rewrite source values.
4995
+
4996
+ Prior structural context:
4997
+ ${JSON.stringify(params.context, null, 2)}
4998
+
4999
+ Source evidence:
5000
+ ${JSON.stringify(params.evidence, null, 2)}`;
5001
+ }
5002
+ function normalizedText(value) {
5003
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "");
5004
+ }
5005
+ function mechanicallyCheckableTokens(value) {
5006
+ const numeric = [...value.matchAll(/\d[\d,./:%-]*/g)].map((match) => match[0].replace(/^0+(?=\d)/, "").replace(/[^0-9a-z]/gi, "")).filter((token) => token.length >= 2);
5007
+ const identifiers = [...value.matchAll(/\b(?=[A-Z0-9-]*\d)[A-Z0-9-]{5,}\b/gi)].map((match) => normalizedText(match[0]));
5008
+ return uniqueStrings2([...numeric, ...identifiers]);
5009
+ }
5010
+ function valueGroundedInText(value, evidenceText) {
5011
+ if (!value) return true;
5012
+ const tokens = mechanicallyCheckableTokens(value);
5013
+ if (tokens.length === 0) return true;
5014
+ const normalizedEvidence = normalizedText(evidenceText);
5015
+ return tokens.every((token) => normalizedEvidence.includes(normalizedText(token)));
5016
+ }
5017
+ function citedText(ids, spansById) {
5018
+ return ids.map((id) => spansById.get(id)?.text ?? "").join(" ");
5019
+ }
5020
+ function validIds2(ids, valid) {
5021
+ return uniqueStrings2(ids.filter((id) => valid.has(id)));
5022
+ }
5023
+ function validateCandidate(candidate, sourceTree, sourceSpans) {
5024
+ const validNodeIds = new Set(sourceTree.map((node) => node.id));
5025
+ const validSpanIds = new Set(sourceSpans.map((span) => span.id));
5026
+ const spansById = new Map(sourceSpans.map((span) => [span.id, span]));
5027
+ let citationRejectionCount = 0;
5028
+ const validateCitation = (sourceNodeIds, sourceSpanIds, values) => {
5029
+ const nodes = validIds2(sourceNodeIds, validNodeIds);
5030
+ const spans = validIds2(sourceSpanIds, validSpanIds);
5031
+ if (nodes.length === 0 && spans.length === 0) {
5032
+ citationRejectionCount += 1;
5033
+ return void 0;
5034
+ }
5035
+ const evidenceText = citedText(spans, spansById);
5036
+ if (values.some((value) => !valueGroundedInText(value, evidenceText))) {
5037
+ citationRejectionCount += 1;
5038
+ return void 0;
5039
+ }
5040
+ return { sourceNodeIds: nodes, sourceSpanIds: spans };
5041
+ };
5042
+ const coverages = candidate.coverages.flatMap((coverage) => {
5043
+ const coverageCitation = validateCitation(
5044
+ coverage.sourceNodeIds,
5045
+ coverage.sourceSpanIds,
5046
+ [coverage.name, coverage.limit, coverage.deductible, coverage.premium, coverage.retroactiveDate, coverage.formNumber, coverage.endorsementNumber]
5047
+ );
5048
+ if (!coverageCitation) return [];
5049
+ if (/\b(?:declined|excluded|not covered|not selected|optional\s*[-:]?\s*no)\b/i.test(coverage.name)) return [];
5050
+ if (/\b(?:premium|tax|fee|surcharge|assessment|rating basis|exposure|insured value)\b/i.test(coverage.name) && coverage.limits.length === 0 && !coverage.limit && !coverage.deductible) return [];
5051
+ const limits = coverage.limits.flatMap((term) => {
5052
+ if (term.kind === "premium") return [];
5053
+ const citation = validateCitation(
5054
+ term.sourceNodeIds,
5055
+ term.sourceSpanIds,
5056
+ [term.label, term.value, term.appliesTo]
5057
+ );
5058
+ return citation ? [{ ...term, ...citation }] : [];
5059
+ });
5060
+ const hasCoverageFact = limits.length > 0 || coverage.limit || coverage.deductible || coverage.retroactiveDate || coverage.formNumber || coverage.endorsementNumber;
5061
+ return hasCoverageFact ? [{ ...coverage, ...coverageCitation, limits }] : [];
5062
+ });
5063
+ const coverageSchedules = candidate.coverageSchedules.flatMap((schedule) => {
5064
+ const sourceSpanIds = validIds2(schedule.sourceSpanIds, validSpanIds);
5065
+ if (sourceSpanIds.length === 0 || !valueGroundedInText(schedule.name, citedText(sourceSpanIds, spansById))) {
5066
+ citationRejectionCount += 1;
5067
+ return [];
5068
+ }
5069
+ const items = schedule.items.flatMap((item) => {
5070
+ const itemSpanIds = validIds2(item.sourceSpanIds, validSpanIds);
5071
+ if (itemSpanIds.length === 0) {
5072
+ citationRejectionCount += 1;
5073
+ return [];
5074
+ }
5075
+ const evidenceText = citedText(itemSpanIds, spansById);
5076
+ const values = item.values.filter((value) => {
5077
+ const valid = valueGroundedInText(value.value, evidenceText);
5078
+ if (!valid) citationRejectionCount += 1;
5079
+ return valid;
5080
+ });
5081
+ return values.length > 0 && valueGroundedInText(item.label, evidenceText) ? [{ ...item, values, sourceSpanIds: itemSpanIds }] : [];
5082
+ });
5083
+ return items.length > 0 ? [{ ...schedule, items, sourceSpanIds }] : [];
5084
+ });
5085
+ const premiumBreakdown = candidate.premiumBreakdown.flatMap((row) => {
5086
+ const citation = validateCitation(row.sourceNodeIds, row.sourceSpanIds, [row.line, row.amount]);
5087
+ return citation ? [{ ...row, ...citation }] : [];
5088
+ });
5089
+ const taxesAndFees = candidate.taxesAndFees.flatMap((row) => {
5090
+ const citation = validateCitation(row.sourceNodeIds, row.sourceSpanIds, [row.name, row.amount]);
5091
+ return citation ? [{ ...row, ...citation }] : [];
5092
+ });
5093
+ const totalCostCitation = candidate.totalCost ? validateCitation(candidate.totalCost.sourceNodeIds, candidate.totalCost.sourceSpanIds, [candidate.totalCost.value]) : void 0;
5094
+ return {
5095
+ candidate: {
5096
+ ...candidate,
5097
+ coverages,
5098
+ coverageSchedules,
5099
+ premiumBreakdown,
5100
+ taxesAndFees,
5101
+ totalCost: candidate.totalCost && totalCostCitation ? { ...candidate.totalCost, ...totalCostCitation } : void 0
5102
+ },
5103
+ citationRejectionCount
5104
+ };
5105
+ }
5106
+ function normalizedLabel(value) {
5107
+ return value.toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, " ").trim();
5108
+ }
5109
+ function sourcePages(ids, spansById) {
5110
+ const pages = ids.flatMap((id) => {
5111
+ const span = spansById.get(id);
5112
+ const start = span ? spanPageStart(span) : void 0;
5113
+ const end = span ? spanPageEnd(span) : void 0;
5114
+ return [start, end].filter((page) => typeof page === "number");
5115
+ });
5116
+ return pages.length > 0 ? [Math.min(...pages), Math.max(...pages)] : void 0;
5117
+ }
5118
+ function sameCoverageScope(primary, recovery, spansById) {
5119
+ if (normalizedLabel(primary.name) !== normalizedLabel(recovery.name)) return false;
5120
+ if (primary.lineOfBusiness && recovery.lineOfBusiness && primary.lineOfBusiness !== recovery.lineOfBusiness) return false;
5121
+ for (const key of ["formNumber", "sectionRef", "endorsementNumber"]) {
5122
+ const left = cleanText(primary[key]);
5123
+ const right = cleanText(recovery[key]);
5124
+ if (left && right && normalizedLabel(left) !== normalizedLabel(right)) return false;
5125
+ if (key === "endorsementNumber" && Boolean(left) !== Boolean(right)) return false;
5126
+ }
5127
+ const primaryPages = sourcePages(primary.sourceSpanIds, spansById);
5128
+ const recoveryPages = sourcePages(recovery.sourceSpanIds, spansById);
5129
+ if (!primaryPages || !recoveryPages) return true;
5130
+ return primaryPages[0] <= recoveryPages[1] + 1 && recoveryPages[0] <= primaryPages[1] + 1;
5131
+ }
5132
+ function termIdentity(term) {
5133
+ return [term.kind, normalizedLabel(term.label), normalizedLabel(term.value), normalizedLabel(term.appliesTo ?? "")].join("|");
5134
+ }
5135
+ function mergeCoverage(primary, recovery, warnings) {
5136
+ const limits = [...primary.limits];
5137
+ const identities = new Set(limits.map(termIdentity));
5138
+ for (const term of recovery.limits) {
5139
+ const identity = termIdentity(term);
5140
+ if (identities.has(identity)) continue;
5141
+ const conflict = limits.find(
5142
+ (current) => current.kind === term.kind && normalizedLabel(current.label) === normalizedLabel(term.label) && normalizedLabel(current.appliesTo ?? "") === normalizedLabel(term.appliesTo ?? "") && normalizedLabel(current.value) !== normalizedLabel(term.value)
5143
+ );
5144
+ if (conflict) {
5145
+ warnings.push(`Coverage recovery preserved conflicting cited ${term.label} terms for ${primary.name}.`);
4560
5146
  }
5147
+ limits.push(term);
5148
+ identities.add(identity);
4561
5149
  }
4562
- const termLimit = primaryLimitFromTerms(next.limits);
4563
- if (termLimit && shouldUseTermLimitDisplay(next.limit, termLimit)) {
4564
- next.limit = termLimit;
5150
+ return {
5151
+ ...recovery,
5152
+ ...primary,
5153
+ limit: primary.limit ?? recovery.limit,
5154
+ deductible: primary.deductible ?? recovery.deductible,
5155
+ premium: primary.premium ?? recovery.premium,
5156
+ retroactiveDate: primary.retroactiveDate ?? recovery.retroactiveDate,
5157
+ formNumber: primary.formNumber ?? recovery.formNumber,
5158
+ sectionRef: primary.sectionRef ?? recovery.sectionRef,
5159
+ endorsementNumber: primary.endorsementNumber ?? recovery.endorsementNumber,
5160
+ limits,
5161
+ sourceNodeIds: uniqueStrings2([...primary.sourceNodeIds, ...recovery.sourceNodeIds]),
5162
+ sourceSpanIds: uniqueStrings2([...primary.sourceSpanIds, ...recovery.sourceSpanIds])
5163
+ };
5164
+ }
5165
+ function appendUnique(primary, additions, key) {
5166
+ const result = [...primary];
5167
+ const seen = new Set(primary.map(key));
5168
+ for (const value of additions) {
5169
+ const identity = key(value);
5170
+ if (seen.has(identity)) continue;
5171
+ seen.add(identity);
5172
+ result.push(value);
4565
5173
  }
4566
- next.sourceNodeIds = uniqueStrings([
4567
- ...next.sourceNodeIds,
4568
- ...next.limits.flatMap((term) => term.sourceNodeIds)
5174
+ return result;
5175
+ }
5176
+ function mergeRecoveryCandidate(profile, candidate, sourceSpans) {
5177
+ const warnings = [...candidate.warnings];
5178
+ const spansById = new Map(sourceSpans.map((span) => [span.id, span]));
5179
+ const coverages = [...profile.coverages];
5180
+ let recoveredCoverageCount = 0;
5181
+ let recoveredTermCount = 0;
5182
+ for (const recovery of candidate.coverages) {
5183
+ const matchIndex = coverages.findIndex((primary) => sameCoverageScope(primary, recovery, spansById));
5184
+ if (matchIndex < 0) {
5185
+ coverages.push(recovery);
5186
+ recoveredCoverageCount += 1;
5187
+ recoveredTermCount += recovery.limits.length;
5188
+ continue;
5189
+ }
5190
+ const before = coverages[matchIndex].limits.length;
5191
+ coverages[matchIndex] = mergeCoverage(coverages[matchIndex], recovery, warnings);
5192
+ recoveredTermCount += coverages[matchIndex].limits.length - before;
5193
+ }
5194
+ const coverageSchedules = appendUnique(
5195
+ profile.coverageSchedules ?? [],
5196
+ candidate.coverageSchedules,
5197
+ (schedule) => `${schedule.kind}|${normalizedLabel(schedule.name)}|${schedule.pageStart ?? ""}|${schedule.pageEnd ?? ""}`
5198
+ );
5199
+ const premiumBreakdown = appendUnique(
5200
+ profile.premiumBreakdown ?? [],
5201
+ candidate.premiumBreakdown,
5202
+ (row) => `${normalizedLabel(row.line)}|${normalizedLabel(row.amount)}|${row.sourceSpanIds.join(",")}`
5203
+ );
5204
+ const taxesAndFees = appendUnique(
5205
+ profile.taxesAndFees ?? [],
5206
+ candidate.taxesAndFees,
5207
+ (row) => `${normalizedLabel(row.name)}|${normalizedLabel(row.amount)}|${row.sourceSpanIds.join(",")}`
5208
+ );
5209
+ const totalCost = profile.totalCost ?? candidate.totalCost;
5210
+ const sourceNodeIds = uniqueStrings2([
5211
+ ...profile.sourceNodeIds,
5212
+ ...coverages.flatMap((coverage) => [
5213
+ ...coverage.sourceNodeIds,
5214
+ ...coverage.limits.flatMap((term) => term.sourceNodeIds)
5215
+ ]),
5216
+ ...premiumBreakdown.flatMap((row) => row.sourceNodeIds),
5217
+ ...taxesAndFees.flatMap((row) => row.sourceNodeIds),
5218
+ ...totalCost?.sourceNodeIds ?? []
4569
5219
  ]);
4570
- next.sourceSpanIds = uniqueStrings([
4571
- ...next.sourceSpanIds,
4572
- ...next.limits.flatMap((term) => term.sourceSpanIds)
5220
+ const sourceSpanIds = uniqueStrings2([
5221
+ ...profile.sourceSpanIds,
5222
+ ...coverages.flatMap((coverage) => [
5223
+ ...coverage.sourceSpanIds,
5224
+ ...coverage.limits.flatMap((term) => term.sourceSpanIds)
5225
+ ]),
5226
+ ...coverageSchedules.flatMap((schedule) => [
5227
+ ...schedule.sourceSpanIds,
5228
+ ...schedule.items.flatMap((item) => item.sourceSpanIds)
5229
+ ]),
5230
+ ...premiumBreakdown.flatMap((row) => row.sourceSpanIds),
5231
+ ...taxesAndFees.flatMap((row) => row.sourceSpanIds),
5232
+ ...totalCost?.sourceSpanIds ?? []
4573
5233
  ]);
4574
- return next.name ? next : coverage;
5234
+ return {
5235
+ operationalProfile: {
5236
+ ...profile,
5237
+ coverages,
5238
+ coverageSchedules,
5239
+ premiumBreakdown,
5240
+ taxesAndFees,
5241
+ totalCost,
5242
+ sourceNodeIds,
5243
+ sourceSpanIds,
5244
+ warnings: uniqueStrings2([...profile.warnings, ...warnings])
5245
+ },
5246
+ warnings,
5247
+ recoveredCoverageCount,
5248
+ recoveredTermCount,
5249
+ recoveredScheduleCount: coverageSchedules.length - (profile.coverageSchedules?.length ?? 0),
5250
+ recoveredFinancialFactCount: premiumBreakdown.length - (profile.premiumBreakdown?.length ?? 0) + taxesAndFees.length - (profile.taxesAndFees?.length ?? 0) + (!profile.totalCost && totalCost ? 1 : 0)
5251
+ };
4575
5252
  }
4576
- function sourceIdsFromOperationalProfile(profile) {
4577
- const backedValues = [
4578
- profile.policyNumber,
4579
- profile.namedInsured,
4580
- profile.insurer,
4581
- profile.broker,
4582
- profile.effectiveDate,
4583
- profile.expirationDate,
4584
- profile.retroactiveDate,
4585
- profile.premium
4586
- ].filter(Boolean);
5253
+ function emptyDiagnostics(status) {
4587
5254
  return {
4588
- sourceNodeIds: uniqueStrings([
4589
- ...backedValues.flatMap((value) => value?.sourceNodeIds ?? []),
4590
- ...profile.coverages.flatMap((coverage) => coverage.sourceNodeIds),
4591
- ...profile.coverages.flatMap((coverage) => coverage.limits.flatMap((term) => term.sourceNodeIds)),
4592
- ...profile.parties.flatMap((party) => party.sourceNodeIds),
4593
- ...profile.endorsementSupport.flatMap((support) => support.sourceNodeIds)
4594
- ]),
4595
- sourceSpanIds: uniqueStrings([
4596
- ...backedValues.flatMap((value) => value?.sourceSpanIds ?? []),
4597
- ...profile.coverages.flatMap((coverage) => coverage.sourceSpanIds),
4598
- ...profile.coverages.flatMap((coverage) => coverage.limits.flatMap((term) => term.sourceSpanIds)),
4599
- ...profile.parties.flatMap((party) => party.sourceSpanIds),
4600
- ...profile.endorsementSupport.flatMap((support) => support.sourceSpanIds)
4601
- ])
5255
+ version: COVERAGE_RECOVERY_VERSION,
5256
+ status,
5257
+ regionCount: 0,
5258
+ modelCallCount: 0,
5259
+ recoveredCoverageCount: 0,
5260
+ recoveredTermCount: 0,
5261
+ recoveredScheduleCount: 0,
5262
+ recoveredFinancialFactCount: 0,
5263
+ citationRejectionCount: 0,
5264
+ warnings: []
4602
5265
  };
4603
5266
  }
4604
- function applyOperationalProfileCleanup(profile, cleanup, validNodeIds, validSpanIds) {
4605
- const coverageDecisionByIndex = /* @__PURE__ */ new Map();
4606
- for (const decision of cleanup.coverageDecisions) {
4607
- if (decision.coverageIndex < profile.coverages.length) coverageDecisionByIndex.set(decision.coverageIndex, decision);
5267
+ function disabledCoverageRecoveryDiagnostics() {
5268
+ return emptyDiagnostics("disabled");
5269
+ }
5270
+ async function recoverOperationalProfileCoverage(params) {
5271
+ const diagnostics = emptyDiagnostics("succeeded");
5272
+ try {
5273
+ const pages = documentPages(params.sourceTree, params.sourceSpans);
5274
+ const discoveredRegions = [];
5275
+ for (const [batchIndex, pageBatch] of chunkValues(pages, DISCOVERY_PAGE_BATCH_SIZE).entries()) {
5276
+ const sketches = pageBatch.map((page) => pageSketch(page, params.sourceTree, params.sourceSpans));
5277
+ const budget = params.resolveBudget("extraction_coverage_recovery", 8192);
5278
+ const startedAt = Date.now();
5279
+ diagnostics.modelCallCount += 1;
5280
+ const response = await safeGenerateObject(
5281
+ params.generateObject,
5282
+ {
5283
+ prompt: discoveryPrompt(sketches),
5284
+ schema: RecoveryRegionDiscoverySchema,
5285
+ maxTokens: budget.maxTokens,
5286
+ taskKind: "extraction_coverage_recovery",
5287
+ budgetDiagnostics: budget,
5288
+ providerOptions: params.providerOptions,
5289
+ trace: {
5290
+ phase: "coverage_recovery_discovery",
5291
+ label: "coverage_recovery_discovery",
5292
+ startPage: pageBatch[0],
5293
+ endPage: pageBatch[pageBatch.length - 1],
5294
+ batchIndex: batchIndex + 1,
5295
+ batchCount: Math.ceil(pages.length / DISCOVERY_PAGE_BATCH_SIZE),
5296
+ sourceBacked: true
5297
+ }
5298
+ },
5299
+ { maxRetries: 0, log: params.log, retry: false }
5300
+ );
5301
+ params.trackUsage(response.usage, {
5302
+ taskKind: "extraction_coverage_recovery",
5303
+ label: "coverage_recovery_discovery",
5304
+ maxTokens: budget.maxTokens,
5305
+ durationMs: Date.now() - startedAt
5306
+ });
5307
+ const discovery = response.object;
5308
+ discoveredRegions.push(...discovery.regions);
5309
+ diagnostics.warnings.push(...discovery.warnings);
5310
+ }
5311
+ const regions = splitRegions(normalizeRegions(discoveredRegions, pages));
5312
+ diagnostics.regionCount = regions.length;
5313
+ let operationalProfile = params.operationalProfile;
5314
+ for (const [regionIndex, region] of regions.entries()) {
5315
+ const evidence = regionEvidence(region, params.sourceTree, params.sourceSpans);
5316
+ const batches = evidenceBatches(evidence);
5317
+ const context = priorStructuralContext(region, params.sourceTree, params.sourceSpans);
5318
+ for (const [batchIndex, batch] of batches.entries()) {
5319
+ const budget = params.resolveBudget("extraction_coverage_recovery", 12288);
5320
+ const startedAt = Date.now();
5321
+ diagnostics.modelCallCount += 1;
5322
+ const response = await safeGenerateObject(
5323
+ params.generateObject,
5324
+ {
5325
+ prompt: recoveryPrompt({
5326
+ region,
5327
+ context,
5328
+ evidence: batch,
5329
+ batchIndex: batchIndex + 1,
5330
+ batchCount: batches.length
5331
+ }),
5332
+ schema: CoverageRecoveryCandidateSchema,
5333
+ maxTokens: budget.maxTokens,
5334
+ taskKind: "extraction_coverage_recovery",
5335
+ budgetDiagnostics: budget,
5336
+ providerOptions: params.providerOptions,
5337
+ trace: {
5338
+ phase: "coverage_recovery",
5339
+ label: "coverage_recovery",
5340
+ startPage: region.pageStart,
5341
+ endPage: region.pageEnd,
5342
+ batchIndex: batchIndex + 1,
5343
+ batchCount: batches.length,
5344
+ sourceBacked: true
5345
+ }
5346
+ },
5347
+ { maxRetries: 0, log: params.log, retry: false }
5348
+ );
5349
+ params.trackUsage(response.usage, {
5350
+ taskKind: "extraction_coverage_recovery",
5351
+ label: `coverage_recovery_${regionIndex + 1}`,
5352
+ maxTokens: budget.maxTokens,
5353
+ durationMs: Date.now() - startedAt
5354
+ });
5355
+ const validated = validateCandidate(
5356
+ response.object,
5357
+ params.sourceTree,
5358
+ params.sourceSpans
5359
+ );
5360
+ diagnostics.citationRejectionCount += validated.citationRejectionCount;
5361
+ const merged = mergeRecoveryCandidate(operationalProfile, validated.candidate, params.sourceSpans);
5362
+ operationalProfile = merged.operationalProfile;
5363
+ diagnostics.recoveredCoverageCount += merged.recoveredCoverageCount;
5364
+ diagnostics.recoveredTermCount += merged.recoveredTermCount;
5365
+ diagnostics.recoveredScheduleCount += merged.recoveredScheduleCount;
5366
+ diagnostics.recoveredFinancialFactCount += merged.recoveredFinancialFactCount;
5367
+ diagnostics.warnings.push(...merged.warnings);
5368
+ }
5369
+ }
5370
+ diagnostics.warnings = uniqueStrings2(diagnostics.warnings);
5371
+ return { operationalProfile, diagnostics };
5372
+ } catch (error) {
5373
+ diagnostics.status = "failed";
5374
+ diagnostics.warnings = uniqueStrings2([
5375
+ ...diagnostics.warnings,
5376
+ `Coverage recovery failed: ${error instanceof Error ? error.message : String(error)}`
5377
+ ]);
5378
+ await params.log?.(diagnostics.warnings[diagnostics.warnings.length - 1]);
5379
+ return { operationalProfile: params.operationalProfile, diagnostics };
4608
5380
  }
4609
- const coverages = profile.coverages.map(
4610
- (coverage, index) => applyCoverageCleanupDecision(coverage, coverageDecisionByIndex.get(index), validNodeIds, validSpanIds)
4611
- ).filter((coverage) => Boolean(coverage));
4612
- const cleanupWarnings = cleanup.warnings.map((warning) => cleanProfileValue(warning)).filter((warning) => Boolean(warning));
4613
- const nextProfile = {
4614
- ...profile,
4615
- coverages,
4616
- warnings: uniqueStrings([
4617
- ...profile.warnings,
4618
- ...cleanupWarnings.map((warning) => `Operational profile cleanup warning: ${warning}`)
4619
- ])
5381
+ }
5382
+ async function runCoverageRecovery(params) {
5383
+ const tokenUsage = { inputTokens: 0, outputTokens: 0 };
5384
+ const performanceReport = {
5385
+ modelCalls: [],
5386
+ totalModelCallDurationMs: 0
4620
5387
  };
4621
- return PolicyOperationalProfileSchema.parse({
4622
- ...nextProfile,
4623
- ...sourceIdsFromOperationalProfile(nextProfile)
5388
+ const recovery = await recoverOperationalProfileCoverage({
5389
+ sourceTree: params.sourceTree,
5390
+ sourceSpans: params.sourceSpans,
5391
+ operationalProfile: params.operationalProfile,
5392
+ generateObject: params.generateObject,
5393
+ providerOptions: params.providerOptions,
5394
+ resolveBudget: (taskKind, hintTokens) => resolveModelBudget({
5395
+ taskKind,
5396
+ hintTokens,
5397
+ modelCapabilities: params.modelCapabilities,
5398
+ constraint: params.modelBudgetConstraint
5399
+ }),
5400
+ trackUsage: (usage, report) => {
5401
+ if (usage) {
5402
+ tokenUsage.inputTokens += usage.inputTokens;
5403
+ tokenUsage.outputTokens += usage.outputTokens;
5404
+ params.onTokenUsage?.(usage);
5405
+ }
5406
+ if (report) {
5407
+ performanceReport.modelCalls.push({
5408
+ ...report,
5409
+ usage,
5410
+ usageReported: Boolean(usage)
5411
+ });
5412
+ if (report.durationMs != null) {
5413
+ performanceReport.totalModelCallDurationMs += report.durationMs;
5414
+ }
5415
+ }
5416
+ },
5417
+ log: params.log
4624
5418
  });
5419
+ return {
5420
+ ...recovery,
5421
+ tokenUsage,
5422
+ performanceReport
5423
+ };
4625
5424
  }
4626
5425
 
4627
5426
  // src/extraction/source-tree-extractor.ts
4628
- var SourceBackedValueForPromptSchema = z23.object({
4629
- value: z23.string(),
4630
- normalizedValue: z23.string().optional(),
4631
- confidence: z23.enum(["low", "medium", "high"]).optional(),
4632
- sourceNodeIds: z23.array(z23.string()),
4633
- sourceSpanIds: z23.array(z23.string())
4634
- });
4635
- var OperationalAddressForPromptSchema = z23.object({
4636
- street1: z23.string().optional(),
4637
- street2: z23.string().optional(),
4638
- city: z23.string().optional(),
4639
- state: z23.string().optional(),
4640
- zip: z23.string().optional(),
4641
- country: z23.string().optional(),
4642
- formatted: z23.string().optional()
4643
- });
4644
- var OperationalDeclarationFactForPromptSchema = z23.object({
4645
- field: z23.enum([
5427
+ var SourceBackedValueForPromptSchema = z24.object({
5428
+ value: z24.string(),
5429
+ normalizedValue: z24.string().optional(),
5430
+ confidence: z24.enum(["low", "medium", "high"]).optional(),
5431
+ sourceNodeIds: z24.array(z24.string()),
5432
+ sourceSpanIds: z24.array(z24.string())
5433
+ });
5434
+ var OperationalAddressForPromptSchema = z24.object({
5435
+ street1: z24.string().optional(),
5436
+ street2: z24.string().optional(),
5437
+ city: z24.string().optional(),
5438
+ state: z24.string().optional(),
5439
+ zip: z24.string().optional(),
5440
+ country: z24.string().optional(),
5441
+ formatted: z24.string().optional()
5442
+ });
5443
+ var OperationalDeclarationFactForPromptSchema = z24.object({
5444
+ field: z24.enum([
4646
5445
  "namedInsured",
4647
5446
  "mailingAddress",
4648
5447
  "dba",
@@ -4657,18 +5456,33 @@ var OperationalDeclarationFactForPromptSchema = z23.object({
4657
5456
  "premium",
4658
5457
  "other"
4659
5458
  ]),
4660
- label: z23.string().optional(),
4661
- value: z23.string(),
4662
- normalizedValue: z23.string().optional(),
4663
- valueKind: z23.enum(["string", "number", "date", "money", "address", "list", "unknown"]).optional(),
5459
+ label: z24.string().optional(),
5460
+ value: z24.string(),
5461
+ normalizedValue: z24.string().optional(),
5462
+ valueKind: z24.enum(["string", "number", "date", "money", "address", "list", "unknown"]).optional(),
5463
+ address: OperationalAddressForPromptSchema.optional(),
5464
+ confidence: z24.enum(["low", "medium", "high"]).optional(),
5465
+ sourceNodeIds: z24.array(z24.string()),
5466
+ sourceSpanIds: z24.array(z24.string())
5467
+ });
5468
+ var OperationalPartyForPromptSchema = z24.object({
5469
+ role: z24.enum([
5470
+ "named_insured",
5471
+ "producer",
5472
+ "broker",
5473
+ "insurer",
5474
+ "carrier",
5475
+ "mga",
5476
+ "administrator"
5477
+ ]),
5478
+ name: z24.string(),
4664
5479
  address: OperationalAddressForPromptSchema.optional(),
4665
- confidence: z23.enum(["low", "medium", "high"]).optional(),
4666
- sourceNodeIds: z23.array(z23.string()),
4667
- sourceSpanIds: z23.array(z23.string())
5480
+ sourceNodeIds: z24.array(z24.string()),
5481
+ sourceSpanIds: z24.array(z24.string())
4668
5482
  });
4669
- var OperationalProfilePromptSchema = z23.object({
4670
- documentType: z23.enum(["policy", "quote"]).optional(),
4671
- linesOfBusiness: z23.array(z23.string()).optional(),
5483
+ var OperationalProfilePromptSchema = z24.object({
5484
+ documentType: z24.enum(["policy", "quote"]).optional(),
5485
+ linesOfBusiness: z24.array(z24.string()).optional(),
4672
5486
  policyNumber: SourceBackedValueForPromptSchema.optional(),
4673
5487
  namedInsured: SourceBackedValueForPromptSchema.optional(),
4674
5488
  insurer: SourceBackedValueForPromptSchema.optional(),
@@ -4677,39 +5491,41 @@ var OperationalProfilePromptSchema = z23.object({
4677
5491
  expirationDate: SourceBackedValueForPromptSchema.optional(),
4678
5492
  retroactiveDate: SourceBackedValueForPromptSchema.optional(),
4679
5493
  premium: SourceBackedValueForPromptSchema.optional(),
4680
- declarationFacts: z23.array(OperationalDeclarationFactForPromptSchema).optional(),
4681
- coverages: z23.array(z23.object({
4682
- name: z23.string(),
4683
- lineOfBusiness: z23.string().optional(),
4684
- coverageCode: z23.string().optional(),
4685
- limit: z23.string().optional(),
4686
- deductible: z23.string().optional(),
4687
- premium: z23.string().optional(),
4688
- retroactiveDate: z23.string().optional(),
4689
- formNumber: z23.string().optional(),
4690
- sectionRef: z23.string().optional(),
4691
- endorsementNumber: z23.string().optional(),
4692
- limits: z23.array(z23.object({
5494
+ operationsDescription: SourceBackedValueForPromptSchema.optional(),
5495
+ declarationFacts: z24.array(OperationalDeclarationFactForPromptSchema).optional(),
5496
+ parties: z24.array(OperationalPartyForPromptSchema).optional(),
5497
+ coverages: z24.array(z24.object({
5498
+ name: z24.string(),
5499
+ lineOfBusiness: z24.string().optional(),
5500
+ coverageCode: z24.string().optional(),
5501
+ limit: z24.string().optional(),
5502
+ deductible: z24.string().optional(),
5503
+ premium: z24.string().optional(),
5504
+ retroactiveDate: z24.string().optional(),
5505
+ formNumber: z24.string().optional(),
5506
+ sectionRef: z24.string().optional(),
5507
+ endorsementNumber: z24.string().optional(),
5508
+ limits: z24.array(z24.object({
4693
5509
  kind: OperationalCoverageTermKindSchema.optional(),
4694
- label: z23.string(),
4695
- value: z23.string(),
4696
- amount: z23.number().optional(),
4697
- appliesTo: z23.string().optional(),
4698
- sourceNodeIds: z23.array(z23.string()),
4699
- sourceSpanIds: z23.array(z23.string())
5510
+ label: z24.string(),
5511
+ value: z24.string(),
5512
+ amount: z24.number().optional(),
5513
+ appliesTo: z24.string().optional(),
5514
+ sourceNodeIds: z24.array(z24.string()),
5515
+ sourceSpanIds: z24.array(z24.string())
4700
5516
  })).optional(),
4701
- sourceNodeIds: z23.array(z23.string()),
4702
- sourceSpanIds: z23.array(z23.string())
5517
+ sourceNodeIds: z24.array(z24.string()),
5518
+ sourceSpanIds: z24.array(z24.string())
4703
5519
  })).optional(),
4704
- sourceNodeIds: z23.array(z23.string()).optional(),
4705
- sourceSpanIds: z23.array(z23.string()).optional()
5520
+ sourceNodeIds: z24.array(z24.string()).optional(),
5521
+ sourceSpanIds: z24.array(z24.string()).optional()
4706
5522
  });
4707
- function cleanText(value, fallback) {
5523
+ function cleanText2(value, fallback) {
4708
5524
  const text = value?.replace(/\s+/g, " ").trim();
4709
5525
  return text || fallback;
4710
5526
  }
4711
5527
  function simplifyOrganizerTitle(value, fallback, kind) {
4712
- const title = cleanText(value, fallback);
5528
+ const title = cleanText2(value, fallback);
4713
5529
  if (/^declarations\b/i.test(title)) return "Declarations";
4714
5530
  if (/^policy\s+form\b/i.test(title)) return "Policy Form";
4715
5531
  if (/^definitions\b/i.test(title)) return "Definitions";
@@ -4722,23 +5538,23 @@ function simplifyOrganizerTitle(value, fallback, kind) {
4722
5538
  return title;
4723
5539
  }
4724
5540
  function endorsementReference(value) {
4725
- const text = cleanText(value, "");
5541
+ const text = cleanText2(value, "");
4726
5542
  const explicit = text.match(/\bendorsement\s+(?:no\.?|number|#)?\s*([A-Z0-9][A-Z0-9.-]*)\b/i)?.[1]?.toUpperCase();
4727
5543
  if (explicit) return explicit;
4728
5544
  return text.match(/\b(?:[A-Z]{2,}-)?END\s+0*([0-9]{1,4})\b/i)?.[1]?.toUpperCase();
4729
5545
  }
4730
5546
  function endorsementTitle(value) {
4731
- const text = cleanText(value, "");
5547
+ const text = cleanText2(value, "");
4732
5548
  const explicit = text.match(/\bendorsement\s+(?:no\.?|number|#)\s*([A-Z0-9][A-Z0-9.-]*)\b/i)?.[1]?.toUpperCase();
4733
5549
  const number = explicit ?? text.match(/\b(?:[A-Z]{2,}-)?END\s+0*([0-9]{1,4})\b/i)?.[1]?.toUpperCase();
4734
5550
  return number ? `Endorsement No. ${number}` : void 0;
4735
5551
  }
4736
5552
  function sourceNodeText(node) {
4737
- return cleanText([node.title, node.description, node.textExcerpt].filter(Boolean).join(" "), "");
5553
+ return cleanText2([node.title, node.description, node.textExcerpt].filter(Boolean).join(" "), "");
4738
5554
  }
4739
5555
  function looksLikeEndorsementStart(node) {
4740
- const title = cleanText(node.title, "");
4741
- const body = cleanText([node.textExcerpt, node.description].filter(Boolean).join(" "), "");
5556
+ const title = cleanText2(node.title, "");
5557
+ const body = cleanText2([node.textExcerpt, node.description].filter(Boolean).join(" "), "");
4742
5558
  const start = body.slice(0, 260);
4743
5559
  if (/\bthis endorsement changes the policy\b/i.test(start) && endorsementReference(start)) return true;
4744
5560
  if (/^(?:[A-Z]{2,}-)?END\s+0*[0-9]{1,4}\b/i.test(start)) return true;
@@ -4747,7 +5563,7 @@ function looksLikeEndorsementStart(node) {
4747
5563
  }
4748
5564
  function looksLikeEndorsementContinuation(node) {
4749
5565
  if (looksLikeEndorsementStart(node)) return false;
4750
- const title = cleanText(node.title, "");
5566
+ const title = cleanText2(node.title, "");
4751
5567
  const text = sourceNodeText(node);
4752
5568
  return /\bendorsement\b/i.test(text) || /\bcontinuation\b/i.test(title) || /\ball\s+other\s+terms\s+and\s+conditions\b/i.test(text);
4753
5569
  }
@@ -4755,7 +5571,7 @@ function endorsementStartTitle(node) {
4755
5571
  return looksLikeEndorsementStart(node) ? endorsementTitle(sourceNodeText(node)) : void 0;
4756
5572
  }
4757
5573
  function endorsementDescription(title, node) {
4758
- return cleanText(
5574
+ return cleanText2(
4759
5575
  [title, "endorsement", node.pageStart ? `page ${node.pageStart}` : void 0].filter(Boolean).join(" | "),
4760
5576
  title
4761
5577
  );
@@ -4763,7 +5579,7 @@ function endorsementDescription(title, node) {
4763
5579
  function endorsementTitleKey(node) {
4764
5580
  const title = endorsementTitle(sourceNodeText(node));
4765
5581
  if (title) return title.toLowerCase();
4766
- const fallback = cleanText(node.title, "");
5582
+ const fallback = cleanText2(node.title, "");
4767
5583
  return fallback ? fallback.toLowerCase() : void 0;
4768
5584
  }
4769
5585
  function nodePageEnd2(node) {
@@ -4807,17 +5623,17 @@ function semanticGroupNodeId(documentId, kind, title, childNodeIds) {
4807
5623
  childNodeIds.join("_").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 80)
4808
5624
  ].join(":");
4809
5625
  }
4810
- function spanPageStart(span) {
5626
+ function spanPageStart2(span) {
4811
5627
  return span.pageStart ?? span.location?.page ?? span.location?.startPage;
4812
5628
  }
4813
- function spanPageEnd(span) {
4814
- return span.pageEnd ?? span.location?.endPage ?? spanPageStart(span);
5629
+ function spanPageEnd2(span) {
5630
+ return span.pageEnd ?? span.location?.endPage ?? spanPageStart2(span);
4815
5631
  }
4816
- function spanSourceUnit(span) {
5632
+ function spanSourceUnit2(span) {
4817
5633
  return span.sourceUnit ?? span.metadata?.sourceUnit ?? span.metadata?.elementType;
4818
5634
  }
4819
5635
  function pageHeadingTitleFromText(text, fallback) {
4820
- const normalized = cleanText(text, "");
5636
+ const normalized = cleanText2(text, "");
4821
5637
  const headingText = normalized.replace(/^page\s+\d+\s*(?:\|\s*page\s*\|\s*page\s+\d+\s*\|?)?/i, "").slice(0, 700);
4822
5638
  const patterns = [
4823
5639
  /\bIMPORTANT NOTICE\s+[—-]\s+HOW TO REPORT A CLAIM\b/i,
@@ -4831,7 +5647,7 @@ function pageHeadingTitleFromText(text, fallback) {
4831
5647
  ];
4832
5648
  for (const pattern of patterns) {
4833
5649
  const match = headingText.match(pattern)?.[0];
4834
- if (match) return cleanText(match, fallback);
5650
+ if (match) return cleanText2(match, fallback);
4835
5651
  }
4836
5652
  return fallback;
4837
5653
  }
@@ -4839,12 +5655,12 @@ function hasSubstantiveDeclarationsScheduleText(text) {
4839
5655
  return /\bitem\s+\d+\.?\s*(?:named insured|policy number|policy period|renewal|form of business|coverage parts?|limits?|premium|extended reporting|producer|forms? and endorsements?)\b/i.test(text) || /\bforms? and endorsements attached at inception\b/i.test(text) || /\bcoverage parts?,?\s+limits? of liability,?\s+deductibles?,?\s+and retroactive dates\b/i.test(text) || /\bannual premium\s*\(all coverage parts?\)\b/i.test(text) || /\berp option\b/i.test(text) || /\bproducer\b[\s\S]{0,240}\blicense\b/i.test(text);
4840
5656
  }
4841
5657
  function looksLikeDeclarationsStart(node) {
4842
- const title = cleanText(node.title, "");
5658
+ const title = cleanText2(node.title, "");
4843
5659
  const text = sourceNodeText(node);
4844
5660
  if (/\b(important notice|privacy notice|ofac advisory|terrorism risk insurance act|how to report a claim)\b/i.test(text)) {
4845
5661
  return false;
4846
5662
  }
4847
- return /^declarations?$/i.test(title) || /\bdeclarations?\s+(page|schedule|section)\b/i.test(text) || /^declarations?\b/i.test(cleanText(node.textExcerpt, ""));
5663
+ return /^declarations?$/i.test(title) || /\bdeclarations?\s+(page|schedule|section)\b/i.test(text) || /^declarations?\b/i.test(cleanText2(node.textExcerpt, ""));
4848
5664
  }
4849
5665
  function looksLikeDeclarationsContinuation(node) {
4850
5666
  const text = sourceNodeText(node);
@@ -4852,7 +5668,7 @@ function looksLikeDeclarationsContinuation(node) {
4852
5668
  }
4853
5669
  function looksLikePolicyFormStart(node) {
4854
5670
  const text = sourceNodeText(node);
4855
- const excerpt = cleanText(node.textExcerpt, "");
5671
+ const excerpt = cleanText2(node.textExcerpt, "");
4856
5672
  if (isAdministrativeNoticeNode(node) || looksLikeDeclarationsStart(node)) return false;
4857
5673
  return /\bpolicy form\b/i.test(node.title) || /^policy\s+form\b/i.test(excerpt) || /\btechnology errors?\s*&?\s*omissions\b/i.test(text) && /\bplease read this entire policy carefully\b/i.test(text) || /\bsection\s+[IVX0-9]+\s*[—-]\s*(insuring agreements?|definitions?|exclusions?|conditions?)\b/i.test(text) || /\bform\s+[A-Z]{2,}-[A-Z0-9-]+\s+\d{2}\s+\d{2}\b/i.test(text);
4858
5674
  }
@@ -4941,7 +5757,7 @@ function applySemanticPageGrouping(sourceTree) {
4941
5757
  return {
4942
5758
  ...nextNode,
4943
5759
  title: "Declarations",
4944
- description: cleanText([nextNode.description, "Declarations"].join(" "), "Declarations"),
5760
+ description: cleanText2([nextNode.description, "Declarations"].join(" "), "Declarations"),
4945
5761
  metadata: { ...nextNode.metadata, organizerRepair: "semantic_page_grouping" }
4946
5762
  };
4947
5763
  }
@@ -4949,7 +5765,7 @@ function applySemanticPageGrouping(sourceTree) {
4949
5765
  return {
4950
5766
  ...nextNode,
4951
5767
  title: "Policy Form",
4952
- description: cleanText([nextNode.description, "Policy Form"].join(" "), "Policy Form"),
5768
+ description: cleanText2([nextNode.description, "Policy Form"].join(" "), "Policy Form"),
4953
5769
  metadata: { ...nextNode.metadata, organizerRepair: "semantic_page_grouping" }
4954
5770
  };
4955
5771
  }
@@ -5217,7 +6033,7 @@ function isTitleBlockNode(node) {
5217
6033
  return metadataText(node, "organizer") === "title_block" || metadataText(node, "elementType") === "title" || metadataText(node, "sourceUnit") === "title";
5218
6034
  }
5219
6035
  function isRejectableSectionHeading(text, container) {
5220
- const normalized = cleanText(text, "");
6036
+ const normalized = cleanText2(text, "");
5221
6037
  if (!normalized) return true;
5222
6038
  if (normalized.length > 160) return true;
5223
6039
  if (/^page\s+\d+$/i.test(normalized)) return true;
@@ -5233,7 +6049,7 @@ function isRejectableSectionHeading(text, container) {
5233
6049
  }
5234
6050
  function sectionHeadingTitle(node, container) {
5235
6051
  if (!isTitleBlockNode(node)) return void 0;
5236
- const text = cleanText(node.title || node.textExcerpt, "");
6052
+ const text = cleanText2(node.title || node.textExcerpt, "");
5237
6053
  if (isRejectableSectionHeading(text, container)) return void 0;
5238
6054
  const words = text.split(/\s+/);
5239
6055
  if (words.length > 18) return void 0;
@@ -5307,7 +6123,7 @@ function applyTitleSectionHierarchy(sourceTree) {
5307
6123
  parentId: container.id,
5308
6124
  kind: sectionKindForTitle(heading),
5309
6125
  title: heading,
5310
- description: descriptionWithPages(cleanText([heading, "section"].join(" "), heading), [current, ...descendants]),
6126
+ description: descriptionWithPages(cleanText2([heading, "section"].join(" "), heading), [current, ...descendants]),
5311
6127
  metadata: {
5312
6128
  ...current.metadata,
5313
6129
  organizer: "title_section",
@@ -5355,7 +6171,7 @@ function applyEndorsementGrouping(sourceTree) {
5355
6171
  return {
5356
6172
  ...node,
5357
6173
  kind: "page",
5358
- title: node.pageStart ? `Page ${node.pageStart}` : cleanText(node.title, "Page"),
6174
+ title: node.pageStart ? `Page ${node.pageStart}` : cleanText2(node.title, "Page"),
5359
6175
  metadata: {
5360
6176
  ...node.metadata,
5361
6177
  organizerRepair: "demote_incidental_endorsement_reference"
@@ -5385,7 +6201,7 @@ function applyEndorsementGrouping(sourceTree) {
5385
6201
  ...node,
5386
6202
  kind: "page_group",
5387
6203
  title: "Endorsements",
5388
- description: descriptionWithPages(cleanText(node.description, "Endorsement forms grouped by source order"), byParent.get(node.id) ?? [node]),
6204
+ description: descriptionWithPages(cleanText2(node.description, "Endorsement forms grouped by source order"), byParent.get(node.id) ?? [node]),
5389
6205
  metadata: {
5390
6206
  ...node.metadata,
5391
6207
  sourceTreeVersion: "v3",
@@ -5564,7 +6380,7 @@ function nodesByParent(sourceTree) {
5564
6380
  }
5565
6381
  return byParent;
5566
6382
  }
5567
- function sourceNodeIdsBySpanId(sourceTree) {
6383
+ function sourceNodeIdsBySpanId2(sourceTree) {
5568
6384
  const bySpan = /* @__PURE__ */ new Map();
5569
6385
  for (const node of sourceTree) {
5570
6386
  for (const spanId of node.sourceSpanIds) {
@@ -5576,7 +6392,7 @@ function sourceNodeIdsBySpanId(sourceTree) {
5576
6392
  return bySpan;
5577
6393
  }
5578
6394
  function operationalEvidenceScore(span) {
5579
- const text = cleanText([
6395
+ const text = cleanText2([
5580
6396
  span.text,
5581
6397
  span.formNumber,
5582
6398
  span.sourceUnit,
@@ -5589,6 +6405,9 @@ function operationalEvidenceScore(span) {
5589
6405
  if (span.metadata?.elementType === "title") score += 4;
5590
6406
  if (span.sourceUnit === "page") score -= 3;
5591
6407
  if (/\b(policy\s*(number|period|term)|effective date|expiration date|expiry date|named insured|insurer|carrier|security|broker|producer|premium|total due)\b/i.test(text)) score += 12;
6408
+ if (/\b(mailing address|business address|address|managing general (?:agent|underwriter)|mga|administrator|description of operations|operations description|nature of business|business description)\b/i.test(text)) score += 12;
6409
+ if (/\b\d{1,6}\s+[A-Z0-9][^\n,]{1,80}\b(?:street|st|avenue|ave|road|rd|boulevard|blvd|drive|dr|lane|ln|way|court|ct|highway|hwy)\b/i.test(text)) score += 10;
6410
+ if (/\b[A-Za-z][A-Za-z .'-]+,\s*[A-Z]{2}\s+\d{5}(?:-\d{4})?\b/.test(text)) score += 10;
5592
6411
  if (/\b(coverage part|limit(?:s)? of liability|deductible|retention|retroactive date|aggregate|sublimit|sub-limit|each claim|each loss|each occurrence|coinsurance)\b/i.test(text)) score += 14;
5593
6412
  if (/\bendorsement\s+(?:no\.?|number|#)?\s*[A-Z0-9]|forms? and endorsements?|attached at inception|schedule\b/i.test(text)) score += 8;
5594
6413
  if (/\bitem\s+\d+\.?\s*(?:named insured|policy number|policy period|renewal|form of business|coverage parts?|premium|extended reporting|producer|forms? and endorsements?)\b/i.test(text)) score += 10;
@@ -5599,19 +6418,22 @@ function spanTableId(span) {
5599
6418
  return span.table?.tableId ?? span.metadata?.tableId;
5600
6419
  }
5601
6420
  function isTableCellSpan(span) {
5602
- return spanSourceUnit(span) === "table_cell";
6421
+ return spanSourceUnit2(span) === "table_cell";
5603
6422
  }
5604
6423
  function isOperationalEvidenceAnchor(span) {
5605
- const sourceUnit3 = spanSourceUnit(span);
6424
+ const sourceUnit3 = spanSourceUnit2(span);
5606
6425
  if (sourceUnit3 === "table_cell") return false;
5607
6426
  if (sourceUnit3 === "table" || sourceUnit3 === "table_row") return true;
5608
- const text = cleanText([span.text, span.formNumber].filter(Boolean).join(" "), "");
6427
+ const text = cleanText2([span.text, span.formNumber].filter(Boolean).join(" "), "");
5609
6428
  if (!text) return false;
5610
6429
  if (sourceUnit3 === "page") {
5611
- return hasSubstantiveDeclarationsScheduleText(text) || /\b(declarations?|named insured|policy number|policy period|effective date|expiration date|premium|total due|producer)\b/i.test(text);
6430
+ return hasSubstantiveDeclarationsScheduleText(text) || /\b(declarations?|named insured|policy number|policy period|effective date|expiration date|premium|total due|producer|mailing address|mga|administrator|description of operations|nature of business|business description)\b/i.test(text);
5612
6431
  }
5613
6432
  if (/\bitem\s+\d+\.?\s*(?:named insured|policy number|policy period|renewal|form of business|coverage parts?|premium|extended reporting|producer|forms? and endorsements?)\b/i.test(text)) return true;
5614
6433
  if (/\b(policy\s*(number|period)|effective date|expiration date|expiry date|named insured|insurer|carrier|broker|producer|premium|total due)\b/i.test(text)) return true;
6434
+ if (/\b(mailing address|business address|address|managing general (?:agent|underwriter)|mga|administrator|description of operations|operations description|nature of business|business description)\b/i.test(text)) return true;
6435
+ if (/\b\d{1,6}\s+[A-Z0-9][^\n,]{1,80}\b(?:street|st|avenue|ave|road|rd|boulevard|blvd|drive|dr|lane|ln|way|court|ct|highway|hwy)\b/i.test(text)) return true;
6436
+ if (/\b[A-Za-z][A-Za-z .'-]+,\s*[A-Z]{2}\s+\d{5}(?:-\d{4})?\b/.test(text)) return true;
5615
6437
  if (/\b(coverage part|forms? and endorsements?|attached at inception|endorsement\s+(?:no\.?|number|#)?\s*[A-Z0-9])\b/i.test(text)) return true;
5616
6438
  if (/\$[\d,.]+|[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4}|[0-9]{1,2}\s+[A-Za-z]{3,9}\s+[0-9]{4}/.test(text)) return true;
5617
6439
  return false;
@@ -5619,9 +6441,9 @@ function isOperationalEvidenceAnchor(span) {
5619
6441
  function operationalEvidencePages(sourceSpans) {
5620
6442
  const scores = /* @__PURE__ */ new Map();
5621
6443
  for (const span of sourceSpans) {
5622
- const page = spanPageStart(span);
6444
+ const page = spanPageStart2(span);
5623
6445
  if (typeof page !== "number") continue;
5624
- const text = cleanText([span.text, span.formNumber, spanSourceUnit(span)].filter(Boolean).join(" "), "");
6446
+ const text = cleanText2([span.text, span.formNumber, spanSourceUnit2(span)].filter(Boolean).join(" "), "");
5625
6447
  if (!text) continue;
5626
6448
  let score = Math.max(0, operationalEvidenceScore(span));
5627
6449
  if (/\bdeclarations?\s+(page|schedule)?\b/i.test(text)) score += 24;
@@ -5629,6 +6451,7 @@ function operationalEvidencePages(sourceSpans) {
5629
6451
  if (/\bcoverage parts?,?\s+limits? of liability,?\s+deductibles?,?\s+and retroactive dates\b/i.test(text)) score += 24;
5630
6452
  if (/\b(policy\s*(number|period|term)|effective date|expiration date|expiry date|named insured|insurer|carrier|security)\b/i.test(text)) score += 12;
5631
6453
  if (/\b(premium|total due|tax|fee|producer|broker)\b/i.test(text)) score += 10;
6454
+ if (/\b(mailing address|business address|managing general (?:agent|underwriter)|mga|administrator|description of operations|operations description|nature of business|business description)\b/i.test(text)) score += 16;
5632
6455
  if (/\b(endorsement\s+(?:no\.?|number|#)?\s*[A-Z0-9]|attached at inception|forms? and endorsements?)\b/i.test(text)) score += 8;
5633
6456
  if (/\b(definitions?|exclusions?|conditions?|duties in the event|action against|cancellation by)\b/i.test(text)) score -= 12;
5634
6457
  if (score > 0) scores.set(page, (scores.get(page) ?? 0) + score);
@@ -5639,7 +6462,7 @@ function operationalEvidencePages(sourceSpans) {
5639
6462
  }
5640
6463
  function operationalProfileEvidence(sourceTree, sourceSpans) {
5641
6464
  const sorted = [...sourceSpans].sort(
5642
- (left, right) => (spanPageStart(left) ?? Number.MAX_SAFE_INTEGER) - (spanPageStart(right) ?? Number.MAX_SAFE_INTEGER) || (left.location?.charStart ?? Number.MAX_SAFE_INTEGER) - (right.location?.charStart ?? Number.MAX_SAFE_INTEGER) || left.id.localeCompare(right.id)
6465
+ (left, right) => (spanPageStart2(left) ?? Number.MAX_SAFE_INTEGER) - (spanPageStart2(right) ?? Number.MAX_SAFE_INTEGER) || (left.location?.charStart ?? Number.MAX_SAFE_INTEGER) - (right.location?.charStart ?? Number.MAX_SAFE_INTEGER) || left.id.localeCompare(right.id)
5643
6466
  );
5644
6467
  const selectedPages = operationalEvidencePages(sorted);
5645
6468
  const selected = /* @__PURE__ */ new Set();
@@ -5649,7 +6472,7 @@ function operationalProfileEvidence(sourceTree, sourceSpans) {
5649
6472
  const score = operationalEvidenceScore(span);
5650
6473
  if (score < 8) continue;
5651
6474
  if (!isOperationalEvidenceAnchor(span)) continue;
5652
- const page = spanPageStart(span);
6475
+ const page = spanPageStart2(span);
5653
6476
  if (selectedPages.size > 0 && typeof page === "number" && !selectedPages.has(page) && score < 30) continue;
5654
6477
  const tableId2 = spanTableId(span);
5655
6478
  if (tableId2 && !isTableCellSpan(span)) selectedTableIds.add(tableId2);
@@ -5657,9 +6480,9 @@ function operationalProfileEvidence(sourceTree, sourceSpans) {
5657
6480
  for (let offset = -neighborWindow; offset <= neighborWindow; offset += 1) {
5658
6481
  const neighborIndex = index + offset;
5659
6482
  const neighbor = sorted[neighborIndex];
5660
- if (!neighbor || spanPageStart(neighbor) !== page) continue;
6483
+ if (!neighbor || spanPageStart2(neighbor) !== page) continue;
5661
6484
  if (selectedPages.size > 0 && typeof page === "number" && !selectedPages.has(page) && operationalEvidenceScore(neighbor) < 30) continue;
5662
- const neighborText = cleanText(neighbor.text, "");
6485
+ const neighborText = cleanText2(neighbor.text, "");
5663
6486
  if (!neighborText || neighborText.length > 3e3) continue;
5664
6487
  selected.add(neighborIndex);
5665
6488
  }
@@ -5668,31 +6491,31 @@ function operationalProfileEvidence(sourceTree, sourceSpans) {
5668
6491
  sorted.forEach((span, index) => {
5669
6492
  const tableId2 = spanTableId(span);
5670
6493
  if (!tableId2 || !selectedTableIds.has(tableId2) || isTableCellSpan(span)) return;
5671
- const text = cleanText(span.text, "");
6494
+ const text = cleanText2(span.text, "");
5672
6495
  if (text && text.length <= 3e3) selected.add(index);
5673
6496
  });
5674
6497
  }
5675
- const nodeIdsBySpanId = sourceNodeIdsBySpanId(sourceTree);
6498
+ const nodeIdsBySpanId = sourceNodeIdsBySpanId2(sourceTree);
5676
6499
  const seenText = /* @__PURE__ */ new Set();
5677
6500
  const entries = [...selected].sort((left, right) => left - right).map((index) => sorted[index]).filter((span) => !isTableCellSpan(span)).flatMap((span) => {
5678
- const text = cleanText(span.text, "");
6501
+ const text = cleanText2(span.text, "");
5679
6502
  if (!text) return [];
5680
- const key = `${spanPageStart(span) ?? "na"}:${text.toLowerCase().slice(0, 240)}`;
6503
+ const key = `${spanPageStart2(span) ?? "na"}:${text.toLowerCase().slice(0, 240)}`;
5681
6504
  if (seenText.has(key)) return [];
5682
6505
  seenText.add(key);
5683
6506
  return [{
5684
6507
  sourceSpanId: span.id,
5685
6508
  sourceNodeIds: [...new Set(nodeIdsBySpanId.get(span.id) ?? [])].slice(0, 4),
5686
- pageStart: spanPageStart(span),
5687
- pageEnd: spanPageEnd(span),
5688
- sourceUnit: spanSourceUnit(span),
6509
+ pageStart: spanPageStart2(span),
6510
+ pageEnd: spanPageEnd2(span),
6511
+ sourceUnit: spanSourceUnit2(span),
5689
6512
  formNumber: span.formNumber,
5690
6513
  text: text.slice(0, span.sourceUnit === "page" ? 900 : 700)
5691
6514
  }];
5692
6515
  });
5693
6516
  const detailEntries = entries.filter((entry) => entry.sourceUnit !== "page");
5694
6517
  const pageEntries = entries.filter((entry) => entry.sourceUnit === "page");
5695
- return [...detailEntries.slice(0, 80), ...pageEntries.slice(0, 8)];
6518
+ return [...detailEntries, ...pageEntries];
5696
6519
  }
5697
6520
  function sourceTreeRootId(sourceTree) {
5698
6521
  return sourceTree.find((node) => node.kind === "document")?.id;
@@ -5703,7 +6526,7 @@ function operationalProfilePromptNodes(sourceTree) {
5703
6526
  return true;
5704
6527
  }
5705
6528
  const text = [node.title, node.path, node.description, node.textExcerpt].filter(Boolean).join(" ");
5706
- return /\b(policy\s*(number|period)|named insured|insurer|carrier|broker|producer|premium|coverage|limit|liability|deductible|retention|retroactive|aggregate|sublimit|sub-limit|endorsement)\b/i.test(text);
6529
+ return /\b(policy\s*(number|period)|named insured|insurer|carrier|broker|producer|managing general (?:agent|underwriter)|mga|administrator|mailing address|description of operations|operations description|nature of business|business description|premium|coverage|limit|liability|deductible|retention|retroactive|aggregate|sublimit|sub-limit|endorsement)\b/i.test(text);
5707
6530
  }).slice(0, 420);
5708
6531
  }
5709
6532
  function emptyOperationalProfile() {
@@ -5712,6 +6535,9 @@ function emptyOperationalProfile() {
5712
6535
  linesOfBusiness: ["UN"],
5713
6536
  declarationFacts: [],
5714
6537
  coverages: [],
6538
+ coverageSchedules: [],
6539
+ premiumBreakdown: [],
6540
+ taxesAndFees: [],
5715
6541
  parties: [],
5716
6542
  endorsementSupport: [],
5717
6543
  sourceNodeIds: [],
@@ -5727,7 +6553,8 @@ function buildOperationalProfilePrompt(sourceTree, sourceSpans) {
5727
6553
  return `Extract a source-backed operational profile for an insurance policy.
5728
6554
 
5729
6555
  Return only high-value operational facts needed for policy lists, Q&A, compliance, and certificate generation:
5730
- - policy number, named insured, insurer/carrier/security, broker/producer, policy period, retroactive date, premium
6556
+ - policy number, named insured, insurer/carrier/security, broker/producer, policy period, retroactive date, premium, and the insured's description of operations
6557
+ - parties[] rows for named insured, producer/broker, insurer/carrier, and MGA/administrator identities and their mailing addresses
5731
6558
  - source-backed declarationFacts for named-insured identity details: named insured, mailing address, DBA, entity type, tax ID/FEIN, additional named insureds, and other durable declaration-page identity facts
5732
6559
  - coverage units with their own nested limit terms, deductibles/retentions, retroactive dates, premiums, and form references
5733
6560
  - coverage type labels
@@ -5739,6 +6566,9 @@ Rules:
5739
6566
  - If a value is not directly supported, omit it.
5740
6567
  - Prefer declarations, schedules, premium tables, and endorsement schedules over generic policy wording.
5741
6568
  - Put named-insured mailing address in declarationFacts[] with field "mailingAddress", valueKind "address", a user-facing value string, and structured address fields when present. Do not put producer, broker, insurer, mortgagee, loss-payee, or certificate-holder addresses in mailingAddress.
6569
+ - Put every source-backed policy party in parties[] using only these canonical roles: "named_insured", "producer", "broker", "insurer", "carrier", "mga", or "administrator". Keep producer/broker, insurer/carrier, and MGA/administrator addresses policy-scoped in parties[]; never represent them as the named-insured mailingAddress declaration fact.
6570
+ - When a party's address is present, return its available street1, street2, city, state, zip, country, and formatted parts under parties[].address. Partial addresses are allowed in parties[], but never guess a missing component. The party row must cite the source node or source span that supports both the identity and address.
6571
+ - Put the insured's directly stated business or operations description in operationsDescription. Do not synthesize it from coverages, industry inference, website research, or generic policy wording.
5742
6572
  - Put DBA or trade name in declarationFacts[] with field "dba"; entity/legal form in field "entityType"; FEIN/tax ID in field "taxId"; each additional named insured in field "additionalNamedInsured".
5743
6573
  - For effective, expiration, retroactive, and other date fields, return a normalized YYYY-MM-DD value when the source date is unambiguous, including month-name dates such as "20 Feb 2026". Do not emit fragmented date text such as "20 2 2026".
5744
6574
  - For broker/producer, extract the agency or company legal name, not the license role, credential, or type. In a block like "Bayshore Insurance Brokers, LLC" followed by "Surplus Lines Broker - CA License No. ...", broker.value must be "Bayshore Insurance Brokers, LLC"; the surplus-lines role and license number are not the broker name.
@@ -5808,13 +6638,6 @@ function valueOf(profile, key) {
5808
6638
  }
5809
6639
  return String(value.value);
5810
6640
  }
5811
- function provenanceOf(value) {
5812
- if (!value?.sourceSpanIds.length) return void 0;
5813
- return {
5814
- sourceSpanIds: value.sourceSpanIds,
5815
- ...value.sourceNodeIds[0] ? { documentNodeId: value.sourceNodeIds[0] } : {}
5816
- };
5817
- }
5818
6641
  function provenanceFromIds(sourceSpanIds, sourceNodeIds) {
5819
6642
  if (sourceSpanIds.length === 0) return void 0;
5820
6643
  return {
@@ -5822,6 +6645,33 @@ function provenanceFromIds(sourceSpanIds, sourceNodeIds) {
5822
6645
  ...sourceNodeIds[0] ? { documentNodeId: sourceNodeIds[0] } : {}
5823
6646
  };
5824
6647
  }
6648
+ function combinedProvenance(...values) {
6649
+ const sourceSpanIds = [...new Set(values.flatMap((value) => value?.sourceSpanIds ?? []))];
6650
+ const sourceNodeIds = [...new Set(values.flatMap((value) => value?.sourceNodeIds ?? []))];
6651
+ return provenanceFromIds(sourceSpanIds, sourceNodeIds);
6652
+ }
6653
+ function firstOperationalParty(profile, roles) {
6654
+ const candidates = roles.flatMap(
6655
+ (role) => profile.parties.filter((candidate) => candidate.role === role && candidate.name.trim())
6656
+ );
6657
+ return candidates.find((candidate) => candidate.address) ?? candidates[0];
6658
+ }
6659
+ function completeOperationalAddress(address) {
6660
+ if (!address?.street1 || !address.city || !address.state || !address.zip) return void 0;
6661
+ return {
6662
+ street1: address.street1,
6663
+ street2: address.street2,
6664
+ city: address.city,
6665
+ state: address.state,
6666
+ zip: address.zip,
6667
+ country: address.country
6668
+ };
6669
+ }
6670
+ function sourceBackedAddressFromParty(party) {
6671
+ const address = completeOperationalAddress(party?.address);
6672
+ const provenance = party ? provenanceFromIds(party.sourceSpanIds, party.sourceNodeIds) : void 0;
6673
+ return address && provenance ? { ...address, ...provenance } : void 0;
6674
+ }
5825
6675
  function declarationFactsByField(profile, field) {
5826
6676
  return profile.declarationFacts.filter((fact) => fact.field === field && fact.value.trim());
5827
6677
  }
@@ -5843,7 +6693,7 @@ function sourceBackedAddressFromFact(fact) {
5843
6693
  };
5844
6694
  }
5845
6695
  function normalizedEntityType(value) {
5846
- const normalized = cleanText(value, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
6696
+ const normalized = cleanText2(value, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
5847
6697
  if (normalized === "inc" || normalized === "incorporated" || normalized === "c_corporation" || normalized === "s_corporation") {
5848
6698
  return "corporation";
5849
6699
  }
@@ -5869,19 +6719,83 @@ function declarationFieldName(fact) {
5869
6719
  if (fact.field === "additionalNamedInsured") return "additionalNamedInsured";
5870
6720
  return fact.field;
5871
6721
  }
6722
+ function scheduleValueMap(item) {
6723
+ return new Map(item.values.map((value) => [
6724
+ value.label.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim(),
6725
+ value.value
6726
+ ]));
6727
+ }
6728
+ function firstScheduleValue(values, labels) {
6729
+ for (const label of labels) {
6730
+ const direct = values.get(label);
6731
+ if (direct) return direct;
6732
+ const match = [...values.entries()].find(([key]) => key.includes(label));
6733
+ if (match?.[1]) return match[1];
6734
+ }
6735
+ return void 0;
6736
+ }
6737
+ function positiveInteger2(value) {
6738
+ const parsed = Number.parseInt(value?.match(/\d+/)?.[0] ?? "", 10);
6739
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
6740
+ }
6741
+ function structuredVehicles(profile) {
6742
+ return (profile.coverageSchedules ?? []).filter((schedule) => schedule.kind === "vehicle").flatMap((schedule) => schedule.items).flatMap((item, index) => {
6743
+ const values = scheduleValueMap(item);
6744
+ const year = positiveInteger2(firstScheduleValue(values, ["year", "model year"]));
6745
+ const make = firstScheduleValue(values, ["make"]);
6746
+ const model = firstScheduleValue(values, ["model"]);
6747
+ const vin = firstScheduleValue(values, ["vin", "vehicle identification number"]);
6748
+ if (!year || !make || !model || !vin) return [];
6749
+ return [{
6750
+ number: positiveInteger2(item.label) ?? index + 1,
6751
+ year,
6752
+ make,
6753
+ model,
6754
+ vin
6755
+ }];
6756
+ });
6757
+ }
6758
+ function structuredLocations(profile) {
6759
+ return (profile.coverageSchedules ?? []).filter((schedule) => schedule.kind === "location" || schedule.kind === "property").flatMap((schedule) => schedule.items).flatMap((item, index) => {
6760
+ const values = scheduleValueMap(item);
6761
+ const street1 = firstScheduleValue(values, ["street 1", "street address", "address"]);
6762
+ const city = firstScheduleValue(values, ["city"]);
6763
+ const state = firstScheduleValue(values, ["state", "province"]);
6764
+ const zip = firstScheduleValue(values, ["zip", "postal code"]);
6765
+ if (!street1 || !city || !state || !zip) return [];
6766
+ return [{
6767
+ number: positiveInteger2(item.label) ?? index + 1,
6768
+ address: {
6769
+ street1,
6770
+ city,
6771
+ state,
6772
+ zip,
6773
+ country: firstScheduleValue(values, ["country"])
6774
+ },
6775
+ description: item.description,
6776
+ buildingValue: firstScheduleValue(values, ["building value", "building"]),
6777
+ contentsValue: firstScheduleValue(values, ["contents value", "contents"])
6778
+ }];
6779
+ });
6780
+ }
5872
6781
  function materializeDocument(params) {
5873
6782
  const profile = params.operationalProfile;
5874
6783
  const policyNumber = valueOf(profile, "policyNumber") ?? "Unknown";
5875
- const insuredName = valueOf(profile, "namedInsured") ?? "Unknown";
5876
- const carrier = valueOf(profile, "insurer") ?? "Unknown";
6784
+ const namedInsuredParty = firstOperationalParty(profile, ["named_insured"]);
6785
+ const insurerParty = firstOperationalParty(profile, ["insurer", "carrier"]);
6786
+ const producerParty = firstOperationalParty(profile, ["producer", "broker"]);
6787
+ const insuredName = valueOf(profile, "namedInsured") ?? namedInsuredParty?.name ?? "Unknown";
6788
+ const carrier = valueOf(profile, "insurer") ?? insurerParty?.name ?? "Unknown";
5877
6789
  const effectiveDate = valueOf(profile, "effectiveDate") ?? "Unknown";
5878
6790
  const expirationDate = valueOf(profile, "expirationDate") ?? "Unknown";
5879
6791
  const premium = valueOf(profile, "premium");
5880
- const insurerProvenance = provenanceOf(profile.insurer);
5881
- const broker = valueOf(profile, "broker");
5882
- const brokerProvenance = provenanceOf(profile.broker);
6792
+ const insurerProvenance = combinedProvenance(profile.insurer, insurerParty);
6793
+ const insurerAddress = completeOperationalAddress(insurerParty?.address);
6794
+ const broker = valueOf(profile, "broker") ?? producerParty?.name;
6795
+ const brokerProvenance = combinedProvenance(profile.broker, producerParty);
6796
+ const producerAddress = completeOperationalAddress(producerParty?.address);
5883
6797
  const mailingAddressFact = firstDeclarationFact(profile, "mailingAddress");
5884
- const insuredAddress = sourceBackedAddressFromFact(mailingAddressFact);
6798
+ const insuredAddress = sourceBackedAddressFromParty(namedInsuredParty) ?? sourceBackedAddressFromFact(mailingAddressFact);
5885
6799
  const insuredDba = firstDeclarationFact(profile, "dba")?.value;
5886
6800
  const insuredEntityType = normalizedEntityType(firstDeclarationFact(profile, "entityType")?.value);
5887
6801
  const insuredFein = firstDeclarationFact(profile, "taxId")?.value;
@@ -5908,6 +6822,30 @@ function materializeDocument(params) {
5908
6822
  ...coverage.limits?.length ? coverage.limits.map((term) => `${term.label}: ${term.value}`) : [coverage.limit, coverage.deductible, coverage.premium]
5909
6823
  ].filter(Boolean).join(" | ")
5910
6824
  }));
6825
+ const coverageSchedules = (profile.coverageSchedules ?? []).map((schedule) => ({
6826
+ ...schedule,
6827
+ items: schedule.items.map((item) => ({ ...item }))
6828
+ }));
6829
+ const premiumBreakdown = (profile.premiumBreakdown ?? []).map((row) => ({
6830
+ line: row.line,
6831
+ amount: row.amount,
6832
+ amountValue: row.amountValue,
6833
+ documentNodeId: row.sourceNodeIds[0],
6834
+ sourceSpanIds: row.sourceSpanIds
6835
+ }));
6836
+ const taxesAndFees = (profile.taxesAndFees ?? []).map((row) => ({
6837
+ name: row.name,
6838
+ amount: row.amount,
6839
+ amountValue: row.amountValue,
6840
+ type: row.type,
6841
+ description: row.description,
6842
+ documentNodeId: row.sourceNodeIds[0],
6843
+ sourceSpanIds: row.sourceSpanIds
6844
+ }));
6845
+ const totalCost = valueOf(profile, "totalCost");
6846
+ const totalCostAmount = totalCost ? Number(totalCost.replace(/[^0-9.-]/g, "")) : void 0;
6847
+ const vehicles = structuredVehicles(profile);
6848
+ const locations = structuredLocations(profile);
5911
6849
  const documentOutline = sourceTreeToOutline(params.sourceTree);
5912
6850
  const documentMetadata = {
5913
6851
  sourceTreeVersion: "v3",
@@ -5940,15 +6878,29 @@ function materializeDocument(params) {
5940
6878
  security: carrier,
5941
6879
  insuredName,
5942
6880
  premium,
6881
+ ...premiumBreakdown.length > 0 ? { premiumBreakdown } : {},
6882
+ ...taxesAndFees.length > 0 ? { taxesAndFees } : {},
6883
+ ...totalCost ? { totalCost } : {},
6884
+ ...typeof totalCostAmount === "number" && Number.isFinite(totalCostAmount) ? { totalCostAmount } : {},
5943
6885
  insuredDba,
5944
6886
  insuredAddress,
5945
6887
  insuredEntityType,
5946
6888
  insuredFein,
5947
6889
  ...additionalNamedInsureds.length > 0 ? { additionalNamedInsureds } : {},
5948
- ...insurerProvenance ? { insurer: { legalName: carrier, ...insurerProvenance } } : {},
6890
+ ...insurerProvenance ? {
6891
+ insurer: {
6892
+ legalName: carrier,
6893
+ ...insurerAddress ? { address: insurerAddress } : {},
6894
+ ...insurerProvenance
6895
+ }
6896
+ } : {},
5949
6897
  ...broker && brokerProvenance ? {
5950
6898
  brokerAgency: broker,
5951
- producer: { agencyName: broker, ...brokerProvenance }
6899
+ producer: {
6900
+ agencyName: broker,
6901
+ ...producerAddress ? { address: producerAddress } : {},
6902
+ ...brokerProvenance
6903
+ }
5952
6904
  } : {},
5953
6905
  linesOfBusiness: profile.linesOfBusiness,
5954
6906
  formInventory: params.formInventory.filter((form) => typeof form.formNumber === "string" && form.formNumber.trim().length > 0).map((form) => ({
@@ -5960,6 +6912,9 @@ function materializeDocument(params) {
5960
6912
  pageEnd: form.pageEnd
5961
6913
  })),
5962
6914
  coverages,
6915
+ ...coverageSchedules.length > 0 ? { coverageSchedules } : {},
6916
+ ...vehicles.length > 0 ? { vehicles } : {},
6917
+ ...locations.length > 0 ? { locations } : {},
5963
6918
  documentMetadata,
5964
6919
  documentOutline,
5965
6920
  declarations: {
@@ -6091,6 +7046,7 @@ async function runSourceTreeExtraction(params) {
6091
7046
  };
6092
7047
  const emptyProfile = emptyOperationalProfile();
6093
7048
  let operationalProfile = emptyProfile;
7049
+ let coverageRecovery = disabledCoverageRecoveryDiagnostics();
6094
7050
  try {
6095
7051
  const validNodeIds = new Set(sourceTree.map((node) => node.id));
6096
7052
  const validSpanIds = new Set(sourceSpans.map((span) => span.id));
@@ -6128,6 +7084,21 @@ async function runSourceTreeExtraction(params) {
6128
7084
  } catch (error) {
6129
7085
  warnings.push(`Operational profile model pass failed; coverage rows omitted (${error instanceof Error ? error.message : String(error)})`);
6130
7086
  }
7087
+ if (params.coverageRecovery?.enabled) {
7088
+ const recovery = await recoverOperationalProfileCoverage({
7089
+ sourceTree,
7090
+ sourceSpans,
7091
+ operationalProfile,
7092
+ generateObject: params.generateObject,
7093
+ providerOptions: params.providerOptions,
7094
+ resolveBudget: params.resolveBudget,
7095
+ trackUsage: localTrack,
7096
+ log: params.log
7097
+ });
7098
+ operationalProfile = recovery.operationalProfile;
7099
+ coverageRecovery = recovery.diagnostics;
7100
+ warnings.push(...coverageRecovery.warnings);
7101
+ }
6131
7102
  if (operationalProfile.coverages.length > 0) {
6132
7103
  try {
6133
7104
  const cleanup = await cleanupOperationalCoverageSchedules({
@@ -6160,6 +7131,7 @@ async function runSourceTreeExtraction(params) {
6160
7131
  sourceChunks: chunkSourceSpans(sourceSpans),
6161
7132
  formInventory: formHints,
6162
7133
  operationalProfile,
7134
+ coverageRecovery,
6163
7135
  document,
6164
7136
  chunks: [],
6165
7137
  warnings: [...warnings, ...operationalProfile.warnings],
@@ -6262,7 +7234,8 @@ function createExtractor(config) {
6262
7234
  providerOptions: activeProviderOptions,
6263
7235
  resolveBudget,
6264
7236
  trackUsage,
6265
- log
7237
+ log,
7238
+ coverageRecovery: options?.coverageRecovery
6266
7239
  });
6267
7240
  const sourceTreeFormInventory = v3.formInventory.flatMap((form) => {
6268
7241
  const formNumber = typeof form.formNumber === "string" ? form.formNumber.trim() : "";
@@ -6302,6 +7275,7 @@ function createExtractor(config) {
6302
7275
  sourceChunks: v3.sourceChunks,
6303
7276
  sourceTree: v3.sourceTree,
6304
7277
  operationalProfile: v3.operationalProfile,
7278
+ coverageRecovery: v3.coverageRecovery,
6305
7279
  warnings: v3.warnings,
6306
7280
  tokenUsage: v3.tokenUsage,
6307
7281
  usageReporting: v3.usageReporting,
@@ -7716,8 +8690,8 @@ Respond with JSON only:
7716
8690
  }`;
7717
8691
 
7718
8692
  // src/schemas/application.ts
7719
- import { z as z24 } from "zod";
7720
- var FieldTypeSchema = z24.enum([
8693
+ import { z as z25 } from "zod";
8694
+ var FieldTypeSchema = z25.enum([
7721
8695
  "text",
7722
8696
  "numeric",
7723
8697
  "currency",
@@ -7726,223 +8700,223 @@ var FieldTypeSchema = z24.enum([
7726
8700
  "table",
7727
8701
  "declaration"
7728
8702
  ]);
7729
- var ApplicationFieldSchema = z24.object({
7730
- id: z24.string(),
7731
- label: z24.string(),
7732
- section: z24.string(),
8703
+ var ApplicationFieldSchema = z25.object({
8704
+ id: z25.string(),
8705
+ label: z25.string(),
8706
+ section: z25.string(),
7733
8707
  fieldType: FieldTypeSchema,
7734
- required: z24.boolean(),
7735
- options: z24.array(z24.string()).optional(),
7736
- columns: z24.array(z24.string()).optional(),
7737
- requiresExplanationIfYes: z24.boolean().optional(),
7738
- condition: z24.object({
7739
- dependsOn: z24.string(),
7740
- whenValue: z24.string()
8708
+ required: z25.boolean(),
8709
+ options: z25.array(z25.string()).optional(),
8710
+ columns: z25.array(z25.string()).optional(),
8711
+ requiresExplanationIfYes: z25.boolean().optional(),
8712
+ condition: z25.object({
8713
+ dependsOn: z25.string(),
8714
+ whenValue: z25.string()
7741
8715
  }).optional(),
7742
- value: z24.string().optional(),
7743
- source: z24.string().optional().describe("Where the value came from: auto-fill, user, lookup"),
7744
- confidence: z24.enum(["confirmed", "high", "medium", "low"]).optional(),
7745
- sourceSpanIds: z24.array(z24.string()).optional().describe("Stable source spans that support the field value or field anchor"),
7746
- userSourceSpanIds: z24.array(z24.string()).optional().describe("Message or attachment spans that support user-provided values"),
7747
- pageNumber: z24.number().int().positive().optional().describe("Application page where the field label or anchor appears"),
7748
- fieldAnchorId: z24.string().optional().describe("Stable field anchor ID derived from page, section, label, and form metadata"),
7749
- acroFormName: z24.string().optional().describe("Native PDF AcroForm field name when available"),
7750
- validationStatus: z24.enum(["valid", "needs_review", "unsupported", "missing"]).optional()
7751
- });
7752
- var ApplicationQuestionConditionSchema = z24.object({
7753
- dependsOn: z24.string(),
7754
- operator: z24.enum(["equals", "not_equals", "in", "not_in", "exists"]).optional(),
7755
- value: z24.string().optional(),
7756
- whenValue: z24.string().optional(),
7757
- values: z24.array(z24.string()).optional()
7758
- });
7759
- var ApplicationRepeatSchema = z24.object({
7760
- min: z24.number().int().nonnegative().optional(),
7761
- max: z24.number().int().positive().optional(),
7762
- label: z24.string().optional()
7763
- });
7764
- var ApplicationQuestionNodeSchema = z24.lazy(
7765
- () => z24.object({
7766
- id: z24.string(),
7767
- nodeType: z24.enum(["group", "question", "repeat_group", "table"]),
7768
- fieldId: z24.string().optional(),
7769
- fieldPath: z24.string().optional(),
7770
- parentId: z24.string().optional(),
7771
- order: z24.number().int().nonnegative().optional(),
7772
- label: z24.string(),
7773
- section: z24.string().optional(),
8716
+ value: z25.string().optional(),
8717
+ source: z25.string().optional().describe("Where the value came from: auto-fill, user, lookup"),
8718
+ confidence: z25.enum(["confirmed", "high", "medium", "low"]).optional(),
8719
+ sourceSpanIds: z25.array(z25.string()).optional().describe("Stable source spans that support the field value or field anchor"),
8720
+ userSourceSpanIds: z25.array(z25.string()).optional().describe("Message or attachment spans that support user-provided values"),
8721
+ pageNumber: z25.number().int().positive().optional().describe("Application page where the field label or anchor appears"),
8722
+ fieldAnchorId: z25.string().optional().describe("Stable field anchor ID derived from page, section, label, and form metadata"),
8723
+ acroFormName: z25.string().optional().describe("Native PDF AcroForm field name when available"),
8724
+ validationStatus: z25.enum(["valid", "needs_review", "unsupported", "missing"]).optional()
8725
+ });
8726
+ var ApplicationQuestionConditionSchema = z25.object({
8727
+ dependsOn: z25.string(),
8728
+ operator: z25.enum(["equals", "not_equals", "in", "not_in", "exists"]).optional(),
8729
+ value: z25.string().optional(),
8730
+ whenValue: z25.string().optional(),
8731
+ values: z25.array(z25.string()).optional()
8732
+ });
8733
+ var ApplicationRepeatSchema = z25.object({
8734
+ min: z25.number().int().nonnegative().optional(),
8735
+ max: z25.number().int().positive().optional(),
8736
+ label: z25.string().optional()
8737
+ });
8738
+ var ApplicationQuestionNodeSchema = z25.lazy(
8739
+ () => z25.object({
8740
+ id: z25.string(),
8741
+ nodeType: z25.enum(["group", "question", "repeat_group", "table"]),
8742
+ fieldId: z25.string().optional(),
8743
+ fieldPath: z25.string().optional(),
8744
+ parentId: z25.string().optional(),
8745
+ order: z25.number().int().nonnegative().optional(),
8746
+ label: z25.string(),
8747
+ section: z25.string().optional(),
7774
8748
  fieldType: FieldTypeSchema.optional(),
7775
- required: z24.boolean().optional(),
7776
- prompt: z24.string().optional(),
7777
- options: z24.array(z24.string()).optional(),
7778
- columns: z24.array(z24.string()).optional(),
8749
+ required: z25.boolean().optional(),
8750
+ prompt: z25.string().optional(),
8751
+ options: z25.array(z25.string()).optional(),
8752
+ columns: z25.array(z25.string()).optional(),
7779
8753
  condition: ApplicationQuestionConditionSchema.optional(),
7780
8754
  repeat: ApplicationRepeatSchema.optional(),
7781
- children: z24.array(ApplicationQuestionNodeSchema).optional()
8755
+ children: z25.array(ApplicationQuestionNodeSchema).optional()
7782
8756
  })
7783
8757
  );
7784
- var ApplicationQuestionGraphSchema = z24.object({
7785
- id: z24.string(),
7786
- version: z24.string(),
7787
- title: z24.string().optional(),
7788
- applicationType: z24.string().nullable().optional(),
7789
- source: z24.enum(["pdf", "manual", "imported", "generated"]).default("generated"),
7790
- rootNodeIds: z24.array(z24.string()).optional(),
7791
- nodes: z24.array(ApplicationQuestionNodeSchema)
7792
- });
7793
- var ApplicationTemplateSchema = z24.object({
7794
- id: z24.string(),
7795
- version: z24.string(),
7796
- title: z24.string(),
7797
- applicationType: z24.string().nullable().optional(),
8758
+ var ApplicationQuestionGraphSchema = z25.object({
8759
+ id: z25.string(),
8760
+ version: z25.string(),
8761
+ title: z25.string().optional(),
8762
+ applicationType: z25.string().nullable().optional(),
8763
+ source: z25.enum(["pdf", "manual", "imported", "generated"]).default("generated"),
8764
+ rootNodeIds: z25.array(z25.string()).optional(),
8765
+ nodes: z25.array(ApplicationQuestionNodeSchema)
8766
+ });
8767
+ var ApplicationTemplateSchema = z25.object({
8768
+ id: z25.string(),
8769
+ version: z25.string(),
8770
+ title: z25.string(),
8771
+ applicationType: z25.string().nullable().optional(),
7798
8772
  questionGraph: ApplicationQuestionGraphSchema,
7799
- fields: z24.array(ApplicationFieldSchema).optional()
7800
- });
7801
- var ApplicationClassifyResultSchema = z24.object({
7802
- isApplication: z24.boolean(),
7803
- confidence: z24.number().min(0).max(1),
7804
- applicationType: z24.string().nullable()
7805
- });
7806
- var FieldExtractionResultSchema = z24.object({
7807
- fields: z24.array(ApplicationFieldSchema)
7808
- });
7809
- var AutoFillMatchSchema = z24.object({
7810
- fieldId: z24.string(),
7811
- value: z24.string(),
7812
- confidence: z24.enum(["confirmed"]),
7813
- contextKey: z24.string()
7814
- });
7815
- var AutoFillResultSchema = z24.object({
7816
- matches: z24.array(AutoFillMatchSchema)
7817
- });
7818
- var QuestionBatchResultSchema = z24.object({
7819
- batches: z24.array(z24.array(z24.string()).describe("Array of field IDs in this batch"))
7820
- });
7821
- var LookupRequestSchema = z24.object({
7822
- type: z24.string().describe("Type of lookup: 'records', 'website', 'policy'"),
7823
- description: z24.string(),
7824
- url: z24.string().optional(),
7825
- targetFieldIds: z24.array(z24.string())
7826
- });
7827
- var ReplyIntentSchema = z24.object({
7828
- primaryIntent: z24.enum(["answers_only", "question", "lookup_request", "mixed"]),
7829
- hasAnswers: z24.boolean(),
7830
- questionText: z24.string().optional(),
7831
- questionFieldIds: z24.array(z24.string()).optional(),
7832
- lookupRequests: z24.array(LookupRequestSchema).optional()
7833
- });
7834
- var ParsedAnswerSchema = z24.object({
7835
- fieldId: z24.string(),
7836
- value: z24.string(),
7837
- explanation: z24.string().optional()
7838
- });
7839
- var AnswerParsingResultSchema = z24.object({
7840
- answers: z24.array(ParsedAnswerSchema),
7841
- unanswered: z24.array(z24.string()).describe("Field IDs that were not answered")
7842
- });
7843
- var LookupFillSchema = z24.object({
7844
- fieldId: z24.string(),
7845
- value: z24.string(),
7846
- source: z24.string().describe("Specific citable reference, e.g. 'GL Policy #POL-12345 (Hartford)'"),
7847
- sourceSpanIds: z24.array(z24.string()).optional()
8773
+ fields: z25.array(ApplicationFieldSchema).optional()
7848
8774
  });
7849
- var LookupFillResultSchema = z24.object({
7850
- fills: z24.array(LookupFillSchema),
7851
- unfillable: z24.array(z24.string()),
7852
- explanation: z24.string().optional()
7853
- });
7854
- var FlatPdfPlacementSchema = z24.object({
7855
- fieldId: z24.string(),
7856
- page: z24.number(),
7857
- x: z24.number().describe("Percentage from left edge (0-100)"),
7858
- y: z24.number().describe("Percentage from top edge (0-100)"),
7859
- text: z24.string(),
7860
- fontSize: z24.number().optional(),
7861
- isCheckmark: z24.boolean().optional()
7862
- });
7863
- var AcroFormMappingSchema = z24.object({
7864
- fieldId: z24.string(),
7865
- acroFormName: z24.string(),
7866
- value: z24.string()
7867
- });
7868
- var QualityGateStatusSchema = z24.enum(["passed", "warning", "failed"]);
7869
- var QualitySeveritySchema = z24.enum(["info", "warning", "blocking"]);
7870
- var ApplicationQualityIssueSchema = z24.object({
7871
- code: z24.string(),
8775
+ var ApplicationClassifyResultSchema = z25.object({
8776
+ isApplication: z25.boolean(),
8777
+ confidence: z25.number().min(0).max(1),
8778
+ applicationType: z25.string().nullable()
8779
+ });
8780
+ var FieldExtractionResultSchema = z25.object({
8781
+ fields: z25.array(ApplicationFieldSchema)
8782
+ });
8783
+ var AutoFillMatchSchema = z25.object({
8784
+ fieldId: z25.string(),
8785
+ value: z25.string(),
8786
+ confidence: z25.enum(["confirmed"]),
8787
+ contextKey: z25.string()
8788
+ });
8789
+ var AutoFillResultSchema = z25.object({
8790
+ matches: z25.array(AutoFillMatchSchema)
8791
+ });
8792
+ var QuestionBatchResultSchema = z25.object({
8793
+ batches: z25.array(z25.array(z25.string()).describe("Array of field IDs in this batch"))
8794
+ });
8795
+ var LookupRequestSchema = z25.object({
8796
+ type: z25.string().describe("Type of lookup: 'records', 'website', 'policy'"),
8797
+ description: z25.string(),
8798
+ url: z25.string().optional(),
8799
+ targetFieldIds: z25.array(z25.string())
8800
+ });
8801
+ var ReplyIntentSchema = z25.object({
8802
+ primaryIntent: z25.enum(["answers_only", "question", "lookup_request", "mixed"]),
8803
+ hasAnswers: z25.boolean(),
8804
+ questionText: z25.string().optional(),
8805
+ questionFieldIds: z25.array(z25.string()).optional(),
8806
+ lookupRequests: z25.array(LookupRequestSchema).optional()
8807
+ });
8808
+ var ParsedAnswerSchema = z25.object({
8809
+ fieldId: z25.string(),
8810
+ value: z25.string(),
8811
+ explanation: z25.string().optional()
8812
+ });
8813
+ var AnswerParsingResultSchema = z25.object({
8814
+ answers: z25.array(ParsedAnswerSchema),
8815
+ unanswered: z25.array(z25.string()).describe("Field IDs that were not answered")
8816
+ });
8817
+ var LookupFillSchema = z25.object({
8818
+ fieldId: z25.string(),
8819
+ value: z25.string(),
8820
+ source: z25.string().describe("Specific citable reference, e.g. 'GL Policy #POL-12345 (Hartford)'"),
8821
+ sourceSpanIds: z25.array(z25.string()).optional()
8822
+ });
8823
+ var LookupFillResultSchema = z25.object({
8824
+ fills: z25.array(LookupFillSchema),
8825
+ unfillable: z25.array(z25.string()),
8826
+ explanation: z25.string().optional()
8827
+ });
8828
+ var FlatPdfPlacementSchema = z25.object({
8829
+ fieldId: z25.string(),
8830
+ page: z25.number(),
8831
+ x: z25.number().describe("Percentage from left edge (0-100)"),
8832
+ y: z25.number().describe("Percentage from top edge (0-100)"),
8833
+ text: z25.string(),
8834
+ fontSize: z25.number().optional(),
8835
+ isCheckmark: z25.boolean().optional()
8836
+ });
8837
+ var AcroFormMappingSchema = z25.object({
8838
+ fieldId: z25.string(),
8839
+ acroFormName: z25.string(),
8840
+ value: z25.string()
8841
+ });
8842
+ var QualityGateStatusSchema = z25.enum(["passed", "warning", "failed"]);
8843
+ var QualitySeveritySchema = z25.enum(["info", "warning", "blocking"]);
8844
+ var ApplicationQualityIssueSchema = z25.object({
8845
+ code: z25.string(),
7872
8846
  severity: QualitySeveritySchema,
7873
- message: z24.string(),
7874
- fieldId: z24.string().optional()
8847
+ message: z25.string(),
8848
+ fieldId: z25.string().optional()
7875
8849
  });
7876
- var ApplicationQualityRoundSchema = z24.object({
7877
- round: z24.number(),
7878
- kind: z24.string(),
8850
+ var ApplicationQualityRoundSchema = z25.object({
8851
+ round: z25.number(),
8852
+ kind: z25.string(),
7879
8853
  status: QualityGateStatusSchema,
7880
- summary: z24.string().optional()
8854
+ summary: z25.string().optional()
7881
8855
  });
7882
- var ApplicationQualityArtifactSchema = z24.object({
7883
- kind: z24.string(),
7884
- label: z24.string().optional(),
7885
- itemCount: z24.number().optional()
8856
+ var ApplicationQualityArtifactSchema = z25.object({
8857
+ kind: z25.string(),
8858
+ label: z25.string().optional(),
8859
+ itemCount: z25.number().optional()
7886
8860
  });
7887
- var ApplicationEmailReviewSchema = z24.object({
7888
- issues: z24.array(ApplicationQualityIssueSchema),
8861
+ var ApplicationEmailReviewSchema = z25.object({
8862
+ issues: z25.array(ApplicationQualityIssueSchema),
7889
8863
  qualityGateStatus: QualityGateStatusSchema
7890
8864
  });
7891
- var ApplicationQualityReportSchema = z24.object({
7892
- issues: z24.array(ApplicationQualityIssueSchema),
7893
- rounds: z24.array(ApplicationQualityRoundSchema).optional(),
7894
- artifacts: z24.array(ApplicationQualityArtifactSchema).optional(),
8865
+ var ApplicationQualityReportSchema = z25.object({
8866
+ issues: z25.array(ApplicationQualityIssueSchema),
8867
+ rounds: z25.array(ApplicationQualityRoundSchema).optional(),
8868
+ artifacts: z25.array(ApplicationQualityArtifactSchema).optional(),
7895
8869
  emailReview: ApplicationEmailReviewSchema.optional(),
7896
8870
  qualityGateStatus: QualityGateStatusSchema
7897
8871
  });
7898
- var ApplicationContextProposalSchema = z24.object({
7899
- id: z24.string(),
7900
- fieldId: z24.string().optional(),
7901
- key: z24.string(),
7902
- value: z24.string(),
7903
- category: z24.string(),
7904
- source: z24.enum(["application", "user", "lookup", "policy", "email", "chat", "imessage", "mcp"]),
7905
- confidence: z24.enum(["confirmed", "high", "medium", "low"]),
7906
- sourceSpanIds: z24.array(z24.string()).optional(),
7907
- userSourceSpanIds: z24.array(z24.string()).optional()
7908
- });
7909
- var ApplicationPacketAnswerSchema = z24.object({
7910
- fieldId: z24.string(),
7911
- label: z24.string(),
7912
- section: z24.string(),
7913
- value: z24.string(),
7914
- source: z24.string(),
7915
- confidence: z24.enum(["confirmed", "high", "medium", "low"]).optional(),
7916
- sourceSpanIds: z24.array(z24.string()).optional(),
7917
- userSourceSpanIds: z24.array(z24.string()).optional()
7918
- });
7919
- var ApplicationPacketSchema = z24.object({
7920
- id: z24.string(),
7921
- applicationId: z24.string(),
7922
- title: z24.string(),
7923
- status: z24.enum(["draft", "broker_ready", "submitted"]),
7924
- answers: z24.array(ApplicationPacketAnswerSchema),
7925
- missingFieldIds: z24.array(z24.string()),
8872
+ var ApplicationContextProposalSchema = z25.object({
8873
+ id: z25.string(),
8874
+ fieldId: z25.string().optional(),
8875
+ key: z25.string(),
8876
+ value: z25.string(),
8877
+ category: z25.string(),
8878
+ source: z25.enum(["application", "user", "lookup", "policy", "email", "chat", "imessage", "mcp"]),
8879
+ confidence: z25.enum(["confirmed", "high", "medium", "low"]),
8880
+ sourceSpanIds: z25.array(z25.string()).optional(),
8881
+ userSourceSpanIds: z25.array(z25.string()).optional()
8882
+ });
8883
+ var ApplicationPacketAnswerSchema = z25.object({
8884
+ fieldId: z25.string(),
8885
+ label: z25.string(),
8886
+ section: z25.string(),
8887
+ value: z25.string(),
8888
+ source: z25.string(),
8889
+ confidence: z25.enum(["confirmed", "high", "medium", "low"]).optional(),
8890
+ sourceSpanIds: z25.array(z25.string()).optional(),
8891
+ userSourceSpanIds: z25.array(z25.string()).optional()
8892
+ });
8893
+ var ApplicationPacketSchema = z25.object({
8894
+ id: z25.string(),
8895
+ applicationId: z25.string(),
8896
+ title: z25.string(),
8897
+ status: z25.enum(["draft", "broker_ready", "submitted"]),
8898
+ answers: z25.array(ApplicationPacketAnswerSchema),
8899
+ missingFieldIds: z25.array(z25.string()),
7926
8900
  qualityReport: ApplicationQualityReportSchema,
7927
- submissionNotes: z24.string().optional(),
7928
- createdAt: z24.number()
7929
- });
7930
- var ApplicationStateSchema = z24.object({
7931
- id: z24.string(),
7932
- pdfBase64: z24.string().optional().describe("Original PDF, omitted after extraction"),
7933
- templateId: z24.string().optional(),
7934
- templateVersion: z24.string().optional(),
8901
+ submissionNotes: z25.string().optional(),
8902
+ createdAt: z25.number()
8903
+ });
8904
+ var ApplicationStateSchema = z25.object({
8905
+ id: z25.string(),
8906
+ pdfBase64: z25.string().optional().describe("Original PDF, omitted after extraction"),
8907
+ templateId: z25.string().optional(),
8908
+ templateVersion: z25.string().optional(),
7935
8909
  templateSnapshot: ApplicationTemplateSchema.optional(),
7936
- title: z24.string().optional(),
7937
- applicationType: z24.string().nullable().optional(),
8910
+ title: z25.string().optional(),
8911
+ applicationType: z25.string().nullable().optional(),
7938
8912
  questionGraph: ApplicationQuestionGraphSchema.optional(),
7939
- fields: z24.array(ApplicationFieldSchema),
7940
- batches: z24.array(z24.array(z24.string())).optional(),
7941
- currentBatchIndex: z24.number().default(0),
7942
- contextProposals: z24.array(ApplicationContextProposalSchema).optional(),
8913
+ fields: z25.array(ApplicationFieldSchema),
8914
+ batches: z25.array(z25.array(z25.string())).optional(),
8915
+ currentBatchIndex: z25.number().default(0),
8916
+ contextProposals: z25.array(ApplicationContextProposalSchema).optional(),
7943
8917
  packet: ApplicationPacketSchema.optional(),
7944
8918
  qualityReport: ApplicationQualityReportSchema.optional(),
7945
- status: z24.enum([
8919
+ status: z25.enum([
7946
8920
  "classifying",
7947
8921
  "extracting",
7948
8922
  "auto_filling",
@@ -7956,8 +8930,8 @@ var ApplicationStateSchema = z24.object({
7956
8930
  "cancelled",
7957
8931
  "complete"
7958
8932
  ]),
7959
- createdAt: z24.number(),
7960
- updatedAt: z24.number()
8933
+ createdAt: z25.number(),
8934
+ updatedAt: z25.number()
7961
8935
  });
7962
8936
 
7963
8937
  // src/application/agents/classifier.ts
@@ -9691,106 +10665,106 @@ Respond with the final answer, deduplicated citations array, overall confidence
9691
10665
  }
9692
10666
 
9693
10667
  // src/schemas/query.ts
9694
- import { z as z25 } from "zod";
9695
- var QueryIntentSchema = z25.enum([
10668
+ import { z as z26 } from "zod";
10669
+ var QueryIntentSchema = z26.enum([
9696
10670
  "policy_question",
9697
10671
  "coverage_comparison",
9698
10672
  "document_search",
9699
10673
  "claims_inquiry",
9700
10674
  "general_knowledge"
9701
10675
  ]);
9702
- var QueryAttachmentKindSchema = z25.enum(["image", "pdf", "text"]);
9703
- var QueryAttachmentSchema = z25.object({
9704
- id: z25.string().optional().describe("Optional stable attachment ID from the caller"),
10676
+ var QueryAttachmentKindSchema = z26.enum(["image", "pdf", "text"]);
10677
+ var QueryAttachmentSchema = z26.object({
10678
+ id: z26.string().optional().describe("Optional stable attachment ID from the caller"),
9705
10679
  kind: QueryAttachmentKindSchema,
9706
- name: z25.string().optional().describe("Original filename or user-facing label"),
9707
- mimeType: z25.string().optional().describe("MIME type such as image/jpeg or application/pdf"),
9708
- base64: z25.string().optional().describe("Base64-encoded file content for image/pdf attachments"),
9709
- text: z25.string().optional().describe("Plain-text attachment content when available"),
9710
- description: z25.string().optional().describe("Caller-provided description of the attachment")
10680
+ name: z26.string().optional().describe("Original filename or user-facing label"),
10681
+ mimeType: z26.string().optional().describe("MIME type such as image/jpeg or application/pdf"),
10682
+ base64: z26.string().optional().describe("Base64-encoded file content for image/pdf attachments"),
10683
+ text: z26.string().optional().describe("Plain-text attachment content when available"),
10684
+ description: z26.string().optional().describe("Caller-provided description of the attachment")
9711
10685
  });
9712
- var QueryRetrievalModeSchema = z25.enum([
10686
+ var QueryRetrievalModeSchema = z26.enum([
9713
10687
  "graph_only",
9714
10688
  "source_rag",
9715
10689
  "long_context",
9716
10690
  "hybrid"
9717
10691
  ]);
9718
- var SubQuestionSchema = z25.object({
9719
- question: z25.string().describe("Atomic sub-question to retrieve and answer independently"),
10692
+ var SubQuestionSchema = z26.object({
10693
+ question: z26.string().describe("Atomic sub-question to retrieve and answer independently"),
9720
10694
  intent: QueryIntentSchema,
9721
- chunkTypes: z25.array(z25.string()).optional().describe("Chunk types to filter retrieval (e.g. coverage, endorsement, declaration)"),
9722
- documentFilters: z25.object({
9723
- type: z25.enum(["policy", "quote"]).optional(),
9724
- carrier: z25.string().optional(),
9725
- insuredName: z25.string().optional(),
9726
- policyNumber: z25.string().optional(),
9727
- quoteNumber: z25.string().optional(),
9728
- linesOfBusiness: z25.array(AcordLobCodeSchema).optional().describe("Filter by ACORD line of business code (e.g. HOME, AUTOP, DISAB) to avoid mixing up similar policies")
10695
+ chunkTypes: z26.array(z26.string()).optional().describe("Chunk types to filter retrieval (e.g. coverage, endorsement, declaration)"),
10696
+ documentFilters: z26.object({
10697
+ type: z26.enum(["policy", "quote"]).optional(),
10698
+ carrier: z26.string().optional(),
10699
+ insuredName: z26.string().optional(),
10700
+ policyNumber: z26.string().optional(),
10701
+ quoteNumber: z26.string().optional(),
10702
+ linesOfBusiness: z26.array(AcordLobCodeSchema).optional().describe("Filter by ACORD line of business code (e.g. HOME, AUTOP, DISAB) to avoid mixing up similar policies")
9729
10703
  }).optional().describe("Structured filters to narrow document lookup")
9730
10704
  });
9731
- var QueryClassifyResultSchema = z25.object({
10705
+ var QueryClassifyResultSchema = z26.object({
9732
10706
  intent: QueryIntentSchema,
9733
- subQuestions: z25.array(SubQuestionSchema).min(1).describe("Decomposed atomic sub-questions"),
9734
- requiresDocumentLookup: z25.boolean().describe("Whether structured document lookup is needed"),
9735
- requiresChunkSearch: z25.boolean().describe("Whether semantic chunk search is needed"),
9736
- requiresConversationHistory: z25.boolean().describe("Whether conversation history is relevant"),
10707
+ subQuestions: z26.array(SubQuestionSchema).min(1).describe("Decomposed atomic sub-questions"),
10708
+ requiresDocumentLookup: z26.boolean().describe("Whether structured document lookup is needed"),
10709
+ requiresChunkSearch: z26.boolean().describe("Whether semantic chunk search is needed"),
10710
+ requiresConversationHistory: z26.boolean().describe("Whether conversation history is relevant"),
9737
10711
  retrievalMode: QueryRetrievalModeSchema.optional().describe("Preferred retrieval strategy for the query when source-span retrieval is available")
9738
10712
  });
9739
- var EvidenceItemSchema = z25.object({
9740
- source: z25.enum(["chunk", "document", "conversation", "attachment", "source_span", "source_node"]),
9741
- chunkId: z25.string().optional(),
9742
- sourceNodeId: z25.string().optional(),
9743
- sourceSpanId: z25.string().optional(),
9744
- documentId: z25.string().optional(),
9745
- turnId: z25.string().optional(),
9746
- attachmentId: z25.string().optional(),
9747
- text: z25.string().describe("Text excerpt from the source"),
9748
- relevance: z25.number().min(0).max(1),
10713
+ var EvidenceItemSchema = z26.object({
10714
+ source: z26.enum(["chunk", "document", "conversation", "attachment", "source_span", "source_node"]),
10715
+ chunkId: z26.string().optional(),
10716
+ sourceNodeId: z26.string().optional(),
10717
+ sourceSpanId: z26.string().optional(),
10718
+ documentId: z26.string().optional(),
10719
+ turnId: z26.string().optional(),
10720
+ attachmentId: z26.string().optional(),
10721
+ text: z26.string().describe("Text excerpt from the source"),
10722
+ relevance: z26.number().min(0).max(1),
9749
10723
  retrievalMode: QueryRetrievalModeSchema.optional(),
9750
10724
  sourceLocation: SourceSpanLocationSchema.optional(),
9751
- metadata: z25.array(z25.object({ key: z25.string(), value: z25.string() })).optional()
9752
- });
9753
- var AttachmentInterpretationSchema = z25.object({
9754
- summary: z25.string().describe("Concise summary of what the attachment shows or contains"),
9755
- extractedFacts: z25.array(z25.string()).describe("Specific observable or document facts grounded in the attachment"),
9756
- recommendedFocus: z25.array(z25.string()).describe("Important details to incorporate when answering follow-up questions"),
9757
- confidence: z25.number().min(0).max(1)
9758
- });
9759
- var RetrievalResultSchema = z25.object({
9760
- subQuestion: z25.string(),
9761
- evidence: z25.array(EvidenceItemSchema)
9762
- });
9763
- var CitationSchema = z25.object({
9764
- index: z25.number().describe("Citation number [1], [2], etc."),
9765
- chunkId: z25.string().optional().describe("Source chunk ID, e.g. doc-123:coverage:2"),
9766
- sourceNodeId: z25.string().optional().describe("Source tree node ID when available"),
9767
- sourceSpanId: z25.string().optional().describe("Precise source span ID when available"),
9768
- documentId: z25.string(),
9769
- documentType: z25.enum(["policy", "quote"]).optional(),
9770
- field: z25.string().optional().describe("Specific field path, e.g. coverages[0].deductible"),
9771
- quote: z25.string().describe("Exact text from source that supports the claim"),
9772
- relevance: z25.number().min(0).max(1),
10725
+ metadata: z26.array(z26.object({ key: z26.string(), value: z26.string() })).optional()
10726
+ });
10727
+ var AttachmentInterpretationSchema = z26.object({
10728
+ summary: z26.string().describe("Concise summary of what the attachment shows or contains"),
10729
+ extractedFacts: z26.array(z26.string()).describe("Specific observable or document facts grounded in the attachment"),
10730
+ recommendedFocus: z26.array(z26.string()).describe("Important details to incorporate when answering follow-up questions"),
10731
+ confidence: z26.number().min(0).max(1)
10732
+ });
10733
+ var RetrievalResultSchema = z26.object({
10734
+ subQuestion: z26.string(),
10735
+ evidence: z26.array(EvidenceItemSchema)
10736
+ });
10737
+ var CitationSchema = z26.object({
10738
+ index: z26.number().describe("Citation number [1], [2], etc."),
10739
+ chunkId: z26.string().optional().describe("Source chunk ID, e.g. doc-123:coverage:2"),
10740
+ sourceNodeId: z26.string().optional().describe("Source tree node ID when available"),
10741
+ sourceSpanId: z26.string().optional().describe("Precise source span ID when available"),
10742
+ documentId: z26.string(),
10743
+ documentType: z26.enum(["policy", "quote"]).optional(),
10744
+ field: z26.string().optional().describe("Specific field path, e.g. coverages[0].deductible"),
10745
+ quote: z26.string().describe("Exact text from source that supports the claim"),
10746
+ relevance: z26.number().min(0).max(1),
9773
10747
  retrievalMode: QueryRetrievalModeSchema.optional(),
9774
10748
  sourceLocation: SourceSpanLocationSchema.optional()
9775
10749
  });
9776
- var SubAnswerSchema = z25.object({
9777
- subQuestion: z25.string(),
9778
- answer: z25.string(),
9779
- citations: z25.array(CitationSchema),
9780
- confidence: z25.number().min(0).max(1),
9781
- needsMoreContext: z25.boolean().describe("True if evidence was insufficient to answer fully")
9782
- });
9783
- var VerifyResultSchema = z25.object({
9784
- approved: z25.boolean().describe("Whether all sub-answers are adequately grounded"),
9785
- issues: z25.array(z25.string()).describe("Specific grounding or consistency issues found"),
9786
- retrySubQuestions: z25.array(z25.string()).optional().describe("Sub-questions that need additional retrieval or re-reasoning")
9787
- });
9788
- var QueryResultSchema = z25.object({
9789
- answer: z25.string(),
9790
- citations: z25.array(CitationSchema),
10750
+ var SubAnswerSchema = z26.object({
10751
+ subQuestion: z26.string(),
10752
+ answer: z26.string(),
10753
+ citations: z26.array(CitationSchema),
10754
+ confidence: z26.number().min(0).max(1),
10755
+ needsMoreContext: z26.boolean().describe("True if evidence was insufficient to answer fully")
10756
+ });
10757
+ var VerifyResultSchema = z26.object({
10758
+ approved: z26.boolean().describe("Whether all sub-answers are adequately grounded"),
10759
+ issues: z26.array(z26.string()).describe("Specific grounding or consistency issues found"),
10760
+ retrySubQuestions: z26.array(z26.string()).optional().describe("Sub-questions that need additional retrieval or re-reasoning")
10761
+ });
10762
+ var QueryResultSchema = z26.object({
10763
+ answer: z26.string(),
10764
+ citations: z26.array(CitationSchema),
9791
10765
  intent: QueryIntentSchema,
9792
- confidence: z25.number().min(0).max(1),
9793
- followUp: z25.string().optional().describe("Suggested follow-up question if applicable")
10766
+ confidence: z26.number().min(0).max(1),
10767
+ followUp: z26.string().optional().describe("Suggested follow-up question if applicable")
9794
10768
  });
9795
10769
 
9796
10770
  // src/query/retriever.ts
@@ -10857,7 +11831,7 @@ ${sa.answer}`).join("\n\n"),
10857
11831
  }
10858
11832
 
10859
11833
  // src/pce/index.ts
10860
- import { z as z26 } from "zod";
11834
+ import { z as z27 } from "zod";
10861
11835
 
10862
11836
  // src/prompts/pce/index.ts
10863
11837
  function buildPceNormalizePrompt(input) {
@@ -10891,11 +11865,11 @@ ${input.openQuestions.map((question) => `- ${question.id}${question.fieldPath ?
10891
11865
  }
10892
11866
 
10893
11867
  // src/pce/index.ts
10894
- var ReplyAnswersSchema = z26.object({
10895
- answers: z26.array(z26.object({
10896
- questionId: z26.string().optional(),
10897
- fieldPath: z26.string().optional(),
10898
- answer: z26.string()
11868
+ var ReplyAnswersSchema = z27.object({
11869
+ answers: z27.array(z27.object({
11870
+ questionId: z27.string().optional(),
11871
+ fieldPath: z27.string().optional(),
11872
+ answer: z27.string()
10899
11873
  }))
10900
11874
  });
10901
11875
  function createPceAgent(config = {}) {
@@ -11649,23 +12623,23 @@ var AGENT_TOOLS = [
11649
12623
  ];
11650
12624
 
11651
12625
  // src/prompts/extractors/carrier-info.ts
11652
- import { z as z27 } from "zod";
11653
- var CarrierInfoSchema = z27.object({
11654
- carrierName: z27.string().describe("Primary insurance company name for display"),
11655
- carrierLegalName: z27.string().optional().describe("Legal entity name of insurer"),
11656
- naicNumber: z27.string().optional().describe("NAIC company code"),
11657
- amBestRating: z27.string().optional().describe("AM Best rating, e.g. 'A+ XV'"),
11658
- admittedStatus: z27.enum(["admitted", "non_admitted", "surplus_lines"]).optional().describe("Admitted status of the carrier"),
11659
- mga: z27.string().optional().describe("Managing General Agent or Program Administrator name"),
11660
- underwriter: z27.string().optional().describe("Named individual underwriter"),
11661
- brokerAgency: z27.string().optional().describe("Broker or producer agency name"),
11662
- brokerContactName: z27.string().optional().describe("Broker or producer contact person name"),
11663
- brokerLicenseNumber: z27.string().optional().describe("Broker or producer license number"),
11664
- policyNumber: z27.string().optional().describe("Policy or quote reference number"),
11665
- effectiveDate: z27.string().optional().describe("Policy effective date (MM/DD/YYYY)"),
11666
- expirationDate: z27.string().optional().describe("Policy expiration date (MM/DD/YYYY)"),
11667
- quoteNumber: z27.string().optional().describe("Quote or proposal reference number"),
11668
- proposedEffectiveDate: z27.string().optional().describe("Proposed effective date for quotes (MM/DD/YYYY)")
12626
+ import { z as z28 } from "zod";
12627
+ var CarrierInfoSchema = z28.object({
12628
+ carrierName: z28.string().describe("Primary insurance company name for display"),
12629
+ carrierLegalName: z28.string().optional().describe("Legal entity name of insurer"),
12630
+ naicNumber: z28.string().optional().describe("NAIC company code"),
12631
+ amBestRating: z28.string().optional().describe("AM Best rating, e.g. 'A+ XV'"),
12632
+ admittedStatus: z28.enum(["admitted", "non_admitted", "surplus_lines"]).optional().describe("Admitted status of the carrier"),
12633
+ mga: z28.string().optional().describe("Managing General Agent or Program Administrator name"),
12634
+ underwriter: z28.string().optional().describe("Named individual underwriter"),
12635
+ brokerAgency: z28.string().optional().describe("Broker or producer agency name"),
12636
+ brokerContactName: z28.string().optional().describe("Broker or producer contact person name"),
12637
+ brokerLicenseNumber: z28.string().optional().describe("Broker or producer license number"),
12638
+ policyNumber: z28.string().optional().describe("Policy or quote reference number"),
12639
+ effectiveDate: z28.string().optional().describe("Policy effective date (MM/DD/YYYY)"),
12640
+ expirationDate: z28.string().optional().describe("Policy expiration date (MM/DD/YYYY)"),
12641
+ quoteNumber: z28.string().optional().describe("Quote or proposal reference number"),
12642
+ proposedEffectiveDate: z28.string().optional().describe("Proposed effective date for quotes (MM/DD/YYYY)")
11669
12643
  });
11670
12644
  function buildCarrierInfoPrompt() {
11671
12645
  return `You are an expert insurance document analyst. Extract carrier and policy identification information from this document.
@@ -11688,21 +12662,21 @@ Return JSON only.`;
11688
12662
  }
11689
12663
 
11690
12664
  // src/prompts/extractors/named-insured.ts
11691
- import { z as z28 } from "zod";
11692
- var AdditionalNamedInsuredSchema = z28.object({
11693
- name: z28.string(),
11694
- relationship: z28.string().optional().describe("e.g. subsidiary, affiliate"),
12665
+ import { z as z29 } from "zod";
12666
+ var AdditionalNamedInsuredSchema = z29.object({
12667
+ name: z29.string(),
12668
+ relationship: z29.string().optional().describe("e.g. subsidiary, affiliate"),
11695
12669
  address: SourceBackedAddressSchema.optional()
11696
12670
  }).merge(SourceProvenanceSchema);
11697
- var ScheduledPartySchema = z28.object({
11698
- name: z28.string(),
12671
+ var ScheduledPartySchema = z29.object({
12672
+ name: z29.string(),
11699
12673
  address: SourceBackedAddressSchema.optional()
11700
12674
  }).merge(SourceProvenanceSchema);
11701
- var NamedInsuredSchema2 = z28.object({
11702
- insuredName: z28.string().describe("Name of primary named insured"),
11703
- insuredDba: z28.string().optional().describe("Doing-business-as name"),
12675
+ var NamedInsuredSchema2 = z29.object({
12676
+ insuredName: z29.string().describe("Name of primary named insured"),
12677
+ insuredDba: z29.string().optional().describe("Doing-business-as name"),
11704
12678
  insuredAddress: SourceBackedAddressSchema.optional().describe("Primary insured mailing address"),
11705
- insuredEntityType: z28.enum([
12679
+ insuredEntityType: z29.enum([
11706
12680
  "corporation",
11707
12681
  "llc",
11708
12682
  "partnership",
@@ -11715,12 +12689,12 @@ var NamedInsuredSchema2 = z28.object({
11715
12689
  "married_couple",
11716
12690
  "other"
11717
12691
  ]).optional().describe("Legal entity type of the insured"),
11718
- insuredFein: z28.string().optional().describe("Federal Employer Identification Number"),
11719
- insuredSicCode: z28.string().optional().describe("SIC code"),
11720
- insuredNaicsCode: z28.string().optional().describe("NAICS code"),
11721
- additionalNamedInsureds: z28.array(AdditionalNamedInsuredSchema).optional().describe("Additional named insureds listed on the policy"),
11722
- lossPayees: z28.array(ScheduledPartySchema).optional().describe("Loss payees listed on the policy"),
11723
- mortgageHolders: z28.array(ScheduledPartySchema).optional().describe("Mortgage holders / lienholders listed on the policy")
12692
+ insuredFein: z29.string().optional().describe("Federal Employer Identification Number"),
12693
+ insuredSicCode: z29.string().optional().describe("SIC code"),
12694
+ insuredNaicsCode: z29.string().optional().describe("NAICS code"),
12695
+ additionalNamedInsureds: z29.array(AdditionalNamedInsuredSchema).optional().describe("Additional named insureds listed on the policy"),
12696
+ lossPayees: z29.array(ScheduledPartySchema).optional().describe("Loss payees listed on the policy"),
12697
+ mortgageHolders: z29.array(ScheduledPartySchema).optional().describe("Mortgage holders / lienholders listed on the policy")
11724
12698
  });
11725
12699
  function buildNamedInsuredPrompt() {
11726
12700
  return `You are an expert insurance document analyst. Extract all named insured information from this document.
@@ -11747,14 +12721,14 @@ Return JSON only.`;
11747
12721
  }
11748
12722
 
11749
12723
  // src/prompts/extractors/coverage-limits.ts
11750
- import { z as z29 } from "zod";
12724
+ import { z as z30 } from "zod";
11751
12725
  var ExtractorCoverageSchema = CoverageSchema.extend({
11752
- coverageCode: z29.string().optional().describe("Coverage code or class code")
12726
+ coverageCode: z30.string().optional().describe("Coverage code or class code")
11753
12727
  });
11754
- var CoverageLimitsSchema = z29.object({
11755
- coverages: z29.array(ExtractorCoverageSchema).describe("All coverages with their limits"),
11756
- coverageForm: z29.enum(["occurrence", "claims_made", "accident"]).optional().describe("Primary coverage trigger type"),
11757
- retroactiveDate: z29.string().optional().describe("Retroactive date for claims-made policies (MM/DD/YYYY)")
12728
+ var CoverageLimitsSchema = z30.object({
12729
+ coverages: z30.array(ExtractorCoverageSchema).describe("All coverages with their limits"),
12730
+ coverageForm: z30.enum(["occurrence", "claims_made", "accident"]).optional().describe("Primary coverage trigger type"),
12731
+ retroactiveDate: z30.string().optional().describe("Retroactive date for claims-made policies (MM/DD/YYYY)")
11758
12732
  });
11759
12733
  function buildCoverageLimitsPrompt() {
11760
12734
  return `You are an expert insurance document analyst. Extract all coverage limits and deductibles from this document.
@@ -11796,14 +12770,14 @@ Return JSON only.`;
11796
12770
  }
11797
12771
 
11798
12772
  // src/prompts/extractors/endorsements.ts
11799
- import { z as z30 } from "zod";
11800
- var EndorsementsSchema = z30.object({
11801
- endorsements: z30.array(
11802
- z30.object({
11803
- formNumber: z30.string().describe("Form number, e.g. 'CG 21 47'"),
11804
- editionDate: z30.string().optional().describe("Edition date, e.g. '12 07'"),
11805
- title: z30.string().describe("Endorsement title"),
11806
- endorsementType: z30.enum([
12773
+ import { z as z31 } from "zod";
12774
+ var EndorsementsSchema = z31.object({
12775
+ endorsements: z31.array(
12776
+ z31.object({
12777
+ formNumber: z31.string().describe("Form number, e.g. 'CG 21 47'"),
12778
+ editionDate: z31.string().optional().describe("Edition date, e.g. '12 07'"),
12779
+ title: z31.string().describe("Endorsement title"),
12780
+ endorsementType: z31.enum([
11807
12781
  "additional_insured",
11808
12782
  "waiver_of_subrogation",
11809
12783
  "primary_noncontributory",
@@ -11823,12 +12797,12 @@ var EndorsementsSchema = z30.object({
11823
12797
  "territorial_extension",
11824
12798
  "other"
11825
12799
  ]).describe("Endorsement type classification"),
11826
- effectiveDate: z30.string().optional().describe("Endorsement effective date"),
11827
- affectedCoverageParts: z30.array(z30.string()).optional().describe("Coverage parts affected by this endorsement"),
11828
- namedParties: z30.array(
11829
- z30.object({
11830
- name: z30.string().describe("Party name"),
11831
- role: z30.enum([
12800
+ effectiveDate: z31.string().optional().describe("Endorsement effective date"),
12801
+ affectedCoverageParts: z31.array(z31.string()).optional().describe("Coverage parts affected by this endorsement"),
12802
+ namedParties: z31.array(
12803
+ z31.object({
12804
+ name: z31.string().describe("Party name"),
12805
+ role: z31.enum([
11832
12806
  "additional_insured",
11833
12807
  "loss_payee",
11834
12808
  "mortgage_holder",
@@ -11837,18 +12811,18 @@ var EndorsementsSchema = z30.object({
11837
12811
  "designated_person",
11838
12812
  "other"
11839
12813
  ]).describe("Party role"),
11840
- relationship: z30.string().optional().describe("Relationship to insured"),
11841
- scope: z30.string().optional().describe("Scope of coverage for this party")
12814
+ relationship: z31.string().optional().describe("Relationship to insured"),
12815
+ scope: z31.string().optional().describe("Scope of coverage for this party")
11842
12816
  })
11843
12817
  ).optional().describe("Named parties (additional insureds, loss payees, etc.)"),
11844
- keyTerms: z30.array(z30.string()).optional().describe("Key terms or notable provisions in the endorsement"),
11845
- premiumImpact: z30.string().optional().describe("Additional premium or credit"),
11846
- excerpt: z30.string().optional().describe("Short source excerpt, not full verbatim text"),
11847
- content: z30.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
11848
- pageStart: z30.number().describe("Starting page number of this endorsement"),
11849
- pageEnd: z30.number().optional().describe("Ending page number of this endorsement"),
11850
- sourceSpanIds: z30.array(z30.string()).optional().describe("Source span IDs grounding this endorsement"),
11851
- sourceTextHash: z30.string().optional().describe("Hash of the source text when available")
12818
+ keyTerms: z31.array(z31.string()).optional().describe("Key terms or notable provisions in the endorsement"),
12819
+ premiumImpact: z31.string().optional().describe("Additional premium or credit"),
12820
+ excerpt: z31.string().optional().describe("Short source excerpt, not full verbatim text"),
12821
+ content: z31.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
12822
+ pageStart: z31.number().describe("Starting page number of this endorsement"),
12823
+ pageEnd: z31.number().optional().describe("Ending page number of this endorsement"),
12824
+ sourceSpanIds: z31.array(z31.string()).optional().describe("Source span IDs grounding this endorsement"),
12825
+ sourceTextHash: z31.string().optional().describe("Hash of the source text when available")
11852
12826
  })
11853
12827
  ).describe("All endorsements found in the document")
11854
12828
  });
@@ -11886,20 +12860,20 @@ Return JSON only.`;
11886
12860
  }
11887
12861
 
11888
12862
  // src/prompts/extractors/exclusions.ts
11889
- import { z as z31 } from "zod";
11890
- var ExclusionsSchema = z31.object({
11891
- exclusions: z31.array(
11892
- z31.object({
11893
- name: z31.string().describe("Exclusion title or short description"),
11894
- formNumber: z31.string().optional().describe("Form number if part of a named endorsement"),
11895
- excludedPerils: z31.array(z31.string()).optional().describe("Specific perils excluded"),
11896
- isAbsolute: z31.boolean().optional().describe("Whether the exclusion is absolute (no exceptions)"),
11897
- exceptions: z31.array(z31.string()).optional().describe("Exceptions to the exclusion, if any"),
11898
- buybackAvailable: z31.boolean().optional().describe("Whether coverage can be bought back via endorsement"),
11899
- buybackEndorsement: z31.string().optional().describe("Form number of the buyback endorsement if available"),
11900
- appliesTo: z31.array(z31.string()).optional().describe("Policy types this exclusion applies to"),
11901
- content: z31.string().describe("Full verbatim exclusion text"),
11902
- pageNumber: z31.number().optional().describe("Page number where exclusion appears")
12863
+ import { z as z32 } from "zod";
12864
+ var ExclusionsSchema = z32.object({
12865
+ exclusions: z32.array(
12866
+ z32.object({
12867
+ name: z32.string().describe("Exclusion title or short description"),
12868
+ formNumber: z32.string().optional().describe("Form number if part of a named endorsement"),
12869
+ excludedPerils: z32.array(z32.string()).optional().describe("Specific perils excluded"),
12870
+ isAbsolute: z32.boolean().optional().describe("Whether the exclusion is absolute (no exceptions)"),
12871
+ exceptions: z32.array(z32.string()).optional().describe("Exceptions to the exclusion, if any"),
12872
+ buybackAvailable: z32.boolean().optional().describe("Whether coverage can be bought back via endorsement"),
12873
+ buybackEndorsement: z32.string().optional().describe("Form number of the buyback endorsement if available"),
12874
+ appliesTo: z32.array(z32.string()).optional().describe("Policy types this exclusion applies to"),
12875
+ content: z32.string().describe("Full verbatim exclusion text"),
12876
+ pageNumber: z32.number().optional().describe("Page number where exclusion appears")
11903
12877
  })
11904
12878
  ).describe("All exclusions found in the document")
11905
12879
  });
@@ -11935,12 +12909,12 @@ Return JSON only.`;
11935
12909
  }
11936
12910
 
11937
12911
  // src/prompts/extractors/conditions.ts
11938
- import { z as z32 } from "zod";
11939
- var ConditionsSchema = z32.object({
11940
- conditions: z32.array(
11941
- z32.object({
11942
- name: z32.string().describe("Condition title"),
11943
- conditionType: z32.enum([
12912
+ import { z as z33 } from "zod";
12913
+ var ConditionsSchema = z33.object({
12914
+ conditions: z33.array(
12915
+ z33.object({
12916
+ name: z33.string().describe("Condition title"),
12917
+ conditionType: z33.enum([
11944
12918
  "duties_after_loss",
11945
12919
  "notice_requirements",
11946
12920
  "other_insurance",
@@ -11959,14 +12933,14 @@ var ConditionsSchema = z32.object({
11959
12933
  "separation_of_insureds",
11960
12934
  "other"
11961
12935
  ]).describe("Condition category"),
11962
- content: z32.string().describe("Full verbatim condition text"),
11963
- keyValues: z32.array(
11964
- z32.object({
11965
- key: z32.string().describe("Key name (e.g. 'noticePeriod', 'suitDeadline')"),
11966
- value: z32.string().describe("Value (e.g. '30 days', '2 years')")
12936
+ content: z33.string().describe("Full verbatim condition text"),
12937
+ keyValues: z33.array(
12938
+ z33.object({
12939
+ key: z33.string().describe("Key name (e.g. 'noticePeriod', 'suitDeadline')"),
12940
+ value: z33.string().describe("Value (e.g. '30 days', '2 years')")
11967
12941
  })
11968
12942
  ).optional().describe("Key values extracted from the condition (notice periods, deadlines, etc.)"),
11969
- pageNumber: z32.number().optional().describe("Page number where condition appears")
12943
+ pageNumber: z33.number().optional().describe("Page number where condition appears")
11970
12944
  })
11971
12945
  ).describe("All policy conditions found in the document")
11972
12946
  });
@@ -12004,34 +12978,34 @@ Return JSON only.`;
12004
12978
  }
12005
12979
 
12006
12980
  // src/prompts/extractors/premium-breakdown.ts
12007
- import { z as z33 } from "zod";
12008
- var PremiumBreakdownSchema = z33.object({
12009
- premium: z33.string().optional().describe("Total premium amount, e.g. '$5,000'"),
12010
- premiumAmount: z33.number().optional().describe("Total premium as a plain number with no currency symbols or commas"),
12011
- totalCost: z33.string().optional().describe("Total cost including taxes and fees, e.g. '$5,250'"),
12012
- totalCostAmount: z33.number().optional().describe("Total cost as a plain number with no currency symbols or commas"),
12013
- premiumBreakdown: z33.array(
12014
- z33.object({
12015
- line: z33.string().describe("Coverage line name"),
12016
- amount: z33.string().describe("Premium amount for this line"),
12017
- amountValue: z33.number().optional().describe("Premium amount as a plain number with no currency symbols or commas")
12981
+ import { z as z34 } from "zod";
12982
+ var PremiumBreakdownSchema = z34.object({
12983
+ premium: z34.string().optional().describe("Total premium amount, e.g. '$5,000'"),
12984
+ premiumAmount: z34.number().optional().describe("Total premium as a plain number with no currency symbols or commas"),
12985
+ totalCost: z34.string().optional().describe("Total cost including taxes and fees, e.g. '$5,250'"),
12986
+ totalCostAmount: z34.number().optional().describe("Total cost as a plain number with no currency symbols or commas"),
12987
+ premiumBreakdown: z34.array(
12988
+ z34.object({
12989
+ line: z34.string().describe("Coverage line name"),
12990
+ amount: z34.string().describe("Premium amount for this line"),
12991
+ amountValue: z34.number().optional().describe("Premium amount as a plain number with no currency symbols or commas")
12018
12992
  })
12019
12993
  ).optional().describe("Per-coverage-line premium breakdown"),
12020
- taxesAndFees: z33.array(
12021
- z33.object({
12022
- name: z33.string().describe("Fee or tax name"),
12023
- amount: z33.string().describe("Dollar amount"),
12024
- amountValue: z33.number().optional().describe("Fee or tax amount as a plain number with no currency symbols or commas"),
12025
- type: z33.enum(["tax", "fee", "surcharge", "assessment"]).optional().describe("Fee category")
12994
+ taxesAndFees: z34.array(
12995
+ z34.object({
12996
+ name: z34.string().describe("Fee or tax name"),
12997
+ amount: z34.string().describe("Dollar amount"),
12998
+ amountValue: z34.number().optional().describe("Fee or tax amount as a plain number with no currency symbols or commas"),
12999
+ type: z34.enum(["tax", "fee", "surcharge", "assessment"]).optional().describe("Fee category")
12026
13000
  })
12027
13001
  ).optional().describe("Taxes, fees, surcharges, and assessments"),
12028
- minimumPremium: z33.string().optional().describe("Minimum premium if stated"),
12029
- minimumPremiumAmount: z33.number().optional().describe("Minimum premium as a plain number when the source states a fixed amount"),
12030
- depositPremium: z33.string().optional().describe("Deposit premium if stated"),
12031
- depositPremiumAmount: z33.number().optional().describe("Deposit premium as a plain number when the source states a fixed amount"),
12032
- paymentPlan: z33.string().optional().describe("Payment plan description"),
12033
- auditType: z33.enum(["annual", "semi_annual", "quarterly", "monthly", "final", "self"]).optional().describe("Premium audit type"),
12034
- ratingBasis: z33.string().optional().describe("Rating basis, e.g. payroll, revenue, area, units")
13002
+ minimumPremium: z34.string().optional().describe("Minimum premium if stated"),
13003
+ minimumPremiumAmount: z34.number().optional().describe("Minimum premium as a plain number when the source states a fixed amount"),
13004
+ depositPremium: z34.string().optional().describe("Deposit premium if stated"),
13005
+ depositPremiumAmount: z34.number().optional().describe("Deposit premium as a plain number when the source states a fixed amount"),
13006
+ paymentPlan: z34.string().optional().describe("Payment plan description"),
13007
+ auditType: z34.enum(["annual", "semi_annual", "quarterly", "monthly", "final", "self"]).optional().describe("Premium audit type"),
13008
+ ratingBasis: z34.string().optional().describe("Rating basis, e.g. payroll, revenue, area, units")
12035
13009
  });
12036
13010
  function buildPremiumBreakdownPrompt() {
12037
13011
  return `You are an expert insurance document analyst. Extract all premium and cost information from this document.
@@ -12053,14 +13027,14 @@ Return JSON only.`;
12053
13027
  }
12054
13028
 
12055
13029
  // src/prompts/extractors/declarations.ts
12056
- import { z as z34 } from "zod";
12057
- var DeclarationsFieldSchema = z34.object({
12058
- field: z34.string().describe("Descriptive field name (e.g. 'policyNumber', 'effectiveDate', 'coverageALimit')"),
12059
- value: z34.string().describe("Extracted value exactly as it appears in the document"),
12060
- section: z34.string().optional().describe("Section or grouping this field belongs to (e.g. 'Coverage Limits', 'Vehicle Schedule')")
13030
+ import { z as z35 } from "zod";
13031
+ var DeclarationsFieldSchema = z35.object({
13032
+ field: z35.string().describe("Descriptive field name (e.g. 'policyNumber', 'effectiveDate', 'coverageALimit')"),
13033
+ value: z35.string().describe("Extracted value exactly as it appears in the document"),
13034
+ section: z35.string().optional().describe("Section or grouping this field belongs to (e.g. 'Coverage Limits', 'Vehicle Schedule')")
12061
13035
  });
12062
- var DeclarationsExtractSchema = z34.object({
12063
- fields: z34.array(DeclarationsFieldSchema).describe("All declarations page fields extracted as key-value pairs. Structure varies by line of business.")
13036
+ var DeclarationsExtractSchema = z35.object({
13037
+ fields: z35.array(DeclarationsFieldSchema).describe("All declarations page fields extracted as key-value pairs. Structure varies by line of business.")
12064
13038
  });
12065
13039
  function buildDeclarationsPrompt() {
12066
13040
  return `You are an expert insurance document analyst. Extract all declarations page data from this document into a flexible key-value structure.
@@ -12100,21 +13074,21 @@ Preserve original values exactly as they appear. Return JSON only.`;
12100
13074
  }
12101
13075
 
12102
13076
  // src/prompts/extractors/loss-history.ts
12103
- import { z as z35 } from "zod";
12104
- var LossHistorySchema = z35.object({
12105
- lossSummary: z35.string().optional().describe("Summary of loss history, e.g. '3 claims in past 5 years totaling $125,000'"),
12106
- individualClaims: z35.array(
12107
- z35.object({
12108
- date: z35.string().optional().describe("Date of loss or claim"),
12109
- type: z35.string().optional().describe("Type of claim, e.g. 'property damage', 'bodily injury'"),
12110
- description: z35.string().optional().describe("Brief description of the claim"),
12111
- amountPaid: z35.string().optional().describe("Amount paid"),
12112
- amountReserved: z35.string().optional().describe("Amount reserved"),
12113
- status: z35.enum(["open", "closed", "reopened"]).optional().describe("Claim status"),
12114
- claimNumber: z35.string().optional().describe("Claim reference number")
13077
+ import { z as z36 } from "zod";
13078
+ var LossHistorySchema = z36.object({
13079
+ lossSummary: z36.string().optional().describe("Summary of loss history, e.g. '3 claims in past 5 years totaling $125,000'"),
13080
+ individualClaims: z36.array(
13081
+ z36.object({
13082
+ date: z36.string().optional().describe("Date of loss or claim"),
13083
+ type: z36.string().optional().describe("Type of claim, e.g. 'property damage', 'bodily injury'"),
13084
+ description: z36.string().optional().describe("Brief description of the claim"),
13085
+ amountPaid: z36.string().optional().describe("Amount paid"),
13086
+ amountReserved: z36.string().optional().describe("Amount reserved"),
13087
+ status: z36.enum(["open", "closed", "reopened"]).optional().describe("Claim status"),
13088
+ claimNumber: z36.string().optional().describe("Claim reference number")
12115
13089
  })
12116
13090
  ).optional().describe("Individual claim records"),
12117
- experienceMod: z35.string().optional().describe("Experience modification factor for workers comp, e.g. '0.85'")
13091
+ experienceMod: z36.string().optional().describe("Experience modification factor for workers comp, e.g. '0.85'")
12118
13092
  });
12119
13093
  function buildLossHistoryPrompt() {
12120
13094
  return `You are an expert insurance document analyst. Extract all loss history and claims information from this document.
@@ -12131,21 +13105,21 @@ Return JSON only.`;
12131
13105
  }
12132
13106
 
12133
13107
  // src/prompts/extractors/sections.ts
12134
- import { z as z36 } from "zod";
12135
- var SubsectionSchema2 = z36.object({
12136
- title: z36.string().describe("Subsection title"),
12137
- sectionNumber: z36.string().optional().describe("Subsection number"),
12138
- pageNumber: z36.number().optional().describe("Page number"),
12139
- excerpt: z36.string().optional().describe("Short source excerpt, not full verbatim text"),
12140
- content: z36.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
12141
- sourceSpanIds: z36.array(z36.string()).optional().describe("Source span IDs grounding this subsection"),
12142
- sourceTextHash: z36.string().optional().describe("Hash of the source text when available")
12143
- });
12144
- var SectionsSchema = z36.object({
12145
- sections: z36.array(
12146
- z36.object({
12147
- title: z36.string().describe("Section title"),
12148
- type: z36.enum([
13108
+ import { z as z37 } from "zod";
13109
+ var SubsectionSchema2 = z37.object({
13110
+ title: z37.string().describe("Subsection title"),
13111
+ sectionNumber: z37.string().optional().describe("Subsection number"),
13112
+ pageNumber: z37.number().optional().describe("Page number"),
13113
+ excerpt: z37.string().optional().describe("Short source excerpt, not full verbatim text"),
13114
+ content: z37.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
13115
+ sourceSpanIds: z37.array(z37.string()).optional().describe("Source span IDs grounding this subsection"),
13116
+ sourceTextHash: z37.string().optional().describe("Hash of the source text when available")
13117
+ });
13118
+ var SectionsSchema = z37.object({
13119
+ sections: z37.array(
13120
+ z37.object({
13121
+ title: z37.string().describe("Section title"),
13122
+ type: z37.enum([
12149
13123
  "declarations",
12150
13124
  "insuring_agreement",
12151
13125
  "policy_form",
@@ -12160,13 +13134,13 @@ var SectionsSchema = z36.object({
12160
13134
  "regulatory",
12161
13135
  "other"
12162
13136
  ]).describe("Section type classification"),
12163
- excerpt: z36.string().optional().describe("Short source excerpt, not full verbatim text"),
12164
- content: z36.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
12165
- pageStart: z36.number().describe("Starting page number"),
12166
- pageEnd: z36.number().optional().describe("Ending page number"),
12167
- sourceSpanIds: z36.array(z36.string()).optional().describe("Source span IDs grounding this section"),
12168
- sourceTextHash: z36.string().optional().describe("Hash of the source text when available"),
12169
- subsections: z36.array(SubsectionSchema2).optional().describe("Subsections within this section")
13137
+ excerpt: z37.string().optional().describe("Short source excerpt, not full verbatim text"),
13138
+ content: z37.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
13139
+ pageStart: z37.number().describe("Starting page number"),
13140
+ pageEnd: z37.number().optional().describe("Ending page number"),
13141
+ sourceSpanIds: z37.array(z37.string()).optional().describe("Source span IDs grounding this section"),
13142
+ sourceTextHash: z37.string().optional().describe("Hash of the source text when available"),
13143
+ subsections: z37.array(SubsectionSchema2).optional().describe("Subsections within this section")
12170
13144
  })
12171
13145
  ).describe("All document sections")
12172
13146
  });
@@ -12200,20 +13174,20 @@ Return JSON only.`;
12200
13174
  }
12201
13175
 
12202
13176
  // src/prompts/extractors/supplementary.ts
12203
- import { z as z37 } from "zod";
12204
- var AuxiliaryFactSchema2 = z37.object({
12205
- key: z37.string().describe("Normalized machine-readable fact key, e.g. 'policyholder_age' or 'insured_name'"),
12206
- value: z37.string().describe("Concrete extracted fact value"),
12207
- subject: z37.string().optional().describe("Person, entity, vehicle, property, or schedule item this fact belongs to"),
12208
- context: z37.string().optional().describe("Short disambiguating context, such as 'Driver Schedule' or 'Named Insured'")
12209
- });
12210
- var SupplementarySchema = z37.object({
12211
- regulatoryContacts: z37.array(ContactSchema).optional().describe("Regulatory body contacts (state department of insurance, ombudsman)"),
12212
- claimsContacts: z37.array(ContactSchema).optional().describe("Claims reporting contacts and instructions"),
12213
- thirdPartyAdministrators: z37.array(ContactSchema).optional().describe("Third-party administrators for claims handling"),
12214
- cancellationNoticeDays: z37.number().optional().describe("Required notice period for cancellation in days"),
12215
- nonrenewalNoticeDays: z37.number().optional().describe("Required notice period for nonrenewal in days"),
12216
- auxiliaryFacts: z37.array(AuxiliaryFactSchema2).optional().describe("Additional retrieval-only facts that do not fit the strict primary schema")
13177
+ import { z as z38 } from "zod";
13178
+ var AuxiliaryFactSchema2 = z38.object({
13179
+ key: z38.string().describe("Normalized machine-readable fact key, e.g. 'policyholder_age' or 'insured_name'"),
13180
+ value: z38.string().describe("Concrete extracted fact value"),
13181
+ subject: z38.string().optional().describe("Person, entity, vehicle, property, or schedule item this fact belongs to"),
13182
+ context: z38.string().optional().describe("Short disambiguating context, such as 'Driver Schedule' or 'Named Insured'")
13183
+ });
13184
+ var SupplementarySchema = z38.object({
13185
+ regulatoryContacts: z38.array(ContactSchema).optional().describe("Regulatory body contacts (state department of insurance, ombudsman)"),
13186
+ claimsContacts: z38.array(ContactSchema).optional().describe("Claims reporting contacts and instructions"),
13187
+ thirdPartyAdministrators: z38.array(ContactSchema).optional().describe("Third-party administrators for claims handling"),
13188
+ cancellationNoticeDays: z38.number().optional().describe("Required notice period for cancellation in days"),
13189
+ nonrenewalNoticeDays: z38.number().optional().describe("Required notice period for nonrenewal in days"),
13190
+ auxiliaryFacts: z38.array(AuxiliaryFactSchema2).optional().describe("Additional retrieval-only facts that do not fit the strict primary schema")
12217
13191
  });
12218
13192
  function buildSupplementaryPrompt(alreadyExtractedSummary) {
12219
13193
  const exclusionBlock = alreadyExtractedSummary ? `
@@ -12253,17 +13227,17 @@ Return JSON only.`;
12253
13227
  }
12254
13228
 
12255
13229
  // src/prompts/extractors/definitions.ts
12256
- import { z as z38 } from "zod";
12257
- var DefinitionsSchema = z38.object({
12258
- definitions: z38.array(
12259
- z38.object({
12260
- term: z38.string().describe("Defined term exactly as shown in the document"),
12261
- definition: z38.string().describe("Full verbatim definition text, preserving original wording"),
12262
- pageNumber: z38.number().optional().describe("Original document page number"),
12263
- formNumber: z38.string().optional().describe("Form number where this definition appears"),
12264
- formTitle: z38.string().optional().describe("Form title where this definition appears"),
12265
- sectionRef: z38.string().optional().describe("Definition section heading or subsection reference"),
12266
- originalContent: z38.string().optional().describe("Short verbatim source snippet containing the term and definition")
13230
+ import { z as z39 } from "zod";
13231
+ var DefinitionsSchema = z39.object({
13232
+ definitions: z39.array(
13233
+ z39.object({
13234
+ term: z39.string().describe("Defined term exactly as shown in the document"),
13235
+ definition: z39.string().describe("Full verbatim definition text, preserving original wording"),
13236
+ pageNumber: z39.number().optional().describe("Original document page number"),
13237
+ formNumber: z39.string().optional().describe("Form number where this definition appears"),
13238
+ formTitle: z39.string().optional().describe("Form title where this definition appears"),
13239
+ sectionRef: z39.string().optional().describe("Definition section heading or subsection reference"),
13240
+ originalContent: z39.string().optional().describe("Short verbatim source snippet containing the term and definition")
12267
13241
  })
12268
13242
  ).describe("All substantive insurance definitions found in the document")
12269
13243
  });
@@ -12297,22 +13271,22 @@ Return JSON only.`;
12297
13271
  }
12298
13272
 
12299
13273
  // src/prompts/extractors/covered-reasons.ts
12300
- import { z as z39 } from "zod";
12301
- var CoveredReasonsSchema = z39.object({
12302
- coveredReasons: z39.array(
12303
- z39.object({
12304
- coverageName: z39.string().describe("Coverage, coverage part, or form this covered reason belongs to"),
12305
- reasonNumber: z39.string().optional().describe("Source number or letter for the covered reason, if shown"),
12306
- title: z39.string().optional().describe("Covered reason title, peril, cause of loss, trigger, or short name"),
12307
- content: z39.string().describe("Full verbatim covered-reason or insuring-agreement text"),
12308
- conditions: z39.array(z39.string()).optional().describe("Conditions, timing rules, documentation requirements, or prerequisites attached to this covered reason"),
12309
- exceptions: z39.array(z39.string()).optional().describe("Exceptions or limitations attached to this covered reason"),
12310
- appliesTo: z39.array(z39.string()).optional().describe("Covered property, persons, autos, locations, operations, or coverage parts this reason applies to"),
12311
- pageNumber: z39.number().optional().describe("Original document page number"),
12312
- formNumber: z39.string().optional().describe("Form number where this covered reason appears"),
12313
- formTitle: z39.string().optional().describe("Form title where this covered reason appears"),
12314
- sectionRef: z39.string().optional().describe("Section heading where this covered reason appears"),
12315
- originalContent: z39.string().optional().describe("Short verbatim source snippet used for this covered reason")
13274
+ import { z as z40 } from "zod";
13275
+ var CoveredReasonsSchema = z40.object({
13276
+ coveredReasons: z40.array(
13277
+ z40.object({
13278
+ coverageName: z40.string().describe("Coverage, coverage part, or form this covered reason belongs to"),
13279
+ reasonNumber: z40.string().optional().describe("Source number or letter for the covered reason, if shown"),
13280
+ title: z40.string().optional().describe("Covered reason title, peril, cause of loss, trigger, or short name"),
13281
+ content: z40.string().describe("Full verbatim covered-reason or insuring-agreement text"),
13282
+ conditions: z40.array(z40.string()).optional().describe("Conditions, timing rules, documentation requirements, or prerequisites attached to this covered reason"),
13283
+ exceptions: z40.array(z40.string()).optional().describe("Exceptions or limitations attached to this covered reason"),
13284
+ appliesTo: z40.array(z40.string()).optional().describe("Covered property, persons, autos, locations, operations, or coverage parts this reason applies to"),
13285
+ pageNumber: z40.number().optional().describe("Original document page number"),
13286
+ formNumber: z40.string().optional().describe("Form number where this covered reason appears"),
13287
+ formTitle: z40.string().optional().describe("Form title where this covered reason appears"),
13288
+ sectionRef: z40.string().optional().describe("Section heading where this covered reason appears"),
13289
+ originalContent: z40.string().optional().describe("Short verbatim source snippet used for this covered reason")
12316
13290
  })
12317
13291
  ).describe("Covered causes, perils, triggers, or reasons that affirmatively grant coverage")
12318
13292
  });
@@ -13304,10 +14278,15 @@ export {
13304
14278
  NamedInsuredSchema,
13305
14279
  OperationalAddressSchema,
13306
14280
  OperationalCoverageLineSchema,
14281
+ OperationalCoverageScheduleItemSchema,
14282
+ OperationalCoverageScheduleSchema,
14283
+ OperationalCoverageScheduleValueSchema,
13307
14284
  OperationalCoverageTermSchema,
13308
14285
  OperationalDeclarationFactSchema,
13309
14286
  OperationalEndorsementSupportSchema,
13310
14287
  OperationalPartySchema,
14288
+ OperationalPremiumLineSchema,
14289
+ OperationalTaxFeeItemSchema,
13311
14290
  PERSONAL_AUTO_USAGES,
13312
14291
  PERSONAL_LOB_CODES,
13313
14292
  PET_SPECIES,
@@ -13494,6 +14473,8 @@ export {
13494
14473
  proposeContextWrites,
13495
14474
  resolveModelBudget,
13496
14475
  resolveOperationalProfileLinesOfBusiness,
14476
+ runCoverageRecovery,
14477
+ runSourceTreeExtraction,
13497
14478
  safeGenerateObject,
13498
14479
  sanitizeNulls,
13499
14480
  scoreCaseProposal,