@hex4c59/pi-ext-copilot-auto 0.0.0-stage → 0.1.1

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/lib/client.ts ADDED
@@ -0,0 +1,516 @@
1
+ /**
2
+ * Copilot API 的 HTTP 客户端。
3
+ *
4
+ * 封装本扩展涉及的五个端点:
5
+ * POST /auto Auto 路由(新通道,返回完整模型对象)
6
+ * POST /models/session Auto 路由(旧通道,返回 id 与授权清单)
7
+ * GET /models 模型目录(能力、端点、计费)
8
+ * GET /copilot_internal/user 账号信息、额度,以及 endpoints.api
9
+ * POST /copilot_internal/v2/token 用 GitHub OAuth 令牌换取 Copilot 访问令牌
10
+ *
11
+ * 关键实测结论(2026-11-11):
12
+ * - `/auto` 只接受 `X-GitHub-Api-Version: 2026-08-01`,用旧版本得到 404;
13
+ * - `/models` 与 `/auto` **都接受 GitHub OAuth refresh token**,
14
+ * 不强制要求尚未过期的 Copilot access token;
15
+ * - 两者也接受有效的 Copilot access token。
16
+ *
17
+ * 这里不记录令牌,错误信息中也不包含任何凭据内容。
18
+ */
19
+
20
+ import {
21
+ API_VERSION,
22
+ AUTO_API_VERSION,
23
+ CLIENT_HEADERS,
24
+ SERVER_EXPIRY_SKEW_MS,
25
+ SESSION_TIMEOUT_MS,
26
+ type AutoRouteResponse,
27
+ type AutoSession,
28
+ type AutoSessionResponse,
29
+ type AutoSessionTokenPayload,
30
+ type CatalogEntry,
31
+ type CatalogResponse,
32
+ type CopilotUserResponse,
33
+ } from './protocol.ts'
34
+ import { AUTO_MODEL_ID } from './catalog.ts'
35
+ import { decodeSessionToken } from './token.ts'
36
+ import type { CopilotAccount } from './account.ts'
37
+
38
+ /** 一次请求的上下文:令牌与 API 根地址。 */
39
+ export interface RequestTarget {
40
+ token: string
41
+ baseUrl: string
42
+ signal?: AbortSignal
43
+ }
44
+
45
+ /** 构造带认证与客户端身份的标准请求头。 */
46
+ function headers(target: RequestTarget, extra?: Record<string, string>): Record<string, string> {
47
+ return {
48
+ Authorization: `Bearer ${target.token}`,
49
+ ...CLIENT_HEADERS,
50
+ 'X-GitHub-Api-Version': API_VERSION,
51
+ ...extra,
52
+ }
53
+ }
54
+
55
+ /** 从错误响应中提取可读信息,避免把整个响应体写入日志。 */
56
+ async function describeFailure(response: Response): Promise<string> {
57
+ const text = await response.text().catch(() => '')
58
+ const trimmed = text.trim()
59
+ if (trimmed === '') return `${response.status} ${response.statusText}`
60
+ try {
61
+ const parsed: unknown = JSON.parse(trimmed)
62
+ if (parsed !== null && typeof parsed === 'object') {
63
+ const record = parsed as Record<string, unknown>
64
+ const error = record['error']
65
+ if (error !== null && typeof error === 'object') {
66
+ const message = (error as Record<string, unknown>)['message']
67
+ if (typeof message === 'string') return `${response.status} ${message}`
68
+ }
69
+ if (typeof record['message'] === 'string') return `${response.status} ${record['message']}`
70
+ }
71
+ } catch {
72
+ // 非 JSON 响应,退回截断文本。
73
+ }
74
+ return `${response.status} ${trimmed.slice(0, 200)}`
75
+ }
76
+
77
+ const DEFAULT_FETCH_TIMEOUT_MS = 15_000
78
+
79
+ /** 为未自带超时的辅助请求统一附加超时,并与外部取消信号合并。 */
80
+ function withFetchTimeout(signal?: AbortSignal, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS): AbortSignal {
81
+ const timeout = AbortSignal.timeout(timeoutMs)
82
+ return signal === undefined ? timeout : AbortSignal.any([signal, timeout])
83
+ }
84
+
85
+ /**
86
+ * 拉取模型目录。
87
+ *
88
+ * 目录是模型元数据的权威来源。失败时抛出错误由调用方决定回退策略。
89
+ *
90
+ * 注意:本端点接受 GitHub OAuth refresh token;实测 Copilot access token
91
+ * 过期时用 access 会得到 401,而 refresh 仍然 200。
92
+ */
93
+ export async function fetchCatalog(target: RequestTarget): Promise<CatalogEntry[]> {
94
+ const response = await fetch(`${target.baseUrl}/models`, {
95
+ method: 'GET',
96
+ headers: headers(target, { Accept: 'application/json', 'X-GitHub-Api-Version': AUTO_API_VERSION }),
97
+ signal: withFetchTimeout(target.signal),
98
+ })
99
+ if (!response.ok) throw new Error(`Copilot 模型目录获取失败: ${await describeFailure(response)}`)
100
+ const body = (await response.json()) as CatalogResponse
101
+ return Array.isArray(body.data) ? body.data : []
102
+ }
103
+
104
+ /** 把服务端下发的过期秒数转换为毫秒,并预留提前量。 */
105
+ function toExpiry(raw: unknown, payload: AutoSessionTokenPayload | undefined): number {
106
+ const seconds = typeof raw === 'number' && Number.isFinite(raw) && raw > 0
107
+ ? raw
108
+ : typeof payload?.exp === 'number' ? payload.exp : undefined
109
+ if (seconds === undefined) {
110
+ // 两项都缺失时保守地按 1 小时处理,避免过早重新协商。
111
+ return Date.now() + 60 * 60 * 1000 - SERVER_EXPIRY_SKEW_MS
112
+ }
113
+ return seconds * 1000 - SERVER_EXPIRY_SKEW_MS
114
+ }
115
+
116
+ /** 把 `/models/session` 响应转换为 AutoSession,并校验关键字段。 */
117
+ function toSessionFromSessionEndpoint(body: AutoSessionResponse): AutoSession {
118
+ if (typeof body.session_token !== 'string' || body.session_token === '') {
119
+ throw new Error('Auto 会话响应缺少 session_token')
120
+ }
121
+ if (typeof body.selected_model !== 'string' || body.selected_model === '') {
122
+ throw new Error('Auto 会话响应缺少 selected_model')
123
+ }
124
+ const payload = decodeSessionToken(body.session_token) as AutoSessionTokenPayload | undefined
125
+
126
+ return {
127
+ token: body.session_token,
128
+ selectedModel: body.selected_model,
129
+ availableModels: Array.isArray(body.available_models) ? body.available_models : [body.selected_model],
130
+ expiresAt: toExpiry(body.expires_at, payload),
131
+ discountedCosts: body.discounted_costs ?? payload?.discounted_costs ?? {},
132
+ channel: 'models-session',
133
+ ...(typeof payload?.auto_session_id === 'string' ? { sessionId: payload.auto_session_id } : {}),
134
+ }
135
+ }
136
+
137
+ /**
138
+ * 把 `/auto` 响应转换为 AutoSession。
139
+ *
140
+ * 该通道的 `selected_model` 是完整对象,因此额外保留 `selectedModelSpec`,
141
+ * 让调用方无需再查目录就能知道上下文窗口、能力与端到端端点类型。
142
+ */
143
+ function toSessionFromAutoEndpoint(body: AutoRouteResponse): AutoSession {
144
+ if (typeof body.session_token !== 'string' || body.session_token === '') {
145
+ throw new Error('/auto 响应缺少 session_token')
146
+ }
147
+ const selected = body.selected_model
148
+ if (selected === null || typeof selected !== 'object' || typeof selected.id !== 'string') {
149
+ throw new Error('/auto 响应缺少 selected_model.id')
150
+ }
151
+ const payload = decodeSessionToken(body.session_token) as AutoSessionTokenPayload | undefined
152
+
153
+ // 载荷里的 selected_model 是权威字符串;对象里的 id 在实测中与之一致。
154
+ const selectedId = typeof payload?.selected_model === 'string' && payload.selected_model !== ''
155
+ ? payload.selected_model
156
+ : selected.id
157
+
158
+ return {
159
+ token: body.session_token,
160
+ selectedModel: selectedId,
161
+ // /auto 不返回授权清单,空数组表示「不做额外限制」。
162
+ availableModels: [],
163
+ expiresAt: toExpiry(body.expires_at, payload),
164
+ discountedCosts: body.discounted_costs ?? payload?.discounted_costs ?? {},
165
+ selectedModelSpec: selected,
166
+ channel: 'auto',
167
+ ...(typeof payload?.auto_session_id === 'string' ? { sessionId: payload.auto_session_id } : {}),
168
+ }
169
+ }
170
+
171
+ /** `/auto` 请求体:只含提示词与图片标记。 */
172
+ function autoBody(prompt: string, needsVision: boolean): Record<string, unknown> {
173
+ const body: Record<string, unknown> = { prompt: prompt.trim() }
174
+ // 实测该字段为 snake_case;客户端据此让服务端避开不支持图片的模型。
175
+ if (needsVision) body['has_image'] = true
176
+ return body
177
+ }
178
+
179
+ /** 带超时地发起一次可能失败的路由请求,失败返回 undefined 而不抛出。 */
180
+ async function tryRoute(
181
+ target: RequestTarget,
182
+ path: string,
183
+ body: Record<string, unknown>,
184
+ apiVersion: string,
185
+ timeoutMs: number,
186
+ ): Promise<unknown | undefined> {
187
+ const timeout = AbortSignal.timeout(timeoutMs)
188
+ const signal = target.signal === undefined ? timeout : AbortSignal.any([target.signal, timeout])
189
+
190
+ try {
191
+ const response = await fetch(`${target.baseUrl}${path}`, {
192
+ method: 'POST',
193
+ headers: headers(target, {
194
+ 'Content-Type': 'application/json',
195
+ 'X-GitHub-Api-Version': apiVersion,
196
+ 'Openai-Intent': 'conversation-edits',
197
+ }),
198
+ body: JSON.stringify(body),
199
+ signal,
200
+ })
201
+ if (!response.ok) {
202
+ await describeFailure(response)
203
+ return undefined
204
+ }
205
+ return (await response.json()) as unknown
206
+ } catch {
207
+ // 超时、网络错误或解析失败都走降级,不让对话本身失败。
208
+ return undefined
209
+ }
210
+ }
211
+
212
+ /** 校验 `/auto` 返回体是否具备必需字段。 */
213
+ function isAutoRouteResponse(value: unknown): value is AutoRouteResponse {
214
+ if (value === null || typeof value !== 'object') return false
215
+ const record = value as Record<string, unknown>
216
+ if (typeof record['session_token'] !== 'string' || record['session_token'] === '') return false
217
+ const selected = record['selected_model']
218
+ return selected !== null && typeof selected === 'object' && typeof (selected as CatalogEntry).id === 'string'
219
+ }
220
+
221
+ /** 校验 `/models/session` 返回体是否具备必需字段。 */
222
+ function isAutoSessionResponse(value: unknown): value is AutoSessionResponse {
223
+ if (value === null || typeof value !== 'object') return false
224
+ const record = value as Record<string, unknown>
225
+ return typeof record['session_token'] === 'string'
226
+ && record['session_token'] !== ''
227
+ && typeof record['selected_model'] === 'string'
228
+ }
229
+
230
+ /** 一次协商的全部可选输入。 */
231
+ export interface NegotiateInput {
232
+ /** 请求的路由提示词。 */
233
+ prompt: string
234
+ /** 本次请求是否含图片。 */
235
+ needsVision: boolean
236
+ timeoutMs?: number
237
+ /**
238
+ * 目录条目,用于协商失败时挑选降级模型。
239
+ *
240
+ * 降级顺序与 OpenCode 一致:先 `is_chat_fallback`,再任一带
241
+ * `billing.auto_discount` 的条目。
242
+ */
243
+ catalog?: readonly CatalogEntry[]
244
+ }
245
+
246
+ /**
247
+ * 请求 `/auto` 路由,失败返回 undefined。
248
+ *
249
+ * 该通道下发选中模型的完整对象,且实测能选中 `/models/session` 授权清单
250
+ * 之外的模型。但它**无法指定模型**:请求体里的 `model`、`model_id`、
251
+ * `selected_model` 均被忽略(已实测)。
252
+ */
253
+ async function negotiateAuto(
254
+ target: RequestTarget,
255
+ input: NegotiateInput,
256
+ ): Promise<AutoSession | undefined> {
257
+ const timeoutMs = input.timeoutMs ?? SESSION_TIMEOUT_MS
258
+ const routed = await tryRoute(
259
+ target,
260
+ '/auto',
261
+ autoBody(input.prompt, input.needsVision),
262
+ AUTO_API_VERSION,
263
+ timeoutMs,
264
+ )
265
+ if (!isAutoRouteResponse(routed)) return undefined
266
+ try {
267
+ return toSessionFromAutoEndpoint(routed)
268
+ } catch {
269
+ return undefined
270
+ }
271
+ }
272
+
273
+ /**
274
+ * 请求 `/models/session` 路由,失败返回 undefined。
275
+ *
276
+ * 该通道的令牌**明确公布覆盖范围** `available_models`,因此适合支撑
277
+ * 用户手动选择的具体模型。
278
+ */
279
+ async function negotiateLegacy(
280
+ target: RequestTarget,
281
+ input: NegotiateInput,
282
+ ): Promise<AutoSession | undefined> {
283
+ const timeoutMs = input.timeoutMs ?? SESSION_TIMEOUT_MS
284
+ const legacy = await tryRoute(
285
+ target,
286
+ '/models/session',
287
+ {
288
+ auto_mode: { enabled: true },
289
+ ...(input.prompt.trim() === '' ? {} : { prompt: input.prompt.trim() }),
290
+ },
291
+ API_VERSION,
292
+ timeoutMs,
293
+ )
294
+ if (!isAutoSessionResponse(legacy)) return undefined
295
+ try {
296
+ return toSessionFromSessionEndpoint(legacy)
297
+ } catch {
298
+ return undefined
299
+ }
300
+ }
301
+
302
+ /** 协商结果:会话本身,或被选中模型与请求不一致时的说明。 */
303
+ export interface NegotiateResult {
304
+ session: AutoSession
305
+ /** 实际应发给 `/responses` 的模型 id。 */
306
+ effectiveModel: string
307
+ /** 用户请求的模型无法取得覆盖令牌时为 true。 */
308
+ unsupported: boolean
309
+ }
310
+
311
+ /**
312
+ * 为用户请求的模型协商一个**能覆盖该模型**的会话。
313
+ *
314
+ * 两个通道的令牌作用域不同(已实测,2026-11-11):
315
+ *
316
+ * | 通道 | 令牌覆盖范围 |
317
+ * | --- | --- |
318
+ * | `/auto` | 只覆盖本次选中的那个模型 |
319
+ * | `/models/session` | 覆盖响应里的 `available_models` |
320
+ *
321
+ * 实测证据:带 A 次 `/auto` 的令牌去请求 `mai-code-1.1-flash` 得到
322
+ * `Requested model not available for session`;而 `/models/session` 的令牌
323
+ * 对 `available_models` 里的每个模型都返回 200。
324
+ *
325
+ * 因此:
326
+ * - 请求 `auto` → 用 `/auto`,由服务端决定模型;
327
+ * - 请求具体模型 → 优先用 `/models/session`(有明确覆盖清单),
328
+ * 未被覆盖时再试 `/auto`(仅在它恰好选中该模型时可用)。
329
+ */
330
+ export async function negotiateForModel(
331
+ target: RequestTarget,
332
+ requestedModel: string,
333
+ input: NegotiateInput,
334
+ ): Promise<NegotiateResult> {
335
+ if (requestedModel === AUTO_MODEL_ID) {
336
+ const routed = await negotiateAuto(target, input)
337
+ if (routed !== undefined) {
338
+ return { session: routed, effectiveModel: routed.selectedModel, unsupported: false }
339
+ }
340
+ // `/auto` 不可用时退回旧通道,并用它选中的模型。
341
+ const legacy = await negotiateLegacy(target, input)
342
+ if (legacy !== undefined) {
343
+ return { session: legacy, effectiveModel: legacy.selectedModel, unsupported: false }
344
+ }
345
+ return { session: degradedSession(input.catalog ?? []), effectiveModel: '', unsupported: false }
346
+ }
347
+
348
+ const legacy = await negotiateLegacy(target, input)
349
+ if (legacy !== undefined && legacy.availableModels.includes(requestedModel)) {
350
+ return { session: legacy, effectiveModel: requestedModel, unsupported: false }
351
+ }
352
+
353
+ const routed = await negotiateAuto(target, input)
354
+ if (routed !== undefined && routed.selectedModel === requestedModel) {
355
+ return { session: routed, effectiveModel: requestedModel, unsupported: false }
356
+ }
357
+
358
+ // 两个通道都无法覆盖该模型:保留一个会话用于状态展示,但标记不支持。
359
+ const fallback = routed ?? legacy
360
+ if (fallback !== undefined) {
361
+ return { session: fallback, effectiveModel: requestedModel, unsupported: true }
362
+ }
363
+ return { session: degradedSession(input.catalog ?? []), effectiveModel: requestedModel, unsupported: true }
364
+ }
365
+
366
+ /**
367
+ * 只查一次 `/models/session` 公布的授权模型清单。
368
+ *
369
+ * 与 `negotiateLegacy` 的区别:这是为**构建模型列表**服务的轻量查询,
370
+ * 不构造会话、不参与缓存,因此可以安全地在启动时调用。
371
+ *
372
+ * 注意:该端点用 **Copilot access 令牌**,不认 GitHub refresh 令牌。
373
+ * 失败时返回空数组(表示不过滤)。
374
+ */
375
+ export async function fetchAuthorizedModels(
376
+ target: RequestTarget,
377
+ timeoutMs = SESSION_TIMEOUT_MS,
378
+ ): Promise<string[]> {
379
+ const body = await tryRoute(
380
+ target,
381
+ '/models/session',
382
+ { auto_mode: { enabled: true } },
383
+ API_VERSION,
384
+ timeoutMs,
385
+ )
386
+ if (!isAutoSessionResponse(body)) return []
387
+ return Array.isArray(body.available_models) ? body.available_models : []
388
+ }
389
+
390
+ /**
391
+ * 兼容入口:不带模型偏好地协商一次。
392
+ *
393
+ * 供会话预取等场景使用,等价于请求 `auto`。
394
+ */
395
+ export async function negotiateSession(
396
+ target: RequestTarget,
397
+ input: NegotiateInput,
398
+ ): Promise<AutoSession> {
399
+ const result = await negotiateForModel(target, AUTO_MODEL_ID, input)
400
+ return result.session
401
+ }
402
+
403
+ /**
404
+ * 构造降级会话。
405
+ *
406
+ * 与 OpenCode 一致:选 `is_chat_fallback` 优先,其次任一 `auto_discount` 条目,
407
+ * 不带 session token(因此只能走普通通道),有效期 5 分钟。
408
+ *
409
+ * 无可用候选时抛错——此时确实没有任何模型可以安全回退。
410
+ */
411
+ export function degradedSession(catalog: readonly CatalogEntry[]): AutoSession {
412
+ const fallback = catalog.find((entry) => entry.is_chat_fallback === true)
413
+ ?? catalog.find((entry) => entry.billing?.auto_discount !== undefined)
414
+
415
+ if (fallback === undefined) {
416
+ throw new Error('Auto 路由协商失败,且模型目录中没有可用的降级模型')
417
+ }
418
+ return {
419
+ token: '',
420
+ selectedModel: fallback.id,
421
+ availableModels: [],
422
+ expiresAt: Date.now() + 300_000,
423
+ discountedCosts: {},
424
+ selectedModelSpec: fallback,
425
+ channel: 'auto',
426
+ degraded: true,
427
+ }
428
+ }
429
+
430
+ /** 会话是否仍然可用。临近过期即视为失效。 */
431
+ export function sessionUsable(session: AutoSession, now = Date.now()): boolean {
432
+ return session.expiresAt > now
433
+ }
434
+
435
+ /**
436
+ * 查询账号信息与额度,同时解析 `endpoints.api`。
437
+ *
438
+ * 关键:这个端点在 `api.github.com`,用的是 **GitHub OAuth 令牌**
439
+ * (auth.json 里的 `github-copilot.refresh`),不是 Copilot 访问令牌。
440
+ * 用错令牌会得到 401。
441
+ */
442
+ export async function fetchAccount(githubToken: string, signal?: AbortSignal): Promise<CopilotAccount> {
443
+ const response = await fetch('https://api.github.com/copilot_internal/user', {
444
+ method: 'GET',
445
+ headers: {
446
+ Authorization: `Bearer ${githubToken}`,
447
+ Accept: 'application/json',
448
+ ...CLIENT_HEADERS,
449
+ },
450
+ signal: withFetchTimeout(signal),
451
+ })
452
+ if (!response.ok) throw new Error(`Copilot 账号信息获取失败: ${await describeFailure(response)}`)
453
+ return (await response.json()) as CopilotAccount
454
+ }
455
+
456
+ /**
457
+ * 由账号端点解析 API 根地址。
458
+ *
459
+ * 这是 OpenCode 的做法:`/copilot_internal/user` 的 `endpoints.api` 才是
460
+ * 权威 baseURL,企业版与区域部署会返回不同主机。失败时返回 undefined,
461
+ * 由调用方回退到默认地址或令牌里的 proxy-ep。
462
+ */
463
+ export async function resolveApiBase(
464
+ githubToken: string,
465
+ signal?: AbortSignal,
466
+ ): Promise<string | undefined> {
467
+ try {
468
+ const response = await fetch('https://api.github.com/copilot_internal/user', {
469
+ method: 'GET',
470
+ headers: {
471
+ Authorization: `Bearer ${githubToken}`,
472
+ Accept: 'application/json',
473
+ ...CLIENT_HEADERS,
474
+ },
475
+ signal: withFetchTimeout(signal),
476
+ })
477
+ if (!response.ok) return undefined
478
+ const body = (await response.json()) as CopilotUserResponse
479
+ const api = body.endpoints?.api
480
+ if (typeof api !== 'string' || api === '') return undefined
481
+ return api.replace(/\/+$/, '')
482
+ } catch {
483
+ return undefined
484
+ }
485
+ }
486
+
487
+ /**
488
+ * 用 GitHub OAuth 令牌换取 Copilot 访问令牌。
489
+ *
490
+ * 内置 provider 会在请求前自动刷新,但本扩展按需触发一次刷新可以避免
491
+ * 启动阶段因 access 过期而拿不到目录。失败返回 undefined,由调用方
492
+ * 继续使用现有 access(让内置刷新链路处理)。
493
+ */
494
+ export async function refreshAccessToken(
495
+ githubToken: string,
496
+ signal?: AbortSignal,
497
+ ): Promise<{ token: string; expiresAt: number } | undefined> {
498
+ try {
499
+ const response = await fetch('https://api.github.com/copilot_internal/v2/token', {
500
+ method: 'GET',
501
+ headers: {
502
+ Authorization: `Bearer ${githubToken}`,
503
+ Accept: 'application/json',
504
+ ...CLIENT_HEADERS,
505
+ },
506
+ signal: withFetchTimeout(signal),
507
+ })
508
+ if (!response.ok) return undefined
509
+ const body = (await response.json()) as { token?: unknown; expires_at?: unknown }
510
+ if (typeof body.token !== 'string' || body.token === '') return undefined
511
+ const expiresAt = typeof body.expires_at === 'number' ? body.expires_at * 1000 : 0
512
+ return { token: body.token, expiresAt }
513
+ } catch {
514
+ return undefined
515
+ }
516
+ }
package/lib/debug.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * 诊断开关。
3
+ *
4
+ * 通过 `COPILOT_AUTO_DEBUG=1` 开启,输出到 stderr。只输出路由决策与请求体
5
+ * 的**结构**(字段名、角色序列),不输出令牌、session token 或消息正文,
6
+ * 避免把凭据或隐私内容写进日志。
7
+ */
8
+
9
+ const enabled = (): boolean => process.env['COPILOT_AUTO_DEBUG'] === '1'
10
+
11
+ /** 输出一行诊断信息。 */
12
+ export function trace(message: string): void {
13
+ if (!enabled()) return
14
+ console.error(`[copilot-auto] ${message}`)
15
+ }
16
+
17
+ /**
18
+ * 构造 `onPayload` 回调,打印请求体结构。
19
+ *
20
+ * 始终返回 undefined,表示不修改 payload。
21
+ */
22
+ export function payloadInspector(): ((payload: unknown) => undefined) | undefined {
23
+ if (!enabled()) return undefined
24
+ return (payload: unknown): undefined => {
25
+ if (payload === null || typeof payload !== 'object') return undefined
26
+ const record = payload as Record<string, unknown>
27
+ trace(`payload keys: ${JSON.stringify(Object.keys(record))}`)
28
+ for (const key of ['model', 'stream', 'store', 'max_output_tokens']) {
29
+ if (key in record) trace(` ${key} = ${JSON.stringify(record[key])}`)
30
+ }
31
+ const input = record['input']
32
+ if (Array.isArray(input)) {
33
+ const roles = input.map((item) =>
34
+ item !== null && typeof item === 'object' ? (item as Record<string, unknown>)['role'] : undefined)
35
+ trace(` input roles: ${JSON.stringify(roles)}`)
36
+ }
37
+ return undefined
38
+ }
39
+ }