@claritylabs/cl-sdk 4.3.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
@@ -1618,251 +1618,541 @@ var DeclarationsSchema = z16.discriminatedUnion("line", [
1618
1618
  ]);
1619
1619
 
1620
1620
  // src/schemas/document.ts
1621
+ import { z as z18 } from "zod";
1622
+
1623
+ // src/source/schemas.ts
1621
1624
  import { z as z17 } from "zod";
1622
- var SubsectionSchema = z17.object({
1623
- title: z17.string(),
1624
- sectionNumber: z17.string().optional(),
1625
- pageNumber: z17.number().optional(),
1626
- excerpt: z17.string().optional(),
1627
- content: z17.string().optional(),
1628
- documentNodeId: z17.string().optional(),
1629
- sourceSpanIds: z17.array(z17.string()).optional(),
1630
- sourceTextHash: z17.string().optional()
1631
- });
1632
- 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,
1633
1732
  title: z17.string(),
1634
- sectionNumber: z17.string().optional(),
1635
- pageStart: z17.number(),
1636
- pageEnd: z17.number().optional(),
1637
- type: z17.string(),
1638
- coverageType: z17.string().optional(),
1639
- excerpt: z17.string().optional(),
1640
- content: z17.string().optional(),
1641
- subsections: z17.array(SubsectionSchema).optional(),
1642
- recordId: z17.string().optional(),
1643
- documentNodeId: z17.string().optional(),
1644
- sourceSpanIds: z17.array(z17.string()).optional(),
1645
- sourceTextHash: z17.string().optional()
1646
- });
1647
- var SubjectivitySchema = z17.object({
1648
1733
  description: z17.string(),
1649
- 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([])
1650
1783
  });
1651
- var UnderwritingConditionSchema = z17.object({
1652
- 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([])
1653
1803
  });
1654
- 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({
1655
1839
  line: z17.string(),
1656
1840
  amount: z17.string(),
1657
1841
  amountValue: z17.number().optional(),
1658
- documentNodeId: z17.string().optional(),
1659
- sourceSpanIds: z17.array(z17.string()).optional(),
1660
- sourceTextHash: z17.string().optional()
1842
+ sourceNodeIds: z17.array(z17.string().min(1)).default([]),
1843
+ sourceSpanIds: z17.array(z17.string().min(1)).default([])
1661
1844
  });
1662
- var AuxiliaryFactSchema = z17.object({
1663
- key: z17.string(),
1664
- value: z17.string(),
1665
- subject: z17.string().optional(),
1666
- context: z17.string().optional(),
1667
- documentNodeId: z17.string().optional(),
1668
- sourceSpanIds: z17.array(z17.string()).optional(),
1669
- sourceTextHash: z17.string().optional()
1670
- });
1671
- var DefinitionSchema = z17.object({
1672
- term: z17.string(),
1673
- definition: z17.string(),
1674
- pageNumber: z17.number().optional(),
1675
- formNumber: z17.string().optional(),
1676
- formTitle: z17.string().optional(),
1677
- sectionRef: z17.string().optional(),
1678
- originalContent: z17.string().optional(),
1679
- recordId: z17.string().optional(),
1680
- documentNodeId: z17.string().optional(),
1681
- sourceSpanIds: z17.array(z17.string()).optional(),
1682
- sourceTextHash: z17.string().optional()
1683
- });
1684
- var CoveredReasonSchema = z17.object({
1685
- coverageName: z17.string(),
1686
- reasonNumber: z17.string().optional(),
1687
- title: z17.string().optional(),
1688
- content: z17.string(),
1689
- conditions: z17.array(z17.string()).optional(),
1690
- exceptions: z17.array(z17.string()).optional(),
1691
- appliesTo: z17.array(z17.string()).optional(),
1692
- pageNumber: z17.number().optional(),
1693
- formNumber: z17.string().optional(),
1694
- formTitle: z17.string().optional(),
1695
- sectionRef: z17.string().optional(),
1696
- originalContent: z17.string().optional(),
1697
- recordId: z17.string().optional(),
1698
- documentNodeId: z17.string().optional(),
1699
- sourceSpanIds: z17.array(z17.string()).optional(),
1700
- sourceTextHash: z17.string().optional()
1701
- });
1702
- var DocumentTableOfContentsEntrySchema = z17.object({
1703
- title: z17.string(),
1704
- level: z17.number().int().positive().optional(),
1705
- pageStart: z17.number().optional(),
1706
- pageEnd: z17.number().optional(),
1707
- documentNodeId: z17.string().optional(),
1708
- sourceSpanIds: z17.array(z17.string()).optional()
1709
- });
1710
- var DocumentPageMapEntrySchema = z17.object({
1711
- page: z17.number().int().positive(),
1712
- label: z17.string().optional(),
1713
- formNumber: z17.string().optional(),
1714
- formTitle: z17.string().optional(),
1715
- sectionTitle: z17.string().optional(),
1716
- extractorNames: z17.array(z17.string()).optional(),
1717
- 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([])
1718
1860
  });
