Open History to see the last commit
1/** Plan-only facts. General pay-as-you-go bodies and prices are not borrowed. */
2import type { ChatRequestMap, EffortLevelMap } from './request-map.ts'
3import type { FactSource, ModelInfo } from './types.ts'
4
5export interface CodingDoc {
6 text: string
7 url: string
8 hash: string
9}
10export type CodingLocale = 'en' | 'zh'
11const failure = (message: string): never => {
12 throw new Error(`glm coding: ${message}`)
13}
14function source(doc: CodingDoc, path: string): FactSource {
15 return {
16 derivation: 'docs-derived',
17 sourceUrl: doc.url,
18 sourceHash: doc.hash,
19 path,
20 }
21}
22function names(text: string): string[] {
23 return [
24 ...new Set(
25 (text.match(/GLM-[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?/gi) ?? []).map((id) =>
26 id.toLowerCase(),
27 ),
28 ),
29 ]
30}
31export function validateCodingDoc(
32 doc: CodingDoc,
33 role: 'overview' | 'latest' | 'thinking',
34 locale: CodingLocale,
35): void {
36 if (/^\s*<(?:!doctype|html)/i.test(doc.text))
37 failure(`${doc.url} returned HTML`)
38 const titles =
39 locale === 'en'
40 ? {
41 overview: 'Overview',
42 latest: 'How to Switch Models',
43 thinking: 'Deep Thinking',
44 }
45 : { overview: '套餐概览', latest: '如何切换模型', thinking: '深度思考' }
46 const title = doc.text.match(/^# ([^\n]+)$/m)?.[1]?.trim()
47 if (title !== titles[role])
48 failure(`${doc.url}: missing native ${role} document heading`)
49}
50function forcedModels(doc: CodingDoc, locale: CodingLocale): Set<string> {
51 const lines = doc.text
52 .split('\n')
53 .filter((line) =>
54 locale === 'en'
55 ? /no longer support disabling thinking/.test(line)
56 : /不再支持关闭思考/.test(line),
57 )
58 return new Set(lines.flatMap(names))
59}
60function codingEfforts(doc: CodingDoc, locale: CodingLocale) {
61 const block =
62 locale === 'en'
63 ? doc.text.match(
64 /In the Coding Plan request:\s*\n((?:[ \t]+\* .*\n)+)/,
65 )?.[1]
66 : doc.text.match(/在 Coding Plan 请求中[ \t]*\n((?:[ \t]+\* .*\n)+)/)?.[1]
67 if (!block) return failure('missing explicit Coding Plan effort block')
68 const forced = forcedModels(doc, locale)
69 const rows = new Map<
70 string,
71 { efforts: string[]; mandatory: boolean | null; levels: EffortLevelMap }
72 >()
73 for (const line of block.trimEnd().split('\n')) {
74 const modelEnd = locale === 'en' ? line.indexOf(',') : line.indexOf(',')
75 if (modelEnd < 0) failure('unreadable effort model scope')
76 const ids = names(line.slice(0, modelEnd))
77 if (!ids.length) failure('effort row has no model scope')
78 const clauses = line
79 .slice(modelEnd + 1)
80 .split(/[;;]/)
81 .map((clause) => clause.trim())
82 .filter(Boolean)
83 const mapping = new Map<string, string>()
84 const efforts = new Set<string>()
85 let mandatory: boolean | null = null
86 for (const clause of clauses) {
87 const targetMatch =
88 locale === 'en'
89 ? clause.match(/(?:are|is) mapped to `([a-z]+)`\.?$/)
90 : clause.match(/映射为 `([a-z]+)`$/)
91 const stops =
92 locale === 'en'
93 ? /indicate that the model stops thinking/.test(clause)
94 : /代表模型放弃思考/.test(clause)
95 if (!targetMatch && !stops)
96 failure(`unreadable Coding effort clause: ${clause}`)
97 const input = targetMatch ? clause.slice(0, targetMatch.index) : clause
98 const values = [...input.matchAll(/`([a-z]+)`/g)].map(
99 (match) => match[1]!,
100 )
101 if (!values.length) failure('empty effort values')
102 for (const value of values) {
103 const target = targetMatch?.[1] ?? value
104 if (mapping.has(value) && mapping.get(value) !== target)
105 failure('conflicting effort mapping')
106 mapping.set(value, target)
107 efforts.add(value)
108 if (stops && (value === 'none' || value === 'minimal'))
109 mandatory = false
110 }
111 }
112 const levels: EffortLevelMap = {
113 off: mandatory === false ? (mapping.get('none') ?? null) : null,
114 minimal: mapping.get('minimal') ?? null,
115 low: mapping.get('low') ?? null,
116 medium: mapping.get('medium') ?? null,
117 high: mapping.get('high') ?? null,
118 xhigh: mapping.get('xhigh') ?? null,
119 max: mapping.get('max') ?? null,
120 }
121 for (const id of ids) {
122 if (rows.has(id)) failure('duplicate Coding effort model')
123 if (mandatory === false && forced.has(id))
124 failure('contradictory native mandatory thinking evidence')
125 rows.set(id, {
126 efforts: [...efforts],
127 mandatory: forced.has(id) ? true : mandatory,
128 levels,
129 })
130 }
131 }
132 return rows
133}
134
135export function parseGlmCodingModels(
136 docs: { overview: CodingDoc; latest: CodingDoc; thinking: CodingDoc },
137 locale: CodingLocale,
138): ModelInfo[] {
139 for (const role of ['overview', 'latest', 'thinking'] as const)
140 validateCodingDoc(docs[role], role, locale)
141 const support = docs.overview.text
142 .split('\n')
143 .filter((line) =>
144 locale === 'en'
145 ? /All plans support[ *]*GLM-/i.test(line)
146 : /所有套餐均支持/.test(line),
147 )
148 if (support.length !== 1)
149 failure('missing or ambiguous supported-plan model list')
150 const ids = names(support[0]!)
151 if (!ids.length) failure('no native supported-plan models')
152 // Scope the count to the actual tool setting, not unrelated compression fields.
153 const contextLines = docs.latest.text
154 .split('\n')
155 .filter((line) => /Context Window Size/.test(line))
156 if (contextLines.length > 1) failure('ambiguous plan context setting')
157 const contextText = contextLines[0]
158 const contextMatch = contextText?.match(
159 /Context Window Size[^\n]*?(?:`(\d+)`|to (\d+)(?=$|\s|[.;](?:$|\s)))/,
160 )
161 if (contextText && !contextMatch) failure('unreadable plan context setting')
162 const contextWindow = contextMatch
163 ? Number(contextMatch[1] ?? contextMatch[2])
164 : null
165 if (
166 contextWindow !== null &&
167 (!Number.isSafeInteger(contextWindow) || contextWindow <= 0)
168 )
169 failure('invalid plan context limit')
170 const effortRows = codingEfforts(docs.thinking, locale)
171 return ids.map((rawId) => {
172 const effort = effortRows.get(rawId)
173 const high = effort?.levels.high
174 const requestMap: ChatRequestMap | null =
175 effort && high
176 ? {
177 // This is the explicit Coding request control, not a compatibility body.
178 thinking: {
179 on: { reasoning_effort: high },
180 off:
181 effort.mandatory === false && effort.levels.off
182 ? { reasoning_effort: effort.levels.off }
183 : null,
184 levels: effort.levels,
185 },
186 maxTokensField: null,
187 developerRole: null,
188 replayReasoningContent: null,
189 store: null,
190 strictTools: null,
191 sessionAffinity: null,
192 cacheControl: null,
193 toolStream: null,
194 reasoningEffort: true,
195 }
196 : null
197 const mediaLine = docs.latest.text
198 .split('\n')
199 .find(
200 (line) => names(line).includes(rawId) && /Support Images/.test(line),
201 )
202 // Native guide puts both model clauses on one line; scope to the named clause.
203 const mediaClause = mediaLine
204 ?.split(/[;;,,]|\bso\b|,因此/)
205 .find((clause) => names(clause).includes(rawId))
206 const textOnly = mediaClause && /text-only|文本模型/.test(mediaClause)
207 const image = mediaClause && /multimodal|多模态/.test(mediaClause)
208 const modalities = textOnly
209 ? { input: ['text'], output: null }
210 : image
211 ? { input: ['image'], output: null }
212 : null
213 return {
214 rawId,
215 displayName: null,
216 activity: 'chat',
217 contextWindow,
218 maxOutput: null,
219 modalities,
220 pricing: null,
221 absent: { pricing: 'cleared' },
222 schemaEndpointId: null,
223 serverTools: null,
224 reasoning: effort
225 ? {
226 mode: 'effort',
227 mandatory: effort.mandatory,
228 efforts: effort.efforts,
229 }
230 : null,
231 capabilities: effort ? ['reasoning', 'reasoning_effort'] : null,
232 requestMap,
233 factSources: {
234 ...(contextWindow !== null
235 ? { contextWindow: source(docs.latest, 'Context Window Size') }
236 : {}),
237 ...(modalities
238 ? { modalities: source(docs.latest, 'Support Images tool setting') }
239 : {}),
240 ...(effort
241 ? {
242 reasoning: source(
243 docs.thinking,
244 'Coding Plan reasoning_effort mapping',
245 ),
246 requestMap: source(
247 docs.thinking,
248 'Coding Plan reasoning_effort mapping',
249 ),
250 capabilities: {
251 reasoning: source(
252 docs.thinking,
253 'Coding Plan reasoning_effort mapping',
254 ),
255 reasoning_effort: source(
256 docs.thinking,
257 'Coding Plan reasoning_effort mapping',
258 ),
259 },
260 }
261 : {}),
262 },
263 }
264 })
265}