Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

source-silent-facts.ts

192 lines5.9 KB

1/** Read-time evidence for provider facts absent from the published sources. */
2import { parseLedger } from '#/lib/completeness.ts'
3import type { LedgerKey } from '#/lib/completeness.ts'
4import {
5 modelLedgerScope,
6 parseLedgerEntry,
7} from '#/lib/source-silence-ledger.ts'
8import type { ChatRequestMap } from './providers/request-map.ts'
9import type {
10 FactSource,
11 ModelFactSources,
12 SourceSilentEvidence,
13} from './providers/types.ts'
14​
15export type { SourceSilentEvidence }
16​
17export type ApiFactSource = FactSource | SourceSilentEvidence
18​
19/** Stored ingest provenance remains unchanged; silence is added only on reads. */
20export type ApiModelFactSources = Omit<
21 ModelFactSources,
22 | 'contextWindow'
23 | 'maxOutput'
24 | 'modalities'
25 | 'pricing'
26 | 'reasoning'
27 | 'requestMap'
28 | 'capabilities'
29 | 'serverTools'
30 | 'schemaEndpointId'
31 | 'requestMapFields'
32 | 'cacheRead'
33> & {
34 contextWindow?: ApiFactSource
35 maxOutput?: ApiFactSource
36 modalities?: ApiFactSource
37 pricing?: ApiFactSource
38 reasoning?: ApiFactSource
39 requestMap?: ApiFactSource
40 requestMapFields?: Partial<Record<keyof ChatRequestMap, ApiFactSource>>
41 capabilities?: Record<string, FactSource> | SourceSilentEvidence
42 serverTools?: Record<string, FactSource> | SourceSilentEvidence
43 schemaEndpointId?: ApiFactSource
44 /** A stated "-" or blank cached-input cell, or a ledgered absence. */
45 cacheRead?: ApiFactSource
46 efforts?: SourceSilentEvidence
48​
49export type SourceSilentEvidenceLedger = Map<
50 string,
51 Map<LedgerKey, SourceSilentEvidence>
53​
54/** Same entry grammar as scoring; metadata is copied only when actually recorded. */
55export function parseSourceSilentEvidence(
56 markdown: string,
57): SourceSilentEvidenceLedger {
58 const ledger = parseLedger(markdown)
59 const evidence: SourceSilentEvidenceLedger = new Map()
60 for (const line of markdown.split('\n')) {
61 const entry = parseLedgerEntry(line)
62 if (!entry) continue
63 const { scope } = entry
64 const key = entry.fact as LedgerKey
65 if (!ledger.get(scope)?.has(key)) continue
66 const url = /https?:\/\/[^\s,`)]+/.exec(line)?.[0]
67 const date = /\bchecked\s+([^\s,`);.]+)/.exec(line)?.[1]
68 if (date) {
69 const time = Date.parse(`${date}T00:00:00Z`)
70 if (
71 !/^\d{4}-\d{2}-\d{2}$/.test(date) ||
72 !Number.isFinite(time) ||
73 new Date(time).toISOString().slice(0, 10) !== date
74 ) {
75 throw new Error(`source-silent ledger: invalid checked date ${date}`)
76 }
77 }
78 const source: SourceSilentEvidence = {
79 derivation: 'source-silent',
80 ...(url ? { sourceUrl: url } : {}),
81 ...(date ? { checkedAt: date } : {}),
82 }
83 const entries =
84 evidence.get(scope) ?? new Map<LedgerKey, SourceSilentEvidence>()
85 if (entries.has(key))
86 throw new Error(`source-silent ledger: duplicate ${scope}: ${key}`)
87 entries.set(key, source)
88 evidence.set(scope, entries)
89 }
90 return evidence
92​
93interface SilentModelFacts {
94 providerId: string
95 rawId?: string
96 activity: string | null
97 contextWindow: unknown
98 maxOutput: unknown
99 modalities: unknown
100 pricing: unknown
101 capabilities: unknown
102 reasoning: unknown
103 requestMap: unknown
104 serverTools?: unknown
106​
107function record(value: unknown): value is Record<string, unknown> {
108 return value !== null && typeof value === 'object' && !Array.isArray(value)
110​
111function missingCacheRead(pricing: unknown): boolean {
112 if (
113 !record(pricing) ||
114 !record(pricing.tables) ||
115 !record(pricing.tables.rate)
116 )
117 return true
118 return !Object.values(pricing.tables.rate).some(
119 (tier) =>
120 record(tier) &&
121 (tier.cache_read_tokens != null || tier.input_cache_read != null),
122 )
124​
125/** Never alter model values, populated-fact provenance, or resolved identity evidence. */
126export function withSourceSilentEvidence(
127 row: SilentModelFacts,
128 schemaEndpointId: string | null,
129 stored: ModelFactSources | null,
130 ledger: SourceSilentEvidenceLedger,
131): ApiModelFactSources | null {
132 // The source-silent ledger describes the chat facts scored by completeness.
133 if (row.activity !== 'chat') return stored
134 const entries = new Map([
135 ...(ledger.get(row.providerId) ?? []),
136 ...(row.rawId !== undefined
137 ? (ledger.get(modelLedgerScope(row.providerId, row.rawId)) ?? [])
138 : []),
139 ])
140 if (!entries.size) return stored
141 const sources: ApiModelFactSources = { ...stored }
142 for (const [key, evidence] of entries) {
143 switch (key) {
144 case 'contextWindow':
145 case 'maxOutput':
146 case 'modalities':
147 case 'capabilities':
148 case 'reasoning':
149 case 'requestMap':
150 if (row[key] == null) sources[key] = evidence
151 break
152 // Evidence only: a stored source (a poll-time silence) stays.
153 case 'serverTools':
154 if (row.serverTools == null && stored?.serverTools == null)
155 sources.serverTools = evidence
156 break
157 case 'replayReasoningContent':
158 if (
159 !record(row.requestMap) ||
160 row.requestMap.replayReasoningContent == null
161 )
162 sources.requestMapFields = {
163 ...sources.requestMapFields,
164 replayReasoningContent: evidence,
165 }
166 break
167 case 'priced':
168 if (row.pricing == null) sources.pricing = evidence
169 break
170 case 'endpoint':
171 if (schemaEndpointId === null) sources.schemaEndpointId = evidence
172 break
173 case 'cacheRead':
174 // A stored `not-offered` source is the stated absence. The ledger
175 // only fills a price the row does not already explain.
176 if (missingCacheRead(row.pricing) && stored?.cacheRead == null)
177 sources.cacheRead = evidence
178 break
179 case 'efforts':
180 if (
181 record(row.reasoning) &&
182 (row.reasoning.mode === 'effort' ||
183 row.reasoning.mode === 'adaptive') &&
184 (!Array.isArray(row.reasoning.efforts) ||
185 row.reasoning.efforts.length === 0)
186 )
187 sources.efforts = evidence
188 break
189 }
190 }
191 return Object.keys(sources).length ? sources : stored