1719
- var DocumentAgentGuidanceSchema = z17.object({
1861
+ var OperationalEndorsementSupportSchema = z17.object({
1720
1862
  kind: z17.string(),
1721
- title: z17.string(),
1722
- detail: z17.string(),
1723
- sourceSpanIds: z17.array(z17.string()).optional()
1724
- });
1725
- var DocumentMetadataSchema = z17.object({
1726
- sourceTreeVersion: z17.string().optional(),
1727
- sourceTreeCanonical: z17.boolean().optional(),
1728
- formInventory: z17.array(FormReferenceSchema).optional(),
1729
- tableOfContents: z17.array(DocumentTableOfContentsEntrySchema).optional(),
1730
- pageMap: z17.array(DocumentPageMapEntrySchema).optional(),
1731
- agentGuidance: z17.array(DocumentAgentGuidanceSchema).optional()
1732
- });
1733
- var DocumentNodeSchema = z17.lazy(
1734
- () => z17.object({
1735
- id: z17.string(),
1736
- title: z17.string(),
1737
- originalTitle: z17.string().optional(),
1738
- type: z17.string().optional(),
1739
- label: z17.string().optional(),
1740
- level: z17.number().int().positive().optional(),
1741
- sectionNumber: z17.string().optional(),
1742
- pageStart: z17.number().optional(),
1743
- pageEnd: z17.number().optional(),
1744
- formNumber: z17.string().optional(),
1745
- formTitle: z17.string().optional(),
1746
- excerpt: z17.string().optional(),
1747
- content: z17.string().optional(),
1748
- interpretationLabels: z17.array(z17.string()).optional(),
1749
- sourceSpanIds: z17.array(z17.string()).optional(),
1750
- sourceTextHash: z17.string().optional(),
1751
- 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()
1752
2041
  })
1753
2042
  );
1754
2043
  var BaseDocumentFields = {
1755
- id: z17.string(),
1756
- carrier: z17.string(),
1757
- security: z17.string().optional(),
1758
- insuredName: z17.string(),
1759
- premium: z17.string().optional(),
1760
- premiumAmount: z17.number().optional(),
1761
- summary: z17.string().optional(),
1762
- linesOfBusiness: z17.array(z17.string()).optional(),
1763
- 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),
1764
2054
  documentMetadata: DocumentMetadataSchema,
1765
- documentOutline: z17.array(DocumentNodeSchema),
1766
- sections: z17.array(SectionSchema).optional(),
1767
- definitions: z17.array(DefinitionSchema).optional(),
1768
- 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(),
1769
2059
  // Enriched fields (v1.2+)
1770
- carrierLegalName: z17.string().optional(),
1771
- carrierNaicNumber: z17.string().optional(),
1772
- carrierAmBestRating: z17.string().optional(),
1773
- carrierAdmittedStatus: z17.string().optional(),
1774
- mga: z17.string().optional(),
1775
- underwriter: z17.string().optional(),
1776
- brokerAgency: z17.string().optional(),
1777
- brokerContactName: z17.string().optional(),
1778
- brokerLicenseNumber: z17.string().optional(),
1779
- priorPolicyNumber: z17.string().optional(),
1780
- programName: z17.string().optional(),
1781
- isRenewal: z17.boolean().optional(),
1782
- isPackage: z17.boolean().optional(),
1783
- 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(),
1784
2074
  insuredAddress: SourceBackedAddressSchema.optional(),
1785
2075
  insuredEntityType: EntityTypeSchema.optional(),
1786
- additionalNamedInsureds: z17.array(NamedInsuredSchema).optional(),
1787
- insuredSicCode: z17.string().optional(),
1788
- insuredNaicsCode: z17.string().optional(),
1789
- insuredFein: z17.string().optional(),
1790
- enrichedCoverages: z17.array(EnrichedCoverageSchema).optional(),
1791
- endorsements: z17.array(EndorsementSchema).optional(),
1792
- exclusions: z17.array(ExclusionSchema).optional(),
1793
- 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(),
1794
2084
  limits: LimitScheduleSchema.optional(),
1795
2085
  deductibles: DeductibleScheduleSchema.optional(),
1796
- locations: z17.array(InsuredLocationSchema).optional(),
1797
- vehicles: z17.array(InsuredVehicleSchema).optional(),
1798
- classifications: z17.array(ClassificationCodeSchema).optional(),
1799
- 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(),
1800
2091
  declarations: DeclarationsSchema.optional(),
1801
2092
  coverageForm: CoverageFormSchema.optional(),
1802
- retroactiveDate: z17.string().optional(),
2093
+ retroactiveDate: z18.string().optional(),
1803
2094
  extendedReportingPeriod: ExtendedReportingPeriodSchema.optional(),
1804
2095
  insurer: InsurerInfoSchema.optional(),
1805
2096
  producer: ProducerInfoSchema.optional(),
1806
- claimsContacts: z17.array(ContactSchema).optional(),
1807
- regulatoryContacts: z17.array(ContactSchema).optional(),
1808
- thirdPartyAdministrators: z17.array(ContactSchema).optional(),
1809
- additionalInsureds: z17.array(EndorsementPartySchema).optional(),
1810
- lossPayees: z17.array(EndorsementPartySchema).optional(),
1811
- mortgageHolders: z17.array(EndorsementPartySchema).optional(),
1812
- taxesAndFees: z17.array(TaxFeeItemSchema).optional(),
1813
- totalCost: z17.string().optional(),
1814
- totalCostAmount: z17.number().optional(),
1815
- minimumPremium: z17.string().optional(),
1816
- minimumPremiumAmount: z17.number().optional(),
1817
- depositPremium: z17.string().optional(),
1818
- 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(),
1819
2110
  paymentPlan: PaymentPlanSchema.optional(),
1820
2111
  auditType: AuditTypeSchema.optional(),
1821
- ratingBasis: z17.array(RatingBasisSchema).optional(),
1822
- premiumByLocation: z17.array(LocationPremiumSchema).optional(),
2112
+ ratingBasis: z18.array(RatingBasisSchema).optional(),
2113
+ premiumByLocation: z18.array(LocationPremiumSchema).optional(),
1823
2114
  lossSummary: LossSummarySchema.optional(),
1824
- individualClaims: z17.array(ClaimRecordSchema).optional(),
2115
+ individualClaims: z18.array(ClaimRecordSchema).optional(),
1825
2116
  experienceMod: ExperienceModSchema.optional(),
1826
- cancellationNoticeDays: z17.number().optional(),
1827
- nonrenewalNoticeDays: z17.number().optional(),
1828
- supplementaryFacts: z17.array(AuxiliaryFactSchema).optional()
2117
+ cancellationNoticeDays: z18.number().optional(),
2118
+ nonrenewalNoticeDays: z18.number().optional(),
2119
+ supplementaryFacts: z18.array(AuxiliaryFactSchema).optional()
1829
2120
  };
1830
- var PolicyDocumentSchema = z17.object({
2121
+ var PolicyDocumentSchema = z18.object({
1831
2122
  ...BaseDocumentFields,
1832
- type: z17.literal("policy"),
1833
- policyNumber: z17.string(),
1834
- effectiveDate: z17.string(),
1835
- expirationDate: z17.string().optional(),
2123
+ type: z18.literal("policy"),
2124
+ policyNumber: z18.string(),
2125
+ effectiveDate: z18.string(),
2126
+ expirationDate: z18.string().optional(),
1836
2127
  policyTermType: PolicyTermTypeSchema.optional(),
1837
- nextReviewDate: z17.string().optional(),
1838
- effectiveTime: z17.string().optional()
2128
+ nextReviewDate: z18.string().optional(),
2129
+ effectiveTime: z18.string().optional()
1839
2130
  });
1840
- var QuoteDocumentSchema = z17.object({
2131
+ var QuoteDocumentSchema = z18.object({
1841
2132
  ...BaseDocumentFields,
1842
- type: z17.literal("quote"),
1843
- quoteNumber: z17.string(),
1844
- proposedEffectiveDate: z17.string().optional(),
1845
- proposedExpirationDate: z17.string().optional(),
1846
- quoteExpirationDate: z17.string().optional(),
1847
- subjectivities: z17.array(SubjectivitySchema).optional(),
1848
- underwritingConditions: z17.array(UnderwritingConditionSchema).optional(),
1849
- 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(),
1850
2140
  // Enriched quote fields (v1.2+)
1851
- enrichedSubjectivities: z17.array(EnrichedSubjectivitySchema).optional(),
1852
- enrichedUnderwritingConditions: z17.array(EnrichedUnderwritingConditionSchema).optional(),
1853
- warrantyRequirements: z17.array(z17.string()).optional(),
1854
- 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(),
1855
2145
  bindingAuthority: BindingAuthoritySchema.optional()
1856
2146
  });
1857
- var InsuranceDocumentSchema = z17.discriminatedUnion("type", [
2147
+ var InsuranceDocumentSchema = z18.discriminatedUnion("type", [
1858
2148
  PolicyDocumentSchema,
1859
2149
  QuoteDocumentSchema
1860
2150
  ]);
1861
2151
 
1862
2152
  // src/schemas/platform.ts
1863
- import { z as z18 } from "zod";
1864
- var PlatformSchema = z18.enum(["email", "chat", "sms", "slack", "discord"]);
1865
- 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"]);
1866
2156
  var PLATFORM_CONFIGS = {
1867
2157
  email: {
1868
2158
  supportsMarkdown: false,
@@ -1895,65 +2185,65 @@ var PLATFORM_CONFIGS = {
1895
2185
  };
1896
2186
 
1897
2187
  // src/schemas/pce.ts
1898
- import { z as z20 } from "zod";
2188
+ import { z as z21 } from "zod";
1899
2189
 
1900
2190
  // src/case/index.ts
1901
- import { z as z19 } from "zod";
1902
- var CaseEvidenceSourceSchema = z19.object({
1903
- id: z19.string(),
1904
- label: z19.string().optional(),
1905
- documentId: z19.string().optional(),
1906
- page: z19.number().optional(),
1907
- fieldPath: z19.string().optional(),
1908
- text: z19.string().describe("Source text available for span validation and citation"),
1909
- metadata: z19.record(z19.string(), z19.string()).optional()
1910
- });
1911
- var CaseCitationSchema = z19.object({
1912
- sourceId: z19.string(),
1913
- quote: z19.string(),
1914
- page: z19.number().optional(),
1915
- fieldPath: z19.string().optional()
1916
- });
1917
- var ValidationIssueSeveritySchema = z19.enum(["info", "warning", "blocking"]);
1918
- var CaseValidationIssueSchema = z19.object({
1919
- 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(),
1920
2210
  severity: ValidationIssueSeveritySchema,
1921
- message: z19.string(),
1922
- itemId: z19.string().optional(),
1923
- fieldPath: z19.string().optional(),
1924
- sourceId: z19.string().optional()
1925
- });
1926
- var MissingInfoQuestionSchema = z19.object({
1927
- id: z19.string(),
1928
- itemId: z19.string().optional(),
1929
- fieldPath: z19.string().optional(),
1930
- question: z19.string(),
1931
- reason: z19.string(),
1932
- answer: z19.string().optional()
1933
- });
1934
- 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([
1935
2225
  "underwriter_summary",
1936
2226
  "carrier_email",
1937
2227
  "missing_info_request",
1938
2228
  "json_packet",
1939
2229
  "validation_report"
1940
2230
  ]);
1941
- var CasePacketArtifactSchema = z19.object({
1942
- id: z19.string(),
2231
+ var CasePacketArtifactSchema = z20.object({
2232
+ id: z20.string(),
1943
2233
  kind: CasePacketArtifactKindSchema,
1944
- title: z19.string(),
1945
- content: z19.string(),
1946
- citations: z19.array(CaseCitationSchema).default([])
1947
- });
1948
- var CaseSubmissionPacketSchema = z19.object({
1949
- id: z19.string(),
1950
- caseId: z19.string(),
1951
- artifacts: z19.array(CasePacketArtifactSchema),
1952
- validationIssues: z19.array(CaseValidationIssueSchema),
1953
- missingInfoQuestions: z19.array(MissingInfoQuestionSchema),
1954
- createdAt: z19.number()
1955
- });
1956
- 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([
1957
2247
  "inspect_attachments",
1958
2248
  "retrieve_policy_evidence",
1959
2249
  "retrieve_prior_applications",
@@ -1966,23 +2256,23 @@ var CaseActionSchema = z19.enum([
1966
2256
  "generate_packet",
1967
2257
  "answer_field_or_case_question"
1968
2258
  ]);
1969
- var AgenticExecutionModeSchema = z19.enum(["deterministic_tree", "market_eval", "hybrid"]);
1970
- var CaseProposalScoreSchema = z19.object({
1971
- grounding: z19.number().min(0).max(1),
1972
- completeness: z19.number().min(0).max(1),
1973
- consistency: z19.number().min(0).max(1),
1974
- determinism: z19.number().min(0).max(1),
1975
- risk: z19.number().min(0).max(1),
1976
- cost: z19.number().min(0).max(1)
1977
- });
1978
- var CaseProposalSchema = z19.object({
1979
- id: z19.string(),
1980
- sourceSpanIds: z19.array(z19.string()).default([]),
1981
- confidence: z19.number().min(0).max(1),
1982
- missingInfo: z19.array(z19.string()).default([]),
1983
- validationIssues: z19.array(CaseValidationIssueSchema).default([]),
1984
- estimatedRisk: z19.number().min(0).max(1).default(0.5),
1985
- 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),
1986
2276
  score: CaseProposalScoreSchema.optional()
1987
2277
  });
1988
2278
  function stableCaseId(prefix, parts) {
@@ -2101,8 +2391,8 @@ function totalProposalScore(score) {
2101
2391
  }
2102
2392
 
2103
2393
  // src/schemas/pce.ts
2104
- var PolicyChangeActionSchema = z20.enum(["add", "remove", "update", "replace", "clarify"]);
2105
- var PolicyChangeKindSchema = z20.enum([
2394
+ var PolicyChangeActionSchema = z21.enum(["add", "remove", "update", "replace", "clarify"]);
2395
+ var PolicyChangeKindSchema = z21.enum([
2106
2396
  "named_insured_change",
2107
2397
  "additional_insured_change",
2108
2398
  "coverage_change",
@@ -2116,70 +2406,70 @@ var PolicyChangeKindSchema = z20.enum([
2116
2406
  "renewal_submission_update",
2117
2407
  "general_endorsement"
2118
2408
  ]);
2119
- var PolicyChangeConfidenceSchema = z20.enum(["high", "medium", "low"]);
2120
- var PolicyChangeStatusSchema = z20.enum(["draft", "needs_info", "ready", "blocked"]);
2121
- var PolicyChangeItemSchema = z20.object({
2122
- 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(),
2123
2413
  kind: PolicyChangeKindSchema.default("general_endorsement"),
2124
2414
  action: PolicyChangeActionSchema,
2125
- affectedPolicyId: z20.string().default("unknown"),
2126
- fieldPath: z20.string().describe("Stable policy field path or business field name"),
2127
- label: z20.string(),
2128
- beforeValue: z20.string().optional().describe("Existing policy value, when cited from policy evidence"),
2129
- afterValue: z20.string().optional().describe("Requested new value"),
2130
- requestedValue: z20.string().optional().describe("Alias for afterValue used by policy-change workflows"),
2131
- effectiveDate: z20.string().optional(),
2132
- reason: z20.string().optional(),
2133
- sourceIds: z20.array(z20.string()).default([]),
2134
- sourceSpanIds: z20.array(z20.string()).default([]),
2135
- userSourceSpanIds: z20.array(z20.string()).optional(),
2136
- 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([]),
2137
2427
  confidence: PolicyChangeConfidenceSchema.default("medium"),
2138
- confidenceScore: z20.number().min(0).max(1).optional(),
2428
+ confidenceScore: z21.number().min(0).max(1).optional(),
2139
2429
  status: PolicyChangeStatusSchema.default("ready")
2140
2430
  });
2141
- var PceNormalizationResultSchema = z20.object({
2142
- summary: z20.string(),
2143
- items: z20.array(PolicyChangeItemSchema.omit({ id: true, status: true }).extend({
2144
- 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(),
2145
2435
  status: PolicyChangeStatusSchema.optional()
2146
2436
  })),
2147
- missingInfoQuestions: z20.array(MissingInfoQuestionSchema.omit({ id: true }).extend({
2148
- id: z20.string().optional()
2437
+ missingInfoQuestions: z21.array(MissingInfoQuestionSchema.omit({ id: true }).extend({
2438
+ id: z21.string().optional()
2149
2439
  })).default([])
2150
2440
  });
2151
- var PolicyChangeImpactSchema = z20.object({
2152
- itemId: z20.string(),
2153
- beforeValue: z20.string().optional(),
2154
- requestedValue: z20.string().optional(),
2155
- likelyEndorsementRequired: z20.boolean().default(true),
2156
- carrierApprovalLikelyRequired: z20.boolean().default(true),
2157
- affectedCoverageForms: z20.array(z20.string()).default([]),
2158
- sourceSpanIds: z20.array(z20.string()).default([])
2159
- });
2160
- var PceCaseStateSchema = z20.object({
2161
- id: z20.string(),
2162
- requestText: z20.string(),
2163
- 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(),
2164
2454
  executionMode: AgenticExecutionModeSchema.default("deterministic_tree"),
2165
- items: z20.array(PolicyChangeItemSchema),
2166
- impacts: z20.array(PolicyChangeImpactSchema),
2167
- evidenceSources: z20.array(CaseEvidenceSourceSchema),
2168
- validationIssues: z20.array(CaseValidationIssueSchema),
2169
- missingInfoQuestions: z20.array(MissingInfoQuestionSchema),
2170
- createdAt: z20.number(),
2171
- updatedAt: z20.number()
2172
- });
2173
- var PolicyChangeRequestSchema = z20.object({
2174
- id: z20.string(),
2175
- 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(),
2176
2466
  executionMode: AgenticExecutionModeSchema.optional(),
2177
- userSourceSpanIds: z20.array(z20.string()).optional(),
2178
- createdAt: z20.number().optional()
2467
+ userSourceSpanIds: z21.array(z21.string()).optional(),
2468
+ createdAt: z21.number().optional()
2179
2469
  });
2180
2470
  var PceSubmissionPacketSchema = CaseSubmissionPacketSchema.extend({
2181
2471
  pceCase: PceCaseStateSchema,
2182
- artifacts: z20.array(CasePacketArtifactSchema)
2472
+ artifacts: z21.array(CasePacketArtifactSchema)
2183
2473
  });
2184
2474
 
2185
2475
  // src/schemas/context-keys.ts
@@ -2234,254 +2524,6 @@ var CONTEXT_KEY_MAP = [
2234
2524
  { extractedField: "declarations.breed", category: "pet_info", contextKey: "pet_breed", description: "Pet breed" }
2235
2525
  ];
2236
2526
 
2237
- // src/source/schemas.ts
2238
- import { z as z21 } from "zod";
2239
- var SourceSpanKindSchema = z21.enum([
2240
- "pdf_text",
2241
- "pdf_image",
2242
- "html",
2243
- "markdown",
2244
- "plain_text",
2245
- "structured_field"
2246
- ]);
2247
- var SourceSpanUnitSchema = z21.enum([
2248
- "page",
2249
- "section",
2250
- "table",
2251
- "table_row",
2252
- "table_cell",
2253
- "key_value",
2254
- "text"
2255
- ]);
2256
- var SourceKindSchema = z21.enum([
2257
- "policy_pdf",
2258
- "application_pdf",
2259
- "email",
2260
- "attachment",
2261
- "manual_note"
2262
- ]);
2263
- var SourceSpanBBoxSchema = z21.object({
2264
- page: z21.number().int().positive(),
2265
- x: z21.number(),
2266
- y: z21.number(),
2267
- width: z21.number(),
2268
- height: z21.number()
2269
- });
2270
- var SourceSpanLocationSchema = z21.object({
2271
- page: z21.number().int().positive().optional(),
2272
- startPage: z21.number().int().positive().optional(),
2273
- endPage: z21.number().int().positive().optional(),
2274
- charStart: z21.number().int().nonnegative().optional(),
2275
- charEnd: z21.number().int().nonnegative().optional(),
2276
- lineStart: z21.number().int().positive().optional(),
2277
- lineEnd: z21.number().int().positive().optional(),
2278
- fieldPath: z21.string().optional()
2279
- });
2280
- var SourceSpanTableLocationSchema = z21.object({
2281
- tableId: z21.string().optional(),
2282
- rowIndex: z21.number().int().nonnegative().optional(),
2283
- columnIndex: z21.number().int().nonnegative().optional(),
2284
- columnName: z21.string().optional(),
2285
- rowSpanId: z21.string().optional(),
2286
- tableSpanId: z21.string().optional(),
2287
- isHeader: z21.boolean().optional()
2288
- });
2289
- var SourceSpanSchema = z21.object({
2290
- id: z21.string().min(1),
2291
- documentId: z21.string().min(1),
2292
- sourceKind: SourceKindSchema.optional(),
2293
- chunkId: z21.string().optional(),
2294
- kind: SourceSpanKindSchema,
2295
- text: z21.string(),
2296
- hash: z21.string().min(1),
2297
- textHash: z21.string().optional(),
2298
- pageStart: z21.number().int().positive().optional(),
2299
- pageEnd: z21.number().int().positive().optional(),
2300
- sectionId: z21.string().optional(),
2301
- formNumber: z21.string().optional(),
2302
- sourceUnit: SourceSpanUnitSchema.optional(),
2303
- parentSpanId: z21.string().optional(),
2304
- table: SourceSpanTableLocationSchema.optional(),
2305
- bbox: z21.array(SourceSpanBBoxSchema).optional(),
2306
- location: SourceSpanLocationSchema.optional(),
2307
- metadata: z21.record(z21.string(), z21.string()).optional()
2308
- });
2309
- var SourceSpanRefSchema = z21.object({
2310
- sourceSpanId: z21.string().min(1),
2311
- documentId: z21.string().min(1).optional(),
2312
- chunkId: z21.string().optional(),
2313
- quote: z21.string().optional(),
2314
- hash: z21.string().optional(),
2315
- location: SourceSpanLocationSchema.optional()
2316
- });
2317
- var SourceChunkSchema = z21.object({
2318
- id: z21.string().min(1),
2319
- documentId: z21.string().min(1),
2320
- sourceSpanIds: z21.array(z21.string().min(1)),
2321
- text: z21.string(),
2322
- textHash: z21.string().min(1),
2323
- pageStart: z21.number().int().positive().optional(),
2324
- pageEnd: z21.number().int().positive().optional(),
2325
- metadata: z21.record(z21.string(), z21.string()).default({})
2326
- });
2327
- var DocumentSourceNodeKindSchema = z21.enum([
2328
- "document",
2329
- "page_group",
2330
- "page",
2331
- "form",
2332
- "endorsement",
2333
- "section",
2334
- "schedule",
2335
- "clause",
2336
- "table",
2337
- "table_row",
2338
- "table_cell",
2339
- "text"
2340
- ]);
2341
- var DocumentSourceNodeSchema = z21.object({
2342
- id: z21.string().min(1),
2343
- documentId: z21.string().min(1),
2344
- parentId: z21.string().optional(),
2345
- kind: DocumentSourceNodeKindSchema,
2346
- title: z21.string(),
2347
- description: z21.string(),
2348
- textExcerpt: z21.string().optional(),
2349
- sourceSpanIds: z21.array(z21.string().min(1)),
2350
- pageStart: z21.number().int().positive().optional(),
2351
- pageEnd: z21.number().int().positive().optional(),
2352
- bbox: z21.array(SourceSpanBBoxSchema).optional(),
2353
- order: z21.number().int().nonnegative(),
2354
- path: z21.string(),
2355
- metadata: z21.record(z21.string(), z21.unknown()).optional()
2356
- });
2357
- var SourceBackedValueSchema = z21.object({
2358
- value: z21.string(),
2359
- normalizedValue: z21.string().optional(),
2360
- confidence: z21.enum(["low", "medium", "high"]).default("medium"),
2361
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2362
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2363
- });
2364
- var OperationalAddressSchema = z21.object({
2365
- street1: z21.string().optional(),
2366
- street2: z21.string().optional(),
2367
- city: z21.string().optional(),
2368
- state: z21.string().optional(),
2369
- zip: z21.string().optional(),
2370
- country: z21.string().optional(),
2371
- formatted: z21.string().optional()
2372
- });
2373
- var OperationalDeclarationFactSchema = z21.object({
2374
- field: z21.enum([
2375
- "namedInsured",
2376
- "mailingAddress",
2377
- "dba",
2378
- "entityType",
2379
- "taxId",
2380
- "additionalNamedInsured",
2381
- "policyNumber",
2382
- "insurer",
2383
- "broker",
2384
- "effectiveDate",
2385
- "expirationDate",
2386
- "premium",
2387
- "other"
2388
- ]),
2389
- label: z21.string().optional(),
2390
- value: z21.string(),
2391
- normalizedValue: z21.string().optional(),
2392
- valueKind: z21.enum(["string", "number", "date", "money", "address", "list", "unknown"]).default("string"),
2393
- address: OperationalAddressSchema.optional(),
2394
- confidence: z21.enum(["low", "medium", "high"]).default("medium"),
2395
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2396
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2397
- });
2398
- var OperationalCoverageTermSchema = z21.object({
2399
- kind: z21.enum([
2400
- "each_claim_limit",
2401
- "each_occurrence_limit",
2402
- "each_loss_limit",
2403
- "aggregate_limit",
2404
- "sublimit",
2405
- "retention",
2406
- "deductible",
2407
- "retroactive_date",
2408
- "premium",
2409
- "other"
2410
- ]).default("other"),
2411
- label: z21.string(),
2412
- value: z21.string(),
2413
- amount: z21.number().optional(),
2414
- appliesTo: z21.string().optional(),
2415
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2416
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2417
- });
2418
- var OperationalCoverageLineSchema = z21.object({
2419
- name: z21.string(),
2420
- lineOfBusiness: AcordLobCodeSchema.optional(),
2421
- coverageCode: z21.string().optional(),
2422
- limit: z21.string().optional(),
2423
- deductible: z21.string().optional(),
2424
- premium: z21.string().optional(),
2425
- retroactiveDate: z21.string().optional(),
2426
- formNumber: z21.string().optional(),
2427
- sectionRef: z21.string().optional(),
2428
- endorsementNumber: z21.string().optional(),
2429
- limits: z21.array(OperationalCoverageTermSchema).default([]),
2430
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2431
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2432
- });
2433
- var OperationalPartySchema = z21.object({
2434
- role: z21.string(),
2435
- name: z21.string(),
2436
- address: OperationalAddressSchema.optional(),
2437
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2438
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2439
- });
2440
- var OperationalEndorsementSupportSchema = z21.object({
2441
- kind: z21.string(),
2442
- status: z21.enum(["supported", "excluded", "requires_review"]),
2443
- summary: z21.string(),
2444
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2445
- sourceSpanIds: z21.array(z21.string().min(1)).default([])
2446
- });
2447
- function legacyOperationalProfileInput(value) {
2448
- if (!value || typeof value !== "object" || Array.isArray(value)) return value;
2449
- const record = value;
2450
- if ("linesOfBusiness" in record) return value;
2451
- if (!("policyTypes" in record)) return value;
2452
- return {
2453
- ...record,
2454
- linesOfBusiness: record.policyTypes
2455
- };
2456
- }
2457
- var OperationalLinesOfBusinessSchema = z21.preprocess(
2458
- (value) => Array.isArray(value) ? toLobCodes(value.filter((item) => typeof item === "string")) : void 0,
2459
- z21.array(AcordLobCodeSchema).default(["UN"])
2460
- );
2461
- var PolicyOperationalProfileSchema = z21.preprocess(
2462
- legacyOperationalProfileInput,
2463
- z21.object({
2464
- documentType: z21.enum(["policy", "quote"]).default("policy"),
2465
- linesOfBusiness: OperationalLinesOfBusinessSchema,
2466
- policyNumber: SourceBackedValueSchema.optional(),
2467
- namedInsured: SourceBackedValueSchema.optional(),
2468
- insurer: SourceBackedValueSchema.optional(),
2469
- broker: SourceBackedValueSchema.optional(),
2470
- effectiveDate: SourceBackedValueSchema.optional(),
2471
- expirationDate: SourceBackedValueSchema.optional(),
2472
- retroactiveDate: SourceBackedValueSchema.optional(),
2473
- premium: SourceBackedValueSchema.optional(),
2474
- operationsDescription: SourceBackedValueSchema.optional(),
2475
- declarationFacts: z21.array(OperationalDeclarationFactSchema).default([]),
2476
- coverages: z21.array(OperationalCoverageLineSchema).default([]),
2477
- parties: z21.array(OperationalPartySchema).default([]),
2478
- endorsementSupport: z21.array(OperationalEndorsementSupportSchema).default([]),
2479
- sourceNodeIds: z21.array(z21.string().min(1)).default([]),
2480
- sourceSpanIds: z21.array(z21.string().min(1)).default([]),
2481
- warnings: z21.array(z21.string()).default([])
2482
- })
2483
- );
2484
-
2485
2527
  // src/source/policy-types.ts
2486
2528
  var LOB_TEXT_PATTERNS = [
2487
2529
  { codes: ["CGL"], pattern: /\b(?:commercial\s+)?general\s+liability\b|\bcgl\b/i },
@@ -3832,7 +3874,7 @@ function shouldFailQualityGate(mode, status) {
3832
3874
  }
3833
3875
 
3834
3876
  // src/extraction/source-tree-extractor.ts
3835
- import { z as z23 } from "zod";
3877
+ import { z as z24 } from "zod";
3836
3878
 
3837
3879
  // src/source/operational-profile.ts
3838
3880
  function normalizeWhitespace4(value) {
@@ -4575,116 +4617,831 @@ function applyCoverageCleanupDecision(coverage, decision, validNodeIds, validSpa
4575
4617
  const value = cleanProfileValue(decision.retroactiveDate);
4576
4618
  if (value) next.retroactiveDate = value;
4577
4619
  }
4578
- const termDecisions = (decision.termDecisions ?? []).filter((termDecision) => termDecision.termIndex < coverage.limits.length);
4579
- const termDecisionByIndex = new Map(termDecisions.map((termDecision) => [termDecision.termIndex, termDecision]));
4580
- next.limits = coverage.limits.map((term, index) => applyTermCleanupDecision(term, termDecisionByIndex.get(index), validNodeIds, validSpanIds)).filter((term) => Boolean(term));
4581
- if (termDecisions.length > 0) {
4582
- if (decision.limit == null && termDecisionsTouch(coverage, termDecisions, isLimitTerm)) {
4583
- const value = primaryLimitFromTerms(next.limits);
4584
- if (value) next.limit = value;
4585
- else delete next.limit;
4620
+ const termDecisions = (decision.termDecisions ?? []).filter((termDecision) => termDecision.termIndex < coverage.limits.length);
4621
+ const termDecisionByIndex = new Map(termDecisions.map((termDecision) => [termDecision.termIndex, termDecision]));
4622
+ next.limits = coverage.limits.map((term, index) => applyTermCleanupDecision(term, termDecisionByIndex.get(index), validNodeIds, validSpanIds)).filter((term) => Boolean(term));
4623
+ if (termDecisions.length > 0) {
4624
+ if (decision.limit == null && termDecisionsTouch(coverage, termDecisions, isLimitTerm)) {
4625
+ const value = primaryLimitFromTerms(next.limits);
4626
+ if (value) next.limit = value;
4627
+ else delete next.limit;
4628
+ }
4629
+ if (decision.deductible == null && termDecisionsTouch(coverage, termDecisions, isDeductibleTerm)) {
4630
+ const value = deductibleFromTerms(next.limits);
4631
+ if (value) next.deductible = value;
4632
+ else delete next.deductible;
4633
+ }
4634
+ if (decision.premium == null && termDecisionsTouch(coverage, termDecisions, isPremiumTerm)) {
4635
+ const value = premiumFromTerms(next.limits);
4636
+ if (value) next.premium = value;
4637
+ else delete next.premium;
4638
+ }
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;
4586
5034
  }
4587
- if (decision.deductible == null && termDecisionsTouch(coverage, termDecisions, isDeductibleTerm)) {
4588
- const value = deductibleFromTerms(next.limits);
4589
- if (value) next.deductible = value;
4590
- else delete next.deductible;
5035
+ const evidenceText = citedText(spans, spansById);
5036
+ if (values.some((value) => !valueGroundedInText(value, evidenceText))) {
5037
+ citationRejectionCount += 1;
5038
+ return void 0;
4591
5039
  }
4592
- if (decision.premium == null && termDecisionsTouch(coverage, termDecisions, isPremiumTerm)) {
4593
- const value = premiumFromTerms(next.limits);
4594
- if (value) next.premium = value;
4595
- else delete next.premium;
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 [];
4596
5068
  }
4597
- if (decision.retroactiveDate == null && termDecisionsTouch(coverage, termDecisions, isRetroactiveDateTerm)) {
4598
- const value = retroactiveDateFromTerms(next.limits);
4599
- if (value) next.retroactiveDate = value;
4600
- else delete next.retroactiveDate;
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}.`);
4601
5146
  }
5147
+ limits.push(term);
5148
+ identities.add(identity);
4602
5149
  }
4603
- const termLimit = primaryLimitFromTerms(next.limits);
4604
- if (termLimit && shouldUseTermLimitDisplay(next.limit, termLimit)) {
4605
- 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);
4606
5173
  }
4607
- next.sourceNodeIds = uniqueStrings([
4608
- ...next.sourceNodeIds,
4609
- ...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 ?? []
4610
5219
  ]);
4611
- next.sourceSpanIds = uniqueStrings([
4612
- ...next.sourceSpanIds,
4613
- ...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 ?? []
4614
5233
  ]);
4615
- 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
+ };
4616
5252
  }
4617
- function sourceIdsFromOperationalProfile(profile) {
4618
- const backedValues = [
4619
- profile.policyNumber,
4620
- profile.namedInsured,
4621
- profile.insurer,
4622
- profile.broker,
4623
- profile.effectiveDate,
4624
- profile.expirationDate,
4625
- profile.retroactiveDate,
4626
- profile.premium,
4627
- profile.operationsDescription
4628
- ].filter(Boolean);
5253
+ function emptyDiagnostics(status) {
4629
5254
  return {
4630
- sourceNodeIds: uniqueStrings([
4631
- ...backedValues.flatMap((value) => value?.sourceNodeIds ?? []),
4632
- ...profile.coverages.flatMap((coverage) => coverage.sourceNodeIds),
4633
- ...profile.coverages.flatMap((coverage) => coverage.limits.flatMap((term) => term.sourceNodeIds)),
4634
- ...profile.parties.flatMap((party) => party.sourceNodeIds),
4635
- ...profile.endorsementSupport.flatMap((support) => support.sourceNodeIds)
4636
- ]),
4637
- sourceSpanIds: uniqueStrings([
4638
- ...backedValues.flatMap((value) => value?.sourceSpanIds ?? []),
4639
- ...profile.coverages.flatMap((coverage) => coverage.sourceSpanIds),
4640
- ...profile.coverages.flatMap((coverage) => coverage.limits.flatMap((term) => term.sourceSpanIds)),
4641
- ...profile.parties.flatMap((party) => party.sourceSpanIds),
4642
- ...profile.endorsementSupport.flatMap((support) => support.sourceSpanIds)
4643
- ])
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: []
4644
5265
  };
4645
5266
  }
4646
- function applyOperationalProfileCleanup(profile, cleanup, validNodeIds, validSpanIds) {
4647
- const coverageDecisionByIndex = /* @__PURE__ */ new Map();
4648
- for (const decision of cleanup.coverageDecisions) {
4649
- 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 };
4650
5380
  }
4651
- const coverages = profile.coverages.map(
4652
- (coverage, index) => applyCoverageCleanupDecision(coverage, coverageDecisionByIndex.get(index), validNodeIds, validSpanIds)
4653
- ).filter((coverage) => Boolean(coverage));
4654
- const cleanupWarnings = cleanup.warnings.map((warning) => cleanProfileValue(warning)).filter((warning) => Boolean(warning));
4655
- const nextProfile = {
4656
- ...profile,
4657
- coverages,
4658
- warnings: uniqueStrings([
4659
- ...profile.warnings,
4660
- ...cleanupWarnings.map((warning) => `Operational profile cleanup warning: ${warning}`)
4661
- ])
5381
+ }
5382
+ async function runCoverageRecovery(params) {
5383
+ const tokenUsage = { inputTokens: 0, outputTokens: 0 };
5384
+ const performanceReport = {
5385
+ modelCalls: [],
5386
+ totalModelCallDurationMs: 0
4662
5387
  };
4663
- return PolicyOperationalProfileSchema.parse({
4664
- ...nextProfile,
4665
- ...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
4666
5418
  });
5419
+ return {
5420
+ ...recovery,
5421
+ tokenUsage,
5422
+ performanceReport
5423
+ };
4667
5424
  }
4668
5425
 
4669
5426
  // src/extraction/source-tree-extractor.ts
4670
- var SourceBackedValueForPromptSchema = z23.object({
4671
- value: z23.string(),
4672
- normalizedValue: z23.string().optional(),
4673
- confidence: z23.enum(["low", "medium", "high"]).optional(),
4674
- sourceNodeIds: z23.array(z23.string()),
4675
- sourceSpanIds: z23.array(z23.string())
4676
- });
4677
- var OperationalAddressForPromptSchema = z23.object({
4678
- street1: z23.string().optional(),
4679
- street2: z23.string().optional(),
4680
- city: z23.string().optional(),
4681
- state: z23.string().optional(),
4682
- zip: z23.string().optional(),
4683
- country: z23.string().optional(),
4684
- formatted: z23.string().optional()
4685
- });
4686
- var OperationalDeclarationFactForPromptSchema = z23.object({
4687
- 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([
4688
5445
  "namedInsured",
4689
5446
  "mailingAddress",
4690
5447
  "dba",
@@ -4699,17 +5456,17 @@ var OperationalDeclarationFactForPromptSchema = z23.object({
4699
5456
  "premium",
4700
5457
  "other"
4701
5458
  ]),
4702
- label: z23.string().optional(),
4703
- value: z23.string(),
4704
- normalizedValue: z23.string().optional(),
4705
- 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(),
4706
5463
  address: OperationalAddressForPromptSchema.optional(),
4707
- confidence: z23.enum(["low", "medium", "high"]).optional(),
4708
- sourceNodeIds: z23.array(z23.string()),
4709
- sourceSpanIds: z23.array(z23.string())
5464
+ confidence: z24.enum(["low", "medium", "high"]).optional(),
5465
+ sourceNodeIds: z24.array(z24.string()),
5466
+ sourceSpanIds: z24.array(z24.string())
4710
5467
  });
4711
- var OperationalPartyForPromptSchema = z23.object({
4712
- role: z23.enum([
5468
+ var OperationalPartyForPromptSchema = z24.object({
5469
+ role: z24.enum([
4713
5470
  "named_insured",
4714
5471
  "producer",
4715
5472
  "broker",
@@ -4718,14 +5475,14 @@ var OperationalPartyForPromptSchema = z23.object({
4718
5475
  "mga",
4719
5476
  "administrator"
4720
5477
  ]),
4721
- name: z23.string(),
5478
+ name: z24.string(),
4722
5479
  address: OperationalAddressForPromptSchema.optional(),
4723
- sourceNodeIds: z23.array(z23.string()),
4724
- sourceSpanIds: z23.array(z23.string())
5480
+ sourceNodeIds: z24.array(z24.string()),
5481
+ sourceSpanIds: z24.array(z24.string())
4725
5482
  });
4726
- var OperationalProfilePromptSchema = z23.object({
4727
- documentType: z23.enum(["policy", "quote"]).optional(),
4728
- 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(),
4729
5486
  policyNumber: SourceBackedValueForPromptSchema.optional(),
4730
5487
  namedInsured: SourceBackedValueForPromptSchema.optional(),
4731
5488
  insurer: SourceBackedValueForPromptSchema.optional(),
@@ -4735,40 +5492,40 @@ var OperationalProfilePromptSchema = z23.object({
4735
5492
  retroactiveDate: SourceBackedValueForPromptSchema.optional(),
4736
5493
  premium: SourceBackedValueForPromptSchema.optional(),
4737
5494
  operationsDescription: SourceBackedValueForPromptSchema.optional(),
4738
- declarationFacts: z23.array(OperationalDeclarationFactForPromptSchema).optional(),
4739
- parties: z23.array(OperationalPartyForPromptSchema).optional(),
4740
- coverages: z23.array(z23.object({
4741
- name: z23.string(),
4742
- lineOfBusiness: z23.string().optional(),
4743
- coverageCode: z23.string().optional(),
4744
- limit: z23.string().optional(),
4745
- deductible: z23.string().optional(),
4746
- premium: z23.string().optional(),
4747
- retroactiveDate: z23.string().optional(),
4748
- formNumber: z23.string().optional(),
4749
- sectionRef: z23.string().optional(),
4750
- endorsementNumber: z23.string().optional(),
4751
- limits: z23.array(z23.object({
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({
4752
5509
  kind: OperationalCoverageTermKindSchema.optional(),
4753
- label: z23.string(),
4754
- value: z23.string(),
4755
- amount: z23.number().optional(),
4756
- appliesTo: z23.string().optional(),
4757
- sourceNodeIds: z23.array(z23.string()),
4758
- 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())
4759
5516
  })).optional(),
4760
- sourceNodeIds: z23.array(z23.string()),
4761
- sourceSpanIds: z23.array(z23.string())
5517
+ sourceNodeIds: z24.array(z24.string()),
5518
+ sourceSpanIds: z24.array(z24.string())
4762
5519
  })).optional(),
4763
- sourceNodeIds: z23.array(z23.string()).optional(),
4764
- sourceSpanIds: z23.array(z23.string()).optional()
5520
+ sourceNodeIds: z24.array(z24.string()).optional(),
5521
+ sourceSpanIds: z24.array(z24.string()).optional()
4765
5522
  });
4766
- function cleanText(value, fallback) {
5523
+ function cleanText2(value, fallback) {
4767
5524
  const text = value?.replace(/\s+/g, " ").trim();
4768
5525
  return text || fallback;
4769
5526
  }
4770
5527
  function simplifyOrganizerTitle(value, fallback, kind) {
4771
- const title = cleanText(value, fallback);
5528
+ const title = cleanText2(value, fallback);
4772
5529
  if (/^declarations\b/i.test(title)) return "Declarations";
4773
5530
  if (/^policy\s+form\b/i.test(title)) return "Policy Form";
4774
5531
  if (/^definitions\b/i.test(title)) return "Definitions";
@@ -4781,23 +5538,23 @@ function simplifyOrganizerTitle(value, fallback, kind) {
4781
5538
  return title;
4782
5539
  }
4783
5540
  function endorsementReference(value) {
4784
- const text = cleanText(value, "");
5541
+ const text = cleanText2(value, "");
4785
5542
  const explicit = text.match(/\bendorsement\s+(?:no\.?|number|#)?\s*([A-Z0-9][A-Z0-9.-]*)\b/i)?.[1]?.toUpperCase();
4786
5543
  if (explicit) return explicit;
4787
5544
  return text.match(/\b(?:[A-Z]{2,}-)?END\s+0*([0-9]{1,4})\b/i)?.[1]?.toUpperCase();
4788
5545
  }
4789
5546
  function endorsementTitle(value) {
4790
- const text = cleanText(value, "");
5547
+ const text = cleanText2(value, "");
4791
5548
  const explicit = text.match(/\bendorsement\s+(?:no\.?|number|#)\s*([A-Z0-9][A-Z0-9.-]*)\b/i)?.[1]?.toUpperCase();
4792
5549
  const number = explicit ?? text.match(/\b(?:[A-Z]{2,}-)?END\s+0*([0-9]{1,4})\b/i)?.[1]?.toUpperCase();
4793
5550
  return number ? `Endorsement No. ${number}` : void 0;
4794
5551
  }
4795
5552
  function sourceNodeText(node) {
4796
- return cleanText([node.title, node.description, node.textExcerpt].filter(Boolean).join(" "), "");
5553
+ return cleanText2([node.title, node.description, node.textExcerpt].filter(Boolean).join(" "), "");
4797
5554
  }
4798
5555
  function looksLikeEndorsementStart(node) {
4799
- const title = cleanText(node.title, "");
4800
- 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(" "), "");
4801
5558
  const start = body.slice(0, 260);
4802
5559
  if (/\bthis endorsement changes the policy\b/i.test(start) && endorsementReference(start)) return true;
4803
5560
  if (/^(?:[A-Z]{2,}-)?END\s+0*[0-9]{1,4}\b/i.test(start)) return true;
@@ -4806,7 +5563,7 @@ function looksLikeEndorsementStart(node) {
4806
5563
  }
4807
5564
  function looksLikeEndorsementContinuation(node) {
4808
5565
  if (looksLikeEndorsementStart(node)) return false;
4809
- const title = cleanText(node.title, "");
5566
+ const title = cleanText2(node.title, "");
4810
5567
  const text = sourceNodeText(node);
4811
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);
4812
5569
  }
@@ -4814,7 +5571,7 @@ function endorsementStartTitle(node) {
4814
5571
  return looksLikeEndorsementStart(node) ? endorsementTitle(sourceNodeText(node)) : void 0;
4815
5572
  }
4816
5573
  function endorsementDescription(title, node) {
4817
- return cleanText(
5574
+ return cleanText2(
4818
5575
  [title, "endorsement", node.pageStart ? `page ${node.pageStart}` : void 0].filter(Boolean).join(" | "),
4819
5576
  title
4820
5577
  );
@@ -4822,7 +5579,7 @@ function endorsementDescription(title, node) {
4822
5579
  function endorsementTitleKey(node) {
4823
5580
  const title = endorsementTitle(sourceNodeText(node));
4824
5581
  if (title) return title.toLowerCase();
4825
- const fallback = cleanText(node.title, "");
5582
+ const fallback = cleanText2(node.title, "");
4826
5583
  return fallback ? fallback.toLowerCase() : void 0;
4827
5584
  }
4828
5585
  function nodePageEnd2(node) {
@@ -4866,17 +5623,17 @@ function semanticGroupNodeId(documentId, kind, title, childNodeIds) {
4866
5623
  childNodeIds.join("_").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 80)
4867
5624
  ].join(":");
4868
5625
  }
4869
- function spanPageStart(span) {
5626
+ function spanPageStart2(span) {
4870
5627
  return span.pageStart ?? span.location?.page ?? span.location?.startPage;
4871
5628
  }
4872
- function spanPageEnd(span) {
4873
- return span.pageEnd ?? span.location?.endPage ?? spanPageStart(span);
5629
+ function spanPageEnd2(span) {
5630
+ return span.pageEnd ?? span.location?.endPage ?? spanPageStart2(span);
4874
5631
  }
4875
- function spanSourceUnit(span) {
5632
+ function spanSourceUnit2(span) {
4876
5633
  return span.sourceUnit ?? span.metadata?.sourceUnit ?? span.metadata?.elementType;
4877
5634
  }
4878
5635
  function pageHeadingTitleFromText(text, fallback) {
4879
- const normalized = cleanText(text, "");
5636
+ const normalized = cleanText2(text, "");
4880
5637
  const headingText = normalized.replace(/^page\s+\d+\s*(?:\|\s*page\s*\|\s*page\s+\d+\s*\|?)?/i, "").slice(0, 700);
4881
5638
  const patterns = [
4882
5639
  /\bIMPORTANT NOTICE\s+[—-]\s+HOW TO REPORT A CLAIM\b/i,
@@ -4890,7 +5647,7 @@ function pageHeadingTitleFromText(text, fallback) {
4890
5647
  ];
4891
5648
  for (const pattern of patterns) {
4892
5649
  const match = headingText.match(pattern)?.[0];
4893
- if (match) return cleanText(match, fallback);
5650
+ if (match) return cleanText2(match, fallback);
4894
5651
  }
4895
5652
  return fallback;
4896
5653
  }
@@ -4898,12 +5655,12 @@ function hasSubstantiveDeclarationsScheduleText(text) {
4898
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);
4899
5656
  }
4900
5657
  function looksLikeDeclarationsStart(node) {
4901
- const title = cleanText(node.title, "");
5658
+ const title = cleanText2(node.title, "");
4902
5659
  const text = sourceNodeText(node);
4903
5660
  if (/\b(important notice|privacy notice|ofac advisory|terrorism risk insurance act|how to report a claim)\b/i.test(text)) {
4904
5661
  return false;
4905
5662
  }
4906
- 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, ""));
4907
5664
  }
4908
5665
  function looksLikeDeclarationsContinuation(node) {
4909
5666
  const text = sourceNodeText(node);
@@ -4911,7 +5668,7 @@ function looksLikeDeclarationsContinuation(node) {
4911
5668
  }
4912
5669
  function looksLikePolicyFormStart(node) {
4913
5670
  const text = sourceNodeText(node);
4914
- const excerpt = cleanText(node.textExcerpt, "");
5671
+ const excerpt = cleanText2(node.textExcerpt, "");
4915
5672
  if (isAdministrativeNoticeNode(node) || looksLikeDeclarationsStart(node)) return false;
4916
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);
4917
5674
  }
@@ -5000,7 +5757,7 @@ function applySemanticPageGrouping(sourceTree) {
5000
5757
  return {
5001
5758
  ...nextNode,
5002
5759
  title: "Declarations",
5003
- description: cleanText([nextNode.description, "Declarations"].join(" "), "Declarations"),
5760
+ description: cleanText2([nextNode.description, "Declarations"].join(" "), "Declarations"),
5004
5761
  metadata: { ...nextNode.metadata, organizerRepair: "semantic_page_grouping" }
5005
5762
  };
5006
5763
  }
@@ -5008,7 +5765,7 @@ function applySemanticPageGrouping(sourceTree) {
5008
5765
  return {
5009
5766
  ...nextNode,
5010
5767
  title: "Policy Form",
5011
- description: cleanText([nextNode.description, "Policy Form"].join(" "), "Policy Form"),
5768
+ description: cleanText2([nextNode.description, "Policy Form"].join(" "), "Policy Form"),
5012
5769
  metadata: { ...nextNode.metadata, organizerRepair: "semantic_page_grouping" }
5013
5770
  };
5014
5771
  }
@@ -5276,7 +6033,7 @@ function isTitleBlockNode(node) {
5276
6033
  return metadataText(node, "organizer") === "title_block" || metadataText(node, "elementType") === "title" || metadataText(node, "sourceUnit") === "title";
5277
6034
  }
5278
6035
  function isRejectableSectionHeading(text, container) {
5279
- const normalized = cleanText(text, "");
6036
+ const normalized = cleanText2(text, "");
5280
6037
  if (!normalized) return true;
5281
6038
  if (normalized.length > 160) return true;
5282
6039
  if (/^page\s+\d+$/i.test(normalized)) return true;
@@ -5292,7 +6049,7 @@ function isRejectableSectionHeading(text, container) {
5292
6049
  }
5293
6050
  function sectionHeadingTitle(node, container) {
5294
6051
  if (!isTitleBlockNode(node)) return void 0;
5295
- const text = cleanText(node.title || node.textExcerpt, "");
6052
+ const text = cleanText2(node.title || node.textExcerpt, "");
5296
6053
  if (isRejectableSectionHeading(text, container)) return void 0;
5297
6054
  const words = text.split(/\s+/);
5298
6055
  if (words.length > 18) return void 0;
@@ -5366,7 +6123,7 @@ function applyTitleSectionHierarchy(sourceTree) {
5366
6123
  parentId: container.id,
5367
6124
  kind: sectionKindForTitle(heading),
5368
6125
  title: heading,
5369
- description: descriptionWithPages(cleanText([heading, "section"].join(" "), heading), [current, ...descendants]),
6126
+ description: descriptionWithPages(cleanText2([heading, "section"].join(" "), heading), [current, ...descendants]),
5370
6127
  metadata: {
5371
6128
  ...current.metadata,
5372
6129
  organizer: "title_section",
@@ -5414,7 +6171,7 @@ function applyEndorsementGrouping(sourceTree) {
5414
6171
  return {
5415
6172
  ...node,
5416
6173
  kind: "page",
5417
- title: node.pageStart ? `Page ${node.pageStart}` : cleanText(node.title, "Page"),
6174
+ title: node.pageStart ? `Page ${node.pageStart}` : cleanText2(node.title, "Page"),
5418
6175
  metadata: {
5419
6176
  ...node.metadata,
5420
6177
  organizerRepair: "demote_incidental_endorsement_reference"
@@ -5444,7 +6201,7 @@ function applyEndorsementGrouping(sourceTree) {
5444
6201
  ...node,
5445
6202
  kind: "page_group",
5446
6203
  title: "Endorsements",
5447
- 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]),
5448
6205
  metadata: {
5449
6206
  ...node.metadata,
5450
6207
  sourceTreeVersion: "v3",
@@ -5623,7 +6380,7 @@ function nodesByParent(sourceTree) {
5623
6380
  }
5624
6381
  return byParent;
5625
6382
  }
5626
- function sourceNodeIdsBySpanId(sourceTree) {
6383
+ function sourceNodeIdsBySpanId2(sourceTree) {
5627
6384
  const bySpan = /* @__PURE__ */ new Map();
5628
6385
  for (const node of sourceTree) {
5629
6386
  for (const spanId of node.sourceSpanIds) {
@@ -5635,7 +6392,7 @@ function sourceNodeIdsBySpanId(sourceTree) {
5635
6392
  return bySpan;
5636
6393
  }
5637
6394
  function operationalEvidenceScore(span) {
5638
- const text = cleanText([
6395
+ const text = cleanText2([
5639
6396
  span.text,
5640
6397
  span.formNumber,
5641
6398
  span.sourceUnit,
@@ -5661,13 +6418,13 @@ function spanTableId(span) {
5661
6418
  return span.table?.tableId ?? span.metadata?.tableId;
5662
6419
  }
5663
6420
  function isTableCellSpan(span) {
5664
- return spanSourceUnit(span) === "table_cell";
6421
+ return spanSourceUnit2(span) === "table_cell";
5665
6422
  }
5666
6423
  function isOperationalEvidenceAnchor(span) {
5667
- const sourceUnit3 = spanSourceUnit(span);
6424
+ const sourceUnit3 = spanSourceUnit2(span);
5668
6425
  if (sourceUnit3 === "table_cell") return false;
5669
6426
  if (sourceUnit3 === "table" || sourceUnit3 === "table_row") return true;
5670
- const text = cleanText([span.text, span.formNumber].filter(Boolean).join(" "), "");
6427
+ const text = cleanText2([span.text, span.formNumber].filter(Boolean).join(" "), "");
5671
6428
  if (!text) return false;
5672
6429
  if (sourceUnit3 === "page") {
5673
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);
@@ -5684,9 +6441,9 @@ function isOperationalEvidenceAnchor(span) {
5684
6441
  function operationalEvidencePages(sourceSpans) {
5685
6442
  const scores = /* @__PURE__ */ new Map();
5686
6443
  for (const span of sourceSpans) {
5687
- const page = spanPageStart(span);
6444
+ const page = spanPageStart2(span);
5688
6445
  if (typeof page !== "number") continue;
5689
- 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(" "), "");
5690
6447
  if (!text) continue;
5691
6448
  let score = Math.max(0, operationalEvidenceScore(span));
5692
6449
  if (/\bdeclarations?\s+(page|schedule)?\b/i.test(text)) score += 24;
@@ -5705,7 +6462,7 @@ function operationalEvidencePages(sourceSpans) {
5705
6462
  }
5706
6463
  function operationalProfileEvidence(sourceTree, sourceSpans) {
5707
6464
  const sorted = [...sourceSpans].sort(
5708
- (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)
5709
6466
  );
5710
6467
  const selectedPages = operationalEvidencePages(sorted);
5711
6468
  const selected = /* @__PURE__ */ new Set();
@@ -5715,7 +6472,7 @@ function operationalProfileEvidence(sourceTree, sourceSpans) {
5715
6472
  const score = operationalEvidenceScore(span);
5716
6473
  if (score < 8) continue;
5717
6474
  if (!isOperationalEvidenceAnchor(span)) continue;
5718
- const page = spanPageStart(span);
6475
+ const page = spanPageStart2(span);
5719
6476
  if (selectedPages.size > 0 && typeof page === "number" && !selectedPages.has(page) && score < 30) continue;
5720
6477
  const tableId2 = spanTableId(span);
5721
6478
  if (tableId2 && !isTableCellSpan(span)) selectedTableIds.add(tableId2);
@@ -5723,9 +6480,9 @@ function operationalProfileEvidence(sourceTree, sourceSpans) {
5723
6480
  for (let offset = -neighborWindow; offset <= neighborWindow; offset += 1) {
5724
6481
  const neighborIndex = index + offset;
5725
6482
  const neighbor = sorted[neighborIndex];
5726
- if (!neighbor || spanPageStart(neighbor) !== page) continue;
6483
+ if (!neighbor || spanPageStart2(neighbor) !== page) continue;
5727
6484
  if (selectedPages.size > 0 && typeof page === "number" && !selectedPages.has(page) && operationalEvidenceScore(neighbor) < 30) continue;
5728
- const neighborText = cleanText(neighbor.text, "");
6485
+ const neighborText = cleanText2(neighbor.text, "");
5729
6486
  if (!neighborText || neighborText.length > 3e3) continue;
5730
6487
  selected.add(neighborIndex);
5731
6488
  }
@@ -5734,31 +6491,31 @@ function operationalProfileEvidence(sourceTree, sourceSpans) {
5734
6491
  sorted.forEach((span, index) => {
5735
6492
  const tableId2 = spanTableId(span);
5736
6493
  if (!tableId2 || !selectedTableIds.has(tableId2) || isTableCellSpan(span)) return;
5737
- const text = cleanText(span.text, "");
6494
+ const text = cleanText2(span.text, "");
5738
6495
  if (text && text.length <= 3e3) selected.add(index);
5739
6496
  });
5740
6497
  }
5741
- const nodeIdsBySpanId = sourceNodeIdsBySpanId(sourceTree);
6498
+ const nodeIdsBySpanId = sourceNodeIdsBySpanId2(sourceTree);
5742
6499
  const seenText = /* @__PURE__ */ new Set();
5743
6500
  const entries = [...selected].sort((left, right) => left - right).map((index) => sorted[index]).filter((span) => !isTableCellSpan(span)).flatMap((span) => {
5744
- const text = cleanText(span.text, "");
6501
+ const text = cleanText2(span.text, "");
5745
6502
  if (!text) return [];
5746
- const key = `${spanPageStart(span) ?? "na"}:${text.toLowerCase().slice(0, 240)}`;
6503
+ const key = `${spanPageStart2(span) ?? "na"}:${text.toLowerCase().slice(0, 240)}`;
5747
6504
  if (seenText.has(key)) return [];
5748
6505
  seenText.add(key);
5749
6506
  return [{
5750
6507
  sourceSpanId: span.id,
5751
6508
  sourceNodeIds: [...new Set(nodeIdsBySpanId.get(span.id) ?? [])].slice(0, 4),
5752
- pageStart: spanPageStart(span),
5753
- pageEnd: spanPageEnd(span),
5754
- sourceUnit: spanSourceUnit(span),
6509
+ pageStart: spanPageStart2(span),
6510
+ pageEnd: spanPageEnd2(span),
6511
+ sourceUnit: spanSourceUnit2(span),
5755
6512
  formNumber: span.formNumber,
5756
6513
  text: text.slice(0, span.sourceUnit === "page" ? 900 : 700)
5757
6514
  }];
5758
6515
  });
5759
6516
  const detailEntries = entries.filter((entry) => entry.sourceUnit !== "page");
5760
6517
  const pageEntries = entries.filter((entry) => entry.sourceUnit === "page");
5761
- return [...detailEntries.slice(0, 80), ...pageEntries.slice(0, 8)];
6518
+ return [...detailEntries, ...pageEntries];
5762
6519
  }
5763
6520
  function sourceTreeRootId(sourceTree) {
5764
6521
  return sourceTree.find((node) => node.kind === "document")?.id;
@@ -5778,6 +6535,9 @@ function emptyOperationalProfile() {
5778
6535
  linesOfBusiness: ["UN"],
5779
6536
  declarationFacts: [],
5780
6537
  coverages: [],
6538
+ coverageSchedules: [],
6539
+ premiumBreakdown: [],
6540
+ taxesAndFees: [],
5781
6541
  parties: [],
5782
6542
  endorsementSupport: [],
5783
6543
  sourceNodeIds: [],
@@ -5933,7 +6693,7 @@ function sourceBackedAddressFromFact(fact) {
5933
6693
  };
5934
6694
  }
5935
6695
  function normalizedEntityType(value) {
5936
- 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, "");
5937
6697
  if (normalized === "inc" || normalized === "incorporated" || normalized === "c_corporation" || normalized === "s_corporation") {
5938
6698
  return "corporation";
5939
6699
  }
@@ -5959,6 +6719,65 @@ function declarationFieldName(fact) {
5959
6719
  if (fact.field === "additionalNamedInsured") return "additionalNamedInsured";
5960
6720
  return fact.field;
5961
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
+ }
5962
6781
  function materializeDocument(params) {
5963
6782
  const profile = params.operationalProfile;
5964
6783
  const policyNumber = valueOf(profile, "policyNumber") ?? "Unknown";
@@ -6003,6 +6822,30 @@ function materializeDocument(params) {
6003
6822
  ...coverage.limits?.length ? coverage.limits.map((term) => `${term.label}: ${term.value}`) : [coverage.limit, coverage.deductible, coverage.premium]
6004
6823
  ].filter(Boolean).join(" | ")
6005
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);
6006
6849
  const documentOutline = sourceTreeToOutline(params.sourceTree);
6007
6850
  const documentMetadata = {
6008
6851
  sourceTreeVersion: "v3",
@@ -6035,6 +6878,10 @@ function materializeDocument(params) {
6035
6878
  security: carrier,
6036
6879
  insuredName,
6037
6880
  premium,
6881
+ ...premiumBreakdown.length > 0 ? { premiumBreakdown } : {},
6882
+ ...taxesAndFees.length > 0 ? { taxesAndFees } : {},
6883
+ ...totalCost ? { totalCost } : {},
6884
+ ...typeof totalCostAmount === "number" && Number.isFinite(totalCostAmount) ? { totalCostAmount } : {},
6038
6885
  insuredDba,
6039
6886
  insuredAddress,
6040
6887
  insuredEntityType,
@@ -6065,6 +6912,9 @@ function materializeDocument(params) {
6065
6912
  pageEnd: form.pageEnd
6066
6913
  })),
6067
6914
  coverages,
6915
+ ...coverageSchedules.length > 0 ? { coverageSchedules } : {},
6916
+ ...vehicles.length > 0 ? { vehicles } : {},
6917
+ ...locations.length > 0 ? { locations } : {},
6068
6918
  documentMetadata,
6069
6919
  documentOutline,
6070
6920
  declarations: {
@@ -6196,6 +7046,7 @@ async function runSourceTreeExtraction(params) {
6196
7046
  };
6197
7047
  const emptyProfile = emptyOperationalProfile();
6198
7048
  let operationalProfile = emptyProfile;
7049
+ let coverageRecovery = disabledCoverageRecoveryDiagnostics();
6199
7050
  try {
6200
7051
  const validNodeIds = new Set(sourceTree.map((node) => node.id));
6201
7052
  const validSpanIds = new Set(sourceSpans.map((span) => span.id));
@@ -6233,6 +7084,21 @@ async function runSourceTreeExtraction(params) {
6233
7084
  } catch (error) {
6234
7085
  warnings.push(`Operational profile model pass failed; coverage rows omitted (${error instanceof Error ? error.message : String(error)})`);
6235
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
+ }
6236
7102
  if (operationalProfile.coverages.length > 0) {
6237
7103
  try {
6238
7104
  const cleanup = await cleanupOperationalCoverageSchedules({
@@ -6265,6 +7131,7 @@ async function runSourceTreeExtraction(params) {
6265
7131
  sourceChunks: chunkSourceSpans(sourceSpans),
6266
7132
  formInventory: formHints,
6267
7133
  operationalProfile,
7134
+ coverageRecovery,
6268
7135
  document,
6269
7136
  chunks: [],
6270
7137
  warnings: [...warnings, ...operationalProfile.warnings],
@@ -6367,7 +7234,8 @@ function createExtractor(config) {
6367
7234
  providerOptions: activeProviderOptions,
6368
7235
  resolveBudget,
6369
7236
  trackUsage,
6370
- log
7237
+ log,
7238
+ coverageRecovery: options?.coverageRecovery
6371
7239
  });
6372
7240
  const sourceTreeFormInventory = v3.formInventory.flatMap((form) => {
6373
7241
  const formNumber = typeof form.formNumber === "string" ? form.formNumber.trim() : "";
@@ -6407,6 +7275,7 @@ function createExtractor(config) {
6407
7275
  sourceChunks: v3.sourceChunks,
6408
7276
  sourceTree: v3.sourceTree,
6409
7277
  operationalProfile: v3.operationalProfile,
7278
+ coverageRecovery: v3.coverageRecovery,
6410
7279
  warnings: v3.warnings,
6411
7280
  tokenUsage: v3.tokenUsage,
6412
7281
  usageReporting: v3.usageReporting,
@@ -7821,8 +8690,8 @@ Respond with JSON only:
7821
8690
  }`;
7822
8691
 
7823
8692
  // src/schemas/application.ts
7824
- import { z as z24 } from "zod";
7825
- var FieldTypeSchema = z24.enum([
8693
+ import { z as z25 } from "zod";
8694
+ var FieldTypeSchema = z25.enum([
7826
8695
  "text",
7827
8696
  "numeric",
7828
8697
  "currency",
@@ -7831,223 +8700,223 @@ var FieldTypeSchema = z24.enum([
7831
8700
  "table",
7832
8701
  "declaration"
7833
8702
  ]);
7834
- var ApplicationFieldSchema = z24.object({
7835
- id: z24.string(),
7836
- label: z24.string(),
7837
- section: z24.string(),
8703
+ var ApplicationFieldSchema = z25.object({
8704
+ id: z25.string(),
8705
+ label: z25.string(),
8706
+ section: z25.string(),
7838
8707
  fieldType: FieldTypeSchema,
7839
- required: z24.boolean(),
7840
- options: z24.array(z24.string()).optional(),
7841
- columns: z24.array(z24.string()).optional(),
7842
- requiresExplanationIfYes: z24.boolean().optional(),
7843
- condition: z24.object({
7844
- dependsOn: z24.string(),
7845
- 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()
7846
8715
  }).optional(),
7847
- value: z24.string().optional(),
7848
- source: z24.string().optional().describe("Where the value came from: auto-fill, user, lookup"),
7849
- confidence: z24.enum(["confirmed", "high", "medium", "low"]).optional(),
7850
- sourceSpanIds: z24.array(z24.string()).optional().describe("Stable source spans that support the field value or field anchor"),
7851
- userSourceSpanIds: z24.array(z24.string()).optional().describe("Message or attachment spans that support user-provided values"),
7852
- pageNumber: z24.number().int().positive().optional().describe("Application page where the field label or anchor appears"),
7853
- fieldAnchorId: z24.string().optional().describe("Stable field anchor ID derived from page, section, label, and form metadata"),
7854
- acroFormName: z24.string().optional().describe("Native PDF AcroForm field name when available"),
7855
- validationStatus: z24.enum(["valid", "needs_review", "unsupported", "missing"]).optional()
7856
- });
7857
- var ApplicationQuestionConditionSchema = z24.object({
7858
- dependsOn: z24.string(),
7859
- operator: z24.enum(["equals", "not_equals", "in", "not_in", "exists"]).optional(),
7860
- value: z24.string().optional(),
7861
- whenValue: z24.string().optional(),
7862
- values: z24.array(z24.string()).optional()
7863
- });
7864
- var ApplicationRepeatSchema = z24.object({
7865
- min: z24.number().int().nonnegative().optional(),
7866
- max: z24.number().int().positive().optional(),
7867
- label: z24.string().optional()
7868
- });
7869
- var ApplicationQuestionNodeSchema = z24.lazy(
7870
- () => z24.object({
7871
- id: z24.string(),
7872
- nodeType: z24.enum(["group", "question", "repeat_group", "table"]),
7873
- fieldId: z24.string().optional(),
7874
- fieldPath: z24.string().optional(),
7875
- parentId: z24.string().optional(),
7876
- order: z24.number().int().nonnegative().optional(),
7877
- label: z24.string(),
7878
- 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(),
7879
8748
  fieldType: FieldTypeSchema.optional(),
7880
- required: z24.boolean().optional(),
7881
- prompt: z24.string().optional(),
7882
- options: z24.array(z24.string()).optional(),
7883
- 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(),
7884
8753
  condition: ApplicationQuestionConditionSchema.optional(),
7885
8754
  repeat: ApplicationRepeatSchema.optional(),
7886
- children: z24.array(ApplicationQuestionNodeSchema).optional()
8755
+ children: z25.array(ApplicationQuestionNodeSchema).optional()
7887
8756
  })
7888
8757
  );
7889
- var ApplicationQuestionGraphSchema = z24.object({
7890
- id: z24.string(),
7891
- version: z24.string(),
7892
- title: z24.string().optional(),
7893
- applicationType: z24.string().nullable().optional(),
7894
- source: z24.enum(["pdf", "manual", "imported", "generated"]).default("generated"),
7895
- rootNodeIds: z24.array(z24.string()).optional(),
7896
- nodes: z24.array(ApplicationQuestionNodeSchema)
7897
- });
7898
- var ApplicationTemplateSchema = z24.object({
7899
- id: z24.string(),
7900
- version: z24.string(),
7901
- title: z24.string(),
7902
- 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(),
7903
8772
  questionGraph: ApplicationQuestionGraphSchema,
7904
- fields: z24.array(ApplicationFieldSchema).optional()
7905
- });
7906
- var ApplicationClassifyResultSchema = z24.object({
7907
- isApplication: z24.boolean(),
7908
- confidence: z24.number().min(0).max(1),
7909
- applicationType: z24.string().nullable()
7910
- });
7911
- var FieldExtractionResultSchema = z24.object({
7912
- fields: z24.array(ApplicationFieldSchema)
7913
- });
7914
- var AutoFillMatchSchema = z24.object({
7915
- fieldId: z24.string(),
7916
- value: z24.string(),
7917
- confidence: z24.enum(["confirmed"]),
7918
- contextKey: z24.string()
7919
- });
7920
- var AutoFillResultSchema = z24.object({
7921
- matches: z24.array(AutoFillMatchSchema)
7922
- });
7923
- var QuestionBatchResultSchema = z24.object({
7924
- batches: z24.array(z24.array(z24.string()).describe("Array of field IDs in this batch"))
7925
- });
7926
- var LookupRequestSchema = z24.object({
7927
- type: z24.string().describe("Type of lookup: 'records', 'website', 'policy'"),
7928
- description: z24.string(),
7929
- url: z24.string().optional(),
7930
- targetFieldIds: z24.array(z24.string())
7931
- });
7932
- var ReplyIntentSchema = z24.object({
7933
- primaryIntent: z24.enum(["answers_only", "question", "lookup_request", "mixed"]),
7934
- hasAnswers: z24.boolean(),
7935
- questionText: z24.string().optional(),
7936
- questionFieldIds: z24.array(z24.string()).optional(),
7937
- lookupRequests: z24.array(LookupRequestSchema).optional()
7938
- });
7939
- var ParsedAnswerSchema = z24.object({
7940
- fieldId: z24.string(),
7941
- value: z24.string(),
7942
- explanation: z24.string().optional()
7943
- });
7944
- var AnswerParsingResultSchema = z24.object({
7945
- answers: z24.array(ParsedAnswerSchema),
7946
- unanswered: z24.array(z24.string()).describe("Field IDs that were not answered")
7947
- });
7948
- var LookupFillSchema = z24.object({
7949
- fieldId: z24.string(),
7950
- value: z24.string(),
7951
- source: z24.string().describe("Specific citable reference, e.g. 'GL Policy #POL-12345 (Hartford)'"),
7952
- sourceSpanIds: z24.array(z24.string()).optional()
8773
+ fields: z25.array(ApplicationFieldSchema).optional()
7953
8774
  });
7954
- var LookupFillResultSchema = z24.object({
7955
- fills: z24.array(LookupFillSchema),
7956
- unfillable: z24.array(z24.string()),
7957
- explanation: z24.string().optional()
7958
- });
7959
- var FlatPdfPlacementSchema = z24.object({
7960
- fieldId: z24.string(),
7961
- page: z24.number(),
7962
- x: z24.number().describe("Percentage from left edge (0-100)"),
7963
- y: z24.number().describe("Percentage from top edge (0-100)"),
7964
- text: z24.string(),
7965
- fontSize: z24.number().optional(),
7966
- isCheckmark: z24.boolean().optional()
7967
- });
7968
- var AcroFormMappingSchema = z24.object({
7969
- fieldId: z24.string(),
7970
- acroFormName: z24.string(),
7971
- value: z24.string()
7972
- });
7973
- var QualityGateStatusSchema = z24.enum(["passed", "warning", "failed"]);
7974
- var QualitySeveritySchema = z24.enum(["info", "warning", "blocking"]);
7975
- var ApplicationQualityIssueSchema = z24.object({
7976
- 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(),
7977
8846
  severity: QualitySeveritySchema,
7978
- message: z24.string(),
7979
- fieldId: z24.string().optional()
8847
+ message: z25.string(),
8848
+ fieldId: z25.string().optional()
7980
8849
  });
7981
- var ApplicationQualityRoundSchema = z24.object({
7982
- round: z24.number(),
7983
- kind: z24.string(),
8850
+ var ApplicationQualityRoundSchema = z25.object({
8851
+ round: z25.number(),
8852
+ kind: z25.string(),
7984
8853
  status: QualityGateStatusSchema,
7985
- summary: z24.string().optional()
8854
+ summary: z25.string().optional()
7986
8855
  });
7987
- var ApplicationQualityArtifactSchema = z24.object({
7988
- kind: z24.string(),
7989
- label: z24.string().optional(),
7990
- itemCount: z24.number().optional()
8856
+ var ApplicationQualityArtifactSchema = z25.object({
8857
+ kind: z25.string(),
8858
+ label: z25.string().optional(),
8859
+ itemCount: z25.number().optional()
7991
8860
  });
7992
- var ApplicationEmailReviewSchema = z24.object({
7993
- issues: z24.array(ApplicationQualityIssueSchema),
8861
+ var ApplicationEmailReviewSchema = z25.object({
8862
+ issues: z25.array(ApplicationQualityIssueSchema),
7994
8863
  qualityGateStatus: QualityGateStatusSchema
7995
8864
  });
7996
- var ApplicationQualityReportSchema = z24.object({
7997
- issues: z24.array(ApplicationQualityIssueSchema),
7998
- rounds: z24.array(ApplicationQualityRoundSchema).optional(),
7999
- 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(),
8000
8869
  emailReview: ApplicationEmailReviewSchema.optional(),
8001
8870
  qualityGateStatus: QualityGateStatusSchema
8002
8871
  });
8003
- var ApplicationContextProposalSchema = z24.object({
8004
- id: z24.string(),
8005
- fieldId: z24.string().optional(),
8006
- key: z24.string(),
8007
- value: z24.string(),
8008
- category: z24.string(),
8009
- source: z24.enum(["application", "user", "lookup", "policy", "email", "chat", "imessage", "mcp"]),
8010
- confidence: z24.enum(["confirmed", "high", "medium", "low"]),
8011
- sourceSpanIds: z24.array(z24.string()).optional(),
8012
- userSourceSpanIds: z24.array(z24.string()).optional()
8013
- });
8014
- var ApplicationPacketAnswerSchema = z24.object({
8015
- fieldId: z24.string(),
8016
- label: z24.string(),
8017
- section: z24.string(),
8018
- value: z24.string(),
8019
- source: z24.string(),
8020
- confidence: z24.enum(["confirmed", "high", "medium", "low"]).optional(),
8021
- sourceSpanIds: z24.array(z24.string()).optional(),
8022
- userSourceSpanIds: z24.array(z24.string()).optional()
8023
- });
8024
- var ApplicationPacketSchema = z24.object({
8025
- id: z24.string(),
8026
- applicationId: z24.string(),
8027
- title: z24.string(),
8028
- status: z24.enum(["draft", "broker_ready", "submitted"]),
8029
- answers: z24.array(ApplicationPacketAnswerSchema),
8030
- 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()),
8031
8900
  qualityReport: ApplicationQualityReportSchema,
8032
- submissionNotes: z24.string().optional(),
8033
- createdAt: z24.number()
8034
- });
8035
- var ApplicationStateSchema = z24.object({
8036
- id: z24.string(),
8037
- pdfBase64: z24.string().optional().describe("Original PDF, omitted after extraction"),
8038
- templateId: z24.string().optional(),
8039
- 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(),
8040
8909
  templateSnapshot: ApplicationTemplateSchema.optional(),
8041
- title: z24.string().optional(),
8042
- applicationType: z24.string().nullable().optional(),
8910
+ title: z25.string().optional(),
8911
+ applicationType: z25.string().nullable().optional(),
8043
8912
  questionGraph: ApplicationQuestionGraphSchema.optional(),
8044
- fields: z24.array(ApplicationFieldSchema),
8045
- batches: z24.array(z24.array(z24.string())).optional(),
8046
- currentBatchIndex: z24.number().default(0),
8047
- 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(),
8048
8917
  packet: ApplicationPacketSchema.optional(),
8049
8918
  qualityReport: ApplicationQualityReportSchema.optional(),
8050
- status: z24.enum([
8919
+ status: z25.enum([
8051
8920
  "classifying",
8052
8921
  "extracting",
8053
8922
  "auto_filling",
@@ -8061,8 +8930,8 @@ var ApplicationStateSchema = z24.object({
8061
8930
  "cancelled",
8062
8931
  "complete"
8063
8932
  ]),
8064
- createdAt: z24.number(),
8065
- updatedAt: z24.number()
8933
+ createdAt: z25.number(),
8934
+ updatedAt: z25.number()
8066
8935
  });
8067
8936
 
8068
8937
  // src/application/agents/classifier.ts
@@ -9796,106 +10665,106 @@ Respond with the final answer, deduplicated citations array, overall confidence
9796
10665
  }
9797
10666
 
9798
10667
  // src/schemas/query.ts
9799
- import { z as z25 } from "zod";
9800
- var QueryIntentSchema = z25.enum([
10668
+ import { z as z26 } from "zod";
10669
+ var QueryIntentSchema = z26.enum([
9801
10670
  "policy_question",
9802
10671
  "coverage_comparison",
9803
10672
  "document_search",
9804
10673
  "claims_inquiry",
9805
10674
  "general_knowledge"
9806
10675
  ]);
9807
- var QueryAttachmentKindSchema = z25.enum(["image", "pdf", "text"]);
9808
- var QueryAttachmentSchema = z25.object({
9809
- 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"),
9810
10679
  kind: QueryAttachmentKindSchema,
9811
- name: z25.string().optional().describe("Original filename or user-facing label"),
9812
- mimeType: z25.string().optional().describe("MIME type such as image/jpeg or application/pdf"),
9813
- base64: z25.string().optional().describe("Base64-encoded file content for image/pdf attachments"),
9814
- text: z25.string().optional().describe("Plain-text attachment content when available"),
9815
- 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")
9816
10685
  });
9817
- var QueryRetrievalModeSchema = z25.enum([
10686
+ var QueryRetrievalModeSchema = z26.enum([
9818
10687
  "graph_only",
9819
10688
  "source_rag",
9820
10689
  "long_context",
9821
10690
  "hybrid"
9822
10691
  ]);
9823
- var SubQuestionSchema = z25.object({
9824
- 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"),
9825
10694
  intent: QueryIntentSchema,
9826
- chunkTypes: z25.array(z25.string()).optional().describe("Chunk types to filter retrieval (e.g. coverage, endorsement, declaration)"),
9827
- documentFilters: z25.object({
9828
- type: z25.enum(["policy", "quote"]).optional(),
9829
- carrier: z25.string().optional(),
9830
- insuredName: z25.string().optional(),
9831
- policyNumber: z25.string().optional(),
9832
- quoteNumber: z25.string().optional(),
9833
- 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")
9834
10703
  }).optional().describe("Structured filters to narrow document lookup")
9835
10704
  });
9836
- var QueryClassifyResultSchema = z25.object({
10705
+ var QueryClassifyResultSchema = z26.object({
9837
10706
  intent: QueryIntentSchema,
9838
- subQuestions: z25.array(SubQuestionSchema).min(1).describe("Decomposed atomic sub-questions"),
9839
- requiresDocumentLookup: z25.boolean().describe("Whether structured document lookup is needed"),
9840
- requiresChunkSearch: z25.boolean().describe("Whether semantic chunk search is needed"),
9841
- 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"),
9842
10711
  retrievalMode: QueryRetrievalModeSchema.optional().describe("Preferred retrieval strategy for the query when source-span retrieval is available")
9843
10712
  });
9844
- var EvidenceItemSchema = z25.object({
9845
- source: z25.enum(["chunk", "document", "conversation", "attachment", "source_span", "source_node"]),
9846
- chunkId: z25.string().optional(),
9847
- sourceNodeId: z25.string().optional(),
9848
- sourceSpanId: z25.string().optional(),
9849
- documentId: z25.string().optional(),
9850
- turnId: z25.string().optional(),
9851
- attachmentId: z25.string().optional(),
9852
- text: z25.string().describe("Text excerpt from the source"),
9853
- 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),
9854
10723
  retrievalMode: QueryRetrievalModeSchema.optional(),
9855
10724
  sourceLocation: SourceSpanLocationSchema.optional(),
9856
- metadata: z25.array(z25.object({ key: z25.string(), value: z25.string() })).optional()
9857
- });
9858
- var AttachmentInterpretationSchema = z25.object({
9859
- summary: z25.string().describe("Concise summary of what the attachment shows or contains"),
9860
- extractedFacts: z25.array(z25.string()).describe("Specific observable or document facts grounded in the attachment"),
9861
- recommendedFocus: z25.array(z25.string()).describe("Important details to incorporate when answering follow-up questions"),
9862
- confidence: z25.number().min(0).max(1)
9863
- });
9864
- var RetrievalResultSchema = z25.object({
9865
- subQuestion: z25.string(),
9866
- evidence: z25.array(EvidenceItemSchema)
9867
- });
9868
- var CitationSchema = z25.object({
9869
- index: z25.number().describe("Citation number [1], [2], etc."),
9870
- chunkId: z25.string().optional().describe("Source chunk ID, e.g. doc-123:coverage:2"),
9871
- sourceNodeId: z25.string().optional().describe("Source tree node ID when available"),
9872
- sourceSpanId: z25.string().optional().describe("Precise source span ID when available"),
9873
- documentId: z25.string(),
9874
- documentType: z25.enum(["policy", "quote"]).optional(),
9875
- field: z25.string().optional().describe("Specific field path, e.g. coverages[0].deductible"),
9876
- quote: z25.string().describe("Exact text from source that supports the claim"),
9877
- 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),
9878
10747
  retrievalMode: QueryRetrievalModeSchema.optional(),
9879
10748
  sourceLocation: SourceSpanLocationSchema.optional()
9880
10749
  });
9881
- var SubAnswerSchema = z25.object({
9882
- subQuestion: z25.string(),
9883
- answer: z25.string(),
9884
- citations: z25.array(CitationSchema),
9885
- confidence: z25.number().min(0).max(1),
9886
- needsMoreContext: z25.boolean().describe("True if evidence was insufficient to answer fully")
9887
- });
9888
- var VerifyResultSchema = z25.object({
9889
- approved: z25.boolean().describe("Whether all sub-answers are adequately grounded"),
9890
- issues: z25.array(z25.string()).describe("Specific grounding or consistency issues found"),
9891
- retrySubQuestions: z25.array(z25.string()).optional().describe("Sub-questions that need additional retrieval or re-reasoning")
9892
- });
9893
- var QueryResultSchema = z25.object({
9894
- answer: z25.string(),
9895
- 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),
9896
10765
  intent: QueryIntentSchema,
9897
- confidence: z25.number().min(0).max(1),
9898
- 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")
9899
10768
  });
9900
10769
 
9901
10770
  // src/query/retriever.ts
@@ -10962,7 +11831,7 @@ ${sa.answer}`).join("\n\n"),
10962
11831
  }
10963
11832
 
10964
11833
  // src/pce/index.ts
10965
- import { z as z26 } from "zod";
11834
+ import { z as z27 } from "zod";
10966
11835
 
10967
11836
  // src/prompts/pce/index.ts
10968
11837
  function buildPceNormalizePrompt(input) {
@@ -10996,11 +11865,11 @@ ${input.openQuestions.map((question) => `- ${question.id}${question.fieldPath ?
10996
11865
  }
10997
11866
 
10998
11867
  // src/pce/index.ts
10999
- var ReplyAnswersSchema = z26.object({
11000
- answers: z26.array(z26.object({
11001
- questionId: z26.string().optional(),
11002
- fieldPath: z26.string().optional(),
11003
- 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()
11004
11873
  }))
11005
11874
  });
11006
11875
  function createPceAgent(config = {}) {
@@ -11754,23 +12623,23 @@ var AGENT_TOOLS = [
11754
12623
  ];
11755
12624
 
11756
12625
  // src/prompts/extractors/carrier-info.ts
11757
- import { z as z27 } from "zod";
11758
- var CarrierInfoSchema = z27.object({
11759
- carrierName: z27.string().describe("Primary insurance company name for display"),
11760
- carrierLegalName: z27.string().optional().describe("Legal entity name of insurer"),
11761
- naicNumber: z27.string().optional().describe("NAIC company code"),
11762
- amBestRating: z27.string().optional().describe("AM Best rating, e.g. 'A+ XV'"),
11763
- admittedStatus: z27.enum(["admitted", "non_admitted", "surplus_lines"]).optional().describe("Admitted status of the carrier"),
11764
- mga: z27.string().optional().describe("Managing General Agent or Program Administrator name"),
11765
- underwriter: z27.string().optional().describe("Named individual underwriter"),
11766
- brokerAgency: z27.string().optional().describe("Broker or producer agency name"),
11767
- brokerContactName: z27.string().optional().describe("Broker or producer contact person name"),
11768
- brokerLicenseNumber: z27.string().optional().describe("Broker or producer license number"),
11769
- policyNumber: z27.string().optional().describe("Policy or quote reference number"),
11770
- effectiveDate: z27.string().optional().describe("Policy effective date (MM/DD/YYYY)"),
11771
- expirationDate: z27.string().optional().describe("Policy expiration date (MM/DD/YYYY)"),
11772
- quoteNumber: z27.string().optional().describe("Quote or proposal reference number"),
11773
- 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)")
11774
12643
  });
11775
12644
  function buildCarrierInfoPrompt() {
11776
12645
  return `You are an expert insurance document analyst. Extract carrier and policy identification information from this document.
@@ -11793,21 +12662,21 @@ Return JSON only.`;
11793
12662
  }
11794
12663
 
11795
12664
  // src/prompts/extractors/named-insured.ts
11796
- import { z as z28 } from "zod";
11797
- var AdditionalNamedInsuredSchema = z28.object({
11798
- name: z28.string(),
11799
- 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"),
11800
12669
  address: SourceBackedAddressSchema.optional()
11801
12670
  }).merge(SourceProvenanceSchema);
11802
- var ScheduledPartySchema = z28.object({
11803
- name: z28.string(),
12671
+ var ScheduledPartySchema = z29.object({
12672
+ name: z29.string(),
11804
12673
  address: SourceBackedAddressSchema.optional()
11805
12674
  }).merge(SourceProvenanceSchema);
11806
- var NamedInsuredSchema2 = z28.object({
11807
- insuredName: z28.string().describe("Name of primary named insured"),
11808
- 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"),
11809
12678
  insuredAddress: SourceBackedAddressSchema.optional().describe("Primary insured mailing address"),
11810
- insuredEntityType: z28.enum([
12679
+ insuredEntityType: z29.enum([
11811
12680
  "corporation",
11812
12681
  "llc",
11813
12682
  "partnership",
@@ -11820,12 +12689,12 @@ var NamedInsuredSchema2 = z28.object({
11820
12689
  "married_couple",
11821
12690
  "other"
11822
12691
  ]).optional().describe("Legal entity type of the insured"),
11823
- insuredFein: z28.string().optional().describe("Federal Employer Identification Number"),
11824
- insuredSicCode: z28.string().optional().describe("SIC code"),
11825
- insuredNaicsCode: z28.string().optional().describe("NAICS code"),
11826
- additionalNamedInsureds: z28.array(AdditionalNamedInsuredSchema).optional().describe("Additional named insureds listed on the policy"),
11827
- lossPayees: z28.array(ScheduledPartySchema).optional().describe("Loss payees listed on the policy"),
11828
- 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")
11829
12698
  });
11830
12699
  function buildNamedInsuredPrompt() {
11831
12700
  return `You are an expert insurance document analyst. Extract all named insured information from this document.
@@ -11852,14 +12721,14 @@ Return JSON only.`;
11852
12721
  }
11853
12722
 
11854
12723
  // src/prompts/extractors/coverage-limits.ts
11855
- import { z as z29 } from "zod";
12724
+ import { z as z30 } from "zod";
11856
12725
  var ExtractorCoverageSchema = CoverageSchema.extend({
11857
- coverageCode: z29.string().optional().describe("Coverage code or class code")
12726
+ coverageCode: z30.string().optional().describe("Coverage code or class code")
11858
12727
  });
11859
- var CoverageLimitsSchema = z29.object({
11860
- coverages: z29.array(ExtractorCoverageSchema).describe("All coverages with their limits"),
11861
- coverageForm: z29.enum(["occurrence", "claims_made", "accident"]).optional().describe("Primary coverage trigger type"),
11862
- 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)")
11863
12732
  });
11864
12733
  function buildCoverageLimitsPrompt() {
11865
12734
  return `You are an expert insurance document analyst. Extract all coverage limits and deductibles from this document.
@@ -11901,14 +12770,14 @@ Return JSON only.`;
11901
12770
  }
11902
12771
 
11903
12772
  // src/prompts/extractors/endorsements.ts
11904
- import { z as z30 } from "zod";
11905
- var EndorsementsSchema = z30.object({
11906
- endorsements: z30.array(
11907
- z30.object({
11908
- formNumber: z30.string().describe("Form number, e.g. 'CG 21 47'"),
11909
- editionDate: z30.string().optional().describe("Edition date, e.g. '12 07'"),
11910
- title: z30.string().describe("Endorsement title"),
11911
- 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([
11912
12781
  "additional_insured",
11913
12782
  "waiver_of_subrogation",
11914
12783
  "primary_noncontributory",
@@ -11928,12 +12797,12 @@ var EndorsementsSchema = z30.object({
11928
12797
  "territorial_extension",
11929
12798
  "other"
11930
12799
  ]).describe("Endorsement type classification"),
11931
- effectiveDate: z30.string().optional().describe("Endorsement effective date"),
11932
- affectedCoverageParts: z30.array(z30.string()).optional().describe("Coverage parts affected by this endorsement"),
11933
- namedParties: z30.array(
11934
- z30.object({
11935
- name: z30.string().describe("Party name"),
11936
- 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([
11937
12806
  "additional_insured",
11938
12807
  "loss_payee",
11939
12808
  "mortgage_holder",
@@ -11942,18 +12811,18 @@ var EndorsementsSchema = z30.object({
11942
12811
  "designated_person",
11943
12812
  "other"
11944
12813
  ]).describe("Party role"),
11945
- relationship: z30.string().optional().describe("Relationship to insured"),
11946
- 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")
11947
12816
  })
11948
12817
  ).optional().describe("Named parties (additional insureds, loss payees, etc.)"),
11949
- keyTerms: z30.array(z30.string()).optional().describe("Key terms or notable provisions in the endorsement"),
11950
- premiumImpact: z30.string().optional().describe("Additional premium or credit"),
11951
- excerpt: z30.string().optional().describe("Short source excerpt, not full verbatim text"),
11952
- content: z30.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
11953
- pageStart: z30.number().describe("Starting page number of this endorsement"),
11954
- pageEnd: z30.number().optional().describe("Ending page number of this endorsement"),
11955
- sourceSpanIds: z30.array(z30.string()).optional().describe("Source span IDs grounding this endorsement"),
11956
- 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")
11957
12826
  })
11958
12827
  ).describe("All endorsements found in the document")
11959
12828
  });
@@ -11991,20 +12860,20 @@ Return JSON only.`;
11991
12860
  }
11992
12861
 
11993
12862
  // src/prompts/extractors/exclusions.ts
11994
- import { z as z31 } from "zod";
11995
- var ExclusionsSchema = z31.object({
11996
- exclusions: z31.array(
11997
- z31.object({
11998
- name: z31.string().describe("Exclusion title or short description"),
11999
- formNumber: z31.string().optional().describe("Form number if part of a named endorsement"),
12000
- excludedPerils: z31.array(z31.string()).optional().describe("Specific perils excluded"),
12001
- isAbsolute: z31.boolean().optional().describe("Whether the exclusion is absolute (no exceptions)"),
12002
- exceptions: z31.array(z31.string()).optional().describe("Exceptions to the exclusion, if any"),
12003
- buybackAvailable: z31.boolean().optional().describe("Whether coverage can be bought back via endorsement"),
12004
- buybackEndorsement: z31.string().optional().describe("Form number of the buyback endorsement if available"),
12005
- appliesTo: z31.array(z31.string()).optional().describe("Policy types this exclusion applies to"),
12006
- content: z31.string().describe("Full verbatim exclusion text"),
12007
- 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")
12008
12877
  })
12009
12878
  ).describe("All exclusions found in the document")
12010
12879
  });
@@ -12040,12 +12909,12 @@ Return JSON only.`;
12040
12909
  }
12041
12910
 
12042
12911
  // src/prompts/extractors/conditions.ts
12043
- import { z as z32 } from "zod";
12044
- var ConditionsSchema = z32.object({
12045
- conditions: z32.array(
12046
- z32.object({
12047
- name: z32.string().describe("Condition title"),
12048
- 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([
12049
12918
  "duties_after_loss",
12050
12919
  "notice_requirements",
12051
12920
  "other_insurance",
@@ -12064,14 +12933,14 @@ var ConditionsSchema = z32.object({
12064
12933
  "separation_of_insureds",
12065
12934
  "other"
12066
12935
  ]).describe("Condition category"),
12067
- content: z32.string().describe("Full verbatim condition text"),
12068
- keyValues: z32.array(
12069
- z32.object({
12070
- key: z32.string().describe("Key name (e.g. 'noticePeriod', 'suitDeadline')"),
12071
- 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')")
12072
12941
  })
12073
12942
  ).optional().describe("Key values extracted from the condition (notice periods, deadlines, etc.)"),
12074
- pageNumber: z32.number().optional().describe("Page number where condition appears")
12943
+ pageNumber: z33.number().optional().describe("Page number where condition appears")
12075
12944
  })
12076
12945
  ).describe("All policy conditions found in the document")
12077
12946
  });
@@ -12109,34 +12978,34 @@ Return JSON only.`;
12109
12978
  }
12110
12979
 
12111
12980
  // src/prompts/extractors/premium-breakdown.ts
12112
- import { z as z33 } from "zod";
12113
- var PremiumBreakdownSchema = z33.object({
12114
- premium: z33.string().optional().describe("Total premium amount, e.g. '$5,000'"),
12115
- premiumAmount: z33.number().optional().describe("Total premium as a plain number with no currency symbols or commas"),
12116
- totalCost: z33.string().optional().describe("Total cost including taxes and fees, e.g. '$5,250'"),
12117
- totalCostAmount: z33.number().optional().describe("Total cost as a plain number with no currency symbols or commas"),
12118
- premiumBreakdown: z33.array(
12119
- z33.object({
12120
- line: z33.string().describe("Coverage line name"),
12121
- amount: z33.string().describe("Premium amount for this line"),
12122
- 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")
12123
12992
  })
12124
12993
  ).optional().describe("Per-coverage-line premium breakdown"),
12125
- taxesAndFees: z33.array(
12126
- z33.object({
12127
- name: z33.string().describe("Fee or tax name"),
12128
- amount: z33.string().describe("Dollar amount"),
12129
- amountValue: z33.number().optional().describe("Fee or tax amount as a plain number with no currency symbols or commas"),
12130
- 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")
12131
13000
  })
12132
13001
  ).optional().describe("Taxes, fees, surcharges, and assessments"),
12133
- minimumPremium: z33.string().optional().describe("Minimum premium if stated"),
12134
- minimumPremiumAmount: z33.number().optional().describe("Minimum premium as a plain number when the source states a fixed amount"),
12135
- depositPremium: z33.string().optional().describe("Deposit premium if stated"),
12136
- depositPremiumAmount: z33.number().optional().describe("Deposit premium as a plain number when the source states a fixed amount"),
12137
- paymentPlan: z33.string().optional().describe("Payment plan description"),
12138
- auditType: z33.enum(["annual", "semi_annual", "quarterly", "monthly", "final", "self"]).optional().describe("Premium audit type"),
12139
- 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")
12140
13009
  });
12141
13010
  function buildPremiumBreakdownPrompt() {
12142
13011
  return `You are an expert insurance document analyst. Extract all premium and cost information from this document.
@@ -12158,14 +13027,14 @@ Return JSON only.`;
12158
13027
  }
12159
13028
 
12160
13029
  // src/prompts/extractors/declarations.ts
12161
- import { z as z34 } from "zod";
12162
- var DeclarationsFieldSchema = z34.object({
12163
- field: z34.string().describe("Descriptive field name (e.g. 'policyNumber', 'effectiveDate', 'coverageALimit')"),
12164
- value: z34.string().describe("Extracted value exactly as it appears in the document"),
12165
- 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')")
12166
13035
  });
12167
- var DeclarationsExtractSchema = z34.object({
12168
- 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.")
12169
13038
  });
12170
13039
  function buildDeclarationsPrompt() {
12171
13040
  return `You are an expert insurance document analyst. Extract all declarations page data from this document into a flexible key-value structure.
@@ -12205,21 +13074,21 @@ Preserve original values exactly as they appear. Return JSON only.`;
12205
13074
  }
12206
13075
 
12207
13076
  // src/prompts/extractors/loss-history.ts
12208
- import { z as z35 } from "zod";
12209
- var LossHistorySchema = z35.object({
12210
- lossSummary: z35.string().optional().describe("Summary of loss history, e.g. '3 claims in past 5 years totaling $125,000'"),
12211
- individualClaims: z35.array(
12212
- z35.object({
12213
- date: z35.string().optional().describe("Date of loss or claim"),
12214
- type: z35.string().optional().describe("Type of claim, e.g. 'property damage', 'bodily injury'"),
12215
- description: z35.string().optional().describe("Brief description of the claim"),
12216
- amountPaid: z35.string().optional().describe("Amount paid"),
12217
- amountReserved: z35.string().optional().describe("Amount reserved"),
12218
- status: z35.enum(["open", "closed", "reopened"]).optional().describe("Claim status"),
12219
- 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")
12220
13089
  })
12221
13090
  ).optional().describe("Individual claim records"),
12222
- 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'")
12223
13092
  });
12224
13093
  function buildLossHistoryPrompt() {
12225
13094
  return `You are an expert insurance document analyst. Extract all loss history and claims information from this document.
@@ -12236,21 +13105,21 @@ Return JSON only.`;
12236
13105
  }
12237
13106
 
12238
13107
  // src/prompts/extractors/sections.ts
12239
- import { z as z36 } from "zod";
12240
- var SubsectionSchema2 = z36.object({
12241
- title: z36.string().describe("Subsection title"),
12242
- sectionNumber: z36.string().optional().describe("Subsection number"),
12243
- pageNumber: z36.number().optional().describe("Page number"),
12244
- excerpt: z36.string().optional().describe("Short source excerpt, not full verbatim text"),
12245
- content: z36.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
12246
- sourceSpanIds: z36.array(z36.string()).optional().describe("Source span IDs grounding this subsection"),
12247
- sourceTextHash: z36.string().optional().describe("Hash of the source text when available")
12248
- });
12249
- var SectionsSchema = z36.object({
12250
- sections: z36.array(
12251
- z36.object({
12252
- title: z36.string().describe("Section title"),
12253
- 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([
12254
13123
  "declarations",
12255
13124
  "insuring_agreement",
12256
13125
  "policy_form",
@@ -12265,13 +13134,13 @@ var SectionsSchema = z36.object({
12265
13134
  "regulatory",
12266
13135
  "other"
12267
13136
  ]).describe("Section type classification"),
12268
- excerpt: z36.string().optional().describe("Short source excerpt, not full verbatim text"),
12269
- content: z36.string().optional().describe("Legacy fallback only; do not return full text when sourceSpanIds are available"),
12270
- pageStart: z36.number().describe("Starting page number"),
12271
- pageEnd: z36.number().optional().describe("Ending page number"),
12272
- sourceSpanIds: z36.array(z36.string()).optional().describe("Source span IDs grounding this section"),
12273
- sourceTextHash: z36.string().optional().describe("Hash of the source text when available"),
12274
- 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")
12275
13144
  })
12276
13145
  ).describe("All document sections")
12277
13146
  });
@@ -12305,20 +13174,20 @@ Return JSON only.`;
12305
13174
  }
12306
13175
 
12307
13176
  // src/prompts/extractors/supplementary.ts
12308
- import { z as z37 } from "zod";
12309
- var AuxiliaryFactSchema2 = z37.object({
12310
- key: z37.string().describe("Normalized machine-readable fact key, e.g. 'policyholder_age' or 'insured_name'"),
12311
- value: z37.string().describe("Concrete extracted fact value"),
12312
- subject: z37.string().optional().describe("Person, entity, vehicle, property, or schedule item this fact belongs to"),
12313
- context: z37.string().optional().describe("Short disambiguating context, such as 'Driver Schedule' or 'Named Insured'")
12314
- });
12315
- var SupplementarySchema = z37.object({
12316
- regulatoryContacts: z37.array(ContactSchema).optional().describe("Regulatory body contacts (state department of insurance, ombudsman)"),
12317
- claimsContacts: z37.array(ContactSchema).optional().describe("Claims reporting contacts and instructions"),
12318
- thirdPartyAdministrators: z37.array(ContactSchema).optional().describe("Third-party administrators for claims handling"),
12319
- cancellationNoticeDays: z37.number().optional().describe("Required notice period for cancellation in days"),
12320
- nonrenewalNoticeDays: z37.number().optional().describe("Required notice period for nonrenewal in days"),
12321
- 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")
12322
13191
  });
12323
13192
  function buildSupplementaryPrompt(alreadyExtractedSummary) {
12324
13193
  const exclusionBlock = alreadyExtractedSummary ? `
@@ -12358,17 +13227,17 @@ Return JSON only.`;
12358
13227
  }
12359
13228
 
12360
13229
  // src/prompts/extractors/definitions.ts
12361
- import { z as z38 } from "zod";
12362
- var DefinitionsSchema = z38.object({
12363
- definitions: z38.array(
12364
- z38.object({
12365
- term: z38.string().describe("Defined term exactly as shown in the document"),
12366
- definition: z38.string().describe("Full verbatim definition text, preserving original wording"),
12367
- pageNumber: z38.number().optional().describe("Original document page number"),
12368
- formNumber: z38.string().optional().describe("Form number where this definition appears"),
12369
- formTitle: z38.string().optional().describe("Form title where this definition appears"),
12370
- sectionRef: z38.string().optional().describe("Definition section heading or subsection reference"),
12371
- 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")
12372
13241
  })
12373
13242
  ).describe("All substantive insurance definitions found in the document")
12374
13243
  });
@@ -12402,22 +13271,22 @@ Return JSON only.`;
12402
13271
  }
12403
13272
 
12404
13273
  // src/prompts/extractors/covered-reasons.ts
12405
- import { z as z39 } from "zod";
12406
- var CoveredReasonsSchema = z39.object({
12407
- coveredReasons: z39.array(
12408
- z39.object({
12409
- coverageName: z39.string().describe("Coverage, coverage part, or form this covered reason belongs to"),
12410
- reasonNumber: z39.string().optional().describe("Source number or letter for the covered reason, if shown"),
12411
- title: z39.string().optional().describe("Covered reason title, peril, cause of loss, trigger, or short name"),
12412
- content: z39.string().describe("Full verbatim covered-reason or insuring-agreement text"),
12413
- conditions: z39.array(z39.string()).optional().describe("Conditions, timing rules, documentation requirements, or prerequisites attached to this covered reason"),
12414
- exceptions: z39.array(z39.string()).optional().describe("Exceptions or limitations attached to this covered reason"),
12415
- appliesTo: z39.array(z39.string()).optional().describe("Covered property, persons, autos, locations, operations, or coverage parts this reason applies to"),
12416
- pageNumber: z39.number().optional().describe("Original document page number"),
12417
- formNumber: z39.string().optional().describe("Form number where this covered reason appears"),
12418
- formTitle: z39.string().optional().describe("Form title where this covered reason appears"),
12419
- sectionRef: z39.string().optional().describe("Section heading where this covered reason appears"),
12420
- 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")
12421
13290
  })
12422
13291
  ).describe("Covered causes, perils, triggers, or reasons that affirmatively grant coverage")
12423
13292
  });
@@ -13409,10 +14278,15 @@ export {
13409
14278
  NamedInsuredSchema,
13410
14279
  OperationalAddressSchema,
13411
14280
  OperationalCoverageLineSchema,
14281
+ OperationalCoverageScheduleItemSchema,
14282
+ OperationalCoverageScheduleSchema,
14283
+ OperationalCoverageScheduleValueSchema,
13412
14284
  OperationalCoverageTermSchema,
13413
14285
  OperationalDeclarationFactSchema,
13414
14286
  OperationalEndorsementSupportSchema,
13415
14287
  OperationalPartySchema,
14288
+ OperationalPremiumLineSchema,
14289
+ OperationalTaxFeeItemSchema,
13416
14290
  PERSONAL_AUTO_USAGES,
13417
14291
  PERSONAL_LOB_CODES,
13418
14292
  PET_SPECIES,
@@ -13599,6 +14473,8 @@ export {
13599
14473
  proposeContextWrites,
13600
14474
  resolveModelBudget,
13601
14475
  resolveOperationalProfileLinesOfBusiness,
14476
+ runCoverageRecovery,
14477
+ runSourceTreeExtraction,
13602
14478
  safeGenerateObject,
13603
14479
  sanitizeNulls,
13604
14480
  scoreCaseProposal,