Open History to see the last commit
1/** Replay facts parsed from each host's own published documentation. */
2import { cachedDocs } from './model-facts.ts'
3import type { ChatRequestMap } from './request-map.ts'
4import { fetchText, sha256Text, timeoutSignal } from './types.ts'
5import type { FactSource, ModelInfo, ModelReasoning } from './types.ts'
6
7export const DEEPSEEK_THINKING_URL =
8 'https://api-docs.deepseek.com/guides/thinking_mode/'
9export const ZAI_THINKING_MODE_URL =
10 'https://docs.z.ai/guides/capabilities/thinking-mode.md'
11export const ZHIPU_THINKING_MODE_URL =
12 'https://docs.bigmodel.cn/cn/guide/capabilities/thinking-mode.md'
13export const KIMI_THINKING_URL =
14 'https://platform.kimi.ai/docs/guide/use-thinking-models.md'
15export const KIMI_CN_THINKING_URL =
16 'https://platform.kimi.com/docs/guide/use-thinking-models.md'
17
18function record(value: unknown): value is Record<string, unknown> {
19 return value !== null && typeof value === 'object' && !Array.isArray(value)
20}
21
22/** A native model-specific effort list is a control, not evidence it is mandatory. */
23export function deepseekEffortFacts(
24 effort: unknown,
25): { reasoning: ModelReasoning; source: FactSource } | null {
26 if (effort == null) return null
27 if (!record(effort)) throw new Error('deepseek: unreadable effort metadata')
28 const levels = effort.supported_levels
29 if (levels === undefined) return null
30 if (
31 !Array.isArray(levels) ||
32 levels.length === 0 ||
33 !levels.every((level) => typeof level === 'string' && level.length > 0)
34 )
35 throw new Error('deepseek: unreadable supported_levels')
36 const efforts = levels as Array<string>
37 return {
38 reasoning: {
39 mode: 'effort',
40 mandatory: null,
41 efforts,
42 },
43 source: {
44 derivation: 'listing',
45 sourceUrl: 'https://api.deepseek.com/models',
46 path: 'data[].effort.supported_levels',
47 },
48 }
49}
50
51export function replayRequestMap(
52 existing?: ChatRequestMap | null,
53): ChatRequestMap {
54 const base: ChatRequestMap = {
55 thinking: null,
56 maxTokensField: null,
57 developerRole: null,
58 replayReasoningContent: true,
59 store: null,
60 strictTools: null,
61 sessionAffinity: null,
62 cacheControl: null,
63 toolStream: null,
64 reasoningEffort: null,
65 }
66 return { ...base, ...existing, replayReasoningContent: true }
67}
68
69function plain(text: string): string {
70 return text
71 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
72 .replace(/<[^>]+>/g, ' ')
73 .replace(/\\_/g, '_')
74 .replace(/[*`]/g, '')
75 .replace(/\s+/g, ' ')
76}
77
78/** The native guide requires replay with tools; without tools it says it is ignored. */
79export function parseDeepseekReplay(text: string): true {
80 const prose = plain(text)
81 if (
82 !/request carries the tools parameter.{0,240}reasoning_content.{0,160}passed back/i.test(
83 prose,
84 ) ||
85 !/does not carry the tools parameter.{0,200}reasoning_content.{0,240}ignored/i.test(
86 prose,
87 )
88 )
89 throw new Error(
90 'deepseek: thinking guide has no verified tool replay contract',
91 )
92 return true
93}
94
95/**
96 * Models the thinking guide gives a non-thinking mode of their own: the
97 * `top_p` bullet that names the model says what happens "in non-thinking
98 * mode". The toggle table is shared by every model, so it binds none.
99 */
100export function parseDeepseekNonThinking(text: string): Array<string> {
101 const ids = [
102 ...plain(text).matchAll(
103 /\b(deepseek-[a-z0-9.-]*[a-z0-9])\s*:[^:]*?\bin non-thinking mode\b/gi,
104 ),
105 ].map((match) => (match[1] ?? '').toLowerCase())
106 return [...new Set(ids)]
107}
108
109/** Only explicitly named models are bound; no inferred model-family membership. */
110export function parseGlmReplay(text: string): Array<string> {
111 const prose = plain(text)
112 const instruction =
113 /thinking blocks.{0,150}preserv.{0,150}return.{0,150}tool results/i.test(
114 prose,
115 ) || /必须显式保留.{0,80}Reasoning content.{0,80}返回工具结果/i.test(prose)
116 if (!instruction || !prose.includes('reasoning_content'))
117 throw new Error(
118 'glm: thinking-mode guide has no verified replay instruction',
119 )
120 const section = text
121 .split(/^## /m)
122 .find((part) =>
123 /^(?:\*\*)?Default Thinking Behaviour|^默认思考行为/.test(part),
124 )
125 const ids = [
126 ...new Set(
127 (section?.match(/\bGLM-\d+(?:\.\d+)?(?:-FLASH)?\b/g) ?? []).map((id) =>
128 id.toLowerCase(),
129 ),
130 ),
131 ]
132 const interleaved = text
133 .split(/^## /m)
134 .find((part) => part.startsWith('**Interleaved thinking'))
135 // The native guide names the first supported model explicitly. It does
136 // not enumerate variants; only that exact id gets this tool-turn rule.
137 const since = interleaved?.match(
138 /supported since (GLM-\d+(?:\.\d+)?(?:-[A-Za-z0-9]+)*)(?![\w-]|\.\d)/,
139 )?.[1]
140 if (
141 since &&
142 /thinking blocks should be explicitly preserved/i.test(plain(interleaved))
143 )
144 ids.push(since.toLowerCase())
145 if (ids.length === 0)
146 throw new Error('glm: thinking-mode guide names no supported model ids')
147 return [...new Set(ids)]
148}
149
150export function parseKimiReplay(text: string): Array<string> {
151 const prose = plain(text)
152 if (
153 !prose.includes('reasoning_content') ||
154 !(
155 /complete assistant message.{0,180}(?:back|including)/i.test(prose) ||
156 /完整 assistant message.{0,80}(?:回传|reasoning_content)/i.test(prose)
157 )
158 )
159 throw new Error('kimi: thinking guide has no verified replay instruction')
160 const preamble = text.split(/^## (?:Basic calls|基本调用)/m)[0] ?? ''
161 const ids = [...new Set(preamble.match(/\bkimi-[a-z0-9][a-z0-9.-]*/g) ?? [])]
162 if (ids.length === 0)
163 throw new Error('kimi: thinking guide names no supported model ids')
164 return ids
165}
166
167export function explicitCardReplay(text: string): boolean {
168 return /must pass back the complete assistant message.{0,180}reasoning_content/i.test(
169 plain(text),
170 )
171}
172
173/**
174 * `verify` runs before the body is cached, so a page it rejects is
175 * refetched next poll instead of being served from KV for six hours.
176 */
177export async function loadReplayDoc(
178 url: string,
179 kv?: KVNamespace,
180 cached: typeof cachedDocs = cachedDocs,
181 verify?: (text: string) => unknown,
182): Promise<{ text: string; source: FactSource }> {
183 const doc = await cached(kv, url, async () => {
184 const text = await fetchText(url, { signal: timeoutSignal(30_000) })
185 if (
186 /^\s*<(?:!doctype|html)/i.test(text) &&
187 !url.includes('api-docs.deepseek.com')
188 )
189 throw new Error(`replay docs: ${url} returned HTML`)
190 verify?.(text)
191 return { text, hash: await sha256Text(text) }
192 })
193 return {
194 text: doc.text,
195 source: {
196 derivation: 'docs-derived',
197 sourceUrl: url,
198 sourceHash: doc.hash,
199 path: 'reasoning_content',
200 },
201 }
202}
203
204export function applyReplay(model: ModelInfo, source: FactSource): ModelInfo {
205 return {
206 ...model,
207 requestMap: replayRequestMap(model.requestMap),
208 factSources: {
209 ...model.factSources,
210 requestMap: model.factSources?.requestMap ?? source,
211 requestMapFields: {
212 ...model.factSources?.requestMapFields,
213 replayReasoningContent: source,
214 },
215 },
216 }
217}