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 // Each input is an alias. The levels it maps to are the model's efforts:
85 // a `none` that maps to `low` does not turn thinking off.
86 const efforts = new Set<string>()
87 let mandatory: boolean | null = null
88 for (const clause of clauses) {
89 const targetMatch =
90 locale === 'en'
91 ? clause.match(/(?:are|is) mapped to `([a-z]+)`\.?$/)
92 : clause.match(/映射为 `([a-z]+)`$/)
93 const stops =
94 locale === 'en'
95 ? /indicate that the model stops thinking/.test(clause)
96 : /代表模型放弃思考/.test(clause)
97 if (!targetMatch && !stops)
98 failure(`unreadable Coding effort clause: ${clause}`)
99 const input = targetMatch ? clause.slice(0, targetMatch.index) : clause
100 const values = [...input.matchAll(/`([a-z]+)`/g)].map(
101 (match) => match[1]!,
102 )
103 if (!values.length) failure('empty effort values')
104 for (const value of values) {
105 const target = targetMatch?.[1] ?? value
106 if (mapping.has(value) && mapping.get(value) !== target)
107 failure('conflicting effort mapping')
108 mapping.set(value, target)
109 efforts.add(target)
110 if (stops && (value === 'none' || value === 'minimal'))
111 mandatory = false
112 }
113 }
114 const levels: EffortLevelMap = {
115 off: mandatory === false ? (mapping.get('none') ?? null) : null,
116 minimal: mapping.get('minimal') ?? null,
117 low: mapping.get('low') ?? null,
118 medium: mapping.get('medium') ?? null,
119 high: mapping.get('high') ?? null,
120 xhigh: mapping.get('xhigh') ?? null,
121 max: mapping.get('max') ?? null,
122 }
123 for (const id of ids) {
124 if (rows.has(id)) failure('duplicate Coding effort model')
125 if (mandatory === false && forced.has(id))
126 failure('contradictory native mandatory thinking evidence')
127 rows.set(id, {
128 efforts: [...efforts],
129 mandatory: forced.has(id) ? true : mandatory,
130 levels,
131 })
132 }
133 }
134 return rows
135}
136
137export function parseGlmCodingModels(
138 docs: { overview: CodingDoc; latest: CodingDoc; thinking: CodingDoc },
139 locale: CodingLocale,
140): ModelInfo[] {
141 for (const role of ['overview', 'latest', 'thinking'] as const)
142 validateCodingDoc(docs[role], role, locale)
143 const support = docs.overview.text
144 .split('\n')
145 .filter((line) =>
146 locale === 'en'
147 ? /All plans support[ *]*GLM-/i.test(line)
148 : /所有套餐均支持/.test(line),
149 )
150 if (support.length !== 1)
151 failure('missing or ambiguous supported-plan model list')
152 const ids = names(support[0]!)
153 if (!ids.length) failure('no native supported-plan models')
154 // Scope the count to the actual tool setting, not unrelated compression fields.
155 const contextLines = docs.latest.text
156 .split('\n')
157 .filter((line) => /Context Window Size/.test(line))
158 if (contextLines.length > 1) failure('ambiguous plan context setting')
159 const contextText = contextLines[0]
160 const contextMatch = contextText?.match(
161 /Context Window Size[^\n]*?(?:`(\d+)`|to (\d+)(?=$|\s|[.;](?:$|\s)))/,
162 )
163 if (contextText && !contextMatch) failure('unreadable plan context setting')
164 const contextWindow = contextMatch
165 ? Number(contextMatch[1] ?? contextMatch[2])
166 : null
167 if (
168 contextWindow !== null &&
169 (!Number.isSafeInteger(contextWindow) || contextWindow <= 0)
170 )
171 failure('invalid plan context limit')
172 const effortRows = codingEfforts(docs.thinking, locale)
173 return ids.map((rawId) => {
174 const effort = effortRows.get(rawId)
175 const high = effort?.levels.high
176 const requestMap: ChatRequestMap | null =
177 effort && high
178 ? {
179 // This is the explicit Coding request control, not a compatibility body.
180 thinking: {
181 on: { reasoning_effort: high },
182 off:
183 effort.mandatory === false && effort.levels.off
184 ? { reasoning_effort: effort.levels.off }
185 : null,
186 levels: effort.levels,
187 },
188 maxTokensField: null,
189 developerRole: null,
190 replayReasoningContent: null,
191 store: null,
192 strictTools: null,
193 sessionAffinity: null,
194 cacheControl: null,
195 toolStream: null,
196 reasoningEffort: true,
197 }
198 : null
199 const mediaLine = docs.latest.text
200 .split('\n')
201 .find(
202 (line) => names(line).includes(rawId) && /Support Images/.test(line),
203 )
204 // Native guide puts both model clauses on one line; scope to the named clause.
205 const mediaClause = mediaLine
206 ?.split(/[;;,,]|\bso\b|,因此/)
207 .find((clause) => names(clause).includes(rawId))
208 const textOnly = mediaClause && /text-only|文本模型/.test(mediaClause)
209 const image = mediaClause && /multimodal|多模态/.test(mediaClause)
210 const modalities = textOnly
211 ? { input: ['text'], output: null }
212 : image
213 ? { input: ['image'], output: null }
214 : null
215 return {
216 rawId,
217 displayName: null,
218 activity: 'chat',
219 contextWindow,
220 maxOutput: null,
221 modalities,
222 pricing: null,
223 absent: { pricing: 'cleared' },
224 schemaEndpointId: null,
225 serverTools: null,
226 reasoning: effort
227 ? {
228 mode: 'effort',
229 mandatory: effort.mandatory,
230 efforts: effort.efforts,
231 }
232 : null,
233 capabilities: effort ? ['reasoning', 'reasoning_effort'] : null,
234 requestMap,
235 factSources: {
236 ...(contextWindow !== null
237 ? { contextWindow: source(docs.latest, 'Context Window Size') }
238 : {}),
239 ...(modalities
240 ? { modalities: source(docs.latest, 'Support Images tool setting') }
241 : {}),
242 ...(effort
243 ? {
244 reasoning: source(
245 docs.thinking,
246 'Coding Plan reasoning_effort mapping',
247 ),
248 requestMap: source(
249 docs.thinking,
250 'Coding Plan reasoning_effort mapping',
251 ),
252 capabilities: {
253 reasoning: source(
254 docs.thinking,
255 'Coding Plan reasoning_effort mapping',
256 ),
257 reasoning_effort: source(
258 docs.thinking,
259 'Coding Plan reasoning_effort mapping',
260 ),
261 },
262 }
263 : {}),
264 },
265 }
266 })
267